idx
int64
project
string
commit_id
string
project_url
string
commit_url
string
commit_message
string
target
int64
func
string
func_hash
float64
file_name
string
file_hash
float64
cwe
sequence
cve
string
cve_desc
string
nvd_url
string
122
savannah
0545ec1ca36b27cb928128870a83e5f668980bc5
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=0545ec1ca36b27cb928128870a83e5f668980bc5
None
1
cff_charset_load( CFF_Charset charset, FT_UInt num_glyphs, FT_Stream stream, FT_ULong base_offset, FT_ULong offset, FT_Bool invert ) { FT_Memory memory = stream->memory; FT_Error error = CFF_Err_Ok; FT_UShort glyph_sid; /* If the the offset is greater than 2, we have to parse the */ /* charset table. */ if ( offset > 2 ) { FT_UInt j; charset->offset = base_offset + offset; /* Get the format of the table. */ if ( FT_STREAM_SEEK( charset->offset ) || FT_READ_BYTE( charset->format ) ) goto Exit; /* Allocate memory for sids. */ if ( FT_NEW_ARRAY( charset->sids, num_glyphs ) ) goto Exit; /* assign the .notdef glyph */ charset->sids[0] = 0; switch ( charset->format ) { case 0: if ( num_glyphs > 0 ) { if ( FT_FRAME_ENTER( ( num_glyphs - 1 ) * 2 ) ) goto Exit; for ( j = 1; j < num_glyphs; j++ ) charset->sids[j] = FT_GET_USHORT(); FT_FRAME_EXIT(); } /* Read the first glyph sid of the range. */ if ( FT_READ_USHORT( glyph_sid ) ) goto Exit; /* Read the number of glyphs in the range. */ if ( charset->format == 2 ) { if ( FT_READ_USHORT( nleft ) ) goto Exit; } else { if ( FT_READ_BYTE( nleft ) ) goto Exit; } /* Fill in the range of sids -- `nleft + 1' glyphs. */ for ( i = 0; j < num_glyphs && i <= nleft; i++, j++, glyph_sid++ ) charset->sids[j] = glyph_sid; } } break; default: FT_ERROR(( "cff_charset_load: invalid table format!\n" )); error = CFF_Err_Invalid_File_Format; goto Exit; }
322,437,368,215,015,760,000,000,000,000,000,000,000
None
null
[ "CWE-189" ]
CVE-2009-0946
Multiple integer overflows in FreeType 2.3.9 and earlier allow remote attackers to execute arbitrary code via vectors related to large values in certain inputs in (1) smooth/ftsmooth.c, (2) sfnt/ttcmap.c, and (3) cff/cffload.c.
https://nvd.nist.gov/vuln/detail/CVE-2009-0946
157,984
savannah
0545ec1ca36b27cb928128870a83e5f668980bc5
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=0545ec1ca36b27cb928128870a83e5f668980bc5
None
0
cff_charset_load( CFF_Charset charset, FT_UInt num_glyphs, FT_Stream stream, FT_ULong base_offset, FT_ULong offset, FT_Bool invert ) { FT_Memory memory = stream->memory; FT_Error error = CFF_Err_Ok; FT_UShort glyph_sid; /* If the the offset is greater than 2, we have to parse the */ /* charset table. */ if ( offset > 2 ) { FT_UInt j; charset->offset = base_offset + offset; /* Get the format of the table. */ if ( FT_STREAM_SEEK( charset->offset ) || FT_READ_BYTE( charset->format ) ) goto Exit; /* Allocate memory for sids. */ if ( FT_NEW_ARRAY( charset->sids, num_glyphs ) ) goto Exit; /* assign the .notdef glyph */ charset->sids[0] = 0; switch ( charset->format ) { case 0: if ( num_glyphs > 0 ) { if ( FT_FRAME_ENTER( ( num_glyphs - 1 ) * 2 ) ) goto Exit; for ( j = 1; j < num_glyphs; j++ ) { FT_UShort sid = FT_GET_USHORT(); /* this constant is given in the CFF specification */ if ( sid < 65000 ) charset->sids[j] = sid; else { FT_ERROR(( "cff_charset_load:" " invalid SID value %d set to zero\n", sid )); charset->sids[j] = 0; } } FT_FRAME_EXIT(); } /* Read the first glyph sid of the range. */ if ( FT_READ_USHORT( glyph_sid ) ) goto Exit; /* Read the number of glyphs in the range. */ if ( charset->format == 2 ) { if ( FT_READ_USHORT( nleft ) ) goto Exit; } else { if ( FT_READ_BYTE( nleft ) ) goto Exit; } /* Fill in the range of sids -- `nleft + 1' glyphs. */ for ( i = 0; j < num_glyphs && i <= nleft; i++, j++, glyph_sid++ ) charset->sids[j] = glyph_sid; } } break; default: FT_ERROR(( "cff_charset_load: invalid table format!\n" )); error = CFF_Err_Invalid_File_Format; goto Exit; }
274,463,663,087,246,400,000,000,000,000,000,000,000
None
null
[ "CWE-189" ]
CVE-2009-0946
Multiple integer overflows in FreeType 2.3.9 and earlier allow remote attackers to execute arbitrary code via vectors related to large values in certain inputs in (1) smooth/ftsmooth.c, (2) sfnt/ttcmap.c, and (3) cff/cffload.c.
https://nvd.nist.gov/vuln/detail/CVE-2009-0946
123
netfilter
2ae1099a42e6a0f06de305ca13a842ac83d4683e
https://git.netfilter.org/conntrack-tools
https://git.netfilter.org/iptables/commit/iptables/xshared.c?id=2ae1099a42e6a0f06de305ca13a842ac83d4683e
None
1
void add_param_to_argv(char *parsestart, int line) { int quote_open = 0, escaped = 0, param_len = 0; char param_buffer[1024], *curchar; /* After fighting with strtok enough, here's now * a 'real' parser. According to Rusty I'm now no } else { param_buffer[param_len++] = *curchar; for (curchar = parsestart; *curchar; curchar++) { if (quote_open) { if (escaped) { param_buffer[param_len++] = *curchar; escaped = 0; continue; } else if (*curchar == '\\') { } switch (*curchar) { quote_open = 0; *curchar = '"'; } else { param_buffer[param_len++] = *curchar; continue; } } else { continue; } break; default: /* regular character, copy to buffer */ param_buffer[param_len++] = *curchar; if (param_len >= sizeof(param_buffer)) xtables_error(PARAMETER_PROBLEM, case ' ': case '\t': case '\n': if (!param_len) { /* two spaces? */ continue; } break; default: /* regular character, copy to buffer */ param_buffer[param_len++] = *curchar; if (param_len >= sizeof(param_buffer)) xtables_error(PARAMETER_PROBLEM, "Parameter too long!"); continue; } param_buffer[param_len] = '\0'; /* check if table name specified */ if ((param_buffer[0] == '-' && param_buffer[1] != '-' && strchr(param_buffer, 't')) || (!strncmp(param_buffer, "--t", 3) && !strncmp(param_buffer, "--table", strlen(param_buffer)))) { xtables_error(PARAMETER_PROBLEM, "The -t option (seen in line %u) cannot be used in %s.\n", line, xt_params->program_name); } add_argv(param_buffer, 0); param_len = 0; }
204,920,135,878,748,700,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2019-11360
A buffer overflow in iptables-restore in netfilter iptables 1.8.2 allows an attacker to (at least) crash the program or potentially gain code execution via a specially crafted iptables-save file. This is related to add_param_to_argv in xshared.c.
https://nvd.nist.gov/vuln/detail/CVE-2019-11360
157,985
netfilter
2ae1099a42e6a0f06de305ca13a842ac83d4683e
https://git.netfilter.org/conntrack-tools
https://git.netfilter.org/iptables/commit/iptables/xshared.c?id=2ae1099a42e6a0f06de305ca13a842ac83d4683e
None
0
void add_param_to_argv(char *parsestart, int line) { int quote_open = 0, escaped = 0; struct xt_param_buf param = {}; char *curchar; /* After fighting with strtok enough, here's now * a 'real' parser. According to Rusty I'm now no } else { param_buffer[param_len++] = *curchar; for (curchar = parsestart; *curchar; curchar++) { if (quote_open) { if (escaped) { add_param(&param, curchar); escaped = 0; continue; } else if (*curchar == '\\') { } switch (*curchar) { quote_open = 0; *curchar = '"'; } else { add_param(&param, curchar); continue; } } else { continue; } break; default: /* regular character, copy to buffer */ param_buffer[param_len++] = *curchar; if (param_len >= sizeof(param_buffer)) xtables_error(PARAMETER_PROBLEM, case ' ': case '\t': case '\n': if (!param.len) { /* two spaces? */ continue; } break; default: /* regular character, copy to buffer */ add_param(&param, curchar); continue; } param.buffer[param.len] = '\0'; /* check if table name specified */ if ((param.buffer[0] == '-' && param.buffer[1] != '-' && strchr(param.buffer, 't')) || (!strncmp(param.buffer, "--t", 3) && !strncmp(param.buffer, "--table", strlen(param.buffer)))) { xtables_error(PARAMETER_PROBLEM, "The -t option (seen in line %u) cannot be used in %s.\n", line, xt_params->program_name); } add_argv(param.buffer, 0); param.len = 0; }
82,639,535,107,168,520,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2019-11360
A buffer overflow in iptables-restore in netfilter iptables 1.8.2 allows an attacker to (at least) crash the program or potentially gain code execution via a specially crafted iptables-save file. This is related to add_param_to_argv in xshared.c.
https://nvd.nist.gov/vuln/detail/CVE-2019-11360
124
accountsservice
f9abd359f71a5bce421b9ae23432f539a067847a
https://cgit.freedesktop.org/accountsservice/commit/?id=f9abd359f71a5bce421b9ae23432f539a067847a
https://cgit.freedesktop.org/accountsservice/commit/?id=f9abd359f71a5bce421b9ae23432f539a067847a
None
1
user_change_icon_file_authorized_cb (Daemon *daemon, User *user, GDBusMethodInvocation *context, gpointer data) { g_autofree gchar *filename = NULL; g_autoptr(GFile) file = NULL; g_autoptr(GFileInfo) info = NULL; guint32 mode; GFileType type; guint64 size; filename = g_strdup (data); if (filename == NULL || *filename == '\0') { g_autofree gchar *dest_path = NULL; g_autoptr(GFile) dest = NULL; g_autoptr(GError) error = NULL; g_clear_pointer (&filename, g_free); dest_path = g_build_filename (ICONDIR, accounts_user_get_user_name (ACCOUNTS_USER (user)), NULL); dest = g_file_new_for_path (dest_path); if (!g_file_delete (dest, NULL, &error) && !g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) { throw_error (context, ERROR_FAILED, "failed to remove user icon, %s", error->message); return; } goto icon_saved; } file = g_file_new_for_path (filename); info = g_file_query_info (file, G_FILE_ATTRIBUTE_UNIX_MODE "," G_FILE_ATTRIBUTE_STANDARD_TYPE "," G_FILE_ATTRIBUTE_STANDARD_SIZE, return; }
310,825,199,754,671,940,000,000,000,000,000,000,000
None
null
[ "CWE-22" ]
CVE-2018-14036
Directory Traversal with ../ sequences occurs in AccountsService before 0.6.50 because of an insufficient path check in user_change_icon_file_authorized_cb() in user.c.
https://nvd.nist.gov/vuln/detail/CVE-2018-14036
157,986
accountsservice
f9abd359f71a5bce421b9ae23432f539a067847a
https://cgit.freedesktop.org/accountsservice/commit/?id=f9abd359f71a5bce421b9ae23432f539a067847a
https://cgit.freedesktop.org/accountsservice/commit/?id=f9abd359f71a5bce421b9ae23432f539a067847a
None
0
user_change_icon_file_authorized_cb (Daemon *daemon, User *user, GDBusMethodInvocation *context, gpointer data) { g_autofree gchar *filename = NULL; g_autoptr(GFile) file = NULL; g_autoptr(GFileInfo) info = NULL; guint32 mode; GFileType type; guint64 size; filename = g_strdup (data); if (filename == NULL || *filename == '\0') { g_autofree gchar *dest_path = NULL; g_autoptr(GFile) dest = NULL; g_autoptr(GError) error = NULL; g_clear_pointer (&filename, g_free); dest_path = g_build_filename (ICONDIR, accounts_user_get_user_name (ACCOUNTS_USER (user)), NULL); dest = g_file_new_for_path (dest_path); if (!g_file_delete (dest, NULL, &error) && !g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) { throw_error (context, ERROR_FAILED, "failed to remove user icon, %s", error->message); return; } goto icon_saved; } file = g_file_new_for_path (filename); g_clear_pointer (&filename, g_free); /* Canonicalize path so we can call g_str_has_prefix on it * below without concern for ../ path components moving outside * the prefix */ filename = g_file_get_path (file); info = g_file_query_info (file, G_FILE_ATTRIBUTE_UNIX_MODE "," G_FILE_ATTRIBUTE_STANDARD_TYPE "," G_FILE_ATTRIBUTE_STANDARD_SIZE, return; }
172,529,280,077,131,830,000,000,000,000,000,000,000
None
null
[ "CWE-22" ]
CVE-2018-14036
Directory Traversal with ../ sequences occurs in AccountsService before 0.6.50 because of an insufficient path check in user_change_icon_file_authorized_cb() in user.c.
https://nvd.nist.gov/vuln/detail/CVE-2018-14036
128
xserver
215f894965df5fb0bb45b107d84524e700d2073c
http://gitweb.freedesktop.org/?p=xorg/xserver
https://cgit.freedesktop.org/xorg/xserver/commit/?id=215f894965df5fb0bb45b107d84524e700d2073c
dix: Disallow GenericEvent in SendEvent request. The SendEvent request holds xEvent which is exactly 32 bytes long, no more, no less. Both ProcSendEvent and SProcSendEvent verify that the received data exactly match the request size. However nothing stops the client from passing in event with xEvent::type = GenericEvent and any value of xGenericEvent::length. In the case of ProcSendEvent, the event will be eventually passed to WriteEventsToClient which will see that it is Generic event and copy the arbitrary length from the receive buffer (and possibly past it) and send it to the other client. This allows clients to copy unitialized heap memory out of X server or to crash it. In case of SProcSendEvent, it will attempt to swap the incoming event by calling a swapping function from the EventSwapVector array. The swapped event is written to target buffer, which in this case is local xEvent variable. The xEvent variable is 32 bytes long, but the swapping functions for GenericEvents expect that the target buffer has size matching the size of the source GenericEvent. This allows clients to cause stack buffer overflows. Signed-off-by: Michal Srb <[email protected]> Reviewed-by: Peter Hutterer <[email protected]> Signed-off-by: Peter Hutterer <[email protected]>
1
ProcSendEvent(ClientPtr client) { WindowPtr pWin; WindowPtr effectiveFocus = NullWindow; /* only set if dest==InputFocus */ DeviceIntPtr dev = PickPointer(client); DeviceIntPtr keybd = GetMaster(dev, MASTER_KEYBOARD); SpritePtr pSprite = dev->spriteInfo->sprite; REQUEST(xSendEventReq); REQUEST_SIZE_MATCH(xSendEventReq); /* libXext and other extension libraries may set the bit indicating * that this event came from a SendEvent request so remove it * since otherwise the event type may fail the range checks * and cause an invalid BadValue error to be returned. * * This is safe to do since we later add the SendEvent bit (0x80) * back in once we send the event to the client */ stuff->event.u.u.type &= ~(SEND_EVENT_BIT); /* The client's event type must be a core event type or one defined by an extension. */ if (!((stuff->event.u.u.type > X_Reply && stuff->event.u.u.type < LASTEvent) || (stuff->event.u.u.type >= EXTENSION_EVENT_BASE && stuff->event.u.u.type < (unsigned) lastEvent))) { client->errorValue = stuff->event.u.u.type; return BadValue; } if (stuff->event.u.u.type == ClientMessage && stuff->event.u.u.detail != 8 && stuff->event.u.u.detail != 16 && stuff->event.u.u.detail != 32) { } if (stuff->destination == PointerWindow) pWin = pSprite->win; else if (stuff->destination == InputFocus) { WindowPtr inputFocus = (keybd) ? keybd->focus->win : NoneWin; if (inputFocus == NoneWin) return Success; /* If the input focus is PointerRootWin, send the event to where the pointer is if possible, then perhaps propogate up to root. */ if (inputFocus == PointerRootWin) inputFocus = GetCurrentRootWindow(dev); if (IsParent(inputFocus, pSprite->win)) { effectiveFocus = inputFocus; pWin = pSprite->win; } else effectiveFocus = pWin = inputFocus; } else dixLookupWindow(&pWin, stuff->destination, client, DixSendAccess); if (!pWin) return BadWindow; if ((stuff->propagate != xFalse) && (stuff->propagate != xTrue)) { client->errorValue = stuff->propagate; return BadValue; } stuff->event.u.u.type |= SEND_EVENT_BIT; if (stuff->propagate) { for (; pWin; pWin = pWin->parent) { if (XaceHook(XACE_SEND_ACCESS, client, NULL, pWin, &stuff->event, 1)) return Success; if (DeliverEventsToWindow(dev, pWin, &stuff->event, 1, stuff->eventMask, NullGrab)) return Success; if (pWin == effectiveFocus) return Success; stuff->eventMask &= ~wDontPropagateMask(pWin); if (!stuff->eventMask) break; } } else if (!XaceHook(XACE_SEND_ACCESS, client, NULL, pWin, &stuff->event, 1)) DeliverEventsToWindow(dev, pWin, &stuff->event, 1, stuff->eventMask, NullGrab); return Success; }
36,683,317,052,216,500,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2017-10971
In the X.Org X server before 2017-06-19, a user authenticated to an X Session could crash or execute code in the context of the X Server by exploiting a stack overflow in the endianness conversion of X Events.
https://nvd.nist.gov/vuln/detail/CVE-2017-10971
157,990
xserver
215f894965df5fb0bb45b107d84524e700d2073c
http://gitweb.freedesktop.org/?p=xorg/xserver
https://cgit.freedesktop.org/xorg/xserver/commit/?id=215f894965df5fb0bb45b107d84524e700d2073c
dix: Disallow GenericEvent in SendEvent request. The SendEvent request holds xEvent which is exactly 32 bytes long, no more, no less. Both ProcSendEvent and SProcSendEvent verify that the received data exactly match the request size. However nothing stops the client from passing in event with xEvent::type = GenericEvent and any value of xGenericEvent::length. In the case of ProcSendEvent, the event will be eventually passed to WriteEventsToClient which will see that it is Generic event and copy the arbitrary length from the receive buffer (and possibly past it) and send it to the other client. This allows clients to copy unitialized heap memory out of X server or to crash it. In case of SProcSendEvent, it will attempt to swap the incoming event by calling a swapping function from the EventSwapVector array. The swapped event is written to target buffer, which in this case is local xEvent variable. The xEvent variable is 32 bytes long, but the swapping functions for GenericEvents expect that the target buffer has size matching the size of the source GenericEvent. This allows clients to cause stack buffer overflows. Signed-off-by: Michal Srb <[email protected]> Reviewed-by: Peter Hutterer <[email protected]> Signed-off-by: Peter Hutterer <[email protected]>
0
ProcSendEvent(ClientPtr client) { WindowPtr pWin; WindowPtr effectiveFocus = NullWindow; /* only set if dest==InputFocus */ DeviceIntPtr dev = PickPointer(client); DeviceIntPtr keybd = GetMaster(dev, MASTER_KEYBOARD); SpritePtr pSprite = dev->spriteInfo->sprite; REQUEST(xSendEventReq); REQUEST_SIZE_MATCH(xSendEventReq); /* libXext and other extension libraries may set the bit indicating * that this event came from a SendEvent request so remove it * since otherwise the event type may fail the range checks * and cause an invalid BadValue error to be returned. * * This is safe to do since we later add the SendEvent bit (0x80) * back in once we send the event to the client */ stuff->event.u.u.type &= ~(SEND_EVENT_BIT); /* The client's event type must be a core event type or one defined by an extension. */ if (!((stuff->event.u.u.type > X_Reply && stuff->event.u.u.type < LASTEvent) || (stuff->event.u.u.type >= EXTENSION_EVENT_BASE && stuff->event.u.u.type < (unsigned) lastEvent))) { client->errorValue = stuff->event.u.u.type; return BadValue; } /* Generic events can have variable size, but SendEvent request holds exactly 32B of event data. */ if (stuff->event.u.u.type == GenericEvent) { client->errorValue = stuff->event.u.u.type; return BadValue; } if (stuff->event.u.u.type == ClientMessage && stuff->event.u.u.detail != 8 && stuff->event.u.u.detail != 16 && stuff->event.u.u.detail != 32) { } if (stuff->destination == PointerWindow) pWin = pSprite->win; else if (stuff->destination == InputFocus) { WindowPtr inputFocus = (keybd) ? keybd->focus->win : NoneWin; if (inputFocus == NoneWin) return Success; /* If the input focus is PointerRootWin, send the event to where the pointer is if possible, then perhaps propogate up to root. */ if (inputFocus == PointerRootWin) inputFocus = GetCurrentRootWindow(dev); if (IsParent(inputFocus, pSprite->win)) { effectiveFocus = inputFocus; pWin = pSprite->win; } else effectiveFocus = pWin = inputFocus; } else dixLookupWindow(&pWin, stuff->destination, client, DixSendAccess); if (!pWin) return BadWindow; if ((stuff->propagate != xFalse) && (stuff->propagate != xTrue)) { client->errorValue = stuff->propagate; return BadValue; } stuff->event.u.u.type |= SEND_EVENT_BIT; if (stuff->propagate) { for (; pWin; pWin = pWin->parent) { if (XaceHook(XACE_SEND_ACCESS, client, NULL, pWin, &stuff->event, 1)) return Success; if (DeliverEventsToWindow(dev, pWin, &stuff->event, 1, stuff->eventMask, NullGrab)) return Success; if (pWin == effectiveFocus) return Success; stuff->eventMask &= ~wDontPropagateMask(pWin); if (!stuff->eventMask) break; } } else if (!XaceHook(XACE_SEND_ACCESS, client, NULL, pWin, &stuff->event, 1)) DeliverEventsToWindow(dev, pWin, &stuff->event, 1, stuff->eventMask, NullGrab); return Success; }
107,904,058,737,663,540,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2017-10971
In the X.Org X server before 2017-06-19, a user authenticated to an X Session could crash or execute code in the context of the X Server by exploiting a stack overflow in the endianness conversion of X Events.
https://nvd.nist.gov/vuln/detail/CVE-2017-10971
129
xserver
8caed4df36b1f802b4992edcfd282cbeeec35d9d
http://gitweb.freedesktop.org/?p=xorg/xserver
https://cgit.freedesktop.org/xorg/xserver/commit/?id=8caed4df36b1f802b4992edcfd282cbeeec35d9d
Xi: Verify all events in ProcXSendExtensionEvent. The requirement is that events have type in range EXTENSION_EVENT_BASE..lastEvent, but it was tested only for first event of all. Signed-off-by: Michal Srb <[email protected]> Reviewed-by: Peter Hutterer <[email protected]> Signed-off-by: Peter Hutterer <[email protected]>
1
ProcXSendExtensionEvent(ClientPtr client) { int ret; DeviceIntPtr dev; xEvent *first; XEventClass *list; struct tmask tmp[EMASKSIZE]; REQUEST(xSendExtensionEventReq); REQUEST_AT_LEAST_SIZE(xSendExtensionEventReq); if (stuff->length != bytes_to_int32(sizeof(xSendExtensionEventReq)) + stuff->count + (stuff->num_events * bytes_to_int32(sizeof(xEvent)))) return BadLength; ret = dixLookupDevice(&dev, stuff->deviceid, client, DixWriteAccess); if (ret != Success) return ret; if (stuff->num_events == 0) return ret; /* The client's event type must be one defined by an extension. */ first = ((xEvent *) &stuff[1]); if (!((EXTENSION_EVENT_BASE <= first->u.u.type) && (first->u.u.type < lastEvent))) { client->errorValue = first->u.u.type; return BadValue; } list = (XEventClass *) (first + stuff->num_events); return ret; ret = (SendEvent(client, dev, stuff->destination, stuff->propagate, (xEvent *) &stuff[1], tmp[stuff->deviceid].mask, stuff->num_events)); return ret; }
288,772,859,654,498,580,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2017-10971
In the X.Org X server before 2017-06-19, a user authenticated to an X Session could crash or execute code in the context of the X Server by exploiting a stack overflow in the endianness conversion of X Events.
https://nvd.nist.gov/vuln/detail/CVE-2017-10971
157,991
xserver
8caed4df36b1f802b4992edcfd282cbeeec35d9d
http://gitweb.freedesktop.org/?p=xorg/xserver
https://cgit.freedesktop.org/xorg/xserver/commit/?id=8caed4df36b1f802b4992edcfd282cbeeec35d9d
Xi: Verify all events in ProcXSendExtensionEvent. The requirement is that events have type in range EXTENSION_EVENT_BASE..lastEvent, but it was tested only for first event of all. Signed-off-by: Michal Srb <[email protected]> Reviewed-by: Peter Hutterer <[email protected]> Signed-off-by: Peter Hutterer <[email protected]>
0
ProcXSendExtensionEvent(ClientPtr client) { int ret, i; DeviceIntPtr dev; xEvent *first; XEventClass *list; struct tmask tmp[EMASKSIZE]; REQUEST(xSendExtensionEventReq); REQUEST_AT_LEAST_SIZE(xSendExtensionEventReq); if (stuff->length != bytes_to_int32(sizeof(xSendExtensionEventReq)) + stuff->count + (stuff->num_events * bytes_to_int32(sizeof(xEvent)))) return BadLength; ret = dixLookupDevice(&dev, stuff->deviceid, client, DixWriteAccess); if (ret != Success) return ret; if (stuff->num_events == 0) return ret; /* The client's event type must be one defined by an extension. */ first = ((xEvent *) &stuff[1]); for (i = 0; i < stuff->num_events; i++) { if (!((EXTENSION_EVENT_BASE <= first[i].u.u.type) && (first[i].u.u.type < lastEvent))) { client->errorValue = first[i].u.u.type; return BadValue; } } list = (XEventClass *) (first + stuff->num_events); return ret; ret = (SendEvent(client, dev, stuff->destination, stuff->propagate, (xEvent *) &stuff[1], tmp[stuff->deviceid].mask, stuff->num_events)); return ret; }
7,864,871,216,394,927,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2017-10971
In the X.Org X server before 2017-06-19, a user authenticated to an X Session could crash or execute code in the context of the X Server by exploiting a stack overflow in the endianness conversion of X Events.
https://nvd.nist.gov/vuln/detail/CVE-2017-10971
130
openssl
9a0db453ba017ebcaccbee933ee6511a9ae4d1c8
https://github.com/openssl/openssl
http://git.openssl.org/?p=openssl.git;a=commitdiff;h=9a0db453ba017ebcaccbee933ee6511a9ae4d1c8
Fix alternate chains certificate forgery issue During certificate verfification, OpenSSL will attempt to find an alternative certificate chain if the first attempt to build such a chain fails. An error in the implementation of this logic can mean that an attacker could cause certain checks on untrusted certificates to be bypassed, such as the CA flag, enabling them to use a valid leaf certificate to act as a CA and "issue" an invalid certificate. This occurs where at least one cert is added to the first chain from the trust store, but that chain still ends up being untrusted. In that case ctx->last_untrusted is decremented in error. Patch provided by the BoringSSL project. CVE-2015-1793 Reviewed-by: Stephen Henson <[email protected]>
1
int X509_verify_cert(X509_STORE_CTX *ctx) { X509 *x, *xtmp, *xtmp2, *chain_ss = NULL; int bad_chain = 0; X509_VERIFY_PARAM *param = ctx->param; int depth, i, ok = 0; int num, j, retry; int (*cb) (int xok, X509_STORE_CTX *xctx); STACK_OF(X509) *sktmp = NULL; if (ctx->cert == NULL) { X509err(X509_F_X509_VERIFY_CERT, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY); return -1; } cb = ctx->verify_cb; /* * first we make sure the chain we are going to build is present and that * the first entry is in place */ if (ctx->chain == NULL) { if (((ctx->chain = sk_X509_new_null()) == NULL) || (!sk_X509_push(ctx->chain, ctx->cert))) { X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE); goto end; } CRYPTO_add(&ctx->cert->references, 1, CRYPTO_LOCK_X509); ctx->last_untrusted = 1; } /* We use a temporary STACK so we can chop and hack at it */ if (ctx->untrusted != NULL && (sktmp = sk_X509_dup(ctx->untrusted)) == NULL) { X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE); goto end; } num = sk_X509_num(ctx->chain); x = sk_X509_value(ctx->chain, num - 1); depth = param->depth; for (;;) { /* If we have enough, we break */ if (depth < num) break; /* FIXME: If this happens, we should take * note of it and, if appropriate, use the * X509_V_ERR_CERT_CHAIN_TOO_LONG error code * later. */ /* If we are self signed, we break */ if (ctx->check_issued(ctx, x, x)) break; /* If we were passed a cert chain, use it first */ if (ctx->untrusted != NULL) { xtmp = find_issuer(ctx, sktmp, x); if (xtmp != NULL) { if (!sk_X509_push(ctx->chain, xtmp)) { X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE); goto end; } CRYPTO_add(&xtmp->references, 1, CRYPTO_LOCK_X509); (void)sk_X509_delete_ptr(sktmp, xtmp); ctx->last_untrusted++; x = xtmp; num++; /* * reparse the full chain for the next one */ continue; } } break; } /* Remember how many untrusted certs we have */ j = num; /* * at this point, chain should contain a list of untrusted certificates. * We now need to add at least one trusted one, if possible, otherwise we * complain. */ do { /* * Examine last certificate in chain and see if it is self signed. */ i = sk_X509_num(ctx->chain); x = sk_X509_value(ctx->chain, i - 1); if (ctx->check_issued(ctx, x, x)) { /* we have a self signed certificate */ if (sk_X509_num(ctx->chain) == 1) { /* * We have a single self signed certificate: see if we can * find it in the store. We must have an exact match to avoid * possible impersonation. */ ok = ctx->get_issuer(&xtmp, ctx, x); if ((ok <= 0) || X509_cmp(x, xtmp)) { ctx->error = X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT; ctx->current_cert = x; ctx->error_depth = i - 1; if (ok == 1) X509_free(xtmp); bad_chain = 1; ok = cb(0, ctx); if (!ok) goto end; } else { /* * We have a match: replace certificate with store * version so we get any trust settings. */ X509_free(x); x = xtmp; (void)sk_X509_set(ctx->chain, i - 1, x); ctx->last_untrusted = 0; } } else { /* * extract and save self signed certificate for later use */ chain_ss = sk_X509_pop(ctx->chain); ctx->last_untrusted--; num--; j--; x = sk_X509_value(ctx->chain, num - 1); } } /* We now lookup certs from the certificate store */ for (;;) { /* If we have enough, we break */ if (depth < num) break; /* If we are self signed, we break */ if (ctx->check_issued(ctx, x, x)) break; ok = ctx->get_issuer(&xtmp, ctx, x); if (ok < 0) return ok; if (ok == 0) break; x = xtmp; if (!sk_X509_push(ctx->chain, x)) { X509_free(xtmp); X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE); return 0; } num++; } /* * If we haven't got a least one certificate from our store then check * if there is an alternative chain that could be used. We only do this * if the user hasn't switched off alternate chain checking */ retry = 0; if (j == ctx->last_untrusted && !(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS)) { while (j-- > 1) { xtmp2 = sk_X509_value(ctx->chain, j - 1); ok = ctx->get_issuer(&xtmp, ctx, xtmp2); if (ok < 0) goto end; /* Check if we found an alternate chain */ if (ok > 0) { /* * Free up the found cert we'll add it again later */ X509_free(xtmp); /* * Dump all the certs above this point - we've found an * alternate chain */ while (num > j) { xtmp = sk_X509_pop(ctx->chain); X509_free(xtmp); num--; ctx->last_untrusted--; } retry = 1; break; } } } } while (retry); /* Is last certificate looked up self signed? */ if (!ctx->check_issued(ctx, x, x)) { if ((chain_ss == NULL) || !ctx->check_issued(ctx, x, chain_ss)) { if (ctx->last_untrusted >= num) ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY; else ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT; ctx->current_cert = x; } else { sk_X509_push(ctx->chain, chain_ss); num++; ctx->last_untrusted = num; ctx->current_cert = chain_ss; ctx->error = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN; chain_ss = NULL; } ctx->error_depth = num - 1; bad_chain = 1; ok = cb(0, ctx); if (!ok) goto end; } /* We have the chain complete: now we need to check its purpose */ ok = check_chain_extensions(ctx); if (!ok) goto end; /* Check name constraints */ ok = check_name_constraints(ctx); if (!ok) goto end; /* The chain extensions are OK: check trust */ if (param->trust > 0) ok = check_trust(ctx); if (!ok) goto end; /* We may as well copy down any DSA parameters that are required */ X509_get_pubkey_parameters(NULL, ctx->chain); /* * Check revocation status: we do this after copying parameters because * they may be needed for CRL signature verification. */ ok = ctx->check_revocation(ctx); if (!ok) goto end; /* At this point, we have a chain and need to verify it */ if (ctx->verify != NULL) ok = ctx->verify(ctx); else ok = internal_verify(ctx); if (!ok) goto end; #ifndef OPENSSL_NO_RFC3779 /* RFC 3779 path validation, now that CRL check has been done */ ok = v3_asid_validate_path(ctx); if (!ok) goto end; ok = v3_addr_validate_path(ctx); if (!ok) goto end; #endif /* If we get this far evaluate policies */ if (!bad_chain && (ctx->param->flags & X509_V_FLAG_POLICY_CHECK)) ok = ctx->check_policy(ctx); if (!ok) goto end; if (0) { end: X509_get_pubkey_parameters(NULL, ctx->chain); } if (sktmp != NULL) sk_X509_free(sktmp); if (chain_ss != NULL) X509_free(chain_ss); return ok; }
115,002,758,247,549,560,000,000,000,000,000,000,000
None
null
[ "CWE-254" ]
CVE-2015-1793
The X509_verify_cert function in crypto/x509/x509_vfy.c in OpenSSL 1.0.1n, 1.0.1o, 1.0.2b, and 1.0.2c does not properly process X.509 Basic Constraints cA values during identification of alternative certificate chains, which allows remote attackers to spoof a Certification Authority role and trigger unintended certificate verifications via a valid leaf certificate.
https://nvd.nist.gov/vuln/detail/CVE-2015-1793
157,992
openssl
9a0db453ba017ebcaccbee933ee6511a9ae4d1c8
https://github.com/openssl/openssl
http://git.openssl.org/?p=openssl.git;a=commitdiff;h=9a0db453ba017ebcaccbee933ee6511a9ae4d1c8
Fix alternate chains certificate forgery issue During certificate verfification, OpenSSL will attempt to find an alternative certificate chain if the first attempt to build such a chain fails. An error in the implementation of this logic can mean that an attacker could cause certain checks on untrusted certificates to be bypassed, such as the CA flag, enabling them to use a valid leaf certificate to act as a CA and "issue" an invalid certificate. This occurs where at least one cert is added to the first chain from the trust store, but that chain still ends up being untrusted. In that case ctx->last_untrusted is decremented in error. Patch provided by the BoringSSL project. CVE-2015-1793 Reviewed-by: Stephen Henson <[email protected]>
0
int X509_verify_cert(X509_STORE_CTX *ctx) { X509 *x, *xtmp, *xtmp2, *chain_ss = NULL; int bad_chain = 0; X509_VERIFY_PARAM *param = ctx->param; int depth, i, ok = 0; int num, j, retry; int (*cb) (int xok, X509_STORE_CTX *xctx); STACK_OF(X509) *sktmp = NULL; if (ctx->cert == NULL) { X509err(X509_F_X509_VERIFY_CERT, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY); return -1; } cb = ctx->verify_cb; /* * first we make sure the chain we are going to build is present and that * the first entry is in place */ if (ctx->chain == NULL) { if (((ctx->chain = sk_X509_new_null()) == NULL) || (!sk_X509_push(ctx->chain, ctx->cert))) { X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE); goto end; } CRYPTO_add(&ctx->cert->references, 1, CRYPTO_LOCK_X509); ctx->last_untrusted = 1; } /* We use a temporary STACK so we can chop and hack at it */ if (ctx->untrusted != NULL && (sktmp = sk_X509_dup(ctx->untrusted)) == NULL) { X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE); goto end; } num = sk_X509_num(ctx->chain); x = sk_X509_value(ctx->chain, num - 1); depth = param->depth; for (;;) { /* If we have enough, we break */ if (depth < num) break; /* FIXME: If this happens, we should take * note of it and, if appropriate, use the * X509_V_ERR_CERT_CHAIN_TOO_LONG error code * later. */ /* If we are self signed, we break */ if (ctx->check_issued(ctx, x, x)) break; /* If we were passed a cert chain, use it first */ if (ctx->untrusted != NULL) { xtmp = find_issuer(ctx, sktmp, x); if (xtmp != NULL) { if (!sk_X509_push(ctx->chain, xtmp)) { X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE); goto end; } CRYPTO_add(&xtmp->references, 1, CRYPTO_LOCK_X509); (void)sk_X509_delete_ptr(sktmp, xtmp); ctx->last_untrusted++; x = xtmp; num++; /* * reparse the full chain for the next one */ continue; } } break; } /* Remember how many untrusted certs we have */ j = num; /* * at this point, chain should contain a list of untrusted certificates. * We now need to add at least one trusted one, if possible, otherwise we * complain. */ do { /* * Examine last certificate in chain and see if it is self signed. */ i = sk_X509_num(ctx->chain); x = sk_X509_value(ctx->chain, i - 1); if (ctx->check_issued(ctx, x, x)) { /* we have a self signed certificate */ if (sk_X509_num(ctx->chain) == 1) { /* * We have a single self signed certificate: see if we can * find it in the store. We must have an exact match to avoid * possible impersonation. */ ok = ctx->get_issuer(&xtmp, ctx, x); if ((ok <= 0) || X509_cmp(x, xtmp)) { ctx->error = X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT; ctx->current_cert = x; ctx->error_depth = i - 1; if (ok == 1) X509_free(xtmp); bad_chain = 1; ok = cb(0, ctx); if (!ok) goto end; } else { /* * We have a match: replace certificate with store * version so we get any trust settings. */ X509_free(x); x = xtmp; (void)sk_X509_set(ctx->chain, i - 1, x); ctx->last_untrusted = 0; } } else { /* * extract and save self signed certificate for later use */ chain_ss = sk_X509_pop(ctx->chain); ctx->last_untrusted--; num--; j--; x = sk_X509_value(ctx->chain, num - 1); } } /* We now lookup certs from the certificate store */ for (;;) { /* If we have enough, we break */ if (depth < num) break; /* If we are self signed, we break */ if (ctx->check_issued(ctx, x, x)) break; ok = ctx->get_issuer(&xtmp, ctx, x); if (ok < 0) return ok; if (ok == 0) break; x = xtmp; if (!sk_X509_push(ctx->chain, x)) { X509_free(xtmp); X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE); return 0; } num++; } /* * If we haven't got a least one certificate from our store then check * if there is an alternative chain that could be used. We only do this * if the user hasn't switched off alternate chain checking */ retry = 0; if (j == ctx->last_untrusted && !(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS)) { while (j-- > 1) { xtmp2 = sk_X509_value(ctx->chain, j - 1); ok = ctx->get_issuer(&xtmp, ctx, xtmp2); if (ok < 0) goto end; /* Check if we found an alternate chain */ if (ok > 0) { /* * Free up the found cert we'll add it again later */ X509_free(xtmp); /* * Dump all the certs above this point - we've found an * alternate chain */ while (num > j) { xtmp = sk_X509_pop(ctx->chain); X509_free(xtmp); num--; } ctx->last_untrusted = sk_X509_num(ctx->chain); retry = 1; break; } } } } while (retry); /* Is last certificate looked up self signed? */ if (!ctx->check_issued(ctx, x, x)) { if ((chain_ss == NULL) || !ctx->check_issued(ctx, x, chain_ss)) { if (ctx->last_untrusted >= num) ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY; else ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT; ctx->current_cert = x; } else { sk_X509_push(ctx->chain, chain_ss); num++; ctx->last_untrusted = num; ctx->current_cert = chain_ss; ctx->error = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN; chain_ss = NULL; } ctx->error_depth = num - 1; bad_chain = 1; ok = cb(0, ctx); if (!ok) goto end; } /* We have the chain complete: now we need to check its purpose */ ok = check_chain_extensions(ctx); if (!ok) goto end; /* Check name constraints */ ok = check_name_constraints(ctx); if (!ok) goto end; /* The chain extensions are OK: check trust */ if (param->trust > 0) ok = check_trust(ctx); if (!ok) goto end; /* We may as well copy down any DSA parameters that are required */ X509_get_pubkey_parameters(NULL, ctx->chain); /* * Check revocation status: we do this after copying parameters because * they may be needed for CRL signature verification. */ ok = ctx->check_revocation(ctx); if (!ok) goto end; /* At this point, we have a chain and need to verify it */ if (ctx->verify != NULL) ok = ctx->verify(ctx); else ok = internal_verify(ctx); if (!ok) goto end; #ifndef OPENSSL_NO_RFC3779 /* RFC 3779 path validation, now that CRL check has been done */ ok = v3_asid_validate_path(ctx); if (!ok) goto end; ok = v3_addr_validate_path(ctx); if (!ok) goto end; #endif /* If we get this far evaluate policies */ if (!bad_chain && (ctx->param->flags & X509_V_FLAG_POLICY_CHECK)) ok = ctx->check_policy(ctx); if (!ok) goto end; if (0) { end: X509_get_pubkey_parameters(NULL, ctx->chain); } if (sktmp != NULL) sk_X509_free(sktmp); if (chain_ss != NULL) X509_free(chain_ss); return ok; }
142,295,385,280,397,700,000,000,000,000,000,000,000
None
null
[ "CWE-254" ]
CVE-2015-1793
The X509_verify_cert function in crypto/x509/x509_vfy.c in OpenSSL 1.0.1n, 1.0.1o, 1.0.2b, and 1.0.2c does not properly process X.509 Basic Constraints cA values during identification of alternative certificate chains, which allows remote attackers to spoof a Certification Authority role and trigger unintended certificate verifications via a valid leaf certificate.
https://nvd.nist.gov/vuln/detail/CVE-2015-1793
132
savannah
cb07844454d8cc9fb21f53ace75975f91185a120
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/tar.git/commit/?id=cb07844454d8cc9fb21f53ace75975f91185a120
None
1
pax_decode_header (struct tar_sparse_file *file) { if (file->stat_info->sparse_major > 0) { uintmax_t u; char nbuf[UINTMAX_STRSIZE_BOUND]; union block *blk; char *p; size_t i; off_t start; #define COPY_BUF(b,buf,src) do \ { \ char *endp = b->buffer + BLOCKSIZE; \ char *dst = buf; \ do \ { \ if (dst == buf + UINTMAX_STRSIZE_BOUND -1) \ { \ ERROR ((0, 0, _("%s: numeric overflow in sparse archive member"), \ file->stat_info->orig_file_name)); \ return false; \ } \ if (src == endp) \ { \ set_next_block_after (b); \ b = find_next_block (); \ src = b->buffer; \ endp = b->buffer + BLOCKSIZE; \ } \ while (*dst++ != '\n'); \ dst[-1] = 0; \ } while (0) start = current_block_ordinal (); set_next_block_after (current_header); start = current_block_ordinal (); set_next_block_after (current_header); blk = find_next_block (); p = blk->buffer; COPY_BUF (blk,nbuf,p); if (!decode_num (&u, nbuf, TYPE_MAXIMUM (size_t))) } file->stat_info->sparse_map_size = u; file->stat_info->sparse_map = xcalloc (file->stat_info->sparse_map_size, sizeof (*file->stat_info->sparse_map)); file->stat_info->sparse_map_avail = 0; for (i = 0; i < file->stat_info->sparse_map_size; i++) { struct sp_array sp; COPY_BUF (blk,nbuf,p); if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t))) { ERROR ((0, 0, _("%s: malformed sparse archive member"), file->stat_info->orig_file_name)); return false; } sp.offset = u; COPY_BUF (blk,nbuf,p); if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t))) { ERROR ((0, 0, _("%s: malformed sparse archive member"), file->stat_info->orig_file_name)); return false; } sp.numbytes = u; sparse_add_map (file->stat_info, &sp); } set_next_block_after (blk); file->dumped_size += BLOCKSIZE * (current_block_ordinal () - start); } return true; }
138,433,573,634,940,220,000,000,000,000,000,000,000
None
null
[ "CWE-476" ]
CVE-2019-9923
pax_decode_header in sparse.c in GNU Tar before 1.32 had a NULL pointer dereference when parsing certain archives that have malformed extended headers.
https://nvd.nist.gov/vuln/detail/CVE-2019-9923
157,994
savannah
cb07844454d8cc9fb21f53ace75975f91185a120
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/tar.git/commit/?id=cb07844454d8cc9fb21f53ace75975f91185a120
None
0
pax_decode_header (struct tar_sparse_file *file) { if (file->stat_info->sparse_major > 0) { uintmax_t u; char nbuf[UINTMAX_STRSIZE_BOUND]; union block *blk; char *p; size_t i; off_t start; #define COPY_BUF(b,buf,src) do \ { \ char *endp = b->buffer + BLOCKSIZE; \ char *dst = buf; \ do \ { \ if (dst == buf + UINTMAX_STRSIZE_BOUND -1) \ { \ ERROR ((0, 0, _("%s: numeric overflow in sparse archive member"), \ file->stat_info->orig_file_name)); \ return false; \ } \ if (src == endp) \ { \ set_next_block_after (b); \ b = find_next_block (); \ if (!b) \ FATAL_ERROR ((0, 0, _("Unexpected EOF in archive"))); \ src = b->buffer; \ endp = b->buffer + BLOCKSIZE; \ } \ while (*dst++ != '\n'); \ dst[-1] = 0; \ } while (0) start = current_block_ordinal (); set_next_block_after (current_header); start = current_block_ordinal (); set_next_block_after (current_header); blk = find_next_block (); if (!blk) FATAL_ERROR ((0, 0, _("Unexpected EOF in archive"))); p = blk->buffer; COPY_BUF (blk,nbuf,p); if (!decode_num (&u, nbuf, TYPE_MAXIMUM (size_t))) } file->stat_info->sparse_map_size = u; file->stat_info->sparse_map = xcalloc (file->stat_info->sparse_map_size, sizeof (*file->stat_info->sparse_map)); file->stat_info->sparse_map_avail = 0; for (i = 0; i < file->stat_info->sparse_map_size; i++) { struct sp_array sp; COPY_BUF (blk,nbuf,p); if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t))) { ERROR ((0, 0, _("%s: malformed sparse archive member"), file->stat_info->orig_file_name)); return false; } sp.offset = u; COPY_BUF (blk,nbuf,p); if (!decode_num (&u, nbuf, TYPE_MAXIMUM (off_t))) { ERROR ((0, 0, _("%s: malformed sparse archive member"), file->stat_info->orig_file_name)); return false; } sp.numbytes = u; sparse_add_map (file->stat_info, &sp); } set_next_block_after (blk); file->dumped_size += BLOCKSIZE * (current_block_ordinal () - start); } return true; }
143,151,925,619,516,230,000,000,000,000,000,000,000
None
null
[ "CWE-476" ]
CVE-2019-9923
pax_decode_header in sparse.c in GNU Tar before 1.32 had a NULL pointer dereference when parsing certain archives that have malformed extended headers.
https://nvd.nist.gov/vuln/detail/CVE-2019-9923
133
ghostscript
961b10cdd71403072fb99401a45f3bef6ce53626
http://git.ghostscript.com/?p=mupdf
http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=961b10cdd71403072fb99401a45f3bef6ce53626
None
1
xps_encode_font_char_imp(xps_font_t *font, int code) { byte *table; /* no cmap selected: return identity */ if (font->cmapsubtable <= 0) return code; table = font->data + font->cmapsubtable; switch (u16(table)) { case 0: /* Apple standard 1-to-1 mapping. */ return table[code + 6]; case 4: /* Microsoft/Adobe segmented mapping. */ { int segCount2 = u16(table + 6); byte *endCount = table + 14; byte *startCount = endCount + segCount2 + 2; byte *idDelta = startCount + segCount2; byte *idRangeOffset = idDelta + segCount2; int i2; for (i2 = 0; i2 < segCount2 - 3; i2 += 2) { int delta, roff; int start = u16(startCount + i2); continue; delta = s16(idDelta + i2); roff = s16(idRangeOffset + i2); if ( roff == 0 ) { return ( code + delta ) & 0xffff; /* mod 65536 */ return 0; } if ( roff == 0 ) { return ( code + delta ) & 0xffff; /* mod 65536 */ return 0; } glyph = u16(idRangeOffset + i2 + roff + ((code - start) << 1)); return (glyph == 0 ? 0 : glyph + delta); } case 6: /* Single interval lookup. */ { int firstCode = u16(table + 6); int entryCount = u16(table + 8); if ( code < firstCode || code >= firstCode + entryCount ) return 0; return u16(table + 10 + ((code - firstCode) << 1)); } case 10: /* Trimmed array (like 6) */ { int startCharCode = u32(table + 12); int numChars = u32(table + 16); if ( code < startCharCode || code >= startCharCode + numChars ) return 0; return u32(table + 20 + (code - startCharCode) * 4); } case 12: /* Segmented coverage. (like 4) */ { int nGroups = u32(table + 12); byte *group = table + 16; int i; for (i = 0; i < nGroups; i++) { int startCharCode = u32(group + 0); int endCharCode = u32(group + 4); int startGlyphID = u32(group + 8); if ( code < startCharCode ) return 0; if ( code <= endCharCode ) return startGlyphID + (code - startCharCode); group += 12; } return 0; } case 2: /* High-byte mapping through table. */ case 8: /* Mixed 16-bit and 32-bit coverage (like 2) */ default: gs_warn1("unknown cmap format: %d\n", u16(table)); return 0; } return 0; } /* * Given a GID, reverse the CMAP subtable lookup to turn it back into a character code * We need a Unicode return value, so we might need to do some fixed tables for * certain kinds of CMAP subtables (ie non-Unicode ones). That would be a future enhancement * if we ever encounter such a beast. */ static int xps_decode_font_char_imp(xps_font_t *font, int code) { byte *table; /* no cmap selected: return identity */ if (font->cmapsubtable <= 0) return code; table = font->data + font->cmapsubtable; switch (u16(table)) { case 0: /* Apple standard 1-to-1 mapping. */ { int i, length = u16(&table[2]) - 6; if (length < 0 || length > 256) return gs_error_invalidfont; for (i=0;i<length;i++) { if (table[6 + i] == code) return i; } } return 0; case 4: /* Microsoft/Adobe segmented mapping. */ { int segCount2 = u16(table + 6); byte *endCount = table + 14; byte *startCount = endCount + segCount2 + 2; byte *idDelta = startCount + segCount2; byte *idRangeOffset = idDelta + segCount2; int i2; if (segCount2 < 3 || segCount2 > 65535) return gs_error_invalidfont; byte *startCount = endCount + segCount2 + 2; byte *idDelta = startCount + segCount2; byte *idRangeOffset = idDelta + segCount2; int i2; if (segCount2 < 3 || segCount2 > 65535) return gs_error_invalidfont; for (i2 = 0; i2 < segCount2 - 3; i2 += 2) if (roff == 0) { glyph = (i + delta) & 0xffff; } else { glyph = u16(idRangeOffset + i2 + roff + ((i - start) << 1)); } if (glyph == code) { return i; } } } if (roff == 0) { glyph = (i + delta) & 0xffff; } else { glyph = u16(idRangeOffset + i2 + roff + ((i - start) << 1)); } if (glyph == code) { return i; ch = u16(&table[10 + (i * 2)]); if (ch == code) return (firstCode + i); } } return 0; case 10: /* Trimmed array (like 6) */ { unsigned int ch, i, length = u32(&table[20]); int firstCode = u32(&table[16]); for (i=0;i<length;i++) { ch = u16(&table[10 + (i * 2)]); if (ch == code) return (firstCode + i); } } return 0; case 12: /* Segmented coverage. (like 4) */ { unsigned int nGroups = u32(&table[12]); int Group; for (Group=0;Group<nGroups;Group++) { int startCharCode = u32(&table[16 + (Group * 12)]); int endCharCode = u32(&table[16 + (Group * 12) + 4]); int startGlyphCode = u32(&table[16 + (Group * 12) + 8]); if (code >= startGlyphCode && code <= (startGlyphCode + (endCharCode - startCharCode))) { return startGlyphCode + (code - startCharCode); } } } return 0; case 2: /* High-byte mapping through table. */ case 8: /* Mixed 16-bit and 32-bit coverage (like 2) */ default: gs_warn1("unknown cmap format: %d\n", u16(table)); return 0; }
76,117,521,649,677,880,000,000,000,000,000,000,000
None
null
[ "CWE-125" ]
CVE-2017-9740
The xps_decode_font_char_imp function in xps/xpsfont.c in Artifex Ghostscript GhostXPS 9.21 allows remote attackers to cause a denial of service (heap-based buffer over-read and application crash) or possibly have unspecified other impact via a crafted document.
https://nvd.nist.gov/vuln/detail/CVE-2017-9740
157,995
ghostscript
961b10cdd71403072fb99401a45f3bef6ce53626
http://git.ghostscript.com/?p=mupdf
http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=961b10cdd71403072fb99401a45f3bef6ce53626
None
0
xps_encode_font_char_imp(xps_font_t *font, int code) { byte *table; /* no cmap selected: return identity */ if (font->cmapsubtable <= 0) return code; table = font->data + font->cmapsubtable; switch (u16(table)) { case 0: /* Apple standard 1-to-1 mapping. */ return table[code + 6]; case 4: /* Microsoft/Adobe segmented mapping. */ { int segCount2 = u16(table + 6); byte *endCount = table + 14; byte *startCount = endCount + segCount2 + 2; byte *idDelta = startCount + segCount2; byte *idRangeOffset = idDelta + segCount2; byte *giddata; int i2; if (segCount2 < 3 || segCount2 > 65535 || idRangeOffset > font->data + font->length) return gs_error_invalidfont; for (i2 = 0; i2 < segCount2 - 3; i2 += 2) { int delta, roff; int start = u16(startCount + i2); continue; delta = s16(idDelta + i2); roff = s16(idRangeOffset + i2); if ( roff == 0 ) { return ( code + delta ) & 0xffff; /* mod 65536 */ return 0; } if ( roff == 0 ) { return ( code + delta ) & 0xffff; /* mod 65536 */ } if ((giddata = (idRangeOffset + i2 + roff + ((code - start) << 1))) > font->data + font->length) { return code; } glyph = u16(giddata); return (glyph == 0 ? 0 : glyph + delta); } case 6: /* Single interval lookup. */ { int firstCode = u16(table + 6); int entryCount = u16(table + 8); if ( code < firstCode || code >= firstCode + entryCount ) return 0; return u16(table + 10 + ((code - firstCode) << 1)); } case 10: /* Trimmed array (like 6) */ { int startCharCode = u32(table + 12); int numChars = u32(table + 16); if ( code < startCharCode || code >= startCharCode + numChars ) return 0; return u32(table + 20 + (code - startCharCode) * 4); } case 12: /* Segmented coverage. (like 4) */ { int nGroups = u32(table + 12); byte *group = table + 16; int i; for (i = 0; i < nGroups; i++) { int startCharCode = u32(group + 0); int endCharCode = u32(group + 4); int startGlyphID = u32(group + 8); if ( code < startCharCode ) return 0; if ( code <= endCharCode ) return startGlyphID + (code - startCharCode); group += 12; } return 0; } case 2: /* High-byte mapping through table. */ case 8: /* Mixed 16-bit and 32-bit coverage (like 2) */ default: gs_warn1("unknown cmap format: %d\n", u16(table)); return 0; } return 0; } /* * Given a GID, reverse the CMAP subtable lookup to turn it back into a character code * We need a Unicode return value, so we might need to do some fixed tables for * certain kinds of CMAP subtables (ie non-Unicode ones). That would be a future enhancement * if we ever encounter such a beast. */ static int xps_decode_font_char_imp(xps_font_t *font, int code) { byte *table; /* no cmap selected: return identity */ if (font->cmapsubtable <= 0) return code; table = font->data + font->cmapsubtable; switch (u16(table)) { case 0: /* Apple standard 1-to-1 mapping. */ { int i, length = u16(&table[2]) - 6; if (length < 0 || length > 256) return gs_error_invalidfont; for (i=0;i<length;i++) { if (table[6 + i] == code) return i; } } return 0; case 4: /* Microsoft/Adobe segmented mapping. */ { int segCount2 = u16(table + 6); byte *endCount = table + 14; byte *startCount = endCount + segCount2 + 2; byte *idDelta = startCount + segCount2; byte *idRangeOffset = idDelta + segCount2; int i2; if (segCount2 < 3 || segCount2 > 65535) return gs_error_invalidfont; byte *startCount = endCount + segCount2 + 2; byte *idDelta = startCount + segCount2; byte *idRangeOffset = idDelta + segCount2; byte *giddata; int i2; if (segCount2 < 3 || segCount2 > 65535 || idRangeOffset > font->data + font->length) return gs_error_invalidfont; for (i2 = 0; i2 < segCount2 - 3; i2 += 2) if (roff == 0) { glyph = (i + delta) & 0xffff; } else { glyph = u16(idRangeOffset + i2 + roff + ((i - start) << 1)); } if (glyph == code) { return i; } } } if (roff == 0) { glyph = (i + delta) & 0xffff; } else { if ((giddata = (idRangeOffset + i2 + roff + ((i - start) << 1))) > font->data + font->length) { return_error(gs_error_invalidfont); } glyph = u16(giddata); } if (glyph == code) { return i; ch = u16(&table[10 + (i * 2)]); if (ch == code) return (firstCode + i); } } return 0; case 10: /* Trimmed array (like 6) */ { unsigned int ch, i, length = u32(&table[20]); int firstCode = u32(&table[16]); for (i=0;i<length;i++) { ch = u16(&table[10 + (i * 2)]); if (ch == code) return (firstCode + i); } } return 0; case 12: /* Segmented coverage. (like 4) */ { unsigned int nGroups = u32(&table[12]); int Group; for (Group=0;Group<nGroups;Group++) { int startCharCode = u32(&table[16 + (Group * 12)]); int endCharCode = u32(&table[16 + (Group * 12) + 4]); int startGlyphCode = u32(&table[16 + (Group * 12) + 8]); if (code >= startGlyphCode && code <= (startGlyphCode + (endCharCode - startCharCode))) { return startGlyphCode + (code - startCharCode); } } } return 0; case 2: /* High-byte mapping through table. */ case 8: /* Mixed 16-bit and 32-bit coverage (like 2) */ default: gs_warn1("unknown cmap format: %d\n", u16(table)); return 0; }
127,631,464,692,449,460,000,000,000,000,000,000,000
None
null
[ "CWE-125" ]
CVE-2017-9740
The xps_decode_font_char_imp function in xps/xpsfont.c in Artifex Ghostscript GhostXPS 9.21 allows remote attackers to cause a denial of service (heap-based buffer over-read and application crash) or possibly have unspecified other impact via a crafted document.
https://nvd.nist.gov/vuln/detail/CVE-2017-9740
134
ghostscript
937ccd17ac65935633b2ebc06cb7089b91e17e6b
http://git.ghostscript.com/?p=mupdf
http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=937ccd17ac65935633b2ebc06cb7089b91e17e6b
None
1
static void gx_ttfReader__Read(ttfReader *self, void *p, int n) { gx_ttfReader *r = (gx_ttfReader *)self; const byte *q; if (!r->error) { if (r->extra_glyph_index != -1) { q = r->glyph_data.bits.data + r->pos; r->error = (r->glyph_data.bits.size - r->pos < n ? gs_note_error(gs_error_invalidfont) : 0); if (r->error == 0) memcpy(p, q, n); unsigned int cnt; for (cnt = 0; cnt < (uint)n; cnt += r->error) { r->error = r->pfont->data.string_proc(r->pfont, (ulong)r->pos + cnt, (ulong)n - cnt, &q); if (r->error < 0) break; else if ( r->error == 0) { memcpy((char *)p + cnt, q, n - cnt); break; } else { memcpy((char *)p + cnt, q, r->error); } } } } if (r->error) { memset(p, 0, n); return; } r->pos += n; }
68,672,817,859,874,020,000,000,000,000,000,000,000
None
null
[ "CWE-125" ]
CVE-2017-9727
The gx_ttfReader__Read function in base/gxttfb.c in Artifex Ghostscript GhostXPS 9.21 allows remote attackers to cause a denial of service (heap-based buffer over-read and application crash) or possibly have unspecified other impact via a crafted document.
https://nvd.nist.gov/vuln/detail/CVE-2017-9727
157,996
ghostscript
937ccd17ac65935633b2ebc06cb7089b91e17e6b
http://git.ghostscript.com/?p=mupdf
http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=937ccd17ac65935633b2ebc06cb7089b91e17e6b
None
0
static void gx_ttfReader__Read(ttfReader *self, void *p, int n) { gx_ttfReader *r = (gx_ttfReader *)self; const byte *q; if (!r->error) { if (r->extra_glyph_index != -1) { q = r->glyph_data.bits.data + r->pos; r->error = ((r->pos >= r->glyph_data.bits.size || r->glyph_data.bits.size - r->pos < n) ? gs_note_error(gs_error_invalidfont) : 0); if (r->error == 0) memcpy(p, q, n); unsigned int cnt; for (cnt = 0; cnt < (uint)n; cnt += r->error) { r->error = r->pfont->data.string_proc(r->pfont, (ulong)r->pos + cnt, (ulong)n - cnt, &q); if (r->error < 0) break; else if ( r->error == 0) { memcpy((char *)p + cnt, q, n - cnt); break; } else { memcpy((char *)p + cnt, q, r->error); } } } } if (r->error) { memset(p, 0, n); return; } r->pos += n; }
292,644,363,497,676,880,000,000,000,000,000,000,000
None
null
[ "CWE-125" ]
CVE-2017-9727
The gx_ttfReader__Read function in base/gxttfb.c in Artifex Ghostscript GhostXPS 9.21 allows remote attackers to cause a denial of service (heap-based buffer over-read and application crash) or possibly have unspecified other impact via a crafted document.
https://nvd.nist.gov/vuln/detail/CVE-2017-9727
135
ghostscript
7755e67116e8973ee0e3b22d653df026a84fa01b
http://git.ghostscript.com/?p=mupdf
http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=7755e67116e8973ee0e3b22d653df026a84fa01b
None
1
static void Ins_MDRP( INS_ARG ) { Int point; TT_F26Dot6 distance, org_dist; point = (Int)args[0]; if ( BOUNDS( args[0], CUR.zp1.n_points ) ) { /* Current version of FreeType silently ignores this out of bounds error * and drops the instruction, see bug #691121 return; } /* XXX: Is there some undocumented feature while in the */ /* twilight zone? */ org_dist = CUR_Func_dualproj( CUR.zp1.org_x[point] - CUR.zp0.org_x[CUR.GS.rp0], CUR.zp1.org_y[point] - CUR.zp0.org_y[CUR.GS.rp0] ); /* single width cutin test */ if ( ABS(org_dist) < CUR.GS.single_width_cutin ) { if ( org_dist >= 0 ) org_dist = CUR.GS.single_width_value; else org_dist = -CUR.GS.single_width_value; } /* round flag */ if ( (CUR.opcode & 4) != 0 ) distance = CUR_Func_round( org_dist, CUR.metrics.compensations[CUR.opcode & 3] ); else distance = Round_None( EXEC_ARGS org_dist, CUR.metrics.compensations[CUR.opcode & 3] ); /* minimum distance flag */ if ( (CUR.opcode & 8) != 0 ) { if ( org_dist >= 0 ) { if ( distance < CUR.GS.minimum_distance ) distance = CUR.GS.minimum_distance; } else { if ( distance > -CUR.GS.minimum_distance ) distance = -CUR.GS.minimum_distance; } } /* now move the point */ org_dist = CUR_Func_project( CUR.zp1.cur_x[point] - CUR.zp0.cur_x[CUR.GS.rp0], CUR.zp1.cur_y[point] - CUR.zp0.cur_y[CUR.GS.rp0] ); CUR_Func_move( &CUR.zp1, point, distance - org_dist ); CUR.GS.rp1 = CUR.GS.rp0; CUR.GS.rp2 = point; if ( (CUR.opcode & 16) != 0 ) CUR.GS.rp0 = point; }
29,186,964,022,494,243,000,000,000,000,000,000,000
None
null
[ "CWE-125" ]
CVE-2017-9726
The Ins_MDRP function in base/ttinterp.c in Artifex Ghostscript GhostXPS 9.21 allows remote attackers to cause a denial of service (heap-based buffer over-read and application crash) or possibly have unspecified other impact via a crafted document.
https://nvd.nist.gov/vuln/detail/CVE-2017-9726
157,997
ghostscript
7755e67116e8973ee0e3b22d653df026a84fa01b
http://git.ghostscript.com/?p=mupdf
http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=7755e67116e8973ee0e3b22d653df026a84fa01b
None
0
static void Ins_MDRP( INS_ARG ) { Int point; TT_F26Dot6 distance, org_dist; point = (Int)args[0]; if ( BOUNDS( args[0], CUR.zp1.n_points ) || BOUNDS( CUR.GS.rp0, CUR.zp0.n_points) ) { /* Current version of FreeType silently ignores this out of bounds error * and drops the instruction, see bug #691121 return; } /* XXX: Is there some undocumented feature while in the */ /* twilight zone? */ org_dist = CUR_Func_dualproj( CUR.zp1.org_x[point] - CUR.zp0.org_x[CUR.GS.rp0], CUR.zp1.org_y[point] - CUR.zp0.org_y[CUR.GS.rp0] ); /* single width cutin test */ if ( ABS(org_dist) < CUR.GS.single_width_cutin ) { if ( org_dist >= 0 ) org_dist = CUR.GS.single_width_value; else org_dist = -CUR.GS.single_width_value; } /* round flag */ if ( (CUR.opcode & 4) != 0 ) distance = CUR_Func_round( org_dist, CUR.metrics.compensations[CUR.opcode & 3] ); else distance = Round_None( EXEC_ARGS org_dist, CUR.metrics.compensations[CUR.opcode & 3] ); /* minimum distance flag */ if ( (CUR.opcode & 8) != 0 ) { if ( org_dist >= 0 ) { if ( distance < CUR.GS.minimum_distance ) distance = CUR.GS.minimum_distance; } else { if ( distance > -CUR.GS.minimum_distance ) distance = -CUR.GS.minimum_distance; } } /* now move the point */ org_dist = CUR_Func_project( CUR.zp1.cur_x[point] - CUR.zp0.cur_x[CUR.GS.rp0], CUR.zp1.cur_y[point] - CUR.zp0.cur_y[CUR.GS.rp0] ); CUR_Func_move( &CUR.zp1, point, distance - org_dist ); CUR.GS.rp1 = CUR.GS.rp0; CUR.GS.rp2 = point; if ( (CUR.opcode & 16) != 0 ) CUR.GS.rp0 = point; }
168,161,902,406,212,550,000,000,000,000,000,000,000
None
null
[ "CWE-125" ]
CVE-2017-9726
The Ins_MDRP function in base/ttinterp.c in Artifex Ghostscript GhostXPS 9.21 allows remote attackers to cause a denial of service (heap-based buffer over-read and application crash) or possibly have unspecified other impact via a crafted document.
https://nvd.nist.gov/vuln/detail/CVE-2017-9726
136
dbus
166978a09cf5edff4028e670b6074215a4c75eca
http://gitweb.freedesktop.org/?p=dbus/dbus
https://cgit.freedesktop.org/dbus/dbus-glib/commit/?id=166978a09cf5edff4028e670b6074215a4c75eca
None
1
dbus_g_proxy_manager_filter (DBusConnection *connection, DBusMessage *message, void *user_data) { DBusGProxyManager *manager; if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL) return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; manager = user_data; dbus_g_proxy_manager_ref (manager); LOCK_MANAGER (manager); if (dbus_message_is_signal (message, DBUS_INTERFACE_LOCAL, "Disconnected")) { /* Destroy all the proxies, quite possibly resulting in unreferencing * the proxy manager and the connection as well. */ GSList *all; GSList *tmp; all = dbus_g_proxy_manager_list_all (manager); tmp = all; while (tmp != NULL) { DBusGProxy *proxy; proxy = DBUS_G_PROXY (tmp->data); UNLOCK_MANAGER (manager); dbus_g_proxy_destroy (proxy); g_object_unref (G_OBJECT (proxy)); LOCK_MANAGER (manager); tmp = tmp->next; } g_slist_free (all); #ifndef G_DISABLE_CHECKS if (manager->proxy_lists != NULL) g_warning ("Disconnection emitted \"destroy\" on all DBusGProxy, but somehow new proxies were created in response to one of those destroy signals. This will cause a memory leak."); #endif } else { char *tri; GSList *full_list; GSList *owned_names; GSList *tmp; const char *sender; /* First we handle NameOwnerChanged internally */ if (dbus_message_is_signal (message, DBUS_INTERFACE_DBUS, "NameOwnerChanged")) { DBusError derr; dbus_error_init (&derr); if (!dbus_message_get_args (message, &derr, DBUS_TYPE_STRING, &name, DBUS_TYPE_STRING, &prev_owner, DBUS_TYPE_STRING, &new_owner, DBUS_TYPE_INVALID)) { /* Ignore this error */ dbus_error_free (&derr); } else if (manager->owner_names != NULL) { dbus_g_proxy_manager_replace_name_owner (manager, name, prev_owner, new_owner); } } } }
115,276,448,693,599,870,000,000,000,000,000,000,000
None
null
[ "CWE-20" ]
CVE-2013-0292
The dbus_g_proxy_manager_filter function in dbus-gproxy in Dbus-glib before 0.100.1 does not properly verify the sender of NameOwnerChanged signals, which allows local users to gain privileges via a spoofed signal.
https://nvd.nist.gov/vuln/detail/CVE-2013-0292
157,998
dbus
166978a09cf5edff4028e670b6074215a4c75eca
http://gitweb.freedesktop.org/?p=dbus/dbus
https://cgit.freedesktop.org/dbus/dbus-glib/commit/?id=166978a09cf5edff4028e670b6074215a4c75eca
None
0
dbus_g_proxy_manager_filter (DBusConnection *connection, DBusMessage *message, void *user_data) { DBusGProxyManager *manager; if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL) return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; manager = user_data; dbus_g_proxy_manager_ref (manager); LOCK_MANAGER (manager); if (dbus_message_is_signal (message, DBUS_INTERFACE_LOCAL, "Disconnected")) { /* Destroy all the proxies, quite possibly resulting in unreferencing * the proxy manager and the connection as well. */ GSList *all; GSList *tmp; all = dbus_g_proxy_manager_list_all (manager); tmp = all; while (tmp != NULL) { DBusGProxy *proxy; proxy = DBUS_G_PROXY (tmp->data); UNLOCK_MANAGER (manager); dbus_g_proxy_destroy (proxy); g_object_unref (G_OBJECT (proxy)); LOCK_MANAGER (manager); tmp = tmp->next; } g_slist_free (all); #ifndef G_DISABLE_CHECKS if (manager->proxy_lists != NULL) g_warning ("Disconnection emitted \"destroy\" on all DBusGProxy, but somehow new proxies were created in response to one of those destroy signals. This will cause a memory leak."); #endif } else { char *tri; GSList *full_list; GSList *owned_names; GSList *tmp; const char *sender; sender = dbus_message_get_sender (message); /* First we handle NameOwnerChanged internally */ if (g_strcmp0 (sender, DBUS_SERVICE_DBUS) == 0 && dbus_message_is_signal (message, DBUS_INTERFACE_DBUS, "NameOwnerChanged")) { DBusError derr; dbus_error_init (&derr); if (!dbus_message_get_args (message, &derr, DBUS_TYPE_STRING, &name, DBUS_TYPE_STRING, &prev_owner, DBUS_TYPE_STRING, &new_owner, DBUS_TYPE_INVALID)) { /* Ignore this error */ dbus_error_free (&derr); } else if (manager->owner_names != NULL) { dbus_g_proxy_manager_replace_name_owner (manager, name, prev_owner, new_owner); } } } }
242,242,174,897,063,400,000,000,000,000,000,000,000
None
null
[ "CWE-20" ]
CVE-2013-0292
The dbus_g_proxy_manager_filter function in dbus-gproxy in Dbus-glib before 0.100.1 does not properly verify the sender of NameOwnerChanged signals, which allows local users to gain privileges via a spoofed signal.
https://nvd.nist.gov/vuln/detail/CVE-2013-0292
139
ghostscript
c53183d4e7103e87368b7cfa15367a47d559e323
http://git.ghostscript.com/?p=mupdf
http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=c53183d4e7103e87368b7cfa15367a47d559e323
None
1
xps_true_callback_glyph_name(gs_font *pfont, gs_glyph glyph, gs_const_string *pstr) { /* This function is copied verbatim from plfont.c */ int table_length; int table_offset; ulong format; uint numGlyphs; uint glyph_name_index; const byte *postp; /* post table pointer */ /* guess if the font type is not truetype */ if ( pfont->FontType != ft_TrueType ) { pstr->size = strlen((char*)pstr->data); return 0; } else { return gs_throw1(-1, "glyph index %lu out of range", (ulong)glyph); } }
83,736,377,691,001,720,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2017-9619
The xps_true_callback_glyph_name function in xps/xpsttf.c in Artifex Ghostscript GhostXPS 9.21 allows remote attackers to cause a denial of service (Segmentation Violation and application crash) via a crafted file.
https://nvd.nist.gov/vuln/detail/CVE-2017-9619
158,000
ghostscript
c53183d4e7103e87368b7cfa15367a47d559e323
http://git.ghostscript.com/?p=mupdf
http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=c53183d4e7103e87368b7cfa15367a47d559e323
None
0
xps_true_callback_glyph_name(gs_font *pfont, gs_glyph glyph, gs_const_string *pstr) { /* This function is copied verbatim from plfont.c */ int table_length; int table_offset; ulong format; int numGlyphs; uint glyph_name_index; const byte *postp; /* post table pointer */ if (glyph >= GS_MIN_GLYPH_INDEX) { glyph -= GS_MIN_GLYPH_INDEX; } /* guess if the font type is not truetype */ if ( pfont->FontType != ft_TrueType ) { pstr->size = strlen((char*)pstr->data); return 0; } else { return gs_throw1(-1, "glyph index %lu out of range", (ulong)glyph); } }
61,931,341,795,887,410,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2017-9619
The xps_true_callback_glyph_name function in xps/xpsttf.c in Artifex Ghostscript GhostXPS 9.21 allows remote attackers to cause a denial of service (Segmentation Violation and application crash) via a crafted file.
https://nvd.nist.gov/vuln/detail/CVE-2017-9619
140
ghostscript
3c2aebbedd37fab054e80f2e315de07d7e9b5bdb
http://git.ghostscript.com/?p=mupdf
http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=3c2aebbedd37fab054e80f2e315de07d7e9b5bdb
None
1
xps_load_sfnt_name(xps_font_t *font, char *namep) { byte *namedata; int offset, length; /*int format;*/ int count, stringoffset; int found; int i, k; found = 0; strcpy(namep, "Unknown"); offset = xps_find_sfnt_table(font, "name", &length); if (offset < 0 || length < 6) { gs_warn("cannot find name table"); return; } /* validate the offset, and the data for the two * values we're about to read */ if (offset + 6 > font->length) { gs_warn("name table byte offset invalid"); return; } namedata = font->data + offset; /*format = u16(namedata + 0);*/ count = u16(namedata + 2); stringoffset = u16(namedata + 4); if (stringoffset + offset > font->length || offset + 6 + count * 12 > font->length) { gs_warn("name table invalid"); return; } if (length < 6 + (count * 12)) { gs_warn("name table too short"); return; } for (i = 0; i < count; i++) { byte *record = namedata + 6 + i * 12; int pid = u16(record + 0); int eid = u16(record + 2); int langid = u16(record + 4); int nameid = u16(record + 6); length = u16(record + 8); offset = u16(record + 10); /* Full font name or postscript name */ if (nameid == 4 || nameid == 6) { if (found < 3) { memcpy(namep, namedata + stringoffset + offset, length); namep[length] = 0; found = 3; } } if (pid == 3 && eid == 1 && langid == 0x409) /* windows unicode ucs-2, US */ { if (found < 2) { unsigned char *s = namedata + stringoffset + offset; int n = length / 2; for (k = 0; k < n; k ++) { int c = u16(s + k * 2); namep[k] = isprint(c) ? c : '?'; } namep[k] = 0; found = 2; } } if (pid == 3 && eid == 10 && langid == 0x409) /* windows unicode ucs-4, US */ { if (found < 1) { unsigned char *s = namedata + stringoffset + offset; int n = length / 4; for (k = 0; k < n; k ++) { int c = u32(s + k * 4); namep[k] = isprint(c) ? c : '?'; } namep[k] = 0; found = 1; } } } }
112,369,513,254,285,680,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2017-9618
The xps_load_sfnt_name function in xps/xpsfont.c in Artifex Ghostscript GhostXPS 9.21 allows remote attackers to cause a denial of service (buffer overflow and application crash) or possibly have unspecified other impact via a crafted document.
https://nvd.nist.gov/vuln/detail/CVE-2017-9618
158,001
ghostscript
3c2aebbedd37fab054e80f2e315de07d7e9b5bdb
http://git.ghostscript.com/?p=mupdf
http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=3c2aebbedd37fab054e80f2e315de07d7e9b5bdb
None
0
xps_load_sfnt_name(xps_font_t *font, char *namep) xps_load_sfnt_name(xps_font_t *font, char *namep, const int buflen) { byte *namedata; int offset, length; /*int format;*/ int count, stringoffset; int found; int i, k; found = 0; strcpy(namep, "Unknown"); offset = xps_find_sfnt_table(font, "name", &length); if (offset < 0 || length < 6) { gs_warn("cannot find name table"); return; } /* validate the offset, and the data for the two * values we're about to read */ if (offset + 6 > font->length) { gs_warn("name table byte offset invalid"); return; } namedata = font->data + offset; /*format = u16(namedata + 0);*/ count = u16(namedata + 2); stringoffset = u16(namedata + 4); if (stringoffset + offset > font->length || offset + 6 + count * 12 > font->length) { gs_warn("name table invalid"); return; } if (length < 6 + (count * 12)) { gs_warn("name table too short"); return; } for (i = 0; i < count; i++) { byte *record = namedata + 6 + i * 12; int pid = u16(record + 0); int eid = u16(record + 2); int langid = u16(record + 4); int nameid = u16(record + 6); length = u16(record + 8); offset = u16(record + 10); length = length > buflen - 1 ? buflen - 1: length; /* Full font name or postscript name */ if (nameid == 4 || nameid == 6) { if (found < 3) { memcpy(namep, namedata + stringoffset + offset, length); namep[length] = 0; found = 3; } } if (pid == 3 && eid == 1 && langid == 0x409) /* windows unicode ucs-2, US */ { if (found < 2) { unsigned char *s = namedata + stringoffset + offset; int n = length / 2; for (k = 0; k < n; k ++) { int c = u16(s + k * 2); namep[k] = isprint(c) ? c : '?'; } namep[k] = 0; found = 2; } } if (pid == 3 && eid == 10 && langid == 0x409) /* windows unicode ucs-4, US */ { if (found < 1) { unsigned char *s = namedata + stringoffset + offset; int n = length / 4; for (k = 0; k < n; k ++) { int c = u32(s + k * 4); namep[k] = isprint(c) ? c : '?'; } namep[k] = 0; found = 1; } } } }
35,053,491,490,394,060,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2017-9618
The xps_load_sfnt_name function in xps/xpsfont.c in Artifex Ghostscript GhostXPS 9.21 allows remote attackers to cause a denial of service (buffer overflow and application crash) or possibly have unspecified other impact via a crafted document.
https://nvd.nist.gov/vuln/detail/CVE-2017-9618
141
altlinux
ffe7058c70253d574b1963c7c93002bd410fddc9
http://git.altlinux.org/people/ldv/packages/?p=pam
http://git.altlinux.org/people/ldv/packages/?p=pam.git;a=commit;h=Linux-PAM-1_1_2-2-gffe7058c70253d574b1963c7c93002bd410fddc9
None
1
check_acl(pam_handle_t *pamh, const char *sense, const char *this_user, const char *other_user, int noent_code, int debug) { char path[PATH_MAX]; struct passwd *pwd; { char path[PATH_MAX]; struct passwd *pwd; FILE *fp; int i, save_errno; uid_t fsuid; /* Check this user's <sense> file. */ pwd = pam_modutil_getpwnam(pamh, this_user); if (pwd == NULL) { } /* Figure out what that file is really named. */ i = snprintf(path, sizeof(path), "%s/.xauth/%s", pwd->pw_dir, sense); if ((i >= (int)sizeof(path)) || (i < 0)) { pam_syslog(pamh, LOG_ERR, "name of user's home directory is too long"); return PAM_SESSION_ERR; } fsuid = setfsuid(pwd->pw_uid); fp = fopen(path, "r"); return PAM_SESSION_ERR; } fsuid = setfsuid(pwd->pw_uid); fp = fopen(path, "r"); save_errno = errno; setfsuid(fsuid); if (fp != NULL) { char buf[LINE_MAX], *tmp; /* Scan the file for a list of specs of users to "trust". */ while (fgets(buf, sizeof(buf), fp) != NULL) { other_user, path); } fclose(fp); return PAM_PERM_DENIED; } else { /* Default to okay if the file doesn't exist. */ errno = save_errno; switch (errno) { case ENOENT: if (noent_code == PAM_SUCCESS) { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s does not exist, ignoring", path); } } else { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s does not exist, failing", path); } } return noent_code; default: if (debug) { pam_syslog(pamh, LOG_DEBUG, "error opening %s: %m", path); } return PAM_PERM_DENIED; } } }
41,551,411,147,695,370,000,000,000,000,000,000,000
None
null
[ "CWE-399" ]
CVE-2010-4707
The check_acl function in pam_xauth.c in the pam_xauth module in Linux-PAM (aka pam) 1.1.2 and earlier does not verify that a certain ACL file is a regular file, which might allow local users to cause a denial of service (resource consumption) via a special file.
https://nvd.nist.gov/vuln/detail/CVE-2010-4707
158,002
altlinux
ffe7058c70253d574b1963c7c93002bd410fddc9
http://git.altlinux.org/people/ldv/packages/?p=pam
http://git.altlinux.org/people/ldv/packages/?p=pam.git;a=commit;h=Linux-PAM-1_1_2-2-gffe7058c70253d574b1963c7c93002bd410fddc9
None
0
check_acl(pam_handle_t *pamh, const char *sense, const char *this_user, const char *other_user, int noent_code, int debug) { char path[PATH_MAX]; struct passwd *pwd; { char path[PATH_MAX]; struct passwd *pwd; FILE *fp = NULL; int i, fd = -1, save_errno; uid_t fsuid; struct stat st; /* Check this user's <sense> file. */ pwd = pam_modutil_getpwnam(pamh, this_user); if (pwd == NULL) { } /* Figure out what that file is really named. */ i = snprintf(path, sizeof(path), "%s/.xauth/%s", pwd->pw_dir, sense); if ((i >= (int)sizeof(path)) || (i < 0)) { pam_syslog(pamh, LOG_ERR, "name of user's home directory is too long"); return PAM_SESSION_ERR; } fsuid = setfsuid(pwd->pw_uid); fp = fopen(path, "r"); return PAM_SESSION_ERR; } fsuid = setfsuid(pwd->pw_uid); if (!stat(path, &st)) { if (!S_ISREG(st.st_mode)) errno = EINVAL; else fd = open(path, O_RDONLY | O_NOCTTY); } save_errno = errno; setfsuid(fsuid); if (fd >= 0) { if (!fstat(fd, &st)) { if (!S_ISREG(st.st_mode)) errno = EINVAL; else fp = fdopen(fd, "r"); } if (!fp) { save_errno = errno; close(fd); } } if (fp) { char buf[LINE_MAX], *tmp; /* Scan the file for a list of specs of users to "trust". */ while (fgets(buf, sizeof(buf), fp) != NULL) { other_user, path); } fclose(fp); return PAM_PERM_DENIED; } else { /* Default to okay if the file doesn't exist. */ errno = save_errno; switch (errno) { case ENOENT: if (noent_code == PAM_SUCCESS) { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s does not exist, ignoring", path); } } else { if (debug) { pam_syslog(pamh, LOG_DEBUG, "%s does not exist, failing", path); } } return noent_code; default: if (debug) { pam_syslog(pamh, LOG_DEBUG, "error opening %s: %m", path); } return PAM_PERM_DENIED; } } }
299,701,102,454,126,300,000,000,000,000,000,000,000
None
null
[ "CWE-399" ]
CVE-2010-4707
The check_acl function in pam_xauth.c in the pam_xauth module in Linux-PAM (aka pam) 1.1.2 and earlier does not verify that a certain ACL file is a regular file, which might allow local users to cause a denial of service (resource consumption) via a special file.
https://nvd.nist.gov/vuln/detail/CVE-2010-4707
144
openssl
62e4506a7d4cec1c8e1ff687f6b220f6a62a57c7
https://github.com/openssl/openssl
http://git.openssl.org/gitweb/?p=openssl.git;a=commitdiff;h=62e4506a7d4cec1c8e1ff687f6b220f6a62a57c7
Don't try and verify signatures if key is NULL (CVE-2013-0166) Add additional check to catch this in ASN1_item_verify too.
1
int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey) { EVP_MD_CTX ctx; unsigned char *buf_in=NULL; int ret= -1,inl; int mdnid, pknid; EVP_MD_CTX_init(&ctx); /* Convert signature OID into digest and public key OIDs */ { if (!pkey->ameth || !pkey->ameth->item_verify) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } ret = pkey->ameth->item_verify(&ctx, it, asn, a, signature, pkey); /* Return value of 2 means carry on, anything else means we * exit straight away: either a fatal error of the underlying * verification routine handles all verification. */ if (ret != 2) goto err; ret = -1; } else { const EVP_MD *type; type=EVP_get_digestbynid(mdnid); if (type == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); goto err; } /* Check public key OID matches public key type */ if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE); goto err; } if (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } } inl = ASN1_item_i2d(asn, &buf_in, it); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } if (!EVP_DigestVerifyUpdate(&ctx,buf_in,inl)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (EVP_DigestVerifyFinal(&ctx,signature->data, (size_t)signature->length) <= 0) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); }
269,188,142,815,144,650,000,000,000,000,000,000,000
None
null
[ "CWE-310" ]
CVE-2013-0166
OpenSSL before 0.9.8y, 1.0.0 before 1.0.0k, and 1.0.1 before 1.0.1d does not properly perform signature verification for OCSP responses, which allows remote OCSP servers to cause a denial of service (NULL pointer dereference and application crash) via an invalid key.
https://nvd.nist.gov/vuln/detail/CVE-2013-0166
158,005
openssl
62e4506a7d4cec1c8e1ff687f6b220f6a62a57c7
https://github.com/openssl/openssl
http://git.openssl.org/gitweb/?p=openssl.git;a=commitdiff;h=62e4506a7d4cec1c8e1ff687f6b220f6a62a57c7
Don't try and verify signatures if key is NULL (CVE-2013-0166) Add additional check to catch this in ASN1_item_verify too.
0
int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey) { EVP_MD_CTX ctx; unsigned char *buf_in=NULL; int ret= -1,inl; int mdnid, pknid; if (!pkey) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER); return -1; } EVP_MD_CTX_init(&ctx); /* Convert signature OID into digest and public key OIDs */ { if (!pkey->ameth || !pkey->ameth->item_verify) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } ret = pkey->ameth->item_verify(&ctx, it, asn, a, signature, pkey); /* Return value of 2 means carry on, anything else means we * exit straight away: either a fatal error of the underlying * verification routine handles all verification. */ if (ret != 2) goto err; ret = -1; } else { const EVP_MD *type; type=EVP_get_digestbynid(mdnid); if (type == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); goto err; } /* Check public key OID matches public key type */ if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE); goto err; } if (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } } inl = ASN1_item_i2d(asn, &buf_in, it); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } if (!EVP_DigestVerifyUpdate(&ctx,buf_in,inl)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (EVP_DigestVerifyFinal(&ctx,signature->data, (size_t)signature->length) <= 0) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); }
283,580,637,719,099,980,000,000,000,000,000,000,000
None
null
[ "CWE-310" ]
CVE-2013-0166
OpenSSL before 0.9.8y, 1.0.0 before 1.0.0k, and 1.0.1 before 1.0.1d does not properly perform signature verification for OCSP responses, which allows remote OCSP servers to cause a denial of service (NULL pointer dereference and application crash) via an invalid key.
https://nvd.nist.gov/vuln/detail/CVE-2013-0166
145
openssl
66e8211c0b1347970096e04b18aa52567c325200
https://github.com/openssl/openssl
http://git.openssl.org/gitweb/?p=openssl.git;a=commitdiff;h=66e8211c0b1347970096e04b18aa52567c325200
Don't try and verify signatures if key is NULL (CVE-2013-0166) Add additional check to catch this in ASN1_item_verify too.
1
int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey) { EVP_MD_CTX ctx; const EVP_MD *type; unsigned char *buf_in=NULL; int ret= -1,i,inl; EVP_MD_CTX_init(&ctx); i=OBJ_obj2nid(a->algorithm); type=EVP_get_digestbyname(OBJ_nid2sn(i)); if (!EVP_VerifyInit_ex(&ctx,type, NULL)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } inl = ASN1_item_i2d(asn, &buf_in, it); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl); OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data, (unsigned int)signature->length,pkey) <= 0) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); }
107,114,806,548,745,270,000,000,000,000,000,000,000
None
null
[ "CWE-310" ]
CVE-2013-0166
OpenSSL before 0.9.8y, 1.0.0 before 1.0.0k, and 1.0.1 before 1.0.1d does not properly perform signature verification for OCSP responses, which allows remote OCSP servers to cause a denial of service (NULL pointer dereference and application crash) via an invalid key.
https://nvd.nist.gov/vuln/detail/CVE-2013-0166
158,006
openssl
66e8211c0b1347970096e04b18aa52567c325200
https://github.com/openssl/openssl
http://git.openssl.org/gitweb/?p=openssl.git;a=commitdiff;h=66e8211c0b1347970096e04b18aa52567c325200
Don't try and verify signatures if key is NULL (CVE-2013-0166) Add additional check to catch this in ASN1_item_verify too.
0
int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey) { EVP_MD_CTX ctx; const EVP_MD *type; unsigned char *buf_in=NULL; int ret= -1,i,inl; if (!pkey) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER); return -1; } EVP_MD_CTX_init(&ctx); i=OBJ_obj2nid(a->algorithm); type=EVP_get_digestbyname(OBJ_nid2sn(i)); if (!EVP_VerifyInit_ex(&ctx,type, NULL)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } inl = ASN1_item_i2d(asn, &buf_in, it); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl); OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data, (unsigned int)signature->length,pkey) <= 0) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); }
40,999,153,640,730,437,000,000,000,000,000,000,000
None
null
[ "CWE-310" ]
CVE-2013-0166
OpenSSL before 0.9.8y, 1.0.0 before 1.0.0k, and 1.0.1 before 1.0.1d does not properly perform signature verification for OCSP responses, which allows remote OCSP servers to cause a denial of service (NULL pointer dereference and application crash) via an invalid key.
https://nvd.nist.gov/vuln/detail/CVE-2013-0166
146
openssl
ebc71865f0506a293242bd4aec97cdc7a8ef24b0
https://github.com/openssl/openssl
http://git.openssl.org/gitweb/?p=openssl.git;a=commitdiff;h=ebc71865f0506a293242bd4aec97cdc7a8ef24b0
Don't try and verify signatures if key is NULL (CVE-2013-0166) Add additional check to catch this in ASN1_item_verify too.
1
int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey) { EVP_MD_CTX ctx; const EVP_MD *type = NULL; unsigned char *buf_in=NULL; int ret= -1,inl; int mdnid, pknid; EVP_MD_CTX_init(&ctx); /* Convert signature OID into digest and public key OIDs */ if (type == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); goto err; } /* Check public key OID matches public key type */ if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE); goto err; } if (!EVP_VerifyInit_ex(&ctx,type, NULL)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } inl = ASN1_item_i2d(asn, &buf_in, it); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl); OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data, (unsigned int)signature->length,pkey) <= 0) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); }
292,171,545,981,096,540,000,000,000,000,000,000,000
None
null
[ "CWE-310" ]
CVE-2013-0166
OpenSSL before 0.9.8y, 1.0.0 before 1.0.0k, and 1.0.1 before 1.0.1d does not properly perform signature verification for OCSP responses, which allows remote OCSP servers to cause a denial of service (NULL pointer dereference and application crash) via an invalid key.
https://nvd.nist.gov/vuln/detail/CVE-2013-0166
158,007
openssl
ebc71865f0506a293242bd4aec97cdc7a8ef24b0
https://github.com/openssl/openssl
http://git.openssl.org/gitweb/?p=openssl.git;a=commitdiff;h=ebc71865f0506a293242bd4aec97cdc7a8ef24b0
Don't try and verify signatures if key is NULL (CVE-2013-0166) Add additional check to catch this in ASN1_item_verify too.
0
int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey) { EVP_MD_CTX ctx; const EVP_MD *type = NULL; unsigned char *buf_in=NULL; int ret= -1,inl; int mdnid, pknid; if (!pkey) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER); return -1; } EVP_MD_CTX_init(&ctx); /* Convert signature OID into digest and public key OIDs */ if (type == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); goto err; } /* Check public key OID matches public key type */ if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE); goto err; } if (!EVP_VerifyInit_ex(&ctx,type, NULL)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } inl = ASN1_item_i2d(asn, &buf_in, it); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl); OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data, (unsigned int)signature->length,pkey) <= 0) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); }
188,744,818,829,646,400,000,000,000,000,000,000,000
None
null
[ "CWE-310" ]
CVE-2013-0166
OpenSSL before 0.9.8y, 1.0.0 before 1.0.0k, and 1.0.1 before 1.0.1d does not properly perform signature verification for OCSP responses, which allows remote OCSP servers to cause a denial of service (NULL pointer dereference and application crash) via an invalid key.
https://nvd.nist.gov/vuln/detail/CVE-2013-0166
147
samba
10c3e3923022485c720f322ca4f0aca5d7501310
https://github.com/samba-team/samba
https://git.samba.org/?p=samba.git;a=commit;h=10c3e3923022485c720f322ca4f0aca5d7501310
s3: smbd: Don't loop infinitely on bad-symlink resolution. In the FILE_OPEN_IF case we have O_CREAT, but not O_EXCL. Previously we went into a loop trying first ~(O_CREAT|O_EXCL), and if that returned ENOENT try (O_CREAT|O_EXCL). We kept looping indefinately until we got an error, or the file was created or opened. The big problem here is dangling symlinks. Opening without O_NOFOLLOW means both bad symlink and missing path return -1, ENOENT from open(). As POSIX is pathname based it's not possible to tell the difference between these two cases in a non-racy way, so change to try only two attempts before giving up. We don't have this problem for the O_NOFOLLOW case as we just return NT_STATUS_OBJECT_PATH_NOT_FOUND mapped from the ELOOP POSIX error and immediately returned. Unroll the loop logic to two tries instead. BUG: https://bugzilla.samba.org/show_bug.cgi?id=12572 Pair-programmed-with: Ralph Boehme <[email protected]> Signed-off-by: Jeremy Allison <[email protected]> Signed-off-by: Ralph Boehme <[email protected]> Reviewed-by: Ralph Boehme <[email protected]>
1
static NTSTATUS fd_open_atomic(struct connection_struct *conn, files_struct *fsp, int flags, mode_t mode, bool *file_created) { NTSTATUS status = NT_STATUS_UNSUCCESSFUL; bool file_existed = VALID_STAT(fsp->fsp_name->st); *file_created = false; * We're not creating the file, just pass through. */ return fd_open(conn, fsp, flags, mode); }
161,881,144,216,406,610,000,000,000,000,000,000,000
None
null
[ "CWE-835" ]
CVE-2017-9461
smbd in Samba before 4.4.10 and 4.5.x before 4.5.6 has a denial of service vulnerability (fd_open_atomic infinite loop with high CPU usage and memory consumption) due to wrongly handling dangling symlinks.
https://nvd.nist.gov/vuln/detail/CVE-2017-9461
158,008
samba
10c3e3923022485c720f322ca4f0aca5d7501310
https://github.com/samba-team/samba
https://git.samba.org/?p=samba.git;a=commit;h=10c3e3923022485c720f322ca4f0aca5d7501310
s3: smbd: Don't loop infinitely on bad-symlink resolution. In the FILE_OPEN_IF case we have O_CREAT, but not O_EXCL. Previously we went into a loop trying first ~(O_CREAT|O_EXCL), and if that returned ENOENT try (O_CREAT|O_EXCL). We kept looping indefinately until we got an error, or the file was created or opened. The big problem here is dangling symlinks. Opening without O_NOFOLLOW means both bad symlink and missing path return -1, ENOENT from open(). As POSIX is pathname based it's not possible to tell the difference between these two cases in a non-racy way, so change to try only two attempts before giving up. We don't have this problem for the O_NOFOLLOW case as we just return NT_STATUS_OBJECT_PATH_NOT_FOUND mapped from the ELOOP POSIX error and immediately returned. Unroll the loop logic to two tries instead. BUG: https://bugzilla.samba.org/show_bug.cgi?id=12572 Pair-programmed-with: Ralph Boehme <[email protected]> Signed-off-by: Jeremy Allison <[email protected]> Signed-off-by: Ralph Boehme <[email protected]> Reviewed-by: Ralph Boehme <[email protected]>
0
static NTSTATUS fd_open_atomic(struct connection_struct *conn, files_struct *fsp, int flags, mode_t mode, bool *file_created) { NTSTATUS status = NT_STATUS_UNSUCCESSFUL; NTSTATUS retry_status; bool file_existed = VALID_STAT(fsp->fsp_name->st); int curr_flags; *file_created = false; * We're not creating the file, just pass through. */ return fd_open(conn, fsp, flags, mode); }
263,754,377,429,576,180,000,000,000,000,000,000,000
None
null
[ "CWE-835" ]
CVE-2017-9461
smbd in Samba before 4.4.10 and 4.5.x before 4.5.6 has a denial of service vulnerability (fd_open_atomic infinite loop with high CPU usage and memory consumption) due to wrongly handling dangling symlinks.
https://nvd.nist.gov/vuln/detail/CVE-2017-9461
150
openssl
d0666f289ac013094bbbf547bfbcd616199b7d2d
https://github.com/openssl/openssl
https://git.openssl.org/gitweb/?p=openssl.git;a=commit;h=d0666f289ac013094bbbf547bfbcd616199b7d2d
evp: prevent underflow in base64 decoding This patch resolves RT ticket #2608. Thanks to Robert Dugal for originally spotting this, and to David Ramos for noticing that the ball had been dropped. Signed-off-by: Geoff Thorpe <[email protected]>
1
int EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl) { int seof= -1,eof=0,rv= -1,ret=0,i,v,tmp,n,ln,exp_nl; unsigned char *d; n=ctx->num; d=ctx->enc_data; ln=ctx->line_num; exp_nl=ctx->expect_nl; /* last line of input. */ if ((inl == 0) || ((n == 0) && (conv_ascii2bin(in[0]) == B64_EOF))) { rv=0; goto end; } /* We parse the input data */ for (i=0; i<inl; i++) { /* If the current line is > 80 characters, scream alot */ if (ln >= 80) { rv= -1; goto end; } /* Get char and put it into the buffer */ tmp= *(in++); v=conv_ascii2bin(tmp); /* only save the good data :-) */ if (!B64_NOT_BASE64(v)) { OPENSSL_assert(n < (int)sizeof(ctx->enc_data)); d[n++]=tmp; ln++; } else if (v == B64_ERROR) { rv= -1; goto end; } /* have we seen a '=' which is 'definitly' the last * input line. seof will point to the character that * holds it. and eof will hold how many characters to * chop off. */ if (tmp == '=') { if (seof == -1) seof=n; eof++; } if (v == B64_CR) { ln = 0; if (exp_nl) continue; } /* eoln */ if (v == B64_EOLN) { ln=0; if (exp_nl) { exp_nl=0; continue; } } exp_nl=0; /* If we are at the end of input and it looks like a * line, process it. */ if (((i+1) == inl) && (((n&3) == 0) || eof)) { v=B64_EOF; /* In case things were given us in really small records (so two '=' were given in separate updates), eof may contain the incorrect number of ending bytes to skip, so let's redo the count */ eof = 0; if (d[n-1] == '=') eof++; if (d[n-2] == '=') eof++; /* There will never be more than two '=' */ } if ((v == B64_EOF && (n&3) == 0) || (n >= 64)) { /* This is needed to work correctly on 64 byte input * lines. We process the line and then need to * accept the '\n' */ if ((v != B64_EOF) && (n >= 64)) exp_nl=1; if (n > 0) { v=EVP_DecodeBlock(out,d,n); n=0; if (v < 0) { rv=0; goto end; } ret+=(v-eof); } else eof=1; v=0; } /* This is the case where we have had a short * but valid input line */ if ((v < ctx->length) && eof) { rv=0; goto end; } else ctx->length=v; if (seof >= 0) { rv=0; goto end; } out+=v; } }
314,448,950,255,259,250,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2015-0292
Integer underflow in the EVP_DecodeUpdate function in crypto/evp/encode.c in the base64-decoding implementation in OpenSSL before 0.9.8za, 1.0.0 before 1.0.0m, and 1.0.1 before 1.0.1h allows remote attackers to cause a denial of service (memory corruption) or possibly have unspecified other impact via crafted base64 data that triggers a buffer overflow.
https://nvd.nist.gov/vuln/detail/CVE-2015-0292
158,011
openssl
d0666f289ac013094bbbf547bfbcd616199b7d2d
https://github.com/openssl/openssl
https://git.openssl.org/gitweb/?p=openssl.git;a=commit;h=d0666f289ac013094bbbf547bfbcd616199b7d2d
evp: prevent underflow in base64 decoding This patch resolves RT ticket #2608. Thanks to Robert Dugal for originally spotting this, and to David Ramos for noticing that the ball had been dropped. Signed-off-by: Geoff Thorpe <[email protected]>
0
int EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl) { int seof= -1,eof=0,rv= -1,ret=0,i,v,tmp,n,ln,exp_nl; unsigned char *d; n=ctx->num; d=ctx->enc_data; ln=ctx->line_num; exp_nl=ctx->expect_nl; /* last line of input. */ if ((inl == 0) || ((n == 0) && (conv_ascii2bin(in[0]) == B64_EOF))) { rv=0; goto end; } /* We parse the input data */ for (i=0; i<inl; i++) { /* If the current line is > 80 characters, scream alot */ if (ln >= 80) { rv= -1; goto end; } /* Get char and put it into the buffer */ tmp= *(in++); v=conv_ascii2bin(tmp); /* only save the good data :-) */ if (!B64_NOT_BASE64(v)) { OPENSSL_assert(n < (int)sizeof(ctx->enc_data)); d[n++]=tmp; ln++; } else if (v == B64_ERROR) { rv= -1; goto end; } /* have we seen a '=' which is 'definitly' the last * input line. seof will point to the character that * holds it. and eof will hold how many characters to * chop off. */ if (tmp == '=') { if (seof == -1) seof=n; eof++; } if (v == B64_CR) { ln = 0; if (exp_nl) continue; } /* eoln */ if (v == B64_EOLN) { ln=0; if (exp_nl) { exp_nl=0; continue; } } exp_nl=0; /* If we are at the end of input and it looks like a * line, process it. */ if (((i+1) == inl) && (((n&3) == 0) || eof)) { v=B64_EOF; /* In case things were given us in really small records (so two '=' were given in separate updates), eof may contain the incorrect number of ending bytes to skip, so let's redo the count */ eof = 0; if (d[n-1] == '=') eof++; if (d[n-2] == '=') eof++; /* There will never be more than two '=' */ } if ((v == B64_EOF && (n&3) == 0) || (n >= 64)) { /* This is needed to work correctly on 64 byte input * lines. We process the line and then need to * accept the '\n' */ if ((v != B64_EOF) && (n >= 64)) exp_nl=1; if (n > 0) { v=EVP_DecodeBlock(out,d,n); n=0; if (v < 0) { rv=0; goto end; } if (eof > v) { rv=-1; goto end; } ret+=(v-eof); } else eof=1; v=0; } /* This is the case where we have had a short * but valid input line */ if ((v < ctx->length) && eof) { rv=0; goto end; } else ctx->length=v; if (seof >= 0) { rv=0; goto end; } out+=v; } }
290,784,375,241,955,930,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2015-0292
Integer underflow in the EVP_DecodeUpdate function in crypto/evp/encode.c in the base64-decoding implementation in OpenSSL before 0.9.8za, 1.0.0 before 1.0.0m, and 1.0.1 before 1.0.1h allows remote attackers to cause a denial of service (memory corruption) or possibly have unspecified other impact via crafted base64 data that triggers a buffer overflow.
https://nvd.nist.gov/vuln/detail/CVE-2015-0292
151
openssl
77c77f0a1b9f15b869ca3342186dfbedd1119d0e
https://github.com/openssl/openssl
https://git.openssl.org/?p=openssl.git;a=commitdiff;h=77c77f0a1b9f15b869ca3342186dfbedd1119d0e
Multiblock corrupted pointer fix OpenSSL 1.0.2 introduced the "multiblock" performance improvement. This feature only applies on 64 bit x86 architecture platforms that support AES NI instructions. A defect in the implementation of "multiblock" can cause OpenSSL's internal write buffer to become incorrectly set to NULL when using non-blocking IO. Typically, when the user application is using a socket BIO for writing, this will only result in a failed connection. However if some other BIO is used then it is likely that a segmentation fault will be triggered, thus enabling a potential DoS attack. CVE-2015-0290 Reviewed-by: Richard Levitte <[email protected]> Reviewed-by: Andy Polyakov <[email protected]>
1
int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len) { const unsigned char *buf = buf_; int tot; unsigned int n, nw; #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK unsigned int max_send_fragment; #endif SSL3_BUFFER *wb = &(s->s3->wbuf); int i; s->rwstate = SSL_NOTHING; OPENSSL_assert(s->s3->wnum <= INT_MAX); tot = s->s3->wnum; s->s3->wnum = 0; if (SSL_in_init(s) && !s->in_handshake) { i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return -1; } } /* * ensure that if we end up with a smaller value of data to write out * than the the original len from a write which didn't complete for * non-blocking I/O and also somehow ended up avoiding the check for * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be * possible to end up with (len-tot) as a large number that will then * promptly send beyond the end of the users buffer ... so we trap and * report the error in a way the user will notice */ if (len < tot) { SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_BAD_LENGTH); return (-1); } /* * first check if there is a SSL3_BUFFER still being written out. This * will happen with non blocking IO */ if (wb->left != 0) { i = ssl3_write_pending(s, type, &buf[tot], s->s3->wpend_tot); if (i <= 0) { /* XXX should we ssl3_release_write_buffer if i<0? */ s->s3->wnum = tot; return i; } tot += i; /* this might be last fragment */ } #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK /* * Depending on platform multi-block can deliver several *times* * better performance. Downside is that it has to allocate * jumbo buffer to accomodate up to 8 records, but the * compromise is considered worthy. */ if (type == SSL3_RT_APPLICATION_DATA && len >= 4 * (int)(max_send_fragment = s->max_send_fragment) && s->compress == NULL && s->msg_callback == NULL && SSL_USE_EXPLICIT_IV(s) && EVP_CIPHER_flags(s->enc_write_ctx->cipher) & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) { unsigned char aad[13]; EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param; int packlen; /* minimize address aliasing conflicts */ if ((max_send_fragment & 0xfff) == 0) max_send_fragment -= 512; if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */ ssl3_release_write_buffer(s); packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE, max_send_fragment, NULL); if (len >= 8 * (int)max_send_fragment) packlen *= 8; else packlen *= 4; wb->buf = OPENSSL_malloc(packlen); if(!wb->buf) { SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_MALLOC_FAILURE); return -1; } wb->len = packlen; } else if (tot == len) { /* done? */ OPENSSL_free(wb->buf); /* free jumbo buffer */ wb->buf = NULL; return tot; } n = (len - tot); for (;;) { if (n < 4 * max_send_fragment) { OPENSSL_free(wb->buf); /* free jumbo buffer */ wb->buf = NULL; break; } if (s->s3->alert_dispatch) { i = s->method->ssl_dispatch_alert(s); if (i <= 0) { s->s3->wnum = tot; return i; } } if (n >= 8 * max_send_fragment) nw = max_send_fragment * (mb_param.interleave = 8); else nw = max_send_fragment * (mb_param.interleave = 4); memcpy(aad, s->s3->write_sequence, 8); aad[8] = type; aad[9] = (unsigned char)(s->version >> 8); aad[10] = (unsigned char)(s->version); aad[11] = 0; aad[12] = 0; mb_param.out = NULL; mb_param.inp = aad; mb_param.len = nw; packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_AAD, sizeof(mb_param), &mb_param); if (packlen <= 0 || packlen > (int)wb->len) { /* never happens */ OPENSSL_free(wb->buf); /* free jumbo buffer */ wb->buf = NULL; break; } mb_param.out = wb->buf; mb_param.inp = &buf[tot]; mb_param.len = nw; if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT, sizeof(mb_param), &mb_param) <= 0) return -1; s->s3->write_sequence[7] += mb_param.interleave; if (s->s3->write_sequence[7] < mb_param.interleave) { int j = 6; while (j >= 0 && (++s->s3->write_sequence[j--]) == 0) ; } wb->offset = 0; wb->left = packlen; s->s3->wpend_tot = nw; s->s3->wpend_buf = &buf[tot]; s->s3->wpend_type = type; s->s3->wpend_ret = nw; i = ssl3_write_pending(s, type, &buf[tot], nw); if (i <= 0) { if (i < 0) { OPENSSL_free(wb->buf); wb->buf = NULL; } s->s3->wnum = tot; return i; } if (i == (int)n) { OPENSSL_free(wb->buf); /* free jumbo buffer */ wb->buf = NULL; return tot + i; } n -= i; tot += i; } } else #endif if (tot == len) { /* done? */ if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s)) ssl3_release_write_buffer(s); return tot; } n = (len - tot); for (;;) { if (n > s->max_send_fragment) nw = s->max_send_fragment; else nw = n; i = do_ssl3_write(s, type, &(buf[tot]), nw, 0); if (i <= 0) { /* XXX should we ssl3_release_write_buffer if i<0? */ s->s3->wnum = tot; return i; } if ((i == (int)n) || (type == SSL3_RT_APPLICATION_DATA && (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) { /* * next chunk of data should get another prepended empty fragment * in ciphersuites with known-IV weakness: */ s->s3->empty_fragment_done = 0; if ((i == (int)n) && s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s)) ssl3_release_write_buffer(s); return tot + i; } n -= i; tot += i; } }
275,384,842,882,047,000,000,000,000,000,000,000,000
None
null
[ "CWE-17" ]
CVE-2015-0290
The multi-block feature in the ssl3_write_bytes function in s3_pkt.c in OpenSSL 1.0.2 before 1.0.2a on 64-bit x86 platforms with AES NI support does not properly handle certain non-blocking I/O cases, which allows remote attackers to cause a denial of service (pointer corruption and application crash) via unspecified vectors.
https://nvd.nist.gov/vuln/detail/CVE-2015-0290
158,012
openssl
77c77f0a1b9f15b869ca3342186dfbedd1119d0e
https://github.com/openssl/openssl
https://git.openssl.org/?p=openssl.git;a=commitdiff;h=77c77f0a1b9f15b869ca3342186dfbedd1119d0e
Multiblock corrupted pointer fix OpenSSL 1.0.2 introduced the "multiblock" performance improvement. This feature only applies on 64 bit x86 architecture platforms that support AES NI instructions. A defect in the implementation of "multiblock" can cause OpenSSL's internal write buffer to become incorrectly set to NULL when using non-blocking IO. Typically, when the user application is using a socket BIO for writing, this will only result in a failed connection. However if some other BIO is used then it is likely that a segmentation fault will be triggered, thus enabling a potential DoS attack. CVE-2015-0290 Reviewed-by: Richard Levitte <[email protected]> Reviewed-by: Andy Polyakov <[email protected]>
0
int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len) { const unsigned char *buf = buf_; int tot; unsigned int n, nw; #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK unsigned int max_send_fragment; #endif SSL3_BUFFER *wb = &(s->s3->wbuf); int i; s->rwstate = SSL_NOTHING; OPENSSL_assert(s->s3->wnum <= INT_MAX); tot = s->s3->wnum; s->s3->wnum = 0; if (SSL_in_init(s) && !s->in_handshake) { i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return -1; } } /* * ensure that if we end up with a smaller value of data to write out * than the the original len from a write which didn't complete for * non-blocking I/O and also somehow ended up avoiding the check for * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be * possible to end up with (len-tot) as a large number that will then * promptly send beyond the end of the users buffer ... so we trap and * report the error in a way the user will notice */ if (len < tot) { SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_BAD_LENGTH); return (-1); } /* * first check if there is a SSL3_BUFFER still being written out. This * will happen with non blocking IO */ if (wb->left != 0) { i = ssl3_write_pending(s, type, &buf[tot], s->s3->wpend_tot); if (i <= 0) { /* XXX should we ssl3_release_write_buffer if i<0? */ s->s3->wnum = tot; return i; } tot += i; /* this might be last fragment */ } #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK /* * Depending on platform multi-block can deliver several *times* * better performance. Downside is that it has to allocate * jumbo buffer to accomodate up to 8 records, but the * compromise is considered worthy. */ if (type == SSL3_RT_APPLICATION_DATA && len >= 4 * (int)(max_send_fragment = s->max_send_fragment) && s->compress == NULL && s->msg_callback == NULL && SSL_USE_EXPLICIT_IV(s) && EVP_CIPHER_flags(s->enc_write_ctx->cipher) & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) { unsigned char aad[13]; EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param; int packlen; /* minimize address aliasing conflicts */ if ((max_send_fragment & 0xfff) == 0) max_send_fragment -= 512; if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */ ssl3_release_write_buffer(s); packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE, max_send_fragment, NULL); if (len >= 8 * (int)max_send_fragment) packlen *= 8; else packlen *= 4; wb->buf = OPENSSL_malloc(packlen); if(!wb->buf) { SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_MALLOC_FAILURE); return -1; } wb->len = packlen; } else if (tot == len) { /* done? */ OPENSSL_free(wb->buf); /* free jumbo buffer */ wb->buf = NULL; return tot; } n = (len - tot); for (;;) { if (n < 4 * max_send_fragment) { OPENSSL_free(wb->buf); /* free jumbo buffer */ wb->buf = NULL; break; } if (s->s3->alert_dispatch) { i = s->method->ssl_dispatch_alert(s); if (i <= 0) { s->s3->wnum = tot; return i; } } if (n >= 8 * max_send_fragment) nw = max_send_fragment * (mb_param.interleave = 8); else nw = max_send_fragment * (mb_param.interleave = 4); memcpy(aad, s->s3->write_sequence, 8); aad[8] = type; aad[9] = (unsigned char)(s->version >> 8); aad[10] = (unsigned char)(s->version); aad[11] = 0; aad[12] = 0; mb_param.out = NULL; mb_param.inp = aad; mb_param.len = nw; packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_AAD, sizeof(mb_param), &mb_param); if (packlen <= 0 || packlen > (int)wb->len) { /* never happens */ OPENSSL_free(wb->buf); /* free jumbo buffer */ wb->buf = NULL; break; } mb_param.out = wb->buf; mb_param.inp = &buf[tot]; mb_param.len = nw; if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT, sizeof(mb_param), &mb_param) <= 0) return -1; s->s3->write_sequence[7] += mb_param.interleave; if (s->s3->write_sequence[7] < mb_param.interleave) { int j = 6; while (j >= 0 && (++s->s3->write_sequence[j--]) == 0) ; } wb->offset = 0; wb->left = packlen; s->s3->wpend_tot = nw; s->s3->wpend_buf = &buf[tot]; s->s3->wpend_type = type; s->s3->wpend_ret = nw; i = ssl3_write_pending(s, type, &buf[tot], nw); if (i <= 0) { if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) { OPENSSL_free(wb->buf); wb->buf = NULL; } s->s3->wnum = tot; return i; } if (i == (int)n) { OPENSSL_free(wb->buf); /* free jumbo buffer */ wb->buf = NULL; return tot + i; } n -= i; tot += i; } } else #endif if (tot == len) { /* done? */ if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s)) ssl3_release_write_buffer(s); return tot; } n = (len - tot); for (;;) { if (n > s->max_send_fragment) nw = s->max_send_fragment; else nw = n; i = do_ssl3_write(s, type, &(buf[tot]), nw, 0); if (i <= 0) { /* XXX should we ssl3_release_write_buffer if i<0? */ s->s3->wnum = tot; return i; } if ((i == (int)n) || (type == SSL3_RT_APPLICATION_DATA && (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) { /* * next chunk of data should get another prepended empty fragment * in ciphersuites with known-IV weakness: */ s->s3->empty_fragment_done = 0; if ((i == (int)n) && s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s)) ssl3_release_write_buffer(s); return tot + i; } n -= i; tot += i; } }
174,321,787,959,227,960,000,000,000,000,000,000,000
None
null
[ "CWE-17" ]
CVE-2015-0290
The multi-block feature in the ssl3_write_bytes function in s3_pkt.c in OpenSSL 1.0.2 before 1.0.2a on 64-bit x86 platforms with AES NI support does not properly handle certain non-blocking I/O cases, which allows remote attackers to cause a denial of service (pointer corruption and application crash) via unspecified vectors.
https://nvd.nist.gov/vuln/detail/CVE-2015-0290
154
openssl
b717b083073b6cacc0a5e2397b661678aff7ae7f
https://github.com/openssl/openssl
https://git.openssl.org/?p=openssl.git;a=commitdiff;h=b717b083073b6cacc0a5e2397b661678aff7ae7f
Free up ADB and CHOICE if already initialised. CVE-2015-0287 Reviewed-by: Tim Hudson <[email protected]> Reviewed-by: Emilia Käsper <[email protected]>
1
int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_ITEM *it, int tag, int aclass, char opt, ASN1_TLC *ctx) { const ASN1_TEMPLATE *tt, *errtt = NULL; const ASN1_COMPAT_FUNCS *cf; const ASN1_EXTERN_FUNCS *ef; const ASN1_AUX *aux = it->funcs; ASN1_aux_cb *asn1_cb; const unsigned char *p = NULL, *q; unsigned char *wp = NULL; /* BIG FAT WARNING! BREAKS CONST WHERE USED */ unsigned char imphack = 0, oclass; char seq_eoc, seq_nolen, cst, isopt; long tmplen; int i; int otag; int ret = 0; ASN1_VALUE **pchptr, *ptmpval; if (!pval) return 0; if (aux && aux->asn1_cb) asn1_cb = aux->asn1_cb; else asn1_cb = 0; switch (it->itype) { case ASN1_ITYPE_PRIMITIVE: if (it->templates) { /* * tagging or OPTIONAL is currently illegal on an item template * because the flags can't get passed down. In practice this * isn't a problem: we include the relevant flags from the item * template in the template itself. */ if ((tag != -1) || opt) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE); goto err; } return asn1_template_ex_d2i(pval, in, len, it->templates, opt, ctx); } return asn1_d2i_ex_primitive(pval, in, len, it, tag, aclass, opt, ctx); break; case ASN1_ITYPE_MSTRING: p = *in; /* Just read in tag and class */ ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, NULL, &p, len, -1, 0, 1, ctx); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } /* Must be UNIVERSAL class */ if (oclass != V_ASN1_UNIVERSAL) { /* If OPTIONAL, assume this is OK */ if (opt) return -1; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_NOT_UNIVERSAL); goto err; } /* Check tag matches bit map */ if (!(ASN1_tag2bit(otag) & it->utype)) { /* If OPTIONAL, assume this is OK */ if (opt) return -1; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_WRONG_TAG); goto err; } return asn1_d2i_ex_primitive(pval, in, len, it, otag, 0, 0, ctx); case ASN1_ITYPE_EXTERN: /* Use new style d2i */ ef = it->funcs; return ef->asn1_ex_d2i(pval, in, len, it, tag, aclass, opt, ctx); case ASN1_ITYPE_COMPAT: /* we must resort to old style evil hackery */ cf = it->funcs; /* If OPTIONAL see if it is there */ if (opt) { int exptag; p = *in; if (tag == -1) exptag = it->utype; else exptag = tag; /* * Don't care about anything other than presence of expected tag */ ret = asn1_check_tlen(NULL, NULL, NULL, NULL, NULL, &p, len, exptag, aclass, 1, ctx); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } if (ret == -1) return -1; } /* * This is the old style evil hack IMPLICIT handling: since the * underlying code is expecting a tag and class other than the one * present we change the buffer temporarily then change it back * afterwards. This doesn't and never did work for tags > 30. Yes * this is *horrible* but it is only needed for old style d2i which * will hopefully not be around for much longer. FIXME: should copy * the buffer then modify it so the input buffer can be const: we * should *always* copy because the old style d2i might modify the * buffer. */ if (tag != -1) { wp = *(unsigned char **)in; imphack = *wp; if (p == NULL) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } *wp = (unsigned char)((*p & V_ASN1_CONSTRUCTED) | it->utype); } ptmpval = cf->asn1_d2i(pval, in, len); if (tag != -1) *wp = imphack; if (ptmpval) return 1; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; case ASN1_ITYPE_CHOICE: if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL)) goto auxerr; /* Allocate structure */ if (!*pval && !ASN1_item_ex_new(pval, it)) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, ctx); /* If field not present, try the next one */ if (ret == -1) continue; /* If positive return, read OK, break loop */ if (ret > 0) break; /* Otherwise must be an ASN1 parsing error */ errtt = tt; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } /* Did we fall off the end without reading anything? */ if (i == it->tcount) { /* If OPTIONAL, this is OK */ if (opt) { /* Free and zero it */ ASN1_item_ex_free(pval, it); return -1; } ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_NO_MATCHING_CHOICE_TYPE); goto err; } asn1_set_choice_selector(pval, i, it); *in = p; if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL)) goto auxerr; return 1; case ASN1_ITYPE_NDEF_SEQUENCE: case ASN1_ITYPE_SEQUENCE: p = *in; tmplen = len; /* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */ if (tag == -1) { tag = V_ASN1_SEQUENCE; aclass = V_ASN1_UNIVERSAL; } /* Get SEQUENCE length and update len, p */ ret = asn1_check_tlen(&len, NULL, NULL, &seq_eoc, &cst, &p, len, tag, aclass, opt, ctx); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } else if (ret == -1) return -1; if (aux && (aux->flags & ASN1_AFLG_BROKEN)) { len = tmplen - (p - *in); seq_nolen = 1; } /* If indefinite we don't do a length check */ else seq_nolen = seq_eoc; if (!cst) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_NOT_CONSTRUCTED); goto err; } if (!*pval && !ASN1_item_ex_new(pval, it)) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL)) goto auxerr; /* Get each field entry */ for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) { const ASN1_TEMPLATE *seqtt; ASN1_VALUE **pseqval; if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL)) goto auxerr; /* Get each field entry */ for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) { const ASN1_TEMPLATE *seqtt; } /* * This determines the OPTIONAL flag value. The field cannot be * omitted if it is the last of a SEQUENCE and there is still * data to be read. This isn't strictly necessary but it * increases efficiency in some cases. */ if (i == (it->tcount - 1)) isopt = 0; else isopt = (char)(seqtt->flags & ASN1_TFLG_OPTIONAL); /* * attempt to read in field, allowing each to be OPTIONAL */ ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, ctx); if (!ret) { errtt = seqtt; goto err; } else if (ret == -1) { /* * OPTIONAL component absent. Free and zero the field. */ ASN1_template_free(pseqval, seqtt); continue; } /* Update length */ len -= p - q; } /* Check for EOC if expecting one */ if (seq_eoc && !asn1_check_eoc(&p, len)) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MISSING_EOC); goto err; } /* Check all data read */ if (!seq_nolen && len) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_LENGTH_MISMATCH); goto err; } /* * If we get here we've got no more data in the SEQUENCE, however we * may not have read all fields so check all remaining are OPTIONAL * and clear any that are. */ for (; i < it->tcount; tt++, i++) { const ASN1_TEMPLATE *seqtt; seqtt = asn1_do_adb(pval, tt, 1); if (!seqtt) goto err; if (seqtt->flags & ASN1_TFLG_OPTIONAL) { ASN1_VALUE **pseqval; pseqval = asn1_get_field_ptr(pval, seqtt); ASN1_template_free(pseqval, seqtt); } else { errtt = seqtt; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_FIELD_MISSING); goto err; } } /* Save encoding */ if (!asn1_enc_save(pval, *in, p - *in, it)) goto auxerr; *in = p; if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL)) goto auxerr; return 1; default: return 0; }
71,024,901,693,981,680,000,000,000,000,000,000,000
None
null
[ "CWE-17" ]
CVE-2015-0287
The ASN1_item_ex_d2i function in crypto/asn1/tasn_dec.c in OpenSSL before 0.9.8zf, 1.0.0 before 1.0.0r, 1.0.1 before 1.0.1m, and 1.0.2 before 1.0.2a does not reinitialize CHOICE and ADB data structures, which might allow attackers to cause a denial of service (invalid write operation and memory corruption) by leveraging an application that relies on ASN.1 structure reuse.
https://nvd.nist.gov/vuln/detail/CVE-2015-0287
158,015
openssl
b717b083073b6cacc0a5e2397b661678aff7ae7f
https://github.com/openssl/openssl
https://git.openssl.org/?p=openssl.git;a=commitdiff;h=b717b083073b6cacc0a5e2397b661678aff7ae7f
Free up ADB and CHOICE if already initialised. CVE-2015-0287 Reviewed-by: Tim Hudson <[email protected]> Reviewed-by: Emilia Käsper <[email protected]>
0
int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_ITEM *it, int tag, int aclass, char opt, ASN1_TLC *ctx) { const ASN1_TEMPLATE *tt, *errtt = NULL; const ASN1_COMPAT_FUNCS *cf; const ASN1_EXTERN_FUNCS *ef; const ASN1_AUX *aux = it->funcs; ASN1_aux_cb *asn1_cb; const unsigned char *p = NULL, *q; unsigned char *wp = NULL; /* BIG FAT WARNING! BREAKS CONST WHERE USED */ unsigned char imphack = 0, oclass; char seq_eoc, seq_nolen, cst, isopt; long tmplen; int i; int otag; int ret = 0; ASN1_VALUE **pchptr, *ptmpval; if (!pval) return 0; if (aux && aux->asn1_cb) asn1_cb = aux->asn1_cb; else asn1_cb = 0; switch (it->itype) { case ASN1_ITYPE_PRIMITIVE: if (it->templates) { /* * tagging or OPTIONAL is currently illegal on an item template * because the flags can't get passed down. In practice this * isn't a problem: we include the relevant flags from the item * template in the template itself. */ if ((tag != -1) || opt) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE); goto err; } return asn1_template_ex_d2i(pval, in, len, it->templates, opt, ctx); } return asn1_d2i_ex_primitive(pval, in, len, it, tag, aclass, opt, ctx); break; case ASN1_ITYPE_MSTRING: p = *in; /* Just read in tag and class */ ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, NULL, &p, len, -1, 0, 1, ctx); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } /* Must be UNIVERSAL class */ if (oclass != V_ASN1_UNIVERSAL) { /* If OPTIONAL, assume this is OK */ if (opt) return -1; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_NOT_UNIVERSAL); goto err; } /* Check tag matches bit map */ if (!(ASN1_tag2bit(otag) & it->utype)) { /* If OPTIONAL, assume this is OK */ if (opt) return -1; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_WRONG_TAG); goto err; } return asn1_d2i_ex_primitive(pval, in, len, it, otag, 0, 0, ctx); case ASN1_ITYPE_EXTERN: /* Use new style d2i */ ef = it->funcs; return ef->asn1_ex_d2i(pval, in, len, it, tag, aclass, opt, ctx); case ASN1_ITYPE_COMPAT: /* we must resort to old style evil hackery */ cf = it->funcs; /* If OPTIONAL see if it is there */ if (opt) { int exptag; p = *in; if (tag == -1) exptag = it->utype; else exptag = tag; /* * Don't care about anything other than presence of expected tag */ ret = asn1_check_tlen(NULL, NULL, NULL, NULL, NULL, &p, len, exptag, aclass, 1, ctx); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } if (ret == -1) return -1; } /* * This is the old style evil hack IMPLICIT handling: since the * underlying code is expecting a tag and class other than the one * present we change the buffer temporarily then change it back * afterwards. This doesn't and never did work for tags > 30. Yes * this is *horrible* but it is only needed for old style d2i which * will hopefully not be around for much longer. FIXME: should copy * the buffer then modify it so the input buffer can be const: we * should *always* copy because the old style d2i might modify the * buffer. */ if (tag != -1) { wp = *(unsigned char **)in; imphack = *wp; if (p == NULL) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } *wp = (unsigned char)((*p & V_ASN1_CONSTRUCTED) | it->utype); } ptmpval = cf->asn1_d2i(pval, in, len); if (tag != -1) *wp = imphack; if (ptmpval) return 1; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; case ASN1_ITYPE_CHOICE: if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL)) goto auxerr; if (*pval) { /* Free up and zero CHOICE value if initialised */ i = asn1_get_choice_selector(pval, it); if ((i >= 0) && (i < it->tcount)) { tt = it->templates + i; pchptr = asn1_get_field_ptr(pval, tt); ASN1_template_free(pchptr, tt); asn1_set_choice_selector(pval, -1, it); } } else if (!ASN1_item_ex_new(pval, it)) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, ctx); /* If field not present, try the next one */ if (ret == -1) continue; /* If positive return, read OK, break loop */ if (ret > 0) break; /* Otherwise must be an ASN1 parsing error */ errtt = tt; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } /* Did we fall off the end without reading anything? */ if (i == it->tcount) { /* If OPTIONAL, this is OK */ if (opt) { /* Free and zero it */ ASN1_item_ex_free(pval, it); return -1; } ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_NO_MATCHING_CHOICE_TYPE); goto err; } asn1_set_choice_selector(pval, i, it); *in = p; if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL)) goto auxerr; return 1; case ASN1_ITYPE_NDEF_SEQUENCE: case ASN1_ITYPE_SEQUENCE: p = *in; tmplen = len; /* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */ if (tag == -1) { tag = V_ASN1_SEQUENCE; aclass = V_ASN1_UNIVERSAL; } /* Get SEQUENCE length and update len, p */ ret = asn1_check_tlen(&len, NULL, NULL, &seq_eoc, &cst, &p, len, tag, aclass, opt, ctx); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } else if (ret == -1) return -1; if (aux && (aux->flags & ASN1_AFLG_BROKEN)) { len = tmplen - (p - *in); seq_nolen = 1; } /* If indefinite we don't do a length check */ else seq_nolen = seq_eoc; if (!cst) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_NOT_CONSTRUCTED); goto err; } if (!*pval && !ASN1_item_ex_new(pval, it)) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL)) goto auxerr; /* Get each field entry */ for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) { const ASN1_TEMPLATE *seqtt; ASN1_VALUE **pseqval; if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL)) goto auxerr; /* Free up and zero any ADB found */ for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) { if (tt->flags & ASN1_TFLG_ADB_MASK) { const ASN1_TEMPLATE *seqtt; ASN1_VALUE **pseqval; seqtt = asn1_do_adb(pval, tt, 1); pseqval = asn1_get_field_ptr(pval, seqtt); ASN1_template_free(pseqval, seqtt); } } /* Get each field entry */ for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) { const ASN1_TEMPLATE *seqtt; } /* * This determines the OPTIONAL flag value. The field cannot be * omitted if it is the last of a SEQUENCE and there is still * data to be read. This isn't strictly necessary but it * increases efficiency in some cases. */ if (i == (it->tcount - 1)) isopt = 0; else isopt = (char)(seqtt->flags & ASN1_TFLG_OPTIONAL); /* * attempt to read in field, allowing each to be OPTIONAL */ ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, ctx); if (!ret) { errtt = seqtt; goto err; } else if (ret == -1) { /* * OPTIONAL component absent. Free and zero the field. */ ASN1_template_free(pseqval, seqtt); continue; } /* Update length */ len -= p - q; } /* Check for EOC if expecting one */ if (seq_eoc && !asn1_check_eoc(&p, len)) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MISSING_EOC); goto err; } /* Check all data read */ if (!seq_nolen && len) { ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_LENGTH_MISMATCH); goto err; } /* * If we get here we've got no more data in the SEQUENCE, however we * may not have read all fields so check all remaining are OPTIONAL * and clear any that are. */ for (; i < it->tcount; tt++, i++) { const ASN1_TEMPLATE *seqtt; seqtt = asn1_do_adb(pval, tt, 1); if (!seqtt) goto err; if (seqtt->flags & ASN1_TFLG_OPTIONAL) { ASN1_VALUE **pseqval; pseqval = asn1_get_field_ptr(pval, seqtt); ASN1_template_free(pseqval, seqtt); } else { errtt = seqtt; ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_FIELD_MISSING); goto err; } } /* Save encoding */ if (!asn1_enc_save(pval, *in, p - *in, it)) goto auxerr; *in = p; if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL)) goto auxerr; return 1; default: return 0; }
111,330,312,829,224,190,000,000,000,000,000,000,000
None
null
[ "CWE-17" ]
CVE-2015-0287
The ASN1_item_ex_d2i function in crypto/asn1/tasn_dec.c in OpenSSL before 0.9.8zf, 1.0.0 before 1.0.0r, 1.0.1 before 1.0.1m, and 1.0.2 before 1.0.2a does not reinitialize CHOICE and ADB data structures, which might allow attackers to cause a denial of service (invalid write operation and memory corruption) by leveraging an application that relies on ASN.1 structure reuse.
https://nvd.nist.gov/vuln/detail/CVE-2015-0287
155
openssl
c3c7fb07dc975dc3c9de0eddb7d8fd79fc9c67c1
https://github.com/openssl/openssl
https://git.openssl.org/?p=openssl.git;a=commitdiff;h=c3c7fb07dc975dc3c9de0eddb7d8fd79fc9c67c1
Fix ASN1_TYPE_cmp Fix segmentation violation when ASN1_TYPE_cmp is passed a boolean type. This can be triggered during certificate verification so could be a DoS attack against a client or a server enabling client authentication. CVE-2015-0286 Reviewed-by: Richard Levitte <[email protected]>
1
int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b) { int result = -1; if (!a || !b || a->type != b->type) return -1; switch (a->type) { case V_ASN1_OBJECT: result = OBJ_cmp(a->value.object, b->value.object); break; case V_ASN1_NULL: result = 0; /* They do not have content. */ break; case V_ASN1_NEG_ENUMERATED: case V_ASN1_BIT_STRING: case V_ASN1_OCTET_STRING: case V_ASN1_SEQUENCE: case V_ASN1_SET: case V_ASN1_NUMERICSTRING: case V_ASN1_PRINTABLESTRING: case V_ASN1_T61STRING: case V_ASN1_VIDEOTEXSTRING: case V_ASN1_IA5STRING: case V_ASN1_UTCTIME: case V_ASN1_GENERALIZEDTIME: case V_ASN1_GRAPHICSTRING: case V_ASN1_VISIBLESTRING: case V_ASN1_GENERALSTRING: case V_ASN1_UNIVERSALSTRING: case V_ASN1_BMPSTRING: case V_ASN1_UTF8STRING: case V_ASN1_OTHER: default: result = ASN1_STRING_cmp((ASN1_STRING *)a->value.ptr, (ASN1_STRING *)b->value.ptr); break; } return result; }
210,178,361,702,841,660,000,000,000,000,000,000,000
None
null
[ "CWE-17" ]
CVE-2015-0286
The ASN1_TYPE_cmp function in crypto/asn1/a_type.c in OpenSSL before 0.9.8zf, 1.0.0 before 1.0.0r, 1.0.1 before 1.0.1m, and 1.0.2 before 1.0.2a does not properly perform boolean-type comparisons, which allows remote attackers to cause a denial of service (invalid read operation and application crash) via a crafted X.509 certificate to an endpoint that uses the certificate-verification feature.
https://nvd.nist.gov/vuln/detail/CVE-2015-0286
158,016
openssl
c3c7fb07dc975dc3c9de0eddb7d8fd79fc9c67c1
https://github.com/openssl/openssl
https://git.openssl.org/?p=openssl.git;a=commitdiff;h=c3c7fb07dc975dc3c9de0eddb7d8fd79fc9c67c1
Fix ASN1_TYPE_cmp Fix segmentation violation when ASN1_TYPE_cmp is passed a boolean type. This can be triggered during certificate verification so could be a DoS attack against a client or a server enabling client authentication. CVE-2015-0286 Reviewed-by: Richard Levitte <[email protected]>
0
int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b) { int result = -1; if (!a || !b || a->type != b->type) return -1; switch (a->type) { case V_ASN1_OBJECT: result = OBJ_cmp(a->value.object, b->value.object); break; case V_ASN1_BOOLEAN: result = a->value.boolean - b->value.boolean; break; case V_ASN1_NULL: result = 0; /* They do not have content. */ break; case V_ASN1_NEG_ENUMERATED: case V_ASN1_BIT_STRING: case V_ASN1_OCTET_STRING: case V_ASN1_SEQUENCE: case V_ASN1_SET: case V_ASN1_NUMERICSTRING: case V_ASN1_PRINTABLESTRING: case V_ASN1_T61STRING: case V_ASN1_VIDEOTEXSTRING: case V_ASN1_IA5STRING: case V_ASN1_UTCTIME: case V_ASN1_GENERALIZEDTIME: case V_ASN1_GRAPHICSTRING: case V_ASN1_VISIBLESTRING: case V_ASN1_GENERALSTRING: case V_ASN1_UNIVERSALSTRING: case V_ASN1_BMPSTRING: case V_ASN1_UTF8STRING: case V_ASN1_OTHER: default: result = ASN1_STRING_cmp((ASN1_STRING *)a->value.ptr, (ASN1_STRING *)b->value.ptr); break; } return result; }
6,676,789,780,199,443,000,000,000,000,000,000,000
None
null
[ "CWE-17" ]
CVE-2015-0286
The ASN1_TYPE_cmp function in crypto/asn1/a_type.c in OpenSSL before 0.9.8zf, 1.0.0 before 1.0.0r, 1.0.1 before 1.0.1m, and 1.0.2 before 1.0.2a does not properly perform boolean-type comparisons, which allows remote attackers to cause a denial of service (invalid read operation and application crash) via a crafted X.509 certificate to an endpoint that uses the certificate-verification feature.
https://nvd.nist.gov/vuln/detail/CVE-2015-0286
156
openssl
e1b568dd2462f7cacf98f3d117936c34e2849a6b
https://github.com/openssl/openssl
https://git.openssl.org/gitweb/?p=openssl.git;a=commit;h=e1b568dd2462f7cacf98f3d117936c34e2849a6b
Prevent handshake with unseeded PRNG Fix security issue where under certain conditions a client can complete a handshake with an unseeded PRNG. The conditions are: - Client is on a platform where the PRNG has not been seeded, and the user has not seeded manually - A protocol specific client method version has been used (i.e. not SSL_client_methodv23) - A ciphersuite is used that does not require additional random data from the PRNG beyond the initial ClientHello client random (e.g. PSK-RC4-SHA) If the handshake succeeds then the client random that has been used will have been generated from a PRNG with insufficient entropy and therefore the output may be predictable. For example using the following command with an unseeded openssl will succeed on an unpatched platform: openssl s_client -psk 1a2b3c4d -tls1_2 -cipher PSK-RC4-SHA CVE-2015-0285 Reviewed-by: Richard Levitte <[email protected]>
1
int ssl3_client_hello(SSL *s) { unsigned char *buf; unsigned char *p, *d; int i; unsigned long l; int al = 0; #ifndef OPENSSL_NO_COMP int j; SSL_COMP *comp; #endif buf = (unsigned char *)s->init_buf->data; if (s->state == SSL3_ST_CW_CLNT_HELLO_A) { SSL_SESSION *sess = s->session; if ((sess == NULL) || (sess->ssl_version != s->version) || !sess->session_id_length || (sess->not_resumable)) { if (!ssl_get_new_session(s, 0)) goto err; } if (s->method->version == DTLS_ANY_VERSION) { /* Determine which DTLS version to use */ int options = s->options; /* If DTLS 1.2 disabled correct the version number */ if (options & SSL_OP_NO_DTLSv1_2) { if (tls1_suiteb(s)) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE); goto err; } /* * Disabling all versions is silly: return an error. */ if (options & SSL_OP_NO_DTLSv1) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_WRONG_SSL_VERSION); goto err; } /* * Update method so we don't use any DTLS 1.2 features. */ s->method = DTLSv1_client_method(); s->version = DTLS1_VERSION; } else { /* * We only support one version: update method */ if (options & SSL_OP_NO_DTLSv1) s->method = DTLSv1_2_client_method(); s->version = DTLS1_2_VERSION; } s->client_version = s->version; } /* else use the pre-loaded session */ p = s->s3->client_random; /* * for DTLS if client_random is initialized, reuse it, we are * required to use same upon reply to HelloVerify */ if (SSL_IS_DTLS(s)) { size_t idx; i = 1; for (idx = 0; idx < sizeof(s->s3->client_random); idx++) { if (p[idx]) { i = 0; break; } } } else i = 1; if (i) ssl_fill_hello_random(s, 0, p, sizeof(s->s3->client_random)); /* Do the message type and length last */ d = p = ssl_handshake_start(s); /*- * version indicates the negotiated version: for example from * an SSLv2/v3 compatible client hello). The client_version * field is the maximum version we permit and it is also * used in RSA encrypted premaster secrets. Some servers can * choke if we initially report a higher version then * renegotiate to a lower one in the premaster secret. This * didn't happen with TLS 1.0 as most servers supported it * but it can with TLS 1.1 or later if the server only supports * 1.0. * * Possible scenario with previous logic: * 1. Client hello indicates TLS 1.2 * 2. Server hello says TLS 1.0 * 3. RSA encrypted premaster secret uses 1.2. * 4. Handhaked proceeds using TLS 1.0. * 5. Server sends hello request to renegotiate. * 6. Client hello indicates TLS v1.0 as we now * know that is maximum server supports. * 7. Server chokes on RSA encrypted premaster secret * containing version 1.0. * * For interoperability it should be OK to always use the * maximum version we support in client hello and then rely * on the checking of version to ensure the servers isn't * being inconsistent: for example initially negotiating with * TLS 1.0 and renegotiating with TLS 1.2. We do this by using * client_version in client hello and not resetting it to * the negotiated version. */ *(p++) = s->client_version >> 8; *(p++) = s->client_version & 0xff; /* Random stuff */ memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE); p += SSL3_RANDOM_SIZE; /* Session ID */ if (s->new_session) i = 0; else i = s->session->session_id_length; *(p++) = i; if (i != 0) { if (i > (int)sizeof(s->session->session_id)) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } memcpy(p, s->session->session_id, i); p += i; } /* cookie stuff for DTLS */ if (SSL_IS_DTLS(s)) { if (s->d1->cookie_len > sizeof(s->d1->cookie)) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } *(p++) = s->d1->cookie_len; memcpy(p, s->d1->cookie, s->d1->cookie_len); p += s->d1->cookie_len; } /* Ciphers supported */ i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &(p[2]), 0); if (i == 0) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_NO_CIPHERS_AVAILABLE); goto err; } #ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH /* * Some servers hang if client hello > 256 bytes as hack workaround * chop number of supported ciphers to keep it well below this if we * use TLS v1.2 */ if (TLS1_get_version(s) >= TLS1_2_VERSION && i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH) i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1; #endif s2n(i, p); p += i; /* COMPRESSION */ #ifdef OPENSSL_NO_COMP *(p++) = 1; #else if (!ssl_allow_compression(s) || !s->ctx->comp_methods) j = 0; else j = sk_SSL_COMP_num(s->ctx->comp_methods); *(p++) = 1 + j; for (i = 0; i < j; i++) { comp = sk_SSL_COMP_value(s->ctx->comp_methods, i); *(p++) = comp->id; } #endif *(p++) = 0; /* Add the NULL method */ #ifndef OPENSSL_NO_TLSEXT /* TLS extensions */ if (ssl_prepare_clienthello_tlsext(s) <= 0) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); goto err; } if ((p = ssl_add_clienthello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH, &al)) == NULL) { ssl3_send_alert(s, SSL3_AL_FATAL, al); SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } #endif l = p - d; ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l); s->state = SSL3_ST_CW_CLNT_HELLO_B; } /* SSL3_ST_CW_CLNT_HELLO_B */ return ssl_do_write(s); err: return (-1); }
56,759,383,063,747,970,000,000,000,000,000,000,000
None
null
[ "CWE-310" ]
CVE-2015-0285
The ssl3_client_hello function in s3_clnt.c in OpenSSL 1.0.2 before 1.0.2a does not ensure that the PRNG is seeded before proceeding with a handshake, which makes it easier for remote attackers to defeat cryptographic protection mechanisms by sniffing the network and then conducting a brute-force attack.
https://nvd.nist.gov/vuln/detail/CVE-2015-0285
158,017
openssl
e1b568dd2462f7cacf98f3d117936c34e2849a6b
https://github.com/openssl/openssl
https://git.openssl.org/gitweb/?p=openssl.git;a=commit;h=e1b568dd2462f7cacf98f3d117936c34e2849a6b
Prevent handshake with unseeded PRNG Fix security issue where under certain conditions a client can complete a handshake with an unseeded PRNG. The conditions are: - Client is on a platform where the PRNG has not been seeded, and the user has not seeded manually - A protocol specific client method version has been used (i.e. not SSL_client_methodv23) - A ciphersuite is used that does not require additional random data from the PRNG beyond the initial ClientHello client random (e.g. PSK-RC4-SHA) If the handshake succeeds then the client random that has been used will have been generated from a PRNG with insufficient entropy and therefore the output may be predictable. For example using the following command with an unseeded openssl will succeed on an unpatched platform: openssl s_client -psk 1a2b3c4d -tls1_2 -cipher PSK-RC4-SHA CVE-2015-0285 Reviewed-by: Richard Levitte <[email protected]>
0
int ssl3_client_hello(SSL *s) { unsigned char *buf; unsigned char *p, *d; int i; unsigned long l; int al = 0; #ifndef OPENSSL_NO_COMP int j; SSL_COMP *comp; #endif buf = (unsigned char *)s->init_buf->data; if (s->state == SSL3_ST_CW_CLNT_HELLO_A) { SSL_SESSION *sess = s->session; if ((sess == NULL) || (sess->ssl_version != s->version) || !sess->session_id_length || (sess->not_resumable)) { if (!ssl_get_new_session(s, 0)) goto err; } if (s->method->version == DTLS_ANY_VERSION) { /* Determine which DTLS version to use */ int options = s->options; /* If DTLS 1.2 disabled correct the version number */ if (options & SSL_OP_NO_DTLSv1_2) { if (tls1_suiteb(s)) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE); goto err; } /* * Disabling all versions is silly: return an error. */ if (options & SSL_OP_NO_DTLSv1) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_WRONG_SSL_VERSION); goto err; } /* * Update method so we don't use any DTLS 1.2 features. */ s->method = DTLSv1_client_method(); s->version = DTLS1_VERSION; } else { /* * We only support one version: update method */ if (options & SSL_OP_NO_DTLSv1) s->method = DTLSv1_2_client_method(); s->version = DTLS1_2_VERSION; } s->client_version = s->version; } /* else use the pre-loaded session */ p = s->s3->client_random; /* * for DTLS if client_random is initialized, reuse it, we are * required to use same upon reply to HelloVerify */ if (SSL_IS_DTLS(s)) { size_t idx; i = 1; for (idx = 0; idx < sizeof(s->s3->client_random); idx++) { if (p[idx]) { i = 0; break; } } } else i = 1; if (i && ssl_fill_hello_random(s, 0, p, sizeof(s->s3->client_random)) <= 0) goto err; /* Do the message type and length last */ d = p = ssl_handshake_start(s); /*- * version indicates the negotiated version: for example from * an SSLv2/v3 compatible client hello). The client_version * field is the maximum version we permit and it is also * used in RSA encrypted premaster secrets. Some servers can * choke if we initially report a higher version then * renegotiate to a lower one in the premaster secret. This * didn't happen with TLS 1.0 as most servers supported it * but it can with TLS 1.1 or later if the server only supports * 1.0. * * Possible scenario with previous logic: * 1. Client hello indicates TLS 1.2 * 2. Server hello says TLS 1.0 * 3. RSA encrypted premaster secret uses 1.2. * 4. Handhaked proceeds using TLS 1.0. * 5. Server sends hello request to renegotiate. * 6. Client hello indicates TLS v1.0 as we now * know that is maximum server supports. * 7. Server chokes on RSA encrypted premaster secret * containing version 1.0. * * For interoperability it should be OK to always use the * maximum version we support in client hello and then rely * on the checking of version to ensure the servers isn't * being inconsistent: for example initially negotiating with * TLS 1.0 and renegotiating with TLS 1.2. We do this by using * client_version in client hello and not resetting it to * the negotiated version. */ *(p++) = s->client_version >> 8; *(p++) = s->client_version & 0xff; /* Random stuff */ memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE); p += SSL3_RANDOM_SIZE; /* Session ID */ if (s->new_session) i = 0; else i = s->session->session_id_length; *(p++) = i; if (i != 0) { if (i > (int)sizeof(s->session->session_id)) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } memcpy(p, s->session->session_id, i); p += i; } /* cookie stuff for DTLS */ if (SSL_IS_DTLS(s)) { if (s->d1->cookie_len > sizeof(s->d1->cookie)) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } *(p++) = s->d1->cookie_len; memcpy(p, s->d1->cookie, s->d1->cookie_len); p += s->d1->cookie_len; } /* Ciphers supported */ i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &(p[2]), 0); if (i == 0) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_NO_CIPHERS_AVAILABLE); goto err; } #ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH /* * Some servers hang if client hello > 256 bytes as hack workaround * chop number of supported ciphers to keep it well below this if we * use TLS v1.2 */ if (TLS1_get_version(s) >= TLS1_2_VERSION && i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH) i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1; #endif s2n(i, p); p += i; /* COMPRESSION */ #ifdef OPENSSL_NO_COMP *(p++) = 1; #else if (!ssl_allow_compression(s) || !s->ctx->comp_methods) j = 0; else j = sk_SSL_COMP_num(s->ctx->comp_methods); *(p++) = 1 + j; for (i = 0; i < j; i++) { comp = sk_SSL_COMP_value(s->ctx->comp_methods, i); *(p++) = comp->id; } #endif *(p++) = 0; /* Add the NULL method */ #ifndef OPENSSL_NO_TLSEXT /* TLS extensions */ if (ssl_prepare_clienthello_tlsext(s) <= 0) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); goto err; } if ((p = ssl_add_clienthello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH, &al)) == NULL) { ssl3_send_alert(s, SSL3_AL_FATAL, al); SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } #endif l = p - d; ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l); s->state = SSL3_ST_CW_CLNT_HELLO_B; } /* SSL3_ST_CW_CLNT_HELLO_B */ return ssl_do_write(s); err: return (-1); }
214,124,849,989,913,120,000,000,000,000,000,000,000
None
null
[ "CWE-310" ]
CVE-2015-0285
The ssl3_client_hello function in s3_clnt.c in OpenSSL 1.0.2 before 1.0.2a does not ensure that the PRNG is seeded before proceeding with a handshake, which makes it easier for remote attackers to defeat cryptographic protection mechanisms by sniffing the network and then conducting a brute-force attack.
https://nvd.nist.gov/vuln/detail/CVE-2015-0285
159
lxde
bc8c3d871e9ecc67c47ff002b68cf049793faf08
https://git.lxde.org/gitweb/?p=lxde/pcmanfm
https://git.lxde.org/gitweb/?p=lxde/pcmanfm.git;a=commit;h=bc8c3d871e9ecc67c47ff002b68cf049793faf08
None
1
static void get_socket_name(SingleInstData* data, char* buf, int len) { const char* dpy = g_getenv("DISPLAY"); char* host = NULL; int dpynum; if(dpy) { const char* p = strrchr(dpy, ':'); host = g_strndup(dpy, (p - dpy)); dpynum = atoi(p + 1); } else dpynum = 0; g_snprintf(buf, len, "%s/.%s-socket-%s-%d-%s", g_get_tmp_dir(), data->prog_name, host ? host : "", dpynum, g_get_user_name()); }
106,918,102,879,333,300,000,000,000,000,000,000,000
None
null
[ "CWE-20" ]
CVE-2017-8934
PCManFM 1.2.5 insecurely uses /tmp for a socket file, allowing a local user to cause a denial of service (application unavailability).
https://nvd.nist.gov/vuln/detail/CVE-2017-8934
158,020
lxde
bc8c3d871e9ecc67c47ff002b68cf049793faf08
https://git.lxde.org/gitweb/?p=lxde/pcmanfm
https://git.lxde.org/gitweb/?p=lxde/pcmanfm.git;a=commit;h=bc8c3d871e9ecc67c47ff002b68cf049793faf08
None
0
static void get_socket_name(SingleInstData* data, char* buf, int len) { const char* dpy = g_getenv("DISPLAY"); char* host = NULL; int dpynum; if(dpy) { const char* p = strrchr(dpy, ':'); host = g_strndup(dpy, (p - dpy)); dpynum = atoi(p + 1); } else dpynum = 0; #if GLIB_CHECK_VERSION(2, 28, 0) g_snprintf(buf, len, "%s/%s-socket-%s-%d", g_get_user_runtime_dir(), data->prog_name, host ? host : "", dpynum); #else g_snprintf(buf, len, "%s/.%s-socket-%s-%d-%s", g_get_tmp_dir(), data->prog_name, host ? host : "", dpynum, g_get_user_name()); #endif }
331,737,708,862,764,430,000,000,000,000,000,000,000
None
null
[ "CWE-20" ]
CVE-2017-8934
PCManFM 1.2.5 insecurely uses /tmp for a socket file, allowing a local user to cause a denial of service (application unavailability).
https://nvd.nist.gov/vuln/detail/CVE-2017-8934
165
savannah
7f2e4f4f553f6836be7683f66226afac3fa979b8
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=7f2e4f4f553f6836be7683f66226afac3fa979b8
None
1
_bdf_parse_glyphs( char* line, unsigned long linelen, unsigned long lineno, void* call_data, void* client_data ) { int c, mask_index; char* s; unsigned char* bp; unsigned long i, slen, nibbles; _bdf_parse_t* p; bdf_glyph_t* glyph; bdf_font_t* font; FT_Memory memory; FT_Error error = BDF_Err_Ok; FT_UNUSED( call_data ); FT_UNUSED( lineno ); /* only used in debug mode */ p = (_bdf_parse_t *)client_data; font = p->font; memory = font->memory; /* Check for a comment. */ if ( ft_memcmp( line, "COMMENT", 7 ) == 0 ) { linelen -= 7; s = line + 7; if ( *s != 0 ) { s++; linelen--; } error = _bdf_add_comment( p->font, s, linelen ); goto Exit; } /* The very first thing expected is the number of glyphs. */ if ( !( p->flags & _BDF_GLYPHS ) ) { if ( ft_memcmp( line, "CHARS", 5 ) != 0 ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "CHARS" )); error = BDF_Err_Missing_Chars_Field; goto Exit; } error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; p->cnt = font->glyphs_size = _bdf_atoul( p->list.field[1], 0, 10 ); /* Make sure the number of glyphs is non-zero. */ if ( p->cnt == 0 ) font->glyphs_size = 64; /* Limit ourselves to 1,114,112 glyphs in the font (this is the */ /* number of code points available in Unicode). */ if ( p->cnt >= 0x110000UL ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "CHARS" )); error = BDF_Err_Invalid_Argument; goto Exit; } if ( FT_NEW_ARRAY( font->glyphs, font->glyphs_size ) ) goto Exit; p->flags |= _BDF_GLYPHS; goto Exit; } /* Check for the ENDFONT field. */ if ( ft_memcmp( line, "ENDFONT", 7 ) == 0 ) { /* Sort the glyphs by encoding. */ ft_qsort( (char *)font->glyphs, font->glyphs_used, sizeof ( bdf_glyph_t ), by_encoding ); p->flags &= ~_BDF_START; goto Exit; } /* Check for the ENDCHAR field. */ if ( ft_memcmp( line, "ENDCHAR", 7 ) == 0 ) { p->glyph_enc = 0; p->flags &= ~_BDF_GLYPH_BITS; goto Exit; } /* Check whether a glyph is being scanned but should be */ /* ignored because it is an unencoded glyph. */ if ( ( p->flags & _BDF_GLYPH ) && p->glyph_enc == -1 && p->opts->keep_unencoded == 0 ) goto Exit; /* Check for the STARTCHAR field. */ if ( ft_memcmp( line, "STARTCHAR", 9 ) == 0 ) { /* Set the character name in the parse info first until the */ /* encoding can be checked for an unencoded character. */ FT_FREE( p->glyph_name ); error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; _bdf_list_shift( &p->list, 1 ); s = _bdf_list_join( &p->list, ' ', &slen ); if ( !s ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG8, lineno, "STARTCHAR" )); error = BDF_Err_Invalid_File_Format; goto Exit; } if ( FT_NEW_ARRAY( p->glyph_name, slen + 1 ) ) goto Exit; FT_MEM_COPY( p->glyph_name, s, slen + 1 ); p->flags |= _BDF_GLYPH; FT_TRACE4(( DBGMSG1, lineno, s )); goto Exit; } /* Check for the ENCODING field. */ if ( ft_memcmp( line, "ENCODING", 8 ) == 0 ) { if ( !( p->flags & _BDF_GLYPH ) ) { /* Missing STARTCHAR field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "STARTCHAR" )); error = BDF_Err_Missing_Startchar_Field; goto Exit; } error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; p->glyph_enc = _bdf_atol( p->list.field[1], 0, 10 ); /* Normalize negative encoding values. The specification only */ /* allows -1, but we can be more generous here. */ if ( p->glyph_enc < -1 ) p->glyph_enc = -1; /* Check for alternative encoding format. */ if ( p->glyph_enc == -1 && p->list.used > 2 ) p->glyph_enc = _bdf_atol( p->list.field[2], 0, 10 ); FT_TRACE4(( DBGMSG2, p->glyph_enc )); /* Check that the encoding is in the Unicode range because */ sizeof ( unsigned long ) * 32 ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "ENCODING" )); error = BDF_Err_Invalid_File_Format; goto Exit; } /* Check whether this encoding has already been encountered. */ /* If it has then change it to unencoded so it gets added if */ /* indicated. */ if ( p->glyph_enc >= 0 ) { if ( _bdf_glyph_modified( p->have, p->glyph_enc ) ) { /* Emit a message saying a glyph has been moved to the */ /* unencoded area. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG12, p->glyph_enc, p->glyph_name )); p->glyph_enc = -1; font->modified = 1; } else _bdf_set_glyph_modified( p->have, p->glyph_enc ); } if ( p->glyph_enc >= 0 ) { /* Make sure there are enough glyphs allocated in case the */ /* number of characters happen to be wrong. */ if ( font->glyphs_used == font->glyphs_size ) { if ( FT_RENEW_ARRAY( font->glyphs, font->glyphs_size, font->glyphs_size + 64 ) ) goto Exit; font->glyphs_size += 64; } glyph = font->glyphs + font->glyphs_used++; glyph->name = p->glyph_name; glyph->encoding = p->glyph_enc; /* Reset the initial glyph info. */ p->glyph_name = 0; } else { /* Unencoded glyph. Check whether it should */ /* be added or not. */ if ( p->opts->keep_unencoded != 0 ) { /* Allocate the next unencoded glyph. */ if ( font->unencoded_used == font->unencoded_size ) { if ( FT_RENEW_ARRAY( font->unencoded , font->unencoded_size, font->unencoded_size + 4 ) ) goto Exit; font->unencoded_size += 4; } glyph = font->unencoded + font->unencoded_used; glyph->name = p->glyph_name; glyph->encoding = font->unencoded_used++; } else /* Free up the glyph name if the unencoded shouldn't be */ /* kept. */ FT_FREE( p->glyph_name ); p->glyph_name = 0; } /* Clear the flags that might be added when width and height are */ /* checked for consistency. */ p->flags &= ~( _BDF_GLYPH_WIDTH_CHECK | _BDF_GLYPH_HEIGHT_CHECK ); p->flags |= _BDF_ENCODING; goto Exit; } /* Point at the glyph being constructed. */ if ( p->glyph_enc == -1 ) glyph = font->unencoded + ( font->unencoded_used - 1 ); else glyph = font->glyphs + ( font->glyphs_used - 1 ); /* Check whether a bitmap is being constructed. */ if ( p->flags & _BDF_BITMAP ) { /* If there are more rows than are specified in the glyph metrics, */ /* ignore the remaining lines. */ if ( p->row >= (unsigned long)glyph->bbx.height ) { if ( !( p->flags & _BDF_GLYPH_HEIGHT_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG13, glyph->encoding )); p->flags |= _BDF_GLYPH_HEIGHT_CHECK; font->modified = 1; } goto Exit; } /* Only collect the number of nibbles indicated by the glyph */ /* metrics. If there are more columns, they are simply ignored. */ nibbles = glyph->bpr << 1; bp = glyph->bitmap + p->row * glyph->bpr; for ( i = 0; i < nibbles; i++ ) { c = line[i]; if ( !sbitset( hdigits, c ) ) break; *bp = (FT_Byte)( ( *bp << 4 ) + a2i[c] ); if ( i + 1 < nibbles && ( i & 1 ) ) *++bp = 0; } /* If any line has not enough columns, */ /* indicate they have been padded with zero bits. */ if ( i < nibbles && !( p->flags & _BDF_GLYPH_WIDTH_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG16, glyph->encoding )); p->flags |= _BDF_GLYPH_WIDTH_CHECK; font->modified = 1; } /* Remove possible garbage at the right. */ mask_index = ( glyph->bbx.width * p->font->bpp ) & 7; if ( glyph->bbx.width ) *bp &= nibble_mask[mask_index]; /* If any line has extra columns, indicate they have been removed. */ if ( i == nibbles && sbitset( hdigits, line[nibbles] ) && !( p->flags & _BDF_GLYPH_WIDTH_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG14, glyph->encoding )); p->flags |= _BDF_GLYPH_WIDTH_CHECK; font->modified = 1; } p->row++; goto Exit; } /* Expect the SWIDTH (scalable width) field next. */ if ( ft_memcmp( line, "SWIDTH", 6 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->swidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 ); p->flags |= _BDF_SWIDTH; goto Exit; } /* Expect the DWIDTH (scalable width) field next. */ if ( ft_memcmp( line, "DWIDTH", 6 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->dwidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 ); if ( !( p->flags & _BDF_SWIDTH ) ) { /* Missing SWIDTH field. Emit an auto correction message and set */ /* the scalable width from the device width. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG9, lineno )); glyph->swidth = (unsigned short)FT_MulDiv( glyph->dwidth, 72000L, (FT_Long)( font->point_size * font->resolution_x ) ); } p->flags |= _BDF_DWIDTH; goto Exit; } /* Expect the BBX field next. */ if ( ft_memcmp( line, "BBX", 3 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->bbx.width = _bdf_atos( p->list.field[1], 0, 10 ); glyph->bbx.height = _bdf_atos( p->list.field[2], 0, 10 ); glyph->bbx.x_offset = _bdf_atos( p->list.field[3], 0, 10 ); glyph->bbx.y_offset = _bdf_atos( p->list.field[4], 0, 10 ); /* Generate the ascent and descent of the character. */ glyph->bbx.ascent = (short)( glyph->bbx.height + glyph->bbx.y_offset ); glyph->bbx.descent = (short)( -glyph->bbx.y_offset ); /* Determine the overall font bounding box as the characters are */ /* loaded so corrections can be done later if indicated. */ p->maxas = (short)FT_MAX( glyph->bbx.ascent, p->maxas ); p->maxds = (short)FT_MAX( glyph->bbx.descent, p->maxds ); p->rbearing = (short)( glyph->bbx.width + glyph->bbx.x_offset ); p->maxrb = (short)FT_MAX( p->rbearing, p->maxrb ); p->minlb = (short)FT_MIN( glyph->bbx.x_offset, p->minlb ); p->maxlb = (short)FT_MAX( glyph->bbx.x_offset, p->maxlb ); if ( !( p->flags & _BDF_DWIDTH ) ) { /* Missing DWIDTH field. Emit an auto correction message and set */ /* the device width to the glyph width. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG10, lineno )); glyph->dwidth = glyph->bbx.width; } /* If the BDF_CORRECT_METRICS flag is set, then adjust the SWIDTH */ /* value if necessary. */ if ( p->opts->correct_metrics != 0 ) { /* Determine the point size of the glyph. */ unsigned short sw = (unsigned short)FT_MulDiv( glyph->dwidth, 72000L, (FT_Long)( font->point_size * font->resolution_x ) ); if ( sw != glyph->swidth ) { glyph->swidth = sw; if ( p->glyph_enc == -1 ) _bdf_set_glyph_modified( font->umod, font->unencoded_used - 1 ); else _bdf_set_glyph_modified( font->nmod, glyph->encoding ); p->flags |= _BDF_SWIDTH_ADJ; font->modified = 1; } } p->flags |= _BDF_BBX; goto Exit; } /* And finally, gather up the bitmap. */ if ( ft_memcmp( line, "BITMAP", 6 ) == 0 ) { unsigned long bitmap_size; if ( !( p->flags & _BDF_BBX ) ) { /* Missing BBX field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "BBX" )); error = BDF_Err_Missing_Bbx_Field; goto Exit; } /* Allocate enough space for the bitmap. */ glyph->bpr = ( glyph->bbx.width * p->font->bpp + 7 ) >> 3; bitmap_size = glyph->bpr * glyph->bbx.height; if ( glyph->bpr > 0xFFFFU || bitmap_size > 0xFFFFU ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG4, lineno )); error = BDF_Err_Bbx_Too_Big; goto Exit; } else glyph->bytes = (unsigned short)bitmap_size; if ( FT_NEW_ARRAY( glyph->bitmap, glyph->bytes ) ) goto Exit; p->row = 0; p->flags |= _BDF_BITMAP; goto Exit; } FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG9, lineno )); error = BDF_Err_Invalid_File_Format; goto Exit; Missing_Encoding: /* Missing ENCODING field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "ENCODING" )); error = BDF_Err_Missing_Encoding_Field; Exit: if ( error && ( p->flags & _BDF_GLYPH ) ) FT_FREE( p->glyph_name ); return error; }
241,612,252,320,932,160,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2012-5670
The _bdf_parse_glyphs function in FreeType before 2.4.11 allows context-dependent attackers to cause a denial of service (out-of-bounds write and crash) via vectors related to BDF fonts and an ENCODING field with a negative value.
https://nvd.nist.gov/vuln/detail/CVE-2012-5670
158,025
savannah
7f2e4f4f553f6836be7683f66226afac3fa979b8
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=7f2e4f4f553f6836be7683f66226afac3fa979b8
None
0
_bdf_parse_glyphs( char* line, unsigned long linelen, unsigned long lineno, void* call_data, void* client_data ) { int c, mask_index; char* s; unsigned char* bp; unsigned long i, slen, nibbles; _bdf_parse_t* p; bdf_glyph_t* glyph; bdf_font_t* font; FT_Memory memory; FT_Error error = BDF_Err_Ok; FT_UNUSED( call_data ); FT_UNUSED( lineno ); /* only used in debug mode */ p = (_bdf_parse_t *)client_data; font = p->font; memory = font->memory; /* Check for a comment. */ if ( ft_memcmp( line, "COMMENT", 7 ) == 0 ) { linelen -= 7; s = line + 7; if ( *s != 0 ) { s++; linelen--; } error = _bdf_add_comment( p->font, s, linelen ); goto Exit; } /* The very first thing expected is the number of glyphs. */ if ( !( p->flags & _BDF_GLYPHS ) ) { if ( ft_memcmp( line, "CHARS", 5 ) != 0 ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "CHARS" )); error = BDF_Err_Missing_Chars_Field; goto Exit; } error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; p->cnt = font->glyphs_size = _bdf_atoul( p->list.field[1], 0, 10 ); /* Make sure the number of glyphs is non-zero. */ if ( p->cnt == 0 ) font->glyphs_size = 64; /* Limit ourselves to 1,114,112 glyphs in the font (this is the */ /* number of code points available in Unicode). */ if ( p->cnt >= 0x110000UL ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "CHARS" )); error = BDF_Err_Invalid_Argument; goto Exit; } if ( FT_NEW_ARRAY( font->glyphs, font->glyphs_size ) ) goto Exit; p->flags |= _BDF_GLYPHS; goto Exit; } /* Check for the ENDFONT field. */ if ( ft_memcmp( line, "ENDFONT", 7 ) == 0 ) { /* Sort the glyphs by encoding. */ ft_qsort( (char *)font->glyphs, font->glyphs_used, sizeof ( bdf_glyph_t ), by_encoding ); p->flags &= ~_BDF_START; goto Exit; } /* Check for the ENDCHAR field. */ if ( ft_memcmp( line, "ENDCHAR", 7 ) == 0 ) { p->glyph_enc = 0; p->flags &= ~_BDF_GLYPH_BITS; goto Exit; } /* Check whether a glyph is being scanned but should be */ /* ignored because it is an unencoded glyph. */ if ( ( p->flags & _BDF_GLYPH ) && p->glyph_enc == -1 && p->opts->keep_unencoded == 0 ) goto Exit; /* Check for the STARTCHAR field. */ if ( ft_memcmp( line, "STARTCHAR", 9 ) == 0 ) { /* Set the character name in the parse info first until the */ /* encoding can be checked for an unencoded character. */ FT_FREE( p->glyph_name ); error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; _bdf_list_shift( &p->list, 1 ); s = _bdf_list_join( &p->list, ' ', &slen ); if ( !s ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG8, lineno, "STARTCHAR" )); error = BDF_Err_Invalid_File_Format; goto Exit; } if ( FT_NEW_ARRAY( p->glyph_name, slen + 1 ) ) goto Exit; FT_MEM_COPY( p->glyph_name, s, slen + 1 ); p->flags |= _BDF_GLYPH; FT_TRACE4(( DBGMSG1, lineno, s )); goto Exit; } /* Check for the ENCODING field. */ if ( ft_memcmp( line, "ENCODING", 8 ) == 0 ) { if ( !( p->flags & _BDF_GLYPH ) ) { /* Missing STARTCHAR field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "STARTCHAR" )); error = BDF_Err_Missing_Startchar_Field; goto Exit; } error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; p->glyph_enc = _bdf_atol( p->list.field[1], 0, 10 ); /* Normalize negative encoding values. The specification only */ /* allows -1, but we can be more generous here. */ if ( p->glyph_enc < -1 ) p->glyph_enc = -1; /* Check for alternative encoding format. */ if ( p->glyph_enc == -1 && p->list.used > 2 ) p->glyph_enc = _bdf_atol( p->list.field[2], 0, 10 ); if ( p->glyph_enc < -1 ) p->glyph_enc = -1; FT_TRACE4(( DBGMSG2, p->glyph_enc )); /* Check that the encoding is in the Unicode range because */ sizeof ( unsigned long ) * 32 ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "ENCODING" )); error = BDF_Err_Invalid_File_Format; goto Exit; } /* Check whether this encoding has already been encountered. */ /* If it has then change it to unencoded so it gets added if */ /* indicated. */ if ( p->glyph_enc >= 0 ) { if ( _bdf_glyph_modified( p->have, p->glyph_enc ) ) { /* Emit a message saying a glyph has been moved to the */ /* unencoded area. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG12, p->glyph_enc, p->glyph_name )); p->glyph_enc = -1; font->modified = 1; } else _bdf_set_glyph_modified( p->have, p->glyph_enc ); } if ( p->glyph_enc >= 0 ) { /* Make sure there are enough glyphs allocated in case the */ /* number of characters happen to be wrong. */ if ( font->glyphs_used == font->glyphs_size ) { if ( FT_RENEW_ARRAY( font->glyphs, font->glyphs_size, font->glyphs_size + 64 ) ) goto Exit; font->glyphs_size += 64; } glyph = font->glyphs + font->glyphs_used++; glyph->name = p->glyph_name; glyph->encoding = p->glyph_enc; /* Reset the initial glyph info. */ p->glyph_name = 0; } else { /* Unencoded glyph. Check whether it should */ /* be added or not. */ if ( p->opts->keep_unencoded != 0 ) { /* Allocate the next unencoded glyph. */ if ( font->unencoded_used == font->unencoded_size ) { if ( FT_RENEW_ARRAY( font->unencoded , font->unencoded_size, font->unencoded_size + 4 ) ) goto Exit; font->unencoded_size += 4; } glyph = font->unencoded + font->unencoded_used; glyph->name = p->glyph_name; glyph->encoding = font->unencoded_used++; } else /* Free up the glyph name if the unencoded shouldn't be */ /* kept. */ FT_FREE( p->glyph_name ); p->glyph_name = 0; } /* Clear the flags that might be added when width and height are */ /* checked for consistency. */ p->flags &= ~( _BDF_GLYPH_WIDTH_CHECK | _BDF_GLYPH_HEIGHT_CHECK ); p->flags |= _BDF_ENCODING; goto Exit; } /* Point at the glyph being constructed. */ if ( p->glyph_enc == -1 ) glyph = font->unencoded + ( font->unencoded_used - 1 ); else glyph = font->glyphs + ( font->glyphs_used - 1 ); /* Check whether a bitmap is being constructed. */ if ( p->flags & _BDF_BITMAP ) { /* If there are more rows than are specified in the glyph metrics, */ /* ignore the remaining lines. */ if ( p->row >= (unsigned long)glyph->bbx.height ) { if ( !( p->flags & _BDF_GLYPH_HEIGHT_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG13, glyph->encoding )); p->flags |= _BDF_GLYPH_HEIGHT_CHECK; font->modified = 1; } goto Exit; } /* Only collect the number of nibbles indicated by the glyph */ /* metrics. If there are more columns, they are simply ignored. */ nibbles = glyph->bpr << 1; bp = glyph->bitmap + p->row * glyph->bpr; for ( i = 0; i < nibbles; i++ ) { c = line[i]; if ( !sbitset( hdigits, c ) ) break; *bp = (FT_Byte)( ( *bp << 4 ) + a2i[c] ); if ( i + 1 < nibbles && ( i & 1 ) ) *++bp = 0; } /* If any line has not enough columns, */ /* indicate they have been padded with zero bits. */ if ( i < nibbles && !( p->flags & _BDF_GLYPH_WIDTH_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG16, glyph->encoding )); p->flags |= _BDF_GLYPH_WIDTH_CHECK; font->modified = 1; } /* Remove possible garbage at the right. */ mask_index = ( glyph->bbx.width * p->font->bpp ) & 7; if ( glyph->bbx.width ) *bp &= nibble_mask[mask_index]; /* If any line has extra columns, indicate they have been removed. */ if ( i == nibbles && sbitset( hdigits, line[nibbles] ) && !( p->flags & _BDF_GLYPH_WIDTH_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG14, glyph->encoding )); p->flags |= _BDF_GLYPH_WIDTH_CHECK; font->modified = 1; } p->row++; goto Exit; } /* Expect the SWIDTH (scalable width) field next. */ if ( ft_memcmp( line, "SWIDTH", 6 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->swidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 ); p->flags |= _BDF_SWIDTH; goto Exit; } /* Expect the DWIDTH (scalable width) field next. */ if ( ft_memcmp( line, "DWIDTH", 6 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->dwidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 ); if ( !( p->flags & _BDF_SWIDTH ) ) { /* Missing SWIDTH field. Emit an auto correction message and set */ /* the scalable width from the device width. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG9, lineno )); glyph->swidth = (unsigned short)FT_MulDiv( glyph->dwidth, 72000L, (FT_Long)( font->point_size * font->resolution_x ) ); } p->flags |= _BDF_DWIDTH; goto Exit; } /* Expect the BBX field next. */ if ( ft_memcmp( line, "BBX", 3 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->bbx.width = _bdf_atos( p->list.field[1], 0, 10 ); glyph->bbx.height = _bdf_atos( p->list.field[2], 0, 10 ); glyph->bbx.x_offset = _bdf_atos( p->list.field[3], 0, 10 ); glyph->bbx.y_offset = _bdf_atos( p->list.field[4], 0, 10 ); /* Generate the ascent and descent of the character. */ glyph->bbx.ascent = (short)( glyph->bbx.height + glyph->bbx.y_offset ); glyph->bbx.descent = (short)( -glyph->bbx.y_offset ); /* Determine the overall font bounding box as the characters are */ /* loaded so corrections can be done later if indicated. */ p->maxas = (short)FT_MAX( glyph->bbx.ascent, p->maxas ); p->maxds = (short)FT_MAX( glyph->bbx.descent, p->maxds ); p->rbearing = (short)( glyph->bbx.width + glyph->bbx.x_offset ); p->maxrb = (short)FT_MAX( p->rbearing, p->maxrb ); p->minlb = (short)FT_MIN( glyph->bbx.x_offset, p->minlb ); p->maxlb = (short)FT_MAX( glyph->bbx.x_offset, p->maxlb ); if ( !( p->flags & _BDF_DWIDTH ) ) { /* Missing DWIDTH field. Emit an auto correction message and set */ /* the device width to the glyph width. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG10, lineno )); glyph->dwidth = glyph->bbx.width; } /* If the BDF_CORRECT_METRICS flag is set, then adjust the SWIDTH */ /* value if necessary. */ if ( p->opts->correct_metrics != 0 ) { /* Determine the point size of the glyph. */ unsigned short sw = (unsigned short)FT_MulDiv( glyph->dwidth, 72000L, (FT_Long)( font->point_size * font->resolution_x ) ); if ( sw != glyph->swidth ) { glyph->swidth = sw; if ( p->glyph_enc == -1 ) _bdf_set_glyph_modified( font->umod, font->unencoded_used - 1 ); else _bdf_set_glyph_modified( font->nmod, glyph->encoding ); p->flags |= _BDF_SWIDTH_ADJ; font->modified = 1; } } p->flags |= _BDF_BBX; goto Exit; } /* And finally, gather up the bitmap. */ if ( ft_memcmp( line, "BITMAP", 6 ) == 0 ) { unsigned long bitmap_size; if ( !( p->flags & _BDF_BBX ) ) { /* Missing BBX field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "BBX" )); error = BDF_Err_Missing_Bbx_Field; goto Exit; } /* Allocate enough space for the bitmap. */ glyph->bpr = ( glyph->bbx.width * p->font->bpp + 7 ) >> 3; bitmap_size = glyph->bpr * glyph->bbx.height; if ( glyph->bpr > 0xFFFFU || bitmap_size > 0xFFFFU ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG4, lineno )); error = BDF_Err_Bbx_Too_Big; goto Exit; } else glyph->bytes = (unsigned short)bitmap_size; if ( FT_NEW_ARRAY( glyph->bitmap, glyph->bytes ) ) goto Exit; p->row = 0; p->flags |= _BDF_BITMAP; goto Exit; } FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG9, lineno )); error = BDF_Err_Invalid_File_Format; goto Exit; Missing_Encoding: /* Missing ENCODING field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "ENCODING" )); error = BDF_Err_Missing_Encoding_Field; Exit: if ( error && ( p->flags & _BDF_GLYPH ) ) FT_FREE( p->glyph_name ); return error; }
284,263,663,179,865,300,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2012-5670
The _bdf_parse_glyphs function in FreeType before 2.4.11 allows context-dependent attackers to cause a denial of service (out-of-bounds write and crash) via vectors related to BDF fonts and an ENCODING field with a negative value.
https://nvd.nist.gov/vuln/detail/CVE-2012-5670
166
savannah
07bdb6e289c7954e2a533039dc93c1c136099d2d
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=07bdb6e289c7954e2a533039dc93c1c136099d2d
None
1
_bdf_parse_glyphs( char* line, unsigned long linelen, unsigned long lineno, void* call_data, void* client_data ) { int c, mask_index; char* s; unsigned char* bp; unsigned long i, slen, nibbles; _bdf_parse_t* p; bdf_glyph_t* glyph; bdf_font_t* font; FT_Memory memory; FT_Error error = BDF_Err_Ok; FT_UNUSED( call_data ); FT_UNUSED( lineno ); /* only used in debug mode */ p = (_bdf_parse_t *)client_data; font = p->font; memory = font->memory; /* Check for a comment. */ if ( ft_memcmp( line, "COMMENT", 7 ) == 0 ) { linelen -= 7; s = line + 7; if ( *s != 0 ) { s++; linelen--; } error = _bdf_add_comment( p->font, s, linelen ); goto Exit; } /* The very first thing expected is the number of glyphs. */ if ( !( p->flags & _BDF_GLYPHS ) ) { if ( ft_memcmp( line, "CHARS", 5 ) != 0 ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "CHARS" )); error = BDF_Err_Missing_Chars_Field; goto Exit; } error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; p->cnt = font->glyphs_size = _bdf_atoul( p->list.field[1], 0, 10 ); /* Make sure the number of glyphs is non-zero. */ if ( p->cnt == 0 ) font->glyphs_size = 64; /* Limit ourselves to 1,114,112 glyphs in the font (this is the */ /* number of code points available in Unicode). */ if ( p->cnt >= 0x110000UL ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "CHARS" )); error = BDF_Err_Invalid_Argument; goto Exit; } if ( FT_NEW_ARRAY( font->glyphs, font->glyphs_size ) ) goto Exit; p->flags |= _BDF_GLYPHS; goto Exit; } /* Check for the ENDFONT field. */ if ( ft_memcmp( line, "ENDFONT", 7 ) == 0 ) { /* Sort the glyphs by encoding. */ ft_qsort( (char *)font->glyphs, font->glyphs_used, sizeof ( bdf_glyph_t ), by_encoding ); p->flags &= ~_BDF_START; goto Exit; } /* Check for the ENDCHAR field. */ if ( ft_memcmp( line, "ENDCHAR", 7 ) == 0 ) { p->glyph_enc = 0; p->flags &= ~_BDF_GLYPH_BITS; goto Exit; } /* Check whether a glyph is being scanned but should be */ /* ignored because it is an unencoded glyph. */ if ( ( p->flags & _BDF_GLYPH ) && p->glyph_enc == -1 && p->opts->keep_unencoded == 0 ) goto Exit; /* Check for the STARTCHAR field. */ if ( ft_memcmp( line, "STARTCHAR", 9 ) == 0 ) { /* Set the character name in the parse info first until the */ /* encoding can be checked for an unencoded character. */ FT_FREE( p->glyph_name ); error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; _bdf_list_shift( &p->list, 1 ); s = _bdf_list_join( &p->list, ' ', &slen ); if ( !s ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG8, lineno, "STARTCHAR" )); error = BDF_Err_Invalid_File_Format; goto Exit; } if ( FT_NEW_ARRAY( p->glyph_name, slen + 1 ) ) goto Exit; FT_MEM_COPY( p->glyph_name, s, slen + 1 ); p->flags |= _BDF_GLYPH; FT_TRACE4(( DBGMSG1, lineno, s )); goto Exit; } /* Check for the ENCODING field. */ if ( ft_memcmp( line, "ENCODING", 8 ) == 0 ) { if ( !( p->flags & _BDF_GLYPH ) ) { /* Missing STARTCHAR field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "STARTCHAR" )); error = BDF_Err_Missing_Startchar_Field; goto Exit; } error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; p->glyph_enc = _bdf_atol( p->list.field[1], 0, 10 ); /* Normalize negative encoding values. The specification only */ /* allows -1, but we can be more generous here. */ if ( p->glyph_enc < -1 ) p->glyph_enc = -1; /* Check for alternative encoding format. */ if ( p->glyph_enc == -1 && p->list.used > 2 ) p->glyph_enc = _bdf_atol( p->list.field[2], 0, 10 ); FT_TRACE4(( DBGMSG2, p->glyph_enc )); /* Check that the encoding is in the Unicode range because */ /* otherwise p->have (a bitmap with static size) overflows. */ if ( p->glyph_enc > 0 && (size_t)p->glyph_enc >= sizeof ( p->have ) * 8 ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "ENCODING" )); error = BDF_Err_Invalid_File_Format; } /* Check whether this encoding has already been encountered. */ /* If it has then change it to unencoded so it gets added if */ /* indicated. */ if ( p->glyph_enc >= 0 ) { if ( _bdf_glyph_modified( p->have, p->glyph_enc ) ) { /* Emit a message saying a glyph has been moved to the */ /* unencoded area. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG12, p->glyph_enc, p->glyph_name )); p->glyph_enc = -1; font->modified = 1; } else _bdf_set_glyph_modified( p->have, p->glyph_enc ); } if ( p->glyph_enc >= 0 ) { /* Make sure there are enough glyphs allocated in case the */ /* number of characters happen to be wrong. */ if ( font->glyphs_used == font->glyphs_size ) { if ( FT_RENEW_ARRAY( font->glyphs, font->glyphs_size, font->glyphs_size + 64 ) ) goto Exit; font->glyphs_size += 64; } glyph = font->glyphs + font->glyphs_used++; glyph->name = p->glyph_name; glyph->encoding = p->glyph_enc; /* Reset the initial glyph info. */ p->glyph_name = 0; } else { /* Unencoded glyph. Check whether it should */ /* be added or not. */ if ( p->opts->keep_unencoded != 0 ) { /* Allocate the next unencoded glyph. */ if ( font->unencoded_used == font->unencoded_size ) { if ( FT_RENEW_ARRAY( font->unencoded , font->unencoded_size, font->unencoded_size + 4 ) ) goto Exit; font->unencoded_size += 4; } glyph = font->unencoded + font->unencoded_used; glyph->name = p->glyph_name; glyph->encoding = font->unencoded_used++; } else /* Free up the glyph name if the unencoded shouldn't be */ /* kept. */ FT_FREE( p->glyph_name ); p->glyph_name = 0; } /* Clear the flags that might be added when width and height are */ /* checked for consistency. */ p->flags &= ~( _BDF_GLYPH_WIDTH_CHECK | _BDF_GLYPH_HEIGHT_CHECK ); p->flags |= _BDF_ENCODING; goto Exit; } /* Point at the glyph being constructed. */ if ( p->glyph_enc == -1 ) glyph = font->unencoded + ( font->unencoded_used - 1 ); else glyph = font->glyphs + ( font->glyphs_used - 1 ); /* Check whether a bitmap is being constructed. */ if ( p->flags & _BDF_BITMAP ) { /* If there are more rows than are specified in the glyph metrics, */ /* ignore the remaining lines. */ if ( p->row >= (unsigned long)glyph->bbx.height ) { if ( !( p->flags & _BDF_GLYPH_HEIGHT_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG13, glyph->encoding )); p->flags |= _BDF_GLYPH_HEIGHT_CHECK; font->modified = 1; } goto Exit; } /* Only collect the number of nibbles indicated by the glyph */ /* metrics. If there are more columns, they are simply ignored. */ nibbles = glyph->bpr << 1; bp = glyph->bitmap + p->row * glyph->bpr; for ( i = 0; i < nibbles; i++ ) { c = line[i]; if ( !sbitset( hdigits, c ) ) break; *bp = (FT_Byte)( ( *bp << 4 ) + a2i[c] ); if ( i + 1 < nibbles && ( i & 1 ) ) *++bp = 0; } /* If any line has not enough columns, */ /* indicate they have been padded with zero bits. */ if ( i < nibbles && !( p->flags & _BDF_GLYPH_WIDTH_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG16, glyph->encoding )); p->flags |= _BDF_GLYPH_WIDTH_CHECK; font->modified = 1; } /* Remove possible garbage at the right. */ mask_index = ( glyph->bbx.width * p->font->bpp ) & 7; if ( glyph->bbx.width ) *bp &= nibble_mask[mask_index]; /* If any line has extra columns, indicate they have been removed. */ if ( i == nibbles && sbitset( hdigits, line[nibbles] ) && !( p->flags & _BDF_GLYPH_WIDTH_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG14, glyph->encoding )); p->flags |= _BDF_GLYPH_WIDTH_CHECK; font->modified = 1; } p->row++; goto Exit; } /* Expect the SWIDTH (scalable width) field next. */ if ( ft_memcmp( line, "SWIDTH", 6 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->swidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 ); p->flags |= _BDF_SWIDTH; goto Exit; } /* Expect the DWIDTH (scalable width) field next. */ if ( ft_memcmp( line, "DWIDTH", 6 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->dwidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 ); if ( !( p->flags & _BDF_SWIDTH ) ) { /* Missing SWIDTH field. Emit an auto correction message and set */ /* the scalable width from the device width. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG9, lineno )); glyph->swidth = (unsigned short)FT_MulDiv( glyph->dwidth, 72000L, (FT_Long)( font->point_size * font->resolution_x ) ); } p->flags |= _BDF_DWIDTH; goto Exit; } /* Expect the BBX field next. */ if ( ft_memcmp( line, "BBX", 3 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->bbx.width = _bdf_atos( p->list.field[1], 0, 10 ); glyph->bbx.height = _bdf_atos( p->list.field[2], 0, 10 ); glyph->bbx.x_offset = _bdf_atos( p->list.field[3], 0, 10 ); glyph->bbx.y_offset = _bdf_atos( p->list.field[4], 0, 10 ); /* Generate the ascent and descent of the character. */ glyph->bbx.ascent = (short)( glyph->bbx.height + glyph->bbx.y_offset ); glyph->bbx.descent = (short)( -glyph->bbx.y_offset ); /* Determine the overall font bounding box as the characters are */ /* loaded so corrections can be done later if indicated. */ p->maxas = (short)FT_MAX( glyph->bbx.ascent, p->maxas ); p->maxds = (short)FT_MAX( glyph->bbx.descent, p->maxds ); p->rbearing = (short)( glyph->bbx.width + glyph->bbx.x_offset ); p->maxrb = (short)FT_MAX( p->rbearing, p->maxrb ); p->minlb = (short)FT_MIN( glyph->bbx.x_offset, p->minlb ); p->maxlb = (short)FT_MAX( glyph->bbx.x_offset, p->maxlb ); if ( !( p->flags & _BDF_DWIDTH ) ) { /* Missing DWIDTH field. Emit an auto correction message and set */ /* the device width to the glyph width. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG10, lineno )); glyph->dwidth = glyph->bbx.width; } /* If the BDF_CORRECT_METRICS flag is set, then adjust the SWIDTH */ /* value if necessary. */ if ( p->opts->correct_metrics != 0 ) { /* Determine the point size of the glyph. */ unsigned short sw = (unsigned short)FT_MulDiv( glyph->dwidth, 72000L, (FT_Long)( font->point_size * font->resolution_x ) ); if ( sw != glyph->swidth ) { glyph->swidth = sw; if ( p->glyph_enc == -1 ) _bdf_set_glyph_modified( font->umod, font->unencoded_used - 1 ); else _bdf_set_glyph_modified( font->nmod, glyph->encoding ); p->flags |= _BDF_SWIDTH_ADJ; font->modified = 1; } } p->flags |= _BDF_BBX; goto Exit; } /* And finally, gather up the bitmap. */ if ( ft_memcmp( line, "BITMAP", 6 ) == 0 ) { unsigned long bitmap_size; if ( !( p->flags & _BDF_BBX ) ) { /* Missing BBX field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "BBX" )); error = BDF_Err_Missing_Bbx_Field; goto Exit; } /* Allocate enough space for the bitmap. */ glyph->bpr = ( glyph->bbx.width * p->font->bpp + 7 ) >> 3; bitmap_size = glyph->bpr * glyph->bbx.height; if ( glyph->bpr > 0xFFFFU || bitmap_size > 0xFFFFU ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG4, lineno )); error = BDF_Err_Bbx_Too_Big; goto Exit; } else glyph->bytes = (unsigned short)bitmap_size; if ( FT_NEW_ARRAY( glyph->bitmap, glyph->bytes ) ) goto Exit; p->row = 0; p->flags |= _BDF_BITMAP; goto Exit; } FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG9, lineno )); error = BDF_Err_Invalid_File_Format; goto Exit; Missing_Encoding: /* Missing ENCODING field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "ENCODING" )); error = BDF_Err_Missing_Encoding_Field; Exit: if ( error && ( p->flags & _BDF_GLYPH ) ) FT_FREE( p->glyph_name ); return error; }
339,135,483,814,426,960,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2012-5669
The _bdf_parse_glyphs function in FreeType before 2.4.11 allows context-dependent attackers to cause a denial of service (crash) and possibly execute arbitrary code via vectors related to BDF fonts and an incorrect calculation that triggers an out-of-bounds read.
https://nvd.nist.gov/vuln/detail/CVE-2012-5669
158,026
savannah
07bdb6e289c7954e2a533039dc93c1c136099d2d
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=07bdb6e289c7954e2a533039dc93c1c136099d2d
None
0
_bdf_parse_glyphs( char* line, unsigned long linelen, unsigned long lineno, void* call_data, void* client_data ) { int c, mask_index; char* s; unsigned char* bp; unsigned long i, slen, nibbles; _bdf_parse_t* p; bdf_glyph_t* glyph; bdf_font_t* font; FT_Memory memory; FT_Error error = BDF_Err_Ok; FT_UNUSED( call_data ); FT_UNUSED( lineno ); /* only used in debug mode */ p = (_bdf_parse_t *)client_data; font = p->font; memory = font->memory; /* Check for a comment. */ if ( ft_memcmp( line, "COMMENT", 7 ) == 0 ) { linelen -= 7; s = line + 7; if ( *s != 0 ) { s++; linelen--; } error = _bdf_add_comment( p->font, s, linelen ); goto Exit; } /* The very first thing expected is the number of glyphs. */ if ( !( p->flags & _BDF_GLYPHS ) ) { if ( ft_memcmp( line, "CHARS", 5 ) != 0 ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "CHARS" )); error = BDF_Err_Missing_Chars_Field; goto Exit; } error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; p->cnt = font->glyphs_size = _bdf_atoul( p->list.field[1], 0, 10 ); /* Make sure the number of glyphs is non-zero. */ if ( p->cnt == 0 ) font->glyphs_size = 64; /* Limit ourselves to 1,114,112 glyphs in the font (this is the */ /* number of code points available in Unicode). */ if ( p->cnt >= 0x110000UL ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "CHARS" )); error = BDF_Err_Invalid_Argument; goto Exit; } if ( FT_NEW_ARRAY( font->glyphs, font->glyphs_size ) ) goto Exit; p->flags |= _BDF_GLYPHS; goto Exit; } /* Check for the ENDFONT field. */ if ( ft_memcmp( line, "ENDFONT", 7 ) == 0 ) { /* Sort the glyphs by encoding. */ ft_qsort( (char *)font->glyphs, font->glyphs_used, sizeof ( bdf_glyph_t ), by_encoding ); p->flags &= ~_BDF_START; goto Exit; } /* Check for the ENDCHAR field. */ if ( ft_memcmp( line, "ENDCHAR", 7 ) == 0 ) { p->glyph_enc = 0; p->flags &= ~_BDF_GLYPH_BITS; goto Exit; } /* Check whether a glyph is being scanned but should be */ /* ignored because it is an unencoded glyph. */ if ( ( p->flags & _BDF_GLYPH ) && p->glyph_enc == -1 && p->opts->keep_unencoded == 0 ) goto Exit; /* Check for the STARTCHAR field. */ if ( ft_memcmp( line, "STARTCHAR", 9 ) == 0 ) { /* Set the character name in the parse info first until the */ /* encoding can be checked for an unencoded character. */ FT_FREE( p->glyph_name ); error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; _bdf_list_shift( &p->list, 1 ); s = _bdf_list_join( &p->list, ' ', &slen ); if ( !s ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG8, lineno, "STARTCHAR" )); error = BDF_Err_Invalid_File_Format; goto Exit; } if ( FT_NEW_ARRAY( p->glyph_name, slen + 1 ) ) goto Exit; FT_MEM_COPY( p->glyph_name, s, slen + 1 ); p->flags |= _BDF_GLYPH; FT_TRACE4(( DBGMSG1, lineno, s )); goto Exit; } /* Check for the ENCODING field. */ if ( ft_memcmp( line, "ENCODING", 8 ) == 0 ) { if ( !( p->flags & _BDF_GLYPH ) ) { /* Missing STARTCHAR field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "STARTCHAR" )); error = BDF_Err_Missing_Startchar_Field; goto Exit; } error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; p->glyph_enc = _bdf_atol( p->list.field[1], 0, 10 ); /* Normalize negative encoding values. The specification only */ /* allows -1, but we can be more generous here. */ if ( p->glyph_enc < -1 ) p->glyph_enc = -1; /* Check for alternative encoding format. */ if ( p->glyph_enc == -1 && p->list.used > 2 ) p->glyph_enc = _bdf_atol( p->list.field[2], 0, 10 ); FT_TRACE4(( DBGMSG2, p->glyph_enc )); /* Check that the encoding is in the Unicode range because */ /* otherwise p->have (a bitmap with static size) overflows. */ if ( p->glyph_enc > 0 && (size_t)p->glyph_enc >= sizeof ( p->have ) / sizeof ( unsigned long ) * 32 ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG5, lineno, "ENCODING" )); error = BDF_Err_Invalid_File_Format; } /* Check whether this encoding has already been encountered. */ /* If it has then change it to unencoded so it gets added if */ /* indicated. */ if ( p->glyph_enc >= 0 ) { if ( _bdf_glyph_modified( p->have, p->glyph_enc ) ) { /* Emit a message saying a glyph has been moved to the */ /* unencoded area. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG12, p->glyph_enc, p->glyph_name )); p->glyph_enc = -1; font->modified = 1; } else _bdf_set_glyph_modified( p->have, p->glyph_enc ); } if ( p->glyph_enc >= 0 ) { /* Make sure there are enough glyphs allocated in case the */ /* number of characters happen to be wrong. */ if ( font->glyphs_used == font->glyphs_size ) { if ( FT_RENEW_ARRAY( font->glyphs, font->glyphs_size, font->glyphs_size + 64 ) ) goto Exit; font->glyphs_size += 64; } glyph = font->glyphs + font->glyphs_used++; glyph->name = p->glyph_name; glyph->encoding = p->glyph_enc; /* Reset the initial glyph info. */ p->glyph_name = 0; } else { /* Unencoded glyph. Check whether it should */ /* be added or not. */ if ( p->opts->keep_unencoded != 0 ) { /* Allocate the next unencoded glyph. */ if ( font->unencoded_used == font->unencoded_size ) { if ( FT_RENEW_ARRAY( font->unencoded , font->unencoded_size, font->unencoded_size + 4 ) ) goto Exit; font->unencoded_size += 4; } glyph = font->unencoded + font->unencoded_used; glyph->name = p->glyph_name; glyph->encoding = font->unencoded_used++; } else /* Free up the glyph name if the unencoded shouldn't be */ /* kept. */ FT_FREE( p->glyph_name ); p->glyph_name = 0; } /* Clear the flags that might be added when width and height are */ /* checked for consistency. */ p->flags &= ~( _BDF_GLYPH_WIDTH_CHECK | _BDF_GLYPH_HEIGHT_CHECK ); p->flags |= _BDF_ENCODING; goto Exit; } /* Point at the glyph being constructed. */ if ( p->glyph_enc == -1 ) glyph = font->unencoded + ( font->unencoded_used - 1 ); else glyph = font->glyphs + ( font->glyphs_used - 1 ); /* Check whether a bitmap is being constructed. */ if ( p->flags & _BDF_BITMAP ) { /* If there are more rows than are specified in the glyph metrics, */ /* ignore the remaining lines. */ if ( p->row >= (unsigned long)glyph->bbx.height ) { if ( !( p->flags & _BDF_GLYPH_HEIGHT_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG13, glyph->encoding )); p->flags |= _BDF_GLYPH_HEIGHT_CHECK; font->modified = 1; } goto Exit; } /* Only collect the number of nibbles indicated by the glyph */ /* metrics. If there are more columns, they are simply ignored. */ nibbles = glyph->bpr << 1; bp = glyph->bitmap + p->row * glyph->bpr; for ( i = 0; i < nibbles; i++ ) { c = line[i]; if ( !sbitset( hdigits, c ) ) break; *bp = (FT_Byte)( ( *bp << 4 ) + a2i[c] ); if ( i + 1 < nibbles && ( i & 1 ) ) *++bp = 0; } /* If any line has not enough columns, */ /* indicate they have been padded with zero bits. */ if ( i < nibbles && !( p->flags & _BDF_GLYPH_WIDTH_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG16, glyph->encoding )); p->flags |= _BDF_GLYPH_WIDTH_CHECK; font->modified = 1; } /* Remove possible garbage at the right. */ mask_index = ( glyph->bbx.width * p->font->bpp ) & 7; if ( glyph->bbx.width ) *bp &= nibble_mask[mask_index]; /* If any line has extra columns, indicate they have been removed. */ if ( i == nibbles && sbitset( hdigits, line[nibbles] ) && !( p->flags & _BDF_GLYPH_WIDTH_CHECK ) ) { FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG14, glyph->encoding )); p->flags |= _BDF_GLYPH_WIDTH_CHECK; font->modified = 1; } p->row++; goto Exit; } /* Expect the SWIDTH (scalable width) field next. */ if ( ft_memcmp( line, "SWIDTH", 6 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->swidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 ); p->flags |= _BDF_SWIDTH; goto Exit; } /* Expect the DWIDTH (scalable width) field next. */ if ( ft_memcmp( line, "DWIDTH", 6 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->dwidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 ); if ( !( p->flags & _BDF_SWIDTH ) ) { /* Missing SWIDTH field. Emit an auto correction message and set */ /* the scalable width from the device width. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG9, lineno )); glyph->swidth = (unsigned short)FT_MulDiv( glyph->dwidth, 72000L, (FT_Long)( font->point_size * font->resolution_x ) ); } p->flags |= _BDF_DWIDTH; goto Exit; } /* Expect the BBX field next. */ if ( ft_memcmp( line, "BBX", 3 ) == 0 ) { if ( !( p->flags & _BDF_ENCODING ) ) goto Missing_Encoding; error = _bdf_list_split( &p->list, (char *)" +", line, linelen ); if ( error ) goto Exit; glyph->bbx.width = _bdf_atos( p->list.field[1], 0, 10 ); glyph->bbx.height = _bdf_atos( p->list.field[2], 0, 10 ); glyph->bbx.x_offset = _bdf_atos( p->list.field[3], 0, 10 ); glyph->bbx.y_offset = _bdf_atos( p->list.field[4], 0, 10 ); /* Generate the ascent and descent of the character. */ glyph->bbx.ascent = (short)( glyph->bbx.height + glyph->bbx.y_offset ); glyph->bbx.descent = (short)( -glyph->bbx.y_offset ); /* Determine the overall font bounding box as the characters are */ /* loaded so corrections can be done later if indicated. */ p->maxas = (short)FT_MAX( glyph->bbx.ascent, p->maxas ); p->maxds = (short)FT_MAX( glyph->bbx.descent, p->maxds ); p->rbearing = (short)( glyph->bbx.width + glyph->bbx.x_offset ); p->maxrb = (short)FT_MAX( p->rbearing, p->maxrb ); p->minlb = (short)FT_MIN( glyph->bbx.x_offset, p->minlb ); p->maxlb = (short)FT_MAX( glyph->bbx.x_offset, p->maxlb ); if ( !( p->flags & _BDF_DWIDTH ) ) { /* Missing DWIDTH field. Emit an auto correction message and set */ /* the device width to the glyph width. */ FT_TRACE2(( "_bdf_parse_glyphs: " ACMSG10, lineno )); glyph->dwidth = glyph->bbx.width; } /* If the BDF_CORRECT_METRICS flag is set, then adjust the SWIDTH */ /* value if necessary. */ if ( p->opts->correct_metrics != 0 ) { /* Determine the point size of the glyph. */ unsigned short sw = (unsigned short)FT_MulDiv( glyph->dwidth, 72000L, (FT_Long)( font->point_size * font->resolution_x ) ); if ( sw != glyph->swidth ) { glyph->swidth = sw; if ( p->glyph_enc == -1 ) _bdf_set_glyph_modified( font->umod, font->unencoded_used - 1 ); else _bdf_set_glyph_modified( font->nmod, glyph->encoding ); p->flags |= _BDF_SWIDTH_ADJ; font->modified = 1; } } p->flags |= _BDF_BBX; goto Exit; } /* And finally, gather up the bitmap. */ if ( ft_memcmp( line, "BITMAP", 6 ) == 0 ) { unsigned long bitmap_size; if ( !( p->flags & _BDF_BBX ) ) { /* Missing BBX field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "BBX" )); error = BDF_Err_Missing_Bbx_Field; goto Exit; } /* Allocate enough space for the bitmap. */ glyph->bpr = ( glyph->bbx.width * p->font->bpp + 7 ) >> 3; bitmap_size = glyph->bpr * glyph->bbx.height; if ( glyph->bpr > 0xFFFFU || bitmap_size > 0xFFFFU ) { FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG4, lineno )); error = BDF_Err_Bbx_Too_Big; goto Exit; } else glyph->bytes = (unsigned short)bitmap_size; if ( FT_NEW_ARRAY( glyph->bitmap, glyph->bytes ) ) goto Exit; p->row = 0; p->flags |= _BDF_BITMAP; goto Exit; } FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG9, lineno )); error = BDF_Err_Invalid_File_Format; goto Exit; Missing_Encoding: /* Missing ENCODING field. */ FT_ERROR(( "_bdf_parse_glyphs: " ERRMSG1, lineno, "ENCODING" )); error = BDF_Err_Missing_Encoding_Field; Exit: if ( error && ( p->flags & _BDF_GLYPH ) ) FT_FREE( p->glyph_name ); return error; }
112,133,374,329,751,400,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2012-5669
The _bdf_parse_glyphs function in FreeType before 2.4.11 allows context-dependent attackers to cause a denial of service (crash) and possibly execute arbitrary code via vectors related to BDF fonts and an incorrect calculation that triggers an out-of-bounds read.
https://nvd.nist.gov/vuln/detail/CVE-2012-5669
167
savannah
8fcf61523644df42e1905c81bed26838e0b04f91
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/grep.git/commit/?id=8fcf61523644df42e1905c81bed26838e0b04f91
None
1
context_length_arg (char const *str, int *out) { uintmax_t value; if (! (xstrtoumax (str, 0, 10, &value, "") == LONGINT_OK && 0 <= (*out = value) && *out == value)) { error (EXIT_TROUBLE, 0, "%s: %s", str, _("invalid context length argument")); } page size, unless a read yields a partial page. */ static char *buffer; /* Base of buffer. */ static size_t bufalloc; /* Allocated buffer size, counting slop. */ #define INITIAL_BUFSIZE 32768 /* Initial buffer size, not counting slop. */ static int bufdesc; /* File descriptor. */ static char *bufbeg; /* Beginning of user-visible stuff. */ static char *buflim; /* Limit of user-visible stuff. */ static size_t pagesize; /* alignment of memory pages */ static off_t bufoffset; /* Read offset; defined on regular files. */ static off_t after_last_match; /* Pointer after last matching line that would have been output if we were outputting characters. */ /* Return VAL aligned to the next multiple of ALIGNMENT. VAL can be an integer or a pointer. Both args must be free of side effects. */ #define ALIGN_TO(val, alignment) \ ((size_t) (val) % (alignment) == 0 \ ? (val) \ : (val) + ((alignment) - (size_t) (val) % (alignment))) /* Reset the buffer for a new file, returning zero if we should skip it. Initialize on the first time through. */ static int reset (int fd, char const *file, struct stats *stats) { if (! pagesize) { pagesize = getpagesize (); if (pagesize == 0 || 2 * pagesize + 1 <= pagesize) abort (); bufalloc = ALIGN_TO (INITIAL_BUFSIZE, pagesize) + pagesize + 1; buffer = xmalloc (bufalloc); } bufbeg = buflim = ALIGN_TO (buffer + 1, pagesize); bufbeg[-1] = eolbyte; bufdesc = fd; if (S_ISREG (stats->stat.st_mode)) { if (file) bufoffset = 0; else { bufoffset = lseek (fd, 0, SEEK_CUR); if (bufoffset < 0) { suppressible_error (_("lseek failed"), errno); return 0; } } } return 1; } /* Read new stuff into the buffer, saving the specified amount of old stuff. When we're done, 'bufbeg' points to the beginning of the buffer contents, and 'buflim' points just after the end. Return zero if there's an error. */ static int fillbuf (size_t save, struct stats const *stats) { size_t fillsize = 0; int cc = 1; char *readbuf; size_t readsize; /* Offset from start of buffer to start of old stuff that we want to save. */ size_t saved_offset = buflim - save - buffer; if (pagesize <= buffer + bufalloc - buflim) { readbuf = buflim; bufbeg = buflim - save; } else { size_t minsize = save + pagesize; size_t newsize; size_t newalloc; char *newbuf; /* Grow newsize until it is at least as great as minsize. */ for (newsize = bufalloc - pagesize - 1; newsize < minsize; newsize *= 2) if (newsize * 2 < newsize || newsize * 2 + pagesize + 1 < newsize * 2) xalloc_die (); /* Try not to allocate more memory than the file size indicates, as that might cause unnecessary memory exhaustion if the file is large. However, do not use the original file size as a heuristic if we've already read past the file end, as most likely the file is growing. */ if (S_ISREG (stats->stat.st_mode)) { off_t to_be_read = stats->stat.st_size - bufoffset; off_t maxsize_off = save + to_be_read; if (0 <= to_be_read && to_be_read <= maxsize_off && maxsize_off == (size_t) maxsize_off && minsize <= (size_t) maxsize_off && (size_t) maxsize_off < newsize) newsize = maxsize_off; } /* Add enough room so that the buffer is aligned and has room for byte sentinels fore and aft. */ newalloc = newsize + pagesize + 1; newbuf = bufalloc < newalloc ? xmalloc (bufalloc = newalloc) : buffer; readbuf = ALIGN_TO (newbuf + 1 + save, pagesize); bufbeg = readbuf - save; memmove (bufbeg, buffer + saved_offset, save); bufbeg[-1] = eolbyte; if (newbuf != buffer) { free (buffer); buffer = newbuf; } } readsize = buffer + bufalloc - readbuf; readsize -= readsize % pagesize; if (! fillsize) { ssize_t bytesread; while ((bytesread = read (bufdesc, readbuf, readsize)) < 0 && errno == EINTR) continue; if (bytesread < 0) cc = 0; else fillsize = bytesread; } bufoffset += fillsize; #if defined HAVE_DOS_FILE_CONTENTS if (fillsize) fillsize = undossify_input (readbuf, fillsize); #endif buflim = readbuf + fillsize; return cc; } /* Flags controlling the style of output. */ static enum { BINARY_BINARY_FILES, TEXT_BINARY_FILES, WITHOUT_MATCH_BINARY_FILES } binary_files; /* How to handle binary files. */ static int filename_mask; /* If zero, output nulls after filenames. */ static int out_quiet; /* Suppress all normal output. */ static int out_invert; /* Print nonmatching stuff. */ static int out_file; /* Print filenames. */ static int out_line; /* Print line numbers. */ static int out_byte; /* Print byte offsets. */ static int out_before; /* Lines of leading context. */ static int out_after; /* Lines of trailing context. */ static int out_file; /* Print filenames. */ static int out_line; /* Print line numbers. */ static int out_byte; /* Print byte offsets. */ static int out_before; /* Lines of leading context. */ static int out_after; /* Lines of trailing context. */ static int count_matches; /* Count matching lines. */ static int list_files; /* List matching files. */ static int no_filenames; /* Suppress file names. */ static off_t max_count; /* Stop after outputting this many lines from an input file. */ static int line_buffered; /* If nonzero, use line buffering, i.e. fflush everyline out. */ static char const *lastnl; /* Pointer after last newline counted. */ static char const *lastout; /* Pointer after last character output; NULL if no character has been output or if it's conceptually before bufbeg. */ static uintmax_t totalnl; /* Total newline count before lastnl. */ static off_t outleft; /* Maximum number of lines to be output. */ static int pending; /* Pending lines of output. NULL if no character has been output or if it's conceptually before bufbeg. */ static uintmax_t totalnl; /* Total newline count before lastnl. */ static off_t outleft; /* Maximum number of lines to be output. */ static int pending; /* Pending lines of output. Always kept 0 if out_quiet is true. */ static int done_on_match; /* Stop scanning file on first match. */ static int exit_on_match; /* Exit on first match. */ /* Add two numbers that count input bytes or lines, and report an error if the addition overflows. */ static uintmax_t add_count (uintmax_t a, uintmax_t b) { uintmax_t sum = a + b; if (sum < a) error (EXIT_TROUBLE, 0, _("input is too large to count")); return sum; } static void nlscan (char const *lim) { size_t newlines = 0; char const *beg; for (beg = lastnl; beg < lim; beg++) { beg = memchr (beg, eolbyte, lim - beg); if (!beg) break; newlines++; } totalnl = add_count (totalnl, newlines); lastnl = lim; } /* Print the current filename. */ static void print_filename (void) { pr_sgr_start_if (filename_color); fputs (filename, stdout); pr_sgr_end_if (filename_color); } /* Print a character separator. */ static void print_sep (char sep) { pr_sgr_start_if (sep_color); fputc (sep, stdout); pr_sgr_end_if (sep_color); } /* Print a line number or a byte offset. */ static void print_offset (uintmax_t pos, int min_width, const char *color) { /* Do not rely on printf to print pos, since uintmax_t may be longer than long, and long long is not portable. */ char buf[sizeof pos * CHAR_BIT]; char *p = buf + sizeof buf; do { *--p = '0' + pos % 10; --min_width; } while ((pos /= 10) != 0); /* Do this to maximize the probability of alignment across lines. */ if (align_tabs) while (--min_width >= 0) *--p = ' '; pr_sgr_start_if (color); fwrite (p, 1, buf + sizeof buf - p, stdout); pr_sgr_end_if (color); } /* Print a whole line head (filename, line, byte). */ static void print_line_head (char const *beg, char const *lim, int sep) { int pending_sep = 0; if (out_file) { print_filename (); if (filename_mask) pending_sep = 1; else fputc (0, stdout); } if (out_line) { if (lastnl < lim) { nlscan (beg); totalnl = add_count (totalnl, 1); lastnl = lim; } if (pending_sep) print_sep (sep); print_offset (totalnl, 4, line_num_color); pending_sep = 1; } if (out_byte) { uintmax_t pos = add_count (totalcc, beg - bufbeg); #if defined HAVE_DOS_FILE_CONTENTS pos = dossified_pos (pos); #endif if (pending_sep) print_sep (sep); print_offset (pos, 6, byte_num_color); pending_sep = 1; } if (pending_sep) { /* This assumes sep is one column wide. Try doing this any other way with Unicode (and its combining and wide characters) filenames and you're wasting your efforts. */ if (align_tabs) fputs ("\t\b", stdout); print_sep (sep); } } static const char * print_line_middle (const char *beg, const char *lim, const char *line_color, const char *match_color) { size_t match_size; size_t match_offset; const char *cur = beg; const char *mid = NULL; while (cur < lim && ((match_offset = execute (beg, lim - beg, &match_size, beg + (cur - beg))) != (size_t) -1)) { char const *b = beg + match_offset; /* Avoid matching the empty line at the end of the buffer. */ if (b == lim) break; /* Avoid hanging on grep --color "" foo */ if (match_size == 0) { /* Make minimal progress; there may be further non-empty matches. */ /* XXX - Could really advance by one whole multi-octet character. */ match_size = 1; if (!mid) mid = cur; } else { /* This function is called on a matching line only, but is it selected or rejected/context? */ if (only_matching) print_line_head (b, lim, (out_invert ? SEP_CHAR_REJECTED : SEP_CHAR_SELECTED)); else { pr_sgr_start (line_color); if (mid) { cur = mid; mid = NULL; } fwrite (cur, sizeof (char), b - cur, stdout); } pr_sgr_start_if (match_color); fwrite (b, sizeof (char), match_size, stdout); pr_sgr_end_if (match_color); if (only_matching) fputs ("\n", stdout); } cur = b + match_size; } if (only_matching) cur = lim; else if (mid) cur = mid; return cur; } static const char * print_line_tail (const char *beg, const char *lim, const char *line_color) { size_t eol_size; size_t tail_size; eol_size = (lim > beg && lim[-1] == eolbyte); eol_size += (lim - eol_size > beg && lim[-(1 + eol_size)] == '\r'); tail_size = lim - eol_size - beg; if (tail_size > 0) { pr_sgr_start (line_color); fwrite (beg, 1, tail_size, stdout); beg += tail_size; pr_sgr_end (line_color); } return beg; } static void prline (char const *beg, char const *lim, int sep) { int matching; const char *line_color; const char *match_color; if (!only_matching) print_line_head (beg, lim, sep); matching = (sep == SEP_CHAR_SELECTED) ^ !!out_invert; if (color_option) { line_color = (((sep == SEP_CHAR_SELECTED) ^ (out_invert && (color_option < 0))) ? selected_line_color : context_line_color); match_color = (sep == SEP_CHAR_SELECTED ? selected_match_color : context_match_color); } else line_color = match_color = NULL; /* Shouldn't be used. */ if ((only_matching && matching) || (color_option && (*line_color || *match_color))) { /* We already know that non-matching lines have no match (to colorize). */ if (matching && (only_matching || *match_color)) beg = print_line_middle (beg, lim, line_color, match_color); /* FIXME: this test may be removable. */ if (!only_matching && *line_color) beg = print_line_tail (beg, lim, line_color); } if (!only_matching && lim > beg) fwrite (beg, 1, lim - beg, stdout); if (ferror (stdout)) { write_error_seen = 1; error (EXIT_TROUBLE, 0, _("write error")); } lastout = lim; if (line_buffered) fflush (stdout); } /* Print pending lines of trailing context prior to LIM. Trailing context ends at the next matching line when OUTLEFT is 0. */ static void prpending (char const *lim) { if (!lastout) lastout = bufbeg; while (pending > 0 && lastout < lim) { char const *nl = memchr (lastout, eolbyte, lim - lastout); size_t match_size; --pending; if (outleft || ((execute (lastout, nl + 1 - lastout, &match_size, NULL) == (size_t) -1) == !out_invert)) prline (lastout, nl + 1, SEP_CHAR_REJECTED); else pending = 0; } } /* Print the lines between BEG and LIM. Deal with context crap. If NLINESP is non-null, store a count of lines between BEG and LIM. */ static void prtext (char const *beg, char const *lim, int *nlinesp) { /* Print the lines between BEG and LIM. Deal with context crap. If NLINESP is non-null, store a count of lines between BEG and LIM. */ static void prtext (char const *beg, char const *lim, int *nlinesp) { static int used; /* avoid printing SEP_STR_GROUP before any output */ char const *bp, *p; char eol = eolbyte; int i, n; if (!out_quiet && pending > 0) prpending (beg); /* Deal with leading context crap. */ bp = lastout ? lastout : bufbeg; for (i = 0; i < out_before; ++i) if (p > bp) do --p; while (p[-1] != eol); /* We print the SEP_STR_GROUP separator only if our output is discontiguous from the last output in the file. */ if ((out_before || out_after) && used && p != lastout && group_separator) { pr_sgr_start_if (sep_color); fputs (group_separator, stdout); pr_sgr_end_if (sep_color); fputc ('\n', stdout); } while (p < beg) { char const *nl = memchr (p, eol, beg - p); nl++; prline (p, nl, SEP_CHAR_REJECTED); p = nl; } } if (nlinesp) { /* Caller wants a line count. */ for (n = 0; p < lim && n < outleft; n++) { char const *nl = memchr (p, eol, lim - p); nl++; if (!out_quiet) prline (p, nl, SEP_CHAR_SELECTED); p = nl; } *nlinesp = n; /* relying on it that this function is never called when outleft = 0. */ after_last_match = bufoffset - (buflim - p); } else if (!out_quiet) prline (beg, lim, SEP_CHAR_SELECTED); pending = out_quiet ? 0 : out_after; used = 1; } static size_t do_execute (char const *buf, size_t size, size_t *match_size, char const *start_ptr) { size_t result; const char *line_next; /* With the current implementation, using --ignore-case with a multi-byte character set is very inefficient when applied to a large buffer containing many matches. We can avoid much of the wasted effort by matching line-by-line. FIXME: this is just an ugly workaround, and it doesn't really belong here. Also, PCRE is always using this same per-line matching algorithm. Either we fix -i, or we should refactor this code---for example, we could add another function pointer to struct matcher to split the buffer passed to execute. It would perform the memchr if line-by-line matching is necessary, or just return buf + size otherwise. */ if (MB_CUR_MAX == 1 || !match_icase) return execute (buf, size, match_size, start_ptr); for (line_next = buf; line_next < buf + size; ) { const char *line_buf = line_next; const char *line_end = memchr (line_buf, eolbyte, (buf + size) - line_buf); if (line_end == NULL) line_next = line_end = buf + size; else line_next = line_end + 1; if (start_ptr && start_ptr >= line_end) continue; result = execute (line_buf, line_next - line_buf, match_size, start_ptr); if (result != (size_t) -1) return (line_buf - buf) + result; } return (size_t) -1; } /* Scan the specified portion of the buffer, matching lines (or between matching lines if OUT_INVERT is true). Return a count of lines printed. */ static int grepbuf (char const *beg, char const *lim) /* Scan the specified portion of the buffer, matching lines (or between matching lines if OUT_INVERT is true). Return a count of lines printed. */ static int grepbuf (char const *beg, char const *lim) { int nlines, n; char const *p; size_t match_offset; size_t match_size; { char const *b = p + match_offset; char const *endp = b + match_size; /* Avoid matching the empty line at the end of the buffer. */ if (b == lim) break; if (!out_invert) { prtext (b, endp, (int *) 0); nlines++; break; if (!out_invert) { prtext (b, endp, (int *) 0); nlines++; outleft--; if (!outleft || done_on_match) } } else if (p < b) { prtext (p, b, &n); nlines += n; outleft -= n; if (!outleft) return nlines; } p = endp; } if (out_invert && p < lim) { prtext (p, lim, &n); nlines += n; outleft -= n; } return nlines; } /* Search a given file. Normally, return a count of lines printed; but if the file is a directory and we search it recursively, then return -2 if there was a match, and -1 otherwise. */ static int grep (int fd, char const *file, struct stats *stats) /* Search a given file. Normally, return a count of lines printed; but if the file is a directory and we search it recursively, then return -2 if there was a match, and -1 otherwise. */ static int grep (int fd, char const *file, struct stats *stats) { int nlines, i; int not_text; size_t residue, save; char oldc; return 0; if (file && directories == RECURSE_DIRECTORIES && S_ISDIR (stats->stat.st_mode)) { /* Close fd now, so that we don't open a lot of file descriptors when we recurse deeply. */ if (close (fd) != 0) suppressible_error (file, errno); return grepdir (file, stats) - 2; } totalcc = 0; lastout = 0; totalnl = 0; outleft = max_count; after_last_match = 0; pending = 0; nlines = 0; residue = 0; save = 0; if (! fillbuf (save, stats)) { suppressible_error (filename, errno); return 0; } not_text = (((binary_files == BINARY_BINARY_FILES && !out_quiet) || binary_files == WITHOUT_MATCH_BINARY_FILES) && memchr (bufbeg, eol ? '\0' : '\200', buflim - bufbeg)); if (not_text && binary_files == WITHOUT_MATCH_BINARY_FILES) return 0; done_on_match += not_text; out_quiet += not_text; for (;;) { lastnl = bufbeg; if (lastout) lastout = bufbeg; beg = bufbeg + save; /* no more data to scan (eof) except for maybe a residue -> break */ if (beg == buflim) break; /* Determine new residue (the length of an incomplete line at the end of the buffer, 0 means there is no incomplete last line). */ oldc = beg[-1]; beg[-1] = eol; for (lim = buflim; lim[-1] != eol; lim--) continue; beg[-1] = oldc; if (lim == beg) lim = beg - residue; beg -= residue; residue = buflim - lim; if (beg < lim) { if (outleft) nlines += grepbuf (beg, lim); if (pending) prpending (lim); if ((!outleft && !pending) || (nlines && done_on_match && !out_invert)) goto finish_grep; } /* The last OUT_BEFORE lines at the end of the buffer will be needed as leading context if there is a matching line at the begin of the next data. Make beg point to their begin. */ i = 0; beg = lim; while (i < out_before && beg > bufbeg && beg != lastout) { ++i; do --beg; while (beg[-1] != eol); } /* detect if leading context is discontinuous from last printed line. */ if (beg != lastout) lastout = 0; /* Handle some details and read more data to scan. */ save = residue + lim - beg; if (out_byte) totalcc = add_count (totalcc, buflim - bufbeg - save); if (out_line) nlscan (beg); if (! fillbuf (save, stats)) { suppressible_error (filename, errno); goto finish_grep; } } if (residue) { *buflim++ = eol; if (outleft) nlines += grepbuf (bufbeg + save - residue, buflim); if (pending) prpending (buflim); } finish_grep: done_on_match -= not_text; out_quiet -= not_text; if ((not_text & ~out_quiet) && nlines != 0) printf (_("Binary file %s matches\n"), filename); return nlines; } static int grepfile (char const *file, struct stats *stats) { int desc; int count; int status; grepfile (char const *file, struct stats *stats) { int desc; int count; int status; filename = (file ? file : label ? label : _("(standard input)")); /* Don't open yet, since that might have side effects on a device. */ desc = -1; } else { /* When skipping directories, don't worry about directories that can't be opened. */ desc = open (file, O_RDONLY); if (desc < 0 && directories != SKIP_DIRECTORIES) { suppressible_error (file, errno); return 1; } } if (desc < 0 ? stat (file, &stats->stat) != 0 : fstat (desc, &stats->stat) != 0) { suppressible_error (filename, errno); if (file) close (desc); return 1; } if ((directories == SKIP_DIRECTORIES && S_ISDIR (stats->stat.st_mode)) || (devices == SKIP_DEVICES && (S_ISCHR (stats->stat.st_mode) || S_ISBLK (stats->stat.st_mode) || S_ISSOCK (stats->stat.st_mode) || S_ISFIFO (stats->stat.st_mode)))) { if (file) close (desc); return 1; } /* If there is a regular file on stdout and the current file refers to the same i-node, we have to report the problem and skip it. Otherwise when matching lines from some other input reach the disk before we open this file, we can end up reading and matching those lines and appending them to the file from which we're reading. Then we'd have what appears to be an infinite loop that'd terminate only upon filling the output file system or reaching a quota. However, there is no risk of an infinite loop if grep is generating no output, i.e., with --silent, --quiet, -q. Similarly, with any of these: --max-count=N (-m) (for N >= 2) --files-with-matches (-l) --files-without-match (-L) there is no risk of trouble. For --max-count=1, grep stops after printing the first match, so there is no risk of malfunction. But even --max-count=2, with input==output, while there is no risk of infloop, there is a race condition that could result in "alternate" output. */ if (!out_quiet && list_files == 0 && 1 < max_count && S_ISREG (out_stat.st_mode) && out_stat.st_ino && SAME_INODE (stats->stat, out_stat)) { if (! suppress_errors) error (0, 0, _("input file %s is also the output"), quote (filename)); errseen = 1; if (file) close (desc); return 1; } if (desc < 0) { desc = open (file, O_RDONLY); if (desc < 0) { suppressible_error (file, errno); return 1; } } #if defined SET_BINARY /* Set input to binary mode. Pipes are simulated with files on DOS, so this includes the case of "foo | grep bar". */ if (!isatty (desc)) SET_BINARY (desc); #endif count = grep (desc, file, stats); if (count < 0) status = count + 2; else { if (count_matches) { if (out_file) { print_filename (); if (filename_mask) print_sep (SEP_CHAR_SELECTED); else fputc (0, stdout); } printf ("%d\n", count); } else fputc (0, stdout); } printf ("%d\n", count); } status = !count; if (! file) { off_t required_offset = outleft ? bufoffset : after_last_match; if (required_offset != bufoffset && lseek (desc, required_offset, SEEK_SET) < 0 && S_ISREG (stats->stat.st_mode)) suppressible_error (filename, errno); } else while (close (desc) != 0) if (errno != EINTR) { suppressible_error (file, errno); break; } }
325,237,609,142,015,750,000,000,000,000,000,000,000
None
null
[ "CWE-189" ]
CVE-2012-5667
Multiple integer overflows in GNU Grep before 2.11 might allow context-dependent attackers to execute arbitrary code via vectors involving a long input line that triggers a heap-based buffer overflow.
https://nvd.nist.gov/vuln/detail/CVE-2012-5667
158,027
savannah
8fcf61523644df42e1905c81bed26838e0b04f91
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/grep.git/commit/?id=8fcf61523644df42e1905c81bed26838e0b04f91
None
0
context_length_arg (char const *str, int *out) context_length_arg (char const *str, intmax_t *out) { switch (xstrtoimax (str, 0, 10, out, "")) { case LONGINT_OK: case LONGINT_OVERFLOW: if (0 <= *out) break; /* Fall through. */ default: error (EXIT_TROUBLE, 0, "%s: %s", str, _("invalid context length argument")); } page size, unless a read yields a partial page. */ static char *buffer; /* Base of buffer. */ static size_t bufalloc; /* Allocated buffer size, counting slop. */ #define INITIAL_BUFSIZE 32768 /* Initial buffer size, not counting slop. */ static int bufdesc; /* File descriptor. */ static char *bufbeg; /* Beginning of user-visible stuff. */ static char *buflim; /* Limit of user-visible stuff. */ static size_t pagesize; /* alignment of memory pages */ static off_t bufoffset; /* Read offset; defined on regular files. */ static off_t after_last_match; /* Pointer after last matching line that would have been output if we were outputting characters. */ /* Return VAL aligned to the next multiple of ALIGNMENT. VAL can be an integer or a pointer. Both args must be free of side effects. */ #define ALIGN_TO(val, alignment) \ ((size_t) (val) % (alignment) == 0 \ ? (val) \ : (val) + ((alignment) - (size_t) (val) % (alignment))) /* Reset the buffer for a new file, returning zero if we should skip it. Initialize on the first time through. */ static int reset (int fd, char const *file, struct stats *stats) { if (! pagesize) { pagesize = getpagesize (); if (pagesize == 0 || 2 * pagesize + 1 <= pagesize) abort (); bufalloc = ALIGN_TO (INITIAL_BUFSIZE, pagesize) + pagesize + 1; buffer = xmalloc (bufalloc); } bufbeg = buflim = ALIGN_TO (buffer + 1, pagesize); bufbeg[-1] = eolbyte; bufdesc = fd; if (S_ISREG (stats->stat.st_mode)) { if (file) bufoffset = 0; else { bufoffset = lseek (fd, 0, SEEK_CUR); if (bufoffset < 0) { suppressible_error (_("lseek failed"), errno); return 0; } } } return 1; } /* Read new stuff into the buffer, saving the specified amount of old stuff. When we're done, 'bufbeg' points to the beginning of the buffer contents, and 'buflim' points just after the end. Return zero if there's an error. */ static int fillbuf (size_t save, struct stats const *stats) { size_t fillsize = 0; int cc = 1; char *readbuf; size_t readsize; /* Offset from start of buffer to start of old stuff that we want to save. */ size_t saved_offset = buflim - save - buffer; if (pagesize <= buffer + bufalloc - buflim) { readbuf = buflim; bufbeg = buflim - save; } else { size_t minsize = save + pagesize; size_t newsize; size_t newalloc; char *newbuf; /* Grow newsize until it is at least as great as minsize. */ for (newsize = bufalloc - pagesize - 1; newsize < minsize; newsize *= 2) if (newsize * 2 < newsize || newsize * 2 + pagesize + 1 < newsize * 2) xalloc_die (); /* Try not to allocate more memory than the file size indicates, as that might cause unnecessary memory exhaustion if the file is large. However, do not use the original file size as a heuristic if we've already read past the file end, as most likely the file is growing. */ if (S_ISREG (stats->stat.st_mode)) { off_t to_be_read = stats->stat.st_size - bufoffset; off_t maxsize_off = save + to_be_read; if (0 <= to_be_read && to_be_read <= maxsize_off && maxsize_off == (size_t) maxsize_off && minsize <= (size_t) maxsize_off && (size_t) maxsize_off < newsize) newsize = maxsize_off; } /* Add enough room so that the buffer is aligned and has room for byte sentinels fore and aft. */ newalloc = newsize + pagesize + 1; newbuf = bufalloc < newalloc ? xmalloc (bufalloc = newalloc) : buffer; readbuf = ALIGN_TO (newbuf + 1 + save, pagesize); bufbeg = readbuf - save; memmove (bufbeg, buffer + saved_offset, save); bufbeg[-1] = eolbyte; if (newbuf != buffer) { free (buffer); buffer = newbuf; } } readsize = buffer + bufalloc - readbuf; readsize -= readsize % pagesize; if (! fillsize) { ssize_t bytesread; while ((bytesread = read (bufdesc, readbuf, readsize)) < 0 && errno == EINTR) continue; if (bytesread < 0) cc = 0; else fillsize = bytesread; } bufoffset += fillsize; #if defined HAVE_DOS_FILE_CONTENTS if (fillsize) fillsize = undossify_input (readbuf, fillsize); #endif buflim = readbuf + fillsize; return cc; } /* Flags controlling the style of output. */ static enum { BINARY_BINARY_FILES, TEXT_BINARY_FILES, WITHOUT_MATCH_BINARY_FILES } binary_files; /* How to handle binary files. */ static int filename_mask; /* If zero, output nulls after filenames. */ static int out_quiet; /* Suppress all normal output. */ static int out_invert; /* Print nonmatching stuff. */ static int out_file; /* Print filenames. */ static int out_line; /* Print line numbers. */ static int out_byte; /* Print byte offsets. */ static int out_before; /* Lines of leading context. */ static int out_after; /* Lines of trailing context. */ static int out_file; /* Print filenames. */ static int out_line; /* Print line numbers. */ static int out_byte; /* Print byte offsets. */ static intmax_t out_before; /* Lines of leading context. */ static intmax_t out_after; /* Lines of trailing context. */ static int count_matches; /* Count matching lines. */ static int list_files; /* List matching files. */ static int no_filenames; /* Suppress file names. */ static intmax_t max_count; /* Stop after outputting this many lines from an input file. */ static int line_buffered; /* If nonzero, use line buffering, i.e. fflush everyline out. */ static char const *lastnl; /* Pointer after last newline counted. */ static char const *lastout; /* Pointer after last character output; NULL if no character has been output or if it's conceptually before bufbeg. */ static uintmax_t totalnl; /* Total newline count before lastnl. */ static off_t outleft; /* Maximum number of lines to be output. */ static int pending; /* Pending lines of output. NULL if no character has been output or if it's conceptually before bufbeg. */ static uintmax_t totalnl; /* Total newline count before lastnl. */ static intmax_t outleft; /* Maximum number of lines to be output. */ static intmax_t pending; /* Pending lines of output. Always kept 0 if out_quiet is true. */ static int done_on_match; /* Stop scanning file on first match. */ static int exit_on_match; /* Exit on first match. */ /* Add two numbers that count input bytes or lines, and report an error if the addition overflows. */ static uintmax_t add_count (uintmax_t a, uintmax_t b) { uintmax_t sum = a + b; if (sum < a) error (EXIT_TROUBLE, 0, _("input is too large to count")); return sum; } static void nlscan (char const *lim) { size_t newlines = 0; char const *beg; for (beg = lastnl; beg < lim; beg++) { beg = memchr (beg, eolbyte, lim - beg); if (!beg) break; newlines++; } totalnl = add_count (totalnl, newlines); lastnl = lim; } /* Print the current filename. */ static void print_filename (void) { pr_sgr_start_if (filename_color); fputs (filename, stdout); pr_sgr_end_if (filename_color); } /* Print a character separator. */ static void print_sep (char sep) { pr_sgr_start_if (sep_color); fputc (sep, stdout); pr_sgr_end_if (sep_color); } /* Print a line number or a byte offset. */ static void print_offset (uintmax_t pos, int min_width, const char *color) { /* Do not rely on printf to print pos, since uintmax_t may be longer than long, and long long is not portable. */ char buf[sizeof pos * CHAR_BIT]; char *p = buf + sizeof buf; do { *--p = '0' + pos % 10; --min_width; } while ((pos /= 10) != 0); /* Do this to maximize the probability of alignment across lines. */ if (align_tabs) while (--min_width >= 0) *--p = ' '; pr_sgr_start_if (color); fwrite (p, 1, buf + sizeof buf - p, stdout); pr_sgr_end_if (color); } /* Print a whole line head (filename, line, byte). */ static void print_line_head (char const *beg, char const *lim, int sep) { int pending_sep = 0; if (out_file) { print_filename (); if (filename_mask) pending_sep = 1; else fputc (0, stdout); } if (out_line) { if (lastnl < lim) { nlscan (beg); totalnl = add_count (totalnl, 1); lastnl = lim; } if (pending_sep) print_sep (sep); print_offset (totalnl, 4, line_num_color); pending_sep = 1; } if (out_byte) { uintmax_t pos = add_count (totalcc, beg - bufbeg); #if defined HAVE_DOS_FILE_CONTENTS pos = dossified_pos (pos); #endif if (pending_sep) print_sep (sep); print_offset (pos, 6, byte_num_color); pending_sep = 1; } if (pending_sep) { /* This assumes sep is one column wide. Try doing this any other way with Unicode (and its combining and wide characters) filenames and you're wasting your efforts. */ if (align_tabs) fputs ("\t\b", stdout); print_sep (sep); } } static const char * print_line_middle (const char *beg, const char *lim, const char *line_color, const char *match_color) { size_t match_size; size_t match_offset; const char *cur = beg; const char *mid = NULL; while (cur < lim && ((match_offset = execute (beg, lim - beg, &match_size, beg + (cur - beg))) != (size_t) -1)) { char const *b = beg + match_offset; /* Avoid matching the empty line at the end of the buffer. */ if (b == lim) break; /* Avoid hanging on grep --color "" foo */ if (match_size == 0) { /* Make minimal progress; there may be further non-empty matches. */ /* XXX - Could really advance by one whole multi-octet character. */ match_size = 1; if (!mid) mid = cur; } else { /* This function is called on a matching line only, but is it selected or rejected/context? */ if (only_matching) print_line_head (b, lim, (out_invert ? SEP_CHAR_REJECTED : SEP_CHAR_SELECTED)); else { pr_sgr_start (line_color); if (mid) { cur = mid; mid = NULL; } fwrite (cur, sizeof (char), b - cur, stdout); } pr_sgr_start_if (match_color); fwrite (b, sizeof (char), match_size, stdout); pr_sgr_end_if (match_color); if (only_matching) fputs ("\n", stdout); } cur = b + match_size; } if (only_matching) cur = lim; else if (mid) cur = mid; return cur; } static const char * print_line_tail (const char *beg, const char *lim, const char *line_color) { size_t eol_size; size_t tail_size; eol_size = (lim > beg && lim[-1] == eolbyte); eol_size += (lim - eol_size > beg && lim[-(1 + eol_size)] == '\r'); tail_size = lim - eol_size - beg; if (tail_size > 0) { pr_sgr_start (line_color); fwrite (beg, 1, tail_size, stdout); beg += tail_size; pr_sgr_end (line_color); } return beg; } static void prline (char const *beg, char const *lim, int sep) { int matching; const char *line_color; const char *match_color; if (!only_matching) print_line_head (beg, lim, sep); matching = (sep == SEP_CHAR_SELECTED) ^ !!out_invert; if (color_option) { line_color = (((sep == SEP_CHAR_SELECTED) ^ (out_invert && (color_option < 0))) ? selected_line_color : context_line_color); match_color = (sep == SEP_CHAR_SELECTED ? selected_match_color : context_match_color); } else line_color = match_color = NULL; /* Shouldn't be used. */ if ((only_matching && matching) || (color_option && (*line_color || *match_color))) { /* We already know that non-matching lines have no match (to colorize). */ if (matching && (only_matching || *match_color)) beg = print_line_middle (beg, lim, line_color, match_color); /* FIXME: this test may be removable. */ if (!only_matching && *line_color) beg = print_line_tail (beg, lim, line_color); } if (!only_matching && lim > beg) fwrite (beg, 1, lim - beg, stdout); if (ferror (stdout)) { write_error_seen = 1; error (EXIT_TROUBLE, 0, _("write error")); } lastout = lim; if (line_buffered) fflush (stdout); } /* Print pending lines of trailing context prior to LIM. Trailing context ends at the next matching line when OUTLEFT is 0. */ static void prpending (char const *lim) { if (!lastout) lastout = bufbeg; while (pending > 0 && lastout < lim) { char const *nl = memchr (lastout, eolbyte, lim - lastout); size_t match_size; --pending; if (outleft || ((execute (lastout, nl + 1 - lastout, &match_size, NULL) == (size_t) -1) == !out_invert)) prline (lastout, nl + 1, SEP_CHAR_REJECTED); else pending = 0; } } /* Print the lines between BEG and LIM. Deal with context crap. If NLINESP is non-null, store a count of lines between BEG and LIM. */ static void prtext (char const *beg, char const *lim, int *nlinesp) { /* Print the lines between BEG and LIM. Deal with context crap. If NLINESP is non-null, store a count of lines between BEG and LIM. */ static void prtext (char const *beg, char const *lim, intmax_t *nlinesp) { static int used; /* avoid printing SEP_STR_GROUP before any output */ char const *bp, *p; char eol = eolbyte; intmax_t i, n; if (!out_quiet && pending > 0) prpending (beg); /* Deal with leading context crap. */ bp = lastout ? lastout : bufbeg; for (i = 0; i < out_before; ++i) if (p > bp) do --p; while (p[-1] != eol); /* We print the SEP_STR_GROUP separator only if our output is discontiguous from the last output in the file. */ if ((out_before || out_after) && used && p != lastout && group_separator) { pr_sgr_start_if (sep_color); fputs (group_separator, stdout); pr_sgr_end_if (sep_color); fputc ('\n', stdout); } while (p < beg) { char const *nl = memchr (p, eol, beg - p); nl++; prline (p, nl, SEP_CHAR_REJECTED); p = nl; } } if (nlinesp) { /* Caller wants a line count. */ for (n = 0; p < lim && n < outleft; n++) { char const *nl = memchr (p, eol, lim - p); nl++; if (!out_quiet) prline (p, nl, SEP_CHAR_SELECTED); p = nl; } *nlinesp = n; /* relying on it that this function is never called when outleft = 0. */ after_last_match = bufoffset - (buflim - p); } else if (!out_quiet) prline (beg, lim, SEP_CHAR_SELECTED); pending = out_quiet ? 0 : out_after; used = 1; } static size_t do_execute (char const *buf, size_t size, size_t *match_size, char const *start_ptr) { size_t result; const char *line_next; /* With the current implementation, using --ignore-case with a multi-byte character set is very inefficient when applied to a large buffer containing many matches. We can avoid much of the wasted effort by matching line-by-line. FIXME: this is just an ugly workaround, and it doesn't really belong here. Also, PCRE is always using this same per-line matching algorithm. Either we fix -i, or we should refactor this code---for example, we could add another function pointer to struct matcher to split the buffer passed to execute. It would perform the memchr if line-by-line matching is necessary, or just return buf + size otherwise. */ if (MB_CUR_MAX == 1 || !match_icase) return execute (buf, size, match_size, start_ptr); for (line_next = buf; line_next < buf + size; ) { const char *line_buf = line_next; const char *line_end = memchr (line_buf, eolbyte, (buf + size) - line_buf); if (line_end == NULL) line_next = line_end = buf + size; else line_next = line_end + 1; if (start_ptr && start_ptr >= line_end) continue; result = execute (line_buf, line_next - line_buf, match_size, start_ptr); if (result != (size_t) -1) return (line_buf - buf) + result; } return (size_t) -1; } /* Scan the specified portion of the buffer, matching lines (or between matching lines if OUT_INVERT is true). Return a count of lines printed. */ static int grepbuf (char const *beg, char const *lim) /* Scan the specified portion of the buffer, matching lines (or between matching lines if OUT_INVERT is true). Return a count of lines printed. */ static intmax_t grepbuf (char const *beg, char const *lim) { intmax_t nlines, n; char const *p; size_t match_offset; size_t match_size; { char const *b = p + match_offset; char const *endp = b + match_size; /* Avoid matching the empty line at the end of the buffer. */ if (b == lim) break; if (!out_invert) { prtext (b, endp, (int *) 0); nlines++; break; if (!out_invert) { prtext (b, endp, NULL); nlines++; outleft--; if (!outleft || done_on_match) } } else if (p < b) { prtext (p, b, &n); nlines += n; outleft -= n; if (!outleft) return nlines; } p = endp; } if (out_invert && p < lim) { prtext (p, lim, &n); nlines += n; outleft -= n; } return nlines; } /* Search a given file. Normally, return a count of lines printed; but if the file is a directory and we search it recursively, then return -2 if there was a match, and -1 otherwise. */ static int grep (int fd, char const *file, struct stats *stats) /* Search a given file. Normally, return a count of lines printed; but if the file is a directory and we search it recursively, then return -2 if there was a match, and -1 otherwise. */ static intmax_t grep (int fd, char const *file, struct stats *stats) { intmax_t nlines, i; int not_text; size_t residue, save; char oldc; return 0; if (file && directories == RECURSE_DIRECTORIES && S_ISDIR (stats->stat.st_mode)) { /* Close fd now, so that we don't open a lot of file descriptors when we recurse deeply. */ if (close (fd) != 0) suppressible_error (file, errno); return grepdir (file, stats) - 2; } totalcc = 0; lastout = 0; totalnl = 0; outleft = max_count; after_last_match = 0; pending = 0; nlines = 0; residue = 0; save = 0; if (! fillbuf (save, stats)) { suppressible_error (filename, errno); return 0; } not_text = (((binary_files == BINARY_BINARY_FILES && !out_quiet) || binary_files == WITHOUT_MATCH_BINARY_FILES) && memchr (bufbeg, eol ? '\0' : '\200', buflim - bufbeg)); if (not_text && binary_files == WITHOUT_MATCH_BINARY_FILES) return 0; done_on_match += not_text; out_quiet += not_text; for (;;) { lastnl = bufbeg; if (lastout) lastout = bufbeg; beg = bufbeg + save; /* no more data to scan (eof) except for maybe a residue -> break */ if (beg == buflim) break; /* Determine new residue (the length of an incomplete line at the end of the buffer, 0 means there is no incomplete last line). */ oldc = beg[-1]; beg[-1] = eol; for (lim = buflim; lim[-1] != eol; lim--) continue; beg[-1] = oldc; if (lim == beg) lim = beg - residue; beg -= residue; residue = buflim - lim; if (beg < lim) { if (outleft) nlines += grepbuf (beg, lim); if (pending) prpending (lim); if ((!outleft && !pending) || (nlines && done_on_match && !out_invert)) goto finish_grep; } /* The last OUT_BEFORE lines at the end of the buffer will be needed as leading context if there is a matching line at the begin of the next data. Make beg point to their begin. */ i = 0; beg = lim; while (i < out_before && beg > bufbeg && beg != lastout) { ++i; do --beg; while (beg[-1] != eol); } /* detect if leading context is discontinuous from last printed line. */ if (beg != lastout) lastout = 0; /* Handle some details and read more data to scan. */ save = residue + lim - beg; if (out_byte) totalcc = add_count (totalcc, buflim - bufbeg - save); if (out_line) nlscan (beg); if (! fillbuf (save, stats)) { suppressible_error (filename, errno); goto finish_grep; } } if (residue) { *buflim++ = eol; if (outleft) nlines += grepbuf (bufbeg + save - residue, buflim); if (pending) prpending (buflim); } finish_grep: done_on_match -= not_text; out_quiet -= not_text; if ((not_text & ~out_quiet) && nlines != 0) printf (_("Binary file %s matches\n"), filename); return nlines; } static int grepfile (char const *file, struct stats *stats) { int desc; int count; int status; grepfile (char const *file, struct stats *stats) { int desc; intmax_t count; int status; filename = (file ? file : label ? label : _("(standard input)")); /* Don't open yet, since that might have side effects on a device. */ desc = -1; } else { /* When skipping directories, don't worry about directories that can't be opened. */ desc = open (file, O_RDONLY); if (desc < 0 && directories != SKIP_DIRECTORIES) { suppressible_error (file, errno); return 1; } } if (desc < 0 ? stat (file, &stats->stat) != 0 : fstat (desc, &stats->stat) != 0) { suppressible_error (filename, errno); if (file) close (desc); return 1; } if ((directories == SKIP_DIRECTORIES && S_ISDIR (stats->stat.st_mode)) || (devices == SKIP_DEVICES && (S_ISCHR (stats->stat.st_mode) || S_ISBLK (stats->stat.st_mode) || S_ISSOCK (stats->stat.st_mode) || S_ISFIFO (stats->stat.st_mode)))) { if (file) close (desc); return 1; } /* If there is a regular file on stdout and the current file refers to the same i-node, we have to report the problem and skip it. Otherwise when matching lines from some other input reach the disk before we open this file, we can end up reading and matching those lines and appending them to the file from which we're reading. Then we'd have what appears to be an infinite loop that'd terminate only upon filling the output file system or reaching a quota. However, there is no risk of an infinite loop if grep is generating no output, i.e., with --silent, --quiet, -q. Similarly, with any of these: --max-count=N (-m) (for N >= 2) --files-with-matches (-l) --files-without-match (-L) there is no risk of trouble. For --max-count=1, grep stops after printing the first match, so there is no risk of malfunction. But even --max-count=2, with input==output, while there is no risk of infloop, there is a race condition that could result in "alternate" output. */ if (!out_quiet && list_files == 0 && 1 < max_count && S_ISREG (out_stat.st_mode) && out_stat.st_ino && SAME_INODE (stats->stat, out_stat)) { if (! suppress_errors) error (0, 0, _("input file %s is also the output"), quote (filename)); errseen = 1; if (file) close (desc); return 1; } if (desc < 0) { desc = open (file, O_RDONLY); if (desc < 0) { suppressible_error (file, errno); return 1; } } #if defined SET_BINARY /* Set input to binary mode. Pipes are simulated with files on DOS, so this includes the case of "foo | grep bar". */ if (!isatty (desc)) SET_BINARY (desc); #endif count = grep (desc, file, stats); if (count < 0) status = count + 2; else { if (count_matches) { if (out_file) { print_filename (); if (filename_mask) print_sep (SEP_CHAR_SELECTED); else fputc (0, stdout); } printf ("%d\n", count); } else fputc (0, stdout); } printf ("%" PRIdMAX "\n", count); } status = !count; if (! file) { off_t required_offset = outleft ? bufoffset : after_last_match; if (required_offset != bufoffset && lseek (desc, required_offset, SEEK_SET) < 0 && S_ISREG (stats->stat.st_mode)) suppressible_error (filename, errno); } else while (close (desc) != 0) if (errno != EINTR) { suppressible_error (file, errno); break; } }
46,085,918,764,084,640,000,000,000,000,000,000,000
None
null
[ "CWE-189" ]
CVE-2012-5667
Multiple integer overflows in GNU Grep before 2.11 might allow context-dependent attackers to execute arbitrary code via vectors involving a long input line that triggers a heap-based buffer overflow.
https://nvd.nist.gov/vuln/detail/CVE-2012-5667
169
kde
a90289b0962663bc1d247bbbd31b9e65b2ca000e
https://cgit.kde.org/konversation
https://cgit.kde.org/smb4k.git/commit/?id=a90289b0962663bc1d247bbbd31b9e65b2ca000e
None
1
ActionReply Smb4KMountHelper::mount(const QVariantMap &args) { ActionReply reply; QMapIterator<QString, QVariant> it(args); proc.setOutputChannelMode(KProcess::SeparateChannels); proc.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); #if defined(Q_OS_LINUX) proc.setEnv("PASSWD", entry["mh_url"].toUrl().password(), true); #endif QVariantMap entry = it.value().toMap(); KProcess proc(this); command << entry["mh_mountpoint"].toString(); command << entry["mh_options"].toStringList(); #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) command << entry["mh_command"].toString(); command << entry["mh_options"].toStringList(); command << entry["mh_unc"].toString(); command << entry["mh_mountpoint"].toString(); #else #endif proc.setProgram(command); proc.start(); if (proc.waitForStarted(-1)) { bool userKill = false; QStringList command; #if defined(Q_OS_LINUX) command << entry["mh_command"].toString(); command << entry["mh_unc"].toString(); command << entry["mh_mountpoint"].toString(); command << entry["mh_options"].toStringList(); #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) command << entry["mh_command"].toString(); command << entry["mh_options"].toStringList(); command << entry["mh_unc"].toString(); command << entry["mh_mountpoint"].toString(); else { } if (HelperSupport::isStopped()) { proc.kill(); userKill = true; break; } else { } } if (proc.exitStatus() == KProcess::CrashExit) { if (!userKill) { reply.setType(ActionReply::HelperErrorType); reply.setErrorDescription(i18n("The mount process crashed.")); break; } else { } } else { QString stdErr = QString::fromUtf8(proc.readAllStandardError()); reply.addData(QString("mh_error_message_%1").arg(index), stdErr.trimmed()); } }
171,260,334,698,845,350,000,000,000,000,000,000,000
None
null
[ "CWE-20" ]
CVE-2017-8849
smb4k before 2.0.1 allows local users to gain root privileges by leveraging failure to verify arguments to the mount helper DBUS service.
https://nvd.nist.gov/vuln/detail/CVE-2017-8849
158,029
kde
a90289b0962663bc1d247bbbd31b9e65b2ca000e
https://cgit.kde.org/konversation
https://cgit.kde.org/smb4k.git/commit/?id=a90289b0962663bc1d247bbbd31b9e65b2ca000e
None
0
ActionReply Smb4KMountHelper::mount(const QVariantMap &args) { // // The action reply // ActionReply reply; // Get the mount executable // const QString mount = findMountExecutable(); // QMapIterator<QString, QVariant> it(args); proc.setOutputChannelMode(KProcess::SeparateChannels); proc.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); #if defined(Q_OS_LINUX) proc.setEnv("PASSWD", entry["mh_url"].toUrl().password(), true); #endif QVariantMap entry = it.value().toMap(); // Check the executable // if (mount != entry["mh_command"].toString()) { // Something weird is going on, bail out. reply.setType(ActionReply::HelperErrorType); return reply; } else { // Do nothing } // KProcess proc(this); command << entry["mh_mountpoint"].toString(); command << entry["mh_options"].toStringList(); #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) command << entry["mh_command"].toString(); command << entry["mh_options"].toStringList(); command << entry["mh_unc"].toString(); command << entry["mh_mountpoint"].toString(); #else #endif proc.setProgram(command); proc.start(); if (proc.waitForStarted(-1)) { bool userKill = false; QStringList command; #if defined(Q_OS_LINUX) command << mount; command << entry["mh_unc"].toString(); command << entry["mh_mountpoint"].toString(); command << entry["mh_options"].toStringList(); #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) command << mount; command << entry["mh_options"].toStringList(); command << entry["mh_unc"].toString(); command << entry["mh_mountpoint"].toString(); else { } if (HelperSupport::isStopped()) { proc.kill(); userKill = true; break; } else { } } if (proc.exitStatus() == KProcess::CrashExit) { if (!userKill) { reply.setType(ActionReply::HelperErrorType); reply.setErrorDescription(i18n("The mount process crashed.")); break; } else { } } else { QString stdErr = QString::fromUtf8(proc.readAllStandardError()); reply.addData(QString("mh_error_message_%1").arg(index), stdErr.trimmed()); } }
200,905,717,068,882,130,000,000,000,000,000,000,000
None
null
[ "CWE-20" ]
CVE-2017-8849
smb4k before 2.0.1 allows local users to gain root privileges by leveraging failure to verify arguments to the mount helper DBUS service.
https://nvd.nist.gov/vuln/detail/CVE-2017-8849
177
savannah
df14e6c0b9592cbb24d5381dfc6106b14f915e75
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=df14e6c0b9592cbb24d5381dfc6106b14f915e75
None
1
parse_encoding( T1_Face face, T1_Loader loader ) { T1_Parser parser = &loader->parser; FT_Byte* cur; FT_Byte* limit = parser->root.limit; PSAux_Service psaux = (PSAux_Service)face->psaux; T1_Skip_Spaces( parser ); cur = parser->root.cursor; if ( cur >= limit ) { FT_ERROR(( "parse_encoding: out of bounds\n" )); parser->root.error = FT_THROW( Invalid_File_Format ); return; } /* if we have a number or `[', the encoding is an array, */ /* and we must load it now */ if ( ft_isdigit( *cur ) || *cur == '[' ) { T1_Encoding encode = &face->type1.encoding; FT_Int count, n; PS_Table char_table = &loader->encoding_table; FT_Memory memory = parser->root.memory; FT_Error error; FT_Bool only_immediates = 0; /* read the number of entries in the encoding; should be 256 */ if ( *cur == '[' ) { count = 256; only_immediates = 1; parser->root.cursor++; } else count = (FT_Int)T1_ToInt( parser ); T1_Skip_Spaces( parser ); if ( parser->root.cursor >= limit ) return; /* we use a T1_Table to store our charnames */ loader->num_chars = encode->num_chars = count; if ( FT_NEW_ARRAY( encode->char_index, count ) || FT_NEW_ARRAY( encode->char_name, count ) || FT_SET_ERROR( psaux->ps_table_funcs->init( char_table, count, memory ) ) ) { parser->root.error = error; return; } /* We need to `zero' out encoding_table.elements */ for ( n = 0; n < count; n++ ) { char* notdef = (char *)".notdef"; T1_Add_Table( char_table, n, notdef, 8 ); } /* Now we need to read records of the form */ /* */ /* ... charcode /charname ... */ /* */ /* for each entry in our table. */ /* */ /* We simply look for a number followed by an immediate */ /* name. Note that this ignores correctly the sequence */ /* that is often seen in type1 fonts: */ /* */ /* 0 1 255 { 1 index exch /.notdef put } for dup */ /* */ /* used to clean the encoding array before anything else. */ /* */ /* Alternatively, if the array is directly given as */ /* */ /* /Encoding [ ... ] */ /* */ /* we only read immediates. */ n = 0; T1_Skip_Spaces( parser ); while ( parser->root.cursor < limit ) { cur = parser->root.cursor; /* we stop when we encounter a `def' or `]' */ if ( *cur == 'd' && cur + 3 < limit ) { if ( cur[1] == 'e' && cur[2] == 'f' && IS_PS_DELIM( cur[3] ) ) { FT_TRACE6(( "encoding end\n" )); cur += 3; break; } } if ( *cur == ']' ) { FT_TRACE6(( "encoding end\n" )); cur++; break; } /* check whether we've found an entry */ if ( ft_isdigit( *cur ) || only_immediates ) { FT_Int charcode; if ( only_immediates ) charcode = n; else { charcode = (FT_Int)T1_ToInt( parser ); T1_Skip_Spaces( parser ); } cur = parser->root.cursor; parser->root.cursor = cur; T1_Skip_PS_Token( parser ); if ( parser->root.cursor >= limit ) return; if ( parser->root.error ) return; len = parser->root.cursor - cur; parser->root.error = T1_Add_Table( char_table, charcode, cur, len + 1 ); if ( parser->root.error ) return; char_table->elements[charcode][len] = '\0'; n++; } else if ( only_immediates ) { /* Since the current position is not updated for */ /* immediates-only mode we would get an infinite loop if */ /* we don't do anything here. */ /* */ /* This encoding array is not valid according to the type1 */ /* specification (it might be an encoding for a CID type1 */ /* font, however), so we conclude that this font is NOT a */ /* type1 font. */ parser->root.error = FT_THROW( Unknown_File_Format ); return; } } else { T1_Skip_PS_Token( parser ); if ( parser->root.error ) return; } T1_Skip_Spaces( parser ); } face->type1.encoding_type = T1_ENCODING_TYPE_ARRAY; parser->root.cursor = cur; }
272,856,134,003,844,800,000,000,000,000,000,000,000
None
null
[ "CWE-399" ]
CVE-2014-9745
The parse_encoding function in type1/t1load.c in FreeType before 2.5.3 allows remote attackers to cause a denial of service (infinite loop) via a "broken number-with-base" in a Postscript stream, as demonstrated by 8#garbage.
https://nvd.nist.gov/vuln/detail/CVE-2014-9745
158,037
savannah
df14e6c0b9592cbb24d5381dfc6106b14f915e75
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=df14e6c0b9592cbb24d5381dfc6106b14f915e75
None
0
parse_encoding( T1_Face face, T1_Loader loader ) { T1_Parser parser = &loader->parser; FT_Byte* cur; FT_Byte* limit = parser->root.limit; PSAux_Service psaux = (PSAux_Service)face->psaux; T1_Skip_Spaces( parser ); cur = parser->root.cursor; if ( cur >= limit ) { FT_ERROR(( "parse_encoding: out of bounds\n" )); parser->root.error = FT_THROW( Invalid_File_Format ); return; } /* if we have a number or `[', the encoding is an array, */ /* and we must load it now */ if ( ft_isdigit( *cur ) || *cur == '[' ) { T1_Encoding encode = &face->type1.encoding; FT_Int count, n; PS_Table char_table = &loader->encoding_table; FT_Memory memory = parser->root.memory; FT_Error error; FT_Bool only_immediates = 0; /* read the number of entries in the encoding; should be 256 */ if ( *cur == '[' ) { count = 256; only_immediates = 1; parser->root.cursor++; } else count = (FT_Int)T1_ToInt( parser ); T1_Skip_Spaces( parser ); if ( parser->root.cursor >= limit ) return; /* we use a T1_Table to store our charnames */ loader->num_chars = encode->num_chars = count; if ( FT_NEW_ARRAY( encode->char_index, count ) || FT_NEW_ARRAY( encode->char_name, count ) || FT_SET_ERROR( psaux->ps_table_funcs->init( char_table, count, memory ) ) ) { parser->root.error = error; return; } /* We need to `zero' out encoding_table.elements */ for ( n = 0; n < count; n++ ) { char* notdef = (char *)".notdef"; T1_Add_Table( char_table, n, notdef, 8 ); } /* Now we need to read records of the form */ /* */ /* ... charcode /charname ... */ /* */ /* for each entry in our table. */ /* */ /* We simply look for a number followed by an immediate */ /* name. Note that this ignores correctly the sequence */ /* that is often seen in type1 fonts: */ /* */ /* 0 1 255 { 1 index exch /.notdef put } for dup */ /* */ /* used to clean the encoding array before anything else. */ /* */ /* Alternatively, if the array is directly given as */ /* */ /* /Encoding [ ... ] */ /* */ /* we only read immediates. */ n = 0; T1_Skip_Spaces( parser ); while ( parser->root.cursor < limit ) { cur = parser->root.cursor; /* we stop when we encounter a `def' or `]' */ if ( *cur == 'd' && cur + 3 < limit ) { if ( cur[1] == 'e' && cur[2] == 'f' && IS_PS_DELIM( cur[3] ) ) { FT_TRACE6(( "encoding end\n" )); cur += 3; break; } } if ( *cur == ']' ) { FT_TRACE6(( "encoding end\n" )); cur++; break; } /* check whether we've found an entry */ if ( ft_isdigit( *cur ) || only_immediates ) { FT_Int charcode; if ( only_immediates ) charcode = n; else { charcode = (FT_Int)T1_ToInt( parser ); T1_Skip_Spaces( parser ); /* protect against invalid charcode */ if ( cur == parser->root.cursor ) { parser->root.error = FT_THROW( Unknown_File_Format ); return; } } cur = parser->root.cursor; parser->root.cursor = cur; T1_Skip_PS_Token( parser ); if ( parser->root.cursor >= limit ) return; if ( parser->root.error ) return; len = parser->root.cursor - cur; parser->root.error = T1_Add_Table( char_table, charcode, cur, len + 1 ); if ( parser->root.error ) return; char_table->elements[charcode][len] = '\0'; n++; } else if ( only_immediates ) { /* Since the current position is not updated for */ /* immediates-only mode we would get an infinite loop if */ /* we don't do anything here. */ /* */ /* This encoding array is not valid according to the type1 */ /* specification (it might be an encoding for a CID type1 */ /* font, however), so we conclude that this font is NOT a */ /* type1 font. */ parser->root.error = FT_THROW( Unknown_File_Format ); return; } } else { T1_Skip_PS_Token( parser ); if ( parser->root.error ) return; } T1_Skip_Spaces( parser ); } face->type1.encoding_type = T1_ENCODING_TYPE_ARRAY; parser->root.cursor = cur; }
311,321,372,754,373,600,000,000,000,000,000,000,000
None
null
[ "CWE-399" ]
CVE-2014-9745
The parse_encoding function in type1/t1load.c in FreeType before 2.5.3 allows remote attackers to cause a denial of service (infinite loop) via a "broken number-with-base" in a Postscript stream, as demonstrated by 8#garbage.
https://nvd.nist.gov/vuln/detail/CVE-2014-9745
178
haproxy
17514045e5d934dede62116216c1b016fe23dd06
https://github.com/haproxy/haproxy
https://git.haproxy.org/?p=haproxy-1.8.git;a=commit;h=17514045e5d934dede62116216c1b016fe23dd06
None
1
void check_request_for_cacheability(struct stream *s, struct channel *chn) { struct http_txn *txn = s->txn; char *p1, *p2; char *cur_ptr, *cur_end, *cur_next; int pragma_found; int cc_found; int cur_idx; if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE) return; /* nothing more to do here */ cur_idx = 0; pragma_found = cc_found = 0; cur_next = chn->buf->p + hdr_idx_first_pos(&txn->hdr_idx); while ((cur_idx = txn->hdr_idx.v[cur_idx].next)) { struct hdr_idx_elem *cur_hdr; int val; cur_hdr = &txn->hdr_idx.v[cur_idx]; cur_ptr = cur_next; cur_end = cur_ptr + cur_hdr->len; cur_next = cur_end + cur_hdr->cr + 1; /* We have one full header between cur_ptr and cur_end, and the * next header starts at cur_next. */ val = http_header_match2(cur_ptr, cur_end, "Pragma", 6); if (val) { if ((cur_end - (cur_ptr + val) >= 8) && strncasecmp(cur_ptr + val, "no-cache", 8) == 0) { pragma_found = 1; continue; } } val = http_header_match2(cur_ptr, cur_end, "Cache-control", 13); if (!val) continue; p2 = p1; while (p2 < cur_end && *p2 != '=' && *p2 != ',' && !isspace((unsigned char)*p2)) p2++; /* we have a complete value between p1 and p2. We don't check the * values after max-age, max-stale nor min-fresh, we simply don't * use the cache when they're specified. */ if (((p2 - p1 == 7) && strncasecmp(p1, "max-age", 7) == 0) || ((p2 - p1 == 8) && strncasecmp(p1, "no-cache", 8) == 0) || ((p2 - p1 == 9) && strncasecmp(p1, "max-stale", 9) == 0) || ((p2 - p1 == 9) && strncasecmp(p1, "min-fresh", 9) == 0)) { txn->flags |= TX_CACHE_IGNORE; continue; } if ((p2 - p1 == 8) && strncasecmp(p1, "no-store", 8) == 0) { txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK; continue; } } /* RFC7234#5.4: * When the Cache-Control header field is also present and * understood in a request, Pragma is ignored. * When the Cache-Control header field is not present in a * request, caches MUST consider the no-cache request * pragma-directive as having the same effect as if * "Cache-Control: no-cache" were present. */ if (!cc_found && pragma_found) txn->flags |= TX_CACHE_IGNORE; }
324,327,278,202,769,570,000,000,000,000,000,000,000
None
null
[ "CWE-200" ]
CVE-2018-11469
Incorrect caching of responses to requests including an Authorization header in HAProxy 1.8.0 through 1.8.9 (if cache enabled) allows attackers to achieve information disclosure via an unauthenticated remote request, related to the proto_http.c check_request_for_cacheability function.
https://nvd.nist.gov/vuln/detail/CVE-2018-11469
158,038
haproxy
17514045e5d934dede62116216c1b016fe23dd06
https://github.com/haproxy/haproxy
https://git.haproxy.org/?p=haproxy-1.8.git;a=commit;h=17514045e5d934dede62116216c1b016fe23dd06
None
0
void check_request_for_cacheability(struct stream *s, struct channel *chn) { struct http_txn *txn = s->txn; char *p1, *p2; char *cur_ptr, *cur_end, *cur_next; int pragma_found; int cc_found; int cur_idx; if ((txn->flags & (TX_CACHEABLE|TX_CACHE_IGNORE)) == TX_CACHE_IGNORE) return; /* nothing more to do here */ cur_idx = 0; pragma_found = cc_found = 0; cur_next = chn->buf->p + hdr_idx_first_pos(&txn->hdr_idx); while ((cur_idx = txn->hdr_idx.v[cur_idx].next)) { struct hdr_idx_elem *cur_hdr; int val; cur_hdr = &txn->hdr_idx.v[cur_idx]; cur_ptr = cur_next; cur_end = cur_ptr + cur_hdr->len; cur_next = cur_end + cur_hdr->cr + 1; /* We have one full header between cur_ptr and cur_end, and the * next header starts at cur_next. */ val = http_header_match2(cur_ptr, cur_end, "Pragma", 6); if (val) { if ((cur_end - (cur_ptr + val) >= 8) && strncasecmp(cur_ptr + val, "no-cache", 8) == 0) { pragma_found = 1; continue; } } /* Don't use the cache and don't try to store if we found the * Authorization header */ val = http_header_match2(cur_ptr, cur_end, "Authorization", 13); if (val) { txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK; txn->flags |= TX_CACHE_IGNORE; continue; } val = http_header_match2(cur_ptr, cur_end, "Cache-control", 13); if (!val) continue; p2 = p1; while (p2 < cur_end && *p2 != '=' && *p2 != ',' && !isspace((unsigned char)*p2)) p2++; /* we have a complete value between p1 and p2. We don't check the * values after max-age, max-stale nor min-fresh, we simply don't * use the cache when they're specified. */ if (((p2 - p1 == 7) && strncasecmp(p1, "max-age", 7) == 0) || ((p2 - p1 == 8) && strncasecmp(p1, "no-cache", 8) == 0) || ((p2 - p1 == 9) && strncasecmp(p1, "max-stale", 9) == 0) || ((p2 - p1 == 9) && strncasecmp(p1, "min-fresh", 9) == 0)) { txn->flags |= TX_CACHE_IGNORE; continue; } if ((p2 - p1 == 8) && strncasecmp(p1, "no-store", 8) == 0) { txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK; continue; } } /* RFC7234#5.4: * When the Cache-Control header field is also present and * understood in a request, Pragma is ignored. * When the Cache-Control header field is not present in a * request, caches MUST consider the no-cache request * pragma-directive as having the same effect as if * "Cache-Control: no-cache" were present. */ if (!cc_found && pragma_found) txn->flags |= TX_CACHE_IGNORE; }
134,270,212,007,884,860,000,000,000,000,000,000,000
None
null
[ "CWE-200" ]
CVE-2018-11469
Incorrect caching of responses to requests including an Authorization header in HAProxy 1.8.0 through 1.8.9 (if cache enabled) allows attackers to achieve information disclosure via an unauthenticated remote request, related to the proto_http.c check_request_for_cacheability function.
https://nvd.nist.gov/vuln/detail/CVE-2018-11469
179
savannah
18a8f0d9943369449bc4de92d411c78fb08d616c
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=18a8f0d9943369449bc4de92d411c78fb08d616c
None
1
parse_fond( char* fond_data, short* have_sfnt, ResID* sfnt_id, Str255 lwfn_file_name, short face_index ) { AsscEntry* assoc; AsscEntry* base_assoc; FamRec* fond; *sfnt_id = 0; *have_sfnt = 0; lwfn_file_name[0] = 0; fond = (FamRec*)fond_data; assoc = (AsscEntry*)( fond_data + sizeof ( FamRec ) + 2 ); base_assoc = assoc; /* the maximum faces in a FOND is 48, size of StyleTable.indexes[] */ if ( 47 < face_index ) return; /* Let's do a little range checking before we get too excited here */ if ( face_index < count_faces_sfnt( fond_data ) ) { assoc += face_index; /* add on the face_index! */ /* if the face at this index is not scalable, fall back to the first one (old behavior) */ if ( EndianS16_BtoN( assoc->fontSize ) == 0 ) { *have_sfnt = 1; *sfnt_id = EndianS16_BtoN( assoc->fontID ); } else if ( base_assoc->fontSize == 0 ) { *have_sfnt = 1; *sfnt_id = EndianS16_BtoN( base_assoc->fontID ); } } if ( EndianS32_BtoN( fond->ffStylOff ) ) { unsigned char* p = (unsigned char*)fond_data; StyleTable* style; unsigned short string_count; char ps_name[256]; unsigned char* names[64]; int i; p += EndianS32_BtoN( fond->ffStylOff ); style = (StyleTable*)p; p += sizeof ( StyleTable ); string_count = EndianS16_BtoN( *(short*)(p) ); p += sizeof ( short ); for ( i = 0; i < string_count && i < 64; i++ ) { names[i] = p; p += names[i][0]; } { size_t ps_name_len = (size_t)names[0][0]; if ( ps_name_len != 0 ) { ft_memcpy(ps_name, names[0] + 1, ps_name_len); ps_name[ps_name_len] = 0; ps_name[ps_name_len] = 0; } if ( style->indexes[face_index] > 1 && style->indexes[face_index] <= FT_MIN( string_count, 64 ) ) { unsigned char* suffixes = names[style->indexes[face_index] - 1]; for ( i = 1; i <= suffixes[0]; i++ ) { unsigned char* s; size_t j = suffixes[i] - 1; if ( j < string_count && ( s = names[j] ) != NULL ) { size_t s_len = (size_t)s[0]; if ( s_len != 0 && ps_name_len + s_len < sizeof ( ps_name ) ) { ft_memcpy( ps_name + ps_name_len, s + 1, s_len ); ps_name_len += s_len; ps_name[ps_name_len] = 0; } } } } } create_lwfn_name( ps_name, lwfn_file_name ); } }
233,045,259,701,863,800,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2014-9672
Array index error in the parse_fond function in base/ftmac.c in FreeType before 2.5.4 allows remote attackers to cause a denial of service (out-of-bounds read) or obtain sensitive information from process memory via a crafted FOND resource in a Mac font file.
https://nvd.nist.gov/vuln/detail/CVE-2014-9672
158,039
savannah
18a8f0d9943369449bc4de92d411c78fb08d616c
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=18a8f0d9943369449bc4de92d411c78fb08d616c
None
0
parse_fond( char* fond_data, short* have_sfnt, ResID* sfnt_id, Str255 lwfn_file_name, short face_index ) { AsscEntry* assoc; AsscEntry* base_assoc; FamRec* fond; *sfnt_id = 0; *have_sfnt = 0; lwfn_file_name[0] = 0; fond = (FamRec*)fond_data; assoc = (AsscEntry*)( fond_data + sizeof ( FamRec ) + 2 ); base_assoc = assoc; /* the maximum faces in a FOND is 48, size of StyleTable.indexes[] */ if ( 47 < face_index ) return; /* Let's do a little range checking before we get too excited here */ if ( face_index < count_faces_sfnt( fond_data ) ) { assoc += face_index; /* add on the face_index! */ /* if the face at this index is not scalable, fall back to the first one (old behavior) */ if ( EndianS16_BtoN( assoc->fontSize ) == 0 ) { *have_sfnt = 1; *sfnt_id = EndianS16_BtoN( assoc->fontID ); } else if ( base_assoc->fontSize == 0 ) { *have_sfnt = 1; *sfnt_id = EndianS16_BtoN( base_assoc->fontID ); } } if ( EndianS32_BtoN( fond->ffStylOff ) ) { unsigned char* p = (unsigned char*)fond_data; StyleTable* style; unsigned short string_count; char ps_name[256]; unsigned char* names[64]; int i; p += EndianS32_BtoN( fond->ffStylOff ); style = (StyleTable*)p; p += sizeof ( StyleTable ); string_count = EndianS16_BtoN( *(short*)(p) ); string_count = FT_MIN( 64, string_count ); p += sizeof ( short ); for ( i = 0; i < string_count; i++ ) { names[i] = p; p += names[i][0]; } { size_t ps_name_len = (size_t)names[0][0]; if ( ps_name_len != 0 ) { ft_memcpy(ps_name, names[0] + 1, ps_name_len); ps_name[ps_name_len] = 0; ps_name[ps_name_len] = 0; } if ( style->indexes[face_index] > 1 && style->indexes[face_index] <= string_count ) { unsigned char* suffixes = names[style->indexes[face_index] - 1]; for ( i = 1; i <= suffixes[0]; i++ ) { unsigned char* s; size_t j = suffixes[i] - 1; if ( j < string_count && ( s = names[j] ) != NULL ) { size_t s_len = (size_t)s[0]; if ( s_len != 0 && ps_name_len + s_len < sizeof ( ps_name ) ) { ft_memcpy( ps_name + ps_name_len, s + 1, s_len ); ps_name_len += s_len; ps_name[ps_name_len] = 0; } } } } } create_lwfn_name( ps_name, lwfn_file_name ); } }
183,885,571,031,352,650,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2014-9672
Array index error in the parse_fond function in base/ftmac.c in FreeType before 2.5.4 allows remote attackers to cause a denial of service (out-of-bounds read) or obtain sensitive information from process memory via a crafted FOND resource in a Mac font file.
https://nvd.nist.gov/vuln/detail/CVE-2014-9672
181
savannah
ef1eba75187adfac750f326b563fe543dd5ff4e6
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=ef1eba75187adfac750f326b563fe543dd5ff4e6
None
1
pcf_get_encodings( FT_Stream stream, PCF_Face face ) { FT_Error error; FT_Memory memory = FT_FACE( face )->memory; FT_ULong format, size; int firstCol, lastCol; int firstRow, lastRow; int nencoding, encodingOffset; int i, j, k; PCF_Encoding encoding = NULL; error = pcf_seek_to_table_type( stream, face->toc.tables, face->toc.count, PCF_BDF_ENCODINGS, &format, &size ); if ( error ) return error; error = FT_Stream_EnterFrame( stream, 14 ); if ( error ) return error; format = FT_GET_ULONG_LE(); if ( PCF_BYTE_ORDER( format ) == MSBFirst ) { firstCol = FT_GET_SHORT(); lastCol = FT_GET_SHORT(); firstRow = FT_GET_SHORT(); lastRow = FT_GET_SHORT(); face->defaultChar = FT_GET_SHORT(); } else { firstCol = FT_GET_SHORT_LE(); lastCol = FT_GET_SHORT_LE(); firstRow = FT_GET_SHORT_LE(); lastRow = FT_GET_SHORT_LE(); face->defaultChar = FT_GET_SHORT_LE(); } FT_Stream_ExitFrame( stream ); if ( !PCF_FORMAT_MATCH( format, PCF_DEFAULT_FORMAT ) ) return FT_THROW( Invalid_File_Format ); FT_TRACE4(( "pdf_get_encodings:\n" )); FT_TRACE4(( " firstCol %d, lastCol %d, firstRow %d, lastRow %d\n", goto Bail; k = 0; for ( i = firstRow; i <= lastRow; i++ ) { for ( j = firstCol; j <= lastCol; j++ ) { if ( PCF_BYTE_ORDER( format ) == MSBFirst ) encodingOffset = FT_GET_SHORT(); else encodingOffset = FT_GET_SHORT_LE(); if ( encodingOffset != -1 ) { encoding[k].enc = i * 256 + j; encoding[k].glyph = (FT_Short)encodingOffset; FT_TRACE5(( " code %d (0x%04X): idx %d\n", encoding[k].enc, encoding[k].enc, encoding[k].glyph )); k++; } } } FT_Stream_ExitFrame( stream ); if ( FT_RENEW_ARRAY( encoding, nencoding, k ) ) goto Bail; face->nencodings = k; face->encodings = encoding; return error; Bail: FT_FREE( encoding ); return error; }
176,043,909,406,430,600,000,000,000,000,000,000,000
None
null
[ "CWE-189" ]
CVE-2014-9670
Multiple integer signedness errors in the pcf_get_encodings function in pcf/pcfread.c in FreeType before 2.5.4 allow remote attackers to cause a denial of service (integer overflow, NULL pointer dereference, and application crash) via a crafted PCF file that specifies negative values for the first column and first row.
https://nvd.nist.gov/vuln/detail/CVE-2014-9670
158,041
savannah
ef1eba75187adfac750f326b563fe543dd5ff4e6
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=ef1eba75187adfac750f326b563fe543dd5ff4e6
None
0
pcf_get_encodings( FT_Stream stream, PCF_Face face ) { FT_Error error; FT_Memory memory = FT_FACE( face )->memory; FT_ULong format, size; int firstCol, lastCol; int firstRow, lastRow; int nencoding, encodingOffset; int i, j, k; PCF_Encoding encoding = NULL; error = pcf_seek_to_table_type( stream, face->toc.tables, face->toc.count, PCF_BDF_ENCODINGS, &format, &size ); if ( error ) return error; error = FT_Stream_EnterFrame( stream, 14 ); if ( error ) return error; format = FT_GET_ULONG_LE(); if ( PCF_BYTE_ORDER( format ) == MSBFirst ) { firstCol = FT_GET_SHORT(); lastCol = FT_GET_SHORT(); firstRow = FT_GET_SHORT(); lastRow = FT_GET_SHORT(); face->defaultChar = FT_GET_SHORT(); } else { firstCol = FT_GET_SHORT_LE(); lastCol = FT_GET_SHORT_LE(); firstRow = FT_GET_SHORT_LE(); lastRow = FT_GET_SHORT_LE(); face->defaultChar = FT_GET_SHORT_LE(); } FT_Stream_ExitFrame( stream ); if ( !PCF_FORMAT_MATCH( format, PCF_DEFAULT_FORMAT ) ) return FT_THROW( Invalid_File_Format ); /* sanity checks */ if ( firstCol < 0 || firstCol > lastCol || lastCol > 0xFF || firstRow < 0 || firstRow > lastRow || lastRow > 0xFF ) return FT_THROW( Invalid_Table ); FT_TRACE4(( "pdf_get_encodings:\n" )); FT_TRACE4(( " firstCol %d, lastCol %d, firstRow %d, lastRow %d\n", goto Bail; k = 0; for ( i = firstRow; i <= lastRow; i++ ) { for ( j = firstCol; j <= lastCol; j++ ) { if ( PCF_BYTE_ORDER( format ) == MSBFirst ) encodingOffset = FT_GET_SHORT(); else encodingOffset = FT_GET_SHORT_LE(); if ( encodingOffset != -1 ) { encoding[k].enc = i * 256 + j; encoding[k].glyph = (FT_Short)encodingOffset; FT_TRACE5(( " code %d (0x%04X): idx %d\n", encoding[k].enc, encoding[k].enc, encoding[k].glyph )); k++; } } } FT_Stream_ExitFrame( stream ); if ( FT_RENEW_ARRAY( encoding, nencoding, k ) ) goto Bail; face->nencodings = k; face->encodings = encoding; return error; Bail: FT_FREE( encoding ); return error; }
65,067,616,049,209,970,000,000,000,000,000,000,000
None
null
[ "CWE-189" ]
CVE-2014-9670
Multiple integer signedness errors in the pcf_get_encodings function in pcf/pcfread.c in FreeType before 2.5.4 allow remote attackers to cause a denial of service (integer overflow, NULL pointer dereference, and application crash) via a crafted PCF file that specifies negative values for the first column and first row.
https://nvd.nist.gov/vuln/detail/CVE-2014-9670
182
savannah
602040b1112c9f94d68e200be59ea7ac3d104565
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=602040b1112c9f94d68e200be59ea7ac3d104565
None
1
tt_cmap8_validate( FT_Byte* table, FT_Validator valid ) { FT_Byte* p = table + 4; FT_Byte* is32; FT_UInt32 length; FT_UInt32 num_groups; if ( table + 16 + 8192 > valid->limit ) FT_INVALID_TOO_SHORT; length = TT_NEXT_ULONG( p ); if ( length > (FT_UInt32)( valid->limit - table ) || length < 8192 + 16 ) FT_INVALID_TOO_SHORT; is32 = table + 12; p = is32 + 8192; /* skip `is32' array */ num_groups = TT_NEXT_ULONG( p ); if ( p + num_groups * 12 > valid->limit ) FT_INVALID_TOO_SHORT; /* check groups, they must be in increasing order */ FT_UInt32 n, start, end, start_id, count, last = 0; for ( n = 0; n < num_groups; n++ ) { FT_UInt hi, lo; start = TT_NEXT_ULONG( p ); end = TT_NEXT_ULONG( p ); start_id = TT_NEXT_ULONG( p ); if ( start > end ) FT_INVALID_DATA; if ( n > 0 && start <= last ) FT_INVALID_DATA; if ( valid->level >= FT_VALIDATE_TIGHT ) { if ( start_id + end - start >= TT_VALID_GLYPH_COUNT( valid ) ) FT_INVALID_GLYPH_ID; count = (FT_UInt32)( end - start + 1 ); { hi = (FT_UInt)( start >> 16 ); lo = (FT_UInt)( start & 0xFFFFU ); if ( (is32[hi >> 3] & ( 0x80 >> ( hi & 7 ) ) ) == 0 ) FT_INVALID_DATA; if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) == 0 ) FT_INVALID_DATA; } } else { /* start_hi == 0; check that is32[i] is 0 for each i in */ /* the range [start..end] */ /* end_hi cannot be != 0! */ if ( end & ~0xFFFFU ) FT_INVALID_DATA; for ( ; count > 0; count--, start++ ) { lo = (FT_UInt)( start & 0xFFFFU ); if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) != 0 ) FT_INVALID_DATA; } } } last = end; }
66,140,172,033,877,380,000,000,000,000,000,000,000
None
null
[ "CWE-125" ]
CVE-2014-9669
Multiple integer overflows in sfnt/ttcmap.c in FreeType before 2.5.4 allow remote attackers to cause a denial of service (out-of-bounds read or memory corruption) or possibly have unspecified other impact via a crafted cmap SFNT table.
https://nvd.nist.gov/vuln/detail/CVE-2014-9669
158,042
savannah
602040b1112c9f94d68e200be59ea7ac3d104565
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=602040b1112c9f94d68e200be59ea7ac3d104565
None
0
tt_cmap8_validate( FT_Byte* table, FT_Validator valid ) { FT_Byte* p = table + 4; FT_Byte* is32; FT_UInt32 length; FT_UInt32 num_groups; if ( table + 16 + 8192 > valid->limit ) FT_INVALID_TOO_SHORT; length = TT_NEXT_ULONG( p ); if ( length > (FT_UInt32)( valid->limit - table ) || length < 8192 + 16 ) FT_INVALID_TOO_SHORT; is32 = table + 12; p = is32 + 8192; /* skip `is32' array */ num_groups = TT_NEXT_ULONG( p ); /* p + num_groups * 12 > valid->limit ? */ if ( num_groups > (FT_UInt32)( valid->limit - p ) / 12 ) FT_INVALID_TOO_SHORT; /* check groups, they must be in increasing order */ FT_UInt32 n, start, end, start_id, count, last = 0; for ( n = 0; n < num_groups; n++ ) { FT_UInt hi, lo; start = TT_NEXT_ULONG( p ); end = TT_NEXT_ULONG( p ); start_id = TT_NEXT_ULONG( p ); if ( start > end ) FT_INVALID_DATA; if ( n > 0 && start <= last ) FT_INVALID_DATA; if ( valid->level >= FT_VALIDATE_TIGHT ) { FT_UInt32 d = end - start; /* start_id + end - start >= TT_VALID_GLYPH_COUNT( valid ) ? */ if ( d > TT_VALID_GLYPH_COUNT( valid ) || start_id >= TT_VALID_GLYPH_COUNT( valid ) - d ) FT_INVALID_GLYPH_ID; count = (FT_UInt32)( end - start + 1 ); { hi = (FT_UInt)( start >> 16 ); lo = (FT_UInt)( start & 0xFFFFU ); if ( (is32[hi >> 3] & ( 0x80 >> ( hi & 7 ) ) ) == 0 ) FT_INVALID_DATA; if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) == 0 ) FT_INVALID_DATA; } } else { /* start_hi == 0; check that is32[i] is 0 for each i in */ /* the range [start..end] */ /* end_hi cannot be != 0! */ if ( end & ~0xFFFFU ) FT_INVALID_DATA; for ( ; count > 0; count--, start++ ) { lo = (FT_UInt)( start & 0xFFFFU ); if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) != 0 ) FT_INVALID_DATA; } } } last = end; }
38,750,717,614,291,200,000,000,000,000,000,000,000
None
null
[ "CWE-125" ]
CVE-2014-9669
Multiple integer overflows in sfnt/ttcmap.c in FreeType before 2.5.4 allow remote attackers to cause a denial of service (out-of-bounds read or memory corruption) or possibly have unspecified other impact via a crafted cmap SFNT table.
https://nvd.nist.gov/vuln/detail/CVE-2014-9669
183
savannah
257c270bd25e15890190a28a1456e7623bba4439
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=257c270bd25e15890190a28a1456e7623bba4439
None
1
tt_sbit_decoder_init( TT_SBitDecoder decoder, TT_Face face, FT_ULong strike_index, TT_SBit_MetricsRec* metrics ) { FT_Error error; FT_Stream stream = face->root.stream; FT_ULong ebdt_size; error = face->goto_table( face, TTAG_CBDT, stream, &ebdt_size ); if ( error ) error = face->goto_table( face, TTAG_EBDT, stream, &ebdt_size ); if ( error ) error = face->goto_table( face, TTAG_bdat, stream, &ebdt_size ); if ( error ) goto Exit; decoder->face = face; decoder->stream = stream; decoder->bitmap = &face->root.glyph->bitmap; decoder->metrics = metrics; decoder->metrics_loaded = 0; decoder->bitmap_allocated = 0; decoder->ebdt_start = FT_STREAM_POS(); decoder->ebdt_size = ebdt_size; decoder->eblc_base = face->sbit_table; decoder->eblc_limit = face->sbit_table + face->sbit_table_size; /* now find the strike corresponding to the index */ { FT_Byte* p; if ( 8 + 48 * strike_index + 3 * 4 + 34 + 1 > face->sbit_table_size ) { error = FT_THROW( Invalid_File_Format ); goto Exit; } p = decoder->eblc_base + 8 + 48 * strike_index; decoder->strike_index_array = FT_NEXT_ULONG( p ); p += 4; decoder->strike_index_count = FT_NEXT_ULONG( p ); p += 34; decoder->bit_depth = *p; if ( decoder->strike_index_array > face->sbit_table_size || decoder->strike_index_array + 8 * decoder->strike_index_count > face->sbit_table_size ) error = FT_THROW( Invalid_File_Format ); } }
275,985,852,182,916,000,000,000,000,000,000,000,000
None
null
[ "CWE-189" ]
CVE-2014-9666
The tt_sbit_decoder_init function in sfnt/ttsbit.c in FreeType before 2.5.4 proceeds with a count-to-size association without restricting the count value, which allows remote attackers to cause a denial of service (integer overflow and out-of-bounds read) or possibly have unspecified other impact via a crafted embedded bitmap.
https://nvd.nist.gov/vuln/detail/CVE-2014-9666
158,043
savannah
257c270bd25e15890190a28a1456e7623bba4439
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=257c270bd25e15890190a28a1456e7623bba4439
None
0
tt_sbit_decoder_init( TT_SBitDecoder decoder, TT_Face face, FT_ULong strike_index, TT_SBit_MetricsRec* metrics ) { FT_Error error; FT_Stream stream = face->root.stream; FT_ULong ebdt_size; error = face->goto_table( face, TTAG_CBDT, stream, &ebdt_size ); if ( error ) error = face->goto_table( face, TTAG_EBDT, stream, &ebdt_size ); if ( error ) error = face->goto_table( face, TTAG_bdat, stream, &ebdt_size ); if ( error ) goto Exit; decoder->face = face; decoder->stream = stream; decoder->bitmap = &face->root.glyph->bitmap; decoder->metrics = metrics; decoder->metrics_loaded = 0; decoder->bitmap_allocated = 0; decoder->ebdt_start = FT_STREAM_POS(); decoder->ebdt_size = ebdt_size; decoder->eblc_base = face->sbit_table; decoder->eblc_limit = face->sbit_table + face->sbit_table_size; /* now find the strike corresponding to the index */ { FT_Byte* p; if ( 8 + 48 * strike_index + 3 * 4 + 34 + 1 > face->sbit_table_size ) { error = FT_THROW( Invalid_File_Format ); goto Exit; } p = decoder->eblc_base + 8 + 48 * strike_index; decoder->strike_index_array = FT_NEXT_ULONG( p ); p += 4; decoder->strike_index_count = FT_NEXT_ULONG( p ); p += 34; decoder->bit_depth = *p; /* decoder->strike_index_array + */ /* 8 * decoder->strike_index_count > face->sbit_table_size ? */ if ( decoder->strike_index_array > face->sbit_table_size || decoder->strike_index_count > ( face->sbit_table_size - decoder->strike_index_array ) / 8 ) error = FT_THROW( Invalid_File_Format ); } }
318,862,796,718,235,600,000,000,000,000,000,000,000
None
null
[ "CWE-189" ]
CVE-2014-9666
The tt_sbit_decoder_init function in sfnt/ttsbit.c in FreeType before 2.5.4 proceeds with a count-to-size association without restricting the count value, which allows remote attackers to cause a denial of service (integer overflow and out-of-bounds read) or possibly have unspecified other impact via a crafted embedded bitmap.
https://nvd.nist.gov/vuln/detail/CVE-2014-9666
199
savannah
f70d9342e65cd2cb44e9f26b6d7edeedf191fc6c
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=f70d9342e65cd2cb44e9f26b6d7edeedf191fc6c
None
1
tt_face_load_kern( TT_Face face, FT_Stream stream ) { FT_Error error; FT_ULong table_size; FT_Byte* p; FT_Byte* p_limit; FT_UInt nn, num_tables; FT_UInt32 avail = 0, ordered = 0; /* the kern table is optional; exit silently if it is missing */ error = face->goto_table( face, TTAG_kern, stream, &table_size ); if ( error ) goto Exit; if ( table_size < 4 ) /* the case of a malformed table */ { FT_ERROR(( "tt_face_load_kern:" " kerning table is too small - ignored\n" )); error = FT_THROW( Table_Missing ); goto Exit; } if ( FT_FRAME_EXTRACT( table_size, face->kern_table ) ) { FT_ERROR(( "tt_face_load_kern:" " could not extract kerning table\n" )); goto Exit; } face->kern_table_size = table_size; p = face->kern_table; p_limit = p + table_size; p += 2; /* skip version */ num_tables = FT_NEXT_USHORT( p ); if ( num_tables > 32 ) /* we only support up to 32 sub-tables */ num_tables = 32; for ( nn = 0; nn < num_tables; nn++ ) { FT_UInt num_pairs, length, coverage; FT_Byte* p_next; FT_UInt32 mask = (FT_UInt32)1UL << nn; if ( p + 6 > p_limit ) break; p_next = p; p += 2; /* skip version */ length = FT_NEXT_USHORT( p ); coverage = FT_NEXT_USHORT( p ); if ( length <= 6 ) break; p_next += length; if ( p_next > p_limit ) /* handle broken table */ p_next = p_limit; /* only use horizontal kerning tables */ if ( ( coverage & ~8 ) != 0x0001 || p + 8 > p_limit ) goto NextTable; num_pairs = FT_NEXT_USHORT( p ); p += 6; if ( ( p_next - p ) < 6 * (int)num_pairs ) /* handle broken count */ num_pairs = (FT_UInt)( ( p_next - p ) / 6 ); avail |= mask; /* * Now check whether the pairs in this table are ordered. * We then can use binary search. */ if ( num_pairs > 0 ) { FT_ULong count; FT_ULong old_pair; old_pair = FT_NEXT_ULONG( p ); p += 2; for ( count = num_pairs - 1; count > 0; count-- ) { FT_UInt32 cur_pair; cur_pair = FT_NEXT_ULONG( p ); if ( cur_pair <= old_pair ) break; p += 2; old_pair = cur_pair; } if ( count == 0 ) ordered |= mask; } NextTable: p = p_next; } face->num_kern_tables = nn; face->kern_avail_bits = avail; face->kern_order_bits = ordered; Exit: return error; }
223,904,594,839,516,100,000,000,000,000,000,000,000
None
null
[ "CWE-125" ]
CVE-2014-9658
The tt_face_load_kern function in sfnt/ttkern.c in FreeType before 2.5.4 enforces an incorrect minimum table length, which allows remote attackers to cause a denial of service (out-of-bounds read) or possibly have unspecified other impact via a crafted TrueType font.
https://nvd.nist.gov/vuln/detail/CVE-2014-9658
158,059
savannah
f70d9342e65cd2cb44e9f26b6d7edeedf191fc6c
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=f70d9342e65cd2cb44e9f26b6d7edeedf191fc6c
None
0
tt_face_load_kern( TT_Face face, FT_Stream stream ) { FT_Error error; FT_ULong table_size; FT_Byte* p; FT_Byte* p_limit; FT_UInt nn, num_tables; FT_UInt32 avail = 0, ordered = 0; /* the kern table is optional; exit silently if it is missing */ error = face->goto_table( face, TTAG_kern, stream, &table_size ); if ( error ) goto Exit; if ( table_size < 4 ) /* the case of a malformed table */ { FT_ERROR(( "tt_face_load_kern:" " kerning table is too small - ignored\n" )); error = FT_THROW( Table_Missing ); goto Exit; } if ( FT_FRAME_EXTRACT( table_size, face->kern_table ) ) { FT_ERROR(( "tt_face_load_kern:" " could not extract kerning table\n" )); goto Exit; } face->kern_table_size = table_size; p = face->kern_table; p_limit = p + table_size; p += 2; /* skip version */ num_tables = FT_NEXT_USHORT( p ); if ( num_tables > 32 ) /* we only support up to 32 sub-tables */ num_tables = 32; for ( nn = 0; nn < num_tables; nn++ ) { FT_UInt num_pairs, length, coverage; FT_Byte* p_next; FT_UInt32 mask = (FT_UInt32)1UL << nn; if ( p + 6 > p_limit ) break; p_next = p; p += 2; /* skip version */ length = FT_NEXT_USHORT( p ); coverage = FT_NEXT_USHORT( p ); if ( length <= 6 + 8 ) break; p_next += length; if ( p_next > p_limit ) /* handle broken table */ p_next = p_limit; /* only use horizontal kerning tables */ if ( ( coverage & ~8 ) != 0x0001 || p + 8 > p_limit ) goto NextTable; num_pairs = FT_NEXT_USHORT( p ); p += 6; if ( ( p_next - p ) < 6 * (int)num_pairs ) /* handle broken count */ num_pairs = (FT_UInt)( ( p_next - p ) / 6 ); avail |= mask; /* * Now check whether the pairs in this table are ordered. * We then can use binary search. */ if ( num_pairs > 0 ) { FT_ULong count; FT_ULong old_pair; old_pair = FT_NEXT_ULONG( p ); p += 2; for ( count = num_pairs - 1; count > 0; count-- ) { FT_UInt32 cur_pair; cur_pair = FT_NEXT_ULONG( p ); if ( cur_pair <= old_pair ) break; p += 2; old_pair = cur_pair; } if ( count == 0 ) ordered |= mask; } NextTable: p = p_next; } face->num_kern_tables = nn; face->kern_avail_bits = avail; face->kern_order_bits = ordered; Exit: return error; }
110,539,480,089,627,080,000,000,000,000,000,000,000
None
null
[ "CWE-125" ]
CVE-2014-9658
The tt_face_load_kern function in sfnt/ttkern.c in FreeType before 2.5.4 enforces an incorrect minimum table length, which allows remote attackers to cause a denial of service (out-of-bounds read) or possibly have unspecified other impact via a crafted TrueType font.
https://nvd.nist.gov/vuln/detail/CVE-2014-9658
200
savannah
f0292bb9920aa1dbfed5f53861e7c7a89b35833a
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=f0292bb9920aa1dbfed5f53861e7c7a89b35833a
None
1
tt_sbit_decoder_load_image( TT_SBitDecoder decoder, FT_UInt glyph_index, FT_Int x_pos, FT_Int y_pos ) { /* * First, we find the correct strike range that applies to this * glyph index. */ FT_Byte* p = decoder->eblc_base + decoder->strike_index_array; FT_Byte* p_limit = decoder->eblc_limit; FT_ULong num_ranges = decoder->strike_index_count; FT_UInt start, end, index_format, image_format; FT_ULong image_start = 0, image_end = 0, image_offset; for ( ; num_ranges > 0; num_ranges-- ) { start = FT_NEXT_USHORT( p ); end = FT_NEXT_USHORT( p ); if ( glyph_index >= start && glyph_index <= end ) goto FoundRange; p += 4; /* ignore index offset */ } goto NoBitmap; FoundRange: image_offset = FT_NEXT_ULONG( p ); /* overflow check */ p = decoder->eblc_base + decoder->strike_index_array; if ( image_offset > (FT_ULong)( p_limit - p ) ) goto Failure; p += image_offset; if ( p + 8 > p_limit ) goto NoBitmap; /* now find the glyph's location and extend within the ebdt table */ index_format = FT_NEXT_USHORT( p ); image_format = FT_NEXT_USHORT( p ); image_offset = FT_NEXT_ULONG ( p ); switch ( index_format ) { case 1: /* 4-byte offsets relative to `image_offset' */ p += 4 * ( glyph_index - start ); if ( p + 8 > p_limit ) goto NoBitmap; image_start = FT_NEXT_ULONG( p ); image_end = FT_NEXT_ULONG( p ); if ( image_start == image_end ) /* missing glyph */ goto NoBitmap; break; case 2: /* big metrics, constant image size */ { FT_ULong image_size; if ( p + 12 > p_limit ) goto NoBitmap; image_size = FT_NEXT_ULONG( p ); if ( tt_sbit_decoder_load_metrics( decoder, &p, p_limit, 1 ) ) goto NoBitmap; image_start = image_size * ( glyph_index - start ); image_end = image_start + image_size; } break; case 3: /* 2-byte offsets relative to 'image_offset' */ p += 2 * ( glyph_index - start ); if ( p + 4 > p_limit ) goto NoBitmap; image_start = FT_NEXT_USHORT( p ); image_end = FT_NEXT_USHORT( p ); if ( image_start == image_end ) /* missing glyph */ goto NoBitmap; break; case 4: /* sparse glyph array with (glyph,offset) pairs */ { FT_ULong mm, num_glyphs; if ( p + 4 > p_limit ) goto NoBitmap; num_glyphs = FT_NEXT_ULONG( p ); /* overflow check for p + ( num_glyphs + 1 ) * 4 */ if ( num_glyphs > (FT_ULong)( ( ( p_limit - p ) >> 2 ) - 1 ) ) goto NoBitmap; for ( mm = 0; mm < num_glyphs; mm++ ) FT_UInt gindex = FT_NEXT_USHORT( p ); if ( gindex == glyph_index ) { image_start = FT_NEXT_USHORT( p ); p += 2; image_end = FT_PEEK_USHORT( p ); break; } p += 2; } if ( mm >= num_glyphs ) goto NoBitmap; } break; case 5: /* constant metrics with sparse glyph codes */ case 19: { FT_ULong image_size, mm, num_glyphs; if ( p + 16 > p_limit ) goto NoBitmap; image_size = FT_NEXT_ULONG( p ); if ( tt_sbit_decoder_load_metrics( decoder, &p, p_limit, 1 ) ) goto NoBitmap; num_glyphs = FT_NEXT_ULONG( p ); /* overflow check for p + 2 * num_glyphs */ if ( num_glyphs > (FT_ULong)( ( p_limit - p ) >> 1 ) ) goto NoBitmap; for ( mm = 0; mm < num_glyphs; mm++ ) { FT_UInt gindex = FT_NEXT_USHORT( p ); if ( gindex == glyph_index ) break; } if ( mm >= num_glyphs ) goto NoBitmap; image_start = image_size * mm; image_end = image_start + image_size; } break; default: goto NoBitmap; }
28,994,602,925,432,626,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2014-9656
The tt_sbit_decoder_load_image function in sfnt/ttsbit.c in FreeType before 2.5.4 does not properly check for an integer overflow, which allows remote attackers to cause a denial of service (out-of-bounds read) or possibly have unspecified other impact via a crafted OpenType font.
https://nvd.nist.gov/vuln/detail/CVE-2014-9656
158,060
savannah
f0292bb9920aa1dbfed5f53861e7c7a89b35833a
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=f0292bb9920aa1dbfed5f53861e7c7a89b35833a
None
0
tt_sbit_decoder_load_image( TT_SBitDecoder decoder, FT_UInt glyph_index, FT_Int x_pos, FT_Int y_pos ) { /* * First, we find the correct strike range that applies to this * glyph index. */ FT_Byte* p = decoder->eblc_base + decoder->strike_index_array; FT_Byte* p_limit = decoder->eblc_limit; FT_ULong num_ranges = decoder->strike_index_count; FT_UInt start, end, index_format, image_format; FT_ULong image_start = 0, image_end = 0, image_offset; for ( ; num_ranges > 0; num_ranges-- ) { start = FT_NEXT_USHORT( p ); end = FT_NEXT_USHORT( p ); if ( glyph_index >= start && glyph_index <= end ) goto FoundRange; p += 4; /* ignore index offset */ } goto NoBitmap; FoundRange: image_offset = FT_NEXT_ULONG( p ); /* overflow check */ p = decoder->eblc_base + decoder->strike_index_array; if ( image_offset > (FT_ULong)( p_limit - p ) ) goto Failure; p += image_offset; if ( p + 8 > p_limit ) goto NoBitmap; /* now find the glyph's location and extend within the ebdt table */ index_format = FT_NEXT_USHORT( p ); image_format = FT_NEXT_USHORT( p ); image_offset = FT_NEXT_ULONG ( p ); switch ( index_format ) { case 1: /* 4-byte offsets relative to `image_offset' */ p += 4 * ( glyph_index - start ); if ( p + 8 > p_limit ) goto NoBitmap; image_start = FT_NEXT_ULONG( p ); image_end = FT_NEXT_ULONG( p ); if ( image_start == image_end ) /* missing glyph */ goto NoBitmap; break; case 2: /* big metrics, constant image size */ { FT_ULong image_size; if ( p + 12 > p_limit ) goto NoBitmap; image_size = FT_NEXT_ULONG( p ); if ( tt_sbit_decoder_load_metrics( decoder, &p, p_limit, 1 ) ) goto NoBitmap; image_start = image_size * ( glyph_index - start ); image_end = image_start + image_size; } break; case 3: /* 2-byte offsets relative to 'image_offset' */ p += 2 * ( glyph_index - start ); if ( p + 4 > p_limit ) goto NoBitmap; image_start = FT_NEXT_USHORT( p ); image_end = FT_NEXT_USHORT( p ); if ( image_start == image_end ) /* missing glyph */ goto NoBitmap; break; case 4: /* sparse glyph array with (glyph,offset) pairs */ { FT_ULong mm, num_glyphs; if ( p + 4 > p_limit ) goto NoBitmap; num_glyphs = FT_NEXT_ULONG( p ); /* overflow check for p + ( num_glyphs + 1 ) * 4 */ if ( p + 4 > p_limit || num_glyphs > (FT_ULong)( ( ( p_limit - p ) >> 2 ) - 1 ) ) goto NoBitmap; for ( mm = 0; mm < num_glyphs; mm++ ) FT_UInt gindex = FT_NEXT_USHORT( p ); if ( gindex == glyph_index ) { image_start = FT_NEXT_USHORT( p ); p += 2; image_end = FT_PEEK_USHORT( p ); break; } p += 2; } if ( mm >= num_glyphs ) goto NoBitmap; } break; case 5: /* constant metrics with sparse glyph codes */ case 19: { FT_ULong image_size, mm, num_glyphs; if ( p + 16 > p_limit ) goto NoBitmap; image_size = FT_NEXT_ULONG( p ); if ( tt_sbit_decoder_load_metrics( decoder, &p, p_limit, 1 ) ) goto NoBitmap; num_glyphs = FT_NEXT_ULONG( p ); /* overflow check for p + 2 * num_glyphs */ if ( num_glyphs > (FT_ULong)( ( p_limit - p ) >> 1 ) ) goto NoBitmap; for ( mm = 0; mm < num_glyphs; mm++ ) { FT_UInt gindex = FT_NEXT_USHORT( p ); if ( gindex == glyph_index ) break; } if ( mm >= num_glyphs ) goto NoBitmap; image_start = image_size * mm; image_end = image_start + image_size; } break; default: goto NoBitmap; }
174,846,873,576,513,800,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2014-9656
The tt_sbit_decoder_load_image function in sfnt/ttsbit.c in FreeType before 2.5.4 does not properly check for an integer overflow, which allows remote attackers to cause a denial of service (out-of-bounds read) or possibly have unspecified other impact via a crafted OpenType font.
https://nvd.nist.gov/vuln/detail/CVE-2014-9656
204
savannah
3774fc08b502c3e685afca098b6e8a195aded6a0
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=3774fc08b502c3e685afca098b6e8a195aded6a0
None
1
ps_parser_to_token( PS_Parser parser, T1_Token token ) { FT_Byte* cur; FT_Byte* limit; FT_Int embed; token->type = T1_TOKEN_TYPE_NONE; token->start = NULL; token->limit = NULL; /* first of all, skip leading whitespace */ ps_parser_skip_spaces( parser ); cur = parser->cursor; limit = parser->limit; if ( cur >= limit ) return; switch ( *cur ) { /************* check for literal string *****************/ case '(': token->type = T1_TOKEN_TYPE_STRING; token->start = cur; if ( skip_literal_string( &cur, limit ) == FT_Err_Ok ) token->limit = cur; break; /************* check for programs/array *****************/ case '{': token->type = T1_TOKEN_TYPE_ARRAY; token->start = cur; if ( skip_procedure( &cur, limit ) == FT_Err_Ok ) token->limit = cur; break; /************* check for table/array ********************/ /* XXX: in theory we should also look for "<<" */ /* since this is semantically equivalent to "["; */ /* in practice it doesn't matter (?) */ case '[': token->type = T1_TOKEN_TYPE_ARRAY; embed = 1; token->start = cur++; /* we need this to catch `[ ]' */ parser->cursor = cur; ps_parser_skip_spaces( parser ); cur = parser->cursor; while ( cur < limit && !parser->error ) { /* XXX: this is wrong because it does not */ /* skip comments, procedures, and strings */ if ( *cur == '[' ) embed++; else if ( *cur == ']' ) { embed--; if ( embed <= 0 ) { token->limit = ++cur; break; } } parser->cursor = cur; ps_parser_skip_PS_token( parser ); /* we need this to catch `[XXX ]' */ ps_parser_skip_spaces ( parser ); cur = parser->cursor; } break; /* ************ otherwise, it is any token **************/ default: token->start = cur; token->type = ( *cur == '/' ) ? T1_TOKEN_TYPE_KEY : T1_TOKEN_TYPE_ANY; ps_parser_skip_PS_token( parser ); cur = parser->cursor; if ( !parser->error ) token->limit = cur; } if ( !token->limit ) { token->start = NULL; token->type = T1_TOKEN_TYPE_NONE; } parser->cursor = cur; } /* NB: `tokens' can be NULL if we only want to count */ /* the number of array elements */ FT_LOCAL_DEF( void ) ps_parser_to_token_array( PS_Parser parser, T1_Token tokens, FT_UInt max_tokens, FT_Int* pnum_tokens ) { T1_TokenRec master; *pnum_tokens = -1; /* this also handles leading whitespace */ ps_parser_to_token( parser, &master ); if ( master.type == T1_TOKEN_TYPE_ARRAY ) { FT_Byte* old_cursor = parser->cursor; FT_Byte* old_limit = parser->limit; T1_Token cur = tokens; T1_Token limit = cur + max_tokens; /* don't include outermost delimiters */ parser->cursor = master.start + 1; parser->limit = master.limit - 1; while ( parser->cursor < parser->limit ) { T1_TokenRec token; ps_parser_to_token( parser, &token ); if ( !token.type ) break; if ( tokens && cur < limit ) *cur = token; cur++; } *pnum_tokens = (FT_Int)( cur - tokens ); parser->cursor = old_cursor; parser->limit = old_limit; } } /* first character must be a delimiter or a part of a number */ /* NB: `coords' can be NULL if we just want to skip the */ /* array; in this case we ignore `max_coords' */ static FT_Int ps_tocoordarray( FT_Byte* *acur, FT_Byte* limit, FT_Int max_coords, FT_Short* coords ) { FT_Byte* cur = *acur; FT_Int count = 0; FT_Byte c, ender; if ( cur >= limit ) goto Exit; /* check for the beginning of an array; otherwise, only one number */ /* will be read */ c = *cur; ender = 0; if ( c == '[' ) ender = ']'; else if ( c == '{' ) ender = '}'; if ( ender ) cur++; /* now, read the coordinates */ while ( cur < limit ) { FT_Short dummy; FT_Byte* old_cur; /* skip whitespace in front of data */ skip_spaces( &cur, limit ); if ( cur >= limit ) goto Exit; if ( *cur == ender ) { cur++; break; } old_cur = cur; if ( coords && count >= max_coords ) break; /* call PS_Conv_ToFixed() even if coords == NULL */ /* to properly parse number at `cur' */ *( coords ? &coords[count] : &dummy ) = (FT_Short)( PS_Conv_ToFixed( &cur, limit, 0 ) >> 16 ); if ( old_cur == cur ) { count = -1; goto Exit; } else count++; if ( !ender ) break; } Exit: *acur = cur; return count; } /* first character must be a delimiter or a part of a number */ /* NB: `values' can be NULL if we just want to skip the */ /* array; in this case we ignore `max_values' */ /* */ /* return number of successfully parsed values */ static FT_Int ps_tofixedarray( FT_Byte* *acur, FT_Byte* limit, FT_Int max_values, FT_Fixed* values, FT_Int power_ten ) { FT_Byte* cur = *acur; FT_Int count = 0; FT_Byte c, ender; if ( cur >= limit ) goto Exit; /* Check for the beginning of an array. Otherwise, only one number */ /* will be read. */ c = *cur; ender = 0; if ( c == '[' ) ender = ']'; else if ( c == '{' ) ender = '}'; if ( ender ) cur++; /* now, read the values */ while ( cur < limit ) { FT_Fixed dummy; FT_Byte* old_cur; /* skip whitespace in front of data */ skip_spaces( &cur, limit ); if ( cur >= limit ) goto Exit; if ( *cur == ender ) { cur++; break; } old_cur = cur; if ( values && count >= max_values ) break; /* call PS_Conv_ToFixed() even if coords == NULL */ /* to properly parse number at `cur' */ *( values ? &values[count] : &dummy ) = PS_Conv_ToFixed( &cur, limit, power_ten ); if ( old_cur == cur ) { count = -1; goto Exit; } else count++; if ( !ender ) break; } Exit: *acur = cur; return count; } #if 0 static FT_String* ps_tostring( FT_Byte** cursor, FT_Byte* limit, FT_Memory memory ) { FT_Byte* cur = *cursor; FT_UInt len = 0; FT_Int count; FT_String* result; FT_Error error; /* XXX: some stupid fonts have a `Notice' or `Copyright' string */ /* that simply doesn't begin with an opening parenthesis, even */ /* though they have a closing one! E.g. "amuncial.pfb" */ /* */ /* We must deal with these ill-fated cases there. Note that */ /* these fonts didn't work with the old Type 1 driver as the */ /* notice/copyright was not recognized as a valid string token */ /* and made the old token parser commit errors. */ while ( cur < limit && ( *cur == ' ' || *cur == '\t' ) ) cur++; if ( cur + 1 >= limit ) return 0; if ( *cur == '(' ) cur++; /* skip the opening parenthesis, if there is one */ *cursor = cur; count = 0; /* then, count its length */ for ( ; cur < limit; cur++ ) { if ( *cur == '(' ) count++; else if ( *cur == ')' ) { count--; if ( count < 0 ) break; } } len = (FT_UInt)( cur - *cursor ); if ( cur >= limit || FT_ALLOC( result, len + 1 ) ) return 0; /* now copy the string */ FT_MEM_COPY( result, *cursor, len ); result[len] = '\0'; *cursor = cur; return result; } #endif /* 0 */ static int ps_tobool( FT_Byte* *acur, FT_Byte* limit ) { FT_Byte* cur = *acur; FT_Bool result = 0; /* return 1 if we find `true', 0 otherwise */ if ( cur + 3 < limit && cur[0] == 't' && cur[1] == 'r' && cur[2] == 'u' && cur[3] == 'e' ) { result = 1; cur += 5; } else if ( cur + 4 < limit && cur[0] == 'f' && cur[1] == 'a' && cur[2] == 'l' && cur[3] == 's' && cur[4] == 'e' ) { result = 0; cur += 6; } *acur = cur; return result; } /* load a simple field (i.e. non-table) into the current list of objects */ FT_LOCAL_DEF( FT_Error ) ps_parser_load_field( PS_Parser parser, const T1_Field field, void** objects, FT_UInt max_objects, FT_ULong* pflags ) { T1_TokenRec token; FT_Byte* cur; FT_Byte* limit; FT_UInt count; FT_UInt idx; FT_Error error; T1_FieldType type; /* this also skips leading whitespace */ ps_parser_to_token( parser, &token ); if ( !token.type ) goto Fail; count = 1; idx = 0; cur = token.start; limit = token.limit; type = field->type; /* we must detect arrays in /FontBBox */ if ( type == T1_FIELD_TYPE_BBOX ) { T1_TokenRec token2; FT_Byte* old_cur = parser->cursor; FT_Byte* old_limit = parser->limit; /* don't include delimiters */ parser->cursor = token.start + 1; parser->limit = token.limit - 1; ps_parser_to_token( parser, &token2 ); parser->cursor = old_cur; parser->limit = old_limit; if ( token2.type == T1_TOKEN_TYPE_ARRAY ) { type = T1_FIELD_TYPE_MM_BBOX; goto FieldArray; } } else if ( token.type == T1_TOKEN_TYPE_ARRAY ) { count = max_objects; FieldArray: /* if this is an array and we have no blend, an error occurs */ if ( max_objects == 0 ) goto Fail; idx = 1; /* don't include delimiters */ cur++; limit--; } for ( ; count > 0; count--, idx++ ) { FT_Byte* q = (FT_Byte*)objects[idx] + field->offset; FT_Long val; FT_String* string = NULL; skip_spaces( &cur, limit ); switch ( type ) { case T1_FIELD_TYPE_BOOL: val = ps_tobool( &cur, limit ); goto Store_Integer; case T1_FIELD_TYPE_FIXED: val = PS_Conv_ToFixed( &cur, limit, 0 ); goto Store_Integer; case T1_FIELD_TYPE_FIXED_1000: val = PS_Conv_ToFixed( &cur, limit, 3 ); goto Store_Integer; case T1_FIELD_TYPE_INTEGER: val = PS_Conv_ToInt( &cur, limit ); /* fall through */ Store_Integer: switch ( field->size ) { case (8 / FT_CHAR_BIT): *(FT_Byte*)q = (FT_Byte)val; break; case (16 / FT_CHAR_BIT): *(FT_UShort*)q = (FT_UShort)val; break; case (32 / FT_CHAR_BIT): *(FT_UInt32*)q = (FT_UInt32)val; break; default: /* for 64-bit systems */ *(FT_Long*)q = val; } break; case T1_FIELD_TYPE_STRING: case T1_FIELD_TYPE_KEY: { FT_Memory memory = parser->memory; FT_UInt len = (FT_UInt)( limit - cur ); if ( cur >= limit ) break; /* we allow both a string or a name */ /* for cases like /FontName (foo) def */ if ( token.type == T1_TOKEN_TYPE_KEY ) { /* don't include leading `/' */ len--; cur++; } else if ( token.type == T1_TOKEN_TYPE_STRING ) { /* don't include delimiting parentheses */ /* XXX we don't handle <<...>> here */ /* XXX should we convert octal escapes? */ /* if so, what encoding should we use? */ cur++; len -= 2; } else { FT_ERROR(( "ps_parser_load_field:" " expected a name or string\n" " " " but found token of type %d instead\n", token.type )); error = FT_THROW( Invalid_File_Format ); goto Exit; } /* for this to work (FT_String**)q must have been */ /* initialized to NULL */ if ( *(FT_String**)q ) { FT_TRACE0(( "ps_parser_load_field: overwriting field %s\n", field->ident )); FT_FREE( *(FT_String**)q ); *(FT_String**)q = NULL; } if ( FT_ALLOC( string, len + 1 ) ) goto Exit; FT_MEM_COPY( string, cur, len ); string[len] = 0; *(FT_String**)q = string; } break; case T1_FIELD_TYPE_BBOX: { FT_Fixed temp[4]; FT_BBox* bbox = (FT_BBox*)q; FT_Int result; result = ps_tofixedarray( &cur, limit, 4, temp, 0 ); if ( result < 4 ) { FT_ERROR(( "ps_parser_load_field:" " expected four integers in bounding box\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } bbox->xMin = FT_RoundFix( temp[0] ); bbox->yMin = FT_RoundFix( temp[1] ); bbox->xMax = FT_RoundFix( temp[2] ); bbox->yMax = FT_RoundFix( temp[3] ); } break; case T1_FIELD_TYPE_MM_BBOX: { FT_Memory memory = parser->memory; FT_Fixed* temp = NULL; FT_Int result; FT_UInt i; if ( FT_NEW_ARRAY( temp, max_objects * 4 ) ) goto Exit; for ( i = 0; i < 4; i++ ) { result = ps_tofixedarray( &cur, limit, (FT_Int)max_objects, temp + i * max_objects, 0 ); if ( result < 0 || (FT_UInt)result < max_objects ) { FT_ERROR(( "ps_parser_load_field:" " expected %d integer%s in the %s subarray\n" " " " of /FontBBox in the /Blend dictionary\n", max_objects, max_objects > 1 ? "s" : "", i == 0 ? "first" : ( i == 1 ? "second" : ( i == 2 ? "third" : "fourth" ) ) )); error = FT_THROW( Invalid_File_Format ); FT_FREE( temp ); goto Exit; } skip_spaces( &cur, limit ); } for ( i = 0; i < max_objects; i++ ) { FT_BBox* bbox = (FT_BBox*)objects[i]; bbox->xMin = FT_RoundFix( temp[i ] ); bbox->yMin = FT_RoundFix( temp[i + max_objects] ); bbox->xMax = FT_RoundFix( temp[i + 2 * max_objects] ); bbox->yMax = FT_RoundFix( temp[i + 3 * max_objects] ); } FT_FREE( temp ); } break; default: /* an error occurred */ goto Fail; } } #if 0 /* obsolete -- keep for reference */ if ( pflags ) *pflags |= 1L << field->flag_bit; #else FT_UNUSED( pflags ); #endif error = FT_Err_Ok; Exit: return error; Fail: error = FT_THROW( Invalid_File_Format ); goto Exit; } #define T1_MAX_TABLE_ELEMENTS 32 FT_LOCAL_DEF( FT_Error ) ps_parser_load_field_table( PS_Parser parser, const T1_Field field, void** objects, FT_UInt max_objects, FT_ULong* pflags ) { T1_TokenRec elements[T1_MAX_TABLE_ELEMENTS]; T1_Token token; FT_Int num_elements; FT_Error error = FT_Err_Ok; FT_Byte* old_cursor; FT_Byte* old_limit; T1_FieldRec fieldrec = *(T1_Field)field; fieldrec.type = T1_FIELD_TYPE_INTEGER; if ( field->type == T1_FIELD_TYPE_FIXED_ARRAY || field->type == T1_FIELD_TYPE_BBOX ) fieldrec.type = T1_FIELD_TYPE_FIXED; ps_parser_to_token_array( parser, elements, T1_MAX_TABLE_ELEMENTS, &num_elements ); if ( num_elements < 0 ) { error = FT_ERR( Ignore ); goto Exit; } if ( (FT_UInt)num_elements > field->array_max ) num_elements = (FT_Int)field->array_max; old_cursor = parser->cursor; old_limit = parser->limit; /* we store the elements count if necessary; */ /* we further assume that `count_offset' can't be zero */ if ( field->type != T1_FIELD_TYPE_BBOX && field->count_offset != 0 ) *(FT_Byte*)( (FT_Byte*)objects[0] + field->count_offset ) = (FT_Byte)num_elements; /* we now load each element, adjusting the field.offset on each one */ token = elements; for ( ; num_elements > 0; num_elements--, token++ ) { parser->cursor = token->start; parser->limit = token->limit; error = ps_parser_load_field( parser, &fieldrec, objects, max_objects, 0 ); if ( error ) break; fieldrec.offset += fieldrec.size; } #if 0 /* obsolete -- keep for reference */ if ( pflags ) *pflags |= 1L << field->flag_bit; #else FT_UNUSED( pflags ); #endif parser->cursor = old_cursor; parser->limit = old_limit; Exit: return error; } FT_LOCAL_DEF( FT_Long ) ps_parser_to_int( PS_Parser parser ) { ps_parser_skip_spaces( parser ); return PS_Conv_ToInt( &parser->cursor, parser->limit ); } /* first character must be `<' if `delimiters' is non-zero */ FT_LOCAL_DEF( FT_Error ) ps_parser_to_bytes( PS_Parser parser, FT_Byte* bytes, FT_Offset max_bytes, FT_ULong* pnum_bytes, FT_Bool delimiters ) { FT_Error error = FT_Err_Ok; FT_Byte* cur; ps_parser_skip_spaces( parser ); cur = parser->cursor; if ( cur >= parser->limit ) goto Exit; if ( delimiters ) { if ( *cur != '<' ) { FT_ERROR(( "ps_parser_to_bytes: Missing starting delimiter `<'\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } cur++; } *pnum_bytes = PS_Conv_ASCIIHexDecode( &cur, parser->limit, bytes, max_bytes ); if ( delimiters ) { if ( cur < parser->limit && *cur != '>' ) { FT_ERROR(( "ps_parser_to_bytes: Missing closing delimiter `>'\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } cur++; } parser->cursor = cur; Exit: return error; } FT_LOCAL_DEF( FT_Fixed ) ps_parser_to_fixed( PS_Parser parser, FT_Int power_ten ) { ps_parser_skip_spaces( parser ); return PS_Conv_ToFixed( &parser->cursor, parser->limit, power_ten ); } FT_LOCAL_DEF( FT_Int ) ps_parser_to_coord_array( PS_Parser parser, FT_Int max_coords, FT_Short* coords ) { ps_parser_skip_spaces( parser ); return ps_tocoordarray( &parser->cursor, parser->limit, max_coords, coords ); } FT_LOCAL_DEF( FT_Int ) ps_parser_to_fixed_array( PS_Parser parser, FT_Int max_values, FT_Fixed* values, FT_Int power_ten ) { ps_parser_skip_spaces( parser ); return ps_tofixedarray( &parser->cursor, parser->limit, max_values, values, power_ten ); } #if 0 FT_LOCAL_DEF( FT_String* ) T1_ToString( PS_Parser parser ) { return ps_tostring( &parser->cursor, parser->limit, parser->memory ); } FT_LOCAL_DEF( FT_Bool ) T1_ToBool( PS_Parser parser ) { return ps_tobool( &parser->cursor, parser->limit ); } #endif /* 0 */ FT_LOCAL_DEF( void ) ps_parser_init( PS_Parser parser, FT_Byte* base, FT_Byte* limit, FT_Memory memory ) { parser->error = FT_Err_Ok; parser->base = base; parser->limit = limit; parser->cursor = base; parser->memory = memory; parser->funcs = ps_parser_funcs; } FT_LOCAL_DEF( void ) ps_parser_done( PS_Parser parser ) { FT_UNUSED( parser ); } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** T1 BUILDER *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* t1_builder_init */ /* */ /* <Description> */ /* Initializes a given glyph builder. */ /* */ /* <InOut> */ /* builder :: A pointer to the glyph builder to initialize. */ /* */ /* <Input> */ /* face :: The current face object. */ /* */ /* size :: The current size object. */ /* */ /* glyph :: The current glyph object. */ /* */ /* hinting :: Whether hinting should be applied. */ /* */ FT_LOCAL_DEF( void ) t1_builder_init( T1_Builder builder, FT_Face face, FT_Size size, FT_GlyphSlot glyph, FT_Bool hinting ) { builder->parse_state = T1_Parse_Start; builder->load_points = 1; builder->face = face; builder->glyph = glyph; builder->memory = face->memory; if ( glyph ) { FT_GlyphLoader loader = glyph->internal->loader; builder->loader = loader; builder->base = &loader->base.outline; builder->current = &loader->current.outline; FT_GlyphLoader_Rewind( loader ); builder->hints_globals = size->internal; builder->hints_funcs = NULL; if ( hinting ) builder->hints_funcs = glyph->internal->glyph_hints; } builder->pos_x = 0; builder->pos_y = 0; builder->left_bearing.x = 0; builder->left_bearing.y = 0; builder->advance.x = 0; builder->advance.y = 0; builder->funcs = t1_builder_funcs; } /*************************************************************************/ /* */ /* <Function> */ /* t1_builder_done */ /* */ /* <Description> */ /* Finalizes a given glyph builder. Its contents can still be used */ /* after the call, but the function saves important information */ /* within the corresponding glyph slot. */ /* */ /* <Input> */ /* builder :: A pointer to the glyph builder to finalize. */ /* */ FT_LOCAL_DEF( void ) t1_builder_done( T1_Builder builder ) { FT_GlyphSlot glyph = builder->glyph; if ( glyph ) glyph->outline = *builder->base; } /* check that there is enough space for `count' more points */ FT_LOCAL_DEF( FT_Error ) t1_builder_check_points( T1_Builder builder, FT_Int count ) { return FT_GLYPHLOADER_CHECK_POINTS( builder->loader, count, 0 ); } /* add a new point, do not check space */ FT_LOCAL_DEF( void ) t1_builder_add_point( T1_Builder builder, FT_Pos x, FT_Pos y, FT_Byte flag ) { FT_Outline* outline = builder->current; if ( builder->load_points ) { FT_Vector* point = outline->points + outline->n_points; FT_Byte* control = (FT_Byte*)outline->tags + outline->n_points; point->x = FIXED_TO_INT( x ); point->y = FIXED_TO_INT( y ); *control = (FT_Byte)( flag ? FT_CURVE_TAG_ON : FT_CURVE_TAG_CUBIC ); } outline->n_points++; } /* check space for a new on-curve point, then add it */ FT_LOCAL_DEF( FT_Error ) t1_builder_add_point1( T1_Builder builder, FT_Pos x, FT_Pos y ) { FT_Error error; error = t1_builder_check_points( builder, 1 ); if ( !error ) t1_builder_add_point( builder, x, y, 1 ); return error; } /* check space for a new contour, then add it */ FT_LOCAL_DEF( FT_Error ) t1_builder_add_contour( T1_Builder builder ) { FT_Outline* outline = builder->current; FT_Error error; /* this might happen in invalid fonts */ if ( !outline ) { FT_ERROR(( "t1_builder_add_contour: no outline to add points to\n" )); return FT_THROW( Invalid_File_Format ); } if ( !builder->load_points ) { outline->n_contours++; return FT_Err_Ok; } error = FT_GLYPHLOADER_CHECK_POINTS( builder->loader, 0, 1 ); if ( !error ) { if ( outline->n_contours > 0 ) outline->contours[outline->n_contours - 1] = (short)( outline->n_points - 1 ); outline->n_contours++; } return error; } /* if a path was begun, add its first on-curve point */ FT_LOCAL_DEF( FT_Error ) t1_builder_start_point( T1_Builder builder, FT_Pos x, FT_Pos y ) { FT_Error error = FT_ERR( Invalid_File_Format ); /* test whether we are building a new contour */ if ( builder->parse_state == T1_Parse_Have_Path ) error = FT_Err_Ok; else { builder->parse_state = T1_Parse_Have_Path; error = t1_builder_add_contour( builder ); if ( !error ) error = t1_builder_add_point1( builder, x, y ); } return error; } /* close the current contour */ FT_LOCAL_DEF( void ) t1_builder_close_contour( T1_Builder builder ) { FT_Outline* outline = builder->current; FT_Int first; if ( !outline ) return; first = outline->n_contours <= 1 ? 0 : outline->contours[outline->n_contours - 2] + 1; /* We must not include the last point in the path if it */ /* is located on the first point. */ if ( outline->n_points > 1 ) if ( p1->x == p2->x && p1->y == p2->y ) if ( *control == FT_CURVE_TAG_ON ) outline->n_points--; } if ( outline->n_contours > 0 ) { /* Don't add contours only consisting of one point, i.e., */ /* check whether the first and the last point is the same. */ if ( first == outline->n_points - 1 ) { outline->n_contours--; outline->n_points--; } else outline->contours[outline->n_contours - 1] = (short)( outline->n_points - 1 ); } }
328,688,916,561,979,860,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2017-8287
FreeType 2 before 2017-03-26 has an out-of-bounds write caused by a heap-based buffer overflow related to the t1_builder_close_contour function in psaux/psobjs.c.
https://nvd.nist.gov/vuln/detail/CVE-2017-8287
158,064
savannah
3774fc08b502c3e685afca098b6e8a195aded6a0
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=3774fc08b502c3e685afca098b6e8a195aded6a0
None
0
ps_parser_to_token( PS_Parser parser, T1_Token token ) { FT_Byte* cur; FT_Byte* limit; FT_Int embed; token->type = T1_TOKEN_TYPE_NONE; token->start = NULL; token->limit = NULL; /* first of all, skip leading whitespace */ ps_parser_skip_spaces( parser ); cur = parser->cursor; limit = parser->limit; if ( cur >= limit ) return; switch ( *cur ) { /************* check for literal string *****************/ case '(': token->type = T1_TOKEN_TYPE_STRING; token->start = cur; if ( skip_literal_string( &cur, limit ) == FT_Err_Ok ) token->limit = cur; break; /************* check for programs/array *****************/ case '{': token->type = T1_TOKEN_TYPE_ARRAY; token->start = cur; if ( skip_procedure( &cur, limit ) == FT_Err_Ok ) token->limit = cur; break; /************* check for table/array ********************/ /* XXX: in theory we should also look for "<<" */ /* since this is semantically equivalent to "["; */ /* in practice it doesn't matter (?) */ case '[': token->type = T1_TOKEN_TYPE_ARRAY; embed = 1; token->start = cur++; /* we need this to catch `[ ]' */ parser->cursor = cur; ps_parser_skip_spaces( parser ); cur = parser->cursor; while ( cur < limit && !parser->error ) { /* XXX: this is wrong because it does not */ /* skip comments, procedures, and strings */ if ( *cur == '[' ) embed++; else if ( *cur == ']' ) { embed--; if ( embed <= 0 ) { token->limit = ++cur; break; } } parser->cursor = cur; ps_parser_skip_PS_token( parser ); /* we need this to catch `[XXX ]' */ ps_parser_skip_spaces ( parser ); cur = parser->cursor; } break; /* ************ otherwise, it is any token **************/ default: token->start = cur; token->type = ( *cur == '/' ) ? T1_TOKEN_TYPE_KEY : T1_TOKEN_TYPE_ANY; ps_parser_skip_PS_token( parser ); cur = parser->cursor; if ( !parser->error ) token->limit = cur; } if ( !token->limit ) { token->start = NULL; token->type = T1_TOKEN_TYPE_NONE; } parser->cursor = cur; } /* NB: `tokens' can be NULL if we only want to count */ /* the number of array elements */ FT_LOCAL_DEF( void ) ps_parser_to_token_array( PS_Parser parser, T1_Token tokens, FT_UInt max_tokens, FT_Int* pnum_tokens ) { T1_TokenRec master; *pnum_tokens = -1; /* this also handles leading whitespace */ ps_parser_to_token( parser, &master ); if ( master.type == T1_TOKEN_TYPE_ARRAY ) { FT_Byte* old_cursor = parser->cursor; FT_Byte* old_limit = parser->limit; T1_Token cur = tokens; T1_Token limit = cur + max_tokens; /* don't include outermost delimiters */ parser->cursor = master.start + 1; parser->limit = master.limit - 1; while ( parser->cursor < parser->limit ) { T1_TokenRec token; ps_parser_to_token( parser, &token ); if ( !token.type ) break; if ( tokens && cur < limit ) *cur = token; cur++; } *pnum_tokens = (FT_Int)( cur - tokens ); parser->cursor = old_cursor; parser->limit = old_limit; } } /* first character must be a delimiter or a part of a number */ /* NB: `coords' can be NULL if we just want to skip the */ /* array; in this case we ignore `max_coords' */ static FT_Int ps_tocoordarray( FT_Byte* *acur, FT_Byte* limit, FT_Int max_coords, FT_Short* coords ) { FT_Byte* cur = *acur; FT_Int count = 0; FT_Byte c, ender; if ( cur >= limit ) goto Exit; /* check for the beginning of an array; otherwise, only one number */ /* will be read */ c = *cur; ender = 0; if ( c == '[' ) ender = ']'; else if ( c == '{' ) ender = '}'; if ( ender ) cur++; /* now, read the coordinates */ while ( cur < limit ) { FT_Short dummy; FT_Byte* old_cur; /* skip whitespace in front of data */ skip_spaces( &cur, limit ); if ( cur >= limit ) goto Exit; if ( *cur == ender ) { cur++; break; } old_cur = cur; if ( coords && count >= max_coords ) break; /* call PS_Conv_ToFixed() even if coords == NULL */ /* to properly parse number at `cur' */ *( coords ? &coords[count] : &dummy ) = (FT_Short)( PS_Conv_ToFixed( &cur, limit, 0 ) >> 16 ); if ( old_cur == cur ) { count = -1; goto Exit; } else count++; if ( !ender ) break; } Exit: *acur = cur; return count; } /* first character must be a delimiter or a part of a number */ /* NB: `values' can be NULL if we just want to skip the */ /* array; in this case we ignore `max_values' */ /* */ /* return number of successfully parsed values */ static FT_Int ps_tofixedarray( FT_Byte* *acur, FT_Byte* limit, FT_Int max_values, FT_Fixed* values, FT_Int power_ten ) { FT_Byte* cur = *acur; FT_Int count = 0; FT_Byte c, ender; if ( cur >= limit ) goto Exit; /* Check for the beginning of an array. Otherwise, only one number */ /* will be read. */ c = *cur; ender = 0; if ( c == '[' ) ender = ']'; else if ( c == '{' ) ender = '}'; if ( ender ) cur++; /* now, read the values */ while ( cur < limit ) { FT_Fixed dummy; FT_Byte* old_cur; /* skip whitespace in front of data */ skip_spaces( &cur, limit ); if ( cur >= limit ) goto Exit; if ( *cur == ender ) { cur++; break; } old_cur = cur; if ( values && count >= max_values ) break; /* call PS_Conv_ToFixed() even if coords == NULL */ /* to properly parse number at `cur' */ *( values ? &values[count] : &dummy ) = PS_Conv_ToFixed( &cur, limit, power_ten ); if ( old_cur == cur ) { count = -1; goto Exit; } else count++; if ( !ender ) break; } Exit: *acur = cur; return count; } #if 0 static FT_String* ps_tostring( FT_Byte** cursor, FT_Byte* limit, FT_Memory memory ) { FT_Byte* cur = *cursor; FT_UInt len = 0; FT_Int count; FT_String* result; FT_Error error; /* XXX: some stupid fonts have a `Notice' or `Copyright' string */ /* that simply doesn't begin with an opening parenthesis, even */ /* though they have a closing one! E.g. "amuncial.pfb" */ /* */ /* We must deal with these ill-fated cases there. Note that */ /* these fonts didn't work with the old Type 1 driver as the */ /* notice/copyright was not recognized as a valid string token */ /* and made the old token parser commit errors. */ while ( cur < limit && ( *cur == ' ' || *cur == '\t' ) ) cur++; if ( cur + 1 >= limit ) return 0; if ( *cur == '(' ) cur++; /* skip the opening parenthesis, if there is one */ *cursor = cur; count = 0; /* then, count its length */ for ( ; cur < limit; cur++ ) { if ( *cur == '(' ) count++; else if ( *cur == ')' ) { count--; if ( count < 0 ) break; } } len = (FT_UInt)( cur - *cursor ); if ( cur >= limit || FT_ALLOC( result, len + 1 ) ) return 0; /* now copy the string */ FT_MEM_COPY( result, *cursor, len ); result[len] = '\0'; *cursor = cur; return result; } #endif /* 0 */ static int ps_tobool( FT_Byte* *acur, FT_Byte* limit ) { FT_Byte* cur = *acur; FT_Bool result = 0; /* return 1 if we find `true', 0 otherwise */ if ( cur + 3 < limit && cur[0] == 't' && cur[1] == 'r' && cur[2] == 'u' && cur[3] == 'e' ) { result = 1; cur += 5; } else if ( cur + 4 < limit && cur[0] == 'f' && cur[1] == 'a' && cur[2] == 'l' && cur[3] == 's' && cur[4] == 'e' ) { result = 0; cur += 6; } *acur = cur; return result; } /* load a simple field (i.e. non-table) into the current list of objects */ FT_LOCAL_DEF( FT_Error ) ps_parser_load_field( PS_Parser parser, const T1_Field field, void** objects, FT_UInt max_objects, FT_ULong* pflags ) { T1_TokenRec token; FT_Byte* cur; FT_Byte* limit; FT_UInt count; FT_UInt idx; FT_Error error; T1_FieldType type; /* this also skips leading whitespace */ ps_parser_to_token( parser, &token ); if ( !token.type ) goto Fail; count = 1; idx = 0; cur = token.start; limit = token.limit; type = field->type; /* we must detect arrays in /FontBBox */ if ( type == T1_FIELD_TYPE_BBOX ) { T1_TokenRec token2; FT_Byte* old_cur = parser->cursor; FT_Byte* old_limit = parser->limit; /* don't include delimiters */ parser->cursor = token.start + 1; parser->limit = token.limit - 1; ps_parser_to_token( parser, &token2 ); parser->cursor = old_cur; parser->limit = old_limit; if ( token2.type == T1_TOKEN_TYPE_ARRAY ) { type = T1_FIELD_TYPE_MM_BBOX; goto FieldArray; } } else if ( token.type == T1_TOKEN_TYPE_ARRAY ) { count = max_objects; FieldArray: /* if this is an array and we have no blend, an error occurs */ if ( max_objects == 0 ) goto Fail; idx = 1; /* don't include delimiters */ cur++; limit--; } for ( ; count > 0; count--, idx++ ) { FT_Byte* q = (FT_Byte*)objects[idx] + field->offset; FT_Long val; FT_String* string = NULL; skip_spaces( &cur, limit ); switch ( type ) { case T1_FIELD_TYPE_BOOL: val = ps_tobool( &cur, limit ); goto Store_Integer; case T1_FIELD_TYPE_FIXED: val = PS_Conv_ToFixed( &cur, limit, 0 ); goto Store_Integer; case T1_FIELD_TYPE_FIXED_1000: val = PS_Conv_ToFixed( &cur, limit, 3 ); goto Store_Integer; case T1_FIELD_TYPE_INTEGER: val = PS_Conv_ToInt( &cur, limit ); /* fall through */ Store_Integer: switch ( field->size ) { case (8 / FT_CHAR_BIT): *(FT_Byte*)q = (FT_Byte)val; break; case (16 / FT_CHAR_BIT): *(FT_UShort*)q = (FT_UShort)val; break; case (32 / FT_CHAR_BIT): *(FT_UInt32*)q = (FT_UInt32)val; break; default: /* for 64-bit systems */ *(FT_Long*)q = val; } break; case T1_FIELD_TYPE_STRING: case T1_FIELD_TYPE_KEY: { FT_Memory memory = parser->memory; FT_UInt len = (FT_UInt)( limit - cur ); if ( cur >= limit ) break; /* we allow both a string or a name */ /* for cases like /FontName (foo) def */ if ( token.type == T1_TOKEN_TYPE_KEY ) { /* don't include leading `/' */ len--; cur++; } else if ( token.type == T1_TOKEN_TYPE_STRING ) { /* don't include delimiting parentheses */ /* XXX we don't handle <<...>> here */ /* XXX should we convert octal escapes? */ /* if so, what encoding should we use? */ cur++; len -= 2; } else { FT_ERROR(( "ps_parser_load_field:" " expected a name or string\n" " " " but found token of type %d instead\n", token.type )); error = FT_THROW( Invalid_File_Format ); goto Exit; } /* for this to work (FT_String**)q must have been */ /* initialized to NULL */ if ( *(FT_String**)q ) { FT_TRACE0(( "ps_parser_load_field: overwriting field %s\n", field->ident )); FT_FREE( *(FT_String**)q ); *(FT_String**)q = NULL; } if ( FT_ALLOC( string, len + 1 ) ) goto Exit; FT_MEM_COPY( string, cur, len ); string[len] = 0; *(FT_String**)q = string; } break; case T1_FIELD_TYPE_BBOX: { FT_Fixed temp[4]; FT_BBox* bbox = (FT_BBox*)q; FT_Int result; result = ps_tofixedarray( &cur, limit, 4, temp, 0 ); if ( result < 4 ) { FT_ERROR(( "ps_parser_load_field:" " expected four integers in bounding box\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } bbox->xMin = FT_RoundFix( temp[0] ); bbox->yMin = FT_RoundFix( temp[1] ); bbox->xMax = FT_RoundFix( temp[2] ); bbox->yMax = FT_RoundFix( temp[3] ); } break; case T1_FIELD_TYPE_MM_BBOX: { FT_Memory memory = parser->memory; FT_Fixed* temp = NULL; FT_Int result; FT_UInt i; if ( FT_NEW_ARRAY( temp, max_objects * 4 ) ) goto Exit; for ( i = 0; i < 4; i++ ) { result = ps_tofixedarray( &cur, limit, (FT_Int)max_objects, temp + i * max_objects, 0 ); if ( result < 0 || (FT_UInt)result < max_objects ) { FT_ERROR(( "ps_parser_load_field:" " expected %d integer%s in the %s subarray\n" " " " of /FontBBox in the /Blend dictionary\n", max_objects, max_objects > 1 ? "s" : "", i == 0 ? "first" : ( i == 1 ? "second" : ( i == 2 ? "third" : "fourth" ) ) )); error = FT_THROW( Invalid_File_Format ); FT_FREE( temp ); goto Exit; } skip_spaces( &cur, limit ); } for ( i = 0; i < max_objects; i++ ) { FT_BBox* bbox = (FT_BBox*)objects[i]; bbox->xMin = FT_RoundFix( temp[i ] ); bbox->yMin = FT_RoundFix( temp[i + max_objects] ); bbox->xMax = FT_RoundFix( temp[i + 2 * max_objects] ); bbox->yMax = FT_RoundFix( temp[i + 3 * max_objects] ); } FT_FREE( temp ); } break; default: /* an error occurred */ goto Fail; } } #if 0 /* obsolete -- keep for reference */ if ( pflags ) *pflags |= 1L << field->flag_bit; #else FT_UNUSED( pflags ); #endif error = FT_Err_Ok; Exit: return error; Fail: error = FT_THROW( Invalid_File_Format ); goto Exit; } #define T1_MAX_TABLE_ELEMENTS 32 FT_LOCAL_DEF( FT_Error ) ps_parser_load_field_table( PS_Parser parser, const T1_Field field, void** objects, FT_UInt max_objects, FT_ULong* pflags ) { T1_TokenRec elements[T1_MAX_TABLE_ELEMENTS]; T1_Token token; FT_Int num_elements; FT_Error error = FT_Err_Ok; FT_Byte* old_cursor; FT_Byte* old_limit; T1_FieldRec fieldrec = *(T1_Field)field; fieldrec.type = T1_FIELD_TYPE_INTEGER; if ( field->type == T1_FIELD_TYPE_FIXED_ARRAY || field->type == T1_FIELD_TYPE_BBOX ) fieldrec.type = T1_FIELD_TYPE_FIXED; ps_parser_to_token_array( parser, elements, T1_MAX_TABLE_ELEMENTS, &num_elements ); if ( num_elements < 0 ) { error = FT_ERR( Ignore ); goto Exit; } if ( (FT_UInt)num_elements > field->array_max ) num_elements = (FT_Int)field->array_max; old_cursor = parser->cursor; old_limit = parser->limit; /* we store the elements count if necessary; */ /* we further assume that `count_offset' can't be zero */ if ( field->type != T1_FIELD_TYPE_BBOX && field->count_offset != 0 ) *(FT_Byte*)( (FT_Byte*)objects[0] + field->count_offset ) = (FT_Byte)num_elements; /* we now load each element, adjusting the field.offset on each one */ token = elements; for ( ; num_elements > 0; num_elements--, token++ ) { parser->cursor = token->start; parser->limit = token->limit; error = ps_parser_load_field( parser, &fieldrec, objects, max_objects, 0 ); if ( error ) break; fieldrec.offset += fieldrec.size; } #if 0 /* obsolete -- keep for reference */ if ( pflags ) *pflags |= 1L << field->flag_bit; #else FT_UNUSED( pflags ); #endif parser->cursor = old_cursor; parser->limit = old_limit; Exit: return error; } FT_LOCAL_DEF( FT_Long ) ps_parser_to_int( PS_Parser parser ) { ps_parser_skip_spaces( parser ); return PS_Conv_ToInt( &parser->cursor, parser->limit ); } /* first character must be `<' if `delimiters' is non-zero */ FT_LOCAL_DEF( FT_Error ) ps_parser_to_bytes( PS_Parser parser, FT_Byte* bytes, FT_Offset max_bytes, FT_ULong* pnum_bytes, FT_Bool delimiters ) { FT_Error error = FT_Err_Ok; FT_Byte* cur; ps_parser_skip_spaces( parser ); cur = parser->cursor; if ( cur >= parser->limit ) goto Exit; if ( delimiters ) { if ( *cur != '<' ) { FT_ERROR(( "ps_parser_to_bytes: Missing starting delimiter `<'\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } cur++; } *pnum_bytes = PS_Conv_ASCIIHexDecode( &cur, parser->limit, bytes, max_bytes ); if ( delimiters ) { if ( cur < parser->limit && *cur != '>' ) { FT_ERROR(( "ps_parser_to_bytes: Missing closing delimiter `>'\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } cur++; } parser->cursor = cur; Exit: return error; } FT_LOCAL_DEF( FT_Fixed ) ps_parser_to_fixed( PS_Parser parser, FT_Int power_ten ) { ps_parser_skip_spaces( parser ); return PS_Conv_ToFixed( &parser->cursor, parser->limit, power_ten ); } FT_LOCAL_DEF( FT_Int ) ps_parser_to_coord_array( PS_Parser parser, FT_Int max_coords, FT_Short* coords ) { ps_parser_skip_spaces( parser ); return ps_tocoordarray( &parser->cursor, parser->limit, max_coords, coords ); } FT_LOCAL_DEF( FT_Int ) ps_parser_to_fixed_array( PS_Parser parser, FT_Int max_values, FT_Fixed* values, FT_Int power_ten ) { ps_parser_skip_spaces( parser ); return ps_tofixedarray( &parser->cursor, parser->limit, max_values, values, power_ten ); } #if 0 FT_LOCAL_DEF( FT_String* ) T1_ToString( PS_Parser parser ) { return ps_tostring( &parser->cursor, parser->limit, parser->memory ); } FT_LOCAL_DEF( FT_Bool ) T1_ToBool( PS_Parser parser ) { return ps_tobool( &parser->cursor, parser->limit ); } #endif /* 0 */ FT_LOCAL_DEF( void ) ps_parser_init( PS_Parser parser, FT_Byte* base, FT_Byte* limit, FT_Memory memory ) { parser->error = FT_Err_Ok; parser->base = base; parser->limit = limit; parser->cursor = base; parser->memory = memory; parser->funcs = ps_parser_funcs; } FT_LOCAL_DEF( void ) ps_parser_done( PS_Parser parser ) { FT_UNUSED( parser ); } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** T1 BUILDER *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* t1_builder_init */ /* */ /* <Description> */ /* Initializes a given glyph builder. */ /* */ /* <InOut> */ /* builder :: A pointer to the glyph builder to initialize. */ /* */ /* <Input> */ /* face :: The current face object. */ /* */ /* size :: The current size object. */ /* */ /* glyph :: The current glyph object. */ /* */ /* hinting :: Whether hinting should be applied. */ /* */ FT_LOCAL_DEF( void ) t1_builder_init( T1_Builder builder, FT_Face face, FT_Size size, FT_GlyphSlot glyph, FT_Bool hinting ) { builder->parse_state = T1_Parse_Start; builder->load_points = 1; builder->face = face; builder->glyph = glyph; builder->memory = face->memory; if ( glyph ) { FT_GlyphLoader loader = glyph->internal->loader; builder->loader = loader; builder->base = &loader->base.outline; builder->current = &loader->current.outline; FT_GlyphLoader_Rewind( loader ); builder->hints_globals = size->internal; builder->hints_funcs = NULL; if ( hinting ) builder->hints_funcs = glyph->internal->glyph_hints; } builder->pos_x = 0; builder->pos_y = 0; builder->left_bearing.x = 0; builder->left_bearing.y = 0; builder->advance.x = 0; builder->advance.y = 0; builder->funcs = t1_builder_funcs; } /*************************************************************************/ /* */ /* <Function> */ /* t1_builder_done */ /* */ /* <Description> */ /* Finalizes a given glyph builder. Its contents can still be used */ /* after the call, but the function saves important information */ /* within the corresponding glyph slot. */ /* */ /* <Input> */ /* builder :: A pointer to the glyph builder to finalize. */ /* */ FT_LOCAL_DEF( void ) t1_builder_done( T1_Builder builder ) { FT_GlyphSlot glyph = builder->glyph; if ( glyph ) glyph->outline = *builder->base; } /* check that there is enough space for `count' more points */ FT_LOCAL_DEF( FT_Error ) t1_builder_check_points( T1_Builder builder, FT_Int count ) { return FT_GLYPHLOADER_CHECK_POINTS( builder->loader, count, 0 ); } /* add a new point, do not check space */ FT_LOCAL_DEF( void ) t1_builder_add_point( T1_Builder builder, FT_Pos x, FT_Pos y, FT_Byte flag ) { FT_Outline* outline = builder->current; if ( builder->load_points ) { FT_Vector* point = outline->points + outline->n_points; FT_Byte* control = (FT_Byte*)outline->tags + outline->n_points; point->x = FIXED_TO_INT( x ); point->y = FIXED_TO_INT( y ); *control = (FT_Byte)( flag ? FT_CURVE_TAG_ON : FT_CURVE_TAG_CUBIC ); } outline->n_points++; } /* check space for a new on-curve point, then add it */ FT_LOCAL_DEF( FT_Error ) t1_builder_add_point1( T1_Builder builder, FT_Pos x, FT_Pos y ) { FT_Error error; error = t1_builder_check_points( builder, 1 ); if ( !error ) t1_builder_add_point( builder, x, y, 1 ); return error; } /* check space for a new contour, then add it */ FT_LOCAL_DEF( FT_Error ) t1_builder_add_contour( T1_Builder builder ) { FT_Outline* outline = builder->current; FT_Error error; /* this might happen in invalid fonts */ if ( !outline ) { FT_ERROR(( "t1_builder_add_contour: no outline to add points to\n" )); return FT_THROW( Invalid_File_Format ); } if ( !builder->load_points ) { outline->n_contours++; return FT_Err_Ok; } error = FT_GLYPHLOADER_CHECK_POINTS( builder->loader, 0, 1 ); if ( !error ) { if ( outline->n_contours > 0 ) outline->contours[outline->n_contours - 1] = (short)( outline->n_points - 1 ); outline->n_contours++; } return error; } /* if a path was begun, add its first on-curve point */ FT_LOCAL_DEF( FT_Error ) t1_builder_start_point( T1_Builder builder, FT_Pos x, FT_Pos y ) { FT_Error error = FT_ERR( Invalid_File_Format ); /* test whether we are building a new contour */ if ( builder->parse_state == T1_Parse_Have_Path ) error = FT_Err_Ok; else { builder->parse_state = T1_Parse_Have_Path; error = t1_builder_add_contour( builder ); if ( !error ) error = t1_builder_add_point1( builder, x, y ); } return error; } /* close the current contour */ FT_LOCAL_DEF( void ) t1_builder_close_contour( T1_Builder builder ) { FT_Outline* outline = builder->current; FT_Int first; if ( !outline ) return; first = outline->n_contours <= 1 ? 0 : outline->contours[outline->n_contours - 2] + 1; /* in malformed fonts it can happen that a contour was started */ /* but no points were added */ if ( outline->n_contours && first == outline->n_points ) { outline->n_contours--; return; } /* We must not include the last point in the path if it */ /* is located on the first point. */ if ( outline->n_points > 1 ) if ( p1->x == p2->x && p1->y == p2->y ) if ( *control == FT_CURVE_TAG_ON ) outline->n_points--; } if ( outline->n_contours > 0 ) { /* Don't add contours only consisting of one point, i.e., */ /* check whether the first and the last point is the same. */ if ( first == outline->n_points - 1 ) { outline->n_contours--; outline->n_points--; } else outline->contours[outline->n_contours - 1] = (short)( outline->n_points - 1 ); } }
271,086,143,539,799,130,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2017-8287
FreeType 2 before 2017-03-26 has an out-of-bounds write caused by a heap-based buffer overflow related to the t1_builder_close_contour function in psaux/psobjs.c.
https://nvd.nist.gov/vuln/detail/CVE-2017-8287
211
savannah
f958c48ee431bef8d4d466b40c9cb2d4dbcb7791
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=f958c48ee431bef8d4d466b40c9cb2d4dbcb7791
None
1
t1_decoder_parse_charstrings( T1_Decoder decoder, FT_Byte* charstring_base, FT_UInt charstring_len ) { FT_Error error; T1_Decoder_Zone zone; FT_Byte* ip; FT_Byte* limit; T1_Builder builder = &decoder->builder; FT_Pos x, y, orig_x, orig_y; FT_Int known_othersubr_result_cnt = 0; FT_Int unknown_othersubr_result_cnt = 0; FT_Bool large_int; FT_Fixed seed; T1_Hints_Funcs hinter; #ifdef FT_DEBUG_LEVEL_TRACE FT_Bool bol = TRUE; #endif /* compute random seed from stack address of parameter */ seed = (FT_Fixed)( ( (FT_Offset)(char*)&seed ^ (FT_Offset)(char*)&decoder ^ (FT_Offset)(char*)&charstring_base ) & FT_ULONG_MAX ); seed = ( seed ^ ( seed >> 10 ) ^ ( seed >> 20 ) ) & 0xFFFFL; if ( seed == 0 ) seed = 0x7384; /* First of all, initialize the decoder */ decoder->top = decoder->stack; decoder->zone = decoder->zones; zone = decoder->zones; builder->parse_state = T1_Parse_Start; hinter = (T1_Hints_Funcs)builder->hints_funcs; /* a font that reads BuildCharArray without setting */ /* its values first is buggy, but ... */ FT_ASSERT( ( decoder->len_buildchar == 0 ) == ( decoder->buildchar == NULL ) ); if ( decoder->buildchar && decoder->len_buildchar > 0 ) FT_ARRAY_ZERO( decoder->buildchar, decoder->len_buildchar ); FT_TRACE4(( "\n" "Start charstring\n" )); zone->base = charstring_base; limit = zone->limit = charstring_base + charstring_len; ip = zone->cursor = zone->base; error = FT_Err_Ok; x = orig_x = builder->pos_x; y = orig_y = builder->pos_y; /* begin hints recording session, if any */ if ( hinter ) hinter->open( hinter->hints ); large_int = FALSE; /* now, execute loop */ while ( ip < limit ) { FT_Long* top = decoder->top; T1_Operator op = op_none; FT_Int32 value = 0; FT_ASSERT( known_othersubr_result_cnt == 0 || unknown_othersubr_result_cnt == 0 ); #ifdef FT_DEBUG_LEVEL_TRACE if ( bol ) { FT_TRACE5(( " (%d)", decoder->top - decoder->stack )); bol = FALSE; } #endif /*********************************************************************/ /* */ /* Decode operator or operand */ /* */ /* */ /* first of all, decompress operator or value */ switch ( *ip++ ) { case 1: op = op_hstem; break; case 3: op = op_vstem; break; case 4: op = op_vmoveto; break; case 5: op = op_rlineto; break; case 6: op = op_hlineto; break; case 7: op = op_vlineto; break; case 8: op = op_rrcurveto; break; case 9: op = op_closepath; break; case 10: op = op_callsubr; break; case 11: op = op_return; break; case 13: op = op_hsbw; break; case 14: op = op_endchar; break; case 15: /* undocumented, obsolete operator */ op = op_unknown15; break; case 21: op = op_rmoveto; break; case 22: op = op_hmoveto; break; case 30: op = op_vhcurveto; break; case 31: op = op_hvcurveto; break; case 12: if ( ip >= limit ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " invalid escape (12+EOF)\n" )); goto Syntax_Error; } switch ( *ip++ ) { case 0: op = op_dotsection; break; case 1: op = op_vstem3; break; case 2: op = op_hstem3; break; case 6: op = op_seac; break; case 7: op = op_sbw; break; case 12: op = op_div; break; case 16: op = op_callothersubr; break; case 17: op = op_pop; break; case 33: op = op_setcurrentpoint; break; default: FT_ERROR(( "t1_decoder_parse_charstrings:" " invalid escape (12+%d)\n", ip[-1] )); goto Syntax_Error; } break; case 255: /* four bytes integer */ if ( ip + 4 > limit ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " unexpected EOF in integer\n" )); goto Syntax_Error; } value = (FT_Int32)( ( (FT_UInt32)ip[0] << 24 ) | ( (FT_UInt32)ip[1] << 16 ) | ( (FT_UInt32)ip[2] << 8 ) | (FT_UInt32)ip[3] ); ip += 4; /* According to the specification, values > 32000 or < -32000 must */ /* be followed by a `div' operator to make the result be in the */ /* range [-32000;32000]. We expect that the second argument of */ /* `div' is not a large number. Additionally, we don't handle */ /* stuff like `<large1> <large2> <num> div <num> div' or */ /* <large1> <large2> <num> div div'. This is probably not allowed */ /* anyway. */ if ( value > 32000 || value < -32000 ) { if ( large_int ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " no `div' after large integer\n" )); } else large_int = TRUE; } else { if ( !large_int ) value = (FT_Int32)( (FT_UInt32)value << 16 ); } break; default: if ( ip[-1] >= 32 ) { if ( ip[-1] < 247 ) value = (FT_Int32)ip[-1] - 139; else { if ( ++ip > limit ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " unexpected EOF in integer\n" )); goto Syntax_Error; } if ( ip[-2] < 251 ) value = ( ( ip[-2] - 247 ) * 256 ) + ip[-1] + 108; else value = -( ( ( ip[-2] - 251 ) * 256 ) + ip[-1] + 108 ); } if ( !large_int ) value = (FT_Int32)( (FT_UInt32)value << 16 ); } else { FT_ERROR(( "t1_decoder_parse_charstrings:" " invalid byte (%d)\n", ip[-1] )); goto Syntax_Error; } } if ( unknown_othersubr_result_cnt > 0 ) { switch ( op ) { case op_callsubr: case op_return: case op_none: case op_pop: break; default: /* all operands have been transferred by previous pops */ unknown_othersubr_result_cnt = 0; break; } } if ( large_int && !( op == op_none || op == op_div ) ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " no `div' after large integer\n" )); large_int = FALSE; } /*********************************************************************/ /* */ /* Push value on stack, or process operator */ /* */ /* */ if ( op == op_none ) { if ( top - decoder->stack >= T1_MAX_CHARSTRINGS_OPERANDS ) { FT_ERROR(( "t1_decoder_parse_charstrings: stack overflow\n" )); goto Syntax_Error; } #ifdef FT_DEBUG_LEVEL_TRACE if ( large_int ) FT_TRACE4(( " %d", value )); else FT_TRACE4(( " %d", value / 65536 )); #endif *top++ = value; decoder->top = top; } else if ( op == op_callothersubr ) /* callothersubr */ { FT_Int subr_no; FT_Int arg_cnt; #ifdef FT_DEBUG_LEVEL_TRACE FT_TRACE4(( " callothersubr\n" )); bol = TRUE; #endif if ( top - decoder->stack < 2 ) goto Stack_Underflow; top -= 2; subr_no = Fix2Int( top[1] ); arg_cnt = Fix2Int( top[0] ); /***********************************************************/ /* */ /* remove all operands to callothersubr from the stack */ /* */ /* for handled othersubrs, where we know the number of */ /* arguments, we increase the stack by the value of */ /* known_othersubr_result_cnt */ /* */ /* for unhandled othersubrs the following pops adjust the */ /* stack pointer as necessary */ if ( arg_cnt > top - decoder->stack ) goto Stack_Underflow; top -= arg_cnt; known_othersubr_result_cnt = 0; unknown_othersubr_result_cnt = 0; /* XXX TODO: The checks to `arg_count == <whatever>' */ /* might not be correct; an othersubr expects a certain */ /* number of operands on the PostScript stack (as opposed */ /* to the T1 stack) but it doesn't have to put them there */ /* by itself; previous othersubrs might have left the */ /* operands there if they were not followed by an */ /* appropriate number of pops */ /* */ /* On the other hand, Adobe Reader 7.0.8 for Linux doesn't */ /* accept a font that contains charstrings like */ /* */ /* 100 200 2 20 callothersubr */ /* 300 1 20 callothersubr pop */ /* */ /* Perhaps this is the reason why BuildCharArray exists. */ switch ( subr_no ) { case 0: /* end flex feature */ if ( arg_cnt != 3 ) goto Unexpected_OtherSubr; if ( !decoder->flex_state || decoder->num_flex_vectors != 7 ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " unexpected flex end\n" )); goto Syntax_Error; } /* the two `results' are popped by the following setcurrentpoint */ top[0] = x; top[1] = y; known_othersubr_result_cnt = 2; break; case 1: /* start flex feature */ if ( arg_cnt != 0 ) goto Unexpected_OtherSubr; if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) || FT_SET_ERROR( t1_builder_check_points( builder, 6 ) ) ) goto Fail; decoder->flex_state = 1; decoder->num_flex_vectors = 0; break; case 2: /* add flex vectors */ { FT_Int idx; if ( arg_cnt != 0 ) goto Unexpected_OtherSubr; if ( !decoder->flex_state ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " missing flex start\n" )); goto Syntax_Error; } /* note that we should not add a point for index 0; */ /* this will move our current position to the flex */ /* point without adding any point to the outline */ idx = decoder->num_flex_vectors++; if ( idx > 0 && idx < 7 ) t1_builder_add_point( builder, x, y, (FT_Byte)( idx == 3 || idx == 6 ) ); } break; break; case 12: case 13: /* counter control hints, clear stack */ top = decoder->stack; break; case 14: case 15: case 16: case 17: case 18: /* multiple masters */ { PS_Blend blend = decoder->blend; FT_UInt num_points, nn, mm; FT_Long* delta; FT_Long* values; if ( !blend ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " unexpected multiple masters operator\n" )); goto Syntax_Error; } num_points = (FT_UInt)subr_no - 13 + ( subr_no == 18 ); if ( arg_cnt != (FT_Int)( num_points * blend->num_designs ) ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " incorrect number of multiple masters arguments\n" )); goto Syntax_Error; } /* We want to compute */ /* */ /* a0*w0 + a1*w1 + ... + ak*wk */ /* */ /* but we only have a0, a1-a0, a2-a0, ..., ak-a0. */ /* */ /* However, given that w0 + w1 + ... + wk == 1, we can */ /* rewrite it easily as */ /* */ /* a0 + (a1-a0)*w1 + (a2-a0)*w2 + ... + (ak-a0)*wk */ /* */ /* where k == num_designs-1. */ /* */ /* I guess that's why it's written in this `compact' */ /* form. */ /* */ delta = top + num_points; values = top; for ( nn = 0; nn < num_points; nn++ ) { FT_Long tmp = values[0]; for ( mm = 1; mm < blend->num_designs; mm++ ) tmp += FT_MulFix( *delta++, blend->weight_vector[mm] ); *values++ = tmp; } known_othersubr_result_cnt = (FT_Int)num_points; break; } case 19: /* <idx> 1 19 callothersubr */ /* => replace elements starting from index cvi( <idx> ) */ /* of BuildCharArray with WeightVector */ { FT_Int idx; PS_Blend blend = decoder->blend; if ( arg_cnt != 1 || !blend ) goto Unexpected_OtherSubr; idx = Fix2Int( top[0] ); if ( idx < 0 || (FT_UInt)idx + blend->num_designs > decoder->len_buildchar ) goto Unexpected_OtherSubr; ft_memcpy( &decoder->buildchar[idx], blend->weight_vector, blend->num_designs * sizeof ( blend->weight_vector[0] ) ); } break; case 20: /* <arg1> <arg2> 2 20 callothersubr pop */ /* ==> push <arg1> + <arg2> onto T1 stack */ if ( arg_cnt != 2 ) goto Unexpected_OtherSubr; top[0] += top[1]; /* XXX (over|under)flow */ known_othersubr_result_cnt = 1; break; case 21: /* <arg1> <arg2> 2 21 callothersubr pop */ /* ==> push <arg1> - <arg2> onto T1 stack */ if ( arg_cnt != 2 ) goto Unexpected_OtherSubr; top[0] -= top[1]; /* XXX (over|under)flow */ known_othersubr_result_cnt = 1; break; case 22: /* <arg1> <arg2> 2 22 callothersubr pop */ /* ==> push <arg1> * <arg2> onto T1 stack */ if ( arg_cnt != 2 ) goto Unexpected_OtherSubr; top[0] = FT_MulFix( top[0], top[1] ); known_othersubr_result_cnt = 1; break; case 23: /* <arg1> <arg2> 2 23 callothersubr pop */ /* ==> push <arg1> / <arg2> onto T1 stack */ if ( arg_cnt != 2 || top[1] == 0 ) goto Unexpected_OtherSubr; top[0] = FT_DivFix( top[0], top[1] ); known_othersubr_result_cnt = 1; break; case 24: /* <val> <idx> 2 24 callothersubr */ /* ==> set BuildCharArray[cvi( <idx> )] = <val> */ { FT_Int idx; PS_Blend blend = decoder->blend; if ( arg_cnt != 2 || !blend ) goto Unexpected_OtherSubr; idx = Fix2Int( top[1] ); if ( idx < 0 || (FT_UInt) idx >= decoder->len_buildchar ) goto Unexpected_OtherSubr; decoder->buildchar[idx] = top[0]; } break; case 25: /* <idx> 1 25 callothersubr pop */ /* ==> push BuildCharArray[cvi( idx )] */ /* onto T1 stack */ { FT_Int idx; PS_Blend blend = decoder->blend; if ( arg_cnt != 1 || !blend ) goto Unexpected_OtherSubr; idx = Fix2Int( top[0] ); if ( idx < 0 || (FT_UInt) idx >= decoder->len_buildchar ) goto Unexpected_OtherSubr; top[0] = decoder->buildchar[idx]; } known_othersubr_result_cnt = 1; break; #if 0 case 26: /* <val> mark <idx> ==> set BuildCharArray[cvi( <idx> )] = <val>, */ /* leave mark on T1 stack */ /* <val> <idx> ==> set BuildCharArray[cvi( <idx> )] = <val> */ XXX which routine has left its mark on the (PostScript) stack?; break; #endif case 27: /* <res1> <res2> <val1> <val2> 4 27 callothersubr pop */ /* ==> push <res1> onto T1 stack if <val1> <= <val2>, */ /* otherwise push <res2> */ if ( arg_cnt != 4 ) goto Unexpected_OtherSubr; if ( top[2] > top[3] ) top[0] = top[1]; known_othersubr_result_cnt = 1; break; case 28: /* 0 28 callothersubr pop */ /* => push random value from interval [0, 1) onto stack */ if ( arg_cnt != 0 ) goto Unexpected_OtherSubr; { FT_Fixed Rand; Rand = seed; if ( Rand >= 0x8000L ) Rand++; top[0] = Rand; seed = FT_MulFix( seed, 0x10000L - seed ); if ( seed == 0 ) seed += 0x2873; } known_othersubr_result_cnt = 1; break; default: if ( arg_cnt >= 0 && subr_no >= 0 ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " unknown othersubr [%d %d], wish me luck\n", arg_cnt, subr_no )); unknown_othersubr_result_cnt = arg_cnt; break; } /* fall through */ Unexpected_OtherSubr: FT_ERROR(( "t1_decoder_parse_charstrings:" " invalid othersubr [%d %d]\n", arg_cnt, subr_no )); goto Syntax_Error; } top += known_othersubr_result_cnt; decoder->top = top; } else /* general operator */ { FT_Int num_args = t1_args_count[op]; FT_ASSERT( num_args >= 0 ); if ( top - decoder->stack < num_args ) goto Stack_Underflow; /* XXX Operators usually take their operands from the */ /* bottom of the stack, i.e., the operands are */ /* decoder->stack[0], ..., decoder->stack[num_args - 1]; */ /* only div, callsubr, and callothersubr are different. */ /* In practice it doesn't matter (?). */ #ifdef FT_DEBUG_LEVEL_TRACE switch ( op ) { case op_callsubr: case op_div: case op_callothersubr: case op_pop: case op_return: break; default: if ( top - decoder->stack != num_args ) FT_TRACE0(( "t1_decoder_parse_charstrings:" " too much operands on the stack" " (seen %d, expected %d)\n", top - decoder->stack, num_args )); break; } #endif /* FT_DEBUG_LEVEL_TRACE */ top -= num_args; switch ( op ) { case op_endchar: FT_TRACE4(( " endchar\n" )); t1_builder_close_contour( builder ); /* close hints recording session */ if ( hinter ) { if ( hinter->close( hinter->hints, (FT_UInt)builder->current->n_points ) ) goto Syntax_Error; /* apply hints to the loaded glyph outline now */ error = hinter->apply( hinter->hints, builder->current, (PSH_Globals)builder->hints_globals, decoder->hint_mode ); if ( error ) goto Fail; } /* add current outline to the glyph slot */ FT_GlyphLoader_Add( builder->loader ); /* the compiler should optimize away this empty loop but ... */ #ifdef FT_DEBUG_LEVEL_TRACE if ( decoder->len_buildchar > 0 ) { FT_UInt i; FT_TRACE4(( "BuildCharArray = [ " )); for ( i = 0; i < decoder->len_buildchar; i++ ) FT_TRACE4(( "%d ", decoder->buildchar[i] )); FT_TRACE4(( "]\n" )); } #endif /* FT_DEBUG_LEVEL_TRACE */ FT_TRACE4(( "\n" )); /* return now! */ return FT_Err_Ok; case op_hsbw: FT_TRACE4(( " hsbw" )); builder->parse_state = T1_Parse_Have_Width; builder->left_bearing.x += top[0]; builder->advance.x = top[1]; builder->advance.y = 0; orig_x = x = builder->pos_x + top[0]; orig_y = y = builder->pos_y; FT_UNUSED( orig_y ); /* the `metrics_only' indicates that we only want to compute */ /* the glyph's metrics (lsb + advance width), not load the */ /* rest of it; so exit immediately */ if ( builder->metrics_only ) return FT_Err_Ok; break; case op_seac: return t1operator_seac( decoder, top[0], top[1], top[2], Fix2Int( top[3] ), Fix2Int( top[4] ) ); case op_sbw: FT_TRACE4(( " sbw" )); builder->parse_state = T1_Parse_Have_Width; builder->left_bearing.x += top[0]; builder->left_bearing.y += top[1]; builder->advance.x = top[2]; builder->advance.y = top[3]; x = builder->pos_x + top[0]; y = builder->pos_y + top[1]; /* the `metrics_only' indicates that we only want to compute */ /* the glyph's metrics (lsb + advance width), not load the */ /* rest of it; so exit immediately */ if ( builder->metrics_only ) return FT_Err_Ok; break; case op_closepath: FT_TRACE4(( " closepath" )); /* if there is no path, `closepath' is a no-op */ if ( builder->parse_state == T1_Parse_Have_Path || builder->parse_state == T1_Parse_Have_Moveto ) t1_builder_close_contour( builder ); builder->parse_state = T1_Parse_Have_Width; break; case op_hlineto: FT_TRACE4(( " hlineto" )); if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ) goto Fail; x += top[0]; goto Add_Line; case op_hmoveto: FT_TRACE4(( " hmoveto" )); x += top[0]; if ( !decoder->flex_state ) { if ( builder->parse_state == T1_Parse_Start ) goto Syntax_Error; builder->parse_state = T1_Parse_Have_Moveto; } break; case op_hvcurveto: FT_TRACE4(( " hvcurveto" )); if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) || FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) ) goto Fail; x += top[0]; t1_builder_add_point( builder, x, y, 0 ); x += top[1]; y += top[2]; t1_builder_add_point( builder, x, y, 0 ); y += top[3]; t1_builder_add_point( builder, x, y, 1 ); break; case op_rlineto: FT_TRACE4(( " rlineto" )); if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ) goto Fail; x += top[0]; y += top[1]; Add_Line: if ( FT_SET_ERROR( t1_builder_add_point1( builder, x, y ) ) ) goto Fail; break; case op_rmoveto: FT_TRACE4(( " rmoveto" )); x += top[0]; y += top[1]; if ( !decoder->flex_state ) { if ( builder->parse_state == T1_Parse_Start ) goto Syntax_Error; builder->parse_state = T1_Parse_Have_Moveto; } break; case op_rrcurveto: FT_TRACE4(( " rrcurveto" )); if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) || FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) ) goto Fail; x += top[0]; y += top[1]; t1_builder_add_point( builder, x, y, 0 ); x += top[2]; y += top[3]; t1_builder_add_point( builder, x, y, 0 ); x += top[4]; y += top[5]; t1_builder_add_point( builder, x, y, 1 ); break; case op_vhcurveto: FT_TRACE4(( " vhcurveto" )); if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) || FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) ) goto Fail; y += top[0]; t1_builder_add_point( builder, x, y, 0 ); x += top[1]; y += top[2]; t1_builder_add_point( builder, x, y, 0 ); x += top[3]; t1_builder_add_point( builder, x, y, 1 ); break; case op_vlineto: FT_TRACE4(( " vlineto" )); if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ) goto Fail; y += top[0]; goto Add_Line; case op_vmoveto: FT_TRACE4(( " vmoveto" )); y += top[0]; if ( !decoder->flex_state ) { if ( builder->parse_state == T1_Parse_Start ) goto Syntax_Error; builder->parse_state = T1_Parse_Have_Moveto; } break; case op_div: FT_TRACE4(( " div" )); /* if `large_int' is set, we divide unscaled numbers; */ /* otherwise, we divide numbers in 16.16 format -- */ /* in both cases, it is the same operation */ *top = FT_DivFix( top[0], top[1] ); top++; large_int = FALSE; break; case op_callsubr: { FT_Int idx; FT_TRACE4(( " callsubr" )); idx = Fix2Int( top[0] ); if ( decoder->subrs_hash ) { size_t* val = ft_hash_num_lookup( idx, decoder->subrs_hash ); if ( val ) idx = *val; else idx = -1; } if ( idx < 0 || idx >= decoder->num_subrs ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " invalid subrs index\n" )); goto Syntax_Error; } if ( zone - decoder->zones >= T1_MAX_SUBRS_CALLS ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " too many nested subrs\n" )); goto Syntax_Error; } zone->cursor = ip; /* save current instruction pointer */ zone++; /* The Type 1 driver stores subroutines without the seed bytes. */ /* The CID driver stores subroutines with seed bytes. This */ /* case is taken care of when decoder->subrs_len == 0. */ zone->base = decoder->subrs[idx]; if ( decoder->subrs_len ) zone->limit = zone->base + decoder->subrs_len[idx]; else { /* We are using subroutines from a CID font. We must adjust */ /* for the seed bytes. */ zone->base += ( decoder->lenIV >= 0 ? decoder->lenIV : 0 ); zone->limit = decoder->subrs[idx + 1]; } zone->cursor = zone->base; if ( !zone->base ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " invoking empty subrs\n" )); goto Syntax_Error; } decoder->zone = zone; ip = zone->base; limit = zone->limit; break; } case op_pop: FT_TRACE4(( " pop" )); if ( known_othersubr_result_cnt > 0 ) { known_othersubr_result_cnt--; /* ignore, we pushed the operands ourselves */ break; } if ( unknown_othersubr_result_cnt == 0 ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " no more operands for othersubr\n" )); goto Syntax_Error; } unknown_othersubr_result_cnt--; top++; /* `push' the operand to callothersubr onto the stack */ break; case op_return: FT_TRACE4(( " return" )); if ( zone <= decoder->zones ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " unexpected return\n" )); goto Syntax_Error; } zone--; ip = zone->cursor; limit = zone->limit; decoder->zone = zone; break; case op_dotsection: FT_TRACE4(( " dotsection" )); break; case op_hstem: FT_TRACE4(( " hstem" )); /* record horizontal hint */ if ( hinter ) { /* top[0] += builder->left_bearing.y; */ hinter->stem( hinter->hints, 1, top ); } break; case op_hstem3: FT_TRACE4(( " hstem3" )); /* record horizontal counter-controlled hints */ if ( hinter ) hinter->stem3( hinter->hints, 1, top ); break; case op_vstem: FT_TRACE4(( " vstem" )); /* record vertical hint */ if ( hinter ) { top[0] += orig_x; hinter->stem( hinter->hints, 0, top ); } break; case op_vstem3: FT_TRACE4(( " vstem3" )); /* record vertical counter-controlled hints */ if ( hinter ) { FT_Pos dx = orig_x; top[0] += dx; top[2] += dx; top[4] += dx; hinter->stem3( hinter->hints, 0, top ); } break; case op_setcurrentpoint: FT_TRACE4(( " setcurrentpoint" )); /* From the T1 specification, section 6.4: */ /* */ /* The setcurrentpoint command is used only in */ /* conjunction with results from OtherSubrs procedures. */ /* known_othersubr_result_cnt != 0 is already handled */ /* above. */ /* Note, however, that both Ghostscript and Adobe */ /* Distiller handle this situation by silently ignoring */ /* the inappropriate `setcurrentpoint' instruction. So */ /* we do the same. */ #if 0 if ( decoder->flex_state != 1 ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " unexpected `setcurrentpoint'\n" )); goto Syntax_Error; } else ... #endif x = top[0]; y = top[1]; decoder->flex_state = 0; break; case op_unknown15: FT_TRACE4(( " opcode_15" )); /* nothing to do except to pop the two arguments */ break; default: FT_ERROR(( "t1_decoder_parse_charstrings:" " unhandled opcode %d\n", op )); goto Syntax_Error; } /* XXX Operators usually clear the operand stack; */ /* only div, callsubr, callothersubr, pop, and */ /* return are different. */ /* In practice it doesn't matter (?). */ decoder->top = top; #ifdef FT_DEBUG_LEVEL_TRACE FT_TRACE4(( "\n" )); bol = TRUE; #endif } /* general operator processing */ } /* while ip < limit */ FT_TRACE4(( "..end..\n\n" )); Fail: return error; Syntax_Error: return FT_THROW( Syntax_Error ); Stack_Underflow: return FT_THROW( Stack_Underflow ); }
173,319,081,189,597,150,000,000,000,000,000,000,000
None
null
[ "CWE-787" ]
CVE-2017-8105
FreeType 2 before 2017-03-24 has an out-of-bounds write caused by a heap-based buffer overflow related to the t1_decoder_parse_charstrings function in psaux/t1decode.c.
https://nvd.nist.gov/vuln/detail/CVE-2017-8105
158,071
savannah
f958c48ee431bef8d4d466b40c9cb2d4dbcb7791
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=f958c48ee431bef8d4d466b40c9cb2d4dbcb7791
None
0
t1_decoder_parse_charstrings( T1_Decoder decoder, FT_Byte* charstring_base, FT_UInt charstring_len ) { FT_Error error; T1_Decoder_Zone zone; FT_Byte* ip; FT_Byte* limit; T1_Builder builder = &decoder->builder; FT_Pos x, y, orig_x, orig_y; FT_Int known_othersubr_result_cnt = 0; FT_Int unknown_othersubr_result_cnt = 0; FT_Bool large_int; FT_Fixed seed; T1_Hints_Funcs hinter; #ifdef FT_DEBUG_LEVEL_TRACE FT_Bool bol = TRUE; #endif /* compute random seed from stack address of parameter */ seed = (FT_Fixed)( ( (FT_Offset)(char*)&seed ^ (FT_Offset)(char*)&decoder ^ (FT_Offset)(char*)&charstring_base ) & FT_ULONG_MAX ); seed = ( seed ^ ( seed >> 10 ) ^ ( seed >> 20 ) ) & 0xFFFFL; if ( seed == 0 ) seed = 0x7384; /* First of all, initialize the decoder */ decoder->top = decoder->stack; decoder->zone = decoder->zones; zone = decoder->zones; builder->parse_state = T1_Parse_Start; hinter = (T1_Hints_Funcs)builder->hints_funcs; /* a font that reads BuildCharArray without setting */ /* its values first is buggy, but ... */ FT_ASSERT( ( decoder->len_buildchar == 0 ) == ( decoder->buildchar == NULL ) ); if ( decoder->buildchar && decoder->len_buildchar > 0 ) FT_ARRAY_ZERO( decoder->buildchar, decoder->len_buildchar ); FT_TRACE4(( "\n" "Start charstring\n" )); zone->base = charstring_base; limit = zone->limit = charstring_base + charstring_len; ip = zone->cursor = zone->base; error = FT_Err_Ok; x = orig_x = builder->pos_x; y = orig_y = builder->pos_y; /* begin hints recording session, if any */ if ( hinter ) hinter->open( hinter->hints ); large_int = FALSE; /* now, execute loop */ while ( ip < limit ) { FT_Long* top = decoder->top; T1_Operator op = op_none; FT_Int32 value = 0; FT_ASSERT( known_othersubr_result_cnt == 0 || unknown_othersubr_result_cnt == 0 ); #ifdef FT_DEBUG_LEVEL_TRACE if ( bol ) { FT_TRACE5(( " (%d)", decoder->top - decoder->stack )); bol = FALSE; } #endif /*********************************************************************/ /* */ /* Decode operator or operand */ /* */ /* */ /* first of all, decompress operator or value */ switch ( *ip++ ) { case 1: op = op_hstem; break; case 3: op = op_vstem; break; case 4: op = op_vmoveto; break; case 5: op = op_rlineto; break; case 6: op = op_hlineto; break; case 7: op = op_vlineto; break; case 8: op = op_rrcurveto; break; case 9: op = op_closepath; break; case 10: op = op_callsubr; break; case 11: op = op_return; break; case 13: op = op_hsbw; break; case 14: op = op_endchar; break; case 15: /* undocumented, obsolete operator */ op = op_unknown15; break; case 21: op = op_rmoveto; break; case 22: op = op_hmoveto; break; case 30: op = op_vhcurveto; break; case 31: op = op_hvcurveto; break; case 12: if ( ip >= limit ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " invalid escape (12+EOF)\n" )); goto Syntax_Error; } switch ( *ip++ ) { case 0: op = op_dotsection; break; case 1: op = op_vstem3; break; case 2: op = op_hstem3; break; case 6: op = op_seac; break; case 7: op = op_sbw; break; case 12: op = op_div; break; case 16: op = op_callothersubr; break; case 17: op = op_pop; break; case 33: op = op_setcurrentpoint; break; default: FT_ERROR(( "t1_decoder_parse_charstrings:" " invalid escape (12+%d)\n", ip[-1] )); goto Syntax_Error; } break; case 255: /* four bytes integer */ if ( ip + 4 > limit ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " unexpected EOF in integer\n" )); goto Syntax_Error; } value = (FT_Int32)( ( (FT_UInt32)ip[0] << 24 ) | ( (FT_UInt32)ip[1] << 16 ) | ( (FT_UInt32)ip[2] << 8 ) | (FT_UInt32)ip[3] ); ip += 4; /* According to the specification, values > 32000 or < -32000 must */ /* be followed by a `div' operator to make the result be in the */ /* range [-32000;32000]. We expect that the second argument of */ /* `div' is not a large number. Additionally, we don't handle */ /* stuff like `<large1> <large2> <num> div <num> div' or */ /* <large1> <large2> <num> div div'. This is probably not allowed */ /* anyway. */ if ( value > 32000 || value < -32000 ) { if ( large_int ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " no `div' after large integer\n" )); } else large_int = TRUE; } else { if ( !large_int ) value = (FT_Int32)( (FT_UInt32)value << 16 ); } break; default: if ( ip[-1] >= 32 ) { if ( ip[-1] < 247 ) value = (FT_Int32)ip[-1] - 139; else { if ( ++ip > limit ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " unexpected EOF in integer\n" )); goto Syntax_Error; } if ( ip[-2] < 251 ) value = ( ( ip[-2] - 247 ) * 256 ) + ip[-1] + 108; else value = -( ( ( ip[-2] - 251 ) * 256 ) + ip[-1] + 108 ); } if ( !large_int ) value = (FT_Int32)( (FT_UInt32)value << 16 ); } else { FT_ERROR(( "t1_decoder_parse_charstrings:" " invalid byte (%d)\n", ip[-1] )); goto Syntax_Error; } } if ( unknown_othersubr_result_cnt > 0 ) { switch ( op ) { case op_callsubr: case op_return: case op_none: case op_pop: break; default: /* all operands have been transferred by previous pops */ unknown_othersubr_result_cnt = 0; break; } } if ( large_int && !( op == op_none || op == op_div ) ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " no `div' after large integer\n" )); large_int = FALSE; } /*********************************************************************/ /* */ /* Push value on stack, or process operator */ /* */ /* */ if ( op == op_none ) { if ( top - decoder->stack >= T1_MAX_CHARSTRINGS_OPERANDS ) { FT_ERROR(( "t1_decoder_parse_charstrings: stack overflow\n" )); goto Syntax_Error; } #ifdef FT_DEBUG_LEVEL_TRACE if ( large_int ) FT_TRACE4(( " %d", value )); else FT_TRACE4(( " %d", value / 65536 )); #endif *top++ = value; decoder->top = top; } else if ( op == op_callothersubr ) /* callothersubr */ { FT_Int subr_no; FT_Int arg_cnt; #ifdef FT_DEBUG_LEVEL_TRACE FT_TRACE4(( " callothersubr\n" )); bol = TRUE; #endif if ( top - decoder->stack < 2 ) goto Stack_Underflow; top -= 2; subr_no = Fix2Int( top[1] ); arg_cnt = Fix2Int( top[0] ); /***********************************************************/ /* */ /* remove all operands to callothersubr from the stack */ /* */ /* for handled othersubrs, where we know the number of */ /* arguments, we increase the stack by the value of */ /* known_othersubr_result_cnt */ /* */ /* for unhandled othersubrs the following pops adjust the */ /* stack pointer as necessary */ if ( arg_cnt > top - decoder->stack ) goto Stack_Underflow; top -= arg_cnt; known_othersubr_result_cnt = 0; unknown_othersubr_result_cnt = 0; /* XXX TODO: The checks to `arg_count == <whatever>' */ /* might not be correct; an othersubr expects a certain */ /* number of operands on the PostScript stack (as opposed */ /* to the T1 stack) but it doesn't have to put them there */ /* by itself; previous othersubrs might have left the */ /* operands there if they were not followed by an */ /* appropriate number of pops */ /* */ /* On the other hand, Adobe Reader 7.0.8 for Linux doesn't */ /* accept a font that contains charstrings like */ /* */ /* 100 200 2 20 callothersubr */ /* 300 1 20 callothersubr pop */ /* */ /* Perhaps this is the reason why BuildCharArray exists. */ switch ( subr_no ) { case 0: /* end flex feature */ if ( arg_cnt != 3 ) goto Unexpected_OtherSubr; if ( !decoder->flex_state || decoder->num_flex_vectors != 7 ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " unexpected flex end\n" )); goto Syntax_Error; } /* the two `results' are popped by the following setcurrentpoint */ top[0] = x; top[1] = y; known_othersubr_result_cnt = 2; break; case 1: /* start flex feature */ if ( arg_cnt != 0 ) goto Unexpected_OtherSubr; if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) || FT_SET_ERROR( t1_builder_check_points( builder, 6 ) ) ) goto Fail; decoder->flex_state = 1; decoder->num_flex_vectors = 0; break; case 2: /* add flex vectors */ { FT_Int idx; if ( arg_cnt != 0 ) goto Unexpected_OtherSubr; if ( !decoder->flex_state ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " missing flex start\n" )); goto Syntax_Error; } /* note that we should not add a point for index 0; */ /* this will move our current position to the flex */ /* point without adding any point to the outline */ idx = decoder->num_flex_vectors++; if ( idx > 0 && idx < 7 ) { /* in malformed fonts it is possible to have other */ /* opcodes in the middle of a flex (which don't */ /* increase `num_flex_vectors'); we thus have to */ /* check whether we can add a point */ if ( FT_SET_ERROR( t1_builder_check_points( builder, 1 ) ) ) goto Syntax_Error; t1_builder_add_point( builder, x, y, (FT_Byte)( idx == 3 || idx == 6 ) ); } } break; break; case 12: case 13: /* counter control hints, clear stack */ top = decoder->stack; break; case 14: case 15: case 16: case 17: case 18: /* multiple masters */ { PS_Blend blend = decoder->blend; FT_UInt num_points, nn, mm; FT_Long* delta; FT_Long* values; if ( !blend ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " unexpected multiple masters operator\n" )); goto Syntax_Error; } num_points = (FT_UInt)subr_no - 13 + ( subr_no == 18 ); if ( arg_cnt != (FT_Int)( num_points * blend->num_designs ) ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " incorrect number of multiple masters arguments\n" )); goto Syntax_Error; } /* We want to compute */ /* */ /* a0*w0 + a1*w1 + ... + ak*wk */ /* */ /* but we only have a0, a1-a0, a2-a0, ..., ak-a0. */ /* */ /* However, given that w0 + w1 + ... + wk == 1, we can */ /* rewrite it easily as */ /* */ /* a0 + (a1-a0)*w1 + (a2-a0)*w2 + ... + (ak-a0)*wk */ /* */ /* where k == num_designs-1. */ /* */ /* I guess that's why it's written in this `compact' */ /* form. */ /* */ delta = top + num_points; values = top; for ( nn = 0; nn < num_points; nn++ ) { FT_Long tmp = values[0]; for ( mm = 1; mm < blend->num_designs; mm++ ) tmp += FT_MulFix( *delta++, blend->weight_vector[mm] ); *values++ = tmp; } known_othersubr_result_cnt = (FT_Int)num_points; break; } case 19: /* <idx> 1 19 callothersubr */ /* => replace elements starting from index cvi( <idx> ) */ /* of BuildCharArray with WeightVector */ { FT_Int idx; PS_Blend blend = decoder->blend; if ( arg_cnt != 1 || !blend ) goto Unexpected_OtherSubr; idx = Fix2Int( top[0] ); if ( idx < 0 || (FT_UInt)idx + blend->num_designs > decoder->len_buildchar ) goto Unexpected_OtherSubr; ft_memcpy( &decoder->buildchar[idx], blend->weight_vector, blend->num_designs * sizeof ( blend->weight_vector[0] ) ); } break; case 20: /* <arg1> <arg2> 2 20 callothersubr pop */ /* ==> push <arg1> + <arg2> onto T1 stack */ if ( arg_cnt != 2 ) goto Unexpected_OtherSubr; top[0] += top[1]; /* XXX (over|under)flow */ known_othersubr_result_cnt = 1; break; case 21: /* <arg1> <arg2> 2 21 callothersubr pop */ /* ==> push <arg1> - <arg2> onto T1 stack */ if ( arg_cnt != 2 ) goto Unexpected_OtherSubr; top[0] -= top[1]; /* XXX (over|under)flow */ known_othersubr_result_cnt = 1; break; case 22: /* <arg1> <arg2> 2 22 callothersubr pop */ /* ==> push <arg1> * <arg2> onto T1 stack */ if ( arg_cnt != 2 ) goto Unexpected_OtherSubr; top[0] = FT_MulFix( top[0], top[1] ); known_othersubr_result_cnt = 1; break; case 23: /* <arg1> <arg2> 2 23 callothersubr pop */ /* ==> push <arg1> / <arg2> onto T1 stack */ if ( arg_cnt != 2 || top[1] == 0 ) goto Unexpected_OtherSubr; top[0] = FT_DivFix( top[0], top[1] ); known_othersubr_result_cnt = 1; break; case 24: /* <val> <idx> 2 24 callothersubr */ /* ==> set BuildCharArray[cvi( <idx> )] = <val> */ { FT_Int idx; PS_Blend blend = decoder->blend; if ( arg_cnt != 2 || !blend ) goto Unexpected_OtherSubr; idx = Fix2Int( top[1] ); if ( idx < 0 || (FT_UInt) idx >= decoder->len_buildchar ) goto Unexpected_OtherSubr; decoder->buildchar[idx] = top[0]; } break; case 25: /* <idx> 1 25 callothersubr pop */ /* ==> push BuildCharArray[cvi( idx )] */ /* onto T1 stack */ { FT_Int idx; PS_Blend blend = decoder->blend; if ( arg_cnt != 1 || !blend ) goto Unexpected_OtherSubr; idx = Fix2Int( top[0] ); if ( idx < 0 || (FT_UInt) idx >= decoder->len_buildchar ) goto Unexpected_OtherSubr; top[0] = decoder->buildchar[idx]; } known_othersubr_result_cnt = 1; break; #if 0 case 26: /* <val> mark <idx> ==> set BuildCharArray[cvi( <idx> )] = <val>, */ /* leave mark on T1 stack */ /* <val> <idx> ==> set BuildCharArray[cvi( <idx> )] = <val> */ XXX which routine has left its mark on the (PostScript) stack?; break; #endif case 27: /* <res1> <res2> <val1> <val2> 4 27 callothersubr pop */ /* ==> push <res1> onto T1 stack if <val1> <= <val2>, */ /* otherwise push <res2> */ if ( arg_cnt != 4 ) goto Unexpected_OtherSubr; if ( top[2] > top[3] ) top[0] = top[1]; known_othersubr_result_cnt = 1; break; case 28: /* 0 28 callothersubr pop */ /* => push random value from interval [0, 1) onto stack */ if ( arg_cnt != 0 ) goto Unexpected_OtherSubr; { FT_Fixed Rand; Rand = seed; if ( Rand >= 0x8000L ) Rand++; top[0] = Rand; seed = FT_MulFix( seed, 0x10000L - seed ); if ( seed == 0 ) seed += 0x2873; } known_othersubr_result_cnt = 1; break; default: if ( arg_cnt >= 0 && subr_no >= 0 ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " unknown othersubr [%d %d], wish me luck\n", arg_cnt, subr_no )); unknown_othersubr_result_cnt = arg_cnt; break; } /* fall through */ Unexpected_OtherSubr: FT_ERROR(( "t1_decoder_parse_charstrings:" " invalid othersubr [%d %d]\n", arg_cnt, subr_no )); goto Syntax_Error; } top += known_othersubr_result_cnt; decoder->top = top; } else /* general operator */ { FT_Int num_args = t1_args_count[op]; FT_ASSERT( num_args >= 0 ); if ( top - decoder->stack < num_args ) goto Stack_Underflow; /* XXX Operators usually take their operands from the */ /* bottom of the stack, i.e., the operands are */ /* decoder->stack[0], ..., decoder->stack[num_args - 1]; */ /* only div, callsubr, and callothersubr are different. */ /* In practice it doesn't matter (?). */ #ifdef FT_DEBUG_LEVEL_TRACE switch ( op ) { case op_callsubr: case op_div: case op_callothersubr: case op_pop: case op_return: break; default: if ( top - decoder->stack != num_args ) FT_TRACE0(( "t1_decoder_parse_charstrings:" " too much operands on the stack" " (seen %d, expected %d)\n", top - decoder->stack, num_args )); break; } #endif /* FT_DEBUG_LEVEL_TRACE */ top -= num_args; switch ( op ) { case op_endchar: FT_TRACE4(( " endchar\n" )); t1_builder_close_contour( builder ); /* close hints recording session */ if ( hinter ) { if ( hinter->close( hinter->hints, (FT_UInt)builder->current->n_points ) ) goto Syntax_Error; /* apply hints to the loaded glyph outline now */ error = hinter->apply( hinter->hints, builder->current, (PSH_Globals)builder->hints_globals, decoder->hint_mode ); if ( error ) goto Fail; } /* add current outline to the glyph slot */ FT_GlyphLoader_Add( builder->loader ); /* the compiler should optimize away this empty loop but ... */ #ifdef FT_DEBUG_LEVEL_TRACE if ( decoder->len_buildchar > 0 ) { FT_UInt i; FT_TRACE4(( "BuildCharArray = [ " )); for ( i = 0; i < decoder->len_buildchar; i++ ) FT_TRACE4(( "%d ", decoder->buildchar[i] )); FT_TRACE4(( "]\n" )); } #endif /* FT_DEBUG_LEVEL_TRACE */ FT_TRACE4(( "\n" )); /* return now! */ return FT_Err_Ok; case op_hsbw: FT_TRACE4(( " hsbw" )); builder->parse_state = T1_Parse_Have_Width; builder->left_bearing.x += top[0]; builder->advance.x = top[1]; builder->advance.y = 0; orig_x = x = builder->pos_x + top[0]; orig_y = y = builder->pos_y; FT_UNUSED( orig_y ); /* the `metrics_only' indicates that we only want to compute */ /* the glyph's metrics (lsb + advance width), not load the */ /* rest of it; so exit immediately */ if ( builder->metrics_only ) return FT_Err_Ok; break; case op_seac: return t1operator_seac( decoder, top[0], top[1], top[2], Fix2Int( top[3] ), Fix2Int( top[4] ) ); case op_sbw: FT_TRACE4(( " sbw" )); builder->parse_state = T1_Parse_Have_Width; builder->left_bearing.x += top[0]; builder->left_bearing.y += top[1]; builder->advance.x = top[2]; builder->advance.y = top[3]; x = builder->pos_x + top[0]; y = builder->pos_y + top[1]; /* the `metrics_only' indicates that we only want to compute */ /* the glyph's metrics (lsb + advance width), not load the */ /* rest of it; so exit immediately */ if ( builder->metrics_only ) return FT_Err_Ok; break; case op_closepath: FT_TRACE4(( " closepath" )); /* if there is no path, `closepath' is a no-op */ if ( builder->parse_state == T1_Parse_Have_Path || builder->parse_state == T1_Parse_Have_Moveto ) t1_builder_close_contour( builder ); builder->parse_state = T1_Parse_Have_Width; break; case op_hlineto: FT_TRACE4(( " hlineto" )); if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ) goto Fail; x += top[0]; goto Add_Line; case op_hmoveto: FT_TRACE4(( " hmoveto" )); x += top[0]; if ( !decoder->flex_state ) { if ( builder->parse_state == T1_Parse_Start ) goto Syntax_Error; builder->parse_state = T1_Parse_Have_Moveto; } break; case op_hvcurveto: FT_TRACE4(( " hvcurveto" )); if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) || FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) ) goto Fail; x += top[0]; t1_builder_add_point( builder, x, y, 0 ); x += top[1]; y += top[2]; t1_builder_add_point( builder, x, y, 0 ); y += top[3]; t1_builder_add_point( builder, x, y, 1 ); break; case op_rlineto: FT_TRACE4(( " rlineto" )); if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ) goto Fail; x += top[0]; y += top[1]; Add_Line: if ( FT_SET_ERROR( t1_builder_add_point1( builder, x, y ) ) ) goto Fail; break; case op_rmoveto: FT_TRACE4(( " rmoveto" )); x += top[0]; y += top[1]; if ( !decoder->flex_state ) { if ( builder->parse_state == T1_Parse_Start ) goto Syntax_Error; builder->parse_state = T1_Parse_Have_Moveto; } break; case op_rrcurveto: FT_TRACE4(( " rrcurveto" )); if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) || FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) ) goto Fail; x += top[0]; y += top[1]; t1_builder_add_point( builder, x, y, 0 ); x += top[2]; y += top[3]; t1_builder_add_point( builder, x, y, 0 ); x += top[4]; y += top[5]; t1_builder_add_point( builder, x, y, 1 ); break; case op_vhcurveto: FT_TRACE4(( " vhcurveto" )); if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) || FT_SET_ERROR( t1_builder_check_points( builder, 3 ) ) ) goto Fail; y += top[0]; t1_builder_add_point( builder, x, y, 0 ); x += top[1]; y += top[2]; t1_builder_add_point( builder, x, y, 0 ); x += top[3]; t1_builder_add_point( builder, x, y, 1 ); break; case op_vlineto: FT_TRACE4(( " vlineto" )); if ( FT_SET_ERROR( t1_builder_start_point( builder, x, y ) ) ) goto Fail; y += top[0]; goto Add_Line; case op_vmoveto: FT_TRACE4(( " vmoveto" )); y += top[0]; if ( !decoder->flex_state ) { if ( builder->parse_state == T1_Parse_Start ) goto Syntax_Error; builder->parse_state = T1_Parse_Have_Moveto; } break; case op_div: FT_TRACE4(( " div" )); /* if `large_int' is set, we divide unscaled numbers; */ /* otherwise, we divide numbers in 16.16 format -- */ /* in both cases, it is the same operation */ *top = FT_DivFix( top[0], top[1] ); top++; large_int = FALSE; break; case op_callsubr: { FT_Int idx; FT_TRACE4(( " callsubr" )); idx = Fix2Int( top[0] ); if ( decoder->subrs_hash ) { size_t* val = ft_hash_num_lookup( idx, decoder->subrs_hash ); if ( val ) idx = *val; else idx = -1; } if ( idx < 0 || idx >= decoder->num_subrs ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " invalid subrs index\n" )); goto Syntax_Error; } if ( zone - decoder->zones >= T1_MAX_SUBRS_CALLS ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " too many nested subrs\n" )); goto Syntax_Error; } zone->cursor = ip; /* save current instruction pointer */ zone++; /* The Type 1 driver stores subroutines without the seed bytes. */ /* The CID driver stores subroutines with seed bytes. This */ /* case is taken care of when decoder->subrs_len == 0. */ zone->base = decoder->subrs[idx]; if ( decoder->subrs_len ) zone->limit = zone->base + decoder->subrs_len[idx]; else { /* We are using subroutines from a CID font. We must adjust */ /* for the seed bytes. */ zone->base += ( decoder->lenIV >= 0 ? decoder->lenIV : 0 ); zone->limit = decoder->subrs[idx + 1]; } zone->cursor = zone->base; if ( !zone->base ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " invoking empty subrs\n" )); goto Syntax_Error; } decoder->zone = zone; ip = zone->base; limit = zone->limit; break; } case op_pop: FT_TRACE4(( " pop" )); if ( known_othersubr_result_cnt > 0 ) { known_othersubr_result_cnt--; /* ignore, we pushed the operands ourselves */ break; } if ( unknown_othersubr_result_cnt == 0 ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " no more operands for othersubr\n" )); goto Syntax_Error; } unknown_othersubr_result_cnt--; top++; /* `push' the operand to callothersubr onto the stack */ break; case op_return: FT_TRACE4(( " return" )); if ( zone <= decoder->zones ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " unexpected return\n" )); goto Syntax_Error; } zone--; ip = zone->cursor; limit = zone->limit; decoder->zone = zone; break; case op_dotsection: FT_TRACE4(( " dotsection" )); break; case op_hstem: FT_TRACE4(( " hstem" )); /* record horizontal hint */ if ( hinter ) { /* top[0] += builder->left_bearing.y; */ hinter->stem( hinter->hints, 1, top ); } break; case op_hstem3: FT_TRACE4(( " hstem3" )); /* record horizontal counter-controlled hints */ if ( hinter ) hinter->stem3( hinter->hints, 1, top ); break; case op_vstem: FT_TRACE4(( " vstem" )); /* record vertical hint */ if ( hinter ) { top[0] += orig_x; hinter->stem( hinter->hints, 0, top ); } break; case op_vstem3: FT_TRACE4(( " vstem3" )); /* record vertical counter-controlled hints */ if ( hinter ) { FT_Pos dx = orig_x; top[0] += dx; top[2] += dx; top[4] += dx; hinter->stem3( hinter->hints, 0, top ); } break; case op_setcurrentpoint: FT_TRACE4(( " setcurrentpoint" )); /* From the T1 specification, section 6.4: */ /* */ /* The setcurrentpoint command is used only in */ /* conjunction with results from OtherSubrs procedures. */ /* known_othersubr_result_cnt != 0 is already handled */ /* above. */ /* Note, however, that both Ghostscript and Adobe */ /* Distiller handle this situation by silently ignoring */ /* the inappropriate `setcurrentpoint' instruction. So */ /* we do the same. */ #if 0 if ( decoder->flex_state != 1 ) { FT_ERROR(( "t1_decoder_parse_charstrings:" " unexpected `setcurrentpoint'\n" )); goto Syntax_Error; } else ... #endif x = top[0]; y = top[1]; decoder->flex_state = 0; break; case op_unknown15: FT_TRACE4(( " opcode_15" )); /* nothing to do except to pop the two arguments */ break; default: FT_ERROR(( "t1_decoder_parse_charstrings:" " unhandled opcode %d\n", op )); goto Syntax_Error; } /* XXX Operators usually clear the operand stack; */ /* only div, callsubr, callothersubr, pop, and */ /* return are different. */ /* In practice it doesn't matter (?). */ decoder->top = top; #ifdef FT_DEBUG_LEVEL_TRACE FT_TRACE4(( "\n" )); bol = TRUE; #endif } /* general operator processing */ } /* while ip < limit */ FT_TRACE4(( "..end..\n\n" )); Fail: return error; Syntax_Error: return FT_THROW( Syntax_Error ); Stack_Underflow: return FT_THROW( Stack_Underflow ); }
131,877,843,141,694,360,000,000,000,000,000,000,000
None
null
[ "CWE-787" ]
CVE-2017-8105
FreeType 2 before 2017-03-24 has an out-of-bounds write caused by a heap-based buffer overflow related to the t1_decoder_parse_charstrings function in psaux/t1decode.c.
https://nvd.nist.gov/vuln/detail/CVE-2017-8105
212
dbus
7d65a3a6ed8815e34a99c680ac3869fde49dbbd4
http://gitweb.freedesktop.org/?p=dbus/dbus
https://cgit.freedesktop.org/dbus/dbus/commit/?id=7d65a3a6ed8815e34a99c680ac3869fde49dbbd4
CVE 2010-4352: Reject deeply nested variants Add DBUS_INVALID_NESTED_TOO_DEEPLY validity problem and a test that should generate it. Previously, we rejected deep nesting in the signature, but variants allow dynamic message nesting, conditional only on the depth of the message body. The nesting limit is 64, which was also the limit in static signatures. Empirically, dynamic nesting depth observed on my Fedora 14 system doesn't exceed 2; 64 is really a huge limit. https://bugs.freedesktop.org/show_bug.cgi?id=32321 Signed-Off-By: Colin Walters <[email protected]> Signed-off-by: Will Thompson <[email protected]>
1
validate_body_helper (DBusTypeReader *reader, int byte_order, dbus_bool_t walk_reader_to_end, const unsigned char *p, const unsigned char *end, const unsigned char **new_p) { int current_type; while ((current_type = _dbus_type_reader_get_current_type (reader)) != DBUS_TYPE_INVALID) { const unsigned char *a; case DBUS_TYPE_BYTE: ++p; break; case DBUS_TYPE_BOOLEAN: case DBUS_TYPE_INT16: case DBUS_TYPE_UINT16: case DBUS_TYPE_INT32: case DBUS_TYPE_UINT32: case DBUS_TYPE_UNIX_FD: case DBUS_TYPE_INT64: case DBUS_TYPE_UINT64: case DBUS_TYPE_DOUBLE: alignment = _dbus_type_get_alignment (current_type); a = _DBUS_ALIGN_ADDRESS (p, alignment); if (a >= end) return DBUS_INVALID_NOT_ENOUGH_DATA; while (p != a) { if (*p != '\0') return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL; ++p; } if (current_type == DBUS_TYPE_BOOLEAN) { dbus_uint32_t v = _dbus_unpack_uint32 (byte_order, p); if (!(v == 0 || v == 1)) return DBUS_INVALID_BOOLEAN_NOT_ZERO_OR_ONE; } p += alignment; break; case DBUS_TYPE_ARRAY: case DBUS_TYPE_STRING: case DBUS_TYPE_OBJECT_PATH: { dbus_uint32_t claimed_len; a = _DBUS_ALIGN_ADDRESS (p, 4); if (a + 4 > end) return DBUS_INVALID_NOT_ENOUGH_DATA; while (p != a) { if (*p != '\0') return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL; ++p; } claimed_len = _dbus_unpack_uint32 (byte_order, p); p += 4; /* p may now be == end */ _dbus_assert (p <= end); if (current_type == DBUS_TYPE_ARRAY) { int array_elem_type = _dbus_type_reader_get_element_type (reader); if (!_dbus_type_is_valid (array_elem_type)) { return DBUS_INVALID_UNKNOWN_TYPECODE; } alignment = _dbus_type_get_alignment (array_elem_type); a = _DBUS_ALIGN_ADDRESS (p, alignment); /* a may now be == end */ if (a > end) return DBUS_INVALID_NOT_ENOUGH_DATA; while (p != a) { if (*p != '\0') return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL; ++p; } } if (claimed_len > (unsigned long) (end - p)) return DBUS_INVALID_LENGTH_OUT_OF_BOUNDS; if (current_type == DBUS_TYPE_OBJECT_PATH) { DBusString str; _dbus_string_init_const_len (&str, p, claimed_len); if (!_dbus_validate_path (&str, 0, _dbus_string_get_length (&str))) return DBUS_INVALID_BAD_PATH; p += claimed_len; } else if (current_type == DBUS_TYPE_STRING) { DBusString str; _dbus_string_init_const_len (&str, p, claimed_len); if (!_dbus_string_validate_utf8 (&str, 0, _dbus_string_get_length (&str))) return DBUS_INVALID_BAD_UTF8_IN_STRING; p += claimed_len; } else if (current_type == DBUS_TYPE_ARRAY && claimed_len > 0) { DBusTypeReader sub; DBusValidity validity; const unsigned char *array_end; int array_elem_type; if (claimed_len > DBUS_MAXIMUM_ARRAY_LENGTH) return DBUS_INVALID_ARRAY_LENGTH_EXCEEDS_MAXIMUM; /* Remember that the reader is types only, so we can't * use it to iterate over elements. It stays the same * for all elements. */ _dbus_type_reader_recurse (reader, &sub); array_end = p + claimed_len; array_elem_type = _dbus_type_reader_get_element_type (reader); /* avoid recursive call to validate_body_helper if this is an array * of fixed-size elements */ if (dbus_type_is_fixed (array_elem_type)) { /* bools need to be handled differently, because they can * have an invalid value */ if (array_elem_type == DBUS_TYPE_BOOLEAN) { dbus_uint32_t v; alignment = _dbus_type_get_alignment (array_elem_type); while (p < array_end) { v = _dbus_unpack_uint32 (byte_order, p); if (!(v == 0 || v == 1)) return DBUS_INVALID_BOOLEAN_NOT_ZERO_OR_ONE; p += alignment; } } else { p = array_end; } } else { while (p < array_end) { validity = validate_body_helper (&sub, byte_order, FALSE, p, end, &p); if (validity != DBUS_VALID) return validity; } } if (p != array_end) return DBUS_INVALID_ARRAY_LENGTH_INCORRECT; } /* check nul termination */ { while (p < array_end) { validity = validate_body_helper (&sub, byte_order, FALSE, p, end, &p); if (validity != DBUS_VALID) return validity; } } break; case DBUS_TYPE_SIGNATURE: { dbus_uint32_t claimed_len; DBusString str; DBusValidity validity; claimed_len = *p; ++p; /* 1 is for nul termination */ if (claimed_len + 1 > (unsigned long) (end - p)) return DBUS_INVALID_SIGNATURE_LENGTH_OUT_OF_BOUNDS; _dbus_string_init_const_len (&str, p, claimed_len); validity = _dbus_validate_signature_with_reason (&str, 0, _dbus_string_get_length (&str)); if (validity != DBUS_VALID) return validity; p += claimed_len; _dbus_assert (p < end); if (*p != DBUS_TYPE_INVALID) return DBUS_INVALID_SIGNATURE_MISSING_NUL; ++p; _dbus_verbose ("p = %p end = %p claimed_len %u\n", p, end, claimed_len); } break; case DBUS_TYPE_VARIANT: { /* 1 byte sig len, sig typecodes, align to * contained-type-boundary, values. */ /* In addition to normal signature validation, we need to be sure * the signature contains only a single (possibly container) type. */ dbus_uint32_t claimed_len; DBusString sig; DBusTypeReader sub; DBusValidity validity; int contained_alignment; int contained_type; DBusValidity reason; claimed_len = *p; ++p; /* + 1 for nul */ if (claimed_len + 1 > (unsigned long) (end - p)) return DBUS_INVALID_VARIANT_SIGNATURE_LENGTH_OUT_OF_BOUNDS; _dbus_string_init_const_len (&sig, p, claimed_len); reason = _dbus_validate_signature_with_reason (&sig, 0, _dbus_string_get_length (&sig)); if (!(reason == DBUS_VALID)) { if (reason == DBUS_VALIDITY_UNKNOWN_OOM_ERROR) return reason; else return DBUS_INVALID_VARIANT_SIGNATURE_BAD; } p += claimed_len; if (*p != DBUS_TYPE_INVALID) return DBUS_INVALID_VARIANT_SIGNATURE_MISSING_NUL; ++p; contained_type = _dbus_first_type_in_signature (&sig, 0); if (contained_type == DBUS_TYPE_INVALID) return DBUS_INVALID_VARIANT_SIGNATURE_EMPTY; contained_alignment = _dbus_type_get_alignment (contained_type); a = _DBUS_ALIGN_ADDRESS (p, contained_alignment); if (a > end) return DBUS_INVALID_NOT_ENOUGH_DATA; while (p != a) { if (*p != '\0') return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL; ++p; } _dbus_type_reader_init_types_only (&sub, &sig, 0); _dbus_assert (_dbus_type_reader_get_current_type (&sub) != DBUS_TYPE_INVALID); validity = validate_body_helper (&sub, byte_order, FALSE, p, end, &p); if (validity != DBUS_VALID) return validity; if (_dbus_type_reader_next (&sub)) return DBUS_INVALID_VARIANT_SIGNATURE_SPECIFIES_MULTIPLE_VALUES; _dbus_assert (_dbus_type_reader_get_current_type (&sub) == DBUS_TYPE_INVALID); } break; case DBUS_TYPE_DICT_ENTRY: case DBUS_TYPE_STRUCT: _dbus_assert (_dbus_type_reader_get_current_type (&sub) != DBUS_TYPE_INVALID); validity = validate_body_helper (&sub, byte_order, FALSE, p, end, &p); if (validity != DBUS_VALID) return validity; if (*p != '\0') return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL; ++p; } _dbus_type_reader_recurse (reader, &sub); validity = validate_body_helper (&sub, byte_order, TRUE, p, end, &p); if (validity != DBUS_VALID) return validity; } break; default: _dbus_assert_not_reached ("invalid typecode in supposedly-validated signature"); break; }
293,803,507,783,746,450,000,000,000,000,000,000,000
None
null
[ "CWE-399" ]
CVE-2010-4352
Stack consumption vulnerability in D-Bus (aka DBus) before 1.4.1 allows local users to cause a denial of service (daemon crash) via a message containing many nested variants.
https://nvd.nist.gov/vuln/detail/CVE-2010-4352
158,072
dbus
7d65a3a6ed8815e34a99c680ac3869fde49dbbd4
http://gitweb.freedesktop.org/?p=dbus/dbus
https://cgit.freedesktop.org/dbus/dbus/commit/?id=7d65a3a6ed8815e34a99c680ac3869fde49dbbd4
CVE 2010-4352: Reject deeply nested variants Add DBUS_INVALID_NESTED_TOO_DEEPLY validity problem and a test that should generate it. Previously, we rejected deep nesting in the signature, but variants allow dynamic message nesting, conditional only on the depth of the message body. The nesting limit is 64, which was also the limit in static signatures. Empirically, dynamic nesting depth observed on my Fedora 14 system doesn't exceed 2; 64 is really a huge limit. https://bugs.freedesktop.org/show_bug.cgi?id=32321 Signed-Off-By: Colin Walters <[email protected]> Signed-off-by: Will Thompson <[email protected]>
0
validate_body_helper (DBusTypeReader *reader, int byte_order, dbus_bool_t walk_reader_to_end, int total_depth, const unsigned char *p, const unsigned char *end, const unsigned char **new_p) { int current_type; /* The spec allows arrays and structs to each nest 32, for total * nesting of 2*32. We want to impose the same limit on "dynamic" * value nesting (not visible in the signature) which is introduced * by DBUS_TYPE_VARIANT. */ if (total_depth > (DBUS_MAXIMUM_TYPE_RECURSION_DEPTH * 2)) { return DBUS_INVALID_NESTED_TOO_DEEPLY; } while ((current_type = _dbus_type_reader_get_current_type (reader)) != DBUS_TYPE_INVALID) { const unsigned char *a; case DBUS_TYPE_BYTE: ++p; break; case DBUS_TYPE_BOOLEAN: case DBUS_TYPE_INT16: case DBUS_TYPE_UINT16: case DBUS_TYPE_INT32: case DBUS_TYPE_UINT32: case DBUS_TYPE_UNIX_FD: case DBUS_TYPE_INT64: case DBUS_TYPE_UINT64: case DBUS_TYPE_DOUBLE: alignment = _dbus_type_get_alignment (current_type); a = _DBUS_ALIGN_ADDRESS (p, alignment); if (a >= end) return DBUS_INVALID_NOT_ENOUGH_DATA; while (p != a) { if (*p != '\0') return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL; ++p; } if (current_type == DBUS_TYPE_BOOLEAN) { dbus_uint32_t v = _dbus_unpack_uint32 (byte_order, p); if (!(v == 0 || v == 1)) return DBUS_INVALID_BOOLEAN_NOT_ZERO_OR_ONE; } p += alignment; break; case DBUS_TYPE_ARRAY: case DBUS_TYPE_STRING: case DBUS_TYPE_OBJECT_PATH: { dbus_uint32_t claimed_len; a = _DBUS_ALIGN_ADDRESS (p, 4); if (a + 4 > end) return DBUS_INVALID_NOT_ENOUGH_DATA; while (p != a) { if (*p != '\0') return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL; ++p; } claimed_len = _dbus_unpack_uint32 (byte_order, p); p += 4; /* p may now be == end */ _dbus_assert (p <= end); if (current_type == DBUS_TYPE_ARRAY) { int array_elem_type = _dbus_type_reader_get_element_type (reader); if (!_dbus_type_is_valid (array_elem_type)) { return DBUS_INVALID_UNKNOWN_TYPECODE; } alignment = _dbus_type_get_alignment (array_elem_type); a = _DBUS_ALIGN_ADDRESS (p, alignment); /* a may now be == end */ if (a > end) return DBUS_INVALID_NOT_ENOUGH_DATA; while (p != a) { if (*p != '\0') return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL; ++p; } } if (claimed_len > (unsigned long) (end - p)) return DBUS_INVALID_LENGTH_OUT_OF_BOUNDS; if (current_type == DBUS_TYPE_OBJECT_PATH) { DBusString str; _dbus_string_init_const_len (&str, p, claimed_len); if (!_dbus_validate_path (&str, 0, _dbus_string_get_length (&str))) return DBUS_INVALID_BAD_PATH; p += claimed_len; } else if (current_type == DBUS_TYPE_STRING) { DBusString str; _dbus_string_init_const_len (&str, p, claimed_len); if (!_dbus_string_validate_utf8 (&str, 0, _dbus_string_get_length (&str))) return DBUS_INVALID_BAD_UTF8_IN_STRING; p += claimed_len; } else if (current_type == DBUS_TYPE_ARRAY && claimed_len > 0) { DBusTypeReader sub; DBusValidity validity; const unsigned char *array_end; int array_elem_type; if (claimed_len > DBUS_MAXIMUM_ARRAY_LENGTH) return DBUS_INVALID_ARRAY_LENGTH_EXCEEDS_MAXIMUM; /* Remember that the reader is types only, so we can't * use it to iterate over elements. It stays the same * for all elements. */ _dbus_type_reader_recurse (reader, &sub); array_end = p + claimed_len; array_elem_type = _dbus_type_reader_get_element_type (reader); /* avoid recursive call to validate_body_helper if this is an array * of fixed-size elements */ if (dbus_type_is_fixed (array_elem_type)) { /* bools need to be handled differently, because they can * have an invalid value */ if (array_elem_type == DBUS_TYPE_BOOLEAN) { dbus_uint32_t v; alignment = _dbus_type_get_alignment (array_elem_type); while (p < array_end) { v = _dbus_unpack_uint32 (byte_order, p); if (!(v == 0 || v == 1)) return DBUS_INVALID_BOOLEAN_NOT_ZERO_OR_ONE; p += alignment; } } else { p = array_end; } } else { while (p < array_end) { validity = validate_body_helper (&sub, byte_order, FALSE, p, end, &p); if (validity != DBUS_VALID) return validity; } } if (p != array_end) return DBUS_INVALID_ARRAY_LENGTH_INCORRECT; } /* check nul termination */ { while (p < array_end) { validity = validate_body_helper (&sub, byte_order, FALSE, total_depth + 1, p, end, &p); if (validity != DBUS_VALID) return validity; } } break; case DBUS_TYPE_SIGNATURE: { dbus_uint32_t claimed_len; DBusString str; DBusValidity validity; claimed_len = *p; ++p; /* 1 is for nul termination */ if (claimed_len + 1 > (unsigned long) (end - p)) return DBUS_INVALID_SIGNATURE_LENGTH_OUT_OF_BOUNDS; _dbus_string_init_const_len (&str, p, claimed_len); validity = _dbus_validate_signature_with_reason (&str, 0, _dbus_string_get_length (&str)); if (validity != DBUS_VALID) return validity; p += claimed_len; _dbus_assert (p < end); if (*p != DBUS_TYPE_INVALID) return DBUS_INVALID_SIGNATURE_MISSING_NUL; ++p; _dbus_verbose ("p = %p end = %p claimed_len %u\n", p, end, claimed_len); } break; case DBUS_TYPE_VARIANT: { /* 1 byte sig len, sig typecodes, align to * contained-type-boundary, values. */ /* In addition to normal signature validation, we need to be sure * the signature contains only a single (possibly container) type. */ dbus_uint32_t claimed_len; DBusString sig; DBusTypeReader sub; DBusValidity validity; int contained_alignment; int contained_type; DBusValidity reason; claimed_len = *p; ++p; /* + 1 for nul */ if (claimed_len + 1 > (unsigned long) (end - p)) return DBUS_INVALID_VARIANT_SIGNATURE_LENGTH_OUT_OF_BOUNDS; _dbus_string_init_const_len (&sig, p, claimed_len); reason = _dbus_validate_signature_with_reason (&sig, 0, _dbus_string_get_length (&sig)); if (!(reason == DBUS_VALID)) { if (reason == DBUS_VALIDITY_UNKNOWN_OOM_ERROR) return reason; else return DBUS_INVALID_VARIANT_SIGNATURE_BAD; } p += claimed_len; if (*p != DBUS_TYPE_INVALID) return DBUS_INVALID_VARIANT_SIGNATURE_MISSING_NUL; ++p; contained_type = _dbus_first_type_in_signature (&sig, 0); if (contained_type == DBUS_TYPE_INVALID) return DBUS_INVALID_VARIANT_SIGNATURE_EMPTY; contained_alignment = _dbus_type_get_alignment (contained_type); a = _DBUS_ALIGN_ADDRESS (p, contained_alignment); if (a > end) return DBUS_INVALID_NOT_ENOUGH_DATA; while (p != a) { if (*p != '\0') return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL; ++p; } _dbus_type_reader_init_types_only (&sub, &sig, 0); _dbus_assert (_dbus_type_reader_get_current_type (&sub) != DBUS_TYPE_INVALID); validity = validate_body_helper (&sub, byte_order, FALSE, p, end, &p); if (validity != DBUS_VALID) return validity; if (_dbus_type_reader_next (&sub)) return DBUS_INVALID_VARIANT_SIGNATURE_SPECIFIES_MULTIPLE_VALUES; _dbus_assert (_dbus_type_reader_get_current_type (&sub) == DBUS_TYPE_INVALID); } break; case DBUS_TYPE_DICT_ENTRY: case DBUS_TYPE_STRUCT: _dbus_assert (_dbus_type_reader_get_current_type (&sub) != DBUS_TYPE_INVALID); validity = validate_body_helper (&sub, byte_order, FALSE, total_depth + 1, p, end, &p); if (validity != DBUS_VALID) return validity; if (*p != '\0') return DBUS_INVALID_ALIGNMENT_PADDING_NOT_NUL; ++p; } _dbus_type_reader_recurse (reader, &sub); validity = validate_body_helper (&sub, byte_order, TRUE, p, end, &p); if (validity != DBUS_VALID) return validity; } break; default: _dbus_assert_not_reached ("invalid typecode in supposedly-validated signature"); break; }
176,712,459,114,438,600,000,000,000,000,000,000,000
None
null
[ "CWE-399" ]
CVE-2010-4352
Stack consumption vulnerability in D-Bus (aka DBus) before 1.4.1 allows local users to cause a denial of service (daemon crash) via a message containing many nested variants.
https://nvd.nist.gov/vuln/detail/CVE-2010-4352
213
savannah
e6699596af5c5d6f0ae0ea06e19df87dce088df8
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=e6699596af5c5d6f0ae0ea06e19df87dce088df8
None
1
tt_size_reset( TT_Size size, FT_Bool only_height ) { TT_Face face; FT_Size_Metrics* metrics; size->ttmetrics.valid = FALSE; face = (TT_Face)size->root.face; metrics = &size->metrics; /* copy the result from base layer */ /* This bit flag, if set, indicates that the ppems must be */ /* rounded to integers. Nearly all TrueType fonts have this bit */ /* set, as hinting won't work really well otherwise. */ /* */ if ( face->header.Flags & 8 ) { metrics->ascender = FT_PIX_ROUND( FT_MulFix( face->root.ascender, metrics->y_scale ) ); metrics->descender = FT_PIX_ROUND( FT_MulFix( face->root.descender, metrics->y_scale ) ); metrics->height = FT_PIX_ROUND( FT_MulFix( face->root.height, metrics->y_scale ) ); } size->ttmetrics.valid = TRUE; if ( only_height ) return FT_Err_Ok; if ( face->header.Flags & 8 ) { metrics->x_scale = FT_DivFix( metrics->x_ppem << 6, face->root.units_per_EM ); metrics->y_scale = FT_DivFix( metrics->y_ppem << 6, face->root.units_per_EM ); metrics->max_advance = FT_PIX_ROUND( FT_MulFix( face->root.max_advance_width, metrics->x_scale ) ); } /* compute new transformation */ if ( metrics->x_ppem >= metrics->y_ppem ) { size->ttmetrics.scale = metrics->x_scale; size->ttmetrics.ppem = metrics->x_ppem; size->ttmetrics.x_ratio = 0x10000L; size->ttmetrics.y_ratio = FT_DivFix( metrics->y_ppem, metrics->x_ppem ); } else { size->ttmetrics.scale = metrics->y_scale; size->ttmetrics.ppem = metrics->y_ppem; size->ttmetrics.x_ratio = FT_DivFix( metrics->x_ppem, metrics->y_ppem ); size->ttmetrics.y_ratio = 0x10000L; } #ifdef TT_USE_BYTECODE_INTERPRETER size->cvt_ready = -1; #endif /* TT_USE_BYTECODE_INTERPRETER */ return FT_Err_Ok; }
328,349,556,850,502,900,000,000,000,000,000,000,000
None
null
[ "CWE-787" ]
CVE-2017-7864
FreeType 2 before 2017-02-02 has an out-of-bounds write caused by a heap-based buffer overflow related to the tt_size_reset function in truetype/ttobjs.c.
https://nvd.nist.gov/vuln/detail/CVE-2017-7864
158,073
savannah
e6699596af5c5d6f0ae0ea06e19df87dce088df8
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=e6699596af5c5d6f0ae0ea06e19df87dce088df8
None
0
tt_size_reset( TT_Size size, FT_Bool only_height ) { TT_Face face; FT_Size_Metrics* metrics; face = (TT_Face)size->root.face; /* nothing to do for CFF2 */ if ( face->isCFF2 ) return FT_Err_Ok; size->ttmetrics.valid = FALSE; metrics = &size->metrics; /* copy the result from base layer */ /* This bit flag, if set, indicates that the ppems must be */ /* rounded to integers. Nearly all TrueType fonts have this bit */ /* set, as hinting won't work really well otherwise. */ /* */ if ( face->header.Flags & 8 ) { metrics->ascender = FT_PIX_ROUND( FT_MulFix( face->root.ascender, metrics->y_scale ) ); metrics->descender = FT_PIX_ROUND( FT_MulFix( face->root.descender, metrics->y_scale ) ); metrics->height = FT_PIX_ROUND( FT_MulFix( face->root.height, metrics->y_scale ) ); } size->ttmetrics.valid = TRUE; if ( only_height ) return FT_Err_Ok; if ( face->header.Flags & 8 ) { metrics->x_scale = FT_DivFix( metrics->x_ppem << 6, face->root.units_per_EM ); metrics->y_scale = FT_DivFix( metrics->y_ppem << 6, face->root.units_per_EM ); metrics->max_advance = FT_PIX_ROUND( FT_MulFix( face->root.max_advance_width, metrics->x_scale ) ); } /* compute new transformation */ if ( metrics->x_ppem >= metrics->y_ppem ) { size->ttmetrics.scale = metrics->x_scale; size->ttmetrics.ppem = metrics->x_ppem; size->ttmetrics.x_ratio = 0x10000L; size->ttmetrics.y_ratio = FT_DivFix( metrics->y_ppem, metrics->x_ppem ); } else { size->ttmetrics.scale = metrics->y_scale; size->ttmetrics.ppem = metrics->y_ppem; size->ttmetrics.x_ratio = FT_DivFix( metrics->x_ppem, metrics->y_ppem ); size->ttmetrics.y_ratio = 0x10000L; } #ifdef TT_USE_BYTECODE_INTERPRETER size->cvt_ready = -1; #endif /* TT_USE_BYTECODE_INTERPRETER */ return FT_Err_Ok; }
242,836,455,535,349,770,000,000,000,000,000,000,000
None
null
[ "CWE-787" ]
CVE-2017-7864
FreeType 2 before 2017-02-02 has an out-of-bounds write caused by a heap-based buffer overflow related to the tt_size_reset function in truetype/ttobjs.c.
https://nvd.nist.gov/vuln/detail/CVE-2017-7864
214
savannah
7bbb91fbf47fc0775cc9705673caf0c47a81f94b
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=7bbb91fbf47fc0775cc9705673caf0c47a81f94b
None
1
sfnt_init_face( FT_Stream stream, TT_Face face, FT_Int face_instance_index, FT_Int num_params, FT_Parameter* params ) { FT_Error error; FT_Memory memory = face->root.memory; FT_Library library = face->root.driver->root.library; SFNT_Service sfnt; FT_Int face_index; /* for now, parameters are unused */ FT_UNUSED( num_params ); FT_UNUSED( params ); sfnt = (SFNT_Service)face->sfnt; if ( !sfnt ) { sfnt = (SFNT_Service)FT_Get_Module_Interface( library, "sfnt" ); if ( !sfnt ) { FT_ERROR(( "sfnt_init_face: cannot access `sfnt' module\n" )); return FT_THROW( Missing_Module ); } face->sfnt = sfnt; face->goto_table = sfnt->goto_table; } FT_FACE_FIND_GLOBAL_SERVICE( face, face->psnames, POSTSCRIPT_CMAPS ); #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT if ( !face->mm ) { /* we want the MM interface from the `truetype' module only */ FT_Module tt_module = FT_Get_Module( library, "truetype" ); face->mm = ft_module_get_service( tt_module, FT_SERVICE_ID_MULTI_MASTERS, 0 ); } if ( !face->var ) { /* we want the metrics variations interface */ /* from the `truetype' module only */ FT_Module tt_module = FT_Get_Module( library, "truetype" ); face->var = ft_module_get_service( tt_module, FT_SERVICE_ID_METRICS_VARIATIONS, 0 ); } #endif FT_TRACE2(( "SFNT driver\n" )); error = sfnt_open_font( stream, face ); if ( error ) return error; /* Stream may have changed in sfnt_open_font. */ stream = face->root.stream; FT_TRACE2(( "sfnt_init_face: %08p, %d\n", face, face_instance_index )); face_index = FT_ABS( face_instance_index ) & 0xFFFF; /* value -(N+1) requests information on index N */ if ( face_instance_index < 0 ) face_index--; if ( face_index >= face->ttc_header.count ) { if ( face_instance_index >= 0 ) return FT_THROW( Invalid_Argument ); else face_index = 0; } if ( FT_STREAM_SEEK( face->ttc_header.offsets[face_index] ) ) return error; /* check whether we have a valid TrueType file */ error = sfnt->load_font_dir( face, stream ); if ( error ) return error; #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT { FT_ULong fvar_len; FT_ULong version; FT_ULong offset; FT_UShort num_axes; FT_UShort axis_size; FT_UShort num_instances; FT_UShort instance_size; FT_Int instance_index; FT_Byte* default_values = NULL; FT_Byte* instance_values = NULL; face->is_default_instance = 1; instance_index = FT_ABS( face_instance_index ) >> 16; /* test whether current face is a GX font with named instances */ if ( face->goto_table( face, TTAG_fvar, stream, &fvar_len ) || fvar_len < 20 || FT_READ_ULONG( version ) || FT_READ_USHORT( offset ) || FT_STREAM_SKIP( 2 ) /* reserved */ || FT_READ_USHORT( num_axes ) || FT_READ_USHORT( axis_size ) || FT_READ_USHORT( num_instances ) || FT_READ_USHORT( instance_size ) ) { version = 0; offset = 0; num_axes = 0; axis_size = 0; num_instances = 0; instance_size = 0; } /* check that the data is bound by the table length */ if ( version != 0x00010000UL || axis_size != 20 || num_axes == 0 || /* `num_axes' limit implied by 16-bit `instance_size' */ num_axes > 0x3FFE || !( instance_size == 4 + 4 * num_axes || instance_size == 6 + 4 * num_axes ) || /* `num_instances' limit implied by limited range of name IDs */ num_instances > 0x7EFF || offset + axis_size * num_axes + instance_size * num_instances > fvar_len ) num_instances = 0; else face->variation_support |= TT_FACE_FLAG_VAR_FVAR; /* * As documented in the OpenType specification, an entry for the * default instance may be omitted in the named instance table. In * particular this means that even if there is no named instance * table in the font we actually do have a named instance, namely the * default instance. * * For consistency, we always want the default instance in our list * of named instances. If it is missing, we try to synthesize it * later on. Here, we have to adjust `num_instances' accordingly. */ if ( !( FT_ALLOC( default_values, num_axes * 2 ) || FT_ALLOC( instance_values, num_axes * 2 ) ) ) { /* the current stream position is 16 bytes after the table start */ FT_ULong array_start = FT_STREAM_POS() - 16 + offset; FT_ULong default_value_offset, instance_offset; FT_Byte* p; FT_UInt i; default_value_offset = array_start + 8; p = default_values; for ( i = 0; i < num_axes; i++ ) { (void)FT_STREAM_READ_AT( default_value_offset, p, 2 ); default_value_offset += axis_size; p += 2; } instance_offset = array_start + axis_size * num_axes + 4; for ( i = 0; i < num_instances; i++ ) { (void)FT_STREAM_READ_AT( instance_offset, instance_values, num_axes * 2 ); if ( !ft_memcmp( default_values, instance_values, num_axes * 2 ) ) break; instance_offset += instance_size; } if ( i == num_instances ) { /* no default instance in named instance table; */ /* we thus have to synthesize it */ num_instances++; } } FT_FREE( default_values ); FT_FREE( instance_values ); /* we don't support Multiple Master CFFs yet */ if ( face->goto_table( face, TTAG_glyf, stream, 0 ) && !face->goto_table( face, TTAG_CFF, stream, 0 ) ) num_instances = 0; if ( instance_index > num_instances ) { if ( face_instance_index >= 0 ) return FT_THROW( Invalid_Argument ); else num_instances = 0; } face->root.style_flags = (FT_Long)num_instances << 16; } #endif face->root.num_faces = face->ttc_header.count; face->root.face_index = face_instance_index; return error; }
119,798,325,318,146,810,000,000,000,000,000,000,000
None
null
[ "CWE-787" ]
CVE-2017-7857
FreeType 2 before 2017-03-08 has an out-of-bounds write caused by a heap-based buffer overflow related to the TT_Get_MM_Var function in truetype/ttgxvar.c and the sfnt_init_face function in sfnt/sfobjs.c.
https://nvd.nist.gov/vuln/detail/CVE-2017-7857
158,074
savannah
7bbb91fbf47fc0775cc9705673caf0c47a81f94b
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=7bbb91fbf47fc0775cc9705673caf0c47a81f94b
None
0
sfnt_init_face( FT_Stream stream, TT_Face face, FT_Int face_instance_index, FT_Int num_params, FT_Parameter* params ) { FT_Error error; FT_Memory memory = face->root.memory; FT_Library library = face->root.driver->root.library; SFNT_Service sfnt; FT_Int face_index; /* for now, parameters are unused */ FT_UNUSED( num_params ); FT_UNUSED( params ); sfnt = (SFNT_Service)face->sfnt; if ( !sfnt ) { sfnt = (SFNT_Service)FT_Get_Module_Interface( library, "sfnt" ); if ( !sfnt ) { FT_ERROR(( "sfnt_init_face: cannot access `sfnt' module\n" )); return FT_THROW( Missing_Module ); } face->sfnt = sfnt; face->goto_table = sfnt->goto_table; } FT_FACE_FIND_GLOBAL_SERVICE( face, face->psnames, POSTSCRIPT_CMAPS ); #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT if ( !face->mm ) { /* we want the MM interface from the `truetype' module only */ FT_Module tt_module = FT_Get_Module( library, "truetype" ); face->mm = ft_module_get_service( tt_module, FT_SERVICE_ID_MULTI_MASTERS, 0 ); } if ( !face->var ) { /* we want the metrics variations interface */ /* from the `truetype' module only */ FT_Module tt_module = FT_Get_Module( library, "truetype" ); face->var = ft_module_get_service( tt_module, FT_SERVICE_ID_METRICS_VARIATIONS, 0 ); } #endif FT_TRACE2(( "SFNT driver\n" )); error = sfnt_open_font( stream, face ); if ( error ) return error; /* Stream may have changed in sfnt_open_font. */ stream = face->root.stream; FT_TRACE2(( "sfnt_init_face: %08p, %d\n", face, face_instance_index )); face_index = FT_ABS( face_instance_index ) & 0xFFFF; /* value -(N+1) requests information on index N */ if ( face_instance_index < 0 ) face_index--; if ( face_index >= face->ttc_header.count ) { if ( face_instance_index >= 0 ) return FT_THROW( Invalid_Argument ); else face_index = 0; } if ( FT_STREAM_SEEK( face->ttc_header.offsets[face_index] ) ) return error; /* check whether we have a valid TrueType file */ error = sfnt->load_font_dir( face, stream ); if ( error ) return error; #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT { FT_ULong fvar_len; FT_ULong version; FT_ULong offset; FT_UShort num_axes; FT_UShort axis_size; FT_UShort num_instances; FT_UShort instance_size; FT_Int instance_index; FT_Byte* default_values = NULL; FT_Byte* instance_values = NULL; face->is_default_instance = 1; instance_index = FT_ABS( face_instance_index ) >> 16; /* test whether current face is a GX font with named instances */ if ( face->goto_table( face, TTAG_fvar, stream, &fvar_len ) || fvar_len < 20 || FT_READ_ULONG( version ) || FT_READ_USHORT( offset ) || FT_STREAM_SKIP( 2 ) /* reserved */ || FT_READ_USHORT( num_axes ) || FT_READ_USHORT( axis_size ) || FT_READ_USHORT( num_instances ) || FT_READ_USHORT( instance_size ) ) { version = 0; offset = 0; num_axes = 0; axis_size = 0; num_instances = 0; instance_size = 0; } /* check that the data is bound by the table length */ if ( version != 0x00010000UL || axis_size != 20 || num_axes == 0 || /* `num_axes' limit implied by 16-bit `instance_size' */ num_axes > 0x3FFE || !( instance_size == 4 + 4 * num_axes || instance_size == 6 + 4 * num_axes ) || /* `num_instances' limit implied by limited range of name IDs */ num_instances > 0x7EFF || offset + axis_size * num_axes + instance_size * num_instances > fvar_len ) num_instances = 0; else face->variation_support |= TT_FACE_FLAG_VAR_FVAR; /* * As documented in the OpenType specification, an entry for the * default instance may be omitted in the named instance table. In * particular this means that even if there is no named instance * table in the font we actually do have a named instance, namely the * default instance. * * For consistency, we always want the default instance in our list * of named instances. If it is missing, we try to synthesize it * later on. Here, we have to adjust `num_instances' accordingly. */ if ( !( FT_ALLOC( default_values, num_axes * 2 ) || FT_ALLOC( instance_values, num_axes * 2 ) ) ) { /* the current stream position is 16 bytes after the table start */ FT_ULong array_start = FT_STREAM_POS() - 16 + offset; FT_ULong default_value_offset, instance_offset; FT_Byte* p; FT_UInt i; default_value_offset = array_start + 8; p = default_values; for ( i = 0; i < num_axes; i++ ) { (void)FT_STREAM_READ_AT( default_value_offset, p, 2 ); default_value_offset += axis_size; p += 2; } instance_offset = array_start + axis_size * num_axes + 4; for ( i = 0; i < num_instances; i++ ) { (void)FT_STREAM_READ_AT( instance_offset, instance_values, num_axes * 2 ); if ( !ft_memcmp( default_values, instance_values, num_axes * 2 ) ) break; instance_offset += instance_size; } if ( i == num_instances ) { /* no default instance in named instance table; */ /* we thus have to synthesize it */ num_instances++; } } FT_FREE( default_values ); FT_FREE( instance_values ); /* we don't support Multiple Master CFFs yet; */ /* note that `glyf' or `CFF2' have precedence */ if ( face->goto_table( face, TTAG_glyf, stream, 0 ) && face->goto_table( face, TTAG_CFF2, stream, 0 ) && !face->goto_table( face, TTAG_CFF, stream, 0 ) ) num_instances = 0; if ( instance_index > num_instances ) { if ( face_instance_index >= 0 ) return FT_THROW( Invalid_Argument ); else num_instances = 0; } face->root.style_flags = (FT_Long)num_instances << 16; } #endif face->root.num_faces = face->ttc_header.count; face->root.face_index = face_instance_index; return error; }
226,909,658,136,416,080,000,000,000,000,000,000,000
None
null
[ "CWE-787" ]
CVE-2017-7857
FreeType 2 before 2017-03-08 has an out-of-bounds write caused by a heap-based buffer overflow related to the TT_Get_MM_Var function in truetype/ttgxvar.c and the sfnt_init_face function in sfnt/sfobjs.c.
https://nvd.nist.gov/vuln/detail/CVE-2017-7857
215
poppler
5c9b08a875b07853be6c44e43ff5f7f059df666a
https://github.com/freedesktop/poppler
https://cgit.freedesktop.org/poppler/poppler/commit/?id=5c9b08a875b07853be6c44e43ff5f7f059df666a
pdfunite: Fix crash with broken documents Sometimes we can't parse pages so check before accessing them Thanks to Jiaqi Peng for the report Fixes bugs #101153 and #101149
1
int main (int argc, char *argv[]) { int objectsCount = 0; Guint numOffset = 0; std::vector<Object> pages; std::vector<Guint> offsets; XRef *yRef, *countRef; FILE *f; OutStream *outStr; int i; int j, rootNum; std::vector<PDFDoc *>docs; int majorVersion = 0; int minorVersion = 0; char *fileName = argv[argc - 1]; int exitCode; exitCode = 99; const GBool ok = parseArgs (argDesc, &argc, argv); if (!ok || argc < 3 || printVersion || printHelp) { fprintf(stderr, "pdfunite version %s\n", PACKAGE_VERSION); fprintf(stderr, "%s\n", popplerCopyright); fprintf(stderr, "%s\n", xpdfCopyright); if (!printVersion) { printUsage("pdfunite", "<PDF-sourcefile-1>..<PDF-sourcefile-n> <PDF-destfile>", argDesc); } if (printVersion || printHelp) exitCode = 0; return exitCode; } exitCode = 0; globalParams = new GlobalParams(); for (i = 1; i < argc - 1; i++) { GooString *gfileName = new GooString(argv[i]); PDFDoc *doc = new PDFDoc(gfileName, NULL, NULL, NULL); if (doc->isOk() && !doc->isEncrypted()) { docs.push_back(doc); if (doc->getPDFMajorVersion() > majorVersion) { majorVersion = doc->getPDFMajorVersion(); minorVersion = doc->getPDFMinorVersion(); } else if (doc->getPDFMajorVersion() == majorVersion) { if (doc->getPDFMinorVersion() > minorVersion) { minorVersion = doc->getPDFMinorVersion(); } } } else if (doc->isOk()) { error(errUnimplemented, -1, "Could not merge encrypted files ('{0:s}')", argv[i]); return -1; } else { error(errSyntaxError, -1, "Could not merge damaged documents ('{0:s}')", argv[i]); return -1; } } if (!(f = fopen(fileName, "wb"))) { error(errIO, -1, "Could not open file '{0:s}'", fileName); return -1; } outStr = new FileOutStream(f, 0); yRef = new XRef(); countRef = new XRef(); yRef->add(0, 65535, 0, gFalse); PDFDoc::writeHeader(outStr, majorVersion, minorVersion); Object intents; Object afObj; Object ocObj; Object names; if (docs.size() >= 1) { Object catObj; docs[0]->getXRef()->getCatalog(&catObj); Dict *catDict = catObj.getDict(); catDict->lookup("OutputIntents", &intents); catDict->lookupNF("AcroForm", &afObj); Ref *refPage = docs[0]->getCatalog()->getPageRef(1); if (!afObj.isNull()) { docs[0]->markAcroForm(&afObj, yRef, countRef, 0, refPage->num, refPage->num); } catDict->lookupNF("OCProperties", &ocObj); if (!ocObj.isNull() && ocObj.isDict()) { docs[0]->markPageObjects(ocObj.getDict(), yRef, countRef, 0, refPage->num, refPage->num); } catDict->lookup("Names", &names); if (!names.isNull() && names.isDict()) { docs[0]->markPageObjects(names.getDict(), yRef, countRef, 0, refPage->num, refPage->num); } if (intents.isArray() && intents.arrayGetLength() > 0) { for (i = 1; i < (int) docs.size(); i++) { Object pagecatObj, pageintents; docs[i]->getXRef()->getCatalog(&pagecatObj); Dict *pagecatDict = pagecatObj.getDict(); pagecatDict->lookup("OutputIntents", &pageintents); if (pageintents.isArray() && pageintents.arrayGetLength() > 0) { for (j = intents.arrayGetLength() - 1; j >= 0; j--) { Object intent; intents.arrayGet(j, &intent, 0); if (intent.isDict()) { Object idf; intent.dictLookup("OutputConditionIdentifier", &idf); if (idf.isString()) { GooString *gidf = idf.getString(); GBool removeIntent = gTrue; for (int k = 0; k < pageintents.arrayGetLength(); k++) { Object pgintent; pageintents.arrayGet(k, &pgintent, 0); if (pgintent.isDict()) { Object pgidf; pgintent.dictLookup("OutputConditionIdentifier", &pgidf); if (pgidf.isString()) { GooString *gpgidf = pgidf.getString(); if (gpgidf->cmp(gidf) == 0) { pgidf.free(); removeIntent = gFalse; break; } } pgidf.free(); } } if (removeIntent) { intents.arrayRemove(j); error(errSyntaxWarning, -1, "Output intent {0:s} missing in pdf {1:s}, removed", gidf->getCString(), docs[i]->getFileName()->getCString()); } } else { intents.arrayRemove(j); error(errSyntaxWarning, -1, "Invalid output intent dict, missing required OutputConditionIdentifier"); } idf.free(); } else { intents.arrayRemove(j); } intent.free(); } } else { error(errSyntaxWarning, -1, "Output intents differs, remove them all"); intents.free(); break; } pagecatObj.free(); pageintents.free(); } } if (intents.isArray() && intents.arrayGetLength() > 0) { for (j = intents.arrayGetLength() - 1; j >= 0; j--) { Object intent; intents.arrayGet(j, &intent, 0); if (intent.isDict()) { docs[0]->markPageObjects(intent.getDict(), yRef, countRef, numOffset, 0, 0); } else { intents.arrayRemove(j); } intent.free(); } } catObj.free(); } for (i = 0; i < (int) docs.size(); i++) { for (j = 1; j <= docs[i]->getNumPages(); j++) { PDFRectangle *cropBox = NULL; if (docs[i]->getCatalog()->getPage(j)->isCropped()) cropBox = docs[i]->getCatalog()->getPage(j)->getCropBox(); Object page; docs[i]->getXRef()->fetch(refPage->num, refPage->gen, &page); Dict *pageDict = page.getDict(); Dict *resDict = docs[i]->getCatalog()->getPage(j)->getResourceDict(); if (resDict) { Object *newResource = new Object(); newResource->initDict(resDict); pageDict->set("Resources", newResource); delete newResource; } pages.push_back(page); offsets.push_back(numOffset); docs[i]->markPageObjects(pageDict, yRef, countRef, numOffset, refPage->num, refPage->num); Object annotsObj; pageDict->lookupNF("Annots", &annotsObj); if (!annotsObj.isNull()) { docs[i]->markAnnotations(&annotsObj, yRef, countRef, numOffset, refPage->num, refPage->num); annotsObj.free(); } } Object pageCatObj, pageNames, pageForm; docs[i]->getXRef()->getCatalog(&pageCatObj); Dict *pageCatDict = pageCatObj.getDict(); pageCatDict->lookup("Names", &pageNames); if (!pageNames.isNull() && pageNames.isDict()) { if (!names.isDict()) { names.free(); names.initDict(yRef); } doMergeNameDict(docs[i], yRef, countRef, 0, 0, names.getDict(), pageNames.getDict(), numOffset); } pageCatDict->lookup("AcroForm", &pageForm); if (i > 0 && !pageForm.isNull() && pageForm.isDict()) { if (afObj.isNull()) { pageCatDict->lookupNF("AcroForm", &afObj); } else if (afObj.isDict()) { doMergeFormDict(afObj.getDict(), pageForm.getDict(), numOffset); } } pageForm.free(); pageNames.free(); pageCatObj.free(); objectsCount += docs[i]->writePageObjects(outStr, yRef, numOffset, gTrue); numOffset = yRef->getNumObjects() + 1; } rootNum = yRef->getNumObjects() + 1; yRef->add(rootNum, 0, outStr->getPos(), gTrue); outStr->printf("%d 0 obj\n", rootNum); outStr->printf("<< /Type /Catalog /Pages %d 0 R", rootNum + 1); if (intents.isArray() && intents.arrayGetLength() > 0) { outStr->printf(" /OutputIntents ["); for (j = 0; j < intents.arrayGetLength(); j++) { Object intent; intents.arrayGet(j, &intent, 0); if (intent.isDict()) { PDFDoc::writeObject(&intent, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0); } intent.free(); } outStr->printf("]"); } intents.free(); if (!afObj.isNull()) { outStr->printf(" /AcroForm "); PDFDoc::writeObject(&afObj, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0); afObj.free(); } if (!ocObj.isNull() && ocObj.isDict()) { outStr->printf(" /OCProperties "); PDFDoc::writeObject(&ocObj, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0); ocObj.free(); } if (!names.isNull() && names.isDict()) { outStr->printf(" /Names "); PDFDoc::writeObject(&names, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0); names.free(); } outStr->printf(">>\nendobj\n"); objectsCount++; yRef->add(rootNum + 1, 0, outStr->getPos(), gTrue); outStr->printf("%d 0 obj\n", rootNum + 1); outStr->printf("<< /Type /Pages /Kids ["); for (j = 0; j < (int) pages.size(); j++) outStr->printf(" %d 0 R", rootNum + j + 2); outStr->printf(" ] /Count %zd >>\nendobj\n", pages.size()); objectsCount++; for (i = 0; i < (int) pages.size(); i++) { yRef->add(rootNum + i + 2, 0, outStr->getPos(), gTrue); outStr->printf("%d 0 obj\n", rootNum + i + 2); outStr->printf("<< "); Dict *pageDict = pages[i].getDict(); for (j = 0; j < pageDict->getLength(); j++) { if (j > 0) outStr->printf(" "); const char *key = pageDict->getKey(j); Object value; pageDict->getValNF(j, &value); if (strcmp(key, "Parent") == 0) { outStr->printf("/Parent %d 0 R", rootNum + 1); } else { outStr->printf("/%s ", key); PDFDoc::writeObject(&value, outStr, yRef, offsets[i], NULL, cryptRC4, 0, 0, 0); } value.free(); } outStr->printf(" >>\nendobj\n"); objectsCount++; } Goffset uxrefOffset = outStr->getPos(); Ref ref; ref.num = rootNum; ref.gen = 0; Dict *trailerDict = PDFDoc::createTrailerDict(objectsCount, gFalse, 0, &ref, yRef, fileName, outStr->getPos()); PDFDoc::writeXRefTableTrailer(trailerDict, yRef, gTrue, // write all entries according to ISO 32000-1, 7.5.4 Cross-Reference Table: "For a file that has never been incrementally updated, the cross-reference section shall contain only one subsection, whose object numbering begins at 0." uxrefOffset, outStr, yRef); delete trailerDict; outStr->close(); delete outStr; fclose(f); delete yRef; delete countRef; for (j = 0; j < (int) pages.size (); j++) pages[j].free(); for (i = 0; i < (int) docs.size (); i++) delete docs[i]; delete globalParams; return exitCode; }
180,050,936,886,598,400,000,000,000,000,000,000,000
None
null
[ "CWE-476" ]
CVE-2017-7511
poppler since version 0.17.3 has been vulnerable to NULL pointer dereference in pdfunite triggered by specially crafted documents.
https://nvd.nist.gov/vuln/detail/CVE-2017-7511
158,075
poppler
5c9b08a875b07853be6c44e43ff5f7f059df666a
https://github.com/freedesktop/poppler
https://cgit.freedesktop.org/poppler/poppler/commit/?id=5c9b08a875b07853be6c44e43ff5f7f059df666a
pdfunite: Fix crash with broken documents Sometimes we can't parse pages so check before accessing them Thanks to Jiaqi Peng for the report Fixes bugs #101153 and #101149
0
int main (int argc, char *argv[]) { int objectsCount = 0; Guint numOffset = 0; std::vector<Object> pages; std::vector<Guint> offsets; XRef *yRef, *countRef; FILE *f; OutStream *outStr; int i; int j, rootNum; std::vector<PDFDoc *>docs; int majorVersion = 0; int minorVersion = 0; char *fileName = argv[argc - 1]; int exitCode; exitCode = 99; const GBool ok = parseArgs (argDesc, &argc, argv); if (!ok || argc < 3 || printVersion || printHelp) { fprintf(stderr, "pdfunite version %s\n", PACKAGE_VERSION); fprintf(stderr, "%s\n", popplerCopyright); fprintf(stderr, "%s\n", xpdfCopyright); if (!printVersion) { printUsage("pdfunite", "<PDF-sourcefile-1>..<PDF-sourcefile-n> <PDF-destfile>", argDesc); } if (printVersion || printHelp) exitCode = 0; return exitCode; } exitCode = 0; globalParams = new GlobalParams(); for (i = 1; i < argc - 1; i++) { GooString *gfileName = new GooString(argv[i]); PDFDoc *doc = new PDFDoc(gfileName, NULL, NULL, NULL); if (doc->isOk() && !doc->isEncrypted()) { docs.push_back(doc); if (doc->getPDFMajorVersion() > majorVersion) { majorVersion = doc->getPDFMajorVersion(); minorVersion = doc->getPDFMinorVersion(); } else if (doc->getPDFMajorVersion() == majorVersion) { if (doc->getPDFMinorVersion() > minorVersion) { minorVersion = doc->getPDFMinorVersion(); } } } else if (doc->isOk()) { error(errUnimplemented, -1, "Could not merge encrypted files ('{0:s}')", argv[i]); return -1; } else { error(errSyntaxError, -1, "Could not merge damaged documents ('{0:s}')", argv[i]); return -1; } } if (!(f = fopen(fileName, "wb"))) { error(errIO, -1, "Could not open file '{0:s}'", fileName); return -1; } outStr = new FileOutStream(f, 0); yRef = new XRef(); countRef = new XRef(); yRef->add(0, 65535, 0, gFalse); PDFDoc::writeHeader(outStr, majorVersion, minorVersion); Object intents; Object afObj; Object ocObj; Object names; if (docs.size() >= 1) { Object catObj; docs[0]->getXRef()->getCatalog(&catObj); Dict *catDict = catObj.getDict(); catDict->lookup("OutputIntents", &intents); catDict->lookupNF("AcroForm", &afObj); Ref *refPage = docs[0]->getCatalog()->getPageRef(1); if (!afObj.isNull() && refPage) { docs[0]->markAcroForm(&afObj, yRef, countRef, 0, refPage->num, refPage->num); } catDict->lookupNF("OCProperties", &ocObj); if (!ocObj.isNull() && ocObj.isDict() && refPage) { docs[0]->markPageObjects(ocObj.getDict(), yRef, countRef, 0, refPage->num, refPage->num); } catDict->lookup("Names", &names); if (!names.isNull() && names.isDict() && refPage) { docs[0]->markPageObjects(names.getDict(), yRef, countRef, 0, refPage->num, refPage->num); } if (intents.isArray() && intents.arrayGetLength() > 0) { for (i = 1; i < (int) docs.size(); i++) { Object pagecatObj, pageintents; docs[i]->getXRef()->getCatalog(&pagecatObj); Dict *pagecatDict = pagecatObj.getDict(); pagecatDict->lookup("OutputIntents", &pageintents); if (pageintents.isArray() && pageintents.arrayGetLength() > 0) { for (j = intents.arrayGetLength() - 1; j >= 0; j--) { Object intent; intents.arrayGet(j, &intent, 0); if (intent.isDict()) { Object idf; intent.dictLookup("OutputConditionIdentifier", &idf); if (idf.isString()) { GooString *gidf = idf.getString(); GBool removeIntent = gTrue; for (int k = 0; k < pageintents.arrayGetLength(); k++) { Object pgintent; pageintents.arrayGet(k, &pgintent, 0); if (pgintent.isDict()) { Object pgidf; pgintent.dictLookup("OutputConditionIdentifier", &pgidf); if (pgidf.isString()) { GooString *gpgidf = pgidf.getString(); if (gpgidf->cmp(gidf) == 0) { pgidf.free(); removeIntent = gFalse; break; } } pgidf.free(); } } if (removeIntent) { intents.arrayRemove(j); error(errSyntaxWarning, -1, "Output intent {0:s} missing in pdf {1:s}, removed", gidf->getCString(), docs[i]->getFileName()->getCString()); } } else { intents.arrayRemove(j); error(errSyntaxWarning, -1, "Invalid output intent dict, missing required OutputConditionIdentifier"); } idf.free(); } else { intents.arrayRemove(j); } intent.free(); } } else { error(errSyntaxWarning, -1, "Output intents differs, remove them all"); intents.free(); break; } pagecatObj.free(); pageintents.free(); } } if (intents.isArray() && intents.arrayGetLength() > 0) { for (j = intents.arrayGetLength() - 1; j >= 0; j--) { Object intent; intents.arrayGet(j, &intent, 0); if (intent.isDict()) { docs[0]->markPageObjects(intent.getDict(), yRef, countRef, numOffset, 0, 0); } else { intents.arrayRemove(j); } intent.free(); } } catObj.free(); } for (i = 0; i < (int) docs.size(); i++) { for (j = 1; j <= docs[i]->getNumPages(); j++) { if (!docs[i]->getCatalog()->getPage(j)) { continue; } PDFRectangle *cropBox = NULL; if (docs[i]->getCatalog()->getPage(j)->isCropped()) cropBox = docs[i]->getCatalog()->getPage(j)->getCropBox(); Object page; docs[i]->getXRef()->fetch(refPage->num, refPage->gen, &page); Dict *pageDict = page.getDict(); Dict *resDict = docs[i]->getCatalog()->getPage(j)->getResourceDict(); if (resDict) { Object *newResource = new Object(); newResource->initDict(resDict); pageDict->set("Resources", newResource); delete newResource; } pages.push_back(page); offsets.push_back(numOffset); docs[i]->markPageObjects(pageDict, yRef, countRef, numOffset, refPage->num, refPage->num); Object annotsObj; pageDict->lookupNF("Annots", &annotsObj); if (!annotsObj.isNull()) { docs[i]->markAnnotations(&annotsObj, yRef, countRef, numOffset, refPage->num, refPage->num); annotsObj.free(); } } Object pageCatObj, pageNames, pageForm; docs[i]->getXRef()->getCatalog(&pageCatObj); Dict *pageCatDict = pageCatObj.getDict(); pageCatDict->lookup("Names", &pageNames); if (!pageNames.isNull() && pageNames.isDict()) { if (!names.isDict()) { names.free(); names.initDict(yRef); } doMergeNameDict(docs[i], yRef, countRef, 0, 0, names.getDict(), pageNames.getDict(), numOffset); } pageCatDict->lookup("AcroForm", &pageForm); if (i > 0 && !pageForm.isNull() && pageForm.isDict()) { if (afObj.isNull()) { pageCatDict->lookupNF("AcroForm", &afObj); } else if (afObj.isDict()) { doMergeFormDict(afObj.getDict(), pageForm.getDict(), numOffset); } } pageForm.free(); pageNames.free(); pageCatObj.free(); objectsCount += docs[i]->writePageObjects(outStr, yRef, numOffset, gTrue); numOffset = yRef->getNumObjects() + 1; } rootNum = yRef->getNumObjects() + 1; yRef->add(rootNum, 0, outStr->getPos(), gTrue); outStr->printf("%d 0 obj\n", rootNum); outStr->printf("<< /Type /Catalog /Pages %d 0 R", rootNum + 1); if (intents.isArray() && intents.arrayGetLength() > 0) { outStr->printf(" /OutputIntents ["); for (j = 0; j < intents.arrayGetLength(); j++) { Object intent; intents.arrayGet(j, &intent, 0); if (intent.isDict()) { PDFDoc::writeObject(&intent, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0); } intent.free(); } outStr->printf("]"); } intents.free(); if (!afObj.isNull()) { outStr->printf(" /AcroForm "); PDFDoc::writeObject(&afObj, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0); afObj.free(); } if (!ocObj.isNull() && ocObj.isDict()) { outStr->printf(" /OCProperties "); PDFDoc::writeObject(&ocObj, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0); ocObj.free(); } if (!names.isNull() && names.isDict()) { outStr->printf(" /Names "); PDFDoc::writeObject(&names, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0); names.free(); } outStr->printf(">>\nendobj\n"); objectsCount++; yRef->add(rootNum + 1, 0, outStr->getPos(), gTrue); outStr->printf("%d 0 obj\n", rootNum + 1); outStr->printf("<< /Type /Pages /Kids ["); for (j = 0; j < (int) pages.size(); j++) outStr->printf(" %d 0 R", rootNum + j + 2); outStr->printf(" ] /Count %zd >>\nendobj\n", pages.size()); objectsCount++; for (i = 0; i < (int) pages.size(); i++) { yRef->add(rootNum + i + 2, 0, outStr->getPos(), gTrue); outStr->printf("%d 0 obj\n", rootNum + i + 2); outStr->printf("<< "); Dict *pageDict = pages[i].getDict(); for (j = 0; j < pageDict->getLength(); j++) { if (j > 0) outStr->printf(" "); const char *key = pageDict->getKey(j); Object value; pageDict->getValNF(j, &value); if (strcmp(key, "Parent") == 0) { outStr->printf("/Parent %d 0 R", rootNum + 1); } else { outStr->printf("/%s ", key); PDFDoc::writeObject(&value, outStr, yRef, offsets[i], NULL, cryptRC4, 0, 0, 0); } value.free(); } outStr->printf(" >>\nendobj\n"); objectsCount++; } Goffset uxrefOffset = outStr->getPos(); Ref ref; ref.num = rootNum; ref.gen = 0; Dict *trailerDict = PDFDoc::createTrailerDict(objectsCount, gFalse, 0, &ref, yRef, fileName, outStr->getPos()); PDFDoc::writeXRefTableTrailer(trailerDict, yRef, gTrue, // write all entries according to ISO 32000-1, 7.5.4 Cross-Reference Table: "For a file that has never been incrementally updated, the cross-reference section shall contain only one subsection, whose object numbering begins at 0." uxrefOffset, outStr, yRef); delete trailerDict; outStr->close(); delete outStr; fclose(f); delete yRef; delete countRef; for (j = 0; j < (int) pages.size (); j++) pages[j].free(); for (i = 0; i < (int) docs.size (); i++) delete docs[i]; delete globalParams; return exitCode; }
4,674,050,423,349,651,500,000,000,000,000,000,000
None
null
[ "CWE-476" ]
CVE-2017-7511
poppler since version 0.17.3 has been vulnerable to NULL pointer dereference in pdfunite triggered by specially crafted documents.
https://nvd.nist.gov/vuln/detail/CVE-2017-7511
216
savannah
94e01571507835ff59dd8ce2a0b56a4b566965a4
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/gitweb/?p=gnulib.git;a=commit;h=94e01571507835ff59dd8ce2a0b56a4b566965a4
None
1
main (int argc _GL_UNUSED, char **argv) { struct timespec result; struct timespec result2; struct timespec expected; struct timespec now; const char *p; int i; long gmtoff; time_t ref_time = 1304250918; /* Set the time zone to US Eastern time with the 2012 rules. This should disable any leap second support. Otherwise, there will be a problem with glibc on sites that default to leap seconds; see <http://bugs.gnu.org/12206>. */ setenv ("TZ", "EST5EDT,M3.2.0,M11.1.0", 1); gmtoff = gmt_offset (ref_time); /* ISO 8601 extended date and time of day representation, 'T' separator, local time zone */ p = "2011-05-01T11:55:18"; expected.tv_sec = ref_time - gmtoff; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, ' ' separator, local time zone */ p = "2011-05-01 11:55:18"; expected.tv_sec = ref_time - gmtoff; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601, extended date and time of day representation, 'T' separator, UTC */ p = "2011-05-01T11:55:18Z"; expected.tv_sec = ref_time; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601, extended date and time of day representation, ' ' separator, UTC */ p = "2011-05-01 11:55:18Z"; expected.tv_sec = ref_time; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, 'T' separator, w/UTC offset */ p = "2011-05-01T11:55:18-07:00"; expected.tv_sec = 1304276118; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, ' ' separator, w/UTC offset */ p = "2011-05-01 11:55:18-07:00"; expected.tv_sec = 1304276118; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, 'T' separator, w/hour only UTC offset */ p = "2011-05-01T11:55:18-07"; expected.tv_sec = 1304276118; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, ' ' separator, w/hour only UTC offset */ p = "2011-05-01 11:55:18-07"; expected.tv_sec = 1304276118; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "now"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (now.tv_sec == result.tv_sec && now.tv_nsec == result.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "tomorrow"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (now.tv_sec + 24 * 60 * 60 == result.tv_sec && now.tv_nsec == result.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "yesterday"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (now.tv_sec - 24 * 60 * 60 == result.tv_sec && now.tv_nsec == result.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "4 hours"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (now.tv_sec + 4 * 60 * 60 == result.tv_sec && now.tv_nsec == result.tv_nsec); /* test if timezone is not being ignored for day offset */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+400 +24 hours"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+400 +1 day"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); /* test if several time zones formats are handled same way */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+14:00"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+14"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); p = "UTC+1400"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC-14:00"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC-14"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); p = "UTC-1400"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+0:15"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+0015"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC-1:30"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC-130"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); /* TZ out of range should cause parse_datetime failure */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+25:00"; ASSERT (!parse_datetime (&result, p, &now)); /* Check for several invalid countable dayshifts */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+4:00 +40 yesterday"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 next yesterday"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 tomorrow ago"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 tomorrow hence"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 40 now ago"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 last tomorrow"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 -4 today"; ASSERT (!parse_datetime (&result, p, &now)); /* And check correct usage of dayshifts */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+400 tomorrow"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+400 +1 day"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); p = "UTC+400 1 day hence"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+400 yesterday"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+400 1 day ago"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+400 now"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+400 +0 minutes"; /* silly, but simple "UTC+400" is different*/ ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); /* Check that some "next Monday", "last Wednesday", etc. are correct. */ setenv ("TZ", "UTC0", 1); for (i = 0; day_table[i]; i++) { unsigned int thur2 = 7 * 24 * 3600; /* 2nd thursday */ char tmp[32]; sprintf (tmp, "NEXT %s", day_table[i]); now.tv_sec = thur2 + 4711; now.tv_nsec = 1267; ASSERT (parse_datetime (&result, tmp, &now)); LOG (tmp, now, result); ASSERT (result.tv_nsec == 0); ASSERT (result.tv_sec == thur2 + (i == 4 ? 7 : (i + 3) % 7) * 24 * 3600); sprintf (tmp, "LAST %s", day_table[i]); now.tv_sec = thur2 + 4711; now.tv_nsec = 1267; ASSERT (parse_datetime (&result, tmp, &now)); LOG (tmp, now, result); ASSERT (result.tv_nsec == 0); ASSERT (result.tv_sec == thur2 + ((i + 3) % 7 - 7) * 24 * 3600); } p = "THURSDAY UTC+00"; /* The epoch was on Thursday. */ now.tv_sec = 0; now.tv_nsec = 0; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (result.tv_sec == now.tv_sec && result.tv_nsec == now.tv_nsec); p = "FRIDAY UTC+00"; now.tv_sec = 0; now.tv_nsec = 0; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (result.tv_sec == 24 * 3600 && result.tv_nsec == now.tv_nsec); /* Exercise a sign-extension bug. Before July 2012, an input starting with a high-bit-set byte would be treated like "0". */ ASSERT ( ! parse_datetime (&result, "\xb0", &now)); /* Exercise TZ="" parsing code. */ /* These two would infloop or segfault before Feb 2014. */ ASSERT ( ! parse_datetime (&result, "TZ=\"\"\"", &now)); ASSERT ( ! parse_datetime (&result, "TZ=\"\" \"", &now)); /* Exercise invalid patterns. */ ASSERT ( ! parse_datetime (&result, "TZ=\"", &now)); ASSERT ( ! parse_datetime (&result, "TZ=\"\\\"", &now)); ASSERT ( ! parse_datetime (&result, "TZ=\"\\n", &now)); ASSERT ( ! parse_datetime (&result, "TZ=\"\\n\"", &now)); /* Exercise valid patterns. */ ASSERT ( parse_datetime (&result, "TZ=\"\"", &now)); ASSERT ( parse_datetime (&result, "TZ=\"\" ", &now)); ASSERT ( parse_datetime (&result, " TZ=\"\"", &now)); ASSERT ( parse_datetime (&result, "TZ=\"\\\\\"", &now)); ASSERT ( parse_datetime (&result, "TZ=\"\\\"\"", &now)); return 0; }
85,463,602,567,583,000,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2017-7476
Gnulib before 2017-04-26 has a heap-based buffer overflow with the TZ environment variable. The error is in the save_abbr function in time_rz.c.
https://nvd.nist.gov/vuln/detail/CVE-2017-7476
158,076
savannah
94e01571507835ff59dd8ce2a0b56a4b566965a4
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/gitweb/?p=gnulib.git;a=commit;h=94e01571507835ff59dd8ce2a0b56a4b566965a4
None
0
main (int argc _GL_UNUSED, char **argv) { struct timespec result; struct timespec result2; struct timespec expected; struct timespec now; const char *p; int i; long gmtoff; time_t ref_time = 1304250918; /* Set the time zone to US Eastern time with the 2012 rules. This should disable any leap second support. Otherwise, there will be a problem with glibc on sites that default to leap seconds; see <http://bugs.gnu.org/12206>. */ setenv ("TZ", "EST5EDT,M3.2.0,M11.1.0", 1); gmtoff = gmt_offset (ref_time); /* ISO 8601 extended date and time of day representation, 'T' separator, local time zone */ p = "2011-05-01T11:55:18"; expected.tv_sec = ref_time - gmtoff; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, ' ' separator, local time zone */ p = "2011-05-01 11:55:18"; expected.tv_sec = ref_time - gmtoff; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601, extended date and time of day representation, 'T' separator, UTC */ p = "2011-05-01T11:55:18Z"; expected.tv_sec = ref_time; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601, extended date and time of day representation, ' ' separator, UTC */ p = "2011-05-01 11:55:18Z"; expected.tv_sec = ref_time; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, 'T' separator, w/UTC offset */ p = "2011-05-01T11:55:18-07:00"; expected.tv_sec = 1304276118; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, ' ' separator, w/UTC offset */ p = "2011-05-01 11:55:18-07:00"; expected.tv_sec = 1304276118; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, 'T' separator, w/hour only UTC offset */ p = "2011-05-01T11:55:18-07"; expected.tv_sec = 1304276118; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); /* ISO 8601 extended date and time of day representation, ' ' separator, w/hour only UTC offset */ p = "2011-05-01 11:55:18-07"; expected.tv_sec = 1304276118; expected.tv_nsec = 0; ASSERT (parse_datetime (&result, p, 0)); LOG (p, expected, result); ASSERT (expected.tv_sec == result.tv_sec && expected.tv_nsec == result.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "now"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (now.tv_sec == result.tv_sec && now.tv_nsec == result.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "tomorrow"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (now.tv_sec + 24 * 60 * 60 == result.tv_sec && now.tv_nsec == result.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "yesterday"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (now.tv_sec - 24 * 60 * 60 == result.tv_sec && now.tv_nsec == result.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "4 hours"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (now.tv_sec + 4 * 60 * 60 == result.tv_sec && now.tv_nsec == result.tv_nsec); /* test if timezone is not being ignored for day offset */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+400 +24 hours"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+400 +1 day"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); /* test if several time zones formats are handled same way */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+14:00"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+14"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); p = "UTC+1400"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC-14:00"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC-14"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); p = "UTC-1400"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+0:15"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+0015"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC-1:30"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC-130"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); /* TZ out of range should cause parse_datetime failure */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+25:00"; ASSERT (!parse_datetime (&result, p, &now)); /* Check for several invalid countable dayshifts */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+4:00 +40 yesterday"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 next yesterday"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 tomorrow ago"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 tomorrow hence"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 40 now ago"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 last tomorrow"; ASSERT (!parse_datetime (&result, p, &now)); p = "UTC+4:00 -4 today"; ASSERT (!parse_datetime (&result, p, &now)); /* And check correct usage of dayshifts */ now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+400 tomorrow"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+400 +1 day"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); p = "UTC+400 1 day hence"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+400 yesterday"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+400 1 day ago"; ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); now.tv_sec = 4711; now.tv_nsec = 1267; p = "UTC+400 now"; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); p = "UTC+400 +0 minutes"; /* silly, but simple "UTC+400" is different*/ ASSERT (parse_datetime (&result2, p, &now)); LOG (p, now, result2); ASSERT (result.tv_sec == result2.tv_sec && result.tv_nsec == result2.tv_nsec); /* Check that some "next Monday", "last Wednesday", etc. are correct. */ setenv ("TZ", "UTC0", 1); for (i = 0; day_table[i]; i++) { unsigned int thur2 = 7 * 24 * 3600; /* 2nd thursday */ char tmp[32]; sprintf (tmp, "NEXT %s", day_table[i]); now.tv_sec = thur2 + 4711; now.tv_nsec = 1267; ASSERT (parse_datetime (&result, tmp, &now)); LOG (tmp, now, result); ASSERT (result.tv_nsec == 0); ASSERT (result.tv_sec == thur2 + (i == 4 ? 7 : (i + 3) % 7) * 24 * 3600); sprintf (tmp, "LAST %s", day_table[i]); now.tv_sec = thur2 + 4711; now.tv_nsec = 1267; ASSERT (parse_datetime (&result, tmp, &now)); LOG (tmp, now, result); ASSERT (result.tv_nsec == 0); ASSERT (result.tv_sec == thur2 + ((i + 3) % 7 - 7) * 24 * 3600); } p = "THURSDAY UTC+00"; /* The epoch was on Thursday. */ now.tv_sec = 0; now.tv_nsec = 0; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (result.tv_sec == now.tv_sec && result.tv_nsec == now.tv_nsec); p = "FRIDAY UTC+00"; now.tv_sec = 0; now.tv_nsec = 0; ASSERT (parse_datetime (&result, p, &now)); LOG (p, now, result); ASSERT (result.tv_sec == 24 * 3600 && result.tv_nsec == now.tv_nsec); /* Exercise a sign-extension bug. Before July 2012, an input starting with a high-bit-set byte would be treated like "0". */ ASSERT ( ! parse_datetime (&result, "\xb0", &now)); /* Exercise TZ="" parsing code. */ /* These two would infloop or segfault before Feb 2014. */ ASSERT ( ! parse_datetime (&result, "TZ=\"\"\"", &now)); ASSERT ( ! parse_datetime (&result, "TZ=\"\" \"", &now)); /* Exercise invalid patterns. */ ASSERT ( ! parse_datetime (&result, "TZ=\"", &now)); ASSERT ( ! parse_datetime (&result, "TZ=\"\\\"", &now)); ASSERT ( ! parse_datetime (&result, "TZ=\"\\n", &now)); ASSERT ( ! parse_datetime (&result, "TZ=\"\\n\"", &now)); /* Exercise valid patterns. */ ASSERT ( parse_datetime (&result, "TZ=\"\"", &now)); ASSERT ( parse_datetime (&result, "TZ=\"\" ", &now)); ASSERT ( parse_datetime (&result, " TZ=\"\"", &now)); ASSERT ( parse_datetime (&result, "TZ=\"\\\\\"", &now)); ASSERT ( parse_datetime (&result, "TZ=\"\\\"\"", &now)); /* Outlandishly-long time zone abbreviations should not cause problems. */ { static char const bufprefix[] = "TZ=\""; enum { tzname_len = 2000 }; static char const bufsuffix[] = "0\" 1970-01-01 01:02:03.123456789"; enum { bufsize = sizeof bufprefix - 1 + tzname_len + sizeof bufsuffix }; char buf[bufsize]; memcpy (buf, bufprefix, sizeof bufprefix - 1); memset (buf + sizeof bufprefix - 1, 'X', tzname_len); strcpy (buf + bufsize - sizeof bufsuffix, bufsuffix); ASSERT (parse_datetime (&result, buf, &now)); LOG (buf, now, result); ASSERT (result.tv_sec == 1 * 60 * 60 + 2 * 60 + 3 && result.tv_nsec == 123456789); } return 0; }
254,772,284,669,524,430,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2017-7476
Gnulib before 2017-04-26 has a heap-based buffer overflow with the TZ environment variable. The error is in the save_abbr function in time_rz.c.
https://nvd.nist.gov/vuln/detail/CVE-2017-7476
217
savannah
59eb9f8cfe7d1df379a2318316d1f04f80fba54a
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=59eb9f8cfe7d1df379a2318316d1f04f80fba54a
None
1
ft_var_readpackedpoints( FT_Stream stream, FT_UInt *point_cnt ) { FT_UShort *points; FT_Int n; FT_Int runcnt; FT_Int i; FT_Int j; FT_Int first; FT_Memory memory = stream->memory; FT_Error error = TT_Err_Ok; FT_UNUSED( error ); *point_cnt = n = FT_GET_BYTE(); if ( n == 0 ) return ALL_POINTS; if ( n & GX_PT_POINTS_ARE_WORDS ) n = FT_GET_BYTE() | ( ( n & GX_PT_POINT_RUN_COUNT_MASK ) << 8 ); if ( FT_NEW_ARRAY( points, n ) ) return NULL; i = 0; while ( i < n ) { runcnt = FT_GET_BYTE(); if ( runcnt & GX_PT_POINTS_ARE_WORDS ) { runcnt = runcnt & GX_PT_POINT_RUN_COUNT_MASK; first = points[i++] = FT_GET_USHORT(); if ( runcnt < 1 ) goto Exit; /* first point not included in runcount */ for ( j = 0; j < runcnt; ++j ) points[i++] = (FT_UShort)( first += FT_GET_USHORT() ); } else { first = points[i++] = FT_GET_BYTE(); if ( runcnt < 1 ) goto Exit; for ( j = 0; j < runcnt; ++j ) points[i++] = (FT_UShort)( first += FT_GET_BYTE() ); } } Exit: return points; }
176,444,419,672,545,500,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2010-3855
Buffer overflow in the ft_var_readpackedpoints function in truetype/ttgxvar.c in FreeType 2.4.3 and earlier allows remote attackers to cause a denial of service (application crash) or possibly execute arbitrary code via a crafted TrueType GX font.
https://nvd.nist.gov/vuln/detail/CVE-2010-3855
158,077
savannah
59eb9f8cfe7d1df379a2318316d1f04f80fba54a
https://git.savannah.gnu.org/gitweb/?p=gnutls
https://git.savannah.gnu.org/cgit/freetype/freetype2.git/commit/?id=59eb9f8cfe7d1df379a2318316d1f04f80fba54a
None
0
ft_var_readpackedpoints( FT_Stream stream, FT_UInt *point_cnt ) { FT_UShort *points; FT_Int n; FT_Int runcnt; FT_Int i; FT_Int j; FT_Int first; FT_Memory memory = stream->memory; FT_Error error = TT_Err_Ok; FT_UNUSED( error ); *point_cnt = n = FT_GET_BYTE(); if ( n == 0 ) return ALL_POINTS; if ( n & GX_PT_POINTS_ARE_WORDS ) n = FT_GET_BYTE() | ( ( n & GX_PT_POINT_RUN_COUNT_MASK ) << 8 ); if ( FT_NEW_ARRAY( points, n ) ) return NULL; i = 0; while ( i < n ) { runcnt = FT_GET_BYTE(); if ( runcnt & GX_PT_POINTS_ARE_WORDS ) { runcnt = runcnt & GX_PT_POINT_RUN_COUNT_MASK; first = points[i++] = FT_GET_USHORT(); if ( runcnt < 1 || i + runcnt >= n ) goto Exit; /* first point not included in runcount */ for ( j = 0; j < runcnt; ++j ) points[i++] = (FT_UShort)( first += FT_GET_USHORT() ); } else { first = points[i++] = FT_GET_BYTE(); if ( runcnt < 1 || i + runcnt >= n ) goto Exit; for ( j = 0; j < runcnt; ++j ) points[i++] = (FT_UShort)( first += FT_GET_BYTE() ); } } Exit: return points; }
179,208,058,990,458,740,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2010-3855
Buffer overflow in the ft_var_readpackedpoints function in truetype/ttgxvar.c in FreeType 2.4.3 and earlier allows remote attackers to cause a denial of service (application crash) or possibly execute arbitrary code via a crafted TrueType GX font.
https://nvd.nist.gov/vuln/detail/CVE-2010-3855
218
ghostscript
39b1e54b2968620723bf32e96764c88797714879
http://git.ghostscript.com/?p=mupdf
http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=39b1e54b2968620723bf32e96764c88797714879
None
1
set_text_distance(gs_point *pdist, double dx, double dy, const gs_matrix *pmat) { int code = gs_distance_transform_inverse(dx, dy, pmat, pdist); double rounded; if (code == gs_error_undefinedresult) { /* The CTM is degenerate. Can't know the distance in user space. } else if (code < 0) return code; /* If the distance is very close to integers, round it. */ if (fabs(pdist->x - (rounded = floor(pdist->x + 0.5))) < 0.0005) pdist->x = rounded; if (fabs(pdist->y - (rounded = floor(pdist->y + 0.5))) < 0.0005) pdist->y = rounded; return 0; }
334,604,983,653,907,630,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2018-10194
The set_text_distance function in devices/vector/gdevpdts.c in the pdfwrite component in Artifex Ghostscript through 9.22 does not prevent overflows in text-positioning calculation, which allows remote attackers to cause a denial of service (application crash) or possibly have unspecified other impact via a crafted PDF document.
https://nvd.nist.gov/vuln/detail/CVE-2018-10194
158,078
ghostscript
39b1e54b2968620723bf32e96764c88797714879
http://git.ghostscript.com/?p=mupdf
http://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=39b1e54b2968620723bf32e96764c88797714879
None
0
set_text_distance(gs_point *pdist, double dx, double dy, const gs_matrix *pmat) { int code; double rounded; if (dx > 1e38 || dy > 1e38) code = gs_error_undefinedresult; else code = gs_distance_transform_inverse(dx, dy, pmat, pdist); if (code == gs_error_undefinedresult) { /* The CTM is degenerate. Can't know the distance in user space. } else if (code < 0) return code; /* If the distance is very close to integers, round it. */ if (fabs(pdist->x - (rounded = floor(pdist->x + 0.5))) < 0.0005) pdist->x = rounded; if (fabs(pdist->y - (rounded = floor(pdist->y + 0.5))) < 0.0005) pdist->y = rounded; return 0; }
59,940,488,774,012,010,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2018-10194
The set_text_distance function in devices/vector/gdevpdts.c in the pdfwrite component in Artifex Ghostscript through 9.22 does not prevent overflows in text-positioning calculation, which allows remote attackers to cause a denial of service (application crash) or possibly have unspecified other impact via a crafted PDF document.
https://nvd.nist.gov/vuln/detail/CVE-2018-10194
219
haproxy
3f0e1ec70173593f4c2b3681b26c04a4ed5fc588
https://github.com/haproxy/haproxy
http://git.haproxy.org/?p=haproxy.git;a=commitdiff;h=3f0e1ec70173593f4c2b3681b26c04a4ed5fc588
BUG/CRITICAL: h2: fix incorrect frame length check The incoming H2 frame length was checked against the max_frame_size setting instead of being checked against the bufsize. The max_frame_size only applies to outgoing traffic and not to incoming one, so if a large enough frame size is advertised in the SETTINGS frame, a wrapped frame will be defragmented into a temporary allocated buffer where the second fragment my overflow the heap by up to 16 kB. It is very unlikely that this can be exploited for code execution given that buffers are very short lived and their address not realistically predictable in production, but the likeliness of an immediate crash is absolutely certain. This fix must be backported to 1.8. Many thanks to Jordan Zebor from F5 Networks for reporting this issue in a responsible way.
1
static void h2_process_demux(struct h2c *h2c) { struct h2s *h2s; if (h2c->st0 >= H2_CS_ERROR) return; if (unlikely(h2c->st0 < H2_CS_FRAME_H)) { if (h2c->st0 == H2_CS_PREFACE) { if (unlikely(h2c_frt_recv_preface(h2c) <= 0)) { /* RFC7540#3.5: a GOAWAY frame MAY be omitted */ if (h2c->st0 == H2_CS_ERROR) h2c->st0 = H2_CS_ERROR2; goto fail; } h2c->max_id = 0; h2c->st0 = H2_CS_SETTINGS1; } if (h2c->st0 == H2_CS_SETTINGS1) { struct h2_fh hdr; /* ensure that what is pending is a valid SETTINGS frame * without an ACK. */ if (!h2_get_frame_hdr(h2c->dbuf, &hdr)) { /* RFC7540#3.5: a GOAWAY frame MAY be omitted */ if (h2c->st0 == H2_CS_ERROR) h2c->st0 = H2_CS_ERROR2; goto fail; } if (hdr.sid || hdr.ft != H2_FT_SETTINGS || hdr.ff & H2_F_SETTINGS_ACK) { /* RFC7540#3.5: a GOAWAY frame MAY be omitted */ h2c_error(h2c, H2_ERR_PROTOCOL_ERROR); h2c->st0 = H2_CS_ERROR2; goto fail; } if ((int)hdr.len < 0 || (int)hdr.len > h2c->mfs) { /* RFC7540#3.5: a GOAWAY frame MAY be omitted */ h2c_error(h2c, H2_ERR_FRAME_SIZE_ERROR); h2c->st0 = H2_CS_ERROR2; goto fail; } /* that's OK, switch to FRAME_P to process it */ h2c->dfl = hdr.len; h2c->dsi = hdr.sid; h2c->dft = hdr.ft; h2c->dff = hdr.ff; h2c->dpl = 0; h2c->st0 = H2_CS_FRAME_P; } } /* process as many incoming frames as possible below */ while (h2c->dbuf->i) { int ret = 0; if (h2c->st0 >= H2_CS_ERROR) break; if (h2c->st0 == H2_CS_FRAME_H) { struct h2_fh hdr; if (!h2_peek_frame_hdr(h2c->dbuf, &hdr)) break; if ((int)hdr.len < 0 || (int)hdr.len > h2c->mfs) { h2c_error(h2c, H2_ERR_FRAME_SIZE_ERROR); h2c->st0 = H2_CS_ERROR; break; } h2c->dfl = hdr.len; h2c->dsi = hdr.sid; h2c->dft = hdr.ft; h2c->dff = hdr.ff; h2c->dpl = 0; h2c->st0 = H2_CS_FRAME_P; h2_skip_frame_hdr(h2c->dbuf); } /* Only H2_CS_FRAME_P and H2_CS_FRAME_A here */ h2s = h2c_st_by_id(h2c, h2c->dsi); if (h2c->st0 == H2_CS_FRAME_E) goto strm_err; if (h2s->st == H2_SS_IDLE && h2c->dft != H2_FT_HEADERS && h2c->dft != H2_FT_PRIORITY) { /* RFC7540#5.1: any frame other than HEADERS or PRIORITY in * this state MUST be treated as a connection error */ h2c_error(h2c, H2_ERR_PROTOCOL_ERROR); h2c->st0 = H2_CS_ERROR; break; } if (h2s->st == H2_SS_HREM && h2c->dft != H2_FT_WINDOW_UPDATE && h2c->dft != H2_FT_RST_STREAM && h2c->dft != H2_FT_PRIORITY) { /* RFC7540#5.1: any frame other than WU/PRIO/RST in * this state MUST be treated as a stream error */ h2s_error(h2s, H2_ERR_STREAM_CLOSED); h2c->st0 = H2_CS_FRAME_E; goto strm_err; } /* Below the management of frames received in closed state is a * bit hackish because the spec makes strong differences between * streams closed by receiving RST, sending RST, and seeing ES * in both directions. In addition to this, the creation of a * new stream reusing the identifier of a closed one will be * detected here. Given that we cannot keep track of all closed * streams forever, we consider that unknown closed streams were * closed on RST received, which allows us to respond with an * RST without breaking the connection (eg: to abort a transfer). * Some frames have to be silently ignored as well. */ if (h2s->st == H2_SS_CLOSED && h2c->dsi) { if (h2c->dft == H2_FT_HEADERS || h2c->dft == H2_FT_PUSH_PROMISE) { /* #5.1.1: The identifier of a newly * established stream MUST be numerically * greater than all streams that the initiating * endpoint has opened or reserved. This * governs streams that are opened using a * HEADERS frame and streams that are reserved * using PUSH_PROMISE. An endpoint that * receives an unexpected stream identifier * MUST respond with a connection error. */ h2c_error(h2c, H2_ERR_STREAM_CLOSED); goto strm_err; } if (h2s->flags & H2_SF_RST_RCVD) { /* RFC7540#5.1:closed: an endpoint that * receives any frame other than PRIORITY after * receiving a RST_STREAM MUST treat that as a * stream error of type STREAM_CLOSED. * * Note that old streams fall into this category * and will lead to an RST being sent. */ h2s_error(h2s, H2_ERR_STREAM_CLOSED); h2c->st0 = H2_CS_FRAME_E; goto strm_err; } /* RFC7540#5.1:closed: if this state is reached as a * result of sending a RST_STREAM frame, the peer that * receives the RST_STREAM might have already sent * frames on the stream that cannot be withdrawn. An * endpoint MUST ignore frames that it receives on * closed streams after it has sent a RST_STREAM * frame. An endpoint MAY choose to limit the period * over which it ignores frames and treat frames that * arrive after this time as being in error. */ if (!(h2s->flags & H2_SF_RST_SENT)) { /* RFC7540#5.1:closed: any frame other than * PRIO/WU/RST in this state MUST be treated as * a connection error */ if (h2c->dft != H2_FT_RST_STREAM && h2c->dft != H2_FT_PRIORITY && h2c->dft != H2_FT_WINDOW_UPDATE) { h2c_error(h2c, H2_ERR_STREAM_CLOSED); goto strm_err; } } } #if 0 /* graceful shutdown, ignore streams whose ID is higher than * the one advertised in GOAWAY. RFC7540#6.8. */ if (unlikely(h2c->last_sid >= 0) && h2c->dsi > h2c->last_sid) { ret = MIN(h2c->dbuf->i, h2c->dfl); bi_del(h2c->dbuf, ret); h2c->dfl -= ret; ret = h2c->dfl == 0; goto strm_err; } #endif switch (h2c->dft) { case H2_FT_SETTINGS: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_settings(h2c); if (h2c->st0 == H2_CS_FRAME_A) ret = h2c_ack_settings(h2c); break; case H2_FT_PING: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_ping(h2c); if (h2c->st0 == H2_CS_FRAME_A) ret = h2c_ack_ping(h2c); break; case H2_FT_WINDOW_UPDATE: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_window_update(h2c, h2s); break; case H2_FT_CONTINUATION: /* we currently don't support CONTINUATION frames since * we have nowhere to store the partial HEADERS frame. * Let's abort the stream on an INTERNAL_ERROR here. */ if (h2c->st0 == H2_CS_FRAME_P) { h2s_error(h2s, H2_ERR_INTERNAL_ERROR); h2c->st0 = H2_CS_FRAME_E; } break; case H2_FT_HEADERS: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_frt_handle_headers(h2c, h2s); break; case H2_FT_DATA: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_frt_handle_data(h2c, h2s); if (h2c->st0 == H2_CS_FRAME_A) ret = h2c_send_strm_wu(h2c); break; case H2_FT_PRIORITY: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_priority(h2c); break; case H2_FT_RST_STREAM: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_rst_stream(h2c, h2s); break; case H2_FT_GOAWAY: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_goaway(h2c); break; case H2_FT_PUSH_PROMISE: /* not permitted here, RFC7540#5.1 */ h2c_error(h2c, H2_ERR_PROTOCOL_ERROR); break; /* implement all extra frame types here */ default: /* drop frames that we ignore. They may be larger than * the buffer so we drain all of their contents until * we reach the end. */ ret = MIN(h2c->dbuf->i, h2c->dfl); bi_del(h2c->dbuf, ret); h2c->dfl -= ret; ret = h2c->dfl == 0; } strm_err: /* We may have to send an RST if not done yet */ if (h2s->st == H2_SS_ERROR) h2c->st0 = H2_CS_FRAME_E; if (h2c->st0 == H2_CS_FRAME_E) ret = h2c_send_rst_stream(h2c, h2s); /* error or missing data condition met above ? */ if (ret <= 0) break; if (h2c->st0 != H2_CS_FRAME_H) { bi_del(h2c->dbuf, h2c->dfl); h2c->st0 = H2_CS_FRAME_H; } } if (h2c->rcvd_c > 0 && !(h2c->flags & (H2_CF_MUX_MFULL | H2_CF_DEM_MBUSY | H2_CF_DEM_MROOM))) h2c_send_conn_wu(h2c); fail: /* we can go here on missing data, blocked response or error */ return; }
197,791,135,802,871,480,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2018-10184
An issue was discovered in HAProxy before 1.8.8. The incoming H2 frame length was checked against the max_frame_size setting instead of being checked against the bufsize. The max_frame_size only applies to outgoing traffic and not to incoming, so if a large enough frame size is advertised in the SETTINGS frame, a wrapped frame will be defragmented into a temporary allocated buffer where the second fragment may overflow the heap by up to 16 kB. It is very unlikely that this can be exploited for code execution given that buffers are very short lived and their addresses not realistically predictable in production, but the likelihood of an immediate crash is absolutely certain.
https://nvd.nist.gov/vuln/detail/CVE-2018-10184
158,079
haproxy
3f0e1ec70173593f4c2b3681b26c04a4ed5fc588
https://github.com/haproxy/haproxy
http://git.haproxy.org/?p=haproxy.git;a=commitdiff;h=3f0e1ec70173593f4c2b3681b26c04a4ed5fc588
BUG/CRITICAL: h2: fix incorrect frame length check The incoming H2 frame length was checked against the max_frame_size setting instead of being checked against the bufsize. The max_frame_size only applies to outgoing traffic and not to incoming one, so if a large enough frame size is advertised in the SETTINGS frame, a wrapped frame will be defragmented into a temporary allocated buffer where the second fragment my overflow the heap by up to 16 kB. It is very unlikely that this can be exploited for code execution given that buffers are very short lived and their address not realistically predictable in production, but the likeliness of an immediate crash is absolutely certain. This fix must be backported to 1.8. Many thanks to Jordan Zebor from F5 Networks for reporting this issue in a responsible way.
0
static void h2_process_demux(struct h2c *h2c) { struct h2s *h2s; if (h2c->st0 >= H2_CS_ERROR) return; if (unlikely(h2c->st0 < H2_CS_FRAME_H)) { if (h2c->st0 == H2_CS_PREFACE) { if (unlikely(h2c_frt_recv_preface(h2c) <= 0)) { /* RFC7540#3.5: a GOAWAY frame MAY be omitted */ if (h2c->st0 == H2_CS_ERROR) h2c->st0 = H2_CS_ERROR2; goto fail; } h2c->max_id = 0; h2c->st0 = H2_CS_SETTINGS1; } if (h2c->st0 == H2_CS_SETTINGS1) { struct h2_fh hdr; /* ensure that what is pending is a valid SETTINGS frame * without an ACK. */ if (!h2_get_frame_hdr(h2c->dbuf, &hdr)) { /* RFC7540#3.5: a GOAWAY frame MAY be omitted */ if (h2c->st0 == H2_CS_ERROR) h2c->st0 = H2_CS_ERROR2; goto fail; } if (hdr.sid || hdr.ft != H2_FT_SETTINGS || hdr.ff & H2_F_SETTINGS_ACK) { /* RFC7540#3.5: a GOAWAY frame MAY be omitted */ h2c_error(h2c, H2_ERR_PROTOCOL_ERROR); h2c->st0 = H2_CS_ERROR2; goto fail; } if ((int)hdr.len < 0 || (int)hdr.len > global.tune.bufsize) { /* RFC7540#3.5: a GOAWAY frame MAY be omitted */ h2c_error(h2c, H2_ERR_FRAME_SIZE_ERROR); h2c->st0 = H2_CS_ERROR2; goto fail; } /* that's OK, switch to FRAME_P to process it */ h2c->dfl = hdr.len; h2c->dsi = hdr.sid; h2c->dft = hdr.ft; h2c->dff = hdr.ff; h2c->dpl = 0; h2c->st0 = H2_CS_FRAME_P; } } /* process as many incoming frames as possible below */ while (h2c->dbuf->i) { int ret = 0; if (h2c->st0 >= H2_CS_ERROR) break; if (h2c->st0 == H2_CS_FRAME_H) { struct h2_fh hdr; if (!h2_peek_frame_hdr(h2c->dbuf, &hdr)) break; if ((int)hdr.len < 0 || (int)hdr.len > global.tune.bufsize) { h2c_error(h2c, H2_ERR_FRAME_SIZE_ERROR); h2c->st0 = H2_CS_ERROR; break; } h2c->dfl = hdr.len; h2c->dsi = hdr.sid; h2c->dft = hdr.ft; h2c->dff = hdr.ff; h2c->dpl = 0; h2c->st0 = H2_CS_FRAME_P; h2_skip_frame_hdr(h2c->dbuf); } /* Only H2_CS_FRAME_P and H2_CS_FRAME_A here */ h2s = h2c_st_by_id(h2c, h2c->dsi); if (h2c->st0 == H2_CS_FRAME_E) goto strm_err; if (h2s->st == H2_SS_IDLE && h2c->dft != H2_FT_HEADERS && h2c->dft != H2_FT_PRIORITY) { /* RFC7540#5.1: any frame other than HEADERS or PRIORITY in * this state MUST be treated as a connection error */ h2c_error(h2c, H2_ERR_PROTOCOL_ERROR); h2c->st0 = H2_CS_ERROR; break; } if (h2s->st == H2_SS_HREM && h2c->dft != H2_FT_WINDOW_UPDATE && h2c->dft != H2_FT_RST_STREAM && h2c->dft != H2_FT_PRIORITY) { /* RFC7540#5.1: any frame other than WU/PRIO/RST in * this state MUST be treated as a stream error */ h2s_error(h2s, H2_ERR_STREAM_CLOSED); h2c->st0 = H2_CS_FRAME_E; goto strm_err; } /* Below the management of frames received in closed state is a * bit hackish because the spec makes strong differences between * streams closed by receiving RST, sending RST, and seeing ES * in both directions. In addition to this, the creation of a * new stream reusing the identifier of a closed one will be * detected here. Given that we cannot keep track of all closed * streams forever, we consider that unknown closed streams were * closed on RST received, which allows us to respond with an * RST without breaking the connection (eg: to abort a transfer). * Some frames have to be silently ignored as well. */ if (h2s->st == H2_SS_CLOSED && h2c->dsi) { if (h2c->dft == H2_FT_HEADERS || h2c->dft == H2_FT_PUSH_PROMISE) { /* #5.1.1: The identifier of a newly * established stream MUST be numerically * greater than all streams that the initiating * endpoint has opened or reserved. This * governs streams that are opened using a * HEADERS frame and streams that are reserved * using PUSH_PROMISE. An endpoint that * receives an unexpected stream identifier * MUST respond with a connection error. */ h2c_error(h2c, H2_ERR_STREAM_CLOSED); goto strm_err; } if (h2s->flags & H2_SF_RST_RCVD) { /* RFC7540#5.1:closed: an endpoint that * receives any frame other than PRIORITY after * receiving a RST_STREAM MUST treat that as a * stream error of type STREAM_CLOSED. * * Note that old streams fall into this category * and will lead to an RST being sent. */ h2s_error(h2s, H2_ERR_STREAM_CLOSED); h2c->st0 = H2_CS_FRAME_E; goto strm_err; } /* RFC7540#5.1:closed: if this state is reached as a * result of sending a RST_STREAM frame, the peer that * receives the RST_STREAM might have already sent * frames on the stream that cannot be withdrawn. An * endpoint MUST ignore frames that it receives on * closed streams after it has sent a RST_STREAM * frame. An endpoint MAY choose to limit the period * over which it ignores frames and treat frames that * arrive after this time as being in error. */ if (!(h2s->flags & H2_SF_RST_SENT)) { /* RFC7540#5.1:closed: any frame other than * PRIO/WU/RST in this state MUST be treated as * a connection error */ if (h2c->dft != H2_FT_RST_STREAM && h2c->dft != H2_FT_PRIORITY && h2c->dft != H2_FT_WINDOW_UPDATE) { h2c_error(h2c, H2_ERR_STREAM_CLOSED); goto strm_err; } } } #if 0 /* graceful shutdown, ignore streams whose ID is higher than * the one advertised in GOAWAY. RFC7540#6.8. */ if (unlikely(h2c->last_sid >= 0) && h2c->dsi > h2c->last_sid) { ret = MIN(h2c->dbuf->i, h2c->dfl); bi_del(h2c->dbuf, ret); h2c->dfl -= ret; ret = h2c->dfl == 0; goto strm_err; } #endif switch (h2c->dft) { case H2_FT_SETTINGS: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_settings(h2c); if (h2c->st0 == H2_CS_FRAME_A) ret = h2c_ack_settings(h2c); break; case H2_FT_PING: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_ping(h2c); if (h2c->st0 == H2_CS_FRAME_A) ret = h2c_ack_ping(h2c); break; case H2_FT_WINDOW_UPDATE: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_window_update(h2c, h2s); break; case H2_FT_CONTINUATION: /* we currently don't support CONTINUATION frames since * we have nowhere to store the partial HEADERS frame. * Let's abort the stream on an INTERNAL_ERROR here. */ if (h2c->st0 == H2_CS_FRAME_P) { h2s_error(h2s, H2_ERR_INTERNAL_ERROR); h2c->st0 = H2_CS_FRAME_E; } break; case H2_FT_HEADERS: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_frt_handle_headers(h2c, h2s); break; case H2_FT_DATA: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_frt_handle_data(h2c, h2s); if (h2c->st0 == H2_CS_FRAME_A) ret = h2c_send_strm_wu(h2c); break; case H2_FT_PRIORITY: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_priority(h2c); break; case H2_FT_RST_STREAM: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_rst_stream(h2c, h2s); break; case H2_FT_GOAWAY: if (h2c->st0 == H2_CS_FRAME_P) ret = h2c_handle_goaway(h2c); break; case H2_FT_PUSH_PROMISE: /* not permitted here, RFC7540#5.1 */ h2c_error(h2c, H2_ERR_PROTOCOL_ERROR); break; /* implement all extra frame types here */ default: /* drop frames that we ignore. They may be larger than * the buffer so we drain all of their contents until * we reach the end. */ ret = MIN(h2c->dbuf->i, h2c->dfl); bi_del(h2c->dbuf, ret); h2c->dfl -= ret; ret = h2c->dfl == 0; } strm_err: /* We may have to send an RST if not done yet */ if (h2s->st == H2_SS_ERROR) h2c->st0 = H2_CS_FRAME_E; if (h2c->st0 == H2_CS_FRAME_E) ret = h2c_send_rst_stream(h2c, h2s); /* error or missing data condition met above ? */ if (ret <= 0) break; if (h2c->st0 != H2_CS_FRAME_H) { bi_del(h2c->dbuf, h2c->dfl); h2c->st0 = H2_CS_FRAME_H; } } if (h2c->rcvd_c > 0 && !(h2c->flags & (H2_CF_MUX_MFULL | H2_CF_DEM_MBUSY | H2_CF_DEM_MROOM))) h2c_send_conn_wu(h2c); fail: /* we can go here on missing data, blocked response or error */ return; }
78,211,051,505,197,320,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2018-10184
An issue was discovered in HAProxy before 1.8.8. The incoming H2 frame length was checked against the max_frame_size setting instead of being checked against the bufsize. The max_frame_size only applies to outgoing traffic and not to incoming, so if a large enough frame size is advertised in the SETTINGS frame, a wrapped frame will be defragmented into a temporary allocated buffer where the second fragment may overflow the heap by up to 16 kB. It is very unlikely that this can be exploited for code execution given that buffers are very short lived and their addresses not realistically predictable in production, but the likelihood of an immediate crash is absolutely certain.
https://nvd.nist.gov/vuln/detail/CVE-2018-10184
223
libXvMC
2cd95e7da8367cccdcdd5c9b160012d1dec5cbdb
https://cgit.freedesktop.org/xorg/lib/libXvMC/commit/?id=2cd95e7da8367cccdcdd5c9b160012d1dec5cbdb
https://cgit.freedesktop.org/xorg/lib/libXvMC/commit/?id=2cd95e7da8367cccdcdd5c9b160012d1dec5cbdb
None
1
Status XvMCGetDRInfo(Display *dpy, XvPortID port, char **name, char **busID, int *major, int *minor, int *patchLevel, int *isLocal) { XExtDisplayInfo *info = xvmc_find_display(dpy); xvmcGetDRInfoReply rep; xvmcGetDRInfoReq *req; CARD32 magic; #ifdef HAVE_SHMAT volatile CARD32 *shMem; struct timezone here; struct timeval now; here.tz_minuteswest = 0; here.tz_dsttime = 0; #endif *name = NULL; *busID = NULL; XvMCCheckExtension (dpy, info, BadImplementation); LockDisplay (dpy); XvMCGetReq (GetDRInfo, req); req->port = port; magic = 0; req->magic = 0; #ifdef HAVE_SHMAT req->shmKey = shmget(IPC_PRIVATE, 1024, IPC_CREAT | 0600); /* * We fill a shared memory page with a repetitive pattern. If the * X server can read this pattern, we probably have a local connection. * Note that we can trigger the remote X server to read any shared * page on the remote machine, so we shouldn't be able to guess and verify * any complicated data on those pages. Thats the explanation of this * otherwise stupid-looking pattern algorithm. */ if (req->shmKey >= 0) { shMem = (CARD32 *) shmat(req->shmKey, NULL, 0); shmctl( req->shmKey, IPC_RMID, NULL); if ( shMem ) { register volatile CARD32 *shMemC = shMem; register int i; gettimeofday( &now, &here); magic = now.tv_usec & 0x000FFFFF; req->magic = magic; i = 1024 / sizeof(CARD32); while(i--) { *shMemC++ = magic; magic = ~magic; } } else { req->shmKey = -1; } } #else req->shmKey = 0; #endif if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) { UnlockDisplay (dpy); SyncHandle (); #ifdef HAVE_SHMAT if ( req->shmKey >= 0) { shmdt( (const void *) shMem ); } #endif return -1; } #ifdef HAVE_SHMAT shmdt( (const void *) shMem ); #endif if (rep.length > 0) { unsigned long realSize = 0; char *tmpBuf = NULL; if ((rep.length < (INT_MAX >> 2)) && /* protect against overflow in strncpy below */ (rep.nameLen + rep.busIDLen > rep.nameLen)) { realSize = rep.length << 2; if (realSize >= (rep.nameLen + rep.busIDLen)) { tmpBuf = Xmalloc(realSize); *name = Xmalloc(rep.nameLen); *busID = Xmalloc(rep.busIDLen); } } if (*name && *busID && tmpBuf) { _XRead(dpy, tmpBuf, realSize); strncpy(*name,tmpBuf,rep.nameLen); (*name)[rep.nameLen - 1] = '\0'; strncpy(*busID,tmpBuf+rep.nameLen,rep.busIDLen); (*busID)[rep.busIDLen - 1] = '\0'; XFree(tmpBuf); } else { XFree(*name); *name = NULL; XFree(*busID); *busID = NULL; XFree(tmpBuf); _XEatDataWords(dpy, rep.length); UnlockDisplay (dpy); SyncHandle (); return -1; } } UnlockDisplay (dpy); SyncHandle (); *major = rep.major; *minor = rep.minor; *patchLevel = rep.patchLevel; *isLocal = (req->shmKey > 0) ? rep.isLocal : 1; return (rep.length > 0) ? Success : BadImplementation; }
225,773,238,597,817,000,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2016-7953
Buffer underflow in X.org libXvMC before 1.0.10 allows remote X servers to have unspecified impact via an empty string.
https://nvd.nist.gov/vuln/detail/CVE-2016-7953
158,083
libXvMC
2cd95e7da8367cccdcdd5c9b160012d1dec5cbdb
https://cgit.freedesktop.org/xorg/lib/libXvMC/commit/?id=2cd95e7da8367cccdcdd5c9b160012d1dec5cbdb
https://cgit.freedesktop.org/xorg/lib/libXvMC/commit/?id=2cd95e7da8367cccdcdd5c9b160012d1dec5cbdb
None
0
Status XvMCGetDRInfo(Display *dpy, XvPortID port, char **name, char **busID, int *major, int *minor, int *patchLevel, int *isLocal) { XExtDisplayInfo *info = xvmc_find_display(dpy); xvmcGetDRInfoReply rep; xvmcGetDRInfoReq *req; CARD32 magic; #ifdef HAVE_SHMAT volatile CARD32 *shMem; struct timezone here; struct timeval now; here.tz_minuteswest = 0; here.tz_dsttime = 0; #endif *name = NULL; *busID = NULL; XvMCCheckExtension (dpy, info, BadImplementation); LockDisplay (dpy); XvMCGetReq (GetDRInfo, req); req->port = port; magic = 0; req->magic = 0; #ifdef HAVE_SHMAT req->shmKey = shmget(IPC_PRIVATE, 1024, IPC_CREAT | 0600); /* * We fill a shared memory page with a repetitive pattern. If the * X server can read this pattern, we probably have a local connection. * Note that we can trigger the remote X server to read any shared * page on the remote machine, so we shouldn't be able to guess and verify * any complicated data on those pages. Thats the explanation of this * otherwise stupid-looking pattern algorithm. */ if (req->shmKey >= 0) { shMem = (CARD32 *) shmat(req->shmKey, NULL, 0); shmctl( req->shmKey, IPC_RMID, NULL); if ( shMem ) { register volatile CARD32 *shMemC = shMem; register int i; gettimeofday( &now, &here); magic = now.tv_usec & 0x000FFFFF; req->magic = magic; i = 1024 / sizeof(CARD32); while(i--) { *shMemC++ = magic; magic = ~magic; } } else { req->shmKey = -1; } } #else req->shmKey = 0; #endif if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) { UnlockDisplay (dpy); SyncHandle (); #ifdef HAVE_SHMAT if ( req->shmKey >= 0) { shmdt( (const void *) shMem ); } #endif return -1; } #ifdef HAVE_SHMAT shmdt( (const void *) shMem ); #endif if (rep.length > 0) { unsigned long realSize = 0; char *tmpBuf = NULL; if ((rep.length < (INT_MAX >> 2)) && /* protect against overflow in strncpy below */ (rep.nameLen + rep.busIDLen > rep.nameLen)) { realSize = rep.length << 2; if (realSize >= (rep.nameLen + rep.busIDLen)) { tmpBuf = Xmalloc(realSize); *name = Xmalloc(rep.nameLen); *busID = Xmalloc(rep.busIDLen); } } if (*name && *busID && tmpBuf) { _XRead(dpy, tmpBuf, realSize); strncpy(*name,tmpBuf,rep.nameLen); (*name)[rep.nameLen == 0 ? 0 : rep.nameLen - 1] = '\0'; strncpy(*busID,tmpBuf+rep.nameLen,rep.busIDLen); (*busID)[rep.busIDLen == 0 ? 0 : rep.busIDLen - 1] = '\0'; XFree(tmpBuf); } else { XFree(*name); *name = NULL; XFree(*busID); *busID = NULL; XFree(tmpBuf); _XEatDataWords(dpy, rep.length); UnlockDisplay (dpy); SyncHandle (); return -1; } } UnlockDisplay (dpy); SyncHandle (); *major = rep.major; *minor = rep.minor; *patchLevel = rep.patchLevel; *isLocal = (req->shmKey > 0) ? rep.isLocal : 1; return (rep.length > 0) ? Success : BadImplementation; }
134,961,230,573,839,860,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2016-7953
Buffer underflow in X.org libXvMC before 1.0.10 allows remote X servers to have unspecified impact via an empty string.
https://nvd.nist.gov/vuln/detail/CVE-2016-7953
231
libXfixes
61c1039ee23a2d1de712843bed3480654d7ef42e
https://cgit.freedesktop.org/xorg/lib/libXfixes/commit/?id=61c1039ee23a2d1de712843bed3480654d7ef42e
https://cgit.freedesktop.org/xorg/lib/libXfixes/commit/?id=61c1039ee23a2d1de712843bed3480654d7ef42e
None
1
XFixesFetchRegionAndBounds (Display *dpy, XserverRegion region, int *nrectanglesRet, XRectangle *bounds) { XFixesExtDisplayInfo *info = XFixesFindDisplay (dpy); xXFixesFetchRegionReq *req; xXFixesFetchRegionReply rep; XRectangle *rects; int nrects; long nbytes; long nread; XFixesCheckExtension (dpy, info, NULL); LockDisplay (dpy); GetReq (XFixesFetchRegion, req); req->reqType = info->codes->major_opcode; req->xfixesReqType = X_XFixesFetchRegion; req->region = region; *nrectanglesRet = 0; if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) { UnlockDisplay (dpy); SyncHandle (); return NULL; } bounds->x = rep.x; bounds->y = rep.y; bounds->y = rep.y; bounds->width = rep.width; bounds->height = rep.height; nbytes = (long) rep.length << 2; nrects = rep.length >> 1; rects = Xmalloc (nrects * sizeof (XRectangle)); if (!rects) { _XEatDataWords(dpy, rep.length); _XEatData (dpy, (unsigned long) (nbytes - nread)); } UnlockDisplay (dpy); SyncHandle(); *nrectanglesRet = nrects; return rects; }
306,933,036,253,550,500,000,000,000,000,000,000,000
None
null
[ "CWE-190" ]
CVE-2016-7944
Integer overflow in X.org libXfixes before 5.0.3 on 32-bit platforms might allow remote X servers to gain privileges via a length value of INT_MAX, which triggers the client to stop reading data and get out of sync.
https://nvd.nist.gov/vuln/detail/CVE-2016-7944
158,091
libXfixes
61c1039ee23a2d1de712843bed3480654d7ef42e
https://cgit.freedesktop.org/xorg/lib/libXfixes/commit/?id=61c1039ee23a2d1de712843bed3480654d7ef42e
https://cgit.freedesktop.org/xorg/lib/libXfixes/commit/?id=61c1039ee23a2d1de712843bed3480654d7ef42e
None
0
XFixesFetchRegionAndBounds (Display *dpy, XserverRegion region, int *nrectanglesRet, XRectangle *bounds) { XFixesExtDisplayInfo *info = XFixesFindDisplay (dpy); xXFixesFetchRegionReq *req; xXFixesFetchRegionReply rep; XRectangle *rects; int nrects; long nbytes; long nread; XFixesCheckExtension (dpy, info, NULL); LockDisplay (dpy); GetReq (XFixesFetchRegion, req); req->reqType = info->codes->major_opcode; req->xfixesReqType = X_XFixesFetchRegion; req->region = region; *nrectanglesRet = 0; if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) { UnlockDisplay (dpy); SyncHandle (); return NULL; } bounds->x = rep.x; bounds->y = rep.y; bounds->y = rep.y; bounds->width = rep.width; bounds->height = rep.height; if (rep.length < (INT_MAX >> 2)) { nbytes = (long) rep.length << 2; nrects = rep.length >> 1; rects = Xmalloc (nrects * sizeof (XRectangle)); } else { nbytes = 0; nrects = 0; rects = NULL; } if (!rects) { _XEatDataWords(dpy, rep.length); _XEatData (dpy, (unsigned long) (nbytes - nread)); } UnlockDisplay (dpy); SyncHandle(); *nrectanglesRet = nrects; return rects; }
304,152,935,311,185,560,000,000,000,000,000,000,000
None
null
[ "CWE-190" ]
CVE-2016-7944
Integer overflow in X.org libXfixes before 5.0.3 on 32-bit platforms might allow remote X servers to gain privileges via a length value of INT_MAX, which triggers the client to stop reading data and get out of sync.
https://nvd.nist.gov/vuln/detail/CVE-2016-7944
232
libav
136f55207521f0b03194ef5b55ba70f1635d6aee
https://github.com/libav/libav
https://git.libav.org/?p=libav.git;a=commit;h=136f55207521f0b03194ef5b55ba70f1635d6aee
mpegvideo_motion: Handle edge emulation even without unrestricted_mv Fix out of bounds read. Bug-Id: 962 Found by: F4B3CD@STARLAB and Agostino Sarubbo Signed-off-by: Vittorio Giovara <[email protected]>
1
static inline int hpel_motion(MpegEncContext *s, uint8_t *dest, uint8_t *src, int src_x, int src_y, op_pixels_func *pix_op, int motion_x, int motion_y) { int dxy = 0; int emu = 0; src_x += motion_x >> 1; src_y += motion_y >> 1; /* WARNING: do no forget half pels */ src_x = av_clip(src_x, -16, s->width); // FIXME unneeded for emu? if (src_x != s->width) dxy |= motion_x & 1; src_y = av_clip(src_y, -16, s->height); if (src_y != s->height) dxy |= (motion_y & 1) << 1; src += src_y * s->linesize + src_x; if (s->unrestricted_mv) { if ((unsigned)src_x > FFMAX(s->h_edge_pos - (motion_x & 1) - 8, 0) || (unsigned)src_y > FFMAX(s->v_edge_pos - (motion_y & 1) - 8, 0)) { s->vdsp.emulated_edge_mc(s->sc.edge_emu_buffer, src, s->linesize, s->linesize, 9, 9, src_x, src_y, s->h_edge_pos, s->v_edge_pos); src = s->sc.edge_emu_buffer; emu = 1; } } pix_op[dxy](dest, src, s->linesize, 8); return emu; }
111,292,629,842,222,760,000,000,000,000,000,000,000
mpegvideo_motion.c
50,627,202,363,453,110,000,000,000,000,000,000,000
[ "CWE-476" ]
CVE-2016-7424
The put_no_rnd_pixels8_xy2_mmx function in x86/rnd_template.c in libav 11.7 and earlier allows remote attackers to cause a denial of service (NULL pointer dereference and crash) via a crafted MP3 file.
https://nvd.nist.gov/vuln/detail/CVE-2016-7424
158,092
libav
136f55207521f0b03194ef5b55ba70f1635d6aee
https://github.com/libav/libav
https://git.libav.org/?p=libav.git;a=commit;h=136f55207521f0b03194ef5b55ba70f1635d6aee
mpegvideo_motion: Handle edge emulation even without unrestricted_mv Fix out of bounds read. Bug-Id: 962 Found by: F4B3CD@STARLAB and Agostino Sarubbo Signed-off-by: Vittorio Giovara <[email protected]>
0
static inline int hpel_motion(MpegEncContext *s, uint8_t *dest, uint8_t *src, int src_x, int src_y, op_pixels_func *pix_op, int motion_x, int motion_y) { int dxy = 0; int emu = 0; src_x += motion_x >> 1; src_y += motion_y >> 1; /* WARNING: do no forget half pels */ src_x = av_clip(src_x, -16, s->width); // FIXME unneeded for emu? if (src_x != s->width) dxy |= motion_x & 1; src_y = av_clip(src_y, -16, s->height); if (src_y != s->height) dxy |= (motion_y & 1) << 1; src += src_y * s->linesize + src_x; if ((unsigned)src_x > FFMAX(s->h_edge_pos - (motion_x & 1) - 8, 0) || (unsigned)src_y > FFMAX(s->v_edge_pos - (motion_y & 1) - 8, 0)) { s->vdsp.emulated_edge_mc(s->sc.edge_emu_buffer, src, s->linesize, s->linesize, 9, 9, src_x, src_y, s->h_edge_pos, s->v_edge_pos); src = s->sc.edge_emu_buffer; emu = 1; } pix_op[dxy](dest, src, s->linesize, 8); return emu; }
104,050,017,138,290,810,000,000,000,000,000,000,000
mpegvideo_motion.c
61,191,799,423,593,900,000,000,000,000,000,000,000
[ "CWE-476" ]
CVE-2016-7424
The put_no_rnd_pixels8_xy2_mmx function in x86/rnd_template.c in libav 11.7 and earlier allows remote attackers to cause a denial of service (NULL pointer dereference and crash) via a crafted MP3 file.
https://nvd.nist.gov/vuln/detail/CVE-2016-7424
233
tartarus
4ff22863d895cb7ebfced4cf923a012a614adaa8
https://git.tartarus.org/?p=simon/putty
https://git.tartarus.org/?p=simon/putty.git;a=commitdiff;h=4ff22863d895cb7ebfced4cf923a012a614adaa8
None
1
static void ssh_throttle_all(Ssh ssh, int enable, int bufsize) { int i; struct ssh_channel *c; if (enable == ssh->throttled_all) return; ssh->throttled_all = enable; ssh->overall_bufsize = bufsize; if (!ssh->channels) return; for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) { switch (c->type) { case CHAN_MAINSESSION: /* * This is treated separately, outside the switch. */ break; x11_override_throttle(c->u.x11.xconn, enable); break; case CHAN_AGENT: /* Agent channels require no buffer management. */ break; case CHAN_SOCKDATA: pfd_override_throttle(c->u.pfd.pf, enable); static void ssh_agent_callback(void *sshv, void *reply, int replylen) { Ssh ssh = (Ssh) sshv; ssh->auth_agent_query = NULL; ssh->agent_response = reply; ssh->agent_response_len = replylen; if (ssh->version == 1) do_ssh1_login(ssh, NULL, -1, NULL); else do_ssh2_authconn(ssh, NULL, -1, NULL); } static void ssh_dialog_callback(void *sshv, int ret) { Ssh ssh = (Ssh) sshv; ssh->user_response = ret; if (ssh->version == 1) do_ssh1_login(ssh, NULL, -1, NULL); else do_ssh2_transport(ssh, NULL, -1, NULL); /* * This may have unfrozen the SSH connection, so do a * queued-data run. */ ssh_process_queued_incoming_data(ssh); } static void ssh_agentf_callback(void *cv, void *reply, int replylen) ssh_process_queued_incoming_data(ssh); } static void ssh_agentf_callback(void *cv, void *reply, int replylen) { struct ssh_channel *c = (struct ssh_channel *)cv; const void *sentreply = reply; c->u.a.pending = NULL; c->u.a.outstanding_requests--; if (!sentreply) { /* Fake SSH_AGENT_FAILURE. */ sentreply = "\0\0\0\1\5"; replylen = 5; } ssh_send_channel_data(c, sentreply, replylen); if (reply) sfree(reply); /* * If we've already seen an incoming EOF but haven't sent an * outgoing one, this may be the moment to send it. */ if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF)) sshfwd_write_eof(c); } /* * Client-initiated disconnection. Send a DISCONNECT if `wire_reason' * non-NULL, otherwise just close the connection. `client_reason' == NULL struct Packet *pktin) { int i, j, ret; unsigned char cookie[8], *ptr; struct MD5Context md5c; struct do_ssh1_login_state { int crLine; int len; unsigned char *rsabuf; const unsigned char *keystr1, *keystr2; unsigned long supported_ciphers_mask, supported_auths_mask; int tried_publickey, tried_agent; int tis_auth_refused, ccard_auth_refused; unsigned char session_id[16]; int cipher_type; void *publickey_blob; int publickey_bloblen; char *publickey_comment; int privatekey_available, privatekey_encrypted; prompts_t *cur_prompt; char c; int pwpkt_type; unsigned char request[5], *response, *p; int responselen; int keyi, nkeys; int authed; struct RSAKey key; Bignum challenge; char *commentp; int commentlen; int dlgret; Filename *keyfile; struct RSAKey servkey, hostkey; }; crState(do_ssh1_login_state); crBeginState; if (!pktin) crWaitUntil(pktin); if (pktin->type != SSH1_SMSG_PUBLIC_KEY) { bombout(("Public key packet not received")); crStop(0); } logevent("Received public keys"); ptr = ssh_pkt_getdata(pktin, 8); if (!ptr) { bombout(("SSH-1 public key packet stopped before random cookie")); crStop(0); } memcpy(cookie, ptr, 8); if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) || !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) { bombout(("Failed to read SSH-1 public keys from public key packet")); crStop(0); } /* * Log the host key fingerprint. */ { char logmsg[80]; logevent("Host key fingerprint is:"); strcpy(logmsg, " "); s->hostkey.comment = NULL; rsa_fingerprint(logmsg + strlen(logmsg), sizeof(logmsg) - strlen(logmsg), &s->hostkey); logevent(logmsg); } ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin); s->supported_ciphers_mask = ssh_pkt_getuint32(pktin); s->supported_auths_mask = ssh_pkt_getuint32(pktin); if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA)) s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA); ssh->v1_local_protoflags = ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED; ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER; MD5Init(&md5c); MD5Update(&md5c, s->keystr2, s->hostkey.bytes); MD5Update(&md5c, s->keystr1, s->servkey.bytes); MD5Update(&md5c, cookie, 8); MD5Final(s->session_id, &md5c); for (i = 0; i < 32; i++) ssh->session_key[i] = random_byte(); /* * Verify that the `bits' and `bytes' parameters match. */ if (s->hostkey.bits > s->hostkey.bytes * 8 || s->servkey.bits > s->servkey.bytes * 8) { bombout(("SSH-1 public keys were badly formatted")); crStop(0); } s->len = (s->hostkey.bytes > s->servkey.bytes ? s->hostkey.bytes : s->servkey.bytes); s->rsabuf = snewn(s->len, unsigned char); /* * Verify the host key. */ { /* * First format the key into a string. */ int len = rsastr_len(&s->hostkey); char fingerprint[100]; char *keystr = snewn(len, char); rsastr_fmt(keystr, &s->hostkey); rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey); /* First check against manually configured host keys. */ s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL); if (s->dlgret == 0) { /* did not match */ bombout(("Host key did not appear in manually configured list")); sfree(keystr); crStop(0); } else if (s->dlgret < 0) { /* none configured; use standard handling */ ssh_set_frozen(ssh, 1); s->dlgret = verify_ssh_host_key(ssh->frontend, ssh->savedhost, ssh->savedport, "rsa", keystr, fingerprint, ssh_dialog_callback, ssh); sfree(keystr); #ifdef FUZZING s->dlgret = 1; #endif if (s->dlgret < 0) { do { crReturn(0); if (pktin) { bombout(("Unexpected data from server while waiting" " for user host key response")); crStop(0); } } while (pktin || inlen > 0); s->dlgret = ssh->user_response; } ssh_set_frozen(ssh, 0); if (s->dlgret == 0) { ssh_disconnect(ssh, "User aborted at host key verification", NULL, 0, TRUE); crStop(0); } } else { sfree(keystr); } } for (i = 0; i < 32; i++) { s->rsabuf[i] = ssh->session_key[i]; if (i < 16) s->rsabuf[i] ^= s->session_id[i]; } if (s->hostkey.bytes > s->servkey.bytes) { ret = rsaencrypt(s->rsabuf, 32, &s->servkey); if (ret) ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey); } else { ret = rsaencrypt(s->rsabuf, 32, &s->hostkey); if (ret) ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey); } if (!ret) { bombout(("SSH-1 public key encryptions failed due to bad formatting")); crStop(0); } logevent("Encrypted session key"); { int cipher_chosen = 0, warn = 0; const char *cipher_string = NULL; int i; for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) { int next_cipher = conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i); if (next_cipher == CIPHER_WARN) { /* If/when we choose a cipher, warn about it */ warn = 1; } else if (next_cipher == CIPHER_AES) { /* XXX Probably don't need to mention this. */ logevent("AES not supported in SSH-1, skipping"); } else { switch (next_cipher) { case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES; cipher_string = "3DES"; break; case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH; cipher_string = "Blowfish"; break; case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES; cipher_string = "single-DES"; break; } if (s->supported_ciphers_mask & (1 << s->cipher_type)) cipher_chosen = 1; } } if (!cipher_chosen) { if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0) bombout(("Server violates SSH-1 protocol by not " "supporting 3DES encryption")); else /* shouldn't happen */ bombout(("No supported ciphers found")); crStop(0); } /* Warn about chosen cipher if necessary. */ if (warn) { ssh_set_frozen(ssh, 1); s->dlgret = askalg(ssh->frontend, "cipher", cipher_string, ssh_dialog_callback, ssh); if (s->dlgret < 0) { do { crReturn(0); if (pktin) { bombout(("Unexpected data from server while waiting" " for user response")); crStop(0); } } while (pktin || inlen > 0); s->dlgret = ssh->user_response; } ssh_set_frozen(ssh, 0); if (s->dlgret == 0) { ssh_disconnect(ssh, "User aborted at cipher warning", NULL, 0, TRUE); crStop(0); } } } switch (s->cipher_type) { case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break; case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break; case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break; } send_packet(ssh, SSH1_CMSG_SESSION_KEY, PKT_CHAR, s->cipher_type, PKT_DATA, cookie, 8, PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF, PKT_DATA, s->rsabuf, s->len, PKT_INT, ssh->v1_local_protoflags, PKT_END); logevent("Trying to enable encryption..."); sfree(s->rsabuf); ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 : s->cipher_type == SSH_CIPHER_DES ? &ssh_des : &ssh_3des); ssh->v1_cipher_ctx = ssh->cipher->make_context(); ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key); logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name); ssh->crcda_ctx = crcda_make_context(); logevent("Installing CRC compensation attack detector"); if (s->servkey.modulus) { sfree(s->servkey.modulus); s->servkey.modulus = NULL; } if (s->servkey.exponent) { sfree(s->servkey.exponent); s->servkey.exponent = NULL; } if (s->hostkey.modulus) { sfree(s->hostkey.modulus); s->hostkey.modulus = NULL; } if (s->hostkey.exponent) { sfree(s->hostkey.exponent); s->hostkey.exponent = NULL; } crWaitUntil(pktin); if (pktin->type != SSH1_SMSG_SUCCESS) { bombout(("Encryption not successfully enabled")); crStop(0); } logevent("Successfully started encryption"); fflush(stdout); /* FIXME eh? */ { if ((ssh->username = get_remote_username(ssh->conf)) == NULL) { int ret; /* need not be kept over crReturn */ s->cur_prompt = new_prompts(ssh->frontend); s->cur_prompt->to_server = TRUE; s->cur_prompt->name = dupstr("SSH login name"); add_prompt(s->cur_prompt, dupstr("login as: "), TRUE); ret = get_userpass_input(s->cur_prompt, NULL, 0); while (ret < 0) { ssh->send_ok = 1; crWaitUntil(!pktin); ret = get_userpass_input(s->cur_prompt, in, inlen); ssh->send_ok = 0; } if (!ret) { /* * Failed to get a username. Terminate. */ free_prompts(s->cur_prompt); ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE); crStop(0); } ssh->username = dupstr(s->cur_prompt->prompts[0]->result); free_prompts(s->cur_prompt); } send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END); { char *userlog = dupprintf("Sent username \"%s\"", ssh->username); logevent(userlog); if (flags & FLAG_INTERACTIVE && (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) { c_write_str(ssh, userlog); c_write_str(ssh, "\r\n"); } sfree(userlog); } } crWaitUntil(pktin); if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) { /* We must not attempt PK auth. Pretend we've already tried it. */ s->tried_publickey = s->tried_agent = 1; } else { s->tried_publickey = s->tried_agent = 0; } s->tis_auth_refused = s->ccard_auth_refused = 0; /* * Load the public half of any configured keyfile for later use. */ s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile); if (!filename_is_null(s->keyfile)) { int keytype; logeventf(ssh, "Reading key file \"%.150s\"", filename_to_str(s->keyfile)); keytype = key_type(s->keyfile); if (keytype == SSH_KEYTYPE_SSH1 || keytype == SSH_KEYTYPE_SSH1_PUBLIC) { const char *error; if (rsakey_pubblob(s->keyfile, &s->publickey_blob, &s->publickey_bloblen, &s->publickey_comment, &error)) { s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1); if (!s->privatekey_available) logeventf(ssh, "Key file contains public key only"); s->privatekey_encrypted = rsakey_encrypted(s->keyfile, NULL); } else { char *msgbuf; logeventf(ssh, "Unable to load key (%s)", error); msgbuf = dupprintf("Unable to load key file " "\"%.150s\" (%s)\r\n", filename_to_str(s->keyfile), error); c_write_str(ssh, msgbuf); sfree(msgbuf); s->publickey_blob = NULL; } } else { char *msgbuf; logeventf(ssh, "Unable to use this key file (%s)", key_type_to_str(keytype)); msgbuf = dupprintf("Unable to use key file \"%.150s\"" " (%s)\r\n", filename_to_str(s->keyfile), key_type_to_str(keytype)); c_write_str(ssh, msgbuf); sfree(msgbuf); s->publickey_blob = NULL; } } else s->publickey_blob = NULL; while (pktin->type == SSH1_SMSG_FAILURE) { s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD; if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) { /* * Attempt RSA authentication using Pageant. */ void *r; s->authed = FALSE; s->tried_agent = 1; logevent("Pageant is running. Requesting keys."); /* Request the keys held by the agent. */ PUT_32BIT(s->request, 1); s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES; ssh->auth_agent_query = agent_query( s->request, 5, &r, &s->responselen, ssh_agent_callback, ssh); if (ssh->auth_agent_query) { do { crReturn(0); if (pktin) { bombout(("Unexpected data from server while waiting" " for agent response")); crStop(0); } } while (pktin || inlen > 0); r = ssh->agent_response; s->responselen = ssh->agent_response_len; } s->response = (unsigned char *) r; if (s->response && s->responselen >= 5 && s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) { s->p = s->response + 5; s->nkeys = toint(GET_32BIT(s->p)); if (s->nkeys < 0) { logeventf(ssh, "Pageant reported negative key count %d", s->nkeys); s->nkeys = 0; } s->p += 4; logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys); for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) { unsigned char *pkblob = s->p; s->p += 4; { int n, ok = FALSE; do { /* do while (0) to make breaking easy */ n = ssh1_read_bignum (s->p, toint(s->responselen-(s->p-s->response)), &s->key.exponent); if (n < 0) break; s->p += n; n = ssh1_read_bignum (s->p, toint(s->responselen-(s->p-s->response)), &s->key.modulus); if (n < 0) break; s->p += n; if (s->responselen - (s->p-s->response) < 4) break; s->commentlen = toint(GET_32BIT(s->p)); s->p += 4; if (s->commentlen < 0 || toint(s->responselen - (s->p-s->response)) < s->commentlen) break; s->commentp = (char *)s->p; s->p += s->commentlen; ok = TRUE; } while (0); if (!ok) { logevent("Pageant key list packet was truncated"); break; } } if (s->publickey_blob) { if (!memcmp(pkblob, s->publickey_blob, s->publickey_bloblen)) { logeventf(ssh, "Pageant key #%d matches " "configured key file", s->keyi); s->tried_publickey = 1; } else /* Skip non-configured key */ continue; } logeventf(ssh, "Trying Pageant key #%d", s->keyi); send_packet(ssh, SSH1_CMSG_AUTH_RSA, PKT_BIGNUM, s->key.modulus, PKT_END); crWaitUntil(pktin); if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) { logevent("Key refused"); continue; } logevent("Received RSA challenge"); if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) { bombout(("Server's RSA challenge was badly formatted")); crStop(0); } { char *agentreq, *q, *ret; void *vret; int len, retlen; len = 1 + 4; /* message type, bit count */ len += ssh1_bignum_length(s->key.exponent); len += ssh1_bignum_length(s->key.modulus); len += ssh1_bignum_length(s->challenge); len += 16; /* session id */ len += 4; /* response format */ agentreq = snewn(4 + len, char); PUT_32BIT(agentreq, len); q = agentreq + 4; *q++ = SSH1_AGENTC_RSA_CHALLENGE; PUT_32BIT(q, bignum_bitcount(s->key.modulus)); q += 4; q += ssh1_write_bignum(q, s->key.exponent); q += ssh1_write_bignum(q, s->key.modulus); q += ssh1_write_bignum(q, s->challenge); memcpy(q, s->session_id, 16); q += 16; PUT_32BIT(q, 1); /* response format */ ssh->auth_agent_query = agent_query( agentreq, len + 4, &vret, &retlen, ssh_agent_callback, ssh); if (ssh->auth_agent_query) { sfree(agentreq); do { crReturn(0); if (pktin) { bombout(("Unexpected data from server" " while waiting for agent" " response")); crStop(0); } } while (pktin || inlen > 0); vret = ssh->agent_response; retlen = ssh->agent_response_len; } else sfree(agentreq); ret = vret; if (ret) { if (ret[4] == SSH1_AGENT_RSA_RESPONSE) { logevent("Sending Pageant's response"); send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE, PKT_DATA, ret + 5, 16, PKT_END); sfree(ret); crWaitUntil(pktin); if (pktin->type == SSH1_SMSG_SUCCESS) { logevent ("Pageant's response accepted"); if (flags & FLAG_VERBOSE) { c_write_str(ssh, "Authenticated using" " RSA key \""); c_write(ssh, s->commentp, s->commentlen); c_write_str(ssh, "\" from agent\r\n"); } s->authed = TRUE; } else logevent ("Pageant's response not accepted"); } else { logevent ("Pageant failed to answer challenge"); sfree(ret); } } else { logevent("No reply received from Pageant"); } } freebn(s->key.exponent); freebn(s->key.modulus); freebn(s->challenge); if (s->authed) break; } sfree(s->response); if (s->publickey_blob && !s->tried_publickey) logevent("Configured key file not in Pageant"); } else { logevent("Failed to get reply from Pageant"); } if (s->authed) break; } if (s->publickey_blob && s->privatekey_available && !s->tried_publickey) { /* * Try public key authentication with the specified * key file. */ int got_passphrase; /* need not be kept over crReturn */ if (flags & FLAG_VERBOSE) c_write_str(ssh, "Trying public key authentication.\r\n"); s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile); logeventf(ssh, "Trying public key \"%s\"", filename_to_str(s->keyfile)); s->tried_publickey = 1; got_passphrase = FALSE; while (!got_passphrase) { /* * Get a passphrase, if necessary. */ char *passphrase = NULL; /* only written after crReturn */ const char *error; if (!s->privatekey_encrypted) { if (flags & FLAG_VERBOSE) c_write_str(ssh, "No passphrase required.\r\n"); passphrase = NULL; } else { int ret; /* need not be kept over crReturn */ s->cur_prompt = new_prompts(ssh->frontend); s->cur_prompt->to_server = FALSE; s->cur_prompt->name = dupstr("SSH key passphrase"); add_prompt(s->cur_prompt, dupprintf("Passphrase for key \"%.100s\": ", s->publickey_comment), FALSE); ret = get_userpass_input(s->cur_prompt, NULL, 0); while (ret < 0) { ssh->send_ok = 1; crWaitUntil(!pktin); ret = get_userpass_input(s->cur_prompt, in, inlen); ssh->send_ok = 0; } if (!ret) { /* Failed to get a passphrase. Terminate. */ free_prompts(s->cur_prompt); ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE); crStop(0); } passphrase = dupstr(s->cur_prompt->prompts[0]->result); free_prompts(s->cur_prompt); } /* * Try decrypting key with passphrase. */ s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile); ret = loadrsakey(s->keyfile, &s->key, passphrase, &error); if (passphrase) { smemclr(passphrase, strlen(passphrase)); sfree(passphrase); } if (ret == 1) { /* Correct passphrase. */ got_passphrase = TRUE; } else if (ret == 0) { c_write_str(ssh, "Couldn't load private key from "); c_write_str(ssh, filename_to_str(s->keyfile)); c_write_str(ssh, " ("); c_write_str(ssh, error); c_write_str(ssh, ").\r\n"); got_passphrase = FALSE; break; /* go and try something else */ } else if (ret == -1) { c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */ got_passphrase = FALSE; /* and try again */ } else { assert(0 && "unexpected return from loadrsakey()"); got_passphrase = FALSE; /* placate optimisers */ } } if (got_passphrase) { /* * Send a public key attempt. */ send_packet(ssh, SSH1_CMSG_AUTH_RSA, PKT_BIGNUM, s->key.modulus, PKT_END); crWaitUntil(pktin); if (pktin->type == SSH1_SMSG_FAILURE) { c_write_str(ssh, "Server refused our public key.\r\n"); continue; /* go and try something else */ } if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) { bombout(("Bizarre response to offer of public key")); crStop(0); } { int i; unsigned char buffer[32]; Bignum challenge, response; if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) { bombout(("Server's RSA challenge was badly formatted")); crStop(0); } response = rsadecrypt(challenge, &s->key); freebn(s->key.private_exponent);/* burn the evidence */ for (i = 0; i < 32; i++) { buffer[i] = bignum_byte(response, 31 - i); } MD5Init(&md5c); MD5Update(&md5c, buffer, 32); MD5Update(&md5c, s->session_id, 16); MD5Final(buffer, &md5c); send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE, PKT_DATA, buffer, 16, PKT_END); freebn(challenge); freebn(response); } crWaitUntil(pktin); if (pktin->type == SSH1_SMSG_FAILURE) { if (flags & FLAG_VERBOSE) c_write_str(ssh, "Failed to authenticate with" " our public key.\r\n"); continue; /* go and try something else */ } else if (pktin->type != SSH1_SMSG_SUCCESS) { bombout(("Bizarre response to RSA authentication response")); crStop(0); } break; /* we're through! */ } } /* * Otherwise, try various forms of password-like authentication. */ s->cur_prompt = new_prompts(ssh->frontend); if (conf_get_int(ssh->conf, CONF_try_tis_auth) && (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) && !s->tis_auth_refused) { s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE; logevent("Requested TIS authentication"); send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END); crWaitUntil(pktin); if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) { logevent("TIS authentication declined"); if (flags & FLAG_INTERACTIVE) c_write_str(ssh, "TIS authentication refused.\r\n"); s->tis_auth_refused = 1; continue; } else { char *challenge; int challengelen; char *instr_suf, *prompt; ssh_pkt_getstring(pktin, &challenge, &challengelen); if (!challenge) { bombout(("TIS challenge packet was badly formed")); crStop(0); } logevent("Received TIS challenge"); s->cur_prompt->to_server = TRUE; s->cur_prompt->name = dupstr("SSH TIS authentication"); /* Prompt heuristic comes from OpenSSH */ if (memchr(challenge, '\n', challengelen)) { instr_suf = dupstr(""); prompt = dupprintf("%.*s", challengelen, challenge); } else { instr_suf = dupprintf("%.*s", challengelen, challenge); prompt = dupstr("Response: "); } s->cur_prompt->instruction = dupprintf("Using TIS authentication.%s%s", (*instr_suf) ? "\n" : "", instr_suf); s->cur_prompt->instr_reqd = TRUE; add_prompt(s->cur_prompt, prompt, FALSE); sfree(instr_suf); } } if (conf_get_int(ssh->conf, CONF_try_tis_auth) && (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) && !s->ccard_auth_refused) { s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE; logevent("Requested CryptoCard authentication"); send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END); crWaitUntil(pktin); if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) { logevent("CryptoCard authentication declined"); c_write_str(ssh, "CryptoCard authentication refused.\r\n"); s->ccard_auth_refused = 1; continue; } else { char *challenge; int challengelen; char *instr_suf, *prompt; ssh_pkt_getstring(pktin, &challenge, &challengelen); if (!challenge) { bombout(("CryptoCard challenge packet was badly formed")); crStop(0); } logevent("Received CryptoCard challenge"); s->cur_prompt->to_server = TRUE; s->cur_prompt->name = dupstr("SSH CryptoCard authentication"); s->cur_prompt->name_reqd = FALSE; /* Prompt heuristic comes from OpenSSH */ if (memchr(challenge, '\n', challengelen)) { instr_suf = dupstr(""); prompt = dupprintf("%.*s", challengelen, challenge); } else { instr_suf = dupprintf("%.*s", challengelen, challenge); prompt = dupstr("Response: "); } s->cur_prompt->instruction = dupprintf("Using CryptoCard authentication.%s%s", (*instr_suf) ? "\n" : "", instr_suf); s->cur_prompt->instr_reqd = TRUE; add_prompt(s->cur_prompt, prompt, FALSE); sfree(instr_suf); } } if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) { if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) { bombout(("No supported authentication methods available")); crStop(0); } s->cur_prompt->to_server = TRUE; s->cur_prompt->name = dupstr("SSH password"); add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ", ssh->username, ssh->savedhost), FALSE); } /* * Show password prompt, having first obtained it via a TIS * or CryptoCard exchange if we're doing TIS or CryptoCard * authentication. */ { int ret; /* need not be kept over crReturn */ ret = get_userpass_input(s->cur_prompt, NULL, 0); while (ret < 0) { ssh->send_ok = 1; crWaitUntil(!pktin); ret = get_userpass_input(s->cur_prompt, in, inlen); ssh->send_ok = 0; } if (!ret) { /* * Failed to get a password (for example * because one was supplied on the command line * which has already failed to work). Terminate. */ free_prompts(s->cur_prompt); ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE); crStop(0); } } if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) { /* * Defence against traffic analysis: we send a * whole bunch of packets containing strings of * different lengths. One of these strings is the * password, in a SSH1_CMSG_AUTH_PASSWORD packet. * The others are all random data in * SSH1_MSG_IGNORE packets. This way a passive * listener can't tell which is the password, and * hence can't deduce the password length. * * Anybody with a password length greater than 16 * bytes is going to have enough entropy in their * password that a listener won't find it _that_ * much help to know how long it is. So what we'll * do is: * * - if password length < 16, we send 15 packets * containing string lengths 1 through 15 * * - otherwise, we let N be the nearest multiple * of 8 below the password length, and send 8 * packets containing string lengths N through * N+7. This won't obscure the order of * magnitude of the password length, but it will * introduce a bit of extra uncertainty. * * A few servers can't deal with SSH1_MSG_IGNORE, at * least in this context. For these servers, we need * an alternative defence. We make use of the fact * that the password is interpreted as a C string: * so we can append a NUL, then some random data. * * A few servers can deal with neither SSH1_MSG_IGNORE * here _nor_ a padded password string. * For these servers we are left with no defences * against password length sniffing. */ if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) && !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) { /* * The server can deal with SSH1_MSG_IGNORE, so * we can use the primary defence. */ int bottom, top, pwlen, i; char *randomstr; pwlen = strlen(s->cur_prompt->prompts[0]->result); if (pwlen < 16) { bottom = 0; /* zero length passwords are OK! :-) */ top = 15; } else { bottom = pwlen & ~7; top = bottom + 7; } assert(pwlen >= bottom && pwlen <= top); randomstr = snewn(top + 1, char); for (i = bottom; i <= top; i++) { if (i == pwlen) { defer_packet(ssh, s->pwpkt_type, PKT_STR,s->cur_prompt->prompts[0]->result, PKT_END); } else { for (j = 0; j < i; j++) { do { randomstr[j] = random_byte(); } while (randomstr[j] == '\0'); } randomstr[i] = '\0'; defer_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, randomstr, PKT_END); } } logevent("Sending password with camouflage packets"); ssh_pkt_defersend(ssh); sfree(randomstr); } else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) { /* * The server can't deal with SSH1_MSG_IGNORE * but can deal with padded passwords, so we * can use the secondary defence. */ char string[64]; char *ss; int len; len = strlen(s->cur_prompt->prompts[0]->result); if (len < sizeof(string)) { ss = string; strcpy(string, s->cur_prompt->prompts[0]->result); len++; /* cover the zero byte */ while (len < sizeof(string)) { string[len++] = (char) random_byte(); } } else { ss = s->cur_prompt->prompts[0]->result; } logevent("Sending length-padded password"); send_packet(ssh, s->pwpkt_type, PKT_INT, len, PKT_DATA, ss, len, PKT_END); } else { /* * The server is believed unable to cope with * any of our password camouflage methods. */ int len; len = strlen(s->cur_prompt->prompts[0]->result); logevent("Sending unpadded password"); send_packet(ssh, s->pwpkt_type, PKT_INT, len, PKT_DATA, s->cur_prompt->prompts[0]->result, len, PKT_END); } } else { send_packet(ssh, s->pwpkt_type, PKT_STR, s->cur_prompt->prompts[0]->result, PKT_END); } logevent("Sent password"); free_prompts(s->cur_prompt); crWaitUntil(pktin); if (pktin->type == SSH1_SMSG_FAILURE) { if (flags & FLAG_VERBOSE) c_write_str(ssh, "Access denied\r\n"); logevent("Authentication refused"); } else if (pktin->type != SSH1_SMSG_SUCCESS) { bombout(("Strange packet received, type %d", pktin->type)); crStop(0); } } /* Clear up */ if (s->publickey_blob) { sfree(s->publickey_blob); sfree(s->publickey_comment); } logevent("Authentication successful"); crFinish(1); } static void ssh_channel_try_eof(struct ssh_channel *c) { Ssh ssh = c->ssh; assert(c->pending_eof); /* precondition for calling us */ if (c->halfopen) return; /* can't close: not even opened yet */ if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0) return; /* can't send EOF: pending outgoing data */ c->pending_eof = FALSE; /* we're about to send it */ if (ssh->version == 1) { send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid, PKT_END); c->closes |= CLOSES_SENT_EOF; } else { struct Packet *pktout; pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF); ssh2_pkt_adduint32(pktout, c->remoteid); ssh2_pkt_send(ssh, pktout); c->closes |= CLOSES_SENT_EOF; ssh2_channel_check_close(c); } } Conf *sshfwd_get_conf(struct ssh_channel *c) { Ssh ssh = c->ssh; return ssh->conf; } void sshfwd_write_eof(struct ssh_channel *c) { Ssh ssh = c->ssh; if (ssh->state == SSH_STATE_CLOSED) return; if (c->closes & CLOSES_SENT_EOF) return; c->pending_eof = TRUE; ssh_channel_try_eof(c); } void sshfwd_unclean_close(struct ssh_channel *c, const char *err) { Ssh ssh = c->ssh; char *reason; if (ssh->state == SSH_STATE_CLOSED) return; reason = dupprintf("due to local error: %s", err); ssh_channel_close_local(c, reason); sfree(reason); c->pending_eof = FALSE; /* this will confuse a zombie channel */ ssh2_channel_check_close(c); } int sshfwd_write(struct ssh_channel *c, char *buf, int len) { Ssh ssh = c->ssh; if (ssh->state == SSH_STATE_CLOSED) return 0; return ssh_send_channel_data(c, buf, len); } void sshfwd_unthrottle(struct ssh_channel *c, int bufsize) { Ssh ssh = c->ssh; if (ssh->state == SSH_STATE_CLOSED) return; ssh_channel_unthrottle(c, bufsize); } static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin) { struct queued_handler *qh = ssh->qhead; assert(qh != NULL); assert(pktin->type == qh->msg1 || pktin->type == qh->msg2); if (qh->msg1 > 0) { assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler); ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1; } if (qh->msg2 > 0) { assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler); ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2; } if (qh->next) { ssh->qhead = qh->next; if (ssh->qhead->msg1 > 0) { ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1]; ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler; } if (ssh->qhead->msg2 > 0) { ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2]; ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler; } } else { ssh->qhead = ssh->qtail = NULL; } qh->handler(ssh, pktin, qh->ctx); sfree(qh); } static void ssh_queue_handler(Ssh ssh, int msg1, int msg2, chandler_fn_t handler, void *ctx) { struct queued_handler *qh; qh = snew(struct queued_handler); qh->msg1 = msg1; qh->msg2 = msg2; qh->handler = handler; qh->ctx = ctx; qh->next = NULL; if (ssh->qtail == NULL) { ssh->qhead = qh; if (qh->msg1 > 0) { ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1]; ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler; } if (qh->msg2 > 0) { ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2]; ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler; } } else { ssh->qtail->next = qh; } ssh->qtail = qh; } static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx) { struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx; if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS : SSH2_MSG_REQUEST_SUCCESS)) { logeventf(ssh, "Remote port forwarding from %s enabled", pf->sportdesc); } else { logeventf(ssh, "Remote port forwarding from %s refused", pf->sportdesc); rpf = del234(ssh->rportfwds, pf); assert(rpf == pf); pf->pfrec->remote = NULL; free_rportfwd(pf); } } int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport, void *share_ctx) { struct ssh_rportfwd *pf = snew(struct ssh_rportfwd); pf->dhost = NULL; pf->dport = 0; pf->share_ctx = share_ctx; pf->shost = dupstr(shost); pf->sport = sport; pf->sportdesc = NULL; if (!ssh->rportfwds) { assert(ssh->version == 2); ssh->rportfwds = newtree234(ssh_rportcmp_ssh2); } if (add234(ssh->rportfwds, pf) != pf) { sfree(pf->shost); sfree(pf); return FALSE; } return TRUE; } static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin, void *ctx) { share_got_pkt_from_server(ctx, pktin->type, pktin->body, pktin->length); } void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx) { ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE, ssh_sharing_global_request_response, share_ctx); } static void ssh_setup_portfwd(Ssh ssh, Conf *conf) { struct ssh_portfwd *epf; int i; char *key, *val; if (!ssh->portfwds) { ssh->portfwds = newtree234(ssh_portcmp); } else { /* * Go through the existing port forwardings and tag them * with status==DESTROY. Any that we want to keep will be * re-enabled (status==KEEP) as we go through the * configuration and find out which bits are the same as * they were before. */ struct ssh_portfwd *epf; int i; for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++) epf->status = DESTROY; } for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key); val != NULL; val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) { char *kp, *kp2, *vp, *vp2; char address_family, type; int sport,dport,sserv,dserv; char *sports, *dports, *saddr, *host; kp = key; address_family = 'A'; type = 'L'; if (*kp == 'A' || *kp == '4' || *kp == '6') address_family = *kp++; if (*kp == 'L' || *kp == 'R') type = *kp++; if ((kp2 = host_strchr(kp, ':')) != NULL) { /* * There's a colon in the middle of the source port * string, which means that the part before it is * actually a source address. */ char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp); saddr = host_strduptrim(saddr_tmp); sfree(saddr_tmp); sports = kp2+1; } else { saddr = NULL; sports = kp; } sport = atoi(sports); sserv = 0; if (sport == 0) { sserv = 1; sport = net_service_lookup(sports); if (!sport) { logeventf(ssh, "Service lookup failed for source" " port \"%s\"", sports); } } if (type == 'L' && !strcmp(val, "D")) { /* dynamic forwarding */ host = NULL; dports = NULL; dport = -1; dserv = 0; type = 'D'; } else { /* ordinary forwarding */ vp = val; vp2 = vp + host_strcspn(vp, ":"); host = dupprintf("%.*s", (int)(vp2 - vp), vp); if (*vp2) vp2++; dports = vp2; dport = atoi(dports); dserv = 0; if (dport == 0) { dserv = 1; dport = net_service_lookup(dports); if (!dport) { logeventf(ssh, "Service lookup failed for destination" " port \"%s\"", dports); } } } if (sport && dport) { /* Set up a description of the source port. */ struct ssh_portfwd *pfrec, *epfrec; pfrec = snew(struct ssh_portfwd); pfrec->type = type; pfrec->saddr = saddr; pfrec->sserv = sserv ? dupstr(sports) : NULL; pfrec->sport = sport; pfrec->daddr = host; pfrec->dserv = dserv ? dupstr(dports) : NULL; pfrec->dport = dport; pfrec->local = NULL; pfrec->remote = NULL; pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 : address_family == '6' ? ADDRTYPE_IPV6 : ADDRTYPE_UNSPEC); epfrec = add234(ssh->portfwds, pfrec); if (epfrec != pfrec) { if (epfrec->status == DESTROY) { /* * We already have a port forwarding up and running * with precisely these parameters. Hence, no need * to do anything; simply re-tag the existing one * as KEEP. */ epfrec->status = KEEP; } /* * Anything else indicates that there was a duplicate * in our input, which we'll silently ignore. */ free_portfwd(pfrec); } else { pfrec->status = CREATE; } } else { sfree(saddr); sfree(host); } } /* * Now go through and destroy any port forwardings which were * not re-enabled. */ for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++) if (epf->status == DESTROY) { char *message; message = dupprintf("%s port forwarding from %s%s%d", epf->type == 'L' ? "local" : epf->type == 'R' ? "remote" : "dynamic", epf->saddr ? epf->saddr : "", epf->saddr ? ":" : "", epf->sport); if (epf->type != 'D') { char *msg2 = dupprintf("%s to %s:%d", message, epf->daddr, epf->dport); sfree(message); message = msg2; } logeventf(ssh, "Cancelling %s", message); sfree(message); /* epf->remote or epf->local may be NULL if setting up a * forwarding failed. */ if (epf->remote) { struct ssh_rportfwd *rpf = epf->remote; struct Packet *pktout; /* * Cancel the port forwarding at the server * end. */ if (ssh->version == 1) { /* * We cannot cancel listening ports on the * server side in SSH-1! There's no message * to support it. Instead, we simply remove * the rportfwd record from the local end * so that any connections the server tries * to make on it are rejected. */ } else { pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST); ssh2_pkt_addstring(pktout, "cancel-tcpip-forward"); ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */ if (epf->saddr) { ssh2_pkt_addstring(pktout, epf->saddr); } else if (conf_get_int(conf, CONF_rport_acceptall)) { /* XXX: rport_acceptall may not represent * what was used to open the original connection, * since it's reconfigurable. */ ssh2_pkt_addstring(pktout, ""); } else { ssh2_pkt_addstring(pktout, "localhost"); } ssh2_pkt_adduint32(pktout, epf->sport); ssh2_pkt_send(ssh, pktout); } del234(ssh->rportfwds, rpf); free_rportfwd(rpf); } else if (epf->local) { pfl_terminate(epf->local); } delpos234(ssh->portfwds, i); free_portfwd(epf); i--; /* so we don't skip one in the list */ } /* * And finally, set up any new port forwardings (status==CREATE). */ for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++) if (epf->status == CREATE) { char *sportdesc, *dportdesc; sportdesc = dupprintf("%s%s%s%s%d%s", epf->saddr ? epf->saddr : "", epf->saddr ? ":" : "", epf->sserv ? epf->sserv : "", epf->sserv ? "(" : "", epf->sport, epf->sserv ? ")" : ""); if (epf->type == 'D') { dportdesc = NULL; } else { dportdesc = dupprintf("%s:%s%s%d%s", epf->daddr, epf->dserv ? epf->dserv : "", epf->dserv ? "(" : "", epf->dport, epf->dserv ? ")" : ""); } if (epf->type == 'L') { char *err = pfl_listen(epf->daddr, epf->dport, epf->saddr, epf->sport, ssh, conf, &epf->local, epf->addressfamily); logeventf(ssh, "Local %sport %s forwarding to %s%s%s", epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " : epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "", sportdesc, dportdesc, err ? " failed: " : "", err ? err : ""); if (err) sfree(err); } else if (epf->type == 'D') { char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport, ssh, conf, &epf->local, epf->addressfamily); logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s", epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " : epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "", sportdesc, err ? " failed: " : "", err ? err : ""); if (err) sfree(err); } else { struct ssh_rportfwd *pf; /* * Ensure the remote port forwardings tree exists. */ if (!ssh->rportfwds) { if (ssh->version == 1) ssh->rportfwds = newtree234(ssh_rportcmp_ssh1); else ssh->rportfwds = newtree234(ssh_rportcmp_ssh2); } pf = snew(struct ssh_rportfwd); pf->share_ctx = NULL; pf->dhost = dupstr(epf->daddr); pf->dport = epf->dport; if (epf->saddr) { pf->shost = dupstr(epf->saddr); } else if (conf_get_int(conf, CONF_rport_acceptall)) { pf->shost = dupstr(""); } else { pf->shost = dupstr("localhost"); } pf->sport = epf->sport; if (add234(ssh->rportfwds, pf) != pf) { logeventf(ssh, "Duplicate remote port forwarding to %s:%d", epf->daddr, epf->dport); sfree(pf); } else { logeventf(ssh, "Requesting remote port %s" " forward to %s", sportdesc, dportdesc); pf->sportdesc = sportdesc; sportdesc = NULL; epf->remote = pf; pf->pfrec = epf; if (ssh->version == 1) { send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST, PKT_INT, epf->sport, PKT_STR, epf->daddr, PKT_INT, epf->dport, PKT_END); ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS, SSH1_SMSG_FAILURE, ssh_rportfwd_succfail, pf); } else { struct Packet *pktout; pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST); ssh2_pkt_addstring(pktout, "tcpip-forward"); ssh2_pkt_addbool(pktout, 1);/* want reply */ ssh2_pkt_addstring(pktout, pf->shost); ssh2_pkt_adduint32(pktout, pf->sport); ssh2_pkt_send(ssh, pktout); ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE, ssh_rportfwd_succfail, pf); } } } sfree(sportdesc); sfree(dportdesc); } } static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin) { char *string; int stringlen, bufsize; ssh_pkt_getstring(pktin, &string, &stringlen); if (string == NULL) { bombout(("Incoming terminal data packet was badly formed")); return; } bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA, string, stringlen); if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) { ssh->v1_stdout_throttling = 1; ssh_throttle_conn(ssh, +1); } } static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin) { /* Remote side is trying to open a channel to talk to our * X-Server. Give them back a local channel number. */ struct ssh_channel *c; int remoteid = ssh_pkt_getuint32(pktin); logevent("Received X11 connect request"); /* Refuse if X11 forwarding is disabled. */ if (!ssh->X11_fwd_enabled) { send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE, PKT_INT, remoteid, PKT_END); logevent("Rejected X11 connect request"); } else { c = snew(struct ssh_channel); c->ssh = ssh; ssh_channel_init(c); c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1); c->remoteid = remoteid; c->halfopen = FALSE; c->type = CHAN_X11; /* identify channel type */ send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION, PKT_INT, c->remoteid, PKT_INT, c->localid, PKT_END); logevent("Opened X11 forward channel"); } } static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin) { /* Remote side is trying to open a channel to talk to our * agent. Give them back a local channel number. */ struct ssh_channel *c; int remoteid = ssh_pkt_getuint32(pktin); /* Refuse if agent forwarding is disabled. */ if (!ssh->agentfwd_enabled) { send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE, PKT_INT, remoteid, PKT_END); } else { c = snew(struct ssh_channel); c->ssh = ssh; ssh_channel_init(c); c->remoteid = remoteid; c->halfopen = FALSE; c->type = CHAN_AGENT; /* identify channel type */ c->u.a.lensofar = 0; c->u.a.message = NULL; c->u.a.pending = NULL; c->u.a.outstanding_requests = 0; send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION, PKT_INT, c->remoteid, PKT_INT, c->localid, PKT_END); } } static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin) { /* Remote side is trying to open a channel to talk to a * forwarded port. Give them back a local channel number. */ struct ssh_rportfwd pf, *pfp; int remoteid; int hostsize, port; char *host; char *err; remoteid = ssh_pkt_getuint32(pktin); ssh_pkt_getstring(pktin, &host, &hostsize); port = ssh_pkt_getuint32(pktin); pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host)); pf.dport = port; pfp = find234(ssh->rportfwds, &pf, NULL); if (pfp == NULL) { logeventf(ssh, "Rejected remote port open request for %s:%d", pf.dhost, port); send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE, PKT_INT, remoteid, PKT_END); } else { struct ssh_channel *c = snew(struct ssh_channel); c->ssh = ssh; logeventf(ssh, "Received remote port open request for %s:%d", pf.dhost, port); err = pfd_connect(&c->u.pfd.pf, pf.dhost, port, c, ssh->conf, pfp->pfrec->addressfamily); if (err != NULL) { logeventf(ssh, "Port open failed: %s", err); sfree(err); sfree(c); send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE, PKT_INT, remoteid, PKT_END); } else { ssh_channel_init(c); c->remoteid = remoteid; c->halfopen = FALSE; c->type = CHAN_SOCKDATA; /* identify channel type */ send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION, PKT_INT, c->remoteid, PKT_INT, c->localid, PKT_END); logevent("Forwarded port opened successfully"); } } sfree(pf.dhost); } static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin) { struct ssh_channel *c; c = ssh_channel_msg(ssh, pktin); if (c && c->type == CHAN_SOCKDATA) { c->remoteid = ssh_pkt_getuint32(pktin); c->halfopen = FALSE; c->throttling_conn = 0; pfd_confirm(c->u.pfd.pf); } if (c && c->pending_eof) { /* * We have a pending close on this channel, * which we decided on before the server acked * the channel open. So now we know the * remoteid, we can close it again. */ ssh_channel_try_eof(c); } } c->remoteid = remoteid; c->halfopen = FALSE; c->type = CHAN_AGENT; /* identify channel type */ c->u.a.lensofar = 0; c->u.a.message = NULL; c->u.a.pending = NULL; c->u.a.outstanding_requests = 0; send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION, PKT_INT, c->remoteid, PKT_INT, c->localid, PKT_END); del234(ssh->channels, c); sfree(c); } }
325,909,590,182,681,000,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2017-6542
The ssh_agent_channel_data function in PuTTY before 0.68 allows remote attackers to have unspecified impact via a large length value in an agent protocol message and leveraging the ability to connect to the Unix-domain socket representing the forwarded agent connection, which trigger a buffer overflow.
https://nvd.nist.gov/vuln/detail/CVE-2017-6542
158,093
tartarus
4ff22863d895cb7ebfced4cf923a012a614adaa8
https://git.tartarus.org/?p=simon/putty
https://git.tartarus.org/?p=simon/putty.git;a=commitdiff;h=4ff22863d895cb7ebfced4cf923a012a614adaa8
None
0
static void ssh_throttle_all(Ssh ssh, int enable, int bufsize) { int i; struct ssh_channel *c; if (enable == ssh->throttled_all) return; ssh->throttled_all = enable; ssh->overall_bufsize = bufsize; if (!ssh->channels) return; for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) { switch (c->type) { case CHAN_MAINSESSION: /* * This is treated separately, outside the switch. */ break; x11_override_throttle(c->u.x11.xconn, enable); break; case CHAN_AGENT: /* Agent forwarding channels are buffer-managed by * checking ssh->throttled_all in ssh_agentf_try_forward. * So at the moment we _un_throttle again, we must make an * attempt to do something. */ if (!enable) ssh_agentf_try_forward(c); break; case CHAN_SOCKDATA: pfd_override_throttle(c->u.pfd.pf, enable); static void ssh_agent_callback(void *sshv, void *reply, int replylen) { Ssh ssh = (Ssh) sshv; ssh->auth_agent_query = NULL; ssh->agent_response = reply; ssh->agent_response_len = replylen; if (ssh->version == 1) do_ssh1_login(ssh, NULL, -1, NULL); else do_ssh2_authconn(ssh, NULL, -1, NULL); } static void ssh_dialog_callback(void *sshv, int ret) { Ssh ssh = (Ssh) sshv; ssh->user_response = ret; if (ssh->version == 1) do_ssh1_login(ssh, NULL, -1, NULL); else do_ssh2_transport(ssh, NULL, -1, NULL); /* * This may have unfrozen the SSH connection, so do a * queued-data run. */ ssh_process_queued_incoming_data(ssh); } static void ssh_agentf_callback(void *cv, void *reply, int replylen) ssh_process_queued_incoming_data(ssh); } static void ssh_agentf_got_response(struct ssh_channel *c, void *reply, int replylen) { c->u.a.pending = NULL; if (!reply) { /* The real agent didn't send any kind of reply at all for * some reason, so fake an SSH_AGENT_FAILURE. */ reply = "\0\0\0\1\5"; replylen = 5; } ssh_send_channel_data(c, reply, replylen); } static void ssh_agentf_callback(void *cv, void *reply, int replylen); static void ssh_agentf_try_forward(struct ssh_channel *c) { unsigned datalen, lengthfield, messagelen; unsigned char *message; unsigned char msglen[4]; void *reply; int replylen; /* * Don't try to parallelise agent requests. Wait for each one to * return before attempting the next. */ if (c->u.a.pending) return; /* * If the outgoing side of the channel connection is currently * throttled (for any reason, either that channel's window size or * the entire SSH connection being throttled), don't submit any * new forwarded requests to the real agent. This causes the input * side of the agent forwarding not to be emptied, exerting the * required back-pressure on the remote client, and encouraging it * to read our responses before sending too many more requests. */ if (c->ssh->throttled_all || (c->ssh->version == 2 && c->v.v2.remwindow == 0)) return; while (1) { /* * Try to extract a complete message from the input buffer. */ datalen = bufchain_size(&c->u.a.inbuffer); if (datalen < 4) break; /* not even a length field available yet */ bufchain_fetch(&c->u.a.inbuffer, msglen, 4); lengthfield = GET_32BIT(msglen); if (lengthfield > datalen - 4) break; /* a whole message is not yet available */ messagelen = lengthfield + 4; message = snewn(messagelen, unsigned char); bufchain_fetch(&c->u.a.inbuffer, message, messagelen); bufchain_consume(&c->u.a.inbuffer, messagelen); c->u.a.pending = agent_query( message, messagelen, &reply, &replylen, ssh_agentf_callback, c); sfree(message); if (c->u.a.pending) return; /* agent_query promised to reply in due course */ /* * If the agent gave us an answer immediately, pass it * straight on and go round this loop again. */ ssh_agentf_got_response(c, reply, replylen); } /* * If we get here (i.e. we left the above while loop via 'break' * rather than 'return'), that means we've determined that the * input buffer for the agent forwarding connection doesn't * contain a complete request. * * So if there's potentially more data to come, we can return now, * and wait for the remote client to send it. But if the remote * has sent EOF, it would be a mistake to do that, because we'd be * waiting a long time. So this is the moment to check for EOF, * and respond appropriately. */ if (c->closes & CLOSES_RCVD_EOF) sshfwd_write_eof(c); } static void ssh_agentf_callback(void *cv, void *reply, int replylen) { struct ssh_channel *c = (struct ssh_channel *)cv; ssh_agentf_got_response(c, reply, replylen); sfree(reply); /* * Now try to extract and send further messages from the channel's * input-side buffer. */ ssh_agentf_try_forward(c); } /* * Client-initiated disconnection. Send a DISCONNECT if `wire_reason' * non-NULL, otherwise just close the connection. `client_reason' == NULL struct Packet *pktin) { int i, j, ret; unsigned char cookie[8], *ptr; struct MD5Context md5c; struct do_ssh1_login_state { int crLine; int len; unsigned char *rsabuf; const unsigned char *keystr1, *keystr2; unsigned long supported_ciphers_mask, supported_auths_mask; int tried_publickey, tried_agent; int tis_auth_refused, ccard_auth_refused; unsigned char session_id[16]; int cipher_type; void *publickey_blob; int publickey_bloblen; char *publickey_comment; int privatekey_available, privatekey_encrypted; prompts_t *cur_prompt; char c; int pwpkt_type; unsigned char request[5], *response, *p; int responselen; int keyi, nkeys; int authed; struct RSAKey key; Bignum challenge; char *commentp; int commentlen; int dlgret; Filename *keyfile; struct RSAKey servkey, hostkey; }; crState(do_ssh1_login_state); crBeginState; if (!pktin) crWaitUntil(pktin); if (pktin->type != SSH1_SMSG_PUBLIC_KEY) { bombout(("Public key packet not received")); crStop(0); } logevent("Received public keys"); ptr = ssh_pkt_getdata(pktin, 8); if (!ptr) { bombout(("SSH-1 public key packet stopped before random cookie")); crStop(0); } memcpy(cookie, ptr, 8); if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) || !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) { bombout(("Failed to read SSH-1 public keys from public key packet")); crStop(0); } /* * Log the host key fingerprint. */ { char logmsg[80]; logevent("Host key fingerprint is:"); strcpy(logmsg, " "); s->hostkey.comment = NULL; rsa_fingerprint(logmsg + strlen(logmsg), sizeof(logmsg) - strlen(logmsg), &s->hostkey); logevent(logmsg); } ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin); s->supported_ciphers_mask = ssh_pkt_getuint32(pktin); s->supported_auths_mask = ssh_pkt_getuint32(pktin); if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA)) s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA); ssh->v1_local_protoflags = ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED; ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER; MD5Init(&md5c); MD5Update(&md5c, s->keystr2, s->hostkey.bytes); MD5Update(&md5c, s->keystr1, s->servkey.bytes); MD5Update(&md5c, cookie, 8); MD5Final(s->session_id, &md5c); for (i = 0; i < 32; i++) ssh->session_key[i] = random_byte(); /* * Verify that the `bits' and `bytes' parameters match. */ if (s->hostkey.bits > s->hostkey.bytes * 8 || s->servkey.bits > s->servkey.bytes * 8) { bombout(("SSH-1 public keys were badly formatted")); crStop(0); } s->len = (s->hostkey.bytes > s->servkey.bytes ? s->hostkey.bytes : s->servkey.bytes); s->rsabuf = snewn(s->len, unsigned char); /* * Verify the host key. */ { /* * First format the key into a string. */ int len = rsastr_len(&s->hostkey); char fingerprint[100]; char *keystr = snewn(len, char); rsastr_fmt(keystr, &s->hostkey); rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey); /* First check against manually configured host keys. */ s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL); if (s->dlgret == 0) { /* did not match */ bombout(("Host key did not appear in manually configured list")); sfree(keystr); crStop(0); } else if (s->dlgret < 0) { /* none configured; use standard handling */ ssh_set_frozen(ssh, 1); s->dlgret = verify_ssh_host_key(ssh->frontend, ssh->savedhost, ssh->savedport, "rsa", keystr, fingerprint, ssh_dialog_callback, ssh); sfree(keystr); #ifdef FUZZING s->dlgret = 1; #endif if (s->dlgret < 0) { do { crReturn(0); if (pktin) { bombout(("Unexpected data from server while waiting" " for user host key response")); crStop(0); } } while (pktin || inlen > 0); s->dlgret = ssh->user_response; } ssh_set_frozen(ssh, 0); if (s->dlgret == 0) { ssh_disconnect(ssh, "User aborted at host key verification", NULL, 0, TRUE); crStop(0); } } else { sfree(keystr); } } for (i = 0; i < 32; i++) { s->rsabuf[i] = ssh->session_key[i]; if (i < 16) s->rsabuf[i] ^= s->session_id[i]; } if (s->hostkey.bytes > s->servkey.bytes) { ret = rsaencrypt(s->rsabuf, 32, &s->servkey); if (ret) ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey); } else { ret = rsaencrypt(s->rsabuf, 32, &s->hostkey); if (ret) ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey); } if (!ret) { bombout(("SSH-1 public key encryptions failed due to bad formatting")); crStop(0); } logevent("Encrypted session key"); { int cipher_chosen = 0, warn = 0; const char *cipher_string = NULL; int i; for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) { int next_cipher = conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i); if (next_cipher == CIPHER_WARN) { /* If/when we choose a cipher, warn about it */ warn = 1; } else if (next_cipher == CIPHER_AES) { /* XXX Probably don't need to mention this. */ logevent("AES not supported in SSH-1, skipping"); } else { switch (next_cipher) { case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES; cipher_string = "3DES"; break; case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH; cipher_string = "Blowfish"; break; case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES; cipher_string = "single-DES"; break; } if (s->supported_ciphers_mask & (1 << s->cipher_type)) cipher_chosen = 1; } } if (!cipher_chosen) { if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0) bombout(("Server violates SSH-1 protocol by not " "supporting 3DES encryption")); else /* shouldn't happen */ bombout(("No supported ciphers found")); crStop(0); } /* Warn about chosen cipher if necessary. */ if (warn) { ssh_set_frozen(ssh, 1); s->dlgret = askalg(ssh->frontend, "cipher", cipher_string, ssh_dialog_callback, ssh); if (s->dlgret < 0) { do { crReturn(0); if (pktin) { bombout(("Unexpected data from server while waiting" " for user response")); crStop(0); } } while (pktin || inlen > 0); s->dlgret = ssh->user_response; } ssh_set_frozen(ssh, 0); if (s->dlgret == 0) { ssh_disconnect(ssh, "User aborted at cipher warning", NULL, 0, TRUE); crStop(0); } } } switch (s->cipher_type) { case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break; case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break; case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break; } send_packet(ssh, SSH1_CMSG_SESSION_KEY, PKT_CHAR, s->cipher_type, PKT_DATA, cookie, 8, PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF, PKT_DATA, s->rsabuf, s->len, PKT_INT, ssh->v1_local_protoflags, PKT_END); logevent("Trying to enable encryption..."); sfree(s->rsabuf); ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 : s->cipher_type == SSH_CIPHER_DES ? &ssh_des : &ssh_3des); ssh->v1_cipher_ctx = ssh->cipher->make_context(); ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key); logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name); ssh->crcda_ctx = crcda_make_context(); logevent("Installing CRC compensation attack detector"); if (s->servkey.modulus) { sfree(s->servkey.modulus); s->servkey.modulus = NULL; } if (s->servkey.exponent) { sfree(s->servkey.exponent); s->servkey.exponent = NULL; } if (s->hostkey.modulus) { sfree(s->hostkey.modulus); s->hostkey.modulus = NULL; } if (s->hostkey.exponent) { sfree(s->hostkey.exponent); s->hostkey.exponent = NULL; } crWaitUntil(pktin); if (pktin->type != SSH1_SMSG_SUCCESS) { bombout(("Encryption not successfully enabled")); crStop(0); } logevent("Successfully started encryption"); fflush(stdout); /* FIXME eh? */ { if ((ssh->username = get_remote_username(ssh->conf)) == NULL) { int ret; /* need not be kept over crReturn */ s->cur_prompt = new_prompts(ssh->frontend); s->cur_prompt->to_server = TRUE; s->cur_prompt->name = dupstr("SSH login name"); add_prompt(s->cur_prompt, dupstr("login as: "), TRUE); ret = get_userpass_input(s->cur_prompt, NULL, 0); while (ret < 0) { ssh->send_ok = 1; crWaitUntil(!pktin); ret = get_userpass_input(s->cur_prompt, in, inlen); ssh->send_ok = 0; } if (!ret) { /* * Failed to get a username. Terminate. */ free_prompts(s->cur_prompt); ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE); crStop(0); } ssh->username = dupstr(s->cur_prompt->prompts[0]->result); free_prompts(s->cur_prompt); } send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END); { char *userlog = dupprintf("Sent username \"%s\"", ssh->username); logevent(userlog); if (flags & FLAG_INTERACTIVE && (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) { c_write_str(ssh, userlog); c_write_str(ssh, "\r\n"); } sfree(userlog); } } crWaitUntil(pktin); if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) { /* We must not attempt PK auth. Pretend we've already tried it. */ s->tried_publickey = s->tried_agent = 1; } else { s->tried_publickey = s->tried_agent = 0; } s->tis_auth_refused = s->ccard_auth_refused = 0; /* * Load the public half of any configured keyfile for later use. */ s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile); if (!filename_is_null(s->keyfile)) { int keytype; logeventf(ssh, "Reading key file \"%.150s\"", filename_to_str(s->keyfile)); keytype = key_type(s->keyfile); if (keytype == SSH_KEYTYPE_SSH1 || keytype == SSH_KEYTYPE_SSH1_PUBLIC) { const char *error; if (rsakey_pubblob(s->keyfile, &s->publickey_blob, &s->publickey_bloblen, &s->publickey_comment, &error)) { s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1); if (!s->privatekey_available) logeventf(ssh, "Key file contains public key only"); s->privatekey_encrypted = rsakey_encrypted(s->keyfile, NULL); } else { char *msgbuf; logeventf(ssh, "Unable to load key (%s)", error); msgbuf = dupprintf("Unable to load key file " "\"%.150s\" (%s)\r\n", filename_to_str(s->keyfile), error); c_write_str(ssh, msgbuf); sfree(msgbuf); s->publickey_blob = NULL; } } else { char *msgbuf; logeventf(ssh, "Unable to use this key file (%s)", key_type_to_str(keytype)); msgbuf = dupprintf("Unable to use key file \"%.150s\"" " (%s)\r\n", filename_to_str(s->keyfile), key_type_to_str(keytype)); c_write_str(ssh, msgbuf); sfree(msgbuf); s->publickey_blob = NULL; } } else s->publickey_blob = NULL; while (pktin->type == SSH1_SMSG_FAILURE) { s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD; if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) { /* * Attempt RSA authentication using Pageant. */ void *r; s->authed = FALSE; s->tried_agent = 1; logevent("Pageant is running. Requesting keys."); /* Request the keys held by the agent. */ PUT_32BIT(s->request, 1); s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES; ssh->auth_agent_query = agent_query( s->request, 5, &r, &s->responselen, ssh_agent_callback, ssh); if (ssh->auth_agent_query) { do { crReturn(0); if (pktin) { bombout(("Unexpected data from server while waiting" " for agent response")); crStop(0); } } while (pktin || inlen > 0); r = ssh->agent_response; s->responselen = ssh->agent_response_len; } s->response = (unsigned char *) r; if (s->response && s->responselen >= 5 && s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) { s->p = s->response + 5; s->nkeys = toint(GET_32BIT(s->p)); if (s->nkeys < 0) { logeventf(ssh, "Pageant reported negative key count %d", s->nkeys); s->nkeys = 0; } s->p += 4; logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys); for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) { unsigned char *pkblob = s->p; s->p += 4; { int n, ok = FALSE; do { /* do while (0) to make breaking easy */ n = ssh1_read_bignum (s->p, toint(s->responselen-(s->p-s->response)), &s->key.exponent); if (n < 0) break; s->p += n; n = ssh1_read_bignum (s->p, toint(s->responselen-(s->p-s->response)), &s->key.modulus); if (n < 0) break; s->p += n; if (s->responselen - (s->p-s->response) < 4) break; s->commentlen = toint(GET_32BIT(s->p)); s->p += 4; if (s->commentlen < 0 || toint(s->responselen - (s->p-s->response)) < s->commentlen) break; s->commentp = (char *)s->p; s->p += s->commentlen; ok = TRUE; } while (0); if (!ok) { logevent("Pageant key list packet was truncated"); break; } } if (s->publickey_blob) { if (!memcmp(pkblob, s->publickey_blob, s->publickey_bloblen)) { logeventf(ssh, "Pageant key #%d matches " "configured key file", s->keyi); s->tried_publickey = 1; } else /* Skip non-configured key */ continue; } logeventf(ssh, "Trying Pageant key #%d", s->keyi); send_packet(ssh, SSH1_CMSG_AUTH_RSA, PKT_BIGNUM, s->key.modulus, PKT_END); crWaitUntil(pktin); if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) { logevent("Key refused"); continue; } logevent("Received RSA challenge"); if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) { bombout(("Server's RSA challenge was badly formatted")); crStop(0); } { char *agentreq, *q, *ret; void *vret; int len, retlen; len = 1 + 4; /* message type, bit count */ len += ssh1_bignum_length(s->key.exponent); len += ssh1_bignum_length(s->key.modulus); len += ssh1_bignum_length(s->challenge); len += 16; /* session id */ len += 4; /* response format */ agentreq = snewn(4 + len, char); PUT_32BIT(agentreq, len); q = agentreq + 4; *q++ = SSH1_AGENTC_RSA_CHALLENGE; PUT_32BIT(q, bignum_bitcount(s->key.modulus)); q += 4; q += ssh1_write_bignum(q, s->key.exponent); q += ssh1_write_bignum(q, s->key.modulus); q += ssh1_write_bignum(q, s->challenge); memcpy(q, s->session_id, 16); q += 16; PUT_32BIT(q, 1); /* response format */ ssh->auth_agent_query = agent_query( agentreq, len + 4, &vret, &retlen, ssh_agent_callback, ssh); if (ssh->auth_agent_query) { sfree(agentreq); do { crReturn(0); if (pktin) { bombout(("Unexpected data from server" " while waiting for agent" " response")); crStop(0); } } while (pktin || inlen > 0); vret = ssh->agent_response; retlen = ssh->agent_response_len; } else sfree(agentreq); ret = vret; if (ret) { if (ret[4] == SSH1_AGENT_RSA_RESPONSE) { logevent("Sending Pageant's response"); send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE, PKT_DATA, ret + 5, 16, PKT_END); sfree(ret); crWaitUntil(pktin); if (pktin->type == SSH1_SMSG_SUCCESS) { logevent ("Pageant's response accepted"); if (flags & FLAG_VERBOSE) { c_write_str(ssh, "Authenticated using" " RSA key \""); c_write(ssh, s->commentp, s->commentlen); c_write_str(ssh, "\" from agent\r\n"); } s->authed = TRUE; } else logevent ("Pageant's response not accepted"); } else { logevent ("Pageant failed to answer challenge"); sfree(ret); } } else { logevent("No reply received from Pageant"); } } freebn(s->key.exponent); freebn(s->key.modulus); freebn(s->challenge); if (s->authed) break; } sfree(s->response); if (s->publickey_blob && !s->tried_publickey) logevent("Configured key file not in Pageant"); } else { logevent("Failed to get reply from Pageant"); } if (s->authed) break; } if (s->publickey_blob && s->privatekey_available && !s->tried_publickey) { /* * Try public key authentication with the specified * key file. */ int got_passphrase; /* need not be kept over crReturn */ if (flags & FLAG_VERBOSE) c_write_str(ssh, "Trying public key authentication.\r\n"); s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile); logeventf(ssh, "Trying public key \"%s\"", filename_to_str(s->keyfile)); s->tried_publickey = 1; got_passphrase = FALSE; while (!got_passphrase) { /* * Get a passphrase, if necessary. */ char *passphrase = NULL; /* only written after crReturn */ const char *error; if (!s->privatekey_encrypted) { if (flags & FLAG_VERBOSE) c_write_str(ssh, "No passphrase required.\r\n"); passphrase = NULL; } else { int ret; /* need not be kept over crReturn */ s->cur_prompt = new_prompts(ssh->frontend); s->cur_prompt->to_server = FALSE; s->cur_prompt->name = dupstr("SSH key passphrase"); add_prompt(s->cur_prompt, dupprintf("Passphrase for key \"%.100s\": ", s->publickey_comment), FALSE); ret = get_userpass_input(s->cur_prompt, NULL, 0); while (ret < 0) { ssh->send_ok = 1; crWaitUntil(!pktin); ret = get_userpass_input(s->cur_prompt, in, inlen); ssh->send_ok = 0; } if (!ret) { /* Failed to get a passphrase. Terminate. */ free_prompts(s->cur_prompt); ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE); crStop(0); } passphrase = dupstr(s->cur_prompt->prompts[0]->result); free_prompts(s->cur_prompt); } /* * Try decrypting key with passphrase. */ s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile); ret = loadrsakey(s->keyfile, &s->key, passphrase, &error); if (passphrase) { smemclr(passphrase, strlen(passphrase)); sfree(passphrase); } if (ret == 1) { /* Correct passphrase. */ got_passphrase = TRUE; } else if (ret == 0) { c_write_str(ssh, "Couldn't load private key from "); c_write_str(ssh, filename_to_str(s->keyfile)); c_write_str(ssh, " ("); c_write_str(ssh, error); c_write_str(ssh, ").\r\n"); got_passphrase = FALSE; break; /* go and try something else */ } else if (ret == -1) { c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */ got_passphrase = FALSE; /* and try again */ } else { assert(0 && "unexpected return from loadrsakey()"); got_passphrase = FALSE; /* placate optimisers */ } } if (got_passphrase) { /* * Send a public key attempt. */ send_packet(ssh, SSH1_CMSG_AUTH_RSA, PKT_BIGNUM, s->key.modulus, PKT_END); crWaitUntil(pktin); if (pktin->type == SSH1_SMSG_FAILURE) { c_write_str(ssh, "Server refused our public key.\r\n"); continue; /* go and try something else */ } if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) { bombout(("Bizarre response to offer of public key")); crStop(0); } { int i; unsigned char buffer[32]; Bignum challenge, response; if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) { bombout(("Server's RSA challenge was badly formatted")); crStop(0); } response = rsadecrypt(challenge, &s->key); freebn(s->key.private_exponent);/* burn the evidence */ for (i = 0; i < 32; i++) { buffer[i] = bignum_byte(response, 31 - i); } MD5Init(&md5c); MD5Update(&md5c, buffer, 32); MD5Update(&md5c, s->session_id, 16); MD5Final(buffer, &md5c); send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE, PKT_DATA, buffer, 16, PKT_END); freebn(challenge); freebn(response); } crWaitUntil(pktin); if (pktin->type == SSH1_SMSG_FAILURE) { if (flags & FLAG_VERBOSE) c_write_str(ssh, "Failed to authenticate with" " our public key.\r\n"); continue; /* go and try something else */ } else if (pktin->type != SSH1_SMSG_SUCCESS) { bombout(("Bizarre response to RSA authentication response")); crStop(0); } break; /* we're through! */ } } /* * Otherwise, try various forms of password-like authentication. */ s->cur_prompt = new_prompts(ssh->frontend); if (conf_get_int(ssh->conf, CONF_try_tis_auth) && (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) && !s->tis_auth_refused) { s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE; logevent("Requested TIS authentication"); send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END); crWaitUntil(pktin); if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) { logevent("TIS authentication declined"); if (flags & FLAG_INTERACTIVE) c_write_str(ssh, "TIS authentication refused.\r\n"); s->tis_auth_refused = 1; continue; } else { char *challenge; int challengelen; char *instr_suf, *prompt; ssh_pkt_getstring(pktin, &challenge, &challengelen); if (!challenge) { bombout(("TIS challenge packet was badly formed")); crStop(0); } logevent("Received TIS challenge"); s->cur_prompt->to_server = TRUE; s->cur_prompt->name = dupstr("SSH TIS authentication"); /* Prompt heuristic comes from OpenSSH */ if (memchr(challenge, '\n', challengelen)) { instr_suf = dupstr(""); prompt = dupprintf("%.*s", challengelen, challenge); } else { instr_suf = dupprintf("%.*s", challengelen, challenge); prompt = dupstr("Response: "); } s->cur_prompt->instruction = dupprintf("Using TIS authentication.%s%s", (*instr_suf) ? "\n" : "", instr_suf); s->cur_prompt->instr_reqd = TRUE; add_prompt(s->cur_prompt, prompt, FALSE); sfree(instr_suf); } } if (conf_get_int(ssh->conf, CONF_try_tis_auth) && (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) && !s->ccard_auth_refused) { s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE; logevent("Requested CryptoCard authentication"); send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END); crWaitUntil(pktin); if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) { logevent("CryptoCard authentication declined"); c_write_str(ssh, "CryptoCard authentication refused.\r\n"); s->ccard_auth_refused = 1; continue; } else { char *challenge; int challengelen; char *instr_suf, *prompt; ssh_pkt_getstring(pktin, &challenge, &challengelen); if (!challenge) { bombout(("CryptoCard challenge packet was badly formed")); crStop(0); } logevent("Received CryptoCard challenge"); s->cur_prompt->to_server = TRUE; s->cur_prompt->name = dupstr("SSH CryptoCard authentication"); s->cur_prompt->name_reqd = FALSE; /* Prompt heuristic comes from OpenSSH */ if (memchr(challenge, '\n', challengelen)) { instr_suf = dupstr(""); prompt = dupprintf("%.*s", challengelen, challenge); } else { instr_suf = dupprintf("%.*s", challengelen, challenge); prompt = dupstr("Response: "); } s->cur_prompt->instruction = dupprintf("Using CryptoCard authentication.%s%s", (*instr_suf) ? "\n" : "", instr_suf); s->cur_prompt->instr_reqd = TRUE; add_prompt(s->cur_prompt, prompt, FALSE); sfree(instr_suf); } } if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) { if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) { bombout(("No supported authentication methods available")); crStop(0); } s->cur_prompt->to_server = TRUE; s->cur_prompt->name = dupstr("SSH password"); add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ", ssh->username, ssh->savedhost), FALSE); } /* * Show password prompt, having first obtained it via a TIS * or CryptoCard exchange if we're doing TIS or CryptoCard * authentication. */ { int ret; /* need not be kept over crReturn */ ret = get_userpass_input(s->cur_prompt, NULL, 0); while (ret < 0) { ssh->send_ok = 1; crWaitUntil(!pktin); ret = get_userpass_input(s->cur_prompt, in, inlen); ssh->send_ok = 0; } if (!ret) { /* * Failed to get a password (for example * because one was supplied on the command line * which has already failed to work). Terminate. */ free_prompts(s->cur_prompt); ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE); crStop(0); } } if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) { /* * Defence against traffic analysis: we send a * whole bunch of packets containing strings of * different lengths. One of these strings is the * password, in a SSH1_CMSG_AUTH_PASSWORD packet. * The others are all random data in * SSH1_MSG_IGNORE packets. This way a passive * listener can't tell which is the password, and * hence can't deduce the password length. * * Anybody with a password length greater than 16 * bytes is going to have enough entropy in their * password that a listener won't find it _that_ * much help to know how long it is. So what we'll * do is: * * - if password length < 16, we send 15 packets * containing string lengths 1 through 15 * * - otherwise, we let N be the nearest multiple * of 8 below the password length, and send 8 * packets containing string lengths N through * N+7. This won't obscure the order of * magnitude of the password length, but it will * introduce a bit of extra uncertainty. * * A few servers can't deal with SSH1_MSG_IGNORE, at * least in this context. For these servers, we need * an alternative defence. We make use of the fact * that the password is interpreted as a C string: * so we can append a NUL, then some random data. * * A few servers can deal with neither SSH1_MSG_IGNORE * here _nor_ a padded password string. * For these servers we are left with no defences * against password length sniffing. */ if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) && !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) { /* * The server can deal with SSH1_MSG_IGNORE, so * we can use the primary defence. */ int bottom, top, pwlen, i; char *randomstr; pwlen = strlen(s->cur_prompt->prompts[0]->result); if (pwlen < 16) { bottom = 0; /* zero length passwords are OK! :-) */ top = 15; } else { bottom = pwlen & ~7; top = bottom + 7; } assert(pwlen >= bottom && pwlen <= top); randomstr = snewn(top + 1, char); for (i = bottom; i <= top; i++) { if (i == pwlen) { defer_packet(ssh, s->pwpkt_type, PKT_STR,s->cur_prompt->prompts[0]->result, PKT_END); } else { for (j = 0; j < i; j++) { do { randomstr[j] = random_byte(); } while (randomstr[j] == '\0'); } randomstr[i] = '\0'; defer_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, randomstr, PKT_END); } } logevent("Sending password with camouflage packets"); ssh_pkt_defersend(ssh); sfree(randomstr); } else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) { /* * The server can't deal with SSH1_MSG_IGNORE * but can deal with padded passwords, so we * can use the secondary defence. */ char string[64]; char *ss; int len; len = strlen(s->cur_prompt->prompts[0]->result); if (len < sizeof(string)) { ss = string; strcpy(string, s->cur_prompt->prompts[0]->result); len++; /* cover the zero byte */ while (len < sizeof(string)) { string[len++] = (char) random_byte(); } } else { ss = s->cur_prompt->prompts[0]->result; } logevent("Sending length-padded password"); send_packet(ssh, s->pwpkt_type, PKT_INT, len, PKT_DATA, ss, len, PKT_END); } else { /* * The server is believed unable to cope with * any of our password camouflage methods. */ int len; len = strlen(s->cur_prompt->prompts[0]->result); logevent("Sending unpadded password"); send_packet(ssh, s->pwpkt_type, PKT_INT, len, PKT_DATA, s->cur_prompt->prompts[0]->result, len, PKT_END); } } else { send_packet(ssh, s->pwpkt_type, PKT_STR, s->cur_prompt->prompts[0]->result, PKT_END); } logevent("Sent password"); free_prompts(s->cur_prompt); crWaitUntil(pktin); if (pktin->type == SSH1_SMSG_FAILURE) { if (flags & FLAG_VERBOSE) c_write_str(ssh, "Access denied\r\n"); logevent("Authentication refused"); } else if (pktin->type != SSH1_SMSG_SUCCESS) { bombout(("Strange packet received, type %d", pktin->type)); crStop(0); } } /* Clear up */ if (s->publickey_blob) { sfree(s->publickey_blob); sfree(s->publickey_comment); } logevent("Authentication successful"); crFinish(1); } static void ssh_channel_try_eof(struct ssh_channel *c) { Ssh ssh = c->ssh; assert(c->pending_eof); /* precondition for calling us */ if (c->halfopen) return; /* can't close: not even opened yet */ if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0) return; /* can't send EOF: pending outgoing data */ c->pending_eof = FALSE; /* we're about to send it */ if (ssh->version == 1) { send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid, PKT_END); c->closes |= CLOSES_SENT_EOF; } else { struct Packet *pktout; pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF); ssh2_pkt_adduint32(pktout, c->remoteid); ssh2_pkt_send(ssh, pktout); c->closes |= CLOSES_SENT_EOF; ssh2_channel_check_close(c); } } Conf *sshfwd_get_conf(struct ssh_channel *c) { Ssh ssh = c->ssh; return ssh->conf; } void sshfwd_write_eof(struct ssh_channel *c) { Ssh ssh = c->ssh; if (ssh->state == SSH_STATE_CLOSED) return; if (c->closes & CLOSES_SENT_EOF) return; c->pending_eof = TRUE; ssh_channel_try_eof(c); } void sshfwd_unclean_close(struct ssh_channel *c, const char *err) { Ssh ssh = c->ssh; char *reason; if (ssh->state == SSH_STATE_CLOSED) return; reason = dupprintf("due to local error: %s", err); ssh_channel_close_local(c, reason); sfree(reason); c->pending_eof = FALSE; /* this will confuse a zombie channel */ ssh2_channel_check_close(c); } int sshfwd_write(struct ssh_channel *c, char *buf, int len) { Ssh ssh = c->ssh; if (ssh->state == SSH_STATE_CLOSED) return 0; return ssh_send_channel_data(c, buf, len); } void sshfwd_unthrottle(struct ssh_channel *c, int bufsize) { Ssh ssh = c->ssh; if (ssh->state == SSH_STATE_CLOSED) return; ssh_channel_unthrottle(c, bufsize); } static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin) { struct queued_handler *qh = ssh->qhead; assert(qh != NULL); assert(pktin->type == qh->msg1 || pktin->type == qh->msg2); if (qh->msg1 > 0) { assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler); ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1; } if (qh->msg2 > 0) { assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler); ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2; } if (qh->next) { ssh->qhead = qh->next; if (ssh->qhead->msg1 > 0) { ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1]; ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler; } if (ssh->qhead->msg2 > 0) { ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2]; ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler; } } else { ssh->qhead = ssh->qtail = NULL; } qh->handler(ssh, pktin, qh->ctx); sfree(qh); } static void ssh_queue_handler(Ssh ssh, int msg1, int msg2, chandler_fn_t handler, void *ctx) { struct queued_handler *qh; qh = snew(struct queued_handler); qh->msg1 = msg1; qh->msg2 = msg2; qh->handler = handler; qh->ctx = ctx; qh->next = NULL; if (ssh->qtail == NULL) { ssh->qhead = qh; if (qh->msg1 > 0) { ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1]; ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler; } if (qh->msg2 > 0) { ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2]; ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler; } } else { ssh->qtail->next = qh; } ssh->qtail = qh; } static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx) { struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx; if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS : SSH2_MSG_REQUEST_SUCCESS)) { logeventf(ssh, "Remote port forwarding from %s enabled", pf->sportdesc); } else { logeventf(ssh, "Remote port forwarding from %s refused", pf->sportdesc); rpf = del234(ssh->rportfwds, pf); assert(rpf == pf); pf->pfrec->remote = NULL; free_rportfwd(pf); } } int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport, void *share_ctx) { struct ssh_rportfwd *pf = snew(struct ssh_rportfwd); pf->dhost = NULL; pf->dport = 0; pf->share_ctx = share_ctx; pf->shost = dupstr(shost); pf->sport = sport; pf->sportdesc = NULL; if (!ssh->rportfwds) { assert(ssh->version == 2); ssh->rportfwds = newtree234(ssh_rportcmp_ssh2); } if (add234(ssh->rportfwds, pf) != pf) { sfree(pf->shost); sfree(pf); return FALSE; } return TRUE; } static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin, void *ctx) { share_got_pkt_from_server(ctx, pktin->type, pktin->body, pktin->length); } void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx) { ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE, ssh_sharing_global_request_response, share_ctx); } static void ssh_setup_portfwd(Ssh ssh, Conf *conf) { struct ssh_portfwd *epf; int i; char *key, *val; if (!ssh->portfwds) { ssh->portfwds = newtree234(ssh_portcmp); } else { /* * Go through the existing port forwardings and tag them * with status==DESTROY. Any that we want to keep will be * re-enabled (status==KEEP) as we go through the * configuration and find out which bits are the same as * they were before. */ struct ssh_portfwd *epf; int i; for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++) epf->status = DESTROY; } for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key); val != NULL; val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) { char *kp, *kp2, *vp, *vp2; char address_family, type; int sport,dport,sserv,dserv; char *sports, *dports, *saddr, *host; kp = key; address_family = 'A'; type = 'L'; if (*kp == 'A' || *kp == '4' || *kp == '6') address_family = *kp++; if (*kp == 'L' || *kp == 'R') type = *kp++; if ((kp2 = host_strchr(kp, ':')) != NULL) { /* * There's a colon in the middle of the source port * string, which means that the part before it is * actually a source address. */ char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp); saddr = host_strduptrim(saddr_tmp); sfree(saddr_tmp); sports = kp2+1; } else { saddr = NULL; sports = kp; } sport = atoi(sports); sserv = 0; if (sport == 0) { sserv = 1; sport = net_service_lookup(sports); if (!sport) { logeventf(ssh, "Service lookup failed for source" " port \"%s\"", sports); } } if (type == 'L' && !strcmp(val, "D")) { /* dynamic forwarding */ host = NULL; dports = NULL; dport = -1; dserv = 0; type = 'D'; } else { /* ordinary forwarding */ vp = val; vp2 = vp + host_strcspn(vp, ":"); host = dupprintf("%.*s", (int)(vp2 - vp), vp); if (*vp2) vp2++; dports = vp2; dport = atoi(dports); dserv = 0; if (dport == 0) { dserv = 1; dport = net_service_lookup(dports); if (!dport) { logeventf(ssh, "Service lookup failed for destination" " port \"%s\"", dports); } } } if (sport && dport) { /* Set up a description of the source port. */ struct ssh_portfwd *pfrec, *epfrec; pfrec = snew(struct ssh_portfwd); pfrec->type = type; pfrec->saddr = saddr; pfrec->sserv = sserv ? dupstr(sports) : NULL; pfrec->sport = sport; pfrec->daddr = host; pfrec->dserv = dserv ? dupstr(dports) : NULL; pfrec->dport = dport; pfrec->local = NULL; pfrec->remote = NULL; pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 : address_family == '6' ? ADDRTYPE_IPV6 : ADDRTYPE_UNSPEC); epfrec = add234(ssh->portfwds, pfrec); if (epfrec != pfrec) { if (epfrec->status == DESTROY) { /* * We already have a port forwarding up and running * with precisely these parameters. Hence, no need * to do anything; simply re-tag the existing one * as KEEP. */ epfrec->status = KEEP; } /* * Anything else indicates that there was a duplicate * in our input, which we'll silently ignore. */ free_portfwd(pfrec); } else { pfrec->status = CREATE; } } else { sfree(saddr); sfree(host); } } /* * Now go through and destroy any port forwardings which were * not re-enabled. */ for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++) if (epf->status == DESTROY) { char *message; message = dupprintf("%s port forwarding from %s%s%d", epf->type == 'L' ? "local" : epf->type == 'R' ? "remote" : "dynamic", epf->saddr ? epf->saddr : "", epf->saddr ? ":" : "", epf->sport); if (epf->type != 'D') { char *msg2 = dupprintf("%s to %s:%d", message, epf->daddr, epf->dport); sfree(message); message = msg2; } logeventf(ssh, "Cancelling %s", message); sfree(message); /* epf->remote or epf->local may be NULL if setting up a * forwarding failed. */ if (epf->remote) { struct ssh_rportfwd *rpf = epf->remote; struct Packet *pktout; /* * Cancel the port forwarding at the server * end. */ if (ssh->version == 1) { /* * We cannot cancel listening ports on the * server side in SSH-1! There's no message * to support it. Instead, we simply remove * the rportfwd record from the local end * so that any connections the server tries * to make on it are rejected. */ } else { pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST); ssh2_pkt_addstring(pktout, "cancel-tcpip-forward"); ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */ if (epf->saddr) { ssh2_pkt_addstring(pktout, epf->saddr); } else if (conf_get_int(conf, CONF_rport_acceptall)) { /* XXX: rport_acceptall may not represent * what was used to open the original connection, * since it's reconfigurable. */ ssh2_pkt_addstring(pktout, ""); } else { ssh2_pkt_addstring(pktout, "localhost"); } ssh2_pkt_adduint32(pktout, epf->sport); ssh2_pkt_send(ssh, pktout); } del234(ssh->rportfwds, rpf); free_rportfwd(rpf); } else if (epf->local) { pfl_terminate(epf->local); } delpos234(ssh->portfwds, i); free_portfwd(epf); i--; /* so we don't skip one in the list */ } /* * And finally, set up any new port forwardings (status==CREATE). */ for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++) if (epf->status == CREATE) { char *sportdesc, *dportdesc; sportdesc = dupprintf("%s%s%s%s%d%s", epf->saddr ? epf->saddr : "", epf->saddr ? ":" : "", epf->sserv ? epf->sserv : "", epf->sserv ? "(" : "", epf->sport, epf->sserv ? ")" : ""); if (epf->type == 'D') { dportdesc = NULL; } else { dportdesc = dupprintf("%s:%s%s%d%s", epf->daddr, epf->dserv ? epf->dserv : "", epf->dserv ? "(" : "", epf->dport, epf->dserv ? ")" : ""); } if (epf->type == 'L') { char *err = pfl_listen(epf->daddr, epf->dport, epf->saddr, epf->sport, ssh, conf, &epf->local, epf->addressfamily); logeventf(ssh, "Local %sport %s forwarding to %s%s%s", epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " : epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "", sportdesc, dportdesc, err ? " failed: " : "", err ? err : ""); if (err) sfree(err); } else if (epf->type == 'D') { char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport, ssh, conf, &epf->local, epf->addressfamily); logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s", epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " : epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "", sportdesc, err ? " failed: " : "", err ? err : ""); if (err) sfree(err); } else { struct ssh_rportfwd *pf; /* * Ensure the remote port forwardings tree exists. */ if (!ssh->rportfwds) { if (ssh->version == 1) ssh->rportfwds = newtree234(ssh_rportcmp_ssh1); else ssh->rportfwds = newtree234(ssh_rportcmp_ssh2); } pf = snew(struct ssh_rportfwd); pf->share_ctx = NULL; pf->dhost = dupstr(epf->daddr); pf->dport = epf->dport; if (epf->saddr) { pf->shost = dupstr(epf->saddr); } else if (conf_get_int(conf, CONF_rport_acceptall)) { pf->shost = dupstr(""); } else { pf->shost = dupstr("localhost"); } pf->sport = epf->sport; if (add234(ssh->rportfwds, pf) != pf) { logeventf(ssh, "Duplicate remote port forwarding to %s:%d", epf->daddr, epf->dport); sfree(pf); } else { logeventf(ssh, "Requesting remote port %s" " forward to %s", sportdesc, dportdesc); pf->sportdesc = sportdesc; sportdesc = NULL; epf->remote = pf; pf->pfrec = epf; if (ssh->version == 1) { send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST, PKT_INT, epf->sport, PKT_STR, epf->daddr, PKT_INT, epf->dport, PKT_END); ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS, SSH1_SMSG_FAILURE, ssh_rportfwd_succfail, pf); } else { struct Packet *pktout; pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST); ssh2_pkt_addstring(pktout, "tcpip-forward"); ssh2_pkt_addbool(pktout, 1);/* want reply */ ssh2_pkt_addstring(pktout, pf->shost); ssh2_pkt_adduint32(pktout, pf->sport); ssh2_pkt_send(ssh, pktout); ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE, ssh_rportfwd_succfail, pf); } } } sfree(sportdesc); sfree(dportdesc); } } static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin) { char *string; int stringlen, bufsize; ssh_pkt_getstring(pktin, &string, &stringlen); if (string == NULL) { bombout(("Incoming terminal data packet was badly formed")); return; } bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA, string, stringlen); if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) { ssh->v1_stdout_throttling = 1; ssh_throttle_conn(ssh, +1); } } static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin) { /* Remote side is trying to open a channel to talk to our * X-Server. Give them back a local channel number. */ struct ssh_channel *c; int remoteid = ssh_pkt_getuint32(pktin); logevent("Received X11 connect request"); /* Refuse if X11 forwarding is disabled. */ if (!ssh->X11_fwd_enabled) { send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE, PKT_INT, remoteid, PKT_END); logevent("Rejected X11 connect request"); } else { c = snew(struct ssh_channel); c->ssh = ssh; ssh_channel_init(c); c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1); c->remoteid = remoteid; c->halfopen = FALSE; c->type = CHAN_X11; /* identify channel type */ send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION, PKT_INT, c->remoteid, PKT_INT, c->localid, PKT_END); logevent("Opened X11 forward channel"); } } static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin) { /* Remote side is trying to open a channel to talk to our * agent. Give them back a local channel number. */ struct ssh_channel *c; int remoteid = ssh_pkt_getuint32(pktin); /* Refuse if agent forwarding is disabled. */ if (!ssh->agentfwd_enabled) { send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE, PKT_INT, remoteid, PKT_END); } else { c = snew(struct ssh_channel); c->ssh = ssh; ssh_channel_init(c); c->remoteid = remoteid; c->halfopen = FALSE; c->type = CHAN_AGENT; /* identify channel type */ c->u.a.lensofar = 0; c->u.a.message = NULL; c->u.a.pending = NULL; c->u.a.outstanding_requests = 0; send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION, PKT_INT, c->remoteid, PKT_INT, c->localid, PKT_END); } } static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin) { /* Remote side is trying to open a channel to talk to a * forwarded port. Give them back a local channel number. */ struct ssh_rportfwd pf, *pfp; int remoteid; int hostsize, port; char *host; char *err; remoteid = ssh_pkt_getuint32(pktin); ssh_pkt_getstring(pktin, &host, &hostsize); port = ssh_pkt_getuint32(pktin); pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host)); pf.dport = port; pfp = find234(ssh->rportfwds, &pf, NULL); if (pfp == NULL) { logeventf(ssh, "Rejected remote port open request for %s:%d", pf.dhost, port); send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE, PKT_INT, remoteid, PKT_END); } else { struct ssh_channel *c = snew(struct ssh_channel); c->ssh = ssh; logeventf(ssh, "Received remote port open request for %s:%d", pf.dhost, port); err = pfd_connect(&c->u.pfd.pf, pf.dhost, port, c, ssh->conf, pfp->pfrec->addressfamily); if (err != NULL) { logeventf(ssh, "Port open failed: %s", err); sfree(err); sfree(c); send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE, PKT_INT, remoteid, PKT_END); } else { ssh_channel_init(c); c->remoteid = remoteid; c->halfopen = FALSE; c->type = CHAN_SOCKDATA; /* identify channel type */ send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION, PKT_INT, c->remoteid, PKT_INT, c->localid, PKT_END); logevent("Forwarded port opened successfully"); } } sfree(pf.dhost); } static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin) { struct ssh_channel *c; c = ssh_channel_msg(ssh, pktin); if (c && c->type == CHAN_SOCKDATA) { c->remoteid = ssh_pkt_getuint32(pktin); c->halfopen = FALSE; c->throttling_conn = 0; pfd_confirm(c->u.pfd.pf); } if (c && c->pending_eof) { /* * We have a pending close on this channel, * which we decided on before the server acked * the channel open. So now we know the * remoteid, we can close it again. */ ssh_channel_try_eof(c); } } c->remoteid = remoteid; c->halfopen = FALSE; c->type = CHAN_AGENT; /* identify channel type */ c->u.a.pending = NULL; bufchain_init(&c->u.a.inbuffer); send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION, PKT_INT, c->remoteid, PKT_INT, c->localid, PKT_END); del234(ssh->channels, c); sfree(c); } }
245,301,482,448,712,900,000,000,000,000,000,000,000
None
null
[ "CWE-119" ]
CVE-2017-6542
The ssh_agent_channel_data function in PuTTY before 0.68 allows remote attackers to have unspecified impact via a large length value in an agent protocol message and leveraging the ability to connect to the Unix-domain socket representing the forwarded agent connection, which trigger a buffer overflow.
https://nvd.nist.gov/vuln/detail/CVE-2017-6542