is_vulnerable
bool
2 classes
func
stringlengths
28
484k
cwe
listlengths
1
2
project
stringclasses
592 values
commit_id
stringlengths
7
44
hash
stringlengths
34
39
big_vul_idx
int64
4.09k
189k
idx
int64
0
522k
cwe_description
stringclasses
81 values
false
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 ); }
[ "CWE-787" ]
savannah
f958c48ee431bef8d4d466b40c9cb2d4dbcb7791
173319081189597155474138387684978602892
178,056
211
The product writes data past the end, or before the beginning, of the intended buffer.
true
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 ); }
[ "CWE-787" ]
savannah
f958c48ee431bef8d4d466b40c9cb2d4dbcb7791
131877843141694356133309697518467244252
178,056
158,071
The product writes data past the end, or before the beginning, of the intended buffer.
false
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; }
[ "CWE-399" ]
dbus
7d65a3a6ed8815e34a99c680ac3869fde49dbbd4
293803507783746447357509233379751643676
178,058
212
This vulnerability category highlights issues in resource management where failures to properly release memory, file handles, or other resources can degrade system performance or enable denial-of-service conditions.
true
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; }
[ "CWE-399" ]
dbus
7d65a3a6ed8815e34a99c680ac3869fde49dbbd4
176712459114438620245064919145260257013
178,058
158,072
This vulnerability category highlights issues in resource management where failures to properly release memory, file handles, or other resources can degrade system performance or enable denial-of-service conditions.
false
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; }
[ "CWE-787" ]
savannah
e6699596af5c5d6f0ae0ea06e19df87dce088df8
328349556850502930530519513006179954778
178,059
213
The product writes data past the end, or before the beginning, of the intended buffer.
true
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; }
[ "CWE-787" ]
savannah
e6699596af5c5d6f0ae0ea06e19df87dce088df8
242836455535349747653527932796504023034
178,059
158,073
The product writes data past the end, or before the beginning, of the intended buffer.
false
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; }
[ "CWE-787" ]
savannah
7bbb91fbf47fc0775cc9705673caf0c47a81f94b
119798325318146814691558712066205414712
178,060
214
The product writes data past the end, or before the beginning, of the intended buffer.
true
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; }
[ "CWE-787" ]
savannah
7bbb91fbf47fc0775cc9705673caf0c47a81f94b
226909658136416070549978617553739875522
178,060
158,074
The product writes data past the end, or before the beginning, of the intended buffer.
false
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; }
[ "CWE-476" ]
poppler
5c9b08a875b07853be6c44e43ff5f7f059df666a
180050936886598415271458736244884709418
178,062
215
The product dereferences a pointer that it expects to be valid but is NULL.
true
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; }
[ "CWE-476" ]
poppler
5c9b08a875b07853be6c44e43ff5f7f059df666a
4674050423349651754578522671885372804
178,062
158,075
The product dereferences a pointer that it expects to be valid but is NULL.
false
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; }
[ "CWE-119" ]
savannah
94e01571507835ff59dd8ce2a0b56a4b566965a4
85463602567582995767126053202641542542
178,063
216
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
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; }
[ "CWE-119" ]
savannah
94e01571507835ff59dd8ce2a0b56a4b566965a4
254772284669524418106772745534242359013
178,063
158,076
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
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; }
[ "CWE-119" ]
savannah
59eb9f8cfe7d1df379a2318316d1f04f80fba54a
176444419672545527315649492039587951909
178,069
217
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
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; }
[ "CWE-119" ]
savannah
59eb9f8cfe7d1df379a2318316d1f04f80fba54a
179208058990458728256307235003655306316
178,069
158,077
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
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; }
[ "CWE-119" ]
ghostscript
39b1e54b2968620723bf32e96764c88797714879
334604983653907615489271299004330168271
178,070
218
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
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; }
[ "CWE-119" ]
ghostscript
39b1e54b2968620723bf32e96764c88797714879
59940488774012010522720030779464241139
178,070
158,078
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
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; }
[ "CWE-119" ]
haproxy
3f0e1ec70173593f4c2b3681b26c04a4ed5fc588
197791135802871490452896068201538076195
178,071
219
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
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; }
[ "CWE-119" ]
haproxy
3f0e1ec70173593f4c2b3681b26c04a4ed5fc588
78211051505197321979153553871570809611
178,071
158,079
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
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; }
[ "CWE-119" ]
libXvMC
2cd95e7da8367cccdcdd5c9b160012d1dec5cbdb
225773238597816987128397211875317401076
178,085
223
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
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; }
[ "CWE-119" ]
libXvMC
2cd95e7da8367cccdcdd5c9b160012d1dec5cbdb
134961230573839871155626004817245283432
178,085
158,083
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
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; }
[ "CWE-190" ]
libXfixes
61c1039ee23a2d1de712843bed3480654d7ef42e
306933036253550523681529656378317307640
178,094
231
The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number.
true
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; }
[ "CWE-190" ]
libXfixes
61c1039ee23a2d1de712843bed3480654d7ef42e
304152935311185577079726690952840617920
178,094
158,091
The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number.
false
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; }
[ "CWE-476" ]
libav
136f55207521f0b03194ef5b55ba70f1635d6aee
111292629842222758487961407224615725800
178,099
232
The product dereferences a pointer that it expects to be valid but is NULL.
true
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; }
[ "CWE-476" ]
libav
136f55207521f0b03194ef5b55ba70f1635d6aee
104050017138290810308559131153118862587
178,099
158,092
The product dereferences a pointer that it expects to be valid but is NULL.
false
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); } }
[ "CWE-119" ]
tartarus
4ff22863d895cb7ebfced4cf923a012a614adaa8
325909590182680995779527787302149618683
178,103
233
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
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); } }
[ "CWE-119" ]
tartarus
4ff22863d895cb7ebfced4cf923a012a614adaa8
245301482448712873104203214442039471825
178,103
158,093
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl, X509 **pissuer, int *pscore, unsigned int *preasons, STACK_OF(X509_CRL) *crls) { int i, crl_score, best_score = *pscore; unsigned int reasons, best_reasons = 0; X509 *x = ctx->current_cert; X509_CRL *crl, *best_crl = NULL; X509 *crl_issuer = NULL, *best_crl_issuer = NULL; for (i = 0; i < sk_X509_CRL_num(crls); i++) { crl = sk_X509_CRL_value(crls, i); reasons = *preasons; crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x); if (crl_score < best_score) continue; /* If current CRL is equivalent use it if it is newer */ if (crl_score == best_score) { int day, sec; if (ASN1_TIME_diff(&day, &sec, X509_CRL_get_lastUpdate(best_crl), X509_CRL_get_lastUpdate(crl)) == 0) continue; /* * ASN1_TIME_diff never returns inconsistent signs for |day| * and |sec|. */ if (day <= 0 && sec <= 0) continue; } best_crl = crl; best_crl_issuer = crl_issuer; best_score = crl_score; best_reasons = reasons; } if (best_crl) { if (*pcrl) X509_CRL_free(*pcrl); *pcrl = best_crl; *pissuer = best_crl_issuer; *pscore = best_score; *preasons = best_reasons; CRYPTO_add(&best_crl->references, 1, CRYPTO_LOCK_X509_CRL); if (*pdcrl) { X509_CRL_free(*pdcrl); *pdcrl = NULL; } get_delta_sk(ctx, pdcrl, pscore, best_crl, crls); } if (best_score >= CRL_SCORE_VALID) return 1; return 0; }
[ "CWE-476" ]
openssl
6e629b5be45face20b4ca71c4fcbfed78b864a2e
135793188300012979952739633768625629213
178,112
234
The product dereferences a pointer that it expects to be valid but is NULL.
true
static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl, X509 **pissuer, int *pscore, unsigned int *preasons, STACK_OF(X509_CRL) *crls) { int i, crl_score, best_score = *pscore; unsigned int reasons, best_reasons = 0; X509 *x = ctx->current_cert; X509_CRL *crl, *best_crl = NULL; X509 *crl_issuer = NULL, *best_crl_issuer = NULL; for (i = 0; i < sk_X509_CRL_num(crls); i++) { crl = sk_X509_CRL_value(crls, i); reasons = *preasons; crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x); if (crl_score < best_score || crl_score == 0) continue; /* If current CRL is equivalent use it if it is newer */ if (crl_score == best_score && best_crl != NULL) { int day, sec; if (ASN1_TIME_diff(&day, &sec, X509_CRL_get_lastUpdate(best_crl), X509_CRL_get_lastUpdate(crl)) == 0) continue; /* * ASN1_TIME_diff never returns inconsistent signs for |day| * and |sec|. */ if (day <= 0 && sec <= 0) continue; } best_crl = crl; best_crl_issuer = crl_issuer; best_score = crl_score; best_reasons = reasons; } if (best_crl) { if (*pcrl) X509_CRL_free(*pcrl); *pcrl = best_crl; *pissuer = best_crl_issuer; *pscore = best_score; *preasons = best_reasons; CRYPTO_add(&best_crl->references, 1, CRYPTO_LOCK_X509_CRL); if (*pdcrl) { X509_CRL_free(*pdcrl); *pdcrl = NULL; } get_delta_sk(ctx, pdcrl, pscore, best_crl, crls); } if (best_score >= CRL_SCORE_VALID) return 1; return 0; }
[ "CWE-476" ]
openssl
6e629b5be45face20b4ca71c4fcbfed78b864a2e
282685569527671381524876751964696218430
178,112
158,094
The product dereferences a pointer that it expects to be valid but is NULL.
false
vcard_apdu_new(unsigned char *raw_apdu, int len, vcard_7816_status_t *status) { VCardAPDU *new_apdu; *status = VCARD7816_STATUS_EXC_ERROR_MEMORY_FAILURE; if (len < 4) { *status = VCARD7816_STATUS_ERROR_WRONG_LENGTH; return NULL; } new_apdu = g_new(VCardAPDU, 1); new_apdu->a_data = g_memdup(raw_apdu, len); new_apdu->a_len = len; *status = vcard_apdu_set_class(new_apdu); if (*status != VCARD7816_STATUS_SUCCESS) { g_free(new_apdu); return NULL; } *status = vcard_apdu_set_length(new_apdu); if (*status != VCARD7816_STATUS_SUCCESS) { g_free(new_apdu); new_apdu = NULL; } return new_apdu; }
[ "CWE-772" ]
spice
9113dc6a303604a2d9812ac70c17d076ef11886c
336092549544277958136877844795822151529
178,113
235
The product does not release a resource after its effective lifetime has ended, i.e., after the resource is no longer needed.
true
vcard_apdu_new(unsigned char *raw_apdu, int len, vcard_7816_status_t *status) { VCardAPDU *new_apdu; *status = VCARD7816_STATUS_EXC_ERROR_MEMORY_FAILURE; if (len < 4) { *status = VCARD7816_STATUS_ERROR_WRONG_LENGTH; return NULL; } new_apdu = g_new(VCardAPDU, 1); new_apdu->a_data = g_memdup(raw_apdu, len); new_apdu->a_len = len; *status = vcard_apdu_set_class(new_apdu); if (*status != VCARD7816_STATUS_SUCCESS) { vcard_apdu_delete(new_apdu); return NULL; } *status = vcard_apdu_set_length(new_apdu); if (*status != VCARD7816_STATUS_SUCCESS) { vcard_apdu_delete(new_apdu); new_apdu = NULL; } return new_apdu; }
[ "CWE-772" ]
spice
9113dc6a303604a2d9812ac70c17d076ef11886c
81348847311456679355137118764174459124
178,113
158,095
The product does not release a resource after its effective lifetime has ended, i.e., after the resource is no longer needed.
false
int vrend_create_shader(struct vrend_context *ctx, uint32_t handle, const struct pipe_stream_output_info *so_info, const char *shd_text, uint32_t offlen, uint32_t num_tokens, uint32_t type, uint32_t pkt_length) { struct vrend_shader_selector *sel = NULL; int ret_handle; bool new_shader = true, long_shader = false; bool finished = false; int ret; if (type > PIPE_SHADER_GEOMETRY) return EINVAL; if (offlen & VIRGL_OBJ_SHADER_OFFSET_CONT) new_shader = false; else if (((offlen + 3) / 4) > pkt_length) long_shader = true; /* if we have an in progress one - don't allow a new shader of that type or a different handle. */ if (ctx->sub->long_shader_in_progress_handle[type]) { if (new_shader == true) return EINVAL; if (handle != ctx->sub->long_shader_in_progress_handle[type]) return EINVAL; } if (new_shader) { sel = vrend_create_shader_state(ctx, so_info, type); if (sel == NULL) return ENOMEM; if (long_shader) { sel->buf_len = ((offlen + 3) / 4) * 4; /* round up buffer size */ sel->tmp_buf = malloc(sel->buf_len); if (!sel->tmp_buf) { ret = ENOMEM; goto error; } memcpy(sel->tmp_buf, shd_text, pkt_length * 4); sel->buf_offset = pkt_length * 4; ctx->sub->long_shader_in_progress_handle[type] = handle; } else finished = true; } else { sel = vrend_object_lookup(ctx->sub->object_hash, handle, VIRGL_OBJECT_SHADER); if (!sel) { fprintf(stderr, "got continuation without original shader %d\n", handle); ret = EINVAL; goto error; } offlen &= ~VIRGL_OBJ_SHADER_OFFSET_CONT; if (offlen != sel->buf_offset) { fprintf(stderr, "Got mismatched shader continuation %d vs %d\n", offlen, sel->buf_offset); ret = EINVAL; goto error; } if ((pkt_length * 4 + sel->buf_offset) > sel->buf_len) { fprintf(stderr, "Got too large shader continuation %d vs %d\n", pkt_length * 4 + sel->buf_offset, sel->buf_len); shd_text = sel->tmp_buf; } } if (finished) { struct tgsi_token *tokens; tokens = calloc(num_tokens + 10, sizeof(struct tgsi_token)); if (!tokens) { ret = ENOMEM; goto error; } if (vrend_dump_shaders) fprintf(stderr,"shader\n%s\n", shd_text); if (!tgsi_text_translate((const char *)shd_text, tokens, num_tokens + 10)) { free(tokens); ret = EINVAL; goto error; } if (vrend_finish_shader(ctx, sel, tokens)) { free(tokens); ret = EINVAL; goto error; } else { free(sel->tmp_buf); sel->tmp_buf = NULL; } free(tokens); ctx->sub->long_shader_in_progress_handle[type] = 0; } if (new_shader) { ret_handle = vrend_renderer_object_insert(ctx, sel, sizeof(*sel), handle, VIRGL_OBJECT_SHADER); if (ret_handle == 0) { ret = ENOMEM; goto error; } } return 0; error: if (new_shader) vrend_destroy_shader_selector(sel); else vrend_renderer_object_destroy(ctx, handle); return ret; }
[ "CWE-190" ]
virglrenderer
93761787b29f37fa627dea9082cdfc1a1ec608d6
277560631509583395850123120925257608076
178,117
238
The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number.
true
int vrend_create_shader(struct vrend_context *ctx, uint32_t handle, const struct pipe_stream_output_info *so_info, const char *shd_text, uint32_t offlen, uint32_t num_tokens, uint32_t type, uint32_t pkt_length) { struct vrend_shader_selector *sel = NULL; int ret_handle; bool new_shader = true, long_shader = false; bool finished = false; int ret; if (type > PIPE_SHADER_GEOMETRY) return EINVAL; if (offlen & VIRGL_OBJ_SHADER_OFFSET_CONT) new_shader = false; else if (((offlen + 3) / 4) > pkt_length) long_shader = true; /* if we have an in progress one - don't allow a new shader of that type or a different handle. */ if (ctx->sub->long_shader_in_progress_handle[type]) { if (new_shader == true) return EINVAL; if (handle != ctx->sub->long_shader_in_progress_handle[type]) return EINVAL; } if (new_shader) { sel = vrend_create_shader_state(ctx, so_info, type); if (sel == NULL) return ENOMEM; if (long_shader) { sel->buf_len = ((offlen + 3) / 4) * 4; /* round up buffer size */ sel->tmp_buf = malloc(sel->buf_len); if (!sel->tmp_buf) { ret = ENOMEM; goto error; } memcpy(sel->tmp_buf, shd_text, pkt_length * 4); sel->buf_offset = pkt_length * 4; ctx->sub->long_shader_in_progress_handle[type] = handle; } else finished = true; } else { sel = vrend_object_lookup(ctx->sub->object_hash, handle, VIRGL_OBJECT_SHADER); if (!sel) { fprintf(stderr, "got continuation without original shader %d\n", handle); ret = EINVAL; goto error; } offlen &= ~VIRGL_OBJ_SHADER_OFFSET_CONT; if (offlen != sel->buf_offset) { fprintf(stderr, "Got mismatched shader continuation %d vs %d\n", offlen, sel->buf_offset); ret = EINVAL; goto error; } /*make sure no overflow */ if (pkt_length * 4 < pkt_length || pkt_length * 4 + sel->buf_offset < pkt_length * 4 || pkt_length * 4 + sel->buf_offset < sel->buf_offset) { ret = EINVAL; goto error; } if ((pkt_length * 4 + sel->buf_offset) > sel->buf_len) { fprintf(stderr, "Got too large shader continuation %d vs %d\n", pkt_length * 4 + sel->buf_offset, sel->buf_len); shd_text = sel->tmp_buf; } } if (finished) { struct tgsi_token *tokens; tokens = calloc(num_tokens + 10, sizeof(struct tgsi_token)); if (!tokens) { ret = ENOMEM; goto error; } if (vrend_dump_shaders) fprintf(stderr,"shader\n%s\n", shd_text); if (!tgsi_text_translate((const char *)shd_text, tokens, num_tokens + 10)) { free(tokens); ret = EINVAL; goto error; } if (vrend_finish_shader(ctx, sel, tokens)) { free(tokens); ret = EINVAL; goto error; } else { free(sel->tmp_buf); sel->tmp_buf = NULL; } free(tokens); ctx->sub->long_shader_in_progress_handle[type] = 0; } if (new_shader) { ret_handle = vrend_renderer_object_insert(ctx, sel, sizeof(*sel), handle, VIRGL_OBJECT_SHADER); if (ret_handle == 0) { ret = ENOMEM; goto error; } } return 0; error: if (new_shader) vrend_destroy_shader_selector(sel); else vrend_renderer_object_destroy(ctx, handle); return ret; }
[ "CWE-190" ]
virglrenderer
93761787b29f37fa627dea9082cdfc1a1ec608d6
24883819423866269393027879732805252268
178,117
158,098
The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number.
false
static struct vrend_linked_shader_program *add_shader_program(struct vrend_context *ctx, struct vrend_shader *vs, struct vrend_shader *fs, struct vrend_shader *gs) { struct vrend_linked_shader_program *sprog = CALLOC_STRUCT(vrend_linked_shader_program); char name[16]; int i; GLuint prog_id; GLint lret; int id; int last_shader; if (!sprog) return NULL; /* need to rewrite VS code to add interpolation params */ if ((gs && gs->compiled_fs_id != fs->id) || (!gs && vs->compiled_fs_id != fs->id)) { bool ret; if (gs) vrend_patch_vertex_shader_interpolants(gs->glsl_prog, &gs->sel->sinfo, &fs->sel->sinfo, true, fs->key.flatshade); else vrend_patch_vertex_shader_interpolants(vs->glsl_prog, &vs->sel->sinfo, &fs->sel->sinfo, false, fs->key.flatshade); ret = vrend_compile_shader(ctx, gs ? gs : vs); if (ret == false) { glDeleteShader(gs ? gs->id : vs->id); free(sprog); return NULL; } if (gs) gs->compiled_fs_id = fs->id; else vs->compiled_fs_id = fs->id; } prog_id = glCreateProgram(); glAttachShader(prog_id, vs->id); if (gs) { if (gs->id > 0) glAttachShader(prog_id, gs->id); set_stream_out_varyings(prog_id, &gs->sel->sinfo); } else set_stream_out_varyings(prog_id, &vs->sel->sinfo); glAttachShader(prog_id, fs->id); if (fs->sel->sinfo.num_outputs > 1) { if (util_blend_state_is_dual(&ctx->sub->blend_state, 0)) { glBindFragDataLocationIndexed(prog_id, 0, 0, "fsout_c0"); glBindFragDataLocationIndexed(prog_id, 0, 1, "fsout_c1"); sprog->dual_src_linked = true; } else { glBindFragDataLocationIndexed(prog_id, 0, 0, "fsout_c0"); glBindFragDataLocationIndexed(prog_id, 1, 0, "fsout_c1"); sprog->dual_src_linked = false; } } else sprog->dual_src_linked = false; if (vrend_state.have_vertex_attrib_binding) { uint32_t mask = vs->sel->sinfo.attrib_input_mask; while (mask) { i = u_bit_scan(&mask); snprintf(name, 10, "in_%d", i); glBindAttribLocation(prog_id, i, name); } } glLinkProgram(prog_id); glGetProgramiv(prog_id, GL_LINK_STATUS, &lret); if (lret == GL_FALSE) { char infolog[65536]; int len; glGetProgramInfoLog(prog_id, 65536, &len, infolog); fprintf(stderr,"got error linking\n%s\n", infolog); /* dump shaders */ report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_SHADER, 0); fprintf(stderr,"vert shader: %d GLSL\n%s\n", vs->id, vs->glsl_prog); if (gs) fprintf(stderr,"geom shader: %d GLSL\n%s\n", gs->id, gs->glsl_prog); fprintf(stderr,"frag shader: %d GLSL\n%s\n", fs->id, fs->glsl_prog); glDeleteProgram(prog_id); return NULL; } sprog->ss[PIPE_SHADER_FRAGMENT] = fs; sprog->ss[PIPE_SHADER_GEOMETRY] = gs; list_add(&sprog->sl[PIPE_SHADER_VERTEX], &vs->programs); list_add(&sprog->sl[PIPE_SHADER_FRAGMENT], &fs->programs); if (gs) list_add(&sprog->sl[PIPE_SHADER_GEOMETRY], &gs->programs); last_shader = gs ? PIPE_SHADER_GEOMETRY : PIPE_SHADER_FRAGMENT; sprog->id = prog_id; list_addtail(&sprog->head, &ctx->sub->programs); if (fs->key.pstipple_tex) sprog->fs_stipple_loc = glGetUniformLocation(prog_id, "pstipple_sampler"); else sprog->fs_stipple_loc = -1; sprog->vs_ws_adjust_loc = glGetUniformLocation(prog_id, "winsys_adjust"); for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) { if (sprog->ss[id]->sel->sinfo.samplers_used_mask) { uint32_t mask = sprog->ss[id]->sel->sinfo.samplers_used_mask; int nsamp = util_bitcount(sprog->ss[id]->sel->sinfo.samplers_used_mask); int index; sprog->shadow_samp_mask[id] = sprog->ss[id]->sel->sinfo.shadow_samp_mask; if (sprog->ss[id]->sel->sinfo.shadow_samp_mask) { sprog->shadow_samp_mask_locs[id] = calloc(nsamp, sizeof(uint32_t)); sprog->shadow_samp_add_locs[id] = calloc(nsamp, sizeof(uint32_t)); } else { sprog->shadow_samp_mask_locs[id] = sprog->shadow_samp_add_locs[id] = NULL; } sprog->samp_locs[id] = calloc(nsamp, sizeof(uint32_t)); if (sprog->samp_locs[id]) { const char *prefix = pipe_shader_to_prefix(id); index = 0; while(mask) { i = u_bit_scan(&mask); snprintf(name, 10, "%ssamp%d", prefix, i); sprog->samp_locs[id][index] = glGetUniformLocation(prog_id, name); if (sprog->ss[id]->sel->sinfo.shadow_samp_mask & (1 << i)) { snprintf(name, 14, "%sshadmask%d", prefix, i); sprog->shadow_samp_mask_locs[id][index] = glGetUniformLocation(prog_id, name); snprintf(name, 14, "%sshadadd%d", prefix, i); sprog->shadow_samp_add_locs[id][index] = glGetUniformLocation(prog_id, name); } index++; } } } else { sprog->samp_locs[id] = NULL; sprog->shadow_samp_mask_locs[id] = NULL; sprog->shadow_samp_add_locs[id] = NULL; sprog->shadow_samp_mask[id] = 0; } sprog->samplers_used_mask[id] = sprog->ss[id]->sel->sinfo.samplers_used_mask; } for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) { if (sprog->ss[id]->sel->sinfo.num_consts) { sprog->const_locs[id] = calloc(sprog->ss[id]->sel->sinfo.num_consts, sizeof(uint32_t)); if (sprog->const_locs[id]) { const char *prefix = pipe_shader_to_prefix(id); for (i = 0; i < sprog->ss[id]->sel->sinfo.num_consts; i++) { snprintf(name, 16, "%sconst0[%d]", prefix, i); sprog->const_locs[id][i] = glGetUniformLocation(prog_id, name); } } } else sprog->const_locs[id] = NULL; } if (!vrend_state.have_vertex_attrib_binding) { if (vs->sel->sinfo.num_inputs) { sprog->attrib_locs = calloc(vs->sel->sinfo.num_inputs, sizeof(uint32_t)); if (sprog->attrib_locs) { for (i = 0; i < vs->sel->sinfo.num_inputs; i++) { snprintf(name, 10, "in_%d", i); sprog->attrib_locs[i] = glGetAttribLocation(prog_id, name); } } } else sprog->attrib_locs = NULL; } for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) { if (sprog->ss[id]->sel->sinfo.num_ubos) { const char *prefix = pipe_shader_to_prefix(id); sprog->ubo_locs[id] = calloc(sprog->ss[id]->sel->sinfo.num_ubos, sizeof(uint32_t)); for (i = 0; i < sprog->ss[id]->sel->sinfo.num_ubos; i++) { snprintf(name, 16, "%subo%d", prefix, i + 1); sprog->ubo_locs[id][i] = glGetUniformBlockIndex(prog_id, name); } } else sprog->ubo_locs[id] = NULL; } if (vs->sel->sinfo.num_ucp) { for (i = 0; i < vs->sel->sinfo.num_ucp; i++) { snprintf(name, 10, "clipp[%d]", i); sprog->clip_locs[i] = glGetUniformLocation(prog_id, name); } } return sprog; }
[ "CWE-772" ]
virglrenderer
a2f12a1b0f95b13b6f8dc3d05d7b74b4386394e4
323217311057867578248239667496178090457
178,118
239
The product does not release a resource after its effective lifetime has ended, i.e., after the resource is no longer needed.
true
static struct vrend_linked_shader_program *add_shader_program(struct vrend_context *ctx, struct vrend_shader *vs, struct vrend_shader *fs, struct vrend_shader *gs) { struct vrend_linked_shader_program *sprog = CALLOC_STRUCT(vrend_linked_shader_program); char name[16]; int i; GLuint prog_id; GLint lret; int id; int last_shader; if (!sprog) return NULL; /* need to rewrite VS code to add interpolation params */ if ((gs && gs->compiled_fs_id != fs->id) || (!gs && vs->compiled_fs_id != fs->id)) { bool ret; if (gs) vrend_patch_vertex_shader_interpolants(gs->glsl_prog, &gs->sel->sinfo, &fs->sel->sinfo, true, fs->key.flatshade); else vrend_patch_vertex_shader_interpolants(vs->glsl_prog, &vs->sel->sinfo, &fs->sel->sinfo, false, fs->key.flatshade); ret = vrend_compile_shader(ctx, gs ? gs : vs); if (ret == false) { glDeleteShader(gs ? gs->id : vs->id); free(sprog); return NULL; } if (gs) gs->compiled_fs_id = fs->id; else vs->compiled_fs_id = fs->id; } prog_id = glCreateProgram(); glAttachShader(prog_id, vs->id); if (gs) { if (gs->id > 0) glAttachShader(prog_id, gs->id); set_stream_out_varyings(prog_id, &gs->sel->sinfo); } else set_stream_out_varyings(prog_id, &vs->sel->sinfo); glAttachShader(prog_id, fs->id); if (fs->sel->sinfo.num_outputs > 1) { if (util_blend_state_is_dual(&ctx->sub->blend_state, 0)) { glBindFragDataLocationIndexed(prog_id, 0, 0, "fsout_c0"); glBindFragDataLocationIndexed(prog_id, 0, 1, "fsout_c1"); sprog->dual_src_linked = true; } else { glBindFragDataLocationIndexed(prog_id, 0, 0, "fsout_c0"); glBindFragDataLocationIndexed(prog_id, 1, 0, "fsout_c1"); sprog->dual_src_linked = false; } } else sprog->dual_src_linked = false; if (vrend_state.have_vertex_attrib_binding) { uint32_t mask = vs->sel->sinfo.attrib_input_mask; while (mask) { i = u_bit_scan(&mask); snprintf(name, 10, "in_%d", i); glBindAttribLocation(prog_id, i, name); } } glLinkProgram(prog_id); glGetProgramiv(prog_id, GL_LINK_STATUS, &lret); if (lret == GL_FALSE) { char infolog[65536]; int len; glGetProgramInfoLog(prog_id, 65536, &len, infolog); fprintf(stderr,"got error linking\n%s\n", infolog); /* dump shaders */ report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_SHADER, 0); fprintf(stderr,"vert shader: %d GLSL\n%s\n", vs->id, vs->glsl_prog); if (gs) fprintf(stderr,"geom shader: %d GLSL\n%s\n", gs->id, gs->glsl_prog); fprintf(stderr,"frag shader: %d GLSL\n%s\n", fs->id, fs->glsl_prog); glDeleteProgram(prog_id); free(sprog); return NULL; } sprog->ss[PIPE_SHADER_FRAGMENT] = fs; sprog->ss[PIPE_SHADER_GEOMETRY] = gs; list_add(&sprog->sl[PIPE_SHADER_VERTEX], &vs->programs); list_add(&sprog->sl[PIPE_SHADER_FRAGMENT], &fs->programs); if (gs) list_add(&sprog->sl[PIPE_SHADER_GEOMETRY], &gs->programs); last_shader = gs ? PIPE_SHADER_GEOMETRY : PIPE_SHADER_FRAGMENT; sprog->id = prog_id; list_addtail(&sprog->head, &ctx->sub->programs); if (fs->key.pstipple_tex) sprog->fs_stipple_loc = glGetUniformLocation(prog_id, "pstipple_sampler"); else sprog->fs_stipple_loc = -1; sprog->vs_ws_adjust_loc = glGetUniformLocation(prog_id, "winsys_adjust"); for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) { if (sprog->ss[id]->sel->sinfo.samplers_used_mask) { uint32_t mask = sprog->ss[id]->sel->sinfo.samplers_used_mask; int nsamp = util_bitcount(sprog->ss[id]->sel->sinfo.samplers_used_mask); int index; sprog->shadow_samp_mask[id] = sprog->ss[id]->sel->sinfo.shadow_samp_mask; if (sprog->ss[id]->sel->sinfo.shadow_samp_mask) { sprog->shadow_samp_mask_locs[id] = calloc(nsamp, sizeof(uint32_t)); sprog->shadow_samp_add_locs[id] = calloc(nsamp, sizeof(uint32_t)); } else { sprog->shadow_samp_mask_locs[id] = sprog->shadow_samp_add_locs[id] = NULL; } sprog->samp_locs[id] = calloc(nsamp, sizeof(uint32_t)); if (sprog->samp_locs[id]) { const char *prefix = pipe_shader_to_prefix(id); index = 0; while(mask) { i = u_bit_scan(&mask); snprintf(name, 10, "%ssamp%d", prefix, i); sprog->samp_locs[id][index] = glGetUniformLocation(prog_id, name); if (sprog->ss[id]->sel->sinfo.shadow_samp_mask & (1 << i)) { snprintf(name, 14, "%sshadmask%d", prefix, i); sprog->shadow_samp_mask_locs[id][index] = glGetUniformLocation(prog_id, name); snprintf(name, 14, "%sshadadd%d", prefix, i); sprog->shadow_samp_add_locs[id][index] = glGetUniformLocation(prog_id, name); } index++; } } } else { sprog->samp_locs[id] = NULL; sprog->shadow_samp_mask_locs[id] = NULL; sprog->shadow_samp_add_locs[id] = NULL; sprog->shadow_samp_mask[id] = 0; } sprog->samplers_used_mask[id] = sprog->ss[id]->sel->sinfo.samplers_used_mask; } for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) { if (sprog->ss[id]->sel->sinfo.num_consts) { sprog->const_locs[id] = calloc(sprog->ss[id]->sel->sinfo.num_consts, sizeof(uint32_t)); if (sprog->const_locs[id]) { const char *prefix = pipe_shader_to_prefix(id); for (i = 0; i < sprog->ss[id]->sel->sinfo.num_consts; i++) { snprintf(name, 16, "%sconst0[%d]", prefix, i); sprog->const_locs[id][i] = glGetUniformLocation(prog_id, name); } } } else sprog->const_locs[id] = NULL; } if (!vrend_state.have_vertex_attrib_binding) { if (vs->sel->sinfo.num_inputs) { sprog->attrib_locs = calloc(vs->sel->sinfo.num_inputs, sizeof(uint32_t)); if (sprog->attrib_locs) { for (i = 0; i < vs->sel->sinfo.num_inputs; i++) { snprintf(name, 10, "in_%d", i); sprog->attrib_locs[i] = glGetAttribLocation(prog_id, name); } } } else sprog->attrib_locs = NULL; } for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) { if (sprog->ss[id]->sel->sinfo.num_ubos) { const char *prefix = pipe_shader_to_prefix(id); sprog->ubo_locs[id] = calloc(sprog->ss[id]->sel->sinfo.num_ubos, sizeof(uint32_t)); for (i = 0; i < sprog->ss[id]->sel->sinfo.num_ubos; i++) { snprintf(name, 16, "%subo%d", prefix, i + 1); sprog->ubo_locs[id][i] = glGetUniformBlockIndex(prog_id, name); } } else sprog->ubo_locs[id] = NULL; } if (vs->sel->sinfo.num_ucp) { for (i = 0; i < vs->sel->sinfo.num_ucp; i++) { snprintf(name, 10, "clipp[%d]", i); sprog->clip_locs[i] = glGetUniformLocation(prog_id, name); } } return sprog; }
[ "CWE-772" ]
virglrenderer
a2f12a1b0f95b13b6f8dc3d05d7b74b4386394e4
68470240422616925679336488813198975337
178,118
158,099
The product does not release a resource after its effective lifetime has ended, i.e., after the resource is no longer needed.
false
void vrend_renderer_context_destroy(uint32_t handle) { struct vrend_decode_ctx *ctx; bool ret; if (handle >= VREND_MAX_CTX) return; ctx = dec_ctx[handle]; if (!ctx) return; vrend_hw_switch_context(dec_ctx[0]->grctx, true); }
[ "CWE-476" ]
virglrenderer
0a5dff15912207b83018485f83e067474e818bab
248536757234533019908341843286492380403
178,121
240
The product dereferences a pointer that it expects to be valid but is NULL.
true
void vrend_renderer_context_destroy(uint32_t handle) { struct vrend_decode_ctx *ctx; bool ret; if (handle >= VREND_MAX_CTX) return; /* never destroy context 0 here, it will be destroyed in vrend_decode_reset()*/ if (handle == 0) { return; } ctx = dec_ctx[handle]; if (!ctx) return; vrend_hw_switch_context(dec_ctx[0]->grctx, true); }
[ "CWE-476" ]
virglrenderer
0a5dff15912207b83018485f83e067474e818bab
154473925672822272321889471335487355877
178,121
158,100
The product dereferences a pointer that it expects to be valid but is NULL.
false
static boolean parse_identifier( const char **pcur, char *ret ) { const char *cur = *pcur; int i = 0; if (is_alpha_underscore( cur )) { ret[i++] = *cur++; while (is_alpha_underscore( cur ) || is_digit( cur )) ret[i++] = *cur++; ret[i++] = '\0'; *pcur = cur; return TRUE; /* Parse floating point. */ static boolean parse_float( const char **pcur, float *val ) { const char *cur = *pcur; boolean integral_part = FALSE; boolean fractional_part = FALSE; if (*cur == '0' && *(cur + 1) == 'x') { union fi fi; fi.ui = strtoul(cur, NULL, 16); *val = fi.f; cur += 10; goto out; } *val = (float) atof( cur ); if (*cur == '-' || *cur == '+') cur++; if (is_digit( cur )) { cur++; integral_part = TRUE; while (is_digit( cur )) cur++; } if (*cur == '.') { cur++; if (is_digit( cur )) { cur++; fractional_part = TRUE; while (is_digit( cur )) cur++; } } if (!integral_part && !fractional_part) return FALSE; if (uprcase( *cur ) == 'E') { cur++; if (*cur == '-' || *cur == '+') cur++; if (is_digit( cur )) { cur++; while (is_digit( cur )) cur++; } else return FALSE; } out: *pcur = cur; return TRUE; } static boolean parse_double( const char **pcur, uint32_t *val0, uint32_t *val1) { const char *cur = *pcur; union { double dval; uint32_t uval[2]; } v; v.dval = strtod(cur, (char**)pcur); if (*pcur == cur) return FALSE; *val0 = v.uval[0]; *val1 = v.uval[1]; return TRUE; } struct translate_ctx { const char *text; const char *cur; struct tgsi_token *tokens; struct tgsi_token *tokens_cur; struct tgsi_token *tokens_end; struct tgsi_header *header; unsigned processor : 4; unsigned implied_array_size : 6; unsigned num_immediates; }; static void report_error(struct translate_ctx *ctx, const char *format, ...) { va_list args; int line = 1; int column = 1; const char *itr = ctx->text; debug_printf("\nTGSI asm error: "); va_start(args, format); _debug_vprintf(format, args); va_end(args); while (itr != ctx->cur) { if (*itr == '\n') { column = 1; ++line; } ++column; ++itr; } debug_printf(" [%d : %d] \n", line, column); } /* Parse shader header. * Return TRUE for one of the following headers. * FRAG * GEOM * VERT */ static boolean parse_header( struct translate_ctx *ctx ) { uint processor; if (str_match_nocase_whole( &ctx->cur, "FRAG" )) processor = TGSI_PROCESSOR_FRAGMENT; else if (str_match_nocase_whole( &ctx->cur, "VERT" )) processor = TGSI_PROCESSOR_VERTEX; else if (str_match_nocase_whole( &ctx->cur, "GEOM" )) processor = TGSI_PROCESSOR_GEOMETRY; else if (str_match_nocase_whole( &ctx->cur, "TESS_CTRL" )) processor = TGSI_PROCESSOR_TESS_CTRL; else if (str_match_nocase_whole( &ctx->cur, "TESS_EVAL" )) processor = TGSI_PROCESSOR_TESS_EVAL; else if (str_match_nocase_whole( &ctx->cur, "COMP" )) processor = TGSI_PROCESSOR_COMPUTE; else { report_error( ctx, "Unknown header" ); return FALSE; } if (ctx->tokens_cur >= ctx->tokens_end) return FALSE; ctx->header = (struct tgsi_header *) ctx->tokens_cur++; *ctx->header = tgsi_build_header(); if (ctx->tokens_cur >= ctx->tokens_end) return FALSE; *(struct tgsi_processor *) ctx->tokens_cur++ = tgsi_build_processor( processor, ctx->header ); ctx->processor = processor; return TRUE; } static boolean parse_label( struct translate_ctx *ctx, uint *val ) { const char *cur = ctx->cur; if (parse_uint( &cur, val )) { eat_opt_white( &cur ); if (*cur == ':') { cur++; ctx->cur = cur; return TRUE; } } return FALSE; } static boolean parse_file( const char **pcur, uint *file ) { uint i; for (i = 0; i < TGSI_FILE_COUNT; i++) { const char *cur = *pcur; if (str_match_nocase_whole( &cur, tgsi_file_name(i) )) { *pcur = cur; *file = i; return TRUE; } } return FALSE; } static boolean parse_opt_writemask( struct translate_ctx *ctx, uint *writemask ) { const char *cur; cur = ctx->cur; eat_opt_white( &cur ); if (*cur == '.') { cur++; *writemask = TGSI_WRITEMASK_NONE; eat_opt_white( &cur ); if (uprcase( *cur ) == 'X') { cur++; *writemask |= TGSI_WRITEMASK_X; } if (uprcase( *cur ) == 'Y') { cur++; *writemask |= TGSI_WRITEMASK_Y; } if (uprcase( *cur ) == 'Z') { cur++; *writemask |= TGSI_WRITEMASK_Z; } if (uprcase( *cur ) == 'W') { cur++; *writemask |= TGSI_WRITEMASK_W; } if (*writemask == TGSI_WRITEMASK_NONE) { report_error( ctx, "Writemask expected" ); return FALSE; } ctx->cur = cur; } else { *writemask = TGSI_WRITEMASK_XYZW; } return TRUE; } /* <register_file_bracket> ::= <file> `[' */ static boolean parse_register_file_bracket( struct translate_ctx *ctx, uint *file ) { if (!parse_file( &ctx->cur, file )) { report_error( ctx, "Unknown register file" ); return FALSE; } eat_opt_white( &ctx->cur ); if (*ctx->cur != '[') { report_error( ctx, "Expected `['" ); return FALSE; } ctx->cur++; return TRUE; } /* <register_file_bracket_index> ::= <register_file_bracket> <uint> */ static boolean parse_register_file_bracket_index( struct translate_ctx *ctx, uint *file, int *index ) { uint uindex; if (!parse_register_file_bracket( ctx, file )) return FALSE; eat_opt_white( &ctx->cur ); if (!parse_uint( &ctx->cur, &uindex )) { report_error( ctx, "Expected literal unsigned integer" ); return FALSE; } *index = (int) uindex; return TRUE; } /* Parse simple 1d register operand. * <register_dst> ::= <register_file_bracket_index> `]' */ static boolean parse_register_1d(struct translate_ctx *ctx, uint *file, int *index ) { if (!parse_register_file_bracket_index( ctx, file, index )) return FALSE; eat_opt_white( &ctx->cur ); if (*ctx->cur != ']') { report_error( ctx, "Expected `]'" ); return FALSE; } ctx->cur++; return TRUE; } struct parsed_bracket { int index; uint ind_file; int ind_index; uint ind_comp; uint ind_array; }; static boolean parse_register_bracket( struct translate_ctx *ctx, struct parsed_bracket *brackets) { const char *cur; uint uindex; memset(brackets, 0, sizeof(struct parsed_bracket)); eat_opt_white( &ctx->cur ); cur = ctx->cur; if (parse_file( &cur, &brackets->ind_file )) { if (!parse_register_1d( ctx, &brackets->ind_file, &brackets->ind_index )) return FALSE; eat_opt_white( &ctx->cur ); if (*ctx->cur == '.') { ctx->cur++; eat_opt_white(&ctx->cur); switch (uprcase(*ctx->cur)) { case 'X': brackets->ind_comp = TGSI_SWIZZLE_X; break; case 'Y': brackets->ind_comp = TGSI_SWIZZLE_Y; break; case 'Z': brackets->ind_comp = TGSI_SWIZZLE_Z; break; case 'W': brackets->ind_comp = TGSI_SWIZZLE_W; break; default: report_error(ctx, "Expected indirect register swizzle component `x', `y', `z' or `w'"); return FALSE; } ctx->cur++; eat_opt_white(&ctx->cur); } if (*ctx->cur == '+' || *ctx->cur == '-') parse_int( &ctx->cur, &brackets->index ); else brackets->index = 0; } else { if (!parse_uint( &ctx->cur, &uindex )) { report_error( ctx, "Expected literal unsigned integer" ); return FALSE; } brackets->index = (int) uindex; brackets->ind_file = TGSI_FILE_NULL; brackets->ind_index = 0; } eat_opt_white( &ctx->cur ); if (*ctx->cur != ']') { report_error( ctx, "Expected `]'" ); return FALSE; } ctx->cur++; if (*ctx->cur == '(') { ctx->cur++; eat_opt_white( &ctx->cur ); if (!parse_uint( &ctx->cur, &brackets->ind_array )) { report_error( ctx, "Expected literal unsigned integer" ); return FALSE; } eat_opt_white( &ctx->cur ); if (*ctx->cur != ')') { report_error( ctx, "Expected `)'" ); return FALSE; } ctx->cur++; } return TRUE; } static boolean parse_opt_register_src_bracket( struct translate_ctx *ctx, struct parsed_bracket *brackets, int *parsed_brackets) { const char *cur = ctx->cur; *parsed_brackets = 0; eat_opt_white( &cur ); if (cur[0] == '[') { ++cur; ctx->cur = cur; if (!parse_register_bracket(ctx, brackets)) return FALSE; *parsed_brackets = 1; } return TRUE; } /* Parse source register operand. * <register_src> ::= <register_file_bracket_index> `]' | * <register_file_bracket> <register_dst> [`.' (`x' | `y' | `z' | `w')] `]' | * <register_file_bracket> <register_dst> [`.' (`x' | `y' | `z' | `w')] `+' <uint> `]' | * <register_file_bracket> <register_dst> [`.' (`x' | `y' | `z' | `w')] `-' <uint> `]' */ static boolean parse_register_src( struct translate_ctx *ctx, uint *file, struct parsed_bracket *brackets) { brackets->ind_comp = TGSI_SWIZZLE_X; if (!parse_register_file_bracket( ctx, file )) return FALSE; if (!parse_register_bracket( ctx, brackets )) return FALSE; return TRUE; } struct parsed_dcl_bracket { uint first; uint last; }; static boolean parse_register_dcl_bracket( struct translate_ctx *ctx, struct parsed_dcl_bracket *bracket) { uint uindex; memset(bracket, 0, sizeof(struct parsed_dcl_bracket)); eat_opt_white( &ctx->cur ); if (!parse_uint( &ctx->cur, &uindex )) { /* it can be an empty bracket [] which means its range * is from 0 to some implied size */ if (ctx->cur[0] == ']' && ctx->implied_array_size != 0) { bracket->first = 0; bracket->last = ctx->implied_array_size - 1; goto cleanup; } report_error( ctx, "Expected literal unsigned integer" ); return FALSE; } bracket->first = uindex; eat_opt_white( &ctx->cur ); if (ctx->cur[0] == '.' && ctx->cur[1] == '.') { uint uindex; ctx->cur += 2; eat_opt_white( &ctx->cur ); if (!parse_uint( &ctx->cur, &uindex )) { report_error( ctx, "Expected literal integer" ); return FALSE; } bracket->last = (int) uindex; eat_opt_white( &ctx->cur ); } else { bracket->last = bracket->first; } cleanup: if (*ctx->cur != ']') { report_error( ctx, "Expected `]' or `..'" ); return FALSE; } ctx->cur++; return TRUE; } /* Parse register declaration. * <register_dcl> ::= <register_file_bracket_index> `]' | * <register_file_bracket_index> `..' <index> `]' */ static boolean parse_register_dcl( struct translate_ctx *ctx, uint *file, struct parsed_dcl_bracket *brackets, int *num_brackets) { const char *cur; *num_brackets = 0; if (!parse_register_file_bracket( ctx, file )) return FALSE; if (!parse_register_dcl_bracket( ctx, &brackets[0] )) return FALSE; *num_brackets = 1; cur = ctx->cur; eat_opt_white( &cur ); if (cur[0] == '[') { bool is_in = *file == TGSI_FILE_INPUT; bool is_out = *file == TGSI_FILE_OUTPUT; ++cur; ctx->cur = cur; if (!parse_register_dcl_bracket( ctx, &brackets[1] )) return FALSE; /* for geometry shader we don't really care about * the first brackets it's always the size of the * input primitive. so we want to declare just * the index relevant to the semantics which is in * the second bracket */ /* tessellation has similar constraints to geometry shader */ if ((ctx->processor == TGSI_PROCESSOR_GEOMETRY && is_in) || (ctx->processor == TGSI_PROCESSOR_TESS_EVAL && is_in) || (ctx->processor == TGSI_PROCESSOR_TESS_CTRL && (is_in || is_out))) { brackets[0] = brackets[1]; *num_brackets = 1; } else { *num_brackets = 2; } } return TRUE; } /* Parse destination register operand.*/ static boolean parse_register_dst( struct translate_ctx *ctx, uint *file, struct parsed_bracket *brackets) { brackets->ind_comp = TGSI_SWIZZLE_X; if (!parse_register_file_bracket( ctx, file )) return FALSE; if (!parse_register_bracket( ctx, brackets )) return FALSE; return TRUE; } static boolean parse_dst_operand( struct translate_ctx *ctx, struct tgsi_full_dst_register *dst ) { uint file; uint writemask; const char *cur; struct parsed_bracket bracket[2]; int parsed_opt_brackets; if (!parse_register_dst( ctx, &file, &bracket[0] )) return FALSE; if (!parse_opt_register_src_bracket(ctx, &bracket[1], &parsed_opt_brackets)) return FALSE; cur = ctx->cur; eat_opt_white( &cur ); if (!parse_opt_writemask( ctx, &writemask )) return FALSE; dst->Register.File = file; if (parsed_opt_brackets) { dst->Register.Dimension = 1; dst->Dimension.Indirect = 0; dst->Dimension.Dimension = 0; dst->Dimension.Index = bracket[0].index; if (bracket[0].ind_file != TGSI_FILE_NULL) { dst->Dimension.Indirect = 1; dst->DimIndirect.File = bracket[0].ind_file; dst->DimIndirect.Index = bracket[0].ind_index; dst->DimIndirect.Swizzle = bracket[0].ind_comp; dst->DimIndirect.ArrayID = bracket[0].ind_array; } bracket[0] = bracket[1]; } dst->Register.Index = bracket[0].index; dst->Register.WriteMask = writemask; if (bracket[0].ind_file != TGSI_FILE_NULL) { dst->Register.Indirect = 1; dst->Indirect.File = bracket[0].ind_file; dst->Indirect.Index = bracket[0].ind_index; dst->Indirect.Swizzle = bracket[0].ind_comp; dst->Indirect.ArrayID = bracket[0].ind_array; } return TRUE; } static boolean parse_optional_swizzle( struct translate_ctx *ctx, uint *swizzle, boolean *parsed_swizzle, int components) { const char *cur = ctx->cur; *parsed_swizzle = FALSE; eat_opt_white( &cur ); if (*cur == '.') { uint i; cur++; eat_opt_white( &cur ); for (i = 0; i < components; i++) { if (uprcase( *cur ) == 'X') swizzle[i] = TGSI_SWIZZLE_X; else if (uprcase( *cur ) == 'Y') swizzle[i] = TGSI_SWIZZLE_Y; else if (uprcase( *cur ) == 'Z') swizzle[i] = TGSI_SWIZZLE_Z; else if (uprcase( *cur ) == 'W') swizzle[i] = TGSI_SWIZZLE_W; else { report_error( ctx, "Expected register swizzle component `x', `y', `z' or `w'" ); return FALSE; } cur++; } *parsed_swizzle = TRUE; ctx->cur = cur; } return TRUE; } static boolean parse_src_operand( struct translate_ctx *ctx, struct tgsi_full_src_register *src ) { uint file; uint swizzle[4]; boolean parsed_swizzle; struct parsed_bracket bracket[2]; int parsed_opt_brackets; if (*ctx->cur == '-') { ctx->cur++; eat_opt_white( &ctx->cur ); src->Register.Negate = 1; } if (*ctx->cur == '|') { ctx->cur++; eat_opt_white( &ctx->cur ); src->Register.Absolute = 1; } if (!parse_register_src(ctx, &file, &bracket[0])) return FALSE; if (!parse_opt_register_src_bracket(ctx, &bracket[1], &parsed_opt_brackets)) return FALSE; src->Register.File = file; if (parsed_opt_brackets) { src->Register.Dimension = 1; src->Dimension.Indirect = 0; src->Dimension.Dimension = 0; src->Dimension.Index = bracket[0].index; if (bracket[0].ind_file != TGSI_FILE_NULL) { src->Dimension.Indirect = 1; src->DimIndirect.File = bracket[0].ind_file; src->DimIndirect.Index = bracket[0].ind_index; src->DimIndirect.Swizzle = bracket[0].ind_comp; src->DimIndirect.ArrayID = bracket[0].ind_array; } bracket[0] = bracket[1]; } src->Register.Index = bracket[0].index; if (bracket[0].ind_file != TGSI_FILE_NULL) { src->Register.Indirect = 1; src->Indirect.File = bracket[0].ind_file; src->Indirect.Index = bracket[0].ind_index; src->Indirect.Swizzle = bracket[0].ind_comp; src->Indirect.ArrayID = bracket[0].ind_array; } /* Parse optional swizzle. */ if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) { if (parsed_swizzle) { src->Register.SwizzleX = swizzle[0]; src->Register.SwizzleY = swizzle[1]; src->Register.SwizzleZ = swizzle[2]; src->Register.SwizzleW = swizzle[3]; } } if (src->Register.Absolute) { eat_opt_white( &ctx->cur ); if (*ctx->cur != '|') { report_error( ctx, "Expected `|'" ); return FALSE; } ctx->cur++; } return TRUE; } static boolean parse_texoffset_operand( struct translate_ctx *ctx, struct tgsi_texture_offset *src ) { uint file; uint swizzle[3]; boolean parsed_swizzle; struct parsed_bracket bracket; if (!parse_register_src(ctx, &file, &bracket)) return FALSE; src->File = file; src->Index = bracket.index; /* Parse optional swizzle. */ if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 3 )) { if (parsed_swizzle) { src->SwizzleX = swizzle[0]; src->SwizzleY = swizzle[1]; src->SwizzleZ = swizzle[2]; } } return TRUE; } static boolean match_inst(const char **pcur, unsigned *saturate, const struct tgsi_opcode_info *info) { const char *cur = *pcur; /* simple case: the whole string matches the instruction name */ if (str_match_nocase_whole(&cur, info->mnemonic)) { *pcur = cur; *saturate = 0; return TRUE; } if (str_match_no_case(&cur, info->mnemonic)) { /* the instruction has a suffix, figure it out */ if (str_match_nocase_whole(&cur, "_SAT")) { *pcur = cur; *saturate = 1; return TRUE; } } return FALSE; } static boolean parse_instruction( struct translate_ctx *ctx, boolean has_label ) { uint i; uint saturate = 0; const struct tgsi_opcode_info *info; struct tgsi_full_instruction inst; const char *cur; uint advance; inst = tgsi_default_full_instruction(); /* Parse predicate. */ eat_opt_white( &ctx->cur ); if (*ctx->cur == '(') { uint file; int index; uint swizzle[4]; boolean parsed_swizzle; inst.Instruction.Predicate = 1; ctx->cur++; if (*ctx->cur == '!') { ctx->cur++; inst.Predicate.Negate = 1; } if (!parse_register_1d( ctx, &file, &index )) return FALSE; if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) { if (parsed_swizzle) { inst.Predicate.SwizzleX = swizzle[0]; inst.Predicate.SwizzleY = swizzle[1]; inst.Predicate.SwizzleZ = swizzle[2]; inst.Predicate.SwizzleW = swizzle[3]; } } if (*ctx->cur != ')') { report_error( ctx, "Expected `)'" ); return FALSE; } ctx->cur++; } /* Parse instruction name. */ eat_opt_white( &ctx->cur ); for (i = 0; i < TGSI_OPCODE_LAST; i++) { cur = ctx->cur; info = tgsi_get_opcode_info( i ); if (match_inst(&cur, &saturate, info)) { if (info->num_dst + info->num_src + info->is_tex == 0) { ctx->cur = cur; break; } else if (*cur == '\0' || eat_white( &cur )) { ctx->cur = cur; break; } } } if (i == TGSI_OPCODE_LAST) { if (has_label) report_error( ctx, "Unknown opcode" ); else report_error( ctx, "Expected `DCL', `IMM' or a label" ); return FALSE; } inst.Instruction.Opcode = i; inst.Instruction.Saturate = saturate; inst.Instruction.NumDstRegs = info->num_dst; inst.Instruction.NumSrcRegs = info->num_src; if (i >= TGSI_OPCODE_SAMPLE && i <= TGSI_OPCODE_GATHER4) { /* * These are not considered tex opcodes here (no additional * target argument) however we're required to set the Texture * bit so we can set the number of tex offsets. */ inst.Instruction.Texture = 1; inst.Texture.Texture = TGSI_TEXTURE_UNKNOWN; } /* Parse instruction operands. */ for (i = 0; i < info->num_dst + info->num_src + info->is_tex; i++) { if (i > 0) { eat_opt_white( &ctx->cur ); if (*ctx->cur != ',') { report_error( ctx, "Expected `,'" ); return FALSE; } ctx->cur++; eat_opt_white( &ctx->cur ); } if (i < info->num_dst) { if (!parse_dst_operand( ctx, &inst.Dst[i] )) return FALSE; } else if (i < info->num_dst + info->num_src) { if (!parse_src_operand( ctx, &inst.Src[i - info->num_dst] )) return FALSE; } else { uint j; for (j = 0; j < TGSI_TEXTURE_COUNT; j++) { if (str_match_nocase_whole( &ctx->cur, tgsi_texture_names[j] )) { inst.Instruction.Texture = 1; inst.Texture.Texture = j; break; } } if (j == TGSI_TEXTURE_COUNT) { report_error( ctx, "Expected texture target" ); return FALSE; } } } cur = ctx->cur; eat_opt_white( &cur ); for (i = 0; inst.Instruction.Texture && *cur == ','; i++) { cur++; eat_opt_white( &cur ); ctx->cur = cur; if (!parse_texoffset_operand( ctx, &inst.TexOffsets[i] )) return FALSE; cur = ctx->cur; eat_opt_white( &cur ); } inst.Texture.NumOffsets = i; cur = ctx->cur; eat_opt_white( &cur ); if (info->is_branch && *cur == ':') { uint target; cur++; eat_opt_white( &cur ); if (!parse_uint( &cur, &target )) { report_error( ctx, "Expected a label" ); return FALSE; } inst.Instruction.Label = 1; inst.Label.Label = target; ctx->cur = cur; } advance = tgsi_build_full_instruction( &inst, ctx->tokens_cur, ctx->header, (uint) (ctx->tokens_end - ctx->tokens_cur) ); if (advance == 0) return FALSE; ctx->tokens_cur += advance; return TRUE; } /* parses a 4-touple of the form {x, y, z, w} * where x, y, z, w are numbers */ static boolean parse_immediate_data(struct translate_ctx *ctx, unsigned type, union tgsi_immediate_data *values) { unsigned i; int ret; eat_opt_white( &ctx->cur ); if (*ctx->cur != '{') { report_error( ctx, "Expected `{'" ); return FALSE; } ctx->cur++; for (i = 0; i < 4; i++) { eat_opt_white( &ctx->cur ); if (i > 0) { if (*ctx->cur != ',') { report_error( ctx, "Expected `,'" ); return FALSE; } ctx->cur++; eat_opt_white( &ctx->cur ); } switch (type) { case TGSI_IMM_FLOAT64: ret = parse_double(&ctx->cur, &values[i].Uint, &values[i+1].Uint); i++; break; case TGSI_IMM_FLOAT32: ret = parse_float(&ctx->cur, &values[i].Float); break; case TGSI_IMM_UINT32: ret = parse_uint(&ctx->cur, &values[i].Uint); break; case TGSI_IMM_INT32: ret = parse_int(&ctx->cur, &values[i].Int); break; default: assert(0); ret = FALSE; break; } if (!ret) { report_error( ctx, "Expected immediate constant" ); return FALSE; } } eat_opt_white( &ctx->cur ); if (*ctx->cur != '}') { report_error( ctx, "Expected `}'" ); return FALSE; } ctx->cur++; return TRUE; } static boolean parse_declaration( struct translate_ctx *ctx ) { struct tgsi_full_declaration decl; uint file; struct parsed_dcl_bracket brackets[2]; int num_brackets; uint writemask; const char *cur, *cur2; uint advance; boolean is_vs_input; if (!eat_white( &ctx->cur )) { report_error( ctx, "Syntax error" ); return FALSE; } if (!parse_register_dcl( ctx, &file, brackets, &num_brackets)) return FALSE; if (!parse_opt_writemask( ctx, &writemask )) return FALSE; decl = tgsi_default_full_declaration(); decl.Declaration.File = file; decl.Declaration.UsageMask = writemask; if (num_brackets == 1) { decl.Range.First = brackets[0].first; decl.Range.Last = brackets[0].last; } else { decl.Range.First = brackets[1].first; decl.Range.Last = brackets[1].last; decl.Declaration.Dimension = 1; decl.Dim.Index2D = brackets[0].first; } is_vs_input = (file == TGSI_FILE_INPUT && ctx->processor == TGSI_PROCESSOR_VERTEX); cur = ctx->cur; eat_opt_white( &cur ); if (*cur == ',') { cur2 = cur; cur2++; eat_opt_white( &cur2 ); if (str_match_nocase_whole( &cur2, "ARRAY" )) { int arrayid; if (*cur2 != '(') { report_error( ctx, "Expected `('" ); return FALSE; } cur2++; eat_opt_white( &cur2 ); if (!parse_int( &cur2, &arrayid )) { report_error( ctx, "Expected `,'" ); return FALSE; } eat_opt_white( &cur2 ); if (*cur2 != ')') { report_error( ctx, "Expected `)'" ); return FALSE; } cur2++; decl.Declaration.Array = 1; decl.Array.ArrayID = arrayid; ctx->cur = cur = cur2; } } if (*cur == ',' && !is_vs_input) { uint i, j; cur++; eat_opt_white( &cur ); if (file == TGSI_FILE_RESOURCE) { for (i = 0; i < TGSI_TEXTURE_COUNT; i++) { if (str_match_nocase_whole(&cur, tgsi_texture_names[i])) { decl.Resource.Resource = i; break; } } if (i == TGSI_TEXTURE_COUNT) { report_error(ctx, "Expected texture target"); return FALSE; } cur2 = cur; eat_opt_white(&cur2); while (*cur2 == ',') { cur2++; eat_opt_white(&cur2); if (str_match_nocase_whole(&cur2, "RAW")) { decl.Resource.Raw = 1; } else if (str_match_nocase_whole(&cur2, "WR")) { decl.Resource.Writable = 1; } else { break; } cur = cur2; eat_opt_white(&cur2); } ctx->cur = cur; } else if (file == TGSI_FILE_SAMPLER_VIEW) { for (i = 0; i < TGSI_TEXTURE_COUNT; i++) { if (str_match_nocase_whole(&cur, tgsi_texture_names[i])) { decl.SamplerView.Resource = i; break; } } if (i == TGSI_TEXTURE_COUNT) { report_error(ctx, "Expected texture target"); return FALSE; } eat_opt_white( &cur ); if (*cur != ',') { report_error( ctx, "Expected `,'" ); return FALSE; } ++cur; eat_opt_white( &cur ); for (j = 0; j < 4; ++j) { for (i = 0; i < TGSI_RETURN_TYPE_COUNT; ++i) { if (str_match_nocase_whole(&cur, tgsi_return_type_names[i])) { switch (j) { case 0: decl.SamplerView.ReturnTypeX = i; break; case 1: decl.SamplerView.ReturnTypeY = i; break; case 2: decl.SamplerView.ReturnTypeZ = i; break; case 3: decl.SamplerView.ReturnTypeW = i; break; default: assert(0); } break; } } if (i == TGSI_RETURN_TYPE_COUNT) { if (j == 0 || j > 2) { report_error(ctx, "Expected type name"); return FALSE; } break; } else { cur2 = cur; eat_opt_white( &cur2 ); if (*cur2 == ',') { cur2++; eat_opt_white( &cur2 ); cur = cur2; continue; } else break; } } if (j < 4) { decl.SamplerView.ReturnTypeY = decl.SamplerView.ReturnTypeZ = decl.SamplerView.ReturnTypeW = decl.SamplerView.ReturnTypeX; } ctx->cur = cur; } else { if (str_match_nocase_whole(&cur, "LOCAL")) { decl.Declaration.Local = 1; ctx->cur = cur; } cur = ctx->cur; eat_opt_white( &cur ); if (*cur == ',') { cur++; eat_opt_white( &cur ); for (i = 0; i < TGSI_SEMANTIC_COUNT; i++) { if (str_match_nocase_whole(&cur, tgsi_semantic_names[i])) { uint index; cur2 = cur; eat_opt_white( &cur2 ); if (*cur2 == '[') { cur2++; eat_opt_white( &cur2 ); if (!parse_uint( &cur2, &index )) { report_error( ctx, "Expected literal integer" ); return FALSE; } eat_opt_white( &cur2 ); if (*cur2 != ']') { report_error( ctx, "Expected `]'" ); return FALSE; } cur2++; decl.Semantic.Index = index; cur = cur2; } decl.Declaration.Semantic = 1; decl.Semantic.Name = i; ctx->cur = cur; break; } } } } } cur = ctx->cur; eat_opt_white( &cur ); if (*cur == ',' && !is_vs_input) { uint i; cur++; eat_opt_white( &cur ); for (i = 0; i < TGSI_INTERPOLATE_COUNT; i++) { if (str_match_nocase_whole( &cur, tgsi_interpolate_names[i] )) { decl.Declaration.Interpolate = 1; decl.Interp.Interpolate = i; ctx->cur = cur; break; } } if (i == TGSI_INTERPOLATE_COUNT) { report_error( ctx, "Expected semantic or interpolate attribute" ); return FALSE; } } cur = ctx->cur; eat_opt_white( &cur ); if (*cur == ',' && !is_vs_input) { uint i; cur++; eat_opt_white( &cur ); for (i = 0; i < TGSI_INTERPOLATE_LOC_COUNT; i++) { if (str_match_nocase_whole( &cur, tgsi_interpolate_locations[i] )) { decl.Interp.Location = i; ctx->cur = cur; break; } } } advance = tgsi_build_full_declaration( &decl, ctx->tokens_cur, ctx->header, (uint) (ctx->tokens_end - ctx->tokens_cur) ); if (advance == 0) return FALSE; ctx->tokens_cur += advance; return TRUE; } static boolean parse_immediate( struct translate_ctx *ctx ) { struct tgsi_full_immediate imm; uint advance; int type; if (*ctx->cur == '[') { uint uindex; ++ctx->cur; eat_opt_white( &ctx->cur ); if (!parse_uint( &ctx->cur, &uindex )) { report_error( ctx, "Expected literal unsigned integer" ); return FALSE; } if (uindex != ctx->num_immediates) { report_error( ctx, "Immediates must be sorted" ); return FALSE; } eat_opt_white( &ctx->cur ); if (*ctx->cur != ']') { report_error( ctx, "Expected `]'" ); return FALSE; } ctx->cur++; } if (!eat_white( &ctx->cur )) { report_error( ctx, "Syntax error" ); return FALSE; } for (type = 0; type < Elements(tgsi_immediate_type_names); ++type) { if (str_match_nocase_whole(&ctx->cur, tgsi_immediate_type_names[type])) break; } if (type == Elements(tgsi_immediate_type_names)) { report_error( ctx, "Expected immediate type" ); return FALSE; } imm = tgsi_default_full_immediate(); imm.Immediate.NrTokens += 4; imm.Immediate.DataType = type; parse_immediate_data(ctx, type, imm.u); advance = tgsi_build_full_immediate( &imm, ctx->tokens_cur, ctx->header, (uint) (ctx->tokens_end - ctx->tokens_cur) ); if (advance == 0) return FALSE; ctx->tokens_cur += advance; ctx->num_immediates++; return TRUE; } static boolean parse_primitive( const char **pcur, uint *primitive ) { uint i; for (i = 0; i < PIPE_PRIM_MAX; i++) { const char *cur = *pcur; if (str_match_nocase_whole( &cur, tgsi_primitive_names[i])) { *primitive = i; *pcur = cur; return TRUE; } } return FALSE; } static boolean parse_fs_coord_origin( const char **pcur, uint *fs_coord_origin ) { uint i; for (i = 0; i < Elements(tgsi_fs_coord_origin_names); i++) { const char *cur = *pcur; if (str_match_nocase_whole( &cur, tgsi_fs_coord_origin_names[i])) { *fs_coord_origin = i; *pcur = cur; return TRUE; } } return FALSE; } static boolean parse_fs_coord_pixel_center( const char **pcur, uint *fs_coord_pixel_center ) { uint i; for (i = 0; i < Elements(tgsi_fs_coord_pixel_center_names); i++) { const char *cur = *pcur; if (str_match_nocase_whole( &cur, tgsi_fs_coord_pixel_center_names[i])) { *fs_coord_pixel_center = i; *pcur = cur; return TRUE; } } return FALSE; } static boolean parse_property( struct translate_ctx *ctx ) { struct tgsi_full_property prop; uint property_name; uint values[8]; uint advance; char id[64]; if (!eat_white( &ctx->cur )) { report_error( ctx, "Syntax error" ); return FALSE; } report_error( ctx, "Syntax error" ); return FALSE; } if (!parse_identifier( &ctx->cur, id )) { report_error( ctx, "Syntax error" ); return FALSE; } break; } }
[ "CWE-119" ]
virglrenderer
e534b51ca3c3cd25f3990589932a9ed711c59b27
142817990104108566810102542927701673732
178,123
241
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
static boolean parse_identifier( const char **pcur, char *ret ) static boolean parse_identifier( const char **pcur, char *ret, size_t len ) { const char *cur = *pcur; int i = 0; if (is_alpha_underscore( cur )) { ret[i++] = *cur++; while (is_alpha_underscore( cur ) || is_digit( cur )) { if (i == len - 1) return FALSE; ret[i++] = *cur++; } ret[i++] = '\0'; *pcur = cur; return TRUE; /* Parse floating point. */ static boolean parse_float( const char **pcur, float *val ) { const char *cur = *pcur; boolean integral_part = FALSE; boolean fractional_part = FALSE; if (*cur == '0' && *(cur + 1) == 'x') { union fi fi; fi.ui = strtoul(cur, NULL, 16); *val = fi.f; cur += 10; goto out; } *val = (float) atof( cur ); if (*cur == '-' || *cur == '+') cur++; if (is_digit( cur )) { cur++; integral_part = TRUE; while (is_digit( cur )) cur++; } if (*cur == '.') { cur++; if (is_digit( cur )) { cur++; fractional_part = TRUE; while (is_digit( cur )) cur++; } } if (!integral_part && !fractional_part) return FALSE; if (uprcase( *cur ) == 'E') { cur++; if (*cur == '-' || *cur == '+') cur++; if (is_digit( cur )) { cur++; while (is_digit( cur )) cur++; } else return FALSE; } out: *pcur = cur; return TRUE; } static boolean parse_double( const char **pcur, uint32_t *val0, uint32_t *val1) { const char *cur = *pcur; union { double dval; uint32_t uval[2]; } v; v.dval = strtod(cur, (char**)pcur); if (*pcur == cur) return FALSE; *val0 = v.uval[0]; *val1 = v.uval[1]; return TRUE; } struct translate_ctx { const char *text; const char *cur; struct tgsi_token *tokens; struct tgsi_token *tokens_cur; struct tgsi_token *tokens_end; struct tgsi_header *header; unsigned processor : 4; unsigned implied_array_size : 6; unsigned num_immediates; }; static void report_error(struct translate_ctx *ctx, const char *format, ...) { va_list args; int line = 1; int column = 1; const char *itr = ctx->text; debug_printf("\nTGSI asm error: "); va_start(args, format); _debug_vprintf(format, args); va_end(args); while (itr != ctx->cur) { if (*itr == '\n') { column = 1; ++line; } ++column; ++itr; } debug_printf(" [%d : %d] \n", line, column); } /* Parse shader header. * Return TRUE for one of the following headers. * FRAG * GEOM * VERT */ static boolean parse_header( struct translate_ctx *ctx ) { uint processor; if (str_match_nocase_whole( &ctx->cur, "FRAG" )) processor = TGSI_PROCESSOR_FRAGMENT; else if (str_match_nocase_whole( &ctx->cur, "VERT" )) processor = TGSI_PROCESSOR_VERTEX; else if (str_match_nocase_whole( &ctx->cur, "GEOM" )) processor = TGSI_PROCESSOR_GEOMETRY; else if (str_match_nocase_whole( &ctx->cur, "TESS_CTRL" )) processor = TGSI_PROCESSOR_TESS_CTRL; else if (str_match_nocase_whole( &ctx->cur, "TESS_EVAL" )) processor = TGSI_PROCESSOR_TESS_EVAL; else if (str_match_nocase_whole( &ctx->cur, "COMP" )) processor = TGSI_PROCESSOR_COMPUTE; else { report_error( ctx, "Unknown header" ); return FALSE; } if (ctx->tokens_cur >= ctx->tokens_end) return FALSE; ctx->header = (struct tgsi_header *) ctx->tokens_cur++; *ctx->header = tgsi_build_header(); if (ctx->tokens_cur >= ctx->tokens_end) return FALSE; *(struct tgsi_processor *) ctx->tokens_cur++ = tgsi_build_processor( processor, ctx->header ); ctx->processor = processor; return TRUE; } static boolean parse_label( struct translate_ctx *ctx, uint *val ) { const char *cur = ctx->cur; if (parse_uint( &cur, val )) { eat_opt_white( &cur ); if (*cur == ':') { cur++; ctx->cur = cur; return TRUE; } } return FALSE; } static boolean parse_file( const char **pcur, uint *file ) { uint i; for (i = 0; i < TGSI_FILE_COUNT; i++) { const char *cur = *pcur; if (str_match_nocase_whole( &cur, tgsi_file_name(i) )) { *pcur = cur; *file = i; return TRUE; } } return FALSE; } static boolean parse_opt_writemask( struct translate_ctx *ctx, uint *writemask ) { const char *cur; cur = ctx->cur; eat_opt_white( &cur ); if (*cur == '.') { cur++; *writemask = TGSI_WRITEMASK_NONE; eat_opt_white( &cur ); if (uprcase( *cur ) == 'X') { cur++; *writemask |= TGSI_WRITEMASK_X; } if (uprcase( *cur ) == 'Y') { cur++; *writemask |= TGSI_WRITEMASK_Y; } if (uprcase( *cur ) == 'Z') { cur++; *writemask |= TGSI_WRITEMASK_Z; } if (uprcase( *cur ) == 'W') { cur++; *writemask |= TGSI_WRITEMASK_W; } if (*writemask == TGSI_WRITEMASK_NONE) { report_error( ctx, "Writemask expected" ); return FALSE; } ctx->cur = cur; } else { *writemask = TGSI_WRITEMASK_XYZW; } return TRUE; } /* <register_file_bracket> ::= <file> `[' */ static boolean parse_register_file_bracket( struct translate_ctx *ctx, uint *file ) { if (!parse_file( &ctx->cur, file )) { report_error( ctx, "Unknown register file" ); return FALSE; } eat_opt_white( &ctx->cur ); if (*ctx->cur != '[') { report_error( ctx, "Expected `['" ); return FALSE; } ctx->cur++; return TRUE; } /* <register_file_bracket_index> ::= <register_file_bracket> <uint> */ static boolean parse_register_file_bracket_index( struct translate_ctx *ctx, uint *file, int *index ) { uint uindex; if (!parse_register_file_bracket( ctx, file )) return FALSE; eat_opt_white( &ctx->cur ); if (!parse_uint( &ctx->cur, &uindex )) { report_error( ctx, "Expected literal unsigned integer" ); return FALSE; } *index = (int) uindex; return TRUE; } /* Parse simple 1d register operand. * <register_dst> ::= <register_file_bracket_index> `]' */ static boolean parse_register_1d(struct translate_ctx *ctx, uint *file, int *index ) { if (!parse_register_file_bracket_index( ctx, file, index )) return FALSE; eat_opt_white( &ctx->cur ); if (*ctx->cur != ']') { report_error( ctx, "Expected `]'" ); return FALSE; } ctx->cur++; return TRUE; } struct parsed_bracket { int index; uint ind_file; int ind_index; uint ind_comp; uint ind_array; }; static boolean parse_register_bracket( struct translate_ctx *ctx, struct parsed_bracket *brackets) { const char *cur; uint uindex; memset(brackets, 0, sizeof(struct parsed_bracket)); eat_opt_white( &ctx->cur ); cur = ctx->cur; if (parse_file( &cur, &brackets->ind_file )) { if (!parse_register_1d( ctx, &brackets->ind_file, &brackets->ind_index )) return FALSE; eat_opt_white( &ctx->cur ); if (*ctx->cur == '.') { ctx->cur++; eat_opt_white(&ctx->cur); switch (uprcase(*ctx->cur)) { case 'X': brackets->ind_comp = TGSI_SWIZZLE_X; break; case 'Y': brackets->ind_comp = TGSI_SWIZZLE_Y; break; case 'Z': brackets->ind_comp = TGSI_SWIZZLE_Z; break; case 'W': brackets->ind_comp = TGSI_SWIZZLE_W; break; default: report_error(ctx, "Expected indirect register swizzle component `x', `y', `z' or `w'"); return FALSE; } ctx->cur++; eat_opt_white(&ctx->cur); } if (*ctx->cur == '+' || *ctx->cur == '-') parse_int( &ctx->cur, &brackets->index ); else brackets->index = 0; } else { if (!parse_uint( &ctx->cur, &uindex )) { report_error( ctx, "Expected literal unsigned integer" ); return FALSE; } brackets->index = (int) uindex; brackets->ind_file = TGSI_FILE_NULL; brackets->ind_index = 0; } eat_opt_white( &ctx->cur ); if (*ctx->cur != ']') { report_error( ctx, "Expected `]'" ); return FALSE; } ctx->cur++; if (*ctx->cur == '(') { ctx->cur++; eat_opt_white( &ctx->cur ); if (!parse_uint( &ctx->cur, &brackets->ind_array )) { report_error( ctx, "Expected literal unsigned integer" ); return FALSE; } eat_opt_white( &ctx->cur ); if (*ctx->cur != ')') { report_error( ctx, "Expected `)'" ); return FALSE; } ctx->cur++; } return TRUE; } static boolean parse_opt_register_src_bracket( struct translate_ctx *ctx, struct parsed_bracket *brackets, int *parsed_brackets) { const char *cur = ctx->cur; *parsed_brackets = 0; eat_opt_white( &cur ); if (cur[0] == '[') { ++cur; ctx->cur = cur; if (!parse_register_bracket(ctx, brackets)) return FALSE; *parsed_brackets = 1; } return TRUE; } /* Parse source register operand. * <register_src> ::= <register_file_bracket_index> `]' | * <register_file_bracket> <register_dst> [`.' (`x' | `y' | `z' | `w')] `]' | * <register_file_bracket> <register_dst> [`.' (`x' | `y' | `z' | `w')] `+' <uint> `]' | * <register_file_bracket> <register_dst> [`.' (`x' | `y' | `z' | `w')] `-' <uint> `]' */ static boolean parse_register_src( struct translate_ctx *ctx, uint *file, struct parsed_bracket *brackets) { brackets->ind_comp = TGSI_SWIZZLE_X; if (!parse_register_file_bracket( ctx, file )) return FALSE; if (!parse_register_bracket( ctx, brackets )) return FALSE; return TRUE; } struct parsed_dcl_bracket { uint first; uint last; }; static boolean parse_register_dcl_bracket( struct translate_ctx *ctx, struct parsed_dcl_bracket *bracket) { uint uindex; memset(bracket, 0, sizeof(struct parsed_dcl_bracket)); eat_opt_white( &ctx->cur ); if (!parse_uint( &ctx->cur, &uindex )) { /* it can be an empty bracket [] which means its range * is from 0 to some implied size */ if (ctx->cur[0] == ']' && ctx->implied_array_size != 0) { bracket->first = 0; bracket->last = ctx->implied_array_size - 1; goto cleanup; } report_error( ctx, "Expected literal unsigned integer" ); return FALSE; } bracket->first = uindex; eat_opt_white( &ctx->cur ); if (ctx->cur[0] == '.' && ctx->cur[1] == '.') { uint uindex; ctx->cur += 2; eat_opt_white( &ctx->cur ); if (!parse_uint( &ctx->cur, &uindex )) { report_error( ctx, "Expected literal integer" ); return FALSE; } bracket->last = (int) uindex; eat_opt_white( &ctx->cur ); } else { bracket->last = bracket->first; } cleanup: if (*ctx->cur != ']') { report_error( ctx, "Expected `]' or `..'" ); return FALSE; } ctx->cur++; return TRUE; } /* Parse register declaration. * <register_dcl> ::= <register_file_bracket_index> `]' | * <register_file_bracket_index> `..' <index> `]' */ static boolean parse_register_dcl( struct translate_ctx *ctx, uint *file, struct parsed_dcl_bracket *brackets, int *num_brackets) { const char *cur; *num_brackets = 0; if (!parse_register_file_bracket( ctx, file )) return FALSE; if (!parse_register_dcl_bracket( ctx, &brackets[0] )) return FALSE; *num_brackets = 1; cur = ctx->cur; eat_opt_white( &cur ); if (cur[0] == '[') { bool is_in = *file == TGSI_FILE_INPUT; bool is_out = *file == TGSI_FILE_OUTPUT; ++cur; ctx->cur = cur; if (!parse_register_dcl_bracket( ctx, &brackets[1] )) return FALSE; /* for geometry shader we don't really care about * the first brackets it's always the size of the * input primitive. so we want to declare just * the index relevant to the semantics which is in * the second bracket */ /* tessellation has similar constraints to geometry shader */ if ((ctx->processor == TGSI_PROCESSOR_GEOMETRY && is_in) || (ctx->processor == TGSI_PROCESSOR_TESS_EVAL && is_in) || (ctx->processor == TGSI_PROCESSOR_TESS_CTRL && (is_in || is_out))) { brackets[0] = brackets[1]; *num_brackets = 1; } else { *num_brackets = 2; } } return TRUE; } /* Parse destination register operand.*/ static boolean parse_register_dst( struct translate_ctx *ctx, uint *file, struct parsed_bracket *brackets) { brackets->ind_comp = TGSI_SWIZZLE_X; if (!parse_register_file_bracket( ctx, file )) return FALSE; if (!parse_register_bracket( ctx, brackets )) return FALSE; return TRUE; } static boolean parse_dst_operand( struct translate_ctx *ctx, struct tgsi_full_dst_register *dst ) { uint file; uint writemask; const char *cur; struct parsed_bracket bracket[2]; int parsed_opt_brackets; if (!parse_register_dst( ctx, &file, &bracket[0] )) return FALSE; if (!parse_opt_register_src_bracket(ctx, &bracket[1], &parsed_opt_brackets)) return FALSE; cur = ctx->cur; eat_opt_white( &cur ); if (!parse_opt_writemask( ctx, &writemask )) return FALSE; dst->Register.File = file; if (parsed_opt_brackets) { dst->Register.Dimension = 1; dst->Dimension.Indirect = 0; dst->Dimension.Dimension = 0; dst->Dimension.Index = bracket[0].index; if (bracket[0].ind_file != TGSI_FILE_NULL) { dst->Dimension.Indirect = 1; dst->DimIndirect.File = bracket[0].ind_file; dst->DimIndirect.Index = bracket[0].ind_index; dst->DimIndirect.Swizzle = bracket[0].ind_comp; dst->DimIndirect.ArrayID = bracket[0].ind_array; } bracket[0] = bracket[1]; } dst->Register.Index = bracket[0].index; dst->Register.WriteMask = writemask; if (bracket[0].ind_file != TGSI_FILE_NULL) { dst->Register.Indirect = 1; dst->Indirect.File = bracket[0].ind_file; dst->Indirect.Index = bracket[0].ind_index; dst->Indirect.Swizzle = bracket[0].ind_comp; dst->Indirect.ArrayID = bracket[0].ind_array; } return TRUE; } static boolean parse_optional_swizzle( struct translate_ctx *ctx, uint *swizzle, boolean *parsed_swizzle, int components) { const char *cur = ctx->cur; *parsed_swizzle = FALSE; eat_opt_white( &cur ); if (*cur == '.') { uint i; cur++; eat_opt_white( &cur ); for (i = 0; i < components; i++) { if (uprcase( *cur ) == 'X') swizzle[i] = TGSI_SWIZZLE_X; else if (uprcase( *cur ) == 'Y') swizzle[i] = TGSI_SWIZZLE_Y; else if (uprcase( *cur ) == 'Z') swizzle[i] = TGSI_SWIZZLE_Z; else if (uprcase( *cur ) == 'W') swizzle[i] = TGSI_SWIZZLE_W; else { report_error( ctx, "Expected register swizzle component `x', `y', `z' or `w'" ); return FALSE; } cur++; } *parsed_swizzle = TRUE; ctx->cur = cur; } return TRUE; } static boolean parse_src_operand( struct translate_ctx *ctx, struct tgsi_full_src_register *src ) { uint file; uint swizzle[4]; boolean parsed_swizzle; struct parsed_bracket bracket[2]; int parsed_opt_brackets; if (*ctx->cur == '-') { ctx->cur++; eat_opt_white( &ctx->cur ); src->Register.Negate = 1; } if (*ctx->cur == '|') { ctx->cur++; eat_opt_white( &ctx->cur ); src->Register.Absolute = 1; } if (!parse_register_src(ctx, &file, &bracket[0])) return FALSE; if (!parse_opt_register_src_bracket(ctx, &bracket[1], &parsed_opt_brackets)) return FALSE; src->Register.File = file; if (parsed_opt_brackets) { src->Register.Dimension = 1; src->Dimension.Indirect = 0; src->Dimension.Dimension = 0; src->Dimension.Index = bracket[0].index; if (bracket[0].ind_file != TGSI_FILE_NULL) { src->Dimension.Indirect = 1; src->DimIndirect.File = bracket[0].ind_file; src->DimIndirect.Index = bracket[0].ind_index; src->DimIndirect.Swizzle = bracket[0].ind_comp; src->DimIndirect.ArrayID = bracket[0].ind_array; } bracket[0] = bracket[1]; } src->Register.Index = bracket[0].index; if (bracket[0].ind_file != TGSI_FILE_NULL) { src->Register.Indirect = 1; src->Indirect.File = bracket[0].ind_file; src->Indirect.Index = bracket[0].ind_index; src->Indirect.Swizzle = bracket[0].ind_comp; src->Indirect.ArrayID = bracket[0].ind_array; } /* Parse optional swizzle. */ if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) { if (parsed_swizzle) { src->Register.SwizzleX = swizzle[0]; src->Register.SwizzleY = swizzle[1]; src->Register.SwizzleZ = swizzle[2]; src->Register.SwizzleW = swizzle[3]; } } if (src->Register.Absolute) { eat_opt_white( &ctx->cur ); if (*ctx->cur != '|') { report_error( ctx, "Expected `|'" ); return FALSE; } ctx->cur++; } return TRUE; } static boolean parse_texoffset_operand( struct translate_ctx *ctx, struct tgsi_texture_offset *src ) { uint file; uint swizzle[3]; boolean parsed_swizzle; struct parsed_bracket bracket; if (!parse_register_src(ctx, &file, &bracket)) return FALSE; src->File = file; src->Index = bracket.index; /* Parse optional swizzle. */ if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 3 )) { if (parsed_swizzle) { src->SwizzleX = swizzle[0]; src->SwizzleY = swizzle[1]; src->SwizzleZ = swizzle[2]; } } return TRUE; } static boolean match_inst(const char **pcur, unsigned *saturate, const struct tgsi_opcode_info *info) { const char *cur = *pcur; /* simple case: the whole string matches the instruction name */ if (str_match_nocase_whole(&cur, info->mnemonic)) { *pcur = cur; *saturate = 0; return TRUE; } if (str_match_no_case(&cur, info->mnemonic)) { /* the instruction has a suffix, figure it out */ if (str_match_nocase_whole(&cur, "_SAT")) { *pcur = cur; *saturate = 1; return TRUE; } } return FALSE; } static boolean parse_instruction( struct translate_ctx *ctx, boolean has_label ) { uint i; uint saturate = 0; const struct tgsi_opcode_info *info; struct tgsi_full_instruction inst; const char *cur; uint advance; inst = tgsi_default_full_instruction(); /* Parse predicate. */ eat_opt_white( &ctx->cur ); if (*ctx->cur == '(') { uint file; int index; uint swizzle[4]; boolean parsed_swizzle; inst.Instruction.Predicate = 1; ctx->cur++; if (*ctx->cur == '!') { ctx->cur++; inst.Predicate.Negate = 1; } if (!parse_register_1d( ctx, &file, &index )) return FALSE; if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) { if (parsed_swizzle) { inst.Predicate.SwizzleX = swizzle[0]; inst.Predicate.SwizzleY = swizzle[1]; inst.Predicate.SwizzleZ = swizzle[2]; inst.Predicate.SwizzleW = swizzle[3]; } } if (*ctx->cur != ')') { report_error( ctx, "Expected `)'" ); return FALSE; } ctx->cur++; } /* Parse instruction name. */ eat_opt_white( &ctx->cur ); for (i = 0; i < TGSI_OPCODE_LAST; i++) { cur = ctx->cur; info = tgsi_get_opcode_info( i ); if (match_inst(&cur, &saturate, info)) { if (info->num_dst + info->num_src + info->is_tex == 0) { ctx->cur = cur; break; } else if (*cur == '\0' || eat_white( &cur )) { ctx->cur = cur; break; } } } if (i == TGSI_OPCODE_LAST) { if (has_label) report_error( ctx, "Unknown opcode" ); else report_error( ctx, "Expected `DCL', `IMM' or a label" ); return FALSE; } inst.Instruction.Opcode = i; inst.Instruction.Saturate = saturate; inst.Instruction.NumDstRegs = info->num_dst; inst.Instruction.NumSrcRegs = info->num_src; if (i >= TGSI_OPCODE_SAMPLE && i <= TGSI_OPCODE_GATHER4) { /* * These are not considered tex opcodes here (no additional * target argument) however we're required to set the Texture * bit so we can set the number of tex offsets. */ inst.Instruction.Texture = 1; inst.Texture.Texture = TGSI_TEXTURE_UNKNOWN; } /* Parse instruction operands. */ for (i = 0; i < info->num_dst + info->num_src + info->is_tex; i++) { if (i > 0) { eat_opt_white( &ctx->cur ); if (*ctx->cur != ',') { report_error( ctx, "Expected `,'" ); return FALSE; } ctx->cur++; eat_opt_white( &ctx->cur ); } if (i < info->num_dst) { if (!parse_dst_operand( ctx, &inst.Dst[i] )) return FALSE; } else if (i < info->num_dst + info->num_src) { if (!parse_src_operand( ctx, &inst.Src[i - info->num_dst] )) return FALSE; } else { uint j; for (j = 0; j < TGSI_TEXTURE_COUNT; j++) { if (str_match_nocase_whole( &ctx->cur, tgsi_texture_names[j] )) { inst.Instruction.Texture = 1; inst.Texture.Texture = j; break; } } if (j == TGSI_TEXTURE_COUNT) { report_error( ctx, "Expected texture target" ); return FALSE; } } } cur = ctx->cur; eat_opt_white( &cur ); for (i = 0; inst.Instruction.Texture && *cur == ','; i++) { cur++; eat_opt_white( &cur ); ctx->cur = cur; if (!parse_texoffset_operand( ctx, &inst.TexOffsets[i] )) return FALSE; cur = ctx->cur; eat_opt_white( &cur ); } inst.Texture.NumOffsets = i; cur = ctx->cur; eat_opt_white( &cur ); if (info->is_branch && *cur == ':') { uint target; cur++; eat_opt_white( &cur ); if (!parse_uint( &cur, &target )) { report_error( ctx, "Expected a label" ); return FALSE; } inst.Instruction.Label = 1; inst.Label.Label = target; ctx->cur = cur; } advance = tgsi_build_full_instruction( &inst, ctx->tokens_cur, ctx->header, (uint) (ctx->tokens_end - ctx->tokens_cur) ); if (advance == 0) return FALSE; ctx->tokens_cur += advance; return TRUE; } /* parses a 4-touple of the form {x, y, z, w} * where x, y, z, w are numbers */ static boolean parse_immediate_data(struct translate_ctx *ctx, unsigned type, union tgsi_immediate_data *values) { unsigned i; int ret; eat_opt_white( &ctx->cur ); if (*ctx->cur != '{') { report_error( ctx, "Expected `{'" ); return FALSE; } ctx->cur++; for (i = 0; i < 4; i++) { eat_opt_white( &ctx->cur ); if (i > 0) { if (*ctx->cur != ',') { report_error( ctx, "Expected `,'" ); return FALSE; } ctx->cur++; eat_opt_white( &ctx->cur ); } switch (type) { case TGSI_IMM_FLOAT64: ret = parse_double(&ctx->cur, &values[i].Uint, &values[i+1].Uint); i++; break; case TGSI_IMM_FLOAT32: ret = parse_float(&ctx->cur, &values[i].Float); break; case TGSI_IMM_UINT32: ret = parse_uint(&ctx->cur, &values[i].Uint); break; case TGSI_IMM_INT32: ret = parse_int(&ctx->cur, &values[i].Int); break; default: assert(0); ret = FALSE; break; } if (!ret) { report_error( ctx, "Expected immediate constant" ); return FALSE; } } eat_opt_white( &ctx->cur ); if (*ctx->cur != '}') { report_error( ctx, "Expected `}'" ); return FALSE; } ctx->cur++; return TRUE; } static boolean parse_declaration( struct translate_ctx *ctx ) { struct tgsi_full_declaration decl; uint file; struct parsed_dcl_bracket brackets[2]; int num_brackets; uint writemask; const char *cur, *cur2; uint advance; boolean is_vs_input; if (!eat_white( &ctx->cur )) { report_error( ctx, "Syntax error" ); return FALSE; } if (!parse_register_dcl( ctx, &file, brackets, &num_brackets)) return FALSE; if (!parse_opt_writemask( ctx, &writemask )) return FALSE; decl = tgsi_default_full_declaration(); decl.Declaration.File = file; decl.Declaration.UsageMask = writemask; if (num_brackets == 1) { decl.Range.First = brackets[0].first; decl.Range.Last = brackets[0].last; } else { decl.Range.First = brackets[1].first; decl.Range.Last = brackets[1].last; decl.Declaration.Dimension = 1; decl.Dim.Index2D = brackets[0].first; } is_vs_input = (file == TGSI_FILE_INPUT && ctx->processor == TGSI_PROCESSOR_VERTEX); cur = ctx->cur; eat_opt_white( &cur ); if (*cur == ',') { cur2 = cur; cur2++; eat_opt_white( &cur2 ); if (str_match_nocase_whole( &cur2, "ARRAY" )) { int arrayid; if (*cur2 != '(') { report_error( ctx, "Expected `('" ); return FALSE; } cur2++; eat_opt_white( &cur2 ); if (!parse_int( &cur2, &arrayid )) { report_error( ctx, "Expected `,'" ); return FALSE; } eat_opt_white( &cur2 ); if (*cur2 != ')') { report_error( ctx, "Expected `)'" ); return FALSE; } cur2++; decl.Declaration.Array = 1; decl.Array.ArrayID = arrayid; ctx->cur = cur = cur2; } } if (*cur == ',' && !is_vs_input) { uint i, j; cur++; eat_opt_white( &cur ); if (file == TGSI_FILE_RESOURCE) { for (i = 0; i < TGSI_TEXTURE_COUNT; i++) { if (str_match_nocase_whole(&cur, tgsi_texture_names[i])) { decl.Resource.Resource = i; break; } } if (i == TGSI_TEXTURE_COUNT) { report_error(ctx, "Expected texture target"); return FALSE; } cur2 = cur; eat_opt_white(&cur2); while (*cur2 == ',') { cur2++; eat_opt_white(&cur2); if (str_match_nocase_whole(&cur2, "RAW")) { decl.Resource.Raw = 1; } else if (str_match_nocase_whole(&cur2, "WR")) { decl.Resource.Writable = 1; } else { break; } cur = cur2; eat_opt_white(&cur2); } ctx->cur = cur; } else if (file == TGSI_FILE_SAMPLER_VIEW) { for (i = 0; i < TGSI_TEXTURE_COUNT; i++) { if (str_match_nocase_whole(&cur, tgsi_texture_names[i])) { decl.SamplerView.Resource = i; break; } } if (i == TGSI_TEXTURE_COUNT) { report_error(ctx, "Expected texture target"); return FALSE; } eat_opt_white( &cur ); if (*cur != ',') { report_error( ctx, "Expected `,'" ); return FALSE; } ++cur; eat_opt_white( &cur ); for (j = 0; j < 4; ++j) { for (i = 0; i < TGSI_RETURN_TYPE_COUNT; ++i) { if (str_match_nocase_whole(&cur, tgsi_return_type_names[i])) { switch (j) { case 0: decl.SamplerView.ReturnTypeX = i; break; case 1: decl.SamplerView.ReturnTypeY = i; break; case 2: decl.SamplerView.ReturnTypeZ = i; break; case 3: decl.SamplerView.ReturnTypeW = i; break; default: assert(0); } break; } } if (i == TGSI_RETURN_TYPE_COUNT) { if (j == 0 || j > 2) { report_error(ctx, "Expected type name"); return FALSE; } break; } else { cur2 = cur; eat_opt_white( &cur2 ); if (*cur2 == ',') { cur2++; eat_opt_white( &cur2 ); cur = cur2; continue; } else break; } } if (j < 4) { decl.SamplerView.ReturnTypeY = decl.SamplerView.ReturnTypeZ = decl.SamplerView.ReturnTypeW = decl.SamplerView.ReturnTypeX; } ctx->cur = cur; } else { if (str_match_nocase_whole(&cur, "LOCAL")) { decl.Declaration.Local = 1; ctx->cur = cur; } cur = ctx->cur; eat_opt_white( &cur ); if (*cur == ',') { cur++; eat_opt_white( &cur ); for (i = 0; i < TGSI_SEMANTIC_COUNT; i++) { if (str_match_nocase_whole(&cur, tgsi_semantic_names[i])) { uint index; cur2 = cur; eat_opt_white( &cur2 ); if (*cur2 == '[') { cur2++; eat_opt_white( &cur2 ); if (!parse_uint( &cur2, &index )) { report_error( ctx, "Expected literal integer" ); return FALSE; } eat_opt_white( &cur2 ); if (*cur2 != ']') { report_error( ctx, "Expected `]'" ); return FALSE; } cur2++; decl.Semantic.Index = index; cur = cur2; } decl.Declaration.Semantic = 1; decl.Semantic.Name = i; ctx->cur = cur; break; } } } } } cur = ctx->cur; eat_opt_white( &cur ); if (*cur == ',' && !is_vs_input) { uint i; cur++; eat_opt_white( &cur ); for (i = 0; i < TGSI_INTERPOLATE_COUNT; i++) { if (str_match_nocase_whole( &cur, tgsi_interpolate_names[i] )) { decl.Declaration.Interpolate = 1; decl.Interp.Interpolate = i; ctx->cur = cur; break; } } if (i == TGSI_INTERPOLATE_COUNT) { report_error( ctx, "Expected semantic or interpolate attribute" ); return FALSE; } } cur = ctx->cur; eat_opt_white( &cur ); if (*cur == ',' && !is_vs_input) { uint i; cur++; eat_opt_white( &cur ); for (i = 0; i < TGSI_INTERPOLATE_LOC_COUNT; i++) { if (str_match_nocase_whole( &cur, tgsi_interpolate_locations[i] )) { decl.Interp.Location = i; ctx->cur = cur; break; } } } advance = tgsi_build_full_declaration( &decl, ctx->tokens_cur, ctx->header, (uint) (ctx->tokens_end - ctx->tokens_cur) ); if (advance == 0) return FALSE; ctx->tokens_cur += advance; return TRUE; } static boolean parse_immediate( struct translate_ctx *ctx ) { struct tgsi_full_immediate imm; uint advance; int type; if (*ctx->cur == '[') { uint uindex; ++ctx->cur; eat_opt_white( &ctx->cur ); if (!parse_uint( &ctx->cur, &uindex )) { report_error( ctx, "Expected literal unsigned integer" ); return FALSE; } if (uindex != ctx->num_immediates) { report_error( ctx, "Immediates must be sorted" ); return FALSE; } eat_opt_white( &ctx->cur ); if (*ctx->cur != ']') { report_error( ctx, "Expected `]'" ); return FALSE; } ctx->cur++; } if (!eat_white( &ctx->cur )) { report_error( ctx, "Syntax error" ); return FALSE; } for (type = 0; type < Elements(tgsi_immediate_type_names); ++type) { if (str_match_nocase_whole(&ctx->cur, tgsi_immediate_type_names[type])) break; } if (type == Elements(tgsi_immediate_type_names)) { report_error( ctx, "Expected immediate type" ); return FALSE; } imm = tgsi_default_full_immediate(); imm.Immediate.NrTokens += 4; imm.Immediate.DataType = type; parse_immediate_data(ctx, type, imm.u); advance = tgsi_build_full_immediate( &imm, ctx->tokens_cur, ctx->header, (uint) (ctx->tokens_end - ctx->tokens_cur) ); if (advance == 0) return FALSE; ctx->tokens_cur += advance; ctx->num_immediates++; return TRUE; } static boolean parse_primitive( const char **pcur, uint *primitive ) { uint i; for (i = 0; i < PIPE_PRIM_MAX; i++) { const char *cur = *pcur; if (str_match_nocase_whole( &cur, tgsi_primitive_names[i])) { *primitive = i; *pcur = cur; return TRUE; } } return FALSE; } static boolean parse_fs_coord_origin( const char **pcur, uint *fs_coord_origin ) { uint i; for (i = 0; i < Elements(tgsi_fs_coord_origin_names); i++) { const char *cur = *pcur; if (str_match_nocase_whole( &cur, tgsi_fs_coord_origin_names[i])) { *fs_coord_origin = i; *pcur = cur; return TRUE; } } return FALSE; } static boolean parse_fs_coord_pixel_center( const char **pcur, uint *fs_coord_pixel_center ) { uint i; for (i = 0; i < Elements(tgsi_fs_coord_pixel_center_names); i++) { const char *cur = *pcur; if (str_match_nocase_whole( &cur, tgsi_fs_coord_pixel_center_names[i])) { *fs_coord_pixel_center = i; *pcur = cur; return TRUE; } } return FALSE; } static boolean parse_property( struct translate_ctx *ctx ) { struct tgsi_full_property prop; uint property_name; uint values[8]; uint advance; char id[64]; if (!eat_white( &ctx->cur )) { report_error( ctx, "Syntax error" ); return FALSE; } report_error( ctx, "Syntax error" ); return FALSE; } if (!parse_identifier( &ctx->cur, id, sizeof(id) )) { report_error( ctx, "Syntax error" ); return FALSE; } break; } }
[ "CWE-119" ]
virglrenderer
e534b51ca3c3cd25f3990589932a9ed711c59b27
72378232091169844659239787043415407980
178,123
158,101
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
int vrend_create_vertex_elements_state(struct vrend_context *ctx, uint32_t handle, unsigned num_elements, const struct pipe_vertex_element *elements) { struct vrend_vertex_element_array *v = CALLOC_STRUCT(vrend_vertex_element_array); const struct util_format_description *desc; GLenum type; int i; uint32_t ret_handle; if (!v) return ENOMEM; v->count = num_elements; for (i = 0; i < num_elements; i++) { memcpy(&v->elements[i].base, &elements[i], sizeof(struct pipe_vertex_element)); FREE(v); return EINVAL; } type = GL_FALSE; if (desc->channel[0].type == UTIL_FORMAT_TYPE_FLOAT) { if (desc->channel[0].size == 32) type = GL_FLOAT; else if (desc->channel[0].size == 64) type = GL_DOUBLE; else if (desc->channel[0].size == 16) type = GL_HALF_FLOAT; } else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED && desc->channel[0].size == 8) type = GL_UNSIGNED_BYTE; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED && desc->channel[0].size == 8) type = GL_BYTE; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED && desc->channel[0].size == 16) type = GL_UNSIGNED_SHORT; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED && desc->channel[0].size == 16) type = GL_SHORT; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED && desc->channel[0].size == 32) type = GL_UNSIGNED_INT; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED && desc->channel[0].size == 32) type = GL_INT; else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SSCALED || elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SNORM || elements[i].src_format == PIPE_FORMAT_B10G10R10A2_SNORM) type = GL_INT_2_10_10_10_REV; else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_USCALED || elements[i].src_format == PIPE_FORMAT_R10G10B10A2_UNORM || elements[i].src_format == PIPE_FORMAT_B10G10R10A2_UNORM) type = GL_UNSIGNED_INT_2_10_10_10_REV; else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT) type = GL_UNSIGNED_INT_10F_11F_11F_REV; if (type == GL_FALSE) { report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_VERTEX_FORMAT, elements[i].src_format); FREE(v); return EINVAL; } v->elements[i].type = type; if (desc->channel[0].normalized) v->elements[i].norm = GL_TRUE; if (desc->nr_channels == 4 && desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_Z) v->elements[i].nr_chan = GL_BGRA; else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT) v->elements[i].nr_chan = 3; else v->elements[i].nr_chan = desc->nr_channels; }
[ "CWE-119" ]
virglrenderer
114688c526fe45f341d75ccd1d85473c3b08f7a7
127813115019639337707795536823961346235
178,126
242
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
int vrend_create_vertex_elements_state(struct vrend_context *ctx, uint32_t handle, unsigned num_elements, const struct pipe_vertex_element *elements) { struct vrend_vertex_element_array *v = CALLOC_STRUCT(vrend_vertex_element_array); const struct util_format_description *desc; GLenum type; int i; uint32_t ret_handle; if (!v) return ENOMEM; if (num_elements > PIPE_MAX_ATTRIBS) return EINVAL; v->count = num_elements; for (i = 0; i < num_elements; i++) { memcpy(&v->elements[i].base, &elements[i], sizeof(struct pipe_vertex_element)); FREE(v); return EINVAL; } type = GL_FALSE; if (desc->channel[0].type == UTIL_FORMAT_TYPE_FLOAT) { if (desc->channel[0].size == 32) type = GL_FLOAT; else if (desc->channel[0].size == 64) type = GL_DOUBLE; else if (desc->channel[0].size == 16) type = GL_HALF_FLOAT; } else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED && desc->channel[0].size == 8) type = GL_UNSIGNED_BYTE; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED && desc->channel[0].size == 8) type = GL_BYTE; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED && desc->channel[0].size == 16) type = GL_UNSIGNED_SHORT; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED && desc->channel[0].size == 16) type = GL_SHORT; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED && desc->channel[0].size == 32) type = GL_UNSIGNED_INT; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED && desc->channel[0].size == 32) type = GL_INT; else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SSCALED || elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SNORM || elements[i].src_format == PIPE_FORMAT_B10G10R10A2_SNORM) type = GL_INT_2_10_10_10_REV; else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_USCALED || elements[i].src_format == PIPE_FORMAT_R10G10B10A2_UNORM || elements[i].src_format == PIPE_FORMAT_B10G10R10A2_UNORM) type = GL_UNSIGNED_INT_2_10_10_10_REV; else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT) type = GL_UNSIGNED_INT_10F_11F_11F_REV; if (type == GL_FALSE) { report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_VERTEX_FORMAT, elements[i].src_format); FREE(v); return EINVAL; } v->elements[i].type = type; if (desc->channel[0].normalized) v->elements[i].norm = GL_TRUE; if (desc->nr_channels == 4 && desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_Z) v->elements[i].nr_chan = GL_BGRA; else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT) v->elements[i].nr_chan = 3; else v->elements[i].nr_chan = desc->nr_channels; }
[ "CWE-119" ]
virglrenderer
114688c526fe45f341d75ccd1d85473c3b08f7a7
226301324475184087438442572611658189614
178,126
158,102
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
static int vrend_decode_create_ve(struct vrend_decode_ctx *ctx, uint32_t handle, uint16_t length) { struct pipe_vertex_element *ve = NULL; int num_elements; int i; int ret; if (length < 1) return EINVAL; if ((length - 1) % 4) return EINVAL; num_elements = (length - 1) / 4; if (num_elements) { ve = calloc(num_elements, sizeof(struct pipe_vertex_element)); if (!ve) return ENOMEM; for (i = 0; i < num_elements; i++) { ve[i].src_offset = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_OFFSET(i)); ve[i].instance_divisor = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_INSTANCE_DIVISOR(i)); ve[i].vertex_buffer_index = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_VERTEX_BUFFER_INDEX(i)); ve[i].src_format = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_FORMAT(i)); } } return ret; }
[ "CWE-125" ]
virglrenderer
a5ac49940c40ae415eac0cf912eac7070b4ba95d
279616717599430675241465878003165352261
178,129
243
The product reads data past the end, or before the beginning, of the intended buffer.
true
static int vrend_decode_create_ve(struct vrend_decode_ctx *ctx, uint32_t handle, uint16_t length) { struct pipe_vertex_element *ve = NULL; int num_elements; int i; int ret; if (length < 1) return EINVAL; if ((length - 1) % 4) return EINVAL; num_elements = (length - 1) / 4; if (num_elements) { ve = calloc(num_elements, sizeof(struct pipe_vertex_element)); if (!ve) return ENOMEM; for (i = 0; i < num_elements; i++) { ve[i].src_offset = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_OFFSET(i)); ve[i].instance_divisor = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_INSTANCE_DIVISOR(i)); ve[i].vertex_buffer_index = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_VERTEX_BUFFER_INDEX(i)); if (ve[i].vertex_buffer_index >= PIPE_MAX_ATTRIBS) return EINVAL; ve[i].src_format = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_FORMAT(i)); } } return ret; }
[ "CWE-125" ]
virglrenderer
a5ac49940c40ae415eac0cf912eac7070b4ba95d
129688850372043760228352545289414617217
178,129
158,104
The product reads data past the end, or before the beginning, of the intended buffer.
false
static void set_banner(struct openconnect_info *vpninfo) { char *banner, *q; const char *p; if (!vpninfo->banner || !(banner = malloc(strlen(vpninfo->banner)))) { unsetenv("CISCO_BANNER"); return; } p = vpninfo->banner; q = banner; while (*p) { if (*p == '%' && isxdigit((int)(unsigned char)p[1]) && isxdigit((int)(unsigned char)p[2])) { *(q++) = unhex(p + 1); p += 3; } else *(q++) = *(p++); } *q = 0; setenv("CISCO_BANNER", banner, 1); free(banner); }
[ "CWE-119" ]
infradead
14cae65318d3ef1f7d449e463b72b6934e82f1c2
174272131383202600271920404270020112167
178,132
246
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
static void set_banner(struct openconnect_info *vpninfo) { char *banner, *q; const char *p; if (!vpninfo->banner || !(banner = malloc(strlen(vpninfo->banner)+1))) { unsetenv("CISCO_BANNER"); return; } p = vpninfo->banner; q = banner; while (*p) { if (*p == '%' && isxdigit((int)(unsigned char)p[1]) && isxdigit((int)(unsigned char)p[2])) { *(q++) = unhex(p + 1); p += 3; } else *(q++) = *(p++); } *q = 0; setenv("CISCO_BANNER", banner, 1); free(banner); }
[ "CWE-119" ]
infradead
14cae65318d3ef1f7d449e463b72b6934e82f1c2
279834395077552091770358368547534380658
178,132
158,105
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *limit, int *al) { unsigned short type; unsigned short size; unsigned short len; unsigned char *data = *p; int renegotiate_seen = 0; int sigalg_seen = 0; s->servername_done = 0; s->tlsext_status_type = -1; # ifndef OPENSSL_NO_NEXTPROTONEG s->s3->next_proto_neg_seen = 0; # endif # ifndef OPENSSL_NO_HEARTBEATS s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED | SSL_TLSEXT_HB_DONT_SEND_REQUESTS); # endif # ifndef OPENSSL_NO_EC if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG) ssl_check_for_safari(s, data, limit); # endif /* !OPENSSL_NO_EC */ # ifndef OPENSSL_NO_SRP if (s->srp_ctx.login != NULL) { OPENSSL_free(s->srp_ctx.login); s->srp_ctx.login = NULL; } # endif s->srtp_profile = NULL; if (data == limit) goto ri_check; if (limit - data < 2) goto err; n2s(data, len); if (limit - data != len) goto err; while (limit - data >= 4) { n2s(data, type); n2s(data, size); if (limit - data < size) goto err; # if 0 fprintf(stderr, "Received extension type %d size %d\n", type, size); # endif if (s->tlsext_debug_cb) s->tlsext_debug_cb(s, 0, type, data, size, s->tlsext_debug_arg); /*- * The servername extension is treated as follows: * * - Only the hostname type is supported with a maximum length of 255. * - The servername is rejected if too long or if it contains zeros, * in which case an fatal alert is generated. * - The servername field is maintained together with the session cache. * - When a session is resumed, the servername call back invoked in order * to allow the application to position itself to the right context. * - The servername is acknowledged if it is new for a session or when * it is identical to a previously used for the same session. * Applications can control the behaviour. They can at any time * set a 'desirable' servername for a new SSL object. This can be the * case for example with HTTPS when a Host: header field is received and * a renegotiation is requested. In this case, a possible servername * presented in the new client hello is only acknowledged if it matches * the value of the Host: field. * - Applications must use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION * if they provide for changing an explicit servername context for the * session, i.e. when the session has been established with a servername * extension. * - On session reconnect, the servername extension may be absent. * */ if (type == TLSEXT_TYPE_server_name) { unsigned char *sdata; int servname_type; int dsize; if (size < 2) goto err; n2s(data, dsize); size -= 2; if (dsize > size) goto err; sdata = data; while (dsize > 3) { servname_type = *(sdata++); n2s(sdata, len); dsize -= 3; if (len > dsize) goto err; if (s->servername_done == 0) switch (servname_type) { case TLSEXT_NAMETYPE_host_name: if (!s->hit) { if (s->session->tlsext_hostname) goto err; if (len > TLSEXT_MAXLEN_host_name) { *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } if ((s->session->tlsext_hostname = OPENSSL_malloc(len + 1)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->session->tlsext_hostname, sdata, len); s->session->tlsext_hostname[len] = '\0'; if (strlen(s->session->tlsext_hostname) != len) { OPENSSL_free(s->session->tlsext_hostname); s->session->tlsext_hostname = NULL; *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } s->servername_done = 1; } else s->servername_done = s->session->tlsext_hostname && strlen(s->session->tlsext_hostname) == len && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0; break; default: break; } dsize -= len; } if (dsize != 0) goto err; } # ifndef OPENSSL_NO_SRP else if (type == TLSEXT_TYPE_srp) { if (size == 0 || ((len = data[0])) != (size - 1)) goto err; if (s->srp_ctx.login != NULL) goto err; if ((s->srp_ctx.login = OPENSSL_malloc(len + 1)) == NULL) return -1; memcpy(s->srp_ctx.login, &data[1], len); s->srp_ctx.login[len] = '\0'; if (strlen(s->srp_ctx.login) != len) goto err; } # endif # ifndef OPENSSL_NO_EC else if (type == TLSEXT_TYPE_ec_point_formats) { unsigned char *sdata = data; int ecpointformatlist_length = *(sdata++); if (ecpointformatlist_length != size - 1) goto err; if (!s->hit) { if (s->session->tlsext_ecpointformatlist) { OPENSSL_free(s->session->tlsext_ecpointformatlist); s->session->tlsext_ecpointformatlist = NULL; } s->session->tlsext_ecpointformatlist_length = 0; if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length; memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length); } # if 0 fprintf(stderr, "ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length); sdata = s->session->tlsext_ecpointformatlist; for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) fprintf(stderr, "%i ", *(sdata++)); fprintf(stderr, "\n"); # endif } else if (type == TLSEXT_TYPE_elliptic_curves) { unsigned char *sdata = data; int ellipticcurvelist_length = (*(sdata++) << 8); ellipticcurvelist_length += (*(sdata++)); if (ellipticcurvelist_length != size - 2 || ellipticcurvelist_length < 1 || /* Each NamedCurve is 2 bytes. */ ellipticcurvelist_length & 1) goto err; if (!s->hit) { if (s->session->tlsext_ellipticcurvelist) goto err; s->session->tlsext_ellipticcurvelist_length = 0; if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length; memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length); } # if 0 fprintf(stderr, "ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length); sdata = s->session->tlsext_ellipticcurvelist; for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++) fprintf(stderr, "%i ", *(sdata++)); fprintf(stderr, "\n"); # endif } # endif /* OPENSSL_NO_EC */ # ifdef TLSEXT_TYPE_opaque_prf_input else if (type == TLSEXT_TYPE_opaque_prf_input && s->version != DTLS1_VERSION) { unsigned char *sdata = data; if (size < 2) { *al = SSL_AD_DECODE_ERROR; return 0; } n2s(sdata, s->s3->client_opaque_prf_input_len); if (s->s3->client_opaque_prf_input_len != size - 2) { *al = SSL_AD_DECODE_ERROR; return 0; } if (s->s3->client_opaque_prf_input != NULL) { /* shouldn't really happen */ OPENSSL_free(s->s3->client_opaque_prf_input); } /* dummy byte just to get non-NULL */ if (s->s3->client_opaque_prf_input_len == 0) s->s3->client_opaque_prf_input = OPENSSL_malloc(1); else s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len); if (s->s3->client_opaque_prf_input == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } # endif else if (type == TLSEXT_TYPE_session_ticket) { if (s->tls_session_ticket_ext_cb && !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg)) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } else if (type == TLSEXT_TYPE_renegotiate) { if (!ssl_parse_clienthello_renegotiate_ext(s, data, size, al)) return 0; renegotiate_seen = 1; } else if (type == TLSEXT_TYPE_signature_algorithms) { int dsize; if (sigalg_seen || size < 2) goto err; sigalg_seen = 1; n2s(data, dsize); size -= 2; if (dsize != size || dsize & 1) goto err; if (!tls1_process_sigalgs(s, data, dsize)) goto err; } else if (type == TLSEXT_TYPE_status_request && s->version != DTLS1_VERSION) { if (size < 5) goto err; s->tlsext_status_type = *data++; size--; if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) { const unsigned char *sdata; int dsize; /* Read in responder_id_list */ n2s(data, dsize); size -= 2; if (dsize > size) goto err; while (dsize > 0) { OCSP_RESPID *id; int idsize; && !(s->tlsext_ocsp_ids = sk_OCSP_RESPID_new_null())) { OCSP_RESPID_free(id); *al = SSL_AD_INTERNAL_ERROR; return 0; } if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) { OCSP_RESPID_free(id); *al = SSL_AD_INTERNAL_ERROR; return 0; } } OCSP_RESPID_free(id); goto err; } if (!s->tlsext_ocsp_ids && !(s->tlsext_ocsp_ids = sk_OCSP_RESPID_new_null())) { OCSP_RESPID_free(id); *al = SSL_AD_INTERNAL_ERROR; return 0; } if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) { OCSP_RESPID_free(id); *al = SSL_AD_INTERNAL_ERROR; goto err; sdata = data; if (dsize > 0) { if (s->tlsext_ocsp_exts) { sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts, X509_EXTENSION_free); } s->tlsext_ocsp_exts = d2i_X509_EXTENSIONS(NULL, &sdata, dsize); if (!s->tlsext_ocsp_exts || (data + dsize != sdata)) goto err; } } /* * We don't know what to do with any other type * so ignore it. */ else s->tlsext_status_type = -1; } # ifndef OPENSSL_NO_HEARTBEATS else if (type == TLSEXT_TYPE_heartbeat) { switch (data[0]) { case 0x01: /* Client allows us to send HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; break; case 0x02: /* Client doesn't accept HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS; break; default: *al = SSL_AD_ILLEGAL_PARAMETER; return 0; } } # endif # ifndef OPENSSL_NO_NEXTPROTONEG else if (type == TLSEXT_TYPE_next_proto_neg && s->s3->tmp.finish_md_len == 0) { /*- * We shouldn't accept this extension on a * renegotiation. * * s->new_session will be set on renegotiation, but we * probably shouldn't rely that it couldn't be set on * the initial renegotation too in certain cases (when * there's some other reason to disallow resuming an * earlier session -- the current code won't be doing * anything like that, but this might change). * * A valid sign that there's been a previous handshake * in this connection is if s->s3->tmp.finish_md_len > * 0. (We are talking about a check that will happen * in the Hello protocol round, well before a new * Finished message could have been computed.) */ s->s3->next_proto_neg_seen = 1; } # endif /* session ticket processed earlier */ # ifndef OPENSSL_NO_SRTP else if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s) && type == TLSEXT_TYPE_use_srtp) { if (ssl_parse_clienthello_use_srtp_ext(s, data, size, al)) return 0; } # endif data += size; } /* Spurious data on the end */ if (data != limit) goto err; *p = data; ri_check: /* Need RI if renegotiating */ if (!renegotiate_seen && s->renegotiate && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { *al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); return 0; } return 1; err: *al = SSL_AD_DECODE_ERROR; return 0; }
[ "CWE-399" ]
openssl
2c0d295e26306e15a92eb23a84a1802005c1c137
29224115480775327782453555135433777408
178,136
249
This vulnerability category highlights issues in resource management where failures to properly release memory, file handles, or other resources can degrade system performance or enable denial-of-service conditions.
true
int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *limit, int *al) { unsigned short type; unsigned short size; unsigned short len; unsigned char *data = *p; int renegotiate_seen = 0; int sigalg_seen = 0; s->servername_done = 0; s->tlsext_status_type = -1; # ifndef OPENSSL_NO_NEXTPROTONEG s->s3->next_proto_neg_seen = 0; # endif # ifndef OPENSSL_NO_HEARTBEATS s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED | SSL_TLSEXT_HB_DONT_SEND_REQUESTS); # endif # ifndef OPENSSL_NO_EC if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG) ssl_check_for_safari(s, data, limit); # endif /* !OPENSSL_NO_EC */ # ifndef OPENSSL_NO_SRP if (s->srp_ctx.login != NULL) { OPENSSL_free(s->srp_ctx.login); s->srp_ctx.login = NULL; } # endif s->srtp_profile = NULL; if (data == limit) goto ri_check; if (limit - data < 2) goto err; n2s(data, len); if (limit - data != len) goto err; while (limit - data >= 4) { n2s(data, type); n2s(data, size); if (limit - data < size) goto err; # if 0 fprintf(stderr, "Received extension type %d size %d\n", type, size); # endif if (s->tlsext_debug_cb) s->tlsext_debug_cb(s, 0, type, data, size, s->tlsext_debug_arg); /*- * The servername extension is treated as follows: * * - Only the hostname type is supported with a maximum length of 255. * - The servername is rejected if too long or if it contains zeros, * in which case an fatal alert is generated. * - The servername field is maintained together with the session cache. * - When a session is resumed, the servername call back invoked in order * to allow the application to position itself to the right context. * - The servername is acknowledged if it is new for a session or when * it is identical to a previously used for the same session. * Applications can control the behaviour. They can at any time * set a 'desirable' servername for a new SSL object. This can be the * case for example with HTTPS when a Host: header field is received and * a renegotiation is requested. In this case, a possible servername * presented in the new client hello is only acknowledged if it matches * the value of the Host: field. * - Applications must use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION * if they provide for changing an explicit servername context for the * session, i.e. when the session has been established with a servername * extension. * - On session reconnect, the servername extension may be absent. * */ if (type == TLSEXT_TYPE_server_name) { unsigned char *sdata; int servname_type; int dsize; if (size < 2) goto err; n2s(data, dsize); size -= 2; if (dsize > size) goto err; sdata = data; while (dsize > 3) { servname_type = *(sdata++); n2s(sdata, len); dsize -= 3; if (len > dsize) goto err; if (s->servername_done == 0) switch (servname_type) { case TLSEXT_NAMETYPE_host_name: if (!s->hit) { if (s->session->tlsext_hostname) goto err; if (len > TLSEXT_MAXLEN_host_name) { *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } if ((s->session->tlsext_hostname = OPENSSL_malloc(len + 1)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->session->tlsext_hostname, sdata, len); s->session->tlsext_hostname[len] = '\0'; if (strlen(s->session->tlsext_hostname) != len) { OPENSSL_free(s->session->tlsext_hostname); s->session->tlsext_hostname = NULL; *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } s->servername_done = 1; } else s->servername_done = s->session->tlsext_hostname && strlen(s->session->tlsext_hostname) == len && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0; break; default: break; } dsize -= len; } if (dsize != 0) goto err; } # ifndef OPENSSL_NO_SRP else if (type == TLSEXT_TYPE_srp) { if (size == 0 || ((len = data[0])) != (size - 1)) goto err; if (s->srp_ctx.login != NULL) goto err; if ((s->srp_ctx.login = OPENSSL_malloc(len + 1)) == NULL) return -1; memcpy(s->srp_ctx.login, &data[1], len); s->srp_ctx.login[len] = '\0'; if (strlen(s->srp_ctx.login) != len) goto err; } # endif # ifndef OPENSSL_NO_EC else if (type == TLSEXT_TYPE_ec_point_formats) { unsigned char *sdata = data; int ecpointformatlist_length = *(sdata++); if (ecpointformatlist_length != size - 1) goto err; if (!s->hit) { if (s->session->tlsext_ecpointformatlist) { OPENSSL_free(s->session->tlsext_ecpointformatlist); s->session->tlsext_ecpointformatlist = NULL; } s->session->tlsext_ecpointformatlist_length = 0; if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length; memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length); } # if 0 fprintf(stderr, "ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length); sdata = s->session->tlsext_ecpointformatlist; for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) fprintf(stderr, "%i ", *(sdata++)); fprintf(stderr, "\n"); # endif } else if (type == TLSEXT_TYPE_elliptic_curves) { unsigned char *sdata = data; int ellipticcurvelist_length = (*(sdata++) << 8); ellipticcurvelist_length += (*(sdata++)); if (ellipticcurvelist_length != size - 2 || ellipticcurvelist_length < 1 || /* Each NamedCurve is 2 bytes. */ ellipticcurvelist_length & 1) goto err; if (!s->hit) { if (s->session->tlsext_ellipticcurvelist) goto err; s->session->tlsext_ellipticcurvelist_length = 0; if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length; memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length); } # if 0 fprintf(stderr, "ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length); sdata = s->session->tlsext_ellipticcurvelist; for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++) fprintf(stderr, "%i ", *(sdata++)); fprintf(stderr, "\n"); # endif } # endif /* OPENSSL_NO_EC */ # ifdef TLSEXT_TYPE_opaque_prf_input else if (type == TLSEXT_TYPE_opaque_prf_input && s->version != DTLS1_VERSION) { unsigned char *sdata = data; if (size < 2) { *al = SSL_AD_DECODE_ERROR; return 0; } n2s(sdata, s->s3->client_opaque_prf_input_len); if (s->s3->client_opaque_prf_input_len != size - 2) { *al = SSL_AD_DECODE_ERROR; return 0; } if (s->s3->client_opaque_prf_input != NULL) { /* shouldn't really happen */ OPENSSL_free(s->s3->client_opaque_prf_input); } /* dummy byte just to get non-NULL */ if (s->s3->client_opaque_prf_input_len == 0) s->s3->client_opaque_prf_input = OPENSSL_malloc(1); else s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len); if (s->s3->client_opaque_prf_input == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } # endif else if (type == TLSEXT_TYPE_session_ticket) { if (s->tls_session_ticket_ext_cb && !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg)) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } else if (type == TLSEXT_TYPE_renegotiate) { if (!ssl_parse_clienthello_renegotiate_ext(s, data, size, al)) return 0; renegotiate_seen = 1; } else if (type == TLSEXT_TYPE_signature_algorithms) { int dsize; if (sigalg_seen || size < 2) goto err; sigalg_seen = 1; n2s(data, dsize); size -= 2; if (dsize != size || dsize & 1) goto err; if (!tls1_process_sigalgs(s, data, dsize)) goto err; } else if (type == TLSEXT_TYPE_status_request && s->version != DTLS1_VERSION) { if (size < 5) goto err; s->tlsext_status_type = *data++; size--; if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) { const unsigned char *sdata; int dsize; /* Read in responder_id_list */ n2s(data, dsize); size -= 2; if (dsize > size) goto err; /* * We remove any OCSP_RESPIDs from a previous handshake * to prevent unbounded memory growth - CVE-2016-6304 */ sk_OCSP_RESPID_pop_free(s->tlsext_ocsp_ids, OCSP_RESPID_free); if (dsize > 0) { s->tlsext_ocsp_ids = sk_OCSP_RESPID_new_null(); if (s->tlsext_ocsp_ids == NULL) { *al = SSL_AD_INTERNAL_ERROR; return 0; } } else { s->tlsext_ocsp_ids = NULL; } while (dsize > 0) { OCSP_RESPID *id; int idsize; && !(s->tlsext_ocsp_ids = sk_OCSP_RESPID_new_null())) { OCSP_RESPID_free(id); *al = SSL_AD_INTERNAL_ERROR; return 0; } if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) { OCSP_RESPID_free(id); *al = SSL_AD_INTERNAL_ERROR; return 0; } } OCSP_RESPID_free(id); goto err; } if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) { OCSP_RESPID_free(id); *al = SSL_AD_INTERNAL_ERROR; goto err; sdata = data; if (dsize > 0) { if (s->tlsext_ocsp_exts) { sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts, X509_EXTENSION_free); } s->tlsext_ocsp_exts = d2i_X509_EXTENSIONS(NULL, &sdata, dsize); if (!s->tlsext_ocsp_exts || (data + dsize != sdata)) goto err; } } /* * We don't know what to do with any other type * so ignore it. */ else s->tlsext_status_type = -1; } # ifndef OPENSSL_NO_HEARTBEATS else if (type == TLSEXT_TYPE_heartbeat) { switch (data[0]) { case 0x01: /* Client allows us to send HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; break; case 0x02: /* Client doesn't accept HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS; break; default: *al = SSL_AD_ILLEGAL_PARAMETER; return 0; } } # endif # ifndef OPENSSL_NO_NEXTPROTONEG else if (type == TLSEXT_TYPE_next_proto_neg && s->s3->tmp.finish_md_len == 0) { /*- * We shouldn't accept this extension on a * renegotiation. * * s->new_session will be set on renegotiation, but we * probably shouldn't rely that it couldn't be set on * the initial renegotation too in certain cases (when * there's some other reason to disallow resuming an * earlier session -- the current code won't be doing * anything like that, but this might change). * * A valid sign that there's been a previous handshake * in this connection is if s->s3->tmp.finish_md_len > * 0. (We are talking about a check that will happen * in the Hello protocol round, well before a new * Finished message could have been computed.) */ s->s3->next_proto_neg_seen = 1; } # endif /* session ticket processed earlier */ # ifndef OPENSSL_NO_SRTP else if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s) && type == TLSEXT_TYPE_use_srtp) { if (ssl_parse_clienthello_use_srtp_ext(s, data, size, al)) return 0; } # endif data += size; } /* Spurious data on the end */ if (data != limit) goto err; *p = data; ri_check: /* Need RI if renegotiating */ if (!renegotiate_seen && s->renegotiate && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { *al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); return 0; } return 1; err: *al = SSL_AD_DECODE_ERROR; return 0; }
[ "CWE-399" ]
openssl
2c0d295e26306e15a92eb23a84a1802005c1c137
50008233472111594579570026097454618108
178,136
158,108
This vulnerability category highlights issues in resource management where failures to properly release memory, file handles, or other resources can degrade system performance or enable denial-of-service conditions.
false
static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen, const unsigned char *sess_id, int sesslen, SSL_SESSION **psess) { SSL_SESSION *sess; unsigned char *sdec; const unsigned char *p; int slen, mlen, renew_ticket = 0, ret = -1; unsigned char tick_hmac[EVP_MAX_MD_SIZE]; HMAC_CTX *hctx = NULL; EVP_CIPHER_CTX *ctx; SSL_CTX *tctx = s->initial_ctx; /* Need at least keyname + iv + some encrypted data */ if (eticklen < 48) return 2; /* Initialize session ticket encryption and HMAC contexts */ hctx = HMAC_CTX_new(); if (hctx == NULL) hctx = HMAC_CTX_new(); if (hctx == NULL) return -2; ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) { ret = -2; goto err; } if (tctx->tlsext_ticket_key_cb) { unsigned char *nctick = (unsigned char *)etick; int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16, ctx, hctx, 0); if (rv < 0) goto err; if (rv == 0) { ret = 2; goto err; } if (rv == 2) renew_ticket = 1; } else { /* Check key name matches */ if (memcmp(etick, tctx->tlsext_tick_key_name, sizeof(tctx->tlsext_tick_key_name)) != 0) { ret = 2; goto err; } if (HMAC_Init_ex(hctx, tctx->tlsext_tick_hmac_key, sizeof(tctx->tlsext_tick_hmac_key), EVP_sha256(), NULL) <= 0 || EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, tctx->tlsext_tick_aes_key, etick + sizeof(tctx->tlsext_tick_key_name)) <= 0) { goto err; } } /* * Attempt to process session ticket, first conduct sanity and integrity * checks on ticket. if (mlen < 0) { goto err; } eticklen -= mlen; /* Check HMAC of encrypted ticket */ if (HMAC_Update(hctx, etick, eticklen) <= 0 if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen)) { EVP_CIPHER_CTX_free(ctx); return 2; } /* Attempt to decrypt session data */ /* Move p after IV to start of encrypted ticket, update length */ p = etick + 16 + EVP_CIPHER_CTX_iv_length(ctx); eticklen -= 16 + EVP_CIPHER_CTX_iv_length(ctx); sdec = OPENSSL_malloc(eticklen); if (sdec == NULL || EVP_DecryptUpdate(ctx, sdec, &slen, p, eticklen) <= 0) { EVP_CIPHER_CTX_free(ctx); OPENSSL_free(sdec); return -1; } if (EVP_DecryptFinal(ctx, sdec + slen, &mlen) <= 0) { EVP_CIPHER_CTX_free(ctx); OPENSSL_free(sdec); return 2; } slen += mlen; EVP_CIPHER_CTX_free(ctx); ctx = NULL; p = sdec; sess = d2i_SSL_SESSION(NULL, &p, slen); OPENSSL_free(sdec); if (sess) { /* * The session ID, if non-empty, is used by some clients to detect * that the ticket has been accepted. So we copy it to the session * structure. If it is empty set length to zero as required by * standard. */ if (sesslen) memcpy(sess->session_id, sess_id, sesslen); sess->session_id_length = sesslen; *psess = sess; if (renew_ticket) return 4; else return 3; } ERR_clear_error(); /* * For session parse failure, indicate that we need to send a new ticket. */ return 2; err: EVP_CIPHER_CTX_free(ctx); HMAC_CTX_free(hctx); return ret; }
[ "CWE-20" ]
openssl
e97763c92c655dcf4af2860b3abd2bc4c8a267f9
2230119928438274047665345409737174926
178,138
250
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
true
static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen, const unsigned char *sess_id, int sesslen, SSL_SESSION **psess) { SSL_SESSION *sess; unsigned char *sdec; const unsigned char *p; int slen, mlen, renew_ticket = 0, ret = -1; unsigned char tick_hmac[EVP_MAX_MD_SIZE]; HMAC_CTX *hctx = NULL; EVP_CIPHER_CTX *ctx; SSL_CTX *tctx = s->initial_ctx; /* Initialize session ticket encryption and HMAC contexts */ hctx = HMAC_CTX_new(); if (hctx == NULL) hctx = HMAC_CTX_new(); if (hctx == NULL) return -2; ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) { ret = -2; goto err; } if (tctx->tlsext_ticket_key_cb) { unsigned char *nctick = (unsigned char *)etick; int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16, ctx, hctx, 0); if (rv < 0) goto err; if (rv == 0) { ret = 2; goto err; } if (rv == 2) renew_ticket = 1; } else { /* Check key name matches */ if (memcmp(etick, tctx->tlsext_tick_key_name, sizeof(tctx->tlsext_tick_key_name)) != 0) { ret = 2; goto err; } if (HMAC_Init_ex(hctx, tctx->tlsext_tick_hmac_key, sizeof(tctx->tlsext_tick_hmac_key), EVP_sha256(), NULL) <= 0 || EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, tctx->tlsext_tick_aes_key, etick + sizeof(tctx->tlsext_tick_key_name)) <= 0) { goto err; } } /* * Attempt to process session ticket, first conduct sanity and integrity * checks on ticket. if (mlen < 0) { goto err; } /* Sanity check ticket length: must exceed keyname + IV + HMAC */ if (eticklen <= TLSEXT_KEYNAME_LENGTH + EVP_CIPHER_CTX_iv_length(ctx) + mlen) { ret = 2; goto err; } eticklen -= mlen; /* Check HMAC of encrypted ticket */ if (HMAC_Update(hctx, etick, eticklen) <= 0 if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen)) { EVP_CIPHER_CTX_free(ctx); return 2; } /* Attempt to decrypt session data */ /* Move p after IV to start of encrypted ticket, update length */ p = etick + 16 + EVP_CIPHER_CTX_iv_length(ctx); eticklen -= 16 + EVP_CIPHER_CTX_iv_length(ctx); sdec = OPENSSL_malloc(eticklen); if (sdec == NULL || EVP_DecryptUpdate(ctx, sdec, &slen, p, eticklen) <= 0) { EVP_CIPHER_CTX_free(ctx); OPENSSL_free(sdec); return -1; } if (EVP_DecryptFinal(ctx, sdec + slen, &mlen) <= 0) { EVP_CIPHER_CTX_free(ctx); OPENSSL_free(sdec); return 2; } slen += mlen; EVP_CIPHER_CTX_free(ctx); ctx = NULL; p = sdec; sess = d2i_SSL_SESSION(NULL, &p, slen); OPENSSL_free(sdec); if (sess) { /* * The session ID, if non-empty, is used by some clients to detect * that the ticket has been accepted. So we copy it to the session * structure. If it is empty set length to zero as required by * standard. */ if (sesslen) memcpy(sess->session_id, sess_id, sesslen); sess->session_id_length = sesslen; *psess = sess; if (renew_ticket) return 4; else return 3; } ERR_clear_error(); /* * For session parse failure, indicate that we need to send a new ticket. */ return 2; err: EVP_CIPHER_CTX_free(ctx); HMAC_CTX_free(hctx); return ret; }
[ "CWE-20" ]
openssl
e97763c92c655dcf4af2860b3abd2bc4c8a267f9
221161159369771407245687985156292409299
178,138
158,109
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
false
recv_and_process_client_pkt(void /*int fd*/) { ssize_t size; len_and_sockaddr *to; struct sockaddr *from; msg_t msg; uint8_t query_status; l_fixedpt_t query_xmttime; to = get_sock_lsa(G_listen_fd); from = xzalloc(to->len); size = recv_from_to(G_listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len); if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) { char *addr; if (size < 0) { if (errno == EAGAIN) goto bail; bb_perror_msg_and_die("recv"); } addr = xmalloc_sockaddr2dotted_noport(from); bb_error_msg("malformed packet received from %s: size %u", addr, (int)size); free(addr); goto bail; } query_status = msg.m_status; query_xmttime = msg.m_xmttime; msg.m_ppoll = G.poll_exp; msg.m_precision_exp = G_precision_exp; /* this time was obtained between poll() and recv() */ msg.m_rectime = d_to_lfp(G.cur_time); msg.m_xmttime = d_to_lfp(gettime1900d()); /* this instant */ if (G.peer_cnt == 0) { /* we have no peers: "stratum 1 server" mode. reftime = our own time */ G.reftime = G.cur_time; } msg.m_reftime = d_to_lfp(G.reftime); msg.m_orgtime = query_xmttime; msg.m_rootdelay = d_to_sfp(G.rootdelay); msg.m_rootdisp = d_to_sfp(G.rootdisp); msg.m_refid = G.refid; // (version > (3 << VERSION_SHIFT)) ? G.refid : G.refid3; /* We reply from the local address packet was sent to, * this makes to/from look swapped here: */ do_sendto(G_listen_fd, /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len, &msg, size); bail: free(to); free(from); }
[ "CWE-399" ]
busybox
150dc7a2b483b8338a3e185c478b4b23ee884e71
156100728183473686227543895216612348906
178,139
251
This vulnerability category highlights issues in resource management where failures to properly release memory, file handles, or other resources can degrade system performance or enable denial-of-service conditions.
true
recv_and_process_client_pkt(void /*int fd*/) { ssize_t size; len_and_sockaddr *to; struct sockaddr *from; msg_t msg; uint8_t query_status; l_fixedpt_t query_xmttime; to = get_sock_lsa(G_listen_fd); from = xzalloc(to->len); size = recv_from_to(G_listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len); if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) { char *addr; if (size < 0) { if (errno == EAGAIN) goto bail; bb_perror_msg_and_die("recv"); } addr = xmalloc_sockaddr2dotted_noport(from); bb_error_msg("malformed packet received from %s: size %u", addr, (int)size); free(addr); goto bail; } /* Respond only to client and symmetric active packets */ if ((msg.m_status & MODE_MASK) != MODE_CLIENT && (msg.m_status & MODE_MASK) != MODE_SYM_ACT ) { goto bail; } query_status = msg.m_status; query_xmttime = msg.m_xmttime; msg.m_ppoll = G.poll_exp; msg.m_precision_exp = G_precision_exp; /* this time was obtained between poll() and recv() */ msg.m_rectime = d_to_lfp(G.cur_time); msg.m_xmttime = d_to_lfp(gettime1900d()); /* this instant */ if (G.peer_cnt == 0) { /* we have no peers: "stratum 1 server" mode. reftime = our own time */ G.reftime = G.cur_time; } msg.m_reftime = d_to_lfp(G.reftime); msg.m_orgtime = query_xmttime; msg.m_rootdelay = d_to_sfp(G.rootdelay); msg.m_rootdisp = d_to_sfp(G.rootdisp); msg.m_refid = G.refid; // (version > (3 << VERSION_SHIFT)) ? G.refid : G.refid3; /* We reply from the local address packet was sent to, * this makes to/from look swapped here: */ do_sendto(G_listen_fd, /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len, &msg, size); bail: free(to); free(from); }
[ "CWE-399" ]
busybox
150dc7a2b483b8338a3e185c478b4b23ee884e71
21371049218394401264776342910550411194
178,139
158,110
This vulnerability category highlights issues in resource management where failures to properly release memory, file handles, or other resources can degrade system performance or enable denial-of-service conditions.
false
main (int argc, char *argv[]) { struct gengetopt_args_info args_info; char *line = NULL; size_t linelen = 0; char *p, *r; uint32_t *q; unsigned cmdn = 0; int rc; setlocale (LC_ALL, ""); set_program_name (argv[0]); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); if (cmdline_parser (argc, argv, &args_info) != 0) return EXIT_FAILURE; if (args_info.version_given) { version_etc (stdout, "idn", PACKAGE_NAME, VERSION, "Simon Josefsson", (char *) NULL); return EXIT_SUCCESS; } if (args_info.help_given) usage (EXIT_SUCCESS); /* Backwards compatibility: -n has always been the documented short form for --nfkc but, before v1.10, -k was the implemented short form. We now accept both to avoid documentation changes. */ if (args_info.hidden_nfkc_given) args_info.nfkc_given = 1; if (!args_info.stringprep_given && !args_info.punycode_encode_given && !args_info.punycode_decode_given && !args_info.idna_to_ascii_given && !args_info.idna_to_unicode_given && !args_info.nfkc_given) args_info.idna_to_ascii_given = 1; if ((args_info.stringprep_given ? 1 : 0) + (args_info.punycode_encode_given ? 1 : 0) + (args_info.punycode_decode_given ? 1 : 0) + (args_info.idna_to_ascii_given ? 1 : 0) + (args_info.idna_to_unicode_given ? 1 : 0) + (args_info.nfkc_given ? 1 : 0) != 1) { error (0, 0, _("only one of -s, -e, -d, -a, -u or -n can be specified")); usage (EXIT_FAILURE); } if (!args_info.quiet_given && args_info.inputs_num == 0 && isatty (fileno (stdin))) fprintf (stderr, "%s %s\n" GREETING, PACKAGE, VERSION); if (args_info.debug_given) fprintf (stderr, _("Charset `%s'.\n"), stringprep_locale_charset ()); if (!args_info.quiet_given && args_info.inputs_num == 0 && isatty (fileno (stdin))) fprintf (stderr, _("Type each input string on a line by itself, " "terminated by a newline character.\n")); do { if (cmdn < args_info.inputs_num) line = strdup (args_info.inputs[cmdn++]); else if (getline (&line, &linelen, stdin) == -1) { if (feof (stdin)) break; error (EXIT_FAILURE, errno, _("input error")); } if (line[strlen (line) - 1] == '\n') line[strlen (line) - 1] = '\0'; if (args_info.stringprep_given) { if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); q = stringprep_utf8_to_ucs4 (p, -1, NULL); if (!q) { free (p); error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); } if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); } free (q); rc = stringprep_profile (p, &r, args_info.profile_given ? args_info.profile_arg : "Nameprep", 0); free (p); if (rc != STRINGPREP_OK) error (EXIT_FAILURE, 0, _("stringprep_profile: %s"), stringprep_strerror (rc)); q = stringprep_utf8_to_ucs4 (r, -1, NULL); if (!q) { free (r); error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); } if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, q[i]); } free (q); p = stringprep_utf8_to_locale (r); free (r); if (!p) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } if (args_info.punycode_encode_given) { char encbuf[BUFSIZ]; size_t len, len2; p = stringprep_locale_to_utf8 (line); if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); q = stringprep_utf8_to_ucs4 (p, -1, &len); free (p); if (!q) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); if (args_info.debug_given) { size_t i; for (i = 0; i < len; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); } len2 = BUFSIZ - 1; rc = punycode_encode (len, q, NULL, &len2, encbuf); free (q); if (rc != PUNYCODE_SUCCESS) error (EXIT_FAILURE, 0, _("punycode_encode: %s"), punycode_strerror (rc)); encbuf[len2] = '\0'; p = stringprep_utf8_to_locale (encbuf); if (!p) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } if (args_info.punycode_decode_given) { size_t len; len = BUFSIZ; q = (uint32_t *) malloc (len * sizeof (q[0])); if (!q) error (EXIT_FAILURE, ENOMEM, N_("malloc")); rc = punycode_decode (strlen (line), line, &len, q, NULL); if (rc != PUNYCODE_SUCCESS) { free (q); error (EXIT_FAILURE, 0, _("punycode_decode: %s"), punycode_strerror (rc)); } if (args_info.debug_given) { size_t i; for (i = 0; i < len; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, q[i]); } q[len] = 0; r = stringprep_ucs4_to_utf8 (q, -1, NULL, NULL); free (q); if (!r) error (EXIT_FAILURE, 0, _("could not convert from UCS-4 to UTF-8")); p = stringprep_utf8_to_locale (r); free (r); if (!r) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } if (args_info.idna_to_ascii_given) { p = stringprep_locale_to_utf8 (line); if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); q = stringprep_utf8_to_ucs4 (p, -1, NULL); free (p); if (!q) error (EXIT_FAILURE, 0, _("could not convert from UCS-4 to UTF-8")); if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); } rc = idna_to_ascii_4z (q, &p, (args_info.allow_unassigned_given ? IDNA_ALLOW_UNASSIGNED : 0) | (args_info.usestd3asciirules_given ? IDNA_USE_STD3_ASCII_RULES : 0)); free (q); if (rc != IDNA_SUCCESS) error (EXIT_FAILURE, 0, _("idna_to_ascii_4z: %s"), idna_strerror (rc)); #ifdef WITH_TLD if (args_info.tld_flag && !args_info.no_tld_flag) { size_t errpos; rc = idna_to_unicode_8z4z (p, &q, (args_info.allow_unassigned_given ? IDNA_ALLOW_UNASSIGNED : 0) | (args_info.usestd3asciirules_given ? IDNA_USE_STD3_ASCII_RULES : 0)); if (rc != IDNA_SUCCESS) error (EXIT_FAILURE, 0, _("idna_to_unicode_8z4z (TLD): %s"), idna_strerror (rc)); if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "tld[%lu] = U+%04x\n", (unsigned long) i, q[i]); } rc = tld_check_4z (q, &errpos, NULL); free (q); if (rc == TLD_INVALID) error (EXIT_FAILURE, 0, _("tld_check_4z (position %lu): %s"), (unsigned long) errpos, tld_strerror (rc)); if (rc != TLD_SUCCESS) error (EXIT_FAILURE, 0, _("tld_check_4z: %s"), tld_strerror (rc)); } #endif if (args_info.debug_given) { size_t i; for (i = 0; p[i]; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, p[i]); } fprintf (stdout, "%s\n", p); free (p); } if (args_info.idna_to_unicode_given) { p = stringprep_locale_to_utf8 (line); if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); q = stringprep_utf8_to_ucs4 (p, -1, NULL); if (!q) { free (p); error (EXIT_FAILURE, 0, _("could not convert from UCS-4 to UTF-8")); } if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); } free (q); rc = idna_to_unicode_8z4z (p, &q, (args_info.allow_unassigned_given ? IDNA_ALLOW_UNASSIGNED : 0) | (args_info.usestd3asciirules_given ? IDNA_USE_STD3_ASCII_RULES : 0)); free (p); if (rc != IDNA_SUCCESS) error (EXIT_FAILURE, 0, _("idna_to_unicode_8z4z: %s"), idna_strerror (rc)); if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, q[i]); } #ifdef WITH_TLD if (args_info.tld_flag) { size_t errpos; rc = tld_check_4z (q, &errpos, NULL); if (rc == TLD_INVALID) { free (q); error (EXIT_FAILURE, 0, _("tld_check_4z (position %lu): %s"), (unsigned long) errpos, tld_strerror (rc)); } if (rc != TLD_SUCCESS) { free (q); error (EXIT_FAILURE, 0, _("tld_check_4z: %s"), tld_strerror (rc)); } } #endif r = stringprep_ucs4_to_utf8 (q, -1, NULL, NULL); free (q); if (!r) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); p = stringprep_utf8_to_locale (r); free (r); if (!p) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } if (args_info.nfkc_given) { p = stringprep_locale_to_utf8 (line); if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); if (args_info.debug_given) { size_t i; q = stringprep_utf8_to_ucs4 (p, -1, NULL); if (!q) { free (p); error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); } for (i = 0; q[i]; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); free (q); } r = stringprep_utf8_nfkc_normalize (p, -1); free (p); if (!r) error (EXIT_FAILURE, 0, _("could not do NFKC normalization")); if (args_info.debug_given) { size_t i; q = stringprep_utf8_to_ucs4 (r, -1, NULL); if (!q) { free (r); error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); } for (i = 0; q[i]; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, q[i]); free (q); } p = stringprep_utf8_to_locale (r); free (r); if (!p) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } fflush (stdout); } while (!feof (stdin) && !ferror (stdin) && (args_info.inputs_num == 0 || cmdn < args_info.inputs_num)); free (line); return EXIT_SUCCESS; }
[ "CWE-125" ]
savannah
5e3cb9c7b5bf0ce665b9d68f5ddf095af5c9ba60
336554870084234386632359019600938342414
178,157
252
The product reads data past the end, or before the beginning, of the intended buffer.
true
main (int argc, char *argv[]) { struct gengetopt_args_info args_info; char *line = NULL; size_t linelen = 0; char *p, *r; uint32_t *q; unsigned cmdn = 0; int rc; setlocale (LC_ALL, ""); set_program_name (argv[0]); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); if (cmdline_parser (argc, argv, &args_info) != 0) return EXIT_FAILURE; if (args_info.version_given) { version_etc (stdout, "idn", PACKAGE_NAME, VERSION, "Simon Josefsson", (char *) NULL); return EXIT_SUCCESS; } if (args_info.help_given) usage (EXIT_SUCCESS); /* Backwards compatibility: -n has always been the documented short form for --nfkc but, before v1.10, -k was the implemented short form. We now accept both to avoid documentation changes. */ if (args_info.hidden_nfkc_given) args_info.nfkc_given = 1; if (!args_info.stringprep_given && !args_info.punycode_encode_given && !args_info.punycode_decode_given && !args_info.idna_to_ascii_given && !args_info.idna_to_unicode_given && !args_info.nfkc_given) args_info.idna_to_ascii_given = 1; if ((args_info.stringprep_given ? 1 : 0) + (args_info.punycode_encode_given ? 1 : 0) + (args_info.punycode_decode_given ? 1 : 0) + (args_info.idna_to_ascii_given ? 1 : 0) + (args_info.idna_to_unicode_given ? 1 : 0) + (args_info.nfkc_given ? 1 : 0) != 1) { error (0, 0, _("only one of -s, -e, -d, -a, -u or -n can be specified")); usage (EXIT_FAILURE); } if (!args_info.quiet_given && args_info.inputs_num == 0 && isatty (fileno (stdin))) fprintf (stderr, "%s %s\n" GREETING, PACKAGE, VERSION); if (args_info.debug_given) fprintf (stderr, _("Charset `%s'.\n"), stringprep_locale_charset ()); if (!args_info.quiet_given && args_info.inputs_num == 0 && isatty (fileno (stdin))) fprintf (stderr, _("Type each input string on a line by itself, " "terminated by a newline character.\n")); do { if (cmdn < args_info.inputs_num) line = strdup (args_info.inputs[cmdn++]); else if (getline (&line, &linelen, stdin) == -1) { if (feof (stdin)) break; error (EXIT_FAILURE, errno, _("input error")); } if (strlen (line) > 0) if (line[strlen (line) - 1] == '\n') line[strlen (line) - 1] = '\0'; if (args_info.stringprep_given) { if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); q = stringprep_utf8_to_ucs4 (p, -1, NULL); if (!q) { free (p); error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); } if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); } free (q); rc = stringprep_profile (p, &r, args_info.profile_given ? args_info.profile_arg : "Nameprep", 0); free (p); if (rc != STRINGPREP_OK) error (EXIT_FAILURE, 0, _("stringprep_profile: %s"), stringprep_strerror (rc)); q = stringprep_utf8_to_ucs4 (r, -1, NULL); if (!q) { free (r); error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); } if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, q[i]); } free (q); p = stringprep_utf8_to_locale (r); free (r); if (!p) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } if (args_info.punycode_encode_given) { char encbuf[BUFSIZ]; size_t len, len2; p = stringprep_locale_to_utf8 (line); if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); q = stringprep_utf8_to_ucs4 (p, -1, &len); free (p); if (!q) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); if (args_info.debug_given) { size_t i; for (i = 0; i < len; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); } len2 = BUFSIZ - 1; rc = punycode_encode (len, q, NULL, &len2, encbuf); free (q); if (rc != PUNYCODE_SUCCESS) error (EXIT_FAILURE, 0, _("punycode_encode: %s"), punycode_strerror (rc)); encbuf[len2] = '\0'; p = stringprep_utf8_to_locale (encbuf); if (!p) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } if (args_info.punycode_decode_given) { size_t len; len = BUFSIZ; q = (uint32_t *) malloc (len * sizeof (q[0])); if (!q) error (EXIT_FAILURE, ENOMEM, N_("malloc")); rc = punycode_decode (strlen (line), line, &len, q, NULL); if (rc != PUNYCODE_SUCCESS) { free (q); error (EXIT_FAILURE, 0, _("punycode_decode: %s"), punycode_strerror (rc)); } if (args_info.debug_given) { size_t i; for (i = 0; i < len; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, q[i]); } q[len] = 0; r = stringprep_ucs4_to_utf8 (q, -1, NULL, NULL); free (q); if (!r) error (EXIT_FAILURE, 0, _("could not convert from UCS-4 to UTF-8")); p = stringprep_utf8_to_locale (r); free (r); if (!r) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } if (args_info.idna_to_ascii_given) { p = stringprep_locale_to_utf8 (line); if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); q = stringprep_utf8_to_ucs4 (p, -1, NULL); free (p); if (!q) error (EXIT_FAILURE, 0, _("could not convert from UCS-4 to UTF-8")); if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); } rc = idna_to_ascii_4z (q, &p, (args_info.allow_unassigned_given ? IDNA_ALLOW_UNASSIGNED : 0) | (args_info.usestd3asciirules_given ? IDNA_USE_STD3_ASCII_RULES : 0)); free (q); if (rc != IDNA_SUCCESS) error (EXIT_FAILURE, 0, _("idna_to_ascii_4z: %s"), idna_strerror (rc)); #ifdef WITH_TLD if (args_info.tld_flag && !args_info.no_tld_flag) { size_t errpos; rc = idna_to_unicode_8z4z (p, &q, (args_info.allow_unassigned_given ? IDNA_ALLOW_UNASSIGNED : 0) | (args_info.usestd3asciirules_given ? IDNA_USE_STD3_ASCII_RULES : 0)); if (rc != IDNA_SUCCESS) error (EXIT_FAILURE, 0, _("idna_to_unicode_8z4z (TLD): %s"), idna_strerror (rc)); if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "tld[%lu] = U+%04x\n", (unsigned long) i, q[i]); } rc = tld_check_4z (q, &errpos, NULL); free (q); if (rc == TLD_INVALID) error (EXIT_FAILURE, 0, _("tld_check_4z (position %lu): %s"), (unsigned long) errpos, tld_strerror (rc)); if (rc != TLD_SUCCESS) error (EXIT_FAILURE, 0, _("tld_check_4z: %s"), tld_strerror (rc)); } #endif if (args_info.debug_given) { size_t i; for (i = 0; p[i]; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, p[i]); } fprintf (stdout, "%s\n", p); free (p); } if (args_info.idna_to_unicode_given) { p = stringprep_locale_to_utf8 (line); if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); q = stringprep_utf8_to_ucs4 (p, -1, NULL); if (!q) { free (p); error (EXIT_FAILURE, 0, _("could not convert from UCS-4 to UTF-8")); } if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); } free (q); rc = idna_to_unicode_8z4z (p, &q, (args_info.allow_unassigned_given ? IDNA_ALLOW_UNASSIGNED : 0) | (args_info.usestd3asciirules_given ? IDNA_USE_STD3_ASCII_RULES : 0)); free (p); if (rc != IDNA_SUCCESS) error (EXIT_FAILURE, 0, _("idna_to_unicode_8z4z: %s"), idna_strerror (rc)); if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, q[i]); } #ifdef WITH_TLD if (args_info.tld_flag) { size_t errpos; rc = tld_check_4z (q, &errpos, NULL); if (rc == TLD_INVALID) { free (q); error (EXIT_FAILURE, 0, _("tld_check_4z (position %lu): %s"), (unsigned long) errpos, tld_strerror (rc)); } if (rc != TLD_SUCCESS) { free (q); error (EXIT_FAILURE, 0, _("tld_check_4z: %s"), tld_strerror (rc)); } } #endif r = stringprep_ucs4_to_utf8 (q, -1, NULL, NULL); free (q); if (!r) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); p = stringprep_utf8_to_locale (r); free (r); if (!p) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } if (args_info.nfkc_given) { p = stringprep_locale_to_utf8 (line); if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); if (args_info.debug_given) { size_t i; q = stringprep_utf8_to_ucs4 (p, -1, NULL); if (!q) { free (p); error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); } for (i = 0; q[i]; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); free (q); } r = stringprep_utf8_nfkc_normalize (p, -1); free (p); if (!r) error (EXIT_FAILURE, 0, _("could not do NFKC normalization")); if (args_info.debug_given) { size_t i; q = stringprep_utf8_to_ucs4 (r, -1, NULL); if (!q) { free (r); error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); } for (i = 0; q[i]; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, q[i]); free (q); } p = stringprep_utf8_to_locale (r); free (r); if (!p) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } fflush (stdout); } while (!feof (stdin) && !ferror (stdin) && (args_info.inputs_num == 0 || cmdn < args_info.inputs_num)); free (line); return EXIT_SUCCESS; }
[ "CWE-125" ]
savannah
5e3cb9c7b5bf0ce665b9d68f5ddf095af5c9ba60
47000565902019325067062732144193781212
178,157
158,111
The product reads data past the end, or before the beginning, of the intended buffer.
false
FT_Stream_EnterFrame( FT_Stream stream, FT_ULong count ) { FT_Error error = FT_Err_Ok; FT_ULong read_bytes; /* check for nested frame access */ FT_ASSERT( stream && stream->cursor == 0 ); if ( stream->read ) { /* allocate the frame in memory */ FT_Memory memory = stream->memory; /* simple sanity check */ if ( count > stream->size ) { FT_ERROR(( "FT_Stream_EnterFrame:" " frame size (%lu) larger than stream size (%lu)\n", count, stream->size )); error = FT_Err_Invalid_Stream_Operation; goto Exit; } #ifdef FT_DEBUG_MEMORY /* assume _ft_debug_file and _ft_debug_lineno are already set */ stream->base = (unsigned char*)ft_mem_qalloc( memory, count, &error ); if ( error ) goto Exit; #else if ( FT_QALLOC( stream->base, count ) ) goto Exit; #endif /* read it */ read_bytes = stream->read( stream, stream->pos, stream->base, count ); if ( read_bytes < count ) { FT_ERROR(( "FT_Stream_EnterFrame:" " invalid read; expected %lu bytes, got %lu\n", count, read_bytes )); FT_FREE( stream->base ); error = FT_Err_Invalid_Stream_Operation; } stream->cursor = stream->base; stream->limit = stream->cursor + count; stream->pos += read_bytes; } else { /* check current and new position */ if ( stream->pos >= stream->size || stream->pos + count > stream->size ) { FT_ERROR(( "FT_Stream_EnterFrame:" " invalid i/o; pos = 0x%lx, count = %lu, size = 0x%lx\n", stream->pos, count, stream->size )); error = FT_Err_Invalid_Stream_Operation; goto Exit; } /* set cursor */ stream->cursor = stream->base + stream->pos; stream->limit = stream->cursor + count; stream->pos += count; } Exit: return error; }
[ "CWE-20" ]
savannah
45a3c76b547511fa9d97aca34b150a0663257375
171308526437072917405338067244329397761
178,158
253
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
true
FT_Stream_EnterFrame( FT_Stream stream, FT_ULong count ) { FT_Error error = FT_Err_Ok; FT_ULong read_bytes; /* check for nested frame access */ FT_ASSERT( stream && stream->cursor == 0 ); if ( stream->read ) { /* allocate the frame in memory */ FT_Memory memory = stream->memory; /* simple sanity check */ if ( count > stream->size ) { FT_ERROR(( "FT_Stream_EnterFrame:" " frame size (%lu) larger than stream size (%lu)\n", count, stream->size )); error = FT_Err_Invalid_Stream_Operation; goto Exit; } #ifdef FT_DEBUG_MEMORY /* assume _ft_debug_file and _ft_debug_lineno are already set */ stream->base = (unsigned char*)ft_mem_qalloc( memory, count, &error ); if ( error ) goto Exit; #else if ( FT_QALLOC( stream->base, count ) ) goto Exit; #endif /* read it */ read_bytes = stream->read( stream, stream->pos, stream->base, count ); if ( read_bytes < count ) { FT_ERROR(( "FT_Stream_EnterFrame:" " invalid read; expected %lu bytes, got %lu\n", count, read_bytes )); FT_FREE( stream->base ); error = FT_Err_Invalid_Stream_Operation; } stream->cursor = stream->base; stream->limit = stream->cursor + count; stream->pos += read_bytes; } else { /* check current and new position */ if ( stream->pos >= stream->size || stream->size - stream->pos < count ) { FT_ERROR(( "FT_Stream_EnterFrame:" " invalid i/o; pos = 0x%lx, count = %lu, size = 0x%lx\n", stream->pos, count, stream->size )); error = FT_Err_Invalid_Stream_Operation; goto Exit; } /* set cursor */ stream->cursor = stream->base + stream->pos; stream->limit = stream->cursor + count; stream->pos += count; } Exit: return error; }
[ "CWE-20" ]
savannah
45a3c76b547511fa9d97aca34b150a0663257375
15593559594427562342568939375098455612
178,158
158,112
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
false
parse_instruction( struct translate_ctx *ctx, boolean has_label ) { uint i; uint saturate = 0; const struct tgsi_opcode_info *info; struct tgsi_full_instruction inst; const char *cur; uint advance; inst = tgsi_default_full_instruction(); /* Parse predicate. */ eat_opt_white( &ctx->cur ); if (*ctx->cur == '(') { uint file; int index; uint swizzle[4]; boolean parsed_swizzle; inst.Instruction.Predicate = 1; ctx->cur++; if (*ctx->cur == '!') { ctx->cur++; inst.Predicate.Negate = 1; } if (!parse_register_1d( ctx, &file, &index )) return FALSE; if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) { if (parsed_swizzle) { inst.Predicate.SwizzleX = swizzle[0]; inst.Predicate.SwizzleY = swizzle[1]; inst.Predicate.SwizzleZ = swizzle[2]; inst.Predicate.SwizzleW = swizzle[3]; } } if (*ctx->cur != ')') { report_error( ctx, "Expected `)'" ); return FALSE; } ctx->cur++; } /* Parse instruction name. */ eat_opt_white( &ctx->cur ); for (i = 0; i < TGSI_OPCODE_LAST; i++) { cur = ctx->cur; info = tgsi_get_opcode_info( i ); if (match_inst(&cur, &saturate, info)) { if (info->num_dst + info->num_src + info->is_tex == 0) { ctx->cur = cur; break; } else if (*cur == '\0' || eat_white( &cur )) { ctx->cur = cur; break; } } } if (i == TGSI_OPCODE_LAST) { if (has_label) report_error( ctx, "Unknown opcode" ); else report_error( ctx, "Expected `DCL', `IMM' or a label" ); return FALSE; } inst.Instruction.Opcode = i; inst.Instruction.Saturate = saturate; inst.Instruction.NumDstRegs = info->num_dst; inst.Instruction.NumSrcRegs = info->num_src; if (i >= TGSI_OPCODE_SAMPLE && i <= TGSI_OPCODE_GATHER4) { /* * These are not considered tex opcodes here (no additional * target argument) however we're required to set the Texture * bit so we can set the number of tex offsets. */ inst.Instruction.Texture = 1; inst.Texture.Texture = TGSI_TEXTURE_UNKNOWN; } /* Parse instruction operands. */ for (i = 0; i < info->num_dst + info->num_src + info->is_tex; i++) { if (i > 0) { eat_opt_white( &ctx->cur ); if (*ctx->cur != ',') { report_error( ctx, "Expected `,'" ); return FALSE; } ctx->cur++; eat_opt_white( &ctx->cur ); } if (i < info->num_dst) { if (!parse_dst_operand( ctx, &inst.Dst[i] )) return FALSE; } else if (i < info->num_dst + info->num_src) { if (!parse_src_operand( ctx, &inst.Src[i - info->num_dst] )) return FALSE; } else { uint j; for (j = 0; j < TGSI_TEXTURE_COUNT; j++) { if (str_match_nocase_whole( &ctx->cur, tgsi_texture_names[j] )) { inst.Instruction.Texture = 1; inst.Texture.Texture = j; break; } } if (j == TGSI_TEXTURE_COUNT) { report_error( ctx, "Expected texture target" ); return FALSE; } } } cur = ctx->cur; eat_opt_white( &cur ); for (i = 0; inst.Instruction.Texture && *cur == ','; i++) { cur++; eat_opt_white( &cur ); ctx->cur = cur; if (!parse_texoffset_operand( ctx, &inst.TexOffsets[i] )) return FALSE; cur = ctx->cur; eat_opt_white( &cur ); } inst.Texture.NumOffsets = i; cur = ctx->cur; eat_opt_white( &cur ); if (info->is_branch && *cur == ':') { uint target; cur++; eat_opt_white( &cur ); if (!parse_uint( &cur, &target )) { report_error( ctx, "Expected a label" ); return FALSE; } inst.Instruction.Label = 1; inst.Label.Label = target; ctx->cur = cur; } advance = tgsi_build_full_instruction( &inst, ctx->tokens_cur, ctx->header, (uint) (ctx->tokens_end - ctx->tokens_cur) ); if (advance == 0) return FALSE; ctx->tokens_cur += advance; return TRUE; }
[ "CWE-119" ]
virglrenderer
28894a30a17a84529be102b21118e55d6c9f23fa
207706300612945852467345419819110560855
178,159
254
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
parse_instruction( struct translate_ctx *ctx, boolean has_label ) { uint i; uint saturate = 0; const struct tgsi_opcode_info *info; struct tgsi_full_instruction inst; const char *cur; uint advance; inst = tgsi_default_full_instruction(); /* Parse predicate. */ eat_opt_white( &ctx->cur ); if (*ctx->cur == '(') { uint file; int index; uint swizzle[4]; boolean parsed_swizzle; inst.Instruction.Predicate = 1; ctx->cur++; if (*ctx->cur == '!') { ctx->cur++; inst.Predicate.Negate = 1; } if (!parse_register_1d( ctx, &file, &index )) return FALSE; if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) { if (parsed_swizzle) { inst.Predicate.SwizzleX = swizzle[0]; inst.Predicate.SwizzleY = swizzle[1]; inst.Predicate.SwizzleZ = swizzle[2]; inst.Predicate.SwizzleW = swizzle[3]; } } if (*ctx->cur != ')') { report_error( ctx, "Expected `)'" ); return FALSE; } ctx->cur++; } /* Parse instruction name. */ eat_opt_white( &ctx->cur ); for (i = 0; i < TGSI_OPCODE_LAST; i++) { cur = ctx->cur; info = tgsi_get_opcode_info( i ); if (match_inst(&cur, &saturate, info)) { if (info->num_dst + info->num_src + info->is_tex == 0) { ctx->cur = cur; break; } else if (*cur == '\0' || eat_white( &cur )) { ctx->cur = cur; break; } } } if (i == TGSI_OPCODE_LAST) { if (has_label) report_error( ctx, "Unknown opcode" ); else report_error( ctx, "Expected `DCL', `IMM' or a label" ); return FALSE; } inst.Instruction.Opcode = i; inst.Instruction.Saturate = saturate; inst.Instruction.NumDstRegs = info->num_dst; inst.Instruction.NumSrcRegs = info->num_src; if (i >= TGSI_OPCODE_SAMPLE && i <= TGSI_OPCODE_GATHER4) { /* * These are not considered tex opcodes here (no additional * target argument) however we're required to set the Texture * bit so we can set the number of tex offsets. */ inst.Instruction.Texture = 1; inst.Texture.Texture = TGSI_TEXTURE_UNKNOWN; } /* Parse instruction operands. */ for (i = 0; i < info->num_dst + info->num_src + info->is_tex; i++) { if (i > 0) { eat_opt_white( &ctx->cur ); if (*ctx->cur != ',') { report_error( ctx, "Expected `,'" ); return FALSE; } ctx->cur++; eat_opt_white( &ctx->cur ); } if (i < info->num_dst) { if (!parse_dst_operand( ctx, &inst.Dst[i] )) return FALSE; } else if (i < info->num_dst + info->num_src) { if (!parse_src_operand( ctx, &inst.Src[i - info->num_dst] )) return FALSE; } else { uint j; for (j = 0; j < TGSI_TEXTURE_COUNT; j++) { if (str_match_nocase_whole( &ctx->cur, tgsi_texture_names[j] )) { inst.Instruction.Texture = 1; inst.Texture.Texture = j; break; } } if (j == TGSI_TEXTURE_COUNT) { report_error( ctx, "Expected texture target" ); return FALSE; } } } cur = ctx->cur; eat_opt_white( &cur ); for (i = 0; inst.Instruction.Texture && *cur == ',' && i < TGSI_FULL_MAX_TEX_OFFSETS; i++) { cur++; eat_opt_white( &cur ); ctx->cur = cur; if (!parse_texoffset_operand( ctx, &inst.TexOffsets[i] )) return FALSE; cur = ctx->cur; eat_opt_white( &cur ); } inst.Texture.NumOffsets = i; cur = ctx->cur; eat_opt_white( &cur ); if (info->is_branch && *cur == ':') { uint target; cur++; eat_opt_white( &cur ); if (!parse_uint( &cur, &target )) { report_error( ctx, "Expected a label" ); return FALSE; } inst.Instruction.Label = 1; inst.Label.Label = target; ctx->cur = cur; } advance = tgsi_build_full_instruction( &inst, ctx->tokens_cur, ctx->header, (uint) (ctx->tokens_end - ctx->tokens_cur) ); if (advance == 0) return FALSE; ctx->tokens_cur += advance; return TRUE; }
[ "CWE-119" ]
virglrenderer
28894a30a17a84529be102b21118e55d6c9f23fa
321254582650752893308442793791247099756
178,159
158,113
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
int http_request_forward_body(struct session *s, struct channel *req, int an_bit) { struct http_txn *txn = &s->txn; struct http_msg *msg = &s->txn.req; if (unlikely(msg->msg_state < HTTP_MSG_BODY)) return 0; if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) || ((req->flags & CF_SHUTW) && (req->to_forward || req->buf->o))) { /* Output closed while we were sending data. We must abort and * wake the other side up. */ msg->msg_state = HTTP_MSG_ERROR; http_resync_states(s); return 1; } /* Note that we don't have to send 100-continue back because we don't * need the data to complete our job, and it's up to the server to * decide whether to return 100, 417 or anything else in return of * an "Expect: 100-continue" header. */ if (msg->sov > 0) { /* we have msg->sov which points to the first byte of message * body, and req->buf.p still points to the beginning of the * message. We forward the headers now, as we don't need them * anymore, and we want to flush them. */ b_adv(req->buf, msg->sov); msg->next -= msg->sov; msg->sov = 0; /* The previous analysers guarantee that the state is somewhere * between MSG_BODY and the first MSG_DATA. So msg->sol and * msg->next are always correct. */ if (msg->msg_state < HTTP_MSG_CHUNK_SIZE) { if (msg->flags & HTTP_MSGF_TE_CHNK) msg->msg_state = HTTP_MSG_CHUNK_SIZE; else msg->msg_state = HTTP_MSG_DATA; } } /* Some post-connect processing might want us to refrain from starting to * forward data. Currently, the only reason for this is "balance url_param" * whichs need to parse/process the request after we've enabled forwarding. */ if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) { if (!(s->rep->flags & CF_READ_ATTACHED)) { channel_auto_connect(req); req->flags |= CF_WAKE_CONNECT; goto missing_data; } msg->flags &= ~HTTP_MSGF_WAIT_CONN; } /* in most states, we should abort in case of early close */ channel_auto_close(req); if (req->to_forward) { /* We can't process the buffer's contents yet */ req->flags |= CF_WAKE_WRITE; goto missing_data; } while (1) { if (msg->msg_state == HTTP_MSG_DATA) { /* must still forward */ /* we may have some pending data starting at req->buf->p */ if (msg->chunk_len > req->buf->i - msg->next) { req->flags |= CF_WAKE_WRITE; goto missing_data; } msg->next += msg->chunk_len; msg->chunk_len = 0; /* nothing left to forward */ if (msg->flags & HTTP_MSGF_TE_CHNK) msg->msg_state = HTTP_MSG_CHUNK_CRLF; else msg->msg_state = HTTP_MSG_DONE; } else if (msg->msg_state == HTTP_MSG_CHUNK_SIZE) { /* read the chunk size and assign it to ->chunk_len, then * set ->next to point to the body and switch to DATA or * TRAILERS state. */ int ret = http_parse_chunk_size(msg); if (ret == 0) goto missing_data; else if (ret < 0) { session_inc_http_err_ctr(s); if (msg->err_pos >= 0) http_capture_bad_message(&s->fe->invalid_req, s, msg, HTTP_MSG_CHUNK_SIZE, s->be); goto return_bad_req; } /* otherwise we're in HTTP_MSG_DATA or HTTP_MSG_TRAILERS state */ } else if (msg->msg_state == HTTP_MSG_CHUNK_CRLF) { /* we want the CRLF after the data */ int ret = http_skip_chunk_crlf(msg); if (ret == 0) goto missing_data; else if (ret < 0) { session_inc_http_err_ctr(s); if (msg->err_pos >= 0) http_capture_bad_message(&s->fe->invalid_req, s, msg, HTTP_MSG_CHUNK_CRLF, s->be); goto return_bad_req; } /* we're in MSG_CHUNK_SIZE now */ } else if (msg->msg_state == HTTP_MSG_TRAILERS) { int ret = http_forward_trailers(msg); if (ret == 0) goto missing_data; else if (ret < 0) { session_inc_http_err_ctr(s); if (msg->err_pos >= 0) http_capture_bad_message(&s->fe->invalid_req, s, msg, HTTP_MSG_TRAILERS, s->be); goto return_bad_req; } /* we're in HTTP_MSG_DONE now */ } else { int old_state = msg->msg_state; /* other states, DONE...TUNNEL */ /* we may have some pending data starting at req->buf->p * such as last chunk of data or trailers. */ b_adv(req->buf, msg->next); if (unlikely(!(s->rep->flags & CF_READ_ATTACHED))) msg->sov -= msg->next; msg->next = 0; /* for keep-alive we don't want to forward closes on DONE */ if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL || (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL) channel_dont_close(req); if (http_resync_states(s)) { /* some state changes occurred, maybe the analyser * was disabled too. */ if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) { if (req->flags & CF_SHUTW) { /* request errors are most likely due to * the server aborting the transfer. */ goto aborted_xfer; } if (msg->err_pos >= 0) http_capture_bad_message(&s->fe->invalid_req, s, msg, old_state, s->be); goto return_bad_req; } return 1; } /* If "option abortonclose" is set on the backend, we * want to monitor the client's connection and forward * any shutdown notification to the server, which will * decide whether to close or to go on processing the * request. */ if (s->be->options & PR_O_ABRT_CLOSE) { channel_auto_read(req); channel_auto_close(req); } else if (s->txn.meth == HTTP_METH_POST) { /* POST requests may require to read extra CRLF * sent by broken browsers and which could cause * an RST to be sent upon close on some systems * (eg: Linux). */ channel_auto_read(req); } return 0; } } missing_data: /* we may have some pending data starting at req->buf->p */ b_adv(req->buf, msg->next); if (unlikely(!(s->rep->flags & CF_READ_ATTACHED))) msg->sov -= msg->next + MIN(msg->chunk_len, req->buf->i); msg->next = 0; msg->chunk_len -= channel_forward(req, msg->chunk_len); /* stop waiting for data if the input is closed before the end */ if (req->flags & CF_SHUTR) { if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_CLICL; if (!(s->flags & SN_FINST_MASK)) { if (txn->rsp.msg_state < HTTP_MSG_ERROR) s->flags |= SN_FINST_H; else s->flags |= SN_FINST_D; } s->fe->fe_counters.cli_aborts++; s->be->be_counters.cli_aborts++; if (objt_server(s->target)) objt_server(s->target)->counters.cli_aborts++; goto return_bad_req_stats_ok; } /* waiting for the last bits to leave the buffer */ if (req->flags & CF_SHUTW) goto aborted_xfer; /* When TE: chunked is used, we need to get there again to parse remaining * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE. */ if (msg->flags & HTTP_MSGF_TE_CHNK) channel_dont_close(req); /* We know that more data are expected, but we couldn't send more that * what we did. So we always set the CF_EXPECT_MORE flag so that the * system knows it must not set a PUSH on this first part. Interactive * modes are already handled by the stream sock layer. We must not do * this in content-length mode because it could present the MSG_MORE * flag with the last block of forwarded data, which would cause an * additional delay to be observed by the receiver. */ if (msg->flags & HTTP_MSGF_TE_CHNK) req->flags |= CF_EXPECT_MORE; return 0; return_bad_req: /* let's centralize all bad requests */ s->fe->fe_counters.failed_req++; if (s->listener->counters) s->listener->counters->failed_req++; return_bad_req_stats_ok: /* we may have some pending data starting at req->buf->p */ b_adv(req->buf, msg->next); msg->next = 0; txn->req.msg_state = HTTP_MSG_ERROR; if (txn->status) { /* Note: we don't send any error if some data were already sent */ stream_int_retnclose(req->prod, NULL); } else { txn->status = 400; stream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_400)); } req->analysers = 0; s->rep->analysers = 0; /* we're in data phase, we want to abort both directions */ if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_PRXCOND; if (!(s->flags & SN_FINST_MASK)) { if (txn->rsp.msg_state < HTTP_MSG_ERROR) s->flags |= SN_FINST_H; else s->flags |= SN_FINST_D; } return 0; aborted_xfer: txn->req.msg_state = HTTP_MSG_ERROR; if (txn->status) { /* Note: we don't send any error if some data were already sent */ stream_int_retnclose(req->prod, NULL); } else { txn->status = 502; stream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_502)); } req->analysers = 0; s->rep->analysers = 0; /* we're in data phase, we want to abort both directions */ s->fe->fe_counters.srv_aborts++; s->be->be_counters.srv_aborts++; if (objt_server(s->target)) objt_server(s->target)->counters.srv_aborts++; if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_SRVCL; if (!(s->flags & SN_FINST_MASK)) { if (txn->rsp.msg_state < HTTP_MSG_ERROR) s->flags |= SN_FINST_H; else s->flags |= SN_FINST_D; } return 0; }
[ "CWE-189" ]
haproxy
b4d05093bc89f71377230228007e69a1434c1a0c
74231898713312769363715897872246138359
178,162
256
This weakness involves numeric computation errors, such as integer overflows, underflows, or precision losses, which can lead to miscalculations and exploitable behaviors in software.
true
int http_request_forward_body(struct session *s, struct channel *req, int an_bit) { struct http_txn *txn = &s->txn; struct http_msg *msg = &s->txn.req; if (unlikely(msg->msg_state < HTTP_MSG_BODY)) return 0; if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) || ((req->flags & CF_SHUTW) && (req->to_forward || req->buf->o))) { /* Output closed while we were sending data. We must abort and * wake the other side up. */ msg->msg_state = HTTP_MSG_ERROR; http_resync_states(s); return 1; } /* Note that we don't have to send 100-continue back because we don't * need the data to complete our job, and it's up to the server to * decide whether to return 100, 417 or anything else in return of * an "Expect: 100-continue" header. */ if (msg->sov > 0) { /* we have msg->sov which points to the first byte of message * body, and req->buf.p still points to the beginning of the * message. We forward the headers now, as we don't need them * anymore, and we want to flush them. */ b_adv(req->buf, msg->sov); msg->next -= msg->sov; msg->sov = 0; /* The previous analysers guarantee that the state is somewhere * between MSG_BODY and the first MSG_DATA. So msg->sol and * msg->next are always correct. */ if (msg->msg_state < HTTP_MSG_CHUNK_SIZE) { if (msg->flags & HTTP_MSGF_TE_CHNK) msg->msg_state = HTTP_MSG_CHUNK_SIZE; else msg->msg_state = HTTP_MSG_DATA; } } /* Some post-connect processing might want us to refrain from starting to * forward data. Currently, the only reason for this is "balance url_param" * whichs need to parse/process the request after we've enabled forwarding. */ if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) { if (!(s->rep->flags & CF_READ_ATTACHED)) { channel_auto_connect(req); req->flags |= CF_WAKE_CONNECT; goto missing_data; } msg->flags &= ~HTTP_MSGF_WAIT_CONN; } /* in most states, we should abort in case of early close */ channel_auto_close(req); if (req->to_forward) { /* We can't process the buffer's contents yet */ req->flags |= CF_WAKE_WRITE; goto missing_data; } while (1) { if (msg->msg_state == HTTP_MSG_DATA) { /* must still forward */ /* we may have some pending data starting at req->buf->p */ if (msg->chunk_len > req->buf->i - msg->next) { req->flags |= CF_WAKE_WRITE; goto missing_data; } msg->next += msg->chunk_len; msg->chunk_len = 0; /* nothing left to forward */ if (msg->flags & HTTP_MSGF_TE_CHNK) msg->msg_state = HTTP_MSG_CHUNK_CRLF; else msg->msg_state = HTTP_MSG_DONE; } else if (msg->msg_state == HTTP_MSG_CHUNK_SIZE) { /* read the chunk size and assign it to ->chunk_len, then * set ->next to point to the body and switch to DATA or * TRAILERS state. */ int ret = http_parse_chunk_size(msg); if (ret == 0) goto missing_data; else if (ret < 0) { session_inc_http_err_ctr(s); if (msg->err_pos >= 0) http_capture_bad_message(&s->fe->invalid_req, s, msg, HTTP_MSG_CHUNK_SIZE, s->be); goto return_bad_req; } /* otherwise we're in HTTP_MSG_DATA or HTTP_MSG_TRAILERS state */ } else if (msg->msg_state == HTTP_MSG_CHUNK_CRLF) { /* we want the CRLF after the data */ int ret = http_skip_chunk_crlf(msg); if (ret == 0) goto missing_data; else if (ret < 0) { session_inc_http_err_ctr(s); if (msg->err_pos >= 0) http_capture_bad_message(&s->fe->invalid_req, s, msg, HTTP_MSG_CHUNK_CRLF, s->be); goto return_bad_req; } /* we're in MSG_CHUNK_SIZE now */ } else if (msg->msg_state == HTTP_MSG_TRAILERS) { int ret = http_forward_trailers(msg); if (ret == 0) goto missing_data; else if (ret < 0) { session_inc_http_err_ctr(s); if (msg->err_pos >= 0) http_capture_bad_message(&s->fe->invalid_req, s, msg, HTTP_MSG_TRAILERS, s->be); goto return_bad_req; } /* we're in HTTP_MSG_DONE now */ } else { int old_state = msg->msg_state; /* other states, DONE...TUNNEL */ /* we may have some pending data starting at req->buf->p * such as last chunk of data or trailers. */ b_adv(req->buf, msg->next); if (unlikely(!(s->req->flags & CF_WROTE_DATA))) msg->sov -= msg->next; msg->next = 0; /* for keep-alive we don't want to forward closes on DONE */ if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL || (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL) channel_dont_close(req); if (http_resync_states(s)) { /* some state changes occurred, maybe the analyser * was disabled too. */ if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) { if (req->flags & CF_SHUTW) { /* request errors are most likely due to * the server aborting the transfer. */ goto aborted_xfer; } if (msg->err_pos >= 0) http_capture_bad_message(&s->fe->invalid_req, s, msg, old_state, s->be); goto return_bad_req; } return 1; } /* If "option abortonclose" is set on the backend, we * want to monitor the client's connection and forward * any shutdown notification to the server, which will * decide whether to close or to go on processing the * request. */ if (s->be->options & PR_O_ABRT_CLOSE) { channel_auto_read(req); channel_auto_close(req); } else if (s->txn.meth == HTTP_METH_POST) { /* POST requests may require to read extra CRLF * sent by broken browsers and which could cause * an RST to be sent upon close on some systems * (eg: Linux). */ channel_auto_read(req); } return 0; } } missing_data: /* we may have some pending data starting at req->buf->p */ b_adv(req->buf, msg->next); if (unlikely(!(s->req->flags & CF_WROTE_DATA))) msg->sov -= msg->next + MIN(msg->chunk_len, req->buf->i); msg->next = 0; msg->chunk_len -= channel_forward(req, msg->chunk_len); /* stop waiting for data if the input is closed before the end */ if (req->flags & CF_SHUTR) { if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_CLICL; if (!(s->flags & SN_FINST_MASK)) { if (txn->rsp.msg_state < HTTP_MSG_ERROR) s->flags |= SN_FINST_H; else s->flags |= SN_FINST_D; } s->fe->fe_counters.cli_aborts++; s->be->be_counters.cli_aborts++; if (objt_server(s->target)) objt_server(s->target)->counters.cli_aborts++; goto return_bad_req_stats_ok; } /* waiting for the last bits to leave the buffer */ if (req->flags & CF_SHUTW) goto aborted_xfer; /* When TE: chunked is used, we need to get there again to parse remaining * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE. */ if (msg->flags & HTTP_MSGF_TE_CHNK) channel_dont_close(req); /* We know that more data are expected, but we couldn't send more that * what we did. So we always set the CF_EXPECT_MORE flag so that the * system knows it must not set a PUSH on this first part. Interactive * modes are already handled by the stream sock layer. We must not do * this in content-length mode because it could present the MSG_MORE * flag with the last block of forwarded data, which would cause an * additional delay to be observed by the receiver. */ if (msg->flags & HTTP_MSGF_TE_CHNK) req->flags |= CF_EXPECT_MORE; return 0; return_bad_req: /* let's centralize all bad requests */ s->fe->fe_counters.failed_req++; if (s->listener->counters) s->listener->counters->failed_req++; return_bad_req_stats_ok: /* we may have some pending data starting at req->buf->p */ b_adv(req->buf, msg->next); msg->next = 0; txn->req.msg_state = HTTP_MSG_ERROR; if (txn->status) { /* Note: we don't send any error if some data were already sent */ stream_int_retnclose(req->prod, NULL); } else { txn->status = 400; stream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_400)); } req->analysers = 0; s->rep->analysers = 0; /* we're in data phase, we want to abort both directions */ if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_PRXCOND; if (!(s->flags & SN_FINST_MASK)) { if (txn->rsp.msg_state < HTTP_MSG_ERROR) s->flags |= SN_FINST_H; else s->flags |= SN_FINST_D; } return 0; aborted_xfer: txn->req.msg_state = HTTP_MSG_ERROR; if (txn->status) { /* Note: we don't send any error if some data were already sent */ stream_int_retnclose(req->prod, NULL); } else { txn->status = 502; stream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_502)); } req->analysers = 0; s->rep->analysers = 0; /* we're in data phase, we want to abort both directions */ s->fe->fe_counters.srv_aborts++; s->be->be_counters.srv_aborts++; if (objt_server(s->target)) objt_server(s->target)->counters.srv_aborts++; if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_SRVCL; if (!(s->flags & SN_FINST_MASK)) { if (txn->rsp.msg_state < HTTP_MSG_ERROR) s->flags |= SN_FINST_H; else s->flags |= SN_FINST_D; } return 0; }
[ "CWE-189" ]
haproxy
b4d05093bc89f71377230228007e69a1434c1a0c
232911459327632823261392605236293767883
178,162
158,115
This weakness involves numeric computation errors, such as integer overflows, underflows, or precision losses, which can lead to miscalculations and exploitable behaviors in software.
false
void Part::slotOpenExtractedEntry(KJob *job) { if (!job->error()) { OpenJob *openJob = qobject_cast<OpenJob*>(job); Q_ASSERT(openJob); m_tmpExtractDirList << openJob->tempDir(); const QString fullName = openJob->validatedFilePath(); bool isWritable = m_model->archive() && !m_model->archive()->isReadOnly(); if (!isWritable) { QFile::setPermissions(fullName, QFileDevice::ReadOwner | QFileDevice::ReadGroup | QFileDevice::ReadOther); } if (isWritable) { m_fileWatcher = new QFileSystemWatcher; connect(m_fileWatcher, &QFileSystemWatcher::fileChanged, this, &Part::slotWatchedFileModified); m_fileWatcher->addPath(fullName); } if (qobject_cast<OpenWithJob*>(job)) { const QList<QUrl> urls = {QUrl::fromUserInput(fullName, QString(), QUrl::AssumeLocalFile)}; KRun::displayOpenWithDialog(urls, widget()); } else { KRun::runUrl(QUrl::fromUserInput(fullName, QString(), QUrl::AssumeLocalFile), QMimeDatabase().mimeTypeForFile(fullName).name(), widget()); } } else if (job->error() != KJob::KilledJobError) { KMessageBox::error(widget(), job->errorString()); } setReadyGui(); }
[ "CWE-78" ]
kde
82fdfd24d46966a117fa625b68784735a40f9065
127189817454680839187942616776907215530
178,164
257
The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
true
void Part::slotOpenExtractedEntry(KJob *job) { if (!job->error()) { OpenJob *openJob = qobject_cast<OpenJob*>(job); Q_ASSERT(openJob); m_tmpExtractDirList << openJob->tempDir(); const QString fullName = openJob->validatedFilePath(); bool isWritable = m_model->archive() && !m_model->archive()->isReadOnly(); if (!isWritable) { QFile::setPermissions(fullName, QFileDevice::ReadOwner | QFileDevice::ReadGroup | QFileDevice::ReadOther); } if (isWritable) { m_fileWatcher = new QFileSystemWatcher; connect(m_fileWatcher, &QFileSystemWatcher::fileChanged, this, &Part::slotWatchedFileModified); m_fileWatcher->addPath(fullName); } if (qobject_cast<OpenWithJob*>(job)) { const QList<QUrl> urls = {QUrl::fromUserInput(fullName, QString(), QUrl::AssumeLocalFile)}; KRun::displayOpenWithDialog(urls, widget()); } else { KRun::runUrl(QUrl::fromUserInput(fullName, QString(), QUrl::AssumeLocalFile), QMimeDatabase().mimeTypeForFile(fullName).name(), widget(), false, false); } } else if (job->error() != KJob::KilledJobError) { KMessageBox::error(widget(), job->errorString()); } setReadyGui(); }
[ "CWE-78" ]
kde
82fdfd24d46966a117fa625b68784735a40f9065
254744186026668512929911458145895625788
178,164
158,116
The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
false
Ins_IUP( INS_ARG ) { IUP_WorkerRec V; FT_Byte mask; FT_UInt first_point; /* first point of contour */ FT_UInt end_point; /* end point (last+1) of contour */ FT_UInt first_touched; /* first touched point in contour */ FT_UInt cur_touched; /* current touched point in contour */ FT_UInt point; /* current point */ FT_Short contour; /* current contour */ FT_UNUSED_ARG; /* ignore empty outlines */ if ( CUR.pts.n_contours == 0 ) return; if ( CUR.opcode & 1 ) { mask = FT_CURVE_TAG_TOUCH_X; V.orgs = CUR.pts.org; V.curs = CUR.pts.cur; V.orus = CUR.pts.orus; } else { mask = FT_CURVE_TAG_TOUCH_Y; V.orgs = (FT_Vector*)( (FT_Pos*)CUR.pts.org + 1 ); V.curs = (FT_Vector*)( (FT_Pos*)CUR.pts.cur + 1 ); V.orus = (FT_Vector*)( (FT_Pos*)CUR.pts.orus + 1 ); } V.max_points = CUR.pts.n_points; contour = 0; point = 0; do { end_point = CUR.pts.contours[contour] - CUR.pts.first_point; first_point = point; if ( CUR.pts.n_points <= end_point ) end_point = CUR.pts.n_points; while ( point <= end_point && ( CUR.pts.tags[point] & mask ) == 0 ) point++; if ( point <= end_point ) { first_touched = point; cur_touched = point; point++; while ( point <= end_point ) { if ( ( CUR.pts.tags[point] & mask ) != 0 ) { if ( point > 0 ) _iup_worker_interpolate( &V, cur_touched + 1, point - 1, cur_touched, point ); cur_touched = point; } point++; } if ( cur_touched == first_touched ) _iup_worker_shift( &V, first_point, end_point, cur_touched ); else { _iup_worker_interpolate( &V, (FT_UShort)( cur_touched + 1 ), end_point, cur_touched, first_touched ); if ( first_touched > 0 ) _iup_worker_interpolate( &V, first_point, first_touched - 1, cur_touched, first_touched ); } } contour++; } while ( contour < CUR.pts.n_contours ); }
[ "CWE-119" ]
savannah
888cd1843e935fe675cf2ac303116d4ed5b9d54b
271982803099189327229111379866845675067
178,174
263
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
Ins_IUP( INS_ARG ) { IUP_WorkerRec V; FT_Byte mask; FT_UInt first_point; /* first point of contour */ FT_UInt end_point; /* end point (last+1) of contour */ FT_UInt first_touched; /* first touched point in contour */ FT_UInt cur_touched; /* current touched point in contour */ FT_UInt point; /* current point */ FT_Short contour; /* current contour */ FT_UNUSED_ARG; /* ignore empty outlines */ if ( CUR.pts.n_contours == 0 ) return; if ( CUR.opcode & 1 ) { mask = FT_CURVE_TAG_TOUCH_X; V.orgs = CUR.pts.org; V.curs = CUR.pts.cur; V.orus = CUR.pts.orus; } else { mask = FT_CURVE_TAG_TOUCH_Y; V.orgs = (FT_Vector*)( (FT_Pos*)CUR.pts.org + 1 ); V.curs = (FT_Vector*)( (FT_Pos*)CUR.pts.cur + 1 ); V.orus = (FT_Vector*)( (FT_Pos*)CUR.pts.orus + 1 ); } V.max_points = CUR.pts.n_points; contour = 0; point = 0; do { end_point = CUR.pts.contours[contour] - CUR.pts.first_point; first_point = point; if ( BOUNDS ( end_point, CUR.pts.n_points ) ) end_point = CUR.pts.n_points - 1; while ( point <= end_point && ( CUR.pts.tags[point] & mask ) == 0 ) point++; if ( point <= end_point ) { first_touched = point; cur_touched = point; point++; while ( point <= end_point ) { if ( ( CUR.pts.tags[point] & mask ) != 0 ) { if ( point > 0 ) _iup_worker_interpolate( &V, cur_touched + 1, point - 1, cur_touched, point ); cur_touched = point; } point++; } if ( cur_touched == first_touched ) _iup_worker_shift( &V, first_point, end_point, cur_touched ); else { _iup_worker_interpolate( &V, (FT_UShort)( cur_touched + 1 ), end_point, cur_touched, first_touched ); if ( first_touched > 0 ) _iup_worker_interpolate( &V, first_point, first_touched - 1, cur_touched, first_touched ); } } contour++; } while ( contour < CUR.pts.n_contours ); }
[ "CWE-119" ]
savannah
888cd1843e935fe675cf2ac303116d4ed5b9d54b
12490107828131494076459414255246754337
178,174
158,122
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
Mac_Read_POST_Resource( FT_Library library, FT_Stream stream, FT_Long *offsets, FT_Long resource_cnt, FT_Long face_index, FT_Face *aface ) { FT_Error error = FT_Err_Cannot_Open_Resource; FT_Memory memory = library->memory; FT_Byte* pfb_data; int i, type, flags; FT_Long len; FT_Long pfb_len, pfb_pos, pfb_lenpos; FT_Long rlen, temp; if ( face_index == -1 ) face_index = 0; if ( face_index != 0 ) return error; /* Find the length of all the POST resources, concatenated. Assume */ /* worst case (each resource in its own section). */ pfb_len = 0; for ( i = 0; i < resource_cnt; ++i ) { error = FT_Stream_Seek( stream, offsets[i] ); if ( error ) goto Exit; if ( FT_READ_LONG( temp ) ) goto Exit; pfb_len += temp + 6; } if ( FT_ALLOC( pfb_data, (FT_Long)pfb_len + 2 ) ) goto Exit; pfb_data[0] = 0x80; pfb_data[1] = 1; /* Ascii section */ pfb_data[2] = 0; /* 4-byte length, fill in later */ pfb_data[3] = 0; pfb_data[4] = 0; pfb_data[5] = 0; pfb_pos = 6; pfb_lenpos = 2; len = 0; type = 1; for ( i = 0; i < resource_cnt; ++i ) { error = FT_Stream_Seek( stream, offsets[i] ); if ( error ) goto Exit2; if ( FT_READ_LONG( rlen ) ) goto Exit; if ( FT_READ_USHORT( flags ) ) goto Exit; FT_TRACE3(( "POST fragment[%d]: offsets=0x%08x, rlen=0x%08x, flags=0x%04x\n", i, offsets[i], rlen, flags )); /* the flags are part of the resource, so rlen >= 2. */ /* but some fonts declare rlen = 0 for empty fragment */ if ( rlen > 2 ) if ( ( flags >> 8 ) == type ) len += rlen; else { if ( pfb_lenpos + 3 > pfb_len + 2 ) goto Exit2; pfb_data[pfb_lenpos ] = (FT_Byte)( len ); pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 ); pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 ); pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 ); if ( ( flags >> 8 ) == 5 ) /* End of font mark */ break; if ( pfb_pos + 6 > pfb_len + 2 ) goto Exit2; pfb_data[pfb_pos++] = 0x80; type = flags >> 8; len = rlen; pfb_data[pfb_pos++] = (FT_Byte)type; pfb_lenpos = pfb_pos; pfb_data[pfb_pos++] = 0; /* 4-byte length, fill in later */ pfb_data[pfb_pos++] = 0; pfb_data[pfb_pos++] = 0; pfb_data[pfb_pos++] = 0; } error = FT_Stream_Read( stream, (FT_Byte *)pfb_data + pfb_pos, rlen ); if ( error ) goto Exit2; pfb_pos += rlen; } if ( pfb_pos + 2 > pfb_len + 2 ) goto Exit2; pfb_data[pfb_pos++] = 0x80; pfb_data[pfb_pos++] = 3; if ( pfb_lenpos + 3 > pfb_len + 2 ) goto Exit2; pfb_data[pfb_lenpos ] = (FT_Byte)( len ); pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 ); pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 ); pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 ); return open_face_from_buffer( library, pfb_data, pfb_pos, face_index, "type1", aface ); Exit2: FT_FREE( pfb_data ); Exit: return error; }
[ "CWE-119" ]
savannah
b2ea64bcc6c385a8e8318f9c759450a07df58b6d
239474837185248719277265167606864341043
178,175
264
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
Mac_Read_POST_Resource( FT_Library library, FT_Stream stream, FT_Long *offsets, FT_Long resource_cnt, FT_Long face_index, FT_Face *aface ) { FT_Error error = FT_Err_Cannot_Open_Resource; FT_Memory memory = library->memory; FT_Byte* pfb_data; int i, type, flags; FT_Long len; FT_Long pfb_len, pfb_pos, pfb_lenpos; FT_Long rlen, temp; if ( face_index == -1 ) face_index = 0; if ( face_index != 0 ) return error; /* Find the length of all the POST resources, concatenated. Assume */ /* worst case (each resource in its own section). */ pfb_len = 0; for ( i = 0; i < resource_cnt; ++i ) { error = FT_Stream_Seek( stream, offsets[i] ); if ( error ) goto Exit; if ( FT_READ_LONG( temp ) ) goto Exit; pfb_len += temp + 6; } if ( FT_ALLOC( pfb_data, (FT_Long)pfb_len + 2 ) ) goto Exit; pfb_data[0] = 0x80; pfb_data[1] = 1; /* Ascii section */ pfb_data[2] = 0; /* 4-byte length, fill in later */ pfb_data[3] = 0; pfb_data[4] = 0; pfb_data[5] = 0; pfb_pos = 6; pfb_lenpos = 2; len = 0; type = 1; for ( i = 0; i < resource_cnt; ++i ) { error = FT_Stream_Seek( stream, offsets[i] ); if ( error ) goto Exit2; if ( FT_READ_LONG( rlen ) ) goto Exit; if ( FT_READ_USHORT( flags ) ) goto Exit; FT_TRACE3(( "POST fragment[%d]: offsets=0x%08x, rlen=0x%08x, flags=0x%04x\n", i, offsets[i], rlen, flags )); if ( ( flags >> 8 ) == 0 ) /* Comment, should not be loaded */ continue; /* the flags are part of the resource, so rlen >= 2. */ /* but some fonts declare rlen = 0 for empty fragment */ if ( rlen > 2 ) if ( ( flags >> 8 ) == type ) len += rlen; else { if ( pfb_lenpos + 3 > pfb_len + 2 ) goto Exit2; pfb_data[pfb_lenpos ] = (FT_Byte)( len ); pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 ); pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 ); pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 ); if ( ( flags >> 8 ) == 5 ) /* End of font mark */ break; if ( pfb_pos + 6 > pfb_len + 2 ) goto Exit2; pfb_data[pfb_pos++] = 0x80; type = flags >> 8; len = rlen; pfb_data[pfb_pos++] = (FT_Byte)type; pfb_lenpos = pfb_pos; pfb_data[pfb_pos++] = 0; /* 4-byte length, fill in later */ pfb_data[pfb_pos++] = 0; pfb_data[pfb_pos++] = 0; pfb_data[pfb_pos++] = 0; } error = FT_Stream_Read( stream, (FT_Byte *)pfb_data + pfb_pos, rlen ); if ( error ) goto Exit2; pfb_pos += rlen; } if ( pfb_pos + 2 > pfb_len + 2 ) goto Exit2; pfb_data[pfb_pos++] = 0x80; pfb_data[pfb_pos++] = 3; if ( pfb_lenpos + 3 > pfb_len + 2 ) goto Exit2; pfb_data[pfb_lenpos ] = (FT_Byte)( len ); pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 ); pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 ); pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 ); return open_face_from_buffer( library, pfb_data, pfb_pos, face_index, "type1", aface ); Exit2: FT_FREE( pfb_data ); Exit: return error; }
[ "CWE-119" ]
savannah
b2ea64bcc6c385a8e8318f9c759450a07df58b6d
138045724524241880239158930414068620502
178,175
158,123
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
gray_render_span( int y, int count, const FT_Span* spans, PWorker worker ) { unsigned char* p; FT_Bitmap* map = &worker->target; /* first of all, compute the scanline offset */ p = (unsigned char*)map->buffer - y * map->pitch; if ( map->pitch >= 0 ) p += ( map->rows - 1 ) * map->pitch; for ( ; count > 0; count--, spans++ ) { unsigned char coverage = spans->coverage; if ( coverage ) { /* For small-spans it is faster to do it by ourselves than * calling `memset'. This is mainly due to the cost of the * function call. */ if ( spans->len >= 8 ) FT_MEM_SET( p + spans->x, (unsigned char)coverage, spans->len ); else { unsigned char* q = p + spans->x; switch ( spans->len ) { case 7: *q++ = (unsigned char)coverage; case 6: *q++ = (unsigned char)coverage; case 5: *q++ = (unsigned char)coverage; case 4: *q++ = (unsigned char)coverage; case 3: *q++ = (unsigned char)coverage; case 2: *q++ = (unsigned char)coverage; case 1: *q = (unsigned char)coverage; default: ; } } } } }
[ "CWE-189" ]
savannah
6305b869d86ff415a33576df6d43729673c66eee
233903124056505689403424392136593938770
178,176
265
This weakness involves numeric computation errors, such as integer overflows, underflows, or precision losses, which can lead to miscalculations and exploitable behaviors in software.
true
gray_render_span( int y, int count, const FT_Span* spans, PWorker worker ) { unsigned char* p; FT_Bitmap* map = &worker->target; /* first of all, compute the scanline offset */ p = (unsigned char*)map->buffer - y * map->pitch; if ( map->pitch >= 0 ) p += (unsigned)( ( map->rows - 1 ) * map->pitch ); for ( ; count > 0; count--, spans++ ) { unsigned char coverage = spans->coverage; if ( coverage ) { /* For small-spans it is faster to do it by ourselves than * calling `memset'. This is mainly due to the cost of the * function call. */ if ( spans->len >= 8 ) FT_MEM_SET( p + spans->x, (unsigned char)coverage, spans->len ); else { unsigned char* q = p + spans->x; switch ( spans->len ) { case 7: *q++ = (unsigned char)coverage; case 6: *q++ = (unsigned char)coverage; case 5: *q++ = (unsigned char)coverage; case 4: *q++ = (unsigned char)coverage; case 3: *q++ = (unsigned char)coverage; case 2: *q++ = (unsigned char)coverage; case 1: *q = (unsigned char)coverage; default: ; } } } } }
[ "CWE-189" ]
savannah
6305b869d86ff415a33576df6d43729673c66eee
34358703453298665322690073547254403786
178,176
158,124
This weakness involves numeric computation errors, such as integer overflows, underflows, or precision losses, which can lead to miscalculations and exploitable behaviors in software.
false
Mac_Read_POST_Resource( FT_Library library, FT_Stream stream, FT_Long *offsets, FT_Long resource_cnt, FT_Long face_index, FT_Face *aface ) { FT_Error error = FT_Err_Cannot_Open_Resource; FT_Memory memory = library->memory; FT_Byte* pfb_data; int i, type, flags; FT_Long len; FT_Long pfb_len, pfb_pos, pfb_lenpos; FT_Long rlen, temp; if ( face_index == -1 ) face_index = 0; if ( face_index != 0 ) return error; /* Find the length of all the POST resources, concatenated. Assume */ /* worst case (each resource in its own section). */ pfb_len = 0; for ( i = 0; i < resource_cnt; ++i ) { error = FT_Stream_Seek( stream, offsets[i] ); if ( error ) goto Exit; if ( FT_READ_LONG( temp ) ) goto Exit; pfb_len += temp + 6; } if ( FT_ALLOC( pfb_data, (FT_Long)pfb_len + 2 ) ) goto Exit; pfb_data[0] = 0x80; pfb_data[1] = 1; /* Ascii section */ pfb_data[2] = 0; /* 4-byte length, fill in later */ pfb_data[3] = 0; pfb_data[4] = 0; pfb_data[5] = 0; pfb_pos = 6; pfb_lenpos = 2; len = 0; type = 1; for ( i = 0; i < resource_cnt; ++i ) { error = FT_Stream_Seek( stream, offsets[i] ); if ( error ) goto Exit2; if ( FT_READ_LONG( rlen ) ) goto Exit; if ( FT_READ_USHORT( flags ) ) goto Exit; rlen -= 2; /* the flags are part of the resource */ if ( ( flags >> 8 ) == type ) len += rlen; else { pfb_data[pfb_lenpos ] = (FT_Byte)( len ); pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 ); pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 ); pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 ); if ( ( flags >> 8 ) == 5 ) /* End of font mark */ break; pfb_data[pfb_pos++] = 0x80; type = flags >> 8; len = rlen; pfb_data[pfb_pos++] = (FT_Byte)type; pfb_lenpos = pfb_pos; pfb_data[pfb_pos++] = 0; /* 4-byte length, fill in later */ pfb_data[pfb_pos++] = 0; pfb_data[pfb_pos++] = 0; pfb_data[pfb_pos++] = 0; } error = FT_Stream_Read( stream, (FT_Byte *)pfb_data + pfb_pos, rlen ); pfb_pos += rlen; } pfb_data[pfb_lenpos ] = (FT_Byte)( len ); pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 ); pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 ); pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 ); return open_face_from_buffer( library, pfb_data, pfb_pos, face_index, "type1", aface ); Exit2: FT_FREE( pfb_data ); Exit: return error; }
[ "CWE-119" ]
savannah
c69891a1345640096fbf396e8dd567fe879ce233
66761366277063878236162927407801840545
178,178
267
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
Mac_Read_POST_Resource( FT_Library library, FT_Stream stream, FT_Long *offsets, FT_Long resource_cnt, FT_Long face_index, FT_Face *aface ) { FT_Error error = FT_Err_Cannot_Open_Resource; FT_Memory memory = library->memory; FT_Byte* pfb_data; int i, type, flags; FT_Long len; FT_Long pfb_len, pfb_pos, pfb_lenpos; FT_Long rlen, temp; if ( face_index == -1 ) face_index = 0; if ( face_index != 0 ) return error; /* Find the length of all the POST resources, concatenated. Assume */ /* worst case (each resource in its own section). */ pfb_len = 0; for ( i = 0; i < resource_cnt; ++i ) { error = FT_Stream_Seek( stream, offsets[i] ); if ( error ) goto Exit; if ( FT_READ_LONG( temp ) ) goto Exit; pfb_len += temp + 6; } if ( FT_ALLOC( pfb_data, (FT_Long)pfb_len + 2 ) ) goto Exit; pfb_data[0] = 0x80; pfb_data[1] = 1; /* Ascii section */ pfb_data[2] = 0; /* 4-byte length, fill in later */ pfb_data[3] = 0; pfb_data[4] = 0; pfb_data[5] = 0; pfb_pos = 6; pfb_lenpos = 2; len = 0; type = 1; for ( i = 0; i < resource_cnt; ++i ) { error = FT_Stream_Seek( stream, offsets[i] ); if ( error ) goto Exit2; if ( FT_READ_LONG( rlen ) ) goto Exit; if ( FT_READ_USHORT( flags ) ) goto Exit; rlen -= 2; /* the flags are part of the resource */ if ( ( flags >> 8 ) == type ) len += rlen; else { pfb_data[pfb_lenpos ] = (FT_Byte)( len ); pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 ); pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 ); pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 ); if ( ( flags >> 8 ) == 5 ) /* End of font mark */ break; pfb_data[pfb_pos++] = 0x80; type = flags >> 8; len = rlen; pfb_data[pfb_pos++] = (FT_Byte)type; pfb_lenpos = pfb_pos; pfb_data[pfb_pos++] = 0; /* 4-byte length, fill in later */ pfb_data[pfb_pos++] = 0; pfb_data[pfb_pos++] = 0; pfb_data[pfb_pos++] = 0; } error = FT_Stream_Read( stream, (FT_Byte *)pfb_data + pfb_pos, rlen ); if ( error ) goto Exit2; pfb_pos += rlen; } pfb_data[pfb_lenpos ] = (FT_Byte)( len ); pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 ); pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 ); pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 ); return open_face_from_buffer( library, pfb_data, pfb_pos, face_index, "type1", aface ); Exit2: FT_FREE( pfb_data ); Exit: return error; }
[ "CWE-119" ]
savannah
c69891a1345640096fbf396e8dd567fe879ce233
104194448279931618216830643509594183948
178,178
158,126
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
psh_glyph_find_strong_points( PSH_Glyph glyph, FT_Int dimension ) { /* a point is `strong' if it is located on a stem edge and */ /* has an `in' or `out' tangent parallel to the hint's direction */ PSH_Hint_Table table = &glyph->hint_tables[dimension]; PS_Mask mask = table->hint_masks->masks; FT_UInt num_masks = table->hint_masks->num_masks; FT_UInt first = 0; FT_Int major_dir = dimension == 0 ? PSH_DIR_VERTICAL : PSH_DIR_HORIZONTAL; PSH_Dimension dim = &glyph->globals->dimension[dimension]; FT_Fixed scale = dim->scale_mult; FT_Int threshold; threshold = (FT_Int)FT_DivFix( PSH_STRONG_THRESHOLD, scale ); if ( threshold > PSH_STRONG_THRESHOLD_MAXIMUM ) threshold = PSH_STRONG_THRESHOLD_MAXIMUM; /* process secondary hints to `selected' points */ /* process secondary hints to `selected' points */ if ( num_masks > 1 && glyph->num_points > 0 ) { first = mask->end_point; mask++; for ( ; num_masks > 1; num_masks--, mask++ ) { next = mask->end_point; FT_Int count; next = mask->end_point; count = next - first; if ( count > 0 ) { threshold, major_dir ); } first = next; } } /* process primary hints for all points */ if ( num_masks == 1 ) { FT_UInt count = glyph->num_points; PSH_Point point = glyph->points; psh_hint_table_activate_mask( table, table->hint_masks->masks ); psh_hint_table_find_strong_points( table, point, count, threshold, major_dir ); } /* now, certain points may have been attached to a hint and */ /* not marked as strong; update their flags then */ { FT_UInt count = glyph->num_points; PSH_Point point = glyph->points; for ( ; count > 0; count--, point++ ) if ( point->hint && !psh_point_is_strong( point ) ) psh_point_set_strong( point ); } }
[ "CWE-399" ]
savannah
8d22746c9e5af80ff4304aef440986403a5072e2
238917502809110546701210284595052003786
178,179
268
This vulnerability category highlights issues in resource management where failures to properly release memory, file handles, or other resources can degrade system performance or enable denial-of-service conditions.
true
psh_glyph_find_strong_points( PSH_Glyph glyph, FT_Int dimension ) { /* a point is `strong' if it is located on a stem edge and */ /* has an `in' or `out' tangent parallel to the hint's direction */ PSH_Hint_Table table = &glyph->hint_tables[dimension]; PS_Mask mask = table->hint_masks->masks; FT_UInt num_masks = table->hint_masks->num_masks; FT_UInt first = 0; FT_Int major_dir = dimension == 0 ? PSH_DIR_VERTICAL : PSH_DIR_HORIZONTAL; PSH_Dimension dim = &glyph->globals->dimension[dimension]; FT_Fixed scale = dim->scale_mult; FT_Int threshold; threshold = (FT_Int)FT_DivFix( PSH_STRONG_THRESHOLD, scale ); if ( threshold > PSH_STRONG_THRESHOLD_MAXIMUM ) threshold = PSH_STRONG_THRESHOLD_MAXIMUM; /* process secondary hints to `selected' points */ /* process secondary hints to `selected' points */ if ( num_masks > 1 && glyph->num_points > 0 ) { /* the `endchar' op can reduce the number of points */ first = mask->end_point > glyph->num_points ? glyph->num_points : mask->end_point; mask++; for ( ; num_masks > 1; num_masks--, mask++ ) { next = mask->end_point; FT_Int count; next = mask->end_point > glyph->num_points ? glyph->num_points : mask->end_point; count = next - first; if ( count > 0 ) { threshold, major_dir ); } first = next; } } /* process primary hints for all points */ if ( num_masks == 1 ) { FT_UInt count = glyph->num_points; PSH_Point point = glyph->points; psh_hint_table_activate_mask( table, table->hint_masks->masks ); psh_hint_table_find_strong_points( table, point, count, threshold, major_dir ); } /* now, certain points may have been attached to a hint and */ /* not marked as strong; update their flags then */ { FT_UInt count = glyph->num_points; PSH_Point point = glyph->points; for ( ; count > 0; count--, point++ ) if ( point->hint && !psh_point_is_strong( point ) ) psh_point_set_strong( point ); } }
[ "CWE-399" ]
savannah
8d22746c9e5af80ff4304aef440986403a5072e2
125782867654545345190551371896398338847
178,179
158,127
This vulnerability category highlights issues in resource management where failures to properly release memory, file handles, or other resources can degrade system performance or enable denial-of-service conditions.
false
cff_decoder_parse_charstrings( CFF_Decoder* decoder, FT_Byte* charstring_base, FT_ULong charstring_len ) { FT_Error error; CFF_Decoder_Zone* zone; FT_Byte* ip; FT_Byte* limit; CFF_Builder* builder = &decoder->builder; FT_Pos x, y; FT_Fixed seed; FT_Fixed* stack; FT_Int charstring_type = decoder->cff->top_font.font_dict.charstring_type; T2_Hints_Funcs hinter; /* set default width */ decoder->num_hints = 0; decoder->read_width = 1; /* compute random seed from stack address of parameter */ seed = (FT_Fixed)( ( (FT_PtrDist)(char*)&seed ^ (FT_PtrDist)(char*)&decoder ^ (FT_PtrDist)(char*)&charstring_base ) & FT_ULONG_MAX ) ; seed = ( seed ^ ( seed >> 10 ) ^ ( seed >> 20 ) ) & 0xFFFFL; if ( seed == 0 ) seed = 0x7384; /* initialize the decoder */ decoder->top = decoder->stack; decoder->zone = decoder->zones; zone = decoder->zones; stack = decoder->top; hinter = (T2_Hints_Funcs)builder->hints_funcs; builder->path_begun = 0; zone->base = charstring_base; limit = zone->limit = charstring_base + charstring_len; ip = zone->cursor = zone->base; error = CFF_Err_Ok; x = builder->pos_x; y = builder->pos_y; /* begin hints recording session, if any */ if ( hinter ) hinter->open( hinter->hints ); /* now execute loop */ while ( ip < limit ) { CFF_Operator op; FT_Byte v; /********************************************************************/ /* */ /* Decode operator or operand */ /* */ v = *ip++; if ( v >= 32 || v == 28 ) { FT_Int shift = 16; FT_Int32 val; /* this is an operand, push it on the stack */ if ( v == 28 ) { if ( ip + 1 >= limit ) goto Syntax_Error; val = (FT_Short)( ( (FT_Short)ip[0] << 8 ) | ip[1] ); ip += 2; } else if ( v < 247 ) val = (FT_Int32)v - 139; else if ( v < 251 ) { if ( ip >= limit ) goto Syntax_Error; val = ( (FT_Int32)v - 247 ) * 256 + *ip++ + 108; } else if ( v < 255 ) { if ( ip >= limit ) goto Syntax_Error; val = -( (FT_Int32)v - 251 ) * 256 - *ip++ - 108; } else { if ( ip + 3 >= limit ) goto Syntax_Error; val = ( (FT_Int32)ip[0] << 24 ) | ( (FT_Int32)ip[1] << 16 ) | ( (FT_Int32)ip[2] << 8 ) | ip[3]; ip += 4; if ( charstring_type == 2 ) shift = 0; } if ( decoder->top - stack >= CFF_MAX_OPERANDS ) goto Stack_Overflow; val <<= shift; *decoder->top++ = val; #ifdef FT_DEBUG_LEVEL_TRACE if ( !( val & 0xFFFFL ) ) FT_TRACE4(( " %ld", (FT_Int32)( val >> 16 ) )); else FT_TRACE4(( " %.2f", val / 65536.0 )); #endif } else { /* The specification says that normally arguments are to be taken */ /* from the bottom of the stack. However, this seems not to be */ /* correct, at least for Acroread 7.0.8 on GNU/Linux: It pops the */ /* arguments similar to a PS interpreter. */ FT_Fixed* args = decoder->top; FT_Int num_args = (FT_Int)( args - decoder->stack ); FT_Int req_args; /* find operator */ op = cff_op_unknown; switch ( v ) { case 1: op = cff_op_hstem; break; case 3: op = cff_op_vstem; break; case 4: op = cff_op_vmoveto; break; case 5: op = cff_op_rlineto; break; case 6: op = cff_op_hlineto; break; case 7: op = cff_op_vlineto; break; case 8: op = cff_op_rrcurveto; break; case 9: op = cff_op_closepath; break; case 10: op = cff_op_callsubr; break; case 11: op = cff_op_return; break; case 12: { if ( ip >= limit ) goto Syntax_Error; v = *ip++; switch ( v ) { case 0: op = cff_op_dotsection; break; case 1: /* this is actually the Type1 vstem3 operator */ op = cff_op_vstem; break; case 2: /* this is actually the Type1 hstem3 operator */ op = cff_op_hstem; break; case 3: op = cff_op_and; break; case 4: op = cff_op_or; break; case 5: op = cff_op_not; break; case 6: op = cff_op_seac; break; case 7: op = cff_op_sbw; break; case 8: op = cff_op_store; break; case 9: op = cff_op_abs; break; case 10: op = cff_op_add; break; case 11: op = cff_op_sub; break; case 12: op = cff_op_div; break; case 13: op = cff_op_load; break; case 14: op = cff_op_neg; break; case 15: op = cff_op_eq; break; case 16: op = cff_op_callothersubr; break; case 17: op = cff_op_pop; break; case 18: op = cff_op_drop; break; case 20: op = cff_op_put; break; case 21: op = cff_op_get; break; case 22: op = cff_op_ifelse; break; case 23: op = cff_op_random; break; case 24: op = cff_op_mul; break; case 26: op = cff_op_sqrt; break; case 27: op = cff_op_dup; break; case 28: op = cff_op_exch; break; case 29: op = cff_op_index; break; case 30: op = cff_op_roll; break; case 33: op = cff_op_setcurrentpoint; break; case 34: op = cff_op_hflex; break; case 35: op = cff_op_flex; break; case 36: op = cff_op_hflex1; break; case 37: op = cff_op_flex1; break; default: /* decrement ip for syntax error message */ ip--; } } break; case 13: op = cff_op_hsbw; break; case 14: op = cff_op_endchar; break; case 16: op = cff_op_blend; break; case 18: op = cff_op_hstemhm; break; case 19: op = cff_op_hintmask; break; case 20: op = cff_op_cntrmask; break; case 21: op = cff_op_rmoveto; break; case 22: op = cff_op_hmoveto; break; case 23: op = cff_op_vstemhm; break; case 24: op = cff_op_rcurveline; break; case 25: op = cff_op_rlinecurve; break; case 26: op = cff_op_vvcurveto; break; case 27: op = cff_op_hhcurveto; break; case 29: op = cff_op_callgsubr; break; case 30: op = cff_op_vhcurveto; break; case 31: op = cff_op_hvcurveto; break; default: break; } if ( op == cff_op_unknown ) goto Syntax_Error; /* check arguments */ req_args = cff_argument_counts[op]; if ( req_args & CFF_COUNT_CHECK_WIDTH ) { if ( num_args > 0 && decoder->read_width ) { /* If `nominal_width' is non-zero, the number is really a */ /* difference against `nominal_width'. Else, the number here */ /* is truly a width, not a difference against `nominal_width'. */ /* If the font does not set `nominal_width', then */ /* `nominal_width' defaults to zero, and so we can set */ /* `glyph_width' to `nominal_width' plus number on the stack */ /* -- for either case. */ FT_Int set_width_ok; switch ( op ) { case cff_op_hmoveto: case cff_op_vmoveto: set_width_ok = num_args & 2; break; case cff_op_hstem: case cff_op_vstem: case cff_op_hstemhm: case cff_op_vstemhm: case cff_op_rmoveto: case cff_op_hintmask: case cff_op_cntrmask: set_width_ok = num_args & 1; break; case cff_op_endchar: /* If there is a width specified for endchar, we either have */ /* 1 argument or 5 arguments. We like to argue. */ set_width_ok = ( num_args == 5 ) || ( num_args == 1 ); break; default: set_width_ok = 0; break; } if ( set_width_ok ) { decoder->glyph_width = decoder->nominal_width + ( stack[0] >> 16 ); if ( decoder->width_only ) { /* we only want the advance width; stop here */ break; } /* Consumed an argument. */ num_args--; } } decoder->read_width = 0; req_args = 0; } req_args &= 0x000F; if ( num_args < req_args ) goto Stack_Underflow; args -= req_args; num_args -= req_args; /* At this point, `args' points to the first argument of the */ /* operand in case `req_args' isn't zero. Otherwise, we have */ /* to adjust `args' manually. */ /* Note that we only pop arguments from the stack which we */ /* really need and can digest so that we can continue in case */ /* of superfluous stack elements. */ switch ( op ) { case cff_op_hstem: case cff_op_vstem: case cff_op_hstemhm: case cff_op_vstemhm: /* the number of arguments is always even here */ FT_TRACE4(( op == cff_op_hstem ? " hstem\n" : ( op == cff_op_vstem ? " vstem\n" : ( op == cff_op_hstemhm ? " hstemhm\n" : " vstemhm\n" ) ) )); if ( hinter ) hinter->stems( hinter->hints, ( op == cff_op_hstem || op == cff_op_hstemhm ), num_args / 2, args - ( num_args & ~1 ) ); decoder->num_hints += num_args / 2; args = stack; break; case cff_op_hintmask: case cff_op_cntrmask: FT_TRACE4(( op == cff_op_hintmask ? " hintmask" : " cntrmask" )); /* implement vstem when needed -- */ /* the specification doesn't say it, but this also works */ /* with the 'cntrmask' operator */ /* */ if ( num_args > 0 ) { if ( hinter ) hinter->stems( hinter->hints, 0, num_args / 2, args - ( num_args & ~1 ) ); decoder->num_hints += num_args / 2; } if ( hinter ) { if ( op == cff_op_hintmask ) hinter->hintmask( hinter->hints, builder->current->n_points, decoder->num_hints, ip ); else hinter->counter( hinter->hints, decoder->num_hints, ip ); } #ifdef FT_DEBUG_LEVEL_TRACE { FT_UInt maskbyte; FT_TRACE4(( " (maskbytes: " )); for ( maskbyte = 0; maskbyte < (FT_UInt)(( decoder->num_hints + 7 ) >> 3); maskbyte++, ip++ ) FT_TRACE4(( "0x%02X", *ip )); FT_TRACE4(( ")\n" )); } #else ip += ( decoder->num_hints + 7 ) >> 3; #endif if ( ip >= limit ) goto Syntax_Error; args = stack; break; case cff_op_rmoveto: FT_TRACE4(( " rmoveto\n" )); cff_builder_close_contour( builder ); builder->path_begun = 0; x += args[-2]; y += args[-1]; args = stack; break; case cff_op_vmoveto: FT_TRACE4(( " vmoveto\n" )); cff_builder_close_contour( builder ); builder->path_begun = 0; y += args[-1]; args = stack; break; case cff_op_hmoveto: FT_TRACE4(( " hmoveto\n" )); cff_builder_close_contour( builder ); builder->path_begun = 0; x += args[-1]; args = stack; break; case cff_op_rlineto: FT_TRACE4(( " rlineto\n" )); if ( cff_builder_start_point ( builder, x, y ) || check_points( builder, num_args / 2 ) ) goto Fail; if ( num_args < 2 ) goto Stack_Underflow; args -= num_args & ~1; while ( args < decoder->top ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 1 ); args += 2; } args = stack; break; case cff_op_hlineto: case cff_op_vlineto: { FT_Int phase = ( op == cff_op_hlineto ); FT_TRACE4(( op == cff_op_hlineto ? " hlineto\n" : " vlineto\n" )); if ( num_args < 1 ) goto Stack_Underflow; if ( cff_builder_start_point ( builder, x, y ) || check_points( builder, num_args ) ) goto Fail; args = stack; while ( args < decoder->top ) { if ( phase ) x += args[0]; else y += args[0]; if ( cff_builder_add_point1( builder, x, y ) ) goto Fail; args++; phase ^= 1; } args = stack; } break; case cff_op_rrcurveto: { FT_Int nargs; FT_TRACE4(( " rrcurveto\n" )); if ( num_args < 6 ) goto Stack_Underflow; nargs = num_args - num_args % 6; if ( cff_builder_start_point ( builder, x, y ) || check_points( builder, nargs / 2 ) ) goto Fail; args -= nargs; while ( args < decoder->top ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); x += args[4]; y += args[5]; cff_builder_add_point( builder, x, y, 1 ); args += 6; } args = stack; } break; case cff_op_vvcurveto: { FT_Int nargs; FT_TRACE4(( " vvcurveto\n" )); if ( num_args < 4 ) goto Stack_Underflow; /* if num_args isn't of the form 4n or 4n+1, */ /* we reduce it to 4n+1 */ nargs = num_args - num_args % 4; if ( num_args - nargs > 0 ) nargs += 1; if ( cff_builder_start_point( builder, x, y ) ) goto Fail; args -= nargs; if ( nargs & 1 ) { x += args[0]; args++; nargs--; } if ( check_points( builder, 3 * ( nargs / 4 ) ) ) goto Fail; while ( args < decoder->top ) { y += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); y += args[3]; cff_builder_add_point( builder, x, y, 1 ); args += 4; } args = stack; } break; case cff_op_hhcurveto: { FT_Int nargs; FT_TRACE4(( " hhcurveto\n" )); if ( num_args < 4 ) goto Stack_Underflow; /* if num_args isn't of the form 4n or 4n+1, */ /* we reduce it to 4n+1 */ nargs = num_args - num_args % 4; if ( num_args - nargs > 0 ) nargs += 1; if ( cff_builder_start_point( builder, x, y ) ) goto Fail; args -= nargs; if ( nargs & 1 ) { y += args[0]; args++; nargs--; } if ( check_points( builder, 3 * ( nargs / 4 ) ) ) goto Fail; while ( args < decoder->top ) { x += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); x += args[3]; cff_builder_add_point( builder, x, y, 1 ); args += 4; } args = stack; } break; case cff_op_vhcurveto: case cff_op_hvcurveto: { FT_Int phase; FT_Int nargs; FT_TRACE4(( op == cff_op_vhcurveto ? " vhcurveto\n" : " hvcurveto\n" )); if ( cff_builder_start_point( builder, x, y ) ) goto Fail; if ( num_args < 4 ) goto Stack_Underflow; /* if num_args isn't of the form 8n, 8n+1, 8n+4, or 8n+5, */ /* we reduce it to the largest one which fits */ nargs = num_args - num_args % 4; if ( num_args - nargs > 0 ) nargs += 1; args -= nargs; if ( check_points( builder, ( nargs / 4 ) * 3 ) ) goto Stack_Underflow; phase = ( op == cff_op_hvcurveto ); while ( nargs >= 4 ) { nargs -= 4; if ( phase ) { x += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); y += args[3]; if ( nargs == 1 ) x += args[4]; cff_builder_add_point( builder, x, y, 1 ); } else { y += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); x += args[3]; if ( nargs == 1 ) y += args[4]; cff_builder_add_point( builder, x, y, 1 ); } args += 4; phase ^= 1; } args = stack; } break; case cff_op_rlinecurve: { FT_Int num_lines; FT_Int nargs; FT_TRACE4(( " rlinecurve\n" )); if ( num_args < 8 ) goto Stack_Underflow; nargs = num_args & ~1; num_lines = ( nargs - 6 ) / 2; if ( cff_builder_start_point( builder, x, y ) || check_points( builder, num_lines + 3 ) ) goto Fail; args -= nargs; /* first, add the line segments */ while ( num_lines > 0 ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 1 ); args += 2; num_lines--; } /* then the curve */ x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); x += args[4]; y += args[5]; cff_builder_add_point( builder, x, y, 1 ); args = stack; } break; case cff_op_rcurveline: { FT_Int num_curves; FT_Int nargs; FT_TRACE4(( " rcurveline\n" )); if ( num_args < 8 ) goto Stack_Underflow; nargs = num_args - 2; nargs = nargs - nargs % 6 + 2; num_curves = ( nargs - 2 ) / 6; if ( cff_builder_start_point ( builder, x, y ) || check_points( builder, num_curves * 3 + 2 ) ) goto Fail; args -= nargs; /* first, add the curves */ while ( num_curves > 0 ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); x += args[4]; y += args[5]; cff_builder_add_point( builder, x, y, 1 ); args += 6; num_curves--; } /* then the final line */ x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 1 ); args = stack; } break; case cff_op_hflex1: { FT_Pos start_y; FT_TRACE4(( " hflex1\n" )); /* adding five more points: 4 control points, 1 on-curve point */ /* -- make sure we have enough space for the start point if it */ /* needs to be added */ if ( cff_builder_start_point( builder, x, y ) || check_points( builder, 6 ) ) goto Fail; /* record the starting point's y position for later use */ start_y = y; /* first control point */ x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); /* second control point */ x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); /* join point; on curve, with y-value the same as the last */ /* control point's y-value */ x += args[4]; cff_builder_add_point( builder, x, y, 1 ); /* third control point, with y-value the same as the join */ /* point's y-value */ x += args[5]; cff_builder_add_point( builder, x, y, 0 ); /* fourth control point */ x += args[6]; y += args[7]; cff_builder_add_point( builder, x, y, 0 ); /* ending point, with y-value the same as the start */ x += args[8]; y = start_y; cff_builder_add_point( builder, x, y, 1 ); args = stack; break; } case cff_op_hflex: { FT_Pos start_y; FT_TRACE4(( " hflex\n" )); /* adding six more points; 4 control points, 2 on-curve points */ if ( cff_builder_start_point( builder, x, y ) || check_points( builder, 6 ) ) goto Fail; /* record the starting point's y-position for later use */ start_y = y; /* first control point */ x += args[0]; cff_builder_add_point( builder, x, y, 0 ); /* second control point */ x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); /* join point; on curve, with y-value the same as the last */ /* control point's y-value */ x += args[3]; cff_builder_add_point( builder, x, y, 1 ); /* third control point, with y-value the same as the join */ /* point's y-value */ x += args[4]; cff_builder_add_point( builder, x, y, 0 ); /* fourth control point */ x += args[5]; y = start_y; cff_builder_add_point( builder, x, y, 0 ); /* ending point, with y-value the same as the start point's */ /* y-value -- we don't add this point, though */ x += args[6]; cff_builder_add_point( builder, x, y, 1 ); args = stack; break; } case cff_op_flex1: { FT_Pos start_x, start_y; /* record start x, y values for */ /* alter use */ FT_Fixed dx = 0, dy = 0; /* used in horizontal/vertical */ /* algorithm below */ FT_Int horizontal, count; FT_Fixed* temp; FT_TRACE4(( " flex1\n" )); /* adding six more points; 4 control points, 2 on-curve points */ if ( cff_builder_start_point( builder, x, y ) || check_points( builder, 6 ) ) goto Fail; /* record the starting point's x, y position for later use */ start_x = x; start_y = y; /* XXX: figure out whether this is supposed to be a horizontal */ /* or vertical flex; the Type 2 specification is vague... */ temp = args; /* grab up to the last argument */ for ( count = 5; count > 0; count-- ) { dx += temp[0]; dy += temp[1]; temp += 2; } if ( dx < 0 ) dx = -dx; if ( dy < 0 ) dy = -dy; /* strange test, but here it is... */ horizontal = ( dx > dy ); for ( count = 5; count > 0; count-- ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, (FT_Bool)( count == 3 ) ); args += 2; } /* is last operand an x- or y-delta? */ if ( horizontal ) { x += args[0]; y = start_y; } else { x = start_x; y += args[0]; } cff_builder_add_point( builder, x, y, 1 ); args = stack; break; } case cff_op_flex: { FT_UInt count; FT_TRACE4(( " flex\n" )); if ( cff_builder_start_point( builder, x, y ) || check_points( builder, 6 ) ) goto Fail; for ( count = 6; count > 0; count-- ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, (FT_Bool)( count == 4 || count == 1 ) ); args += 2; } args = stack; } break; case cff_op_seac: FT_TRACE4(( " seac\n" )); error = cff_operator_seac( decoder, args[0], args[1], args[2], (FT_Int)( args[3] >> 16 ), (FT_Int)( args[4] >> 16 ) ); /* add current outline to the glyph slot */ FT_GlyphLoader_Add( builder->loader ); /* return now! */ FT_TRACE4(( "\n" )); return error; case cff_op_endchar: FT_TRACE4(( " endchar\n" )); /* We are going to emulate the seac operator. */ if ( num_args >= 4 ) { /* Save glyph width so that the subglyphs don't overwrite it. */ FT_Pos glyph_width = decoder->glyph_width; error = cff_operator_seac( decoder, 0L, args[-4], args[-3], (FT_Int)( args[-2] >> 16 ), (FT_Int)( args[-1] >> 16 ) ); decoder->glyph_width = glyph_width; } else { if ( !error ) error = CFF_Err_Ok; cff_builder_close_contour( builder ); /* close hints recording session */ if ( hinter ) { if ( hinter->close( hinter->hints, builder->current->n_points ) ) goto Syntax_Error; /* apply hints to the loaded glyph outline now */ hinter->apply( hinter->hints, builder->current, (PSH_Globals)builder->hints_globals, decoder->hint_mode ); } /* add current outline to the glyph slot */ FT_GlyphLoader_Add( builder->loader ); } /* return now! */ FT_TRACE4(( "\n" )); return error; case cff_op_abs: FT_TRACE4(( " abs\n" )); if ( args[0] < 0 ) args[0] = -args[0]; args++; break; case cff_op_add: FT_TRACE4(( " add\n" )); args[0] += args[1]; args++; break; case cff_op_sub: FT_TRACE4(( " sub\n" )); args[0] -= args[1]; args++; break; case cff_op_div: FT_TRACE4(( " div\n" )); args[0] = FT_DivFix( args[0], args[1] ); args++; break; case cff_op_neg: FT_TRACE4(( " neg\n" )); args[0] = -args[0]; args++; break; case cff_op_random: { FT_Fixed Rand; FT_TRACE4(( " rand\n" )); Rand = seed; if ( Rand >= 0x8000L ) Rand++; args[0] = Rand; seed = FT_MulFix( seed, 0x10000L - seed ); if ( seed == 0 ) seed += 0x2873; args++; } break; case cff_op_mul: FT_TRACE4(( " mul\n" )); args[0] = FT_MulFix( args[0], args[1] ); args++; break; case cff_op_sqrt: FT_TRACE4(( " sqrt\n" )); if ( args[0] > 0 ) { FT_Int count = 9; FT_Fixed root = args[0]; FT_Fixed new_root; for (;;) { new_root = ( root + FT_DivFix( args[0], root ) + 1 ) >> 1; if ( new_root == root || count <= 0 ) break; root = new_root; } args[0] = new_root; } else args[0] = 0; args++; break; case cff_op_drop: /* nothing */ FT_TRACE4(( " drop\n" )); break; case cff_op_exch: { FT_Fixed tmp; FT_TRACE4(( " exch\n" )); tmp = args[0]; args[0] = args[1]; args[1] = tmp; args += 2; } break; case cff_op_index: { FT_Int idx = (FT_Int)( args[0] >> 16 ); FT_TRACE4(( " index\n" )); if ( idx < 0 ) idx = 0; else if ( idx > num_args - 2 ) idx = num_args - 2; args[0] = args[-( idx + 1 )]; args++; } break; case cff_op_roll: { FT_Int count = (FT_Int)( args[0] >> 16 ); FT_Int idx = (FT_Int)( args[1] >> 16 ); FT_TRACE4(( " roll\n" )); if ( count <= 0 ) count = 1; args -= count; if ( args < stack ) goto Stack_Underflow; if ( idx >= 0 ) { while ( idx > 0 ) { FT_Fixed tmp = args[count - 1]; FT_Int i; for ( i = count - 2; i >= 0; i-- ) args[i + 1] = args[i]; args[0] = tmp; idx--; } } else { while ( idx < 0 ) { FT_Fixed tmp = args[0]; FT_Int i; for ( i = 0; i < count - 1; i++ ) args[i] = args[i + 1]; args[count - 1] = tmp; idx++; } } args += count; } break; case cff_op_dup: FT_TRACE4(( " dup\n" )); args[1] = args[0]; args += 2; break; case cff_op_put: { FT_Fixed val = args[0]; FT_Int idx = (FT_Int)( args[1] >> 16 ); FT_TRACE4(( " put\n" )); if ( idx >= 0 && idx < CFF_MAX_TRANS_ELEMENTS ) decoder->buildchar[idx] = val; } break; case cff_op_get: { FT_Int idx = (FT_Int)( args[0] >> 16 ); FT_Fixed val = 0; FT_TRACE4(( " get\n" )); if ( idx >= 0 && idx < CFF_MAX_TRANS_ELEMENTS ) val = decoder->buildchar[idx]; args[0] = val; args++; } break; case cff_op_store: FT_TRACE4(( " store\n")); goto Unimplemented; case cff_op_load: FT_TRACE4(( " load\n" )); goto Unimplemented; case cff_op_dotsection: /* this operator is deprecated and ignored by the parser */ FT_TRACE4(( " dotsection\n" )); break; case cff_op_closepath: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " closepath (invalid op)\n" )); args = stack; break; case cff_op_hsbw: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " hsbw (invalid op)\n" )); decoder->glyph_width = decoder->nominal_width + ( args[1] >> 16 ); decoder->builder.left_bearing.x = args[0]; decoder->builder.left_bearing.y = 0; x = decoder->builder.pos_x + args[0]; y = decoder->builder.pos_y; args = stack; break; case cff_op_sbw: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " sbw (invalid op)\n" )); decoder->glyph_width = decoder->nominal_width + ( args[2] >> 16 ); decoder->builder.left_bearing.x = args[0]; decoder->builder.left_bearing.y = args[1]; x = decoder->builder.pos_x + args[0]; y = decoder->builder.pos_y + args[1]; args = stack; break; case cff_op_setcurrentpoint: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " setcurrentpoint (invalid op)\n" )); x = decoder->builder.pos_x + args[0]; y = decoder->builder.pos_y + args[1]; args = stack; break; case cff_op_callothersubr: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " callothersubr (invalid op)\n" )); /* subsequent `pop' operands should add the arguments, */ /* this is the implementation described for `unknown' other */ /* subroutines in the Type1 spec. */ args -= 2 + ( args[-2] >> 16 ); break; case cff_op_pop: /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " pop (invalid op)\n" )); args++; break; case cff_op_and: { FT_Fixed cond = args[0] && args[1]; FT_TRACE4(( " and\n" )); args[0] = cond ? 0x10000L : 0; args++; } break; case cff_op_or: { FT_Fixed cond = args[0] || args[1]; FT_TRACE4(( " or\n" )); args[0] = cond ? 0x10000L : 0; args++; } break; case cff_op_eq: { FT_Fixed cond = !args[0]; FT_TRACE4(( " eq\n" )); args[0] = cond ? 0x10000L : 0; args++; } break; case cff_op_ifelse: { FT_Fixed cond = ( args[2] <= args[3] ); FT_TRACE4(( " ifelse\n" )); if ( !cond ) args[0] = args[1]; args++; } break; case cff_op_callsubr: { FT_UInt idx = (FT_UInt)( ( args[0] >> 16 ) + decoder->locals_bias ); FT_TRACE4(( " callsubr(%d)\n", idx )); if ( idx >= decoder->num_locals ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " invalid local subr index\n" )); goto Syntax_Error; } if ( zone - decoder->zones >= CFF_MAX_SUBRS_CALLS ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " too many nested subrs\n" )); goto Syntax_Error; } zone->cursor = ip; /* save current instruction pointer */ zone++; zone->base = decoder->locals[idx]; zone->limit = decoder->locals[idx + 1]; zone->cursor = zone->base; if ( !zone->base || zone->limit == zone->base ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " invoking empty subrs\n" )); goto Syntax_Error; } decoder->zone = zone; ip = zone->base; limit = zone->limit; } break; case cff_op_callgsubr: { FT_UInt idx = (FT_UInt)( ( args[0] >> 16 ) + decoder->globals_bias ); FT_TRACE4(( " callgsubr(%d)\n", idx )); if ( idx >= decoder->num_globals ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " invalid global subr index\n" )); goto Syntax_Error; } if ( zone - decoder->zones >= CFF_MAX_SUBRS_CALLS ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " too many nested subrs\n" )); goto Syntax_Error; } zone->cursor = ip; /* save current instruction pointer */ zone++; zone->base = decoder->globals[idx]; zone->limit = decoder->globals[idx + 1]; zone->cursor = zone->base; if ( !zone->base || zone->limit == zone->base ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " invoking empty subrs\n" )); goto Syntax_Error; } decoder->zone = zone; ip = zone->base; limit = zone->limit; } break; case cff_op_return: FT_TRACE4(( " return\n" )); if ( decoder->zone <= decoder->zones ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " unexpected return\n" )); goto Syntax_Error; } decoder->zone--; zone = decoder->zone; ip = zone->cursor; limit = zone->limit; break; default: Unimplemented: FT_ERROR(( "Unimplemented opcode: %d", ip[-1] )); if ( ip[-1] == 12 ) FT_ERROR(( " %d", ip[0] )); FT_ERROR(( "\n" )); return CFF_Err_Unimplemented_Feature; } decoder->top = args; } /* general operator processing */ } /* while ip < limit */ FT_TRACE4(( "..end..\n\n" )); Fail: return error; Syntax_Error: FT_TRACE4(( "cff_decoder_parse_charstrings: syntax error\n" )); return CFF_Err_Invalid_File_Format; Stack_Underflow: FT_TRACE4(( "cff_decoder_parse_charstrings: stack underflow\n" )); return CFF_Err_Too_Few_Arguments; Stack_Overflow: FT_TRACE4(( "cff_decoder_parse_charstrings: stack overflow\n" )); return CFF_Err_Stack_Overflow; }
[ "CWE-189" ]
savannah
7d3d2cc4fef72c6be9c454b3809c387e12b44cfc
78533740565488192289380822412773176149
178,180
269
This weakness involves numeric computation errors, such as integer overflows, underflows, or precision losses, which can lead to miscalculations and exploitable behaviors in software.
true
cff_decoder_parse_charstrings( CFF_Decoder* decoder, FT_Byte* charstring_base, FT_ULong charstring_len ) { FT_Error error; CFF_Decoder_Zone* zone; FT_Byte* ip; FT_Byte* limit; CFF_Builder* builder = &decoder->builder; FT_Pos x, y; FT_Fixed seed; FT_Fixed* stack; FT_Int charstring_type = decoder->cff->top_font.font_dict.charstring_type; T2_Hints_Funcs hinter; /* set default width */ decoder->num_hints = 0; decoder->read_width = 1; /* compute random seed from stack address of parameter */ seed = (FT_Fixed)( ( (FT_PtrDist)(char*)&seed ^ (FT_PtrDist)(char*)&decoder ^ (FT_PtrDist)(char*)&charstring_base ) & FT_ULONG_MAX ) ; seed = ( seed ^ ( seed >> 10 ) ^ ( seed >> 20 ) ) & 0xFFFFL; if ( seed == 0 ) seed = 0x7384; /* initialize the decoder */ decoder->top = decoder->stack; decoder->zone = decoder->zones; zone = decoder->zones; stack = decoder->top; hinter = (T2_Hints_Funcs)builder->hints_funcs; builder->path_begun = 0; zone->base = charstring_base; limit = zone->limit = charstring_base + charstring_len; ip = zone->cursor = zone->base; error = CFF_Err_Ok; x = builder->pos_x; y = builder->pos_y; /* begin hints recording session, if any */ if ( hinter ) hinter->open( hinter->hints ); /* now execute loop */ while ( ip < limit ) { CFF_Operator op; FT_Byte v; /********************************************************************/ /* */ /* Decode operator or operand */ /* */ v = *ip++; if ( v >= 32 || v == 28 ) { FT_Int shift = 16; FT_Int32 val; /* this is an operand, push it on the stack */ if ( v == 28 ) { if ( ip + 1 >= limit ) goto Syntax_Error; val = (FT_Short)( ( (FT_Short)ip[0] << 8 ) | ip[1] ); ip += 2; } else if ( v < 247 ) val = (FT_Int32)v - 139; else if ( v < 251 ) { if ( ip >= limit ) goto Syntax_Error; val = ( (FT_Int32)v - 247 ) * 256 + *ip++ + 108; } else if ( v < 255 ) { if ( ip >= limit ) goto Syntax_Error; val = -( (FT_Int32)v - 251 ) * 256 - *ip++ - 108; } else { if ( ip + 3 >= limit ) goto Syntax_Error; val = ( (FT_Int32)ip[0] << 24 ) | ( (FT_Int32)ip[1] << 16 ) | ( (FT_Int32)ip[2] << 8 ) | ip[3]; ip += 4; if ( charstring_type == 2 ) shift = 0; } if ( decoder->top - stack >= CFF_MAX_OPERANDS ) goto Stack_Overflow; val <<= shift; *decoder->top++ = val; #ifdef FT_DEBUG_LEVEL_TRACE if ( !( val & 0xFFFFL ) ) FT_TRACE4(( " %ld", (FT_Int32)( val >> 16 ) )); else FT_TRACE4(( " %.2f", val / 65536.0 )); #endif } else { /* The specification says that normally arguments are to be taken */ /* from the bottom of the stack. However, this seems not to be */ /* correct, at least for Acroread 7.0.8 on GNU/Linux: It pops the */ /* arguments similar to a PS interpreter. */ FT_Fixed* args = decoder->top; FT_Int num_args = (FT_Int)( args - decoder->stack ); FT_Int req_args; /* find operator */ op = cff_op_unknown; switch ( v ) { case 1: op = cff_op_hstem; break; case 3: op = cff_op_vstem; break; case 4: op = cff_op_vmoveto; break; case 5: op = cff_op_rlineto; break; case 6: op = cff_op_hlineto; break; case 7: op = cff_op_vlineto; break; case 8: op = cff_op_rrcurveto; break; case 9: op = cff_op_closepath; break; case 10: op = cff_op_callsubr; break; case 11: op = cff_op_return; break; case 12: { if ( ip >= limit ) goto Syntax_Error; v = *ip++; switch ( v ) { case 0: op = cff_op_dotsection; break; case 1: /* this is actually the Type1 vstem3 operator */ op = cff_op_vstem; break; case 2: /* this is actually the Type1 hstem3 operator */ op = cff_op_hstem; break; case 3: op = cff_op_and; break; case 4: op = cff_op_or; break; case 5: op = cff_op_not; break; case 6: op = cff_op_seac; break; case 7: op = cff_op_sbw; break; case 8: op = cff_op_store; break; case 9: op = cff_op_abs; break; case 10: op = cff_op_add; break; case 11: op = cff_op_sub; break; case 12: op = cff_op_div; break; case 13: op = cff_op_load; break; case 14: op = cff_op_neg; break; case 15: op = cff_op_eq; break; case 16: op = cff_op_callothersubr; break; case 17: op = cff_op_pop; break; case 18: op = cff_op_drop; break; case 20: op = cff_op_put; break; case 21: op = cff_op_get; break; case 22: op = cff_op_ifelse; break; case 23: op = cff_op_random; break; case 24: op = cff_op_mul; break; case 26: op = cff_op_sqrt; break; case 27: op = cff_op_dup; break; case 28: op = cff_op_exch; break; case 29: op = cff_op_index; break; case 30: op = cff_op_roll; break; case 33: op = cff_op_setcurrentpoint; break; case 34: op = cff_op_hflex; break; case 35: op = cff_op_flex; break; case 36: op = cff_op_hflex1; break; case 37: op = cff_op_flex1; break; default: /* decrement ip for syntax error message */ ip--; } } break; case 13: op = cff_op_hsbw; break; case 14: op = cff_op_endchar; break; case 16: op = cff_op_blend; break; case 18: op = cff_op_hstemhm; break; case 19: op = cff_op_hintmask; break; case 20: op = cff_op_cntrmask; break; case 21: op = cff_op_rmoveto; break; case 22: op = cff_op_hmoveto; break; case 23: op = cff_op_vstemhm; break; case 24: op = cff_op_rcurveline; break; case 25: op = cff_op_rlinecurve; break; case 26: op = cff_op_vvcurveto; break; case 27: op = cff_op_hhcurveto; break; case 29: op = cff_op_callgsubr; break; case 30: op = cff_op_vhcurveto; break; case 31: op = cff_op_hvcurveto; break; default: break; } if ( op == cff_op_unknown ) goto Syntax_Error; /* check arguments */ req_args = cff_argument_counts[op]; if ( req_args & CFF_COUNT_CHECK_WIDTH ) { if ( num_args > 0 && decoder->read_width ) { /* If `nominal_width' is non-zero, the number is really a */ /* difference against `nominal_width'. Else, the number here */ /* is truly a width, not a difference against `nominal_width'. */ /* If the font does not set `nominal_width', then */ /* `nominal_width' defaults to zero, and so we can set */ /* `glyph_width' to `nominal_width' plus number on the stack */ /* -- for either case. */ FT_Int set_width_ok; switch ( op ) { case cff_op_hmoveto: case cff_op_vmoveto: set_width_ok = num_args & 2; break; case cff_op_hstem: case cff_op_vstem: case cff_op_hstemhm: case cff_op_vstemhm: case cff_op_rmoveto: case cff_op_hintmask: case cff_op_cntrmask: set_width_ok = num_args & 1; break; case cff_op_endchar: /* If there is a width specified for endchar, we either have */ /* 1 argument or 5 arguments. We like to argue. */ set_width_ok = ( num_args == 5 ) || ( num_args == 1 ); break; default: set_width_ok = 0; break; } if ( set_width_ok ) { decoder->glyph_width = decoder->nominal_width + ( stack[0] >> 16 ); if ( decoder->width_only ) { /* we only want the advance width; stop here */ break; } /* Consumed an argument. */ num_args--; } } decoder->read_width = 0; req_args = 0; } req_args &= 0x000F; if ( num_args < req_args ) goto Stack_Underflow; args -= req_args; num_args -= req_args; /* At this point, `args' points to the first argument of the */ /* operand in case `req_args' isn't zero. Otherwise, we have */ /* to adjust `args' manually. */ /* Note that we only pop arguments from the stack which we */ /* really need and can digest so that we can continue in case */ /* of superfluous stack elements. */ switch ( op ) { case cff_op_hstem: case cff_op_vstem: case cff_op_hstemhm: case cff_op_vstemhm: /* the number of arguments is always even here */ FT_TRACE4(( op == cff_op_hstem ? " hstem\n" : ( op == cff_op_vstem ? " vstem\n" : ( op == cff_op_hstemhm ? " hstemhm\n" : " vstemhm\n" ) ) )); if ( hinter ) hinter->stems( hinter->hints, ( op == cff_op_hstem || op == cff_op_hstemhm ), num_args / 2, args - ( num_args & ~1 ) ); decoder->num_hints += num_args / 2; args = stack; break; case cff_op_hintmask: case cff_op_cntrmask: FT_TRACE4(( op == cff_op_hintmask ? " hintmask" : " cntrmask" )); /* implement vstem when needed -- */ /* the specification doesn't say it, but this also works */ /* with the 'cntrmask' operator */ /* */ if ( num_args > 0 ) { if ( hinter ) hinter->stems( hinter->hints, 0, num_args / 2, args - ( num_args & ~1 ) ); decoder->num_hints += num_args / 2; } if ( hinter ) { if ( op == cff_op_hintmask ) hinter->hintmask( hinter->hints, builder->current->n_points, decoder->num_hints, ip ); else hinter->counter( hinter->hints, decoder->num_hints, ip ); } #ifdef FT_DEBUG_LEVEL_TRACE { FT_UInt maskbyte; FT_TRACE4(( " (maskbytes: " )); for ( maskbyte = 0; maskbyte < (FT_UInt)(( decoder->num_hints + 7 ) >> 3); maskbyte++, ip++ ) FT_TRACE4(( "0x%02X", *ip )); FT_TRACE4(( ")\n" )); } #else ip += ( decoder->num_hints + 7 ) >> 3; #endif if ( ip >= limit ) goto Syntax_Error; args = stack; break; case cff_op_rmoveto: FT_TRACE4(( " rmoveto\n" )); cff_builder_close_contour( builder ); builder->path_begun = 0; x += args[-2]; y += args[-1]; args = stack; break; case cff_op_vmoveto: FT_TRACE4(( " vmoveto\n" )); cff_builder_close_contour( builder ); builder->path_begun = 0; y += args[-1]; args = stack; break; case cff_op_hmoveto: FT_TRACE4(( " hmoveto\n" )); cff_builder_close_contour( builder ); builder->path_begun = 0; x += args[-1]; args = stack; break; case cff_op_rlineto: FT_TRACE4(( " rlineto\n" )); if ( cff_builder_start_point ( builder, x, y ) || check_points( builder, num_args / 2 ) ) goto Fail; if ( num_args < 2 ) goto Stack_Underflow; args -= num_args & ~1; while ( args < decoder->top ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 1 ); args += 2; } args = stack; break; case cff_op_hlineto: case cff_op_vlineto: { FT_Int phase = ( op == cff_op_hlineto ); FT_TRACE4(( op == cff_op_hlineto ? " hlineto\n" : " vlineto\n" )); if ( num_args < 1 ) goto Stack_Underflow; if ( cff_builder_start_point ( builder, x, y ) || check_points( builder, num_args ) ) goto Fail; args = stack; while ( args < decoder->top ) { if ( phase ) x += args[0]; else y += args[0]; if ( cff_builder_add_point1( builder, x, y ) ) goto Fail; args++; phase ^= 1; } args = stack; } break; case cff_op_rrcurveto: { FT_Int nargs; FT_TRACE4(( " rrcurveto\n" )); if ( num_args < 6 ) goto Stack_Underflow; nargs = num_args - num_args % 6; if ( cff_builder_start_point ( builder, x, y ) || check_points( builder, nargs / 2 ) ) goto Fail; args -= nargs; while ( args < decoder->top ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); x += args[4]; y += args[5]; cff_builder_add_point( builder, x, y, 1 ); args += 6; } args = stack; } break; case cff_op_vvcurveto: { FT_Int nargs; FT_TRACE4(( " vvcurveto\n" )); if ( num_args < 4 ) goto Stack_Underflow; /* if num_args isn't of the form 4n or 4n+1, */ /* we reduce it to 4n+1 */ nargs = num_args - num_args % 4; if ( num_args - nargs > 0 ) nargs += 1; if ( cff_builder_start_point( builder, x, y ) ) goto Fail; args -= nargs; if ( nargs & 1 ) { x += args[0]; args++; nargs--; } if ( check_points( builder, 3 * ( nargs / 4 ) ) ) goto Fail; while ( args < decoder->top ) { y += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); y += args[3]; cff_builder_add_point( builder, x, y, 1 ); args += 4; } args = stack; } break; case cff_op_hhcurveto: { FT_Int nargs; FT_TRACE4(( " hhcurveto\n" )); if ( num_args < 4 ) goto Stack_Underflow; /* if num_args isn't of the form 4n or 4n+1, */ /* we reduce it to 4n+1 */ nargs = num_args - num_args % 4; if ( num_args - nargs > 0 ) nargs += 1; if ( cff_builder_start_point( builder, x, y ) ) goto Fail; args -= nargs; if ( nargs & 1 ) { y += args[0]; args++; nargs--; } if ( check_points( builder, 3 * ( nargs / 4 ) ) ) goto Fail; while ( args < decoder->top ) { x += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); x += args[3]; cff_builder_add_point( builder, x, y, 1 ); args += 4; } args = stack; } break; case cff_op_vhcurveto: case cff_op_hvcurveto: { FT_Int phase; FT_Int nargs; FT_TRACE4(( op == cff_op_vhcurveto ? " vhcurveto\n" : " hvcurveto\n" )); if ( cff_builder_start_point( builder, x, y ) ) goto Fail; if ( num_args < 4 ) goto Stack_Underflow; /* if num_args isn't of the form 8n, 8n+1, 8n+4, or 8n+5, */ /* we reduce it to the largest one which fits */ nargs = num_args - num_args % 4; if ( num_args - nargs > 0 ) nargs += 1; args -= nargs; if ( check_points( builder, ( nargs / 4 ) * 3 ) ) goto Stack_Underflow; phase = ( op == cff_op_hvcurveto ); while ( nargs >= 4 ) { nargs -= 4; if ( phase ) { x += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); y += args[3]; if ( nargs == 1 ) x += args[4]; cff_builder_add_point( builder, x, y, 1 ); } else { y += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); x += args[3]; if ( nargs == 1 ) y += args[4]; cff_builder_add_point( builder, x, y, 1 ); } args += 4; phase ^= 1; } args = stack; } break; case cff_op_rlinecurve: { FT_Int num_lines; FT_Int nargs; FT_TRACE4(( " rlinecurve\n" )); if ( num_args < 8 ) goto Stack_Underflow; nargs = num_args & ~1; num_lines = ( nargs - 6 ) / 2; if ( cff_builder_start_point( builder, x, y ) || check_points( builder, num_lines + 3 ) ) goto Fail; args -= nargs; /* first, add the line segments */ while ( num_lines > 0 ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 1 ); args += 2; num_lines--; } /* then the curve */ x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); x += args[4]; y += args[5]; cff_builder_add_point( builder, x, y, 1 ); args = stack; } break; case cff_op_rcurveline: { FT_Int num_curves; FT_Int nargs; FT_TRACE4(( " rcurveline\n" )); if ( num_args < 8 ) goto Stack_Underflow; nargs = num_args - 2; nargs = nargs - nargs % 6 + 2; num_curves = ( nargs - 2 ) / 6; if ( cff_builder_start_point ( builder, x, y ) || check_points( builder, num_curves * 3 + 2 ) ) goto Fail; args -= nargs; /* first, add the curves */ while ( num_curves > 0 ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); x += args[4]; y += args[5]; cff_builder_add_point( builder, x, y, 1 ); args += 6; num_curves--; } /* then the final line */ x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 1 ); args = stack; } break; case cff_op_hflex1: { FT_Pos start_y; FT_TRACE4(( " hflex1\n" )); /* adding five more points: 4 control points, 1 on-curve point */ /* -- make sure we have enough space for the start point if it */ /* needs to be added */ if ( cff_builder_start_point( builder, x, y ) || check_points( builder, 6 ) ) goto Fail; /* record the starting point's y position for later use */ start_y = y; /* first control point */ x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); /* second control point */ x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); /* join point; on curve, with y-value the same as the last */ /* control point's y-value */ x += args[4]; cff_builder_add_point( builder, x, y, 1 ); /* third control point, with y-value the same as the join */ /* point's y-value */ x += args[5]; cff_builder_add_point( builder, x, y, 0 ); /* fourth control point */ x += args[6]; y += args[7]; cff_builder_add_point( builder, x, y, 0 ); /* ending point, with y-value the same as the start */ x += args[8]; y = start_y; cff_builder_add_point( builder, x, y, 1 ); args = stack; break; } case cff_op_hflex: { FT_Pos start_y; FT_TRACE4(( " hflex\n" )); /* adding six more points; 4 control points, 2 on-curve points */ if ( cff_builder_start_point( builder, x, y ) || check_points( builder, 6 ) ) goto Fail; /* record the starting point's y-position for later use */ start_y = y; /* first control point */ x += args[0]; cff_builder_add_point( builder, x, y, 0 ); /* second control point */ x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); /* join point; on curve, with y-value the same as the last */ /* control point's y-value */ x += args[3]; cff_builder_add_point( builder, x, y, 1 ); /* third control point, with y-value the same as the join */ /* point's y-value */ x += args[4]; cff_builder_add_point( builder, x, y, 0 ); /* fourth control point */ x += args[5]; y = start_y; cff_builder_add_point( builder, x, y, 0 ); /* ending point, with y-value the same as the start point's */ /* y-value -- we don't add this point, though */ x += args[6]; cff_builder_add_point( builder, x, y, 1 ); args = stack; break; } case cff_op_flex1: { FT_Pos start_x, start_y; /* record start x, y values for */ /* alter use */ FT_Fixed dx = 0, dy = 0; /* used in horizontal/vertical */ /* algorithm below */ FT_Int horizontal, count; FT_Fixed* temp; FT_TRACE4(( " flex1\n" )); /* adding six more points; 4 control points, 2 on-curve points */ if ( cff_builder_start_point( builder, x, y ) || check_points( builder, 6 ) ) goto Fail; /* record the starting point's x, y position for later use */ start_x = x; start_y = y; /* XXX: figure out whether this is supposed to be a horizontal */ /* or vertical flex; the Type 2 specification is vague... */ temp = args; /* grab up to the last argument */ for ( count = 5; count > 0; count-- ) { dx += temp[0]; dy += temp[1]; temp += 2; } if ( dx < 0 ) dx = -dx; if ( dy < 0 ) dy = -dy; /* strange test, but here it is... */ horizontal = ( dx > dy ); for ( count = 5; count > 0; count-- ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, (FT_Bool)( count == 3 ) ); args += 2; } /* is last operand an x- or y-delta? */ if ( horizontal ) { x += args[0]; y = start_y; } else { x = start_x; y += args[0]; } cff_builder_add_point( builder, x, y, 1 ); args = stack; break; } case cff_op_flex: { FT_UInt count; FT_TRACE4(( " flex\n" )); if ( cff_builder_start_point( builder, x, y ) || check_points( builder, 6 ) ) goto Fail; for ( count = 6; count > 0; count-- ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, (FT_Bool)( count == 4 || count == 1 ) ); args += 2; } args = stack; } break; case cff_op_seac: FT_TRACE4(( " seac\n" )); error = cff_operator_seac( decoder, args[0], args[1], args[2], (FT_Int)( args[3] >> 16 ), (FT_Int)( args[4] >> 16 ) ); /* add current outline to the glyph slot */ FT_GlyphLoader_Add( builder->loader ); /* return now! */ FT_TRACE4(( "\n" )); return error; case cff_op_endchar: FT_TRACE4(( " endchar\n" )); /* We are going to emulate the seac operator. */ if ( num_args >= 4 ) { /* Save glyph width so that the subglyphs don't overwrite it. */ FT_Pos glyph_width = decoder->glyph_width; error = cff_operator_seac( decoder, 0L, args[-4], args[-3], (FT_Int)( args[-2] >> 16 ), (FT_Int)( args[-1] >> 16 ) ); decoder->glyph_width = glyph_width; } else { if ( !error ) error = CFF_Err_Ok; cff_builder_close_contour( builder ); /* close hints recording session */ if ( hinter ) { if ( hinter->close( hinter->hints, builder->current->n_points ) ) goto Syntax_Error; /* apply hints to the loaded glyph outline now */ hinter->apply( hinter->hints, builder->current, (PSH_Globals)builder->hints_globals, decoder->hint_mode ); } /* add current outline to the glyph slot */ FT_GlyphLoader_Add( builder->loader ); } /* return now! */ FT_TRACE4(( "\n" )); return error; case cff_op_abs: FT_TRACE4(( " abs\n" )); if ( args[0] < 0 ) args[0] = -args[0]; args++; break; case cff_op_add: FT_TRACE4(( " add\n" )); args[0] += args[1]; args++; break; case cff_op_sub: FT_TRACE4(( " sub\n" )); args[0] -= args[1]; args++; break; case cff_op_div: FT_TRACE4(( " div\n" )); args[0] = FT_DivFix( args[0], args[1] ); args++; break; case cff_op_neg: FT_TRACE4(( " neg\n" )); args[0] = -args[0]; args++; break; case cff_op_random: { FT_Fixed Rand; FT_TRACE4(( " rand\n" )); Rand = seed; if ( Rand >= 0x8000L ) Rand++; args[0] = Rand; seed = FT_MulFix( seed, 0x10000L - seed ); if ( seed == 0 ) seed += 0x2873; args++; } break; case cff_op_mul: FT_TRACE4(( " mul\n" )); args[0] = FT_MulFix( args[0], args[1] ); args++; break; case cff_op_sqrt: FT_TRACE4(( " sqrt\n" )); if ( args[0] > 0 ) { FT_Int count = 9; FT_Fixed root = args[0]; FT_Fixed new_root; for (;;) { new_root = ( root + FT_DivFix( args[0], root ) + 1 ) >> 1; if ( new_root == root || count <= 0 ) break; root = new_root; } args[0] = new_root; } else args[0] = 0; args++; break; case cff_op_drop: /* nothing */ FT_TRACE4(( " drop\n" )); break; case cff_op_exch: { FT_Fixed tmp; FT_TRACE4(( " exch\n" )); tmp = args[0]; args[0] = args[1]; args[1] = tmp; args += 2; } break; case cff_op_index: { FT_Int idx = (FT_Int)( args[0] >> 16 ); FT_TRACE4(( " index\n" )); if ( idx < 0 ) idx = 0; else if ( idx > num_args - 2 ) idx = num_args - 2; args[0] = args[-( idx + 1 )]; args++; } break; case cff_op_roll: { FT_Int count = (FT_Int)( args[0] >> 16 ); FT_Int idx = (FT_Int)( args[1] >> 16 ); FT_TRACE4(( " roll\n" )); if ( count <= 0 ) count = 1; args -= count; if ( args < stack ) goto Stack_Underflow; if ( idx >= 0 ) { while ( idx > 0 ) { FT_Fixed tmp = args[count - 1]; FT_Int i; for ( i = count - 2; i >= 0; i-- ) args[i + 1] = args[i]; args[0] = tmp; idx--; } } else { while ( idx < 0 ) { FT_Fixed tmp = args[0]; FT_Int i; for ( i = 0; i < count - 1; i++ ) args[i] = args[i + 1]; args[count - 1] = tmp; idx++; } } args += count; } break; case cff_op_dup: FT_TRACE4(( " dup\n" )); args[1] = args[0]; args += 2; break; case cff_op_put: { FT_Fixed val = args[0]; FT_Int idx = (FT_Int)( args[1] >> 16 ); FT_TRACE4(( " put\n" )); if ( idx >= 0 && idx < CFF_MAX_TRANS_ELEMENTS ) decoder->buildchar[idx] = val; } break; case cff_op_get: { FT_Int idx = (FT_Int)( args[0] >> 16 ); FT_Fixed val = 0; FT_TRACE4(( " get\n" )); if ( idx >= 0 && idx < CFF_MAX_TRANS_ELEMENTS ) val = decoder->buildchar[idx]; args[0] = val; args++; } break; case cff_op_store: FT_TRACE4(( " store\n")); goto Unimplemented; case cff_op_load: FT_TRACE4(( " load\n" )); goto Unimplemented; case cff_op_dotsection: /* this operator is deprecated and ignored by the parser */ FT_TRACE4(( " dotsection\n" )); break; case cff_op_closepath: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " closepath (invalid op)\n" )); args = stack; break; case cff_op_hsbw: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " hsbw (invalid op)\n" )); decoder->glyph_width = decoder->nominal_width + ( args[1] >> 16 ); decoder->builder.left_bearing.x = args[0]; decoder->builder.left_bearing.y = 0; x = decoder->builder.pos_x + args[0]; y = decoder->builder.pos_y; args = stack; break; case cff_op_sbw: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " sbw (invalid op)\n" )); decoder->glyph_width = decoder->nominal_width + ( args[2] >> 16 ); decoder->builder.left_bearing.x = args[0]; decoder->builder.left_bearing.y = args[1]; x = decoder->builder.pos_x + args[0]; y = decoder->builder.pos_y + args[1]; args = stack; break; case cff_op_setcurrentpoint: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " setcurrentpoint (invalid op)\n" )); x = decoder->builder.pos_x + args[0]; y = decoder->builder.pos_y + args[1]; args = stack; break; case cff_op_callothersubr: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " callothersubr (invalid op)\n" )); /* subsequent `pop' operands should add the arguments, */ /* this is the implementation described for `unknown' other */ /* subroutines in the Type1 spec. */ args -= 2 + ( args[-2] >> 16 ); if ( args < stack ) goto Stack_Underflow; break; case cff_op_pop: /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( " pop (invalid op)\n" )); args++; break; case cff_op_and: { FT_Fixed cond = args[0] && args[1]; FT_TRACE4(( " and\n" )); args[0] = cond ? 0x10000L : 0; args++; } break; case cff_op_or: { FT_Fixed cond = args[0] || args[1]; FT_TRACE4(( " or\n" )); args[0] = cond ? 0x10000L : 0; args++; } break; case cff_op_eq: { FT_Fixed cond = !args[0]; FT_TRACE4(( " eq\n" )); args[0] = cond ? 0x10000L : 0; args++; } break; case cff_op_ifelse: { FT_Fixed cond = ( args[2] <= args[3] ); FT_TRACE4(( " ifelse\n" )); if ( !cond ) args[0] = args[1]; args++; } break; case cff_op_callsubr: { FT_UInt idx = (FT_UInt)( ( args[0] >> 16 ) + decoder->locals_bias ); FT_TRACE4(( " callsubr(%d)\n", idx )); if ( idx >= decoder->num_locals ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " invalid local subr index\n" )); goto Syntax_Error; } if ( zone - decoder->zones >= CFF_MAX_SUBRS_CALLS ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " too many nested subrs\n" )); goto Syntax_Error; } zone->cursor = ip; /* save current instruction pointer */ zone++; zone->base = decoder->locals[idx]; zone->limit = decoder->locals[idx + 1]; zone->cursor = zone->base; if ( !zone->base || zone->limit == zone->base ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " invoking empty subrs\n" )); goto Syntax_Error; } decoder->zone = zone; ip = zone->base; limit = zone->limit; } break; case cff_op_callgsubr: { FT_UInt idx = (FT_UInt)( ( args[0] >> 16 ) + decoder->globals_bias ); FT_TRACE4(( " callgsubr(%d)\n", idx )); if ( idx >= decoder->num_globals ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " invalid global subr index\n" )); goto Syntax_Error; } if ( zone - decoder->zones >= CFF_MAX_SUBRS_CALLS ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " too many nested subrs\n" )); goto Syntax_Error; } zone->cursor = ip; /* save current instruction pointer */ zone++; zone->base = decoder->globals[idx]; zone->limit = decoder->globals[idx + 1]; zone->cursor = zone->base; if ( !zone->base || zone->limit == zone->base ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " invoking empty subrs\n" )); goto Syntax_Error; } decoder->zone = zone; ip = zone->base; limit = zone->limit; } break; case cff_op_return: FT_TRACE4(( " return\n" )); if ( decoder->zone <= decoder->zones ) { FT_ERROR(( "cff_decoder_parse_charstrings:" " unexpected return\n" )); goto Syntax_Error; } decoder->zone--; zone = decoder->zone; ip = zone->cursor; limit = zone->limit; break; default: Unimplemented: FT_ERROR(( "Unimplemented opcode: %d", ip[-1] )); if ( ip[-1] == 12 ) FT_ERROR(( " %d", ip[0] )); FT_ERROR(( "\n" )); return CFF_Err_Unimplemented_Feature; } decoder->top = args; } /* general operator processing */ } /* while ip < limit */ FT_TRACE4(( "..end..\n\n" )); Fail: return error; Syntax_Error: FT_TRACE4(( "cff_decoder_parse_charstrings: syntax error\n" )); return CFF_Err_Invalid_File_Format; Stack_Underflow: FT_TRACE4(( "cff_decoder_parse_charstrings: stack underflow\n" )); return CFF_Err_Too_Few_Arguments; Stack_Overflow: FT_TRACE4(( "cff_decoder_parse_charstrings: stack overflow\n" )); return CFF_Err_Stack_Overflow; }
[ "CWE-189" ]
savannah
7d3d2cc4fef72c6be9c454b3809c387e12b44cfc
338965105723107567424020450442881213658
178,180
158,128
This weakness involves numeric computation errors, such as integer overflows, underflows, or precision losses, which can lead to miscalculations and exploitable behaviors in software.
false
XvQueryAdaptors( Display *dpy, Window window, unsigned int *p_nAdaptors, XvAdaptorInfo **p_pAdaptors) { XExtDisplayInfo *info = xv_find_display(dpy); xvQueryAdaptorsReq *req; xvQueryAdaptorsReply rep; size_t size; unsigned int ii, jj; char *name; XvAdaptorInfo *pas = NULL, *pa; XvFormat *pfs, *pf; char *buffer = NULL; char *buffer; char *string; xvAdaptorInfo *pa; xvFormat *pf; } u;
[ "CWE-125" ]
libXv
d9da580b46a28ab497de2e94fdc7b9ff953dab17
25138831966304988672154482243921916552
178,181
270
The product reads data past the end, or before the beginning, of the intended buffer.
true
XvQueryAdaptors( Display *dpy, Window window, unsigned int *p_nAdaptors, XvAdaptorInfo **p_pAdaptors) { XExtDisplayInfo *info = xv_find_display(dpy); xvQueryAdaptorsReq *req; xvQueryAdaptorsReply rep; size_t size; unsigned int ii, jj; char *name; char *end; XvAdaptorInfo *pas = NULL, *pa; XvFormat *pfs, *pf; char *buffer = NULL; char *buffer; char *string; xvAdaptorInfo *pa; xvFormat *pf; } u;
[ "CWE-125" ]
libXv
d9da580b46a28ab497de2e94fdc7b9ff953dab17
13775494404515584781393413951208073381
178,181
158,129
The product reads data past the end, or before the beginning, of the intended buffer.
false
intuit_diff_type (bool need_header, mode_t *p_file_type) { file_offset this_line = 0; file_offset first_command_line = -1; char first_ed_command_letter = 0; lin fcl_line = 0; /* Pacify 'gcc -W'. */ bool this_is_a_command = false; bool stars_this_line = false; bool extended_headers = false; enum nametype i; struct stat st[3]; int stat_errno[3]; int version_controlled[3]; enum diff retval; mode_t file_type; size_t indent = 0; for (i = OLD; i <= INDEX; i++) if (p_name[i]) { free (p_name[i]); p_name[i] = 0; } for (i = 0; i < ARRAY_SIZE (invalid_names); i++) invalid_names[i] = NULL; for (i = OLD; i <= NEW; i++) if (p_timestr[i]) { free(p_timestr[i]); p_timestr[i] = 0; } for (i = OLD; i <= NEW; i++) if (p_sha1[i]) { free (p_sha1[i]); p_sha1[i] = 0; } p_git_diff = false; for (i = OLD; i <= NEW; i++) { p_mode[i] = 0; p_copy[i] = false; p_rename[i] = false; } /* Ed and normal format patches don't have filename headers. */ if (diff_type == ED_DIFF || diff_type == NORMAL_DIFF) need_header = false; version_controlled[OLD] = -1; version_controlled[NEW] = -1; version_controlled[INDEX] = -1; p_rfc934_nesting = 0; p_timestamp[OLD].tv_sec = p_timestamp[NEW].tv_sec = -1; p_says_nonexistent[OLD] = p_says_nonexistent[NEW] = 0; Fseek (pfp, p_base, SEEK_SET); p_input_line = p_bline - 1; for (;;) { char *s; char *t; file_offset previous_line = this_line; bool last_line_was_command = this_is_a_command; bool stars_last_line = stars_this_line; size_t indent_last_line = indent; char ed_command_letter; bool strip_trailing_cr; size_t chars_read; indent = 0; this_line = file_tell (pfp); chars_read = pget_line (0, 0, false, false); if (chars_read == (size_t) -1) xalloc_die (); if (! chars_read) { if (first_ed_command_letter) { /* nothing but deletes!? */ p_start = first_command_line; p_sline = fcl_line; retval = ED_DIFF; goto scan_exit; } else { p_start = this_line; p_sline = p_input_line; if (extended_headers) { /* Patch contains no hunks; any diff type will do. */ retval = UNI_DIFF; goto scan_exit; } return NO_DIFF; } } strip_trailing_cr = 2 <= chars_read && buf[chars_read - 2] == '\r'; for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) { if (*s == '\t') indent = (indent + 8) & ~7; else indent++; } if (ISDIGIT (*s)) { for (t = s + 1; ISDIGIT (*t) || *t == ','; t++) /* do nothing */ ; if (*t == 'd' || *t == 'c' || *t == 'a') { for (t++; ISDIGIT (*t) || *t == ','; t++) /* do nothing */ ; for (; *t == ' ' || *t == '\t'; t++) /* do nothing */ ; if (*t == '\r') t++; this_is_a_command = (*t == '\n'); } } if (! need_header && first_command_line < 0 && ((ed_command_letter = get_ed_command_letter (s)) || this_is_a_command)) { first_command_line = this_line; first_ed_command_letter = ed_command_letter; fcl_line = p_input_line; p_indent = indent; /* assume this for now */ p_strip_trailing_cr = strip_trailing_cr; } if (!stars_last_line && strnEQ(s, "*** ", 4)) { fetchname (s+4, strippath, &p_name[OLD], &p_timestr[OLD], &p_timestamp[OLD]); need_header = false; } else if (strnEQ(s, "+++ ", 4)) { /* Swap with NEW below. */ fetchname (s+4, strippath, &p_name[OLD], &p_timestr[OLD], &p_timestamp[OLD]); need_header = false; p_strip_trailing_cr = strip_trailing_cr; } else if (strnEQ(s, "Index:", 6)) { fetchname (s+6, strippath, &p_name[INDEX], (char **) 0, NULL); need_header = false; p_strip_trailing_cr = strip_trailing_cr; } else if (strnEQ(s, "Prereq:", 7)) { for (t = s + 7; ISSPACE ((unsigned char) *t); t++) /* do nothing */ ; revision = t; for (t = revision; *t; t++) if (ISSPACE ((unsigned char) *t)) { char const *u; for (u = t + 1; ISSPACE ((unsigned char) *u); u++) /* do nothing */ ; if (*u) { char numbuf[LINENUM_LENGTH_BOUND + 1]; say ("Prereq: with multiple words at line %s of patch\n", format_linenum (numbuf, this_line)); } break; } if (t == revision) revision = 0; else { char oldc = *t; *t = '\0'; revision = xstrdup (revision); *t = oldc; } } else if (strnEQ (s, "diff --git ", 11)) { char const *u; if (extended_headers) { p_start = this_line; p_sline = p_input_line; /* Patch contains no hunks; any diff type will do. */ retval = UNI_DIFF; goto scan_exit; } for (i = OLD; i <= NEW; i++) { free (p_name[i]); p_name[i] = 0; } if (! ((p_name[OLD] = parse_name (s + 11, strippath, &u)) && ISSPACE ((unsigned char) *u) && (p_name[NEW] = parse_name (u, strippath, &u)) && (u = skip_spaces (u), ! *u))) for (i = OLD; i <= NEW; i++) { free (p_name[i]); p_name[i] = 0; } p_git_diff = true; need_header = false; } else if (p_git_diff && strnEQ (s, "index ", 6)) { char const *u, *v; if ((u = skip_hex_digits (s + 6)) && u[0] == '.' && u[1] == '.' && (v = skip_hex_digits (u + 2)) && (! *v || ISSPACE ((unsigned char) *v))) { get_sha1(&p_sha1[OLD], s + 6, u); get_sha1(&p_sha1[NEW], u + 2, v); p_says_nonexistent[OLD] = sha1_says_nonexistent (p_sha1[OLD]); p_says_nonexistent[NEW] = sha1_says_nonexistent (p_sha1[NEW]); if (*(v = skip_spaces (v))) p_mode[OLD] = p_mode[NEW] = fetchmode (v); extended_headers = true; } } else if (p_git_diff && strnEQ (s, "old mode ", 9)) { p_mode[OLD] = fetchmode (s + 9); extended_headers = true; } else if (p_git_diff && strnEQ (s, "new mode ", 9)) { p_mode[NEW] = fetchmode (s + 9); extended_headers = true; } else if (p_git_diff && strnEQ (s, "deleted file mode ", 18)) { p_mode[OLD] = fetchmode (s + 18); p_says_nonexistent[NEW] = 2; extended_headers = true; } else if (p_git_diff && strnEQ (s, "new file mode ", 14)) { p_mode[NEW] = fetchmode (s + 14); p_says_nonexistent[OLD] = 2; extended_headers = true; } else if (p_git_diff && strnEQ (s, "rename from ", 12)) { /* Git leaves out the prefix in the file name in this header, so we can only ignore the file name. */ p_rename[OLD] = true; extended_headers = true; } else if (p_git_diff && strnEQ (s, "rename to ", 10)) { /* Git leaves out the prefix in the file name in this header, so we can only ignore the file name. */ p_rename[NEW] = true; extended_headers = true; } else if (p_git_diff && strnEQ (s, "copy from ", 10)) { /* Git leaves out the prefix in the file name in this header, so we can only ignore the file name. */ p_copy[OLD] = true; extended_headers = true; } else if (p_git_diff && strnEQ (s, "copy to ", 8)) { /* Git leaves out the prefix in the file name in this header, so we can only ignore the file name. */ p_copy[NEW] = true; extended_headers = true; } else if (p_git_diff && strnEQ (s, "GIT binary patch", 16)) { p_start = this_line; p_sline = p_input_line; retval = GIT_BINARY_DIFF; goto scan_exit; } else { for (t = s; t[0] == '-' && t[1] == ' '; t += 2) /* do nothing */ ; if (strnEQ(t, "--- ", 4)) { struct timespec timestamp; timestamp.tv_sec = -1; fetchname (t+4, strippath, &p_name[NEW], &p_timestr[NEW], &timestamp); need_header = false; if (timestamp.tv_sec != -1) { p_timestamp[NEW] = timestamp; p_rfc934_nesting = (t - s) >> 1; } p_strip_trailing_cr = strip_trailing_cr; } } if (need_header) continue; if ((diff_type == NO_DIFF || diff_type == ED_DIFF) && first_command_line >= 0 && strEQ(s, ".\n") ) { p_start = first_command_line; p_sline = fcl_line; retval = ED_DIFF; goto scan_exit; } if ((diff_type == NO_DIFF || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) { /* 'p_name', 'p_timestr', and 'p_timestamp' are backwards; swap them. */ struct timespec ti = p_timestamp[OLD]; p_timestamp[OLD] = p_timestamp[NEW]; p_timestamp[NEW] = ti; t = p_name[OLD]; p_name[OLD] = p_name[NEW]; p_name[NEW] = t; t = p_timestr[OLD]; p_timestr[OLD] = p_timestr[NEW]; p_timestr[NEW] = t; s += 4; if (s[0] == '0' && !ISDIGIT (s[1])) p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD].tv_sec; while (*s != ' ' && *s != '\n') s++; while (*s == ' ') s++; if (s[0] == '+' && s[1] == '0' && !ISDIGIT (s[2])) p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW].tv_sec; p_indent = indent; p_start = this_line; p_sline = p_input_line; retval = UNI_DIFF; if (! ((p_name[OLD] || ! p_timestamp[OLD].tv_sec) && (p_name[NEW] || ! p_timestamp[NEW].tv_sec)) && ! p_name[INDEX] && need_header) { char numbuf[LINENUM_LENGTH_BOUND + 1]; say ("missing header for unified diff at line %s of patch\n", format_linenum (numbuf, p_sline)); } goto scan_exit; } stars_this_line = strnEQ(s, "********", 8); if ((diff_type == NO_DIFF || diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) && stars_last_line && indent_last_line == indent && strnEQ (s, "*** ", 4)) { s += 4; if (s[0] == '0' && !ISDIGIT (s[1])) p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD].tv_sec; /* if this is a new context diff the character just before */ /* the newline is a '*'. */ while (*s != '\n') s++; p_indent = indent; p_strip_trailing_cr = strip_trailing_cr; p_start = previous_line; p_sline = p_input_line - 1; retval = (*(s-1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF); { /* Scan the first hunk to see whether the file contents appear to have been deleted. */ file_offset saved_p_base = p_base; lin saved_p_bline = p_bline; Fseek (pfp, previous_line, SEEK_SET); p_input_line -= 2; if (another_hunk (retval, false) && ! p_repl_lines && p_newfirst == 1) p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW].tv_sec; next_intuit_at (saved_p_base, saved_p_bline); } if (! ((p_name[OLD] || ! p_timestamp[OLD].tv_sec) && (p_name[NEW] || ! p_timestamp[NEW].tv_sec)) && ! p_name[INDEX] && need_header) { char numbuf[LINENUM_LENGTH_BOUND + 1]; say ("missing header for context diff at line %s of patch\n", format_linenum (numbuf, p_sline)); } goto scan_exit; } if ((diff_type == NO_DIFF || diff_type == NORMAL_DIFF) && last_line_was_command && (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2)) ) { p_start = previous_line; p_sline = p_input_line - 1; p_indent = indent; retval = NORMAL_DIFF; goto scan_exit; } } scan_exit: /* The old, new, or old and new file types may be defined. When both file types are defined, make sure they are the same, or else assume we do not know the file type. */ file_type = p_mode[OLD] & S_IFMT; if (file_type) { mode_t new_file_type = p_mode[NEW] & S_IFMT; if (new_file_type && file_type != new_file_type) file_type = 0; } else { file_type = p_mode[NEW] & S_IFMT; if (! file_type) file_type = S_IFREG; } *p_file_type = file_type; /* To intuit 'inname', the name of the file to patch, use the algorithm specified by POSIX 1003.1-2001 XCU lines 25680-26599 (with some modifications if posixly_correct is zero): - Take the old and new names from the context header if present, and take the index name from the 'Index:' line if present and if either the old and new names are both absent or posixly_correct is nonzero. Consider the file names to be in the order (old, new, index). - If some named files exist, use the first one if posixly_correct is nonzero, the best one otherwise. - If patch_get is nonzero, and no named files exist, but an RCS or SCCS master file exists, use the first named file with an RCS or SCCS master. - If no named files exist, no RCS or SCCS master was found, some names are given, posixly_correct is zero, and the patch appears to create a file, then use the best name requiring the creation of the fewest directories. - Otherwise, report failure by setting 'inname' to 0; this causes our invoker to ask the user for a file name. */ i = NONE; if (!inname) { enum nametype i0 = NONE; if (! posixly_correct && (p_name[OLD] || p_name[NEW]) && p_name[INDEX]) { free (p_name[INDEX]); p_name[INDEX] = 0; } for (i = OLD; i <= INDEX; i++) if (p_name[i]) { if (i0 != NONE && strcmp (p_name[i0], p_name[i]) == 0) { /* It's the same name as before; reuse stat results. */ stat_errno[i] = stat_errno[i0]; if (! stat_errno[i]) st[i] = st[i0]; } else { stat_errno[i] = stat_file (p_name[i], &st[i]); if (! stat_errno[i]) { if (lookup_file_id (&st[i]) == DELETE_LATER) stat_errno[i] = ENOENT; else if (posixly_correct && name_is_valid (p_name[i])) break; } } i0 = i; } if (! posixly_correct) { /* The best of all existing files. */ i = best_name (p_name, stat_errno); if (i == NONE && patch_get) { enum nametype nope = NONE; for (i = OLD; i <= INDEX; i++) if (p_name[i]) { char const *cs; char *getbuf; char *diffbuf; bool readonly = (outfile && strcmp (outfile, p_name[i]) != 0); if (nope == NONE || strcmp (p_name[nope], p_name[i]) != 0) { cs = (version_controller (p_name[i], readonly, (struct stat *) 0, &getbuf, &diffbuf)); version_controlled[i] = !! cs; if (cs) { if (version_get (p_name[i], cs, false, readonly, getbuf, &st[i])) stat_errno[i] = 0; else version_controlled[i] = 0; free (getbuf); free (diffbuf); if (! stat_errno[i]) break; } } nope = i; } } if (i0 != NONE && (i == NONE || (st[i].st_mode & S_IFMT) == file_type) && maybe_reverse (p_name[i == NONE ? i0 : i], i == NONE, i == NONE || st[i].st_size == 0) && i == NONE) i = i0; if (i == NONE && p_says_nonexistent[reverse]) { int newdirs[3]; int newdirs_min = INT_MAX; int distance_from_minimum[3]; for (i = OLD; i <= INDEX; i++) if (p_name[i]) { newdirs[i] = (prefix_components (p_name[i], false) - prefix_components (p_name[i], true)); if (newdirs[i] < newdirs_min) newdirs_min = newdirs[i]; } for (i = OLD; i <= INDEX; i++) if (p_name[i]) distance_from_minimum[i] = newdirs[i] - newdirs_min; /* The best of the filenames which create the fewest directories. */ i = best_name (p_name, distance_from_minimum); } } } if ((pch_rename () || pch_copy ()) && ! inname && ! ((i == OLD || i == NEW) && p_name[! reverse] && name_is_valid (p_name[! reverse]))) { say ("Cannot %s file without two valid file names\n", pch_rename () ? "rename" : "copy"); } if (i == NONE) { if (inname) { inerrno = stat_file (inname, &instat); if (inerrno || (instat.st_mode & S_IFMT) == file_type) maybe_reverse (inname, inerrno, inerrno || instat.st_size == 0); } else inerrno = -1; } else { inname = xstrdup (p_name[i]); inerrno = stat_errno[i]; invc = version_controlled[i]; instat = st[i]; } return retval; }
[ "CWE-476" ]
savannah
f290f48a621867084884bfff87f8093c15195e6a
119977677141531301071259218660699705481
178,192
274
The product dereferences a pointer that it expects to be valid but is NULL.
true
intuit_diff_type (bool need_header, mode_t *p_file_type) { file_offset this_line = 0; file_offset first_command_line = -1; char first_ed_command_letter = 0; lin fcl_line = 0; /* Pacify 'gcc -W'. */ bool this_is_a_command = false; bool stars_this_line = false; bool extended_headers = false; enum nametype i; struct stat st[3]; int stat_errno[3]; int version_controlled[3]; enum diff retval; mode_t file_type; size_t indent = 0; for (i = OLD; i <= INDEX; i++) if (p_name[i]) { free (p_name[i]); p_name[i] = 0; } for (i = 0; i < ARRAY_SIZE (invalid_names); i++) invalid_names[i] = NULL; for (i = OLD; i <= NEW; i++) if (p_timestr[i]) { free(p_timestr[i]); p_timestr[i] = 0; } for (i = OLD; i <= NEW; i++) if (p_sha1[i]) { free (p_sha1[i]); p_sha1[i] = 0; } p_git_diff = false; for (i = OLD; i <= NEW; i++) { p_mode[i] = 0; p_copy[i] = false; p_rename[i] = false; } /* Ed and normal format patches don't have filename headers. */ if (diff_type == ED_DIFF || diff_type == NORMAL_DIFF) need_header = false; version_controlled[OLD] = -1; version_controlled[NEW] = -1; version_controlled[INDEX] = -1; p_rfc934_nesting = 0; p_timestamp[OLD].tv_sec = p_timestamp[NEW].tv_sec = -1; p_says_nonexistent[OLD] = p_says_nonexistent[NEW] = 0; Fseek (pfp, p_base, SEEK_SET); p_input_line = p_bline - 1; for (;;) { char *s; char *t; file_offset previous_line = this_line; bool last_line_was_command = this_is_a_command; bool stars_last_line = stars_this_line; size_t indent_last_line = indent; char ed_command_letter; bool strip_trailing_cr; size_t chars_read; indent = 0; this_line = file_tell (pfp); chars_read = pget_line (0, 0, false, false); if (chars_read == (size_t) -1) xalloc_die (); if (! chars_read) { if (first_ed_command_letter) { /* nothing but deletes!? */ p_start = first_command_line; p_sline = fcl_line; retval = ED_DIFF; goto scan_exit; } else { p_start = this_line; p_sline = p_input_line; if (extended_headers) { /* Patch contains no hunks; any diff type will do. */ retval = UNI_DIFF; goto scan_exit; } return NO_DIFF; } } strip_trailing_cr = 2 <= chars_read && buf[chars_read - 2] == '\r'; for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) { if (*s == '\t') indent = (indent + 8) & ~7; else indent++; } if (ISDIGIT (*s)) { for (t = s + 1; ISDIGIT (*t) || *t == ','; t++) /* do nothing */ ; if (*t == 'd' || *t == 'c' || *t == 'a') { for (t++; ISDIGIT (*t) || *t == ','; t++) /* do nothing */ ; for (; *t == ' ' || *t == '\t'; t++) /* do nothing */ ; if (*t == '\r') t++; this_is_a_command = (*t == '\n'); } } if (! need_header && first_command_line < 0 && ((ed_command_letter = get_ed_command_letter (s)) || this_is_a_command)) { first_command_line = this_line; first_ed_command_letter = ed_command_letter; fcl_line = p_input_line; p_indent = indent; /* assume this for now */ p_strip_trailing_cr = strip_trailing_cr; } if (!stars_last_line && strnEQ(s, "*** ", 4)) { fetchname (s+4, strippath, &p_name[OLD], &p_timestr[OLD], &p_timestamp[OLD]); need_header = false; } else if (strnEQ(s, "+++ ", 4)) { /* Swap with NEW below. */ fetchname (s+4, strippath, &p_name[OLD], &p_timestr[OLD], &p_timestamp[OLD]); need_header = false; p_strip_trailing_cr = strip_trailing_cr; } else if (strnEQ(s, "Index:", 6)) { fetchname (s+6, strippath, &p_name[INDEX], (char **) 0, NULL); need_header = false; p_strip_trailing_cr = strip_trailing_cr; } else if (strnEQ(s, "Prereq:", 7)) { for (t = s + 7; ISSPACE ((unsigned char) *t); t++) /* do nothing */ ; revision = t; for (t = revision; *t; t++) if (ISSPACE ((unsigned char) *t)) { char const *u; for (u = t + 1; ISSPACE ((unsigned char) *u); u++) /* do nothing */ ; if (*u) { char numbuf[LINENUM_LENGTH_BOUND + 1]; say ("Prereq: with multiple words at line %s of patch\n", format_linenum (numbuf, this_line)); } break; } if (t == revision) revision = 0; else { char oldc = *t; *t = '\0'; revision = xstrdup (revision); *t = oldc; } } else if (strnEQ (s, "diff --git ", 11)) { char const *u; if (extended_headers) { p_start = this_line; p_sline = p_input_line; /* Patch contains no hunks; any diff type will do. */ retval = UNI_DIFF; goto scan_exit; } for (i = OLD; i <= NEW; i++) { free (p_name[i]); p_name[i] = 0; } if (! ((p_name[OLD] = parse_name (s + 11, strippath, &u)) && ISSPACE ((unsigned char) *u) && (p_name[NEW] = parse_name (u, strippath, &u)) && (u = skip_spaces (u), ! *u))) for (i = OLD; i <= NEW; i++) { free (p_name[i]); p_name[i] = 0; } p_git_diff = true; need_header = false; } else if (p_git_diff && strnEQ (s, "index ", 6)) { char const *u, *v; if ((u = skip_hex_digits (s + 6)) && u[0] == '.' && u[1] == '.' && (v = skip_hex_digits (u + 2)) && (! *v || ISSPACE ((unsigned char) *v))) { get_sha1(&p_sha1[OLD], s + 6, u); get_sha1(&p_sha1[NEW], u + 2, v); p_says_nonexistent[OLD] = sha1_says_nonexistent (p_sha1[OLD]); p_says_nonexistent[NEW] = sha1_says_nonexistent (p_sha1[NEW]); if (*(v = skip_spaces (v))) p_mode[OLD] = p_mode[NEW] = fetchmode (v); extended_headers = true; } } else if (p_git_diff && strnEQ (s, "old mode ", 9)) { p_mode[OLD] = fetchmode (s + 9); extended_headers = true; } else if (p_git_diff && strnEQ (s, "new mode ", 9)) { p_mode[NEW] = fetchmode (s + 9); extended_headers = true; } else if (p_git_diff && strnEQ (s, "deleted file mode ", 18)) { p_mode[OLD] = fetchmode (s + 18); p_says_nonexistent[NEW] = 2; extended_headers = true; } else if (p_git_diff && strnEQ (s, "new file mode ", 14)) { p_mode[NEW] = fetchmode (s + 14); p_says_nonexistent[OLD] = 2; extended_headers = true; } else if (p_git_diff && strnEQ (s, "rename from ", 12)) { /* Git leaves out the prefix in the file name in this header, so we can only ignore the file name. */ p_rename[OLD] = true; extended_headers = true; } else if (p_git_diff && strnEQ (s, "rename to ", 10)) { /* Git leaves out the prefix in the file name in this header, so we can only ignore the file name. */ p_rename[NEW] = true; extended_headers = true; } else if (p_git_diff && strnEQ (s, "copy from ", 10)) { /* Git leaves out the prefix in the file name in this header, so we can only ignore the file name. */ p_copy[OLD] = true; extended_headers = true; } else if (p_git_diff && strnEQ (s, "copy to ", 8)) { /* Git leaves out the prefix in the file name in this header, so we can only ignore the file name. */ p_copy[NEW] = true; extended_headers = true; } else if (p_git_diff && strnEQ (s, "GIT binary patch", 16)) { p_start = this_line; p_sline = p_input_line; retval = GIT_BINARY_DIFF; goto scan_exit; } else { for (t = s; t[0] == '-' && t[1] == ' '; t += 2) /* do nothing */ ; if (strnEQ(t, "--- ", 4)) { struct timespec timestamp; timestamp.tv_sec = -1; fetchname (t+4, strippath, &p_name[NEW], &p_timestr[NEW], &timestamp); need_header = false; if (timestamp.tv_sec != -1) { p_timestamp[NEW] = timestamp; p_rfc934_nesting = (t - s) >> 1; } p_strip_trailing_cr = strip_trailing_cr; } } if (need_header) continue; if ((diff_type == NO_DIFF || diff_type == ED_DIFF) && first_command_line >= 0 && strEQ(s, ".\n") ) { p_start = first_command_line; p_sline = fcl_line; retval = ED_DIFF; goto scan_exit; } if ((diff_type == NO_DIFF || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) { /* 'p_name', 'p_timestr', and 'p_timestamp' are backwards; swap them. */ struct timespec ti = p_timestamp[OLD]; p_timestamp[OLD] = p_timestamp[NEW]; p_timestamp[NEW] = ti; t = p_name[OLD]; p_name[OLD] = p_name[NEW]; p_name[NEW] = t; t = p_timestr[OLD]; p_timestr[OLD] = p_timestr[NEW]; p_timestr[NEW] = t; s += 4; if (s[0] == '0' && !ISDIGIT (s[1])) p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD].tv_sec; while (*s != ' ' && *s != '\n') s++; while (*s == ' ') s++; if (s[0] == '+' && s[1] == '0' && !ISDIGIT (s[2])) p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW].tv_sec; p_indent = indent; p_start = this_line; p_sline = p_input_line; retval = UNI_DIFF; if (! ((p_name[OLD] || ! p_timestamp[OLD].tv_sec) && (p_name[NEW] || ! p_timestamp[NEW].tv_sec)) && ! p_name[INDEX] && need_header) { char numbuf[LINENUM_LENGTH_BOUND + 1]; say ("missing header for unified diff at line %s of patch\n", format_linenum (numbuf, p_sline)); } goto scan_exit; } stars_this_line = strnEQ(s, "********", 8); if ((diff_type == NO_DIFF || diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) && stars_last_line && indent_last_line == indent && strnEQ (s, "*** ", 4)) { s += 4; if (s[0] == '0' && !ISDIGIT (s[1])) p_says_nonexistent[OLD] = 1 + ! p_timestamp[OLD].tv_sec; /* if this is a new context diff the character just before */ /* the newline is a '*'. */ while (*s != '\n') s++; p_indent = indent; p_strip_trailing_cr = strip_trailing_cr; p_start = previous_line; p_sline = p_input_line - 1; retval = (*(s-1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF); { /* Scan the first hunk to see whether the file contents appear to have been deleted. */ file_offset saved_p_base = p_base; lin saved_p_bline = p_bline; Fseek (pfp, previous_line, SEEK_SET); p_input_line -= 2; if (another_hunk (retval, false) && ! p_repl_lines && p_newfirst == 1) p_says_nonexistent[NEW] = 1 + ! p_timestamp[NEW].tv_sec; next_intuit_at (saved_p_base, saved_p_bline); } if (! ((p_name[OLD] || ! p_timestamp[OLD].tv_sec) && (p_name[NEW] || ! p_timestamp[NEW].tv_sec)) && ! p_name[INDEX] && need_header) { char numbuf[LINENUM_LENGTH_BOUND + 1]; say ("missing header for context diff at line %s of patch\n", format_linenum (numbuf, p_sline)); } goto scan_exit; } if ((diff_type == NO_DIFF || diff_type == NORMAL_DIFF) && last_line_was_command && (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2)) ) { p_start = previous_line; p_sline = p_input_line - 1; p_indent = indent; retval = NORMAL_DIFF; goto scan_exit; } } scan_exit: /* The old, new, or old and new file types may be defined. When both file types are defined, make sure they are the same, or else assume we do not know the file type. */ file_type = p_mode[OLD] & S_IFMT; if (file_type) { mode_t new_file_type = p_mode[NEW] & S_IFMT; if (new_file_type && file_type != new_file_type) file_type = 0; } else { file_type = p_mode[NEW] & S_IFMT; if (! file_type) file_type = S_IFREG; } *p_file_type = file_type; /* To intuit 'inname', the name of the file to patch, use the algorithm specified by POSIX 1003.1-2001 XCU lines 25680-26599 (with some modifications if posixly_correct is zero): - Take the old and new names from the context header if present, and take the index name from the 'Index:' line if present and if either the old and new names are both absent or posixly_correct is nonzero. Consider the file names to be in the order (old, new, index). - If some named files exist, use the first one if posixly_correct is nonzero, the best one otherwise. - If patch_get is nonzero, and no named files exist, but an RCS or SCCS master file exists, use the first named file with an RCS or SCCS master. - If no named files exist, no RCS or SCCS master was found, some names are given, posixly_correct is zero, and the patch appears to create a file, then use the best name requiring the creation of the fewest directories. - Otherwise, report failure by setting 'inname' to 0; this causes our invoker to ask the user for a file name. */ i = NONE; if (!inname) { enum nametype i0 = NONE; if (! posixly_correct && (p_name[OLD] || p_name[NEW]) && p_name[INDEX]) { free (p_name[INDEX]); p_name[INDEX] = 0; } for (i = OLD; i <= INDEX; i++) if (p_name[i]) { if (i0 != NONE && strcmp (p_name[i0], p_name[i]) == 0) { /* It's the same name as before; reuse stat results. */ stat_errno[i] = stat_errno[i0]; if (! stat_errno[i]) st[i] = st[i0]; } else { stat_errno[i] = stat_file (p_name[i], &st[i]); if (! stat_errno[i]) { if (lookup_file_id (&st[i]) == DELETE_LATER) stat_errno[i] = ENOENT; else if (posixly_correct && name_is_valid (p_name[i])) break; } } i0 = i; } if (! posixly_correct) { /* The best of all existing files. */ i = best_name (p_name, stat_errno); if (i == NONE && patch_get) { enum nametype nope = NONE; for (i = OLD; i <= INDEX; i++) if (p_name[i]) { char const *cs; char *getbuf; char *diffbuf; bool readonly = (outfile && strcmp (outfile, p_name[i]) != 0); if (nope == NONE || strcmp (p_name[nope], p_name[i]) != 0) { cs = (version_controller (p_name[i], readonly, (struct stat *) 0, &getbuf, &diffbuf)); version_controlled[i] = !! cs; if (cs) { if (version_get (p_name[i], cs, false, readonly, getbuf, &st[i])) stat_errno[i] = 0; else version_controlled[i] = 0; free (getbuf); free (diffbuf); if (! stat_errno[i]) break; } } nope = i; } } if (i0 != NONE && (i == NONE || (st[i].st_mode & S_IFMT) == file_type) && maybe_reverse (p_name[i == NONE ? i0 : i], i == NONE, i == NONE || st[i].st_size == 0) && i == NONE) i = i0; if (i == NONE && p_says_nonexistent[reverse]) { int newdirs[3]; int newdirs_min = INT_MAX; int distance_from_minimum[3]; for (i = OLD; i <= INDEX; i++) if (p_name[i]) { newdirs[i] = (prefix_components (p_name[i], false) - prefix_components (p_name[i], true)); if (newdirs[i] < newdirs_min) newdirs_min = newdirs[i]; } for (i = OLD; i <= INDEX; i++) if (p_name[i]) distance_from_minimum[i] = newdirs[i] - newdirs_min; /* The best of the filenames which create the fewest directories. */ i = best_name (p_name, distance_from_minimum); } } } if ((pch_rename () || pch_copy ()) && ! inname && ! ((i == OLD || i == NEW) && p_name[reverse] && p_name[! reverse] && name_is_valid (p_name[reverse]) && name_is_valid (p_name[! reverse]))) { say ("Cannot %s file without two valid file names\n", pch_rename () ? "rename" : "copy"); } if (i == NONE) { if (inname) { inerrno = stat_file (inname, &instat); if (inerrno || (instat.st_mode & S_IFMT) == file_type) maybe_reverse (inname, inerrno, inerrno || instat.st_size == 0); } else inerrno = -1; } else { inname = xstrdup (p_name[i]); inerrno = stat_errno[i]; invc = version_controlled[i]; instat = st[i]; } return retval; }
[ "CWE-476" ]
savannah
f290f48a621867084884bfff87f8093c15195e6a
146473763077753726031355449366744801662
178,192
158,133
The product dereferences a pointer that it expects to be valid but is NULL.
false
Ins_GETVARIATION( TT_ExecContext exc, FT_Long* args ) { FT_UInt num_axes = exc->face->blend->num_axis; FT_Fixed* coords = exc->face->blend->normalizedcoords; FT_UInt i; if ( BOUNDS( num_axes, exc->stackSize + 1 - exc->top ) ) { exc->error = FT_THROW( Stack_Overflow ); return; } for ( i = 0; i < num_axes; i++ ) args[i] = coords[i] >> 2; /* convert 16.16 to 2.14 format */ }
[ "CWE-476" ]
savannah
29c759284e305ec428703c9a5831d0b1fc3497ef
139567459660525946313428439964298096333
178,193
275
The product dereferences a pointer that it expects to be valid but is NULL.
true
Ins_GETVARIATION( TT_ExecContext exc, FT_Long* args ) { FT_UInt num_axes = exc->face->blend->num_axis; FT_Fixed* coords = exc->face->blend->normalizedcoords; FT_UInt i; if ( BOUNDS( num_axes, exc->stackSize + 1 - exc->top ) ) { exc->error = FT_THROW( Stack_Overflow ); return; } if ( coords ) { for ( i = 0; i < num_axes; i++ ) args[i] = coords[i] >> 2; /* convert 16.16 to 2.14 format */ } else { for ( i = 0; i < num_axes; i++ ) args[i] = 0; } }
[ "CWE-476" ]
savannah
29c759284e305ec428703c9a5831d0b1fc3497ef
159806780920376373711216124732552440560
178,193
158,134
The product dereferences a pointer that it expects to be valid but is NULL.
false
int ssl3_get_server_hello(SSL *s) { STACK_OF(SSL_CIPHER) *sk; const SSL_CIPHER *c; unsigned char *p,*d; int i,al,ok; unsigned int j; long n; #ifndef OPENSSL_NO_COMP SSL_COMP *comp; #endif n=s->method->ssl_get_message(s, SSL3_ST_CR_SRVR_HELLO_A, SSL3_ST_CR_SRVR_HELLO_B, -1, 20000, /* ?? */ &ok); if (!ok) return((int)n); if ( SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER) { if ( s->s3->tmp.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST) { if ( s->d1->send_cookie == 0) { s->s3->tmp.reuse_message = 1; return 1; } else /* already sent a cookie */ { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE); goto f_err; } } } if ( s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE); goto f_err; } d=p=(unsigned char *)s->init_msg; if ((p[0] != (s->version>>8)) || (p[1] != (s->version&0xff))) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION); s->version=(s->version&0xff00)|p[1]; al=SSL_AD_PROTOCOL_VERSION; goto f_err; } p+=2; /* load the server hello data */ /* load the server random */ memcpy(s->s3->server_random,p,SSL3_RANDOM_SIZE); p+=SSL3_RANDOM_SIZE; /* get the session-id */ j= *(p++); if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SSL3_SESSION_ID_TOO_LONG); goto f_err; } #ifndef OPENSSL_NO_TLSEXT /* check if we want to resume the session based on external pre-shared secret */ if (s->version >= TLS1_VERSION && s->tls_session_secret_cb) { SSL_CIPHER *pref_cipher=NULL; s->session->master_key_length=sizeof(s->session->master_key); if (s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length, NULL, &pref_cipher, s->tls_session_secret_cb_arg)) { s->session->cipher = pref_cipher ? pref_cipher : ssl_get_cipher_by_char(s, p+j); s->s3->flags |= SSL3_FLAGS_CCS_OK; } } #endif /* OPENSSL_NO_TLSEXT */ if (j != 0 && j == s->session->session_id_length && memcmp(p,s->session->session_id,j) == 0) { if(s->sid_ctx_length != s->session->sid_ctx_length || memcmp(s->session->sid_ctx,s->sid_ctx,s->sid_ctx_length)) { /* actually a client application bug */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT); goto f_err; } s->s3->flags |= SSL3_FLAGS_CCS_OK; s->hit=1; } else /* a miss or crap from the other end */ { /* If we were trying for session-id reuse, make a new * SSL_SESSION so we don't stuff up other people */ s->hit=0; if (s->session->session_id_length > 0) { if (!ssl_get_new_session(s,0)) { al=SSL_AD_INTERNAL_ERROR; goto f_err; } } s->session->session_id_length=j; memcpy(s->session->session_id,p,j); /* j could be 0 */ } p+=j; c=ssl_get_cipher_by_char(s,p); if (c == NULL) { /* unknown cipher */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNKNOWN_CIPHER_RETURNED); goto f_err; } /* TLS v1.2 only ciphersuites require v1.2 or later */ if ((c->algorithm_ssl & SSL_TLSV1_2) && (TLS1_get_version(s) < TLS1_2_VERSION)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED); goto f_err; } p+=ssl_put_cipher_by_char(s,NULL,NULL); sk=ssl_get_ciphers_by_id(s); /* Depending on the session caching (internal/external), the cipher and/or cipher_id values may not be set. Make sure that cipher_id is set and use it for comparison. */ if (s->session->cipher) s->session->cipher_id = s->session->cipher->id; if (s->hit && (s->session->cipher_id != c->id)) { /* Workaround is now obsolete */ #if 0 if (!(s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)) #endif { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED); goto f_err; } } s->s3->tmp.new_cipher=c; /* Don't digest cached records if TLS v1.2: we may need them for * client authentication. */ if (TLS1_get_version(s) < TLS1_2_VERSION && !ssl3_digest_cached_records(s)) { al = SSL_AD_INTERNAL_ERROR; goto f_err; } /* lets get the compression algorithm */ /* COMPRESSION */ #ifdef OPENSSL_NO_COMP if (*(p++) != 0) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM); goto f_err; } /* If compression is disabled we'd better not try to resume a session * using compression. */ if (s->session->compress_meth != 0) { al=SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } #else j= *(p++); if (s->hit && j != s->session->compress_meth) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED); goto f_err; } if (j == 0) comp=NULL; else if (s->options & SSL_OP_NO_COMPRESSION) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_COMPRESSION_DISABLED); goto f_err; } else comp=ssl3_comp_find(s->ctx->comp_methods,j); if ((j != 0) && (comp == NULL)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM); goto f_err; } else { s->s3->tmp.new_compression=comp; } #endif #ifndef OPENSSL_NO_TLSEXT /* TLS extensions*/ if (s->version >= SSL3_VERSION) { if (!ssl_parse_serverhello_tlsext(s,&p,d,n, &al)) { /* 'al' set by ssl_parse_serverhello_tlsext */ SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_PARSE_TLSEXT); goto f_err; } if (ssl_check_serverhello_tlsext(s) <= 0) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT); goto err; } } #endif if (p != (d+n)) { /* wrong packet length */ al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_PACKET_LENGTH); goto f_err; } return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(-1); }
[ "Other" ]
openssl
83764a989dcc87fbea337da5f8f86806fe767b7e
277497504299456757679652544715041856567
178,194
276
Unknown
true
int ssl3_get_server_hello(SSL *s) { STACK_OF(SSL_CIPHER) *sk; const SSL_CIPHER *c; unsigned char *p,*d; int i,al,ok; unsigned int j; long n; #ifndef OPENSSL_NO_COMP SSL_COMP *comp; #endif n=s->method->ssl_get_message(s, SSL3_ST_CR_SRVR_HELLO_A, SSL3_ST_CR_SRVR_HELLO_B, -1, 20000, /* ?? */ &ok); if (!ok) return((int)n); if ( SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER) { if ( s->s3->tmp.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST) { if ( s->d1->send_cookie == 0) { s->s3->tmp.reuse_message = 1; return 1; } else /* already sent a cookie */ { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE); goto f_err; } } } if ( s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE); goto f_err; } d=p=(unsigned char *)s->init_msg; if ((p[0] != (s->version>>8)) || (p[1] != (s->version&0xff))) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION); s->version=(s->version&0xff00)|p[1]; al=SSL_AD_PROTOCOL_VERSION; goto f_err; } p+=2; /* load the server hello data */ /* load the server random */ memcpy(s->s3->server_random,p,SSL3_RANDOM_SIZE); p+=SSL3_RANDOM_SIZE; /* get the session-id */ j= *(p++); if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SSL3_SESSION_ID_TOO_LONG); goto f_err; } #ifndef OPENSSL_NO_TLSEXT /* check if we want to resume the session based on external pre-shared secret */ if (s->version >= TLS1_VERSION && s->tls_session_secret_cb) { SSL_CIPHER *pref_cipher=NULL; s->session->master_key_length=sizeof(s->session->master_key); if (s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length, NULL, &pref_cipher, s->tls_session_secret_cb_arg)) { s->session->cipher = pref_cipher ? pref_cipher : ssl_get_cipher_by_char(s, p+j); s->s3->flags |= SSL3_FLAGS_CCS_OK; } } #endif /* OPENSSL_NO_TLSEXT */ if (j != 0 && j == s->session->session_id_length && memcmp(p,s->session->session_id,j) == 0) { if(s->sid_ctx_length != s->session->sid_ctx_length || memcmp(s->session->sid_ctx,s->sid_ctx,s->sid_ctx_length)) { /* actually a client application bug */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT); goto f_err; } s->s3->flags |= SSL3_FLAGS_CCS_OK; s->hit=1; } else /* a miss or crap from the other end */ { /* If we were trying for session-id reuse, make a new * SSL_SESSION so we don't stuff up other people */ s->hit=0; if (s->session->session_id_length > 0) { if (!ssl_get_new_session(s,0)) { al=SSL_AD_INTERNAL_ERROR; goto f_err; } } s->session->session_id_length=j; memcpy(s->session->session_id,p,j); /* j could be 0 */ } p+=j; c=ssl_get_cipher_by_char(s,p); if (c == NULL) { /* unknown cipher */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNKNOWN_CIPHER_RETURNED); goto f_err; } /* TLS v1.2 only ciphersuites require v1.2 or later */ if ((c->algorithm_ssl & SSL_TLSV1_2) && (TLS1_get_version(s) < TLS1_2_VERSION)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED); goto f_err; } #ifndef OPENSSL_NO_SRP if (((c->algorithm_mkey & SSL_kSRP) || (c->algorithm_auth & SSL_aSRP)) && !(s->srp_ctx.srp_Mask & SSL_kSRP)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED); goto f_err; } #endif /* OPENSSL_NO_SRP */ p+=ssl_put_cipher_by_char(s,NULL,NULL); sk=ssl_get_ciphers_by_id(s); /* Depending on the session caching (internal/external), the cipher and/or cipher_id values may not be set. Make sure that cipher_id is set and use it for comparison. */ if (s->session->cipher) s->session->cipher_id = s->session->cipher->id; if (s->hit && (s->session->cipher_id != c->id)) { /* Workaround is now obsolete */ #if 0 if (!(s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)) #endif { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED); goto f_err; } } s->s3->tmp.new_cipher=c; /* Don't digest cached records if TLS v1.2: we may need them for * client authentication. */ if (TLS1_get_version(s) < TLS1_2_VERSION && !ssl3_digest_cached_records(s)) { al = SSL_AD_INTERNAL_ERROR; goto f_err; } /* lets get the compression algorithm */ /* COMPRESSION */ #ifdef OPENSSL_NO_COMP if (*(p++) != 0) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM); goto f_err; } /* If compression is disabled we'd better not try to resume a session * using compression. */ if (s->session->compress_meth != 0) { al=SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } #else j= *(p++); if (s->hit && j != s->session->compress_meth) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED); goto f_err; } if (j == 0) comp=NULL; else if (s->options & SSL_OP_NO_COMPRESSION) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_COMPRESSION_DISABLED); goto f_err; } else comp=ssl3_comp_find(s->ctx->comp_methods,j); if ((j != 0) && (comp == NULL)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM); goto f_err; } else { s->s3->tmp.new_compression=comp; } #endif #ifndef OPENSSL_NO_TLSEXT /* TLS extensions*/ if (s->version >= SSL3_VERSION) { if (!ssl_parse_serverhello_tlsext(s,&p,d,n, &al)) { /* 'al' set by ssl_parse_serverhello_tlsext */ SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_PARSE_TLSEXT); goto f_err; } if (ssl_check_serverhello_tlsext(s) <= 0) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT); goto err; } } #endif if (p != (d+n)) { /* wrong packet length */ al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_PACKET_LENGTH); goto f_err; } return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(-1); }
[ "Other" ]
openssl
83764a989dcc87fbea337da5f8f86806fe767b7e
213542089899120777699331744298021444999
178,194
158,135
Unknown
false
void ssl_set_client_disabled(SSL *s) { CERT *c = s->cert; c->mask_a = 0; c->mask_k = 0; /* Don't allow TLS 1.2 only ciphers if we don't suppport them */ if (!SSL_CLIENT_USE_TLS1_2_CIPHERS(s)) c->mask_ssl = SSL_TLSV1_2; else c->mask_ssl = 0; ssl_set_sig_mask(&c->mask_a, s, SSL_SECOP_SIGALG_MASK); /* Disable static DH if we don't include any appropriate * signature algorithms. */ if (c->mask_a & SSL_aRSA) c->mask_k |= SSL_kDHr|SSL_kECDHr; if (c->mask_a & SSL_aDSS) c->mask_k |= SSL_kDHd; if (c->mask_a & SSL_aECDSA) c->mask_k |= SSL_kECDHe; #ifndef OPENSSL_NO_KRB5 if (!kssl_tgt_is_available(s->kssl_ctx)) { c->mask_a |= SSL_aKRB5; c->mask_k |= SSL_kKRB5; } #endif #ifndef OPENSSL_NO_PSK /* with PSK there must be client callback set */ if (!s->psk_client_callback) { c->mask_a |= SSL_aPSK; c->mask_k |= SSL_kPSK; } #endif /* OPENSSL_NO_PSK */ c->valid = 1; }
[ "Other" ]
openssl
80bd7b41b30af6ee96f519e629463583318de3b0
145190138964748869120683088287665695350
178,195
277
Unknown
true
void ssl_set_client_disabled(SSL *s) { CERT *c = s->cert; c->mask_a = 0; c->mask_k = 0; /* Don't allow TLS 1.2 only ciphers if we don't suppport them */ if (!SSL_CLIENT_USE_TLS1_2_CIPHERS(s)) c->mask_ssl = SSL_TLSV1_2; else c->mask_ssl = 0; ssl_set_sig_mask(&c->mask_a, s, SSL_SECOP_SIGALG_MASK); /* Disable static DH if we don't include any appropriate * signature algorithms. */ if (c->mask_a & SSL_aRSA) c->mask_k |= SSL_kDHr|SSL_kECDHr; if (c->mask_a & SSL_aDSS) c->mask_k |= SSL_kDHd; if (c->mask_a & SSL_aECDSA) c->mask_k |= SSL_kECDHe; #ifndef OPENSSL_NO_KRB5 if (!kssl_tgt_is_available(s->kssl_ctx)) { c->mask_a |= SSL_aKRB5; c->mask_k |= SSL_kKRB5; } #endif #ifndef OPENSSL_NO_PSK /* with PSK there must be client callback set */ if (!s->psk_client_callback) { c->mask_a |= SSL_aPSK; c->mask_k |= SSL_kPSK; } #endif /* OPENSSL_NO_PSK */ #ifndef OPENSSL_NO_SRP if (!(s->srp_ctx.srp_Mask & SSL_kSRP)) { c->mask_a |= SSL_aSRP; c->mask_k |= SSL_kSRP; } #endif c->valid = 1; }
[ "Other" ]
openssl
80bd7b41b30af6ee96f519e629463583318de3b0
282690502176957429077395181909592930453
178,195
158,136
Unknown
false
void DelayedExecutor::delayedExecute(const QString &udi) { Solid::Device device(udi); QString exec = m_service.exec(); MacroExpander mx(device); mx.expandMacros(exec); KRun::runCommand(exec, QString(), m_service.icon(), 0); deleteLater(); }
[ "CWE-78" ]
kde
9db872df82c258315c6ebad800af59e81ffb9212
185460399545264476872601191691271963408
178,196
278
The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
true
void DelayedExecutor::delayedExecute(const QString &udi) { Solid::Device device(udi); QString exec = m_service.exec(); MacroExpander mx(device); mx.expandMacrosShellQuote(exec); KRun::runCommand(exec, QString(), m_service.icon(), 0); deleteLater(); }
[ "CWE-78" ]
kde
9db872df82c258315c6ebad800af59e81ffb9212
323699902109915935156580630724126463315
178,196
158,137
The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
false
uint NotificationsEngine::Notify(const QString &app_name, uint replaces_id, const QString &app_icon, const QString &summary, const QString &body, const QStringList &actions, const QVariantMap &hints, int timeout) { uint partOf = 0; const QString appRealName = hints[QStringLiteral("x-kde-appname")].toString(); const QString eventId = hints[QStringLiteral("x-kde-eventId")].toString(); const bool skipGrouping = hints[QStringLiteral("x-kde-skipGrouping")].toBool(); if (!replaces_id && m_activeNotifications.values().contains(app_name + summary) && !skipGrouping && !m_alwaysReplaceAppsList.contains(app_name)) { partOf = m_activeNotifications.key(app_name + summary).midRef(13).toUInt(); } qDebug() << "Currrent active notifications:" << m_activeNotifications; qDebug() << "Guessing partOf as:" << partOf; qDebug() << " New Notification: " << summary << body << timeout << "& Part of:" << partOf; QString _body; if (partOf > 0) { const QString source = QStringLiteral("notification %1").arg(partOf); Plasma::DataContainer *container = containerForSource(source); if (container) { _body = container->data()[QStringLiteral("body")].toString(); if (_body != body) { _body.append("\n").append(body); } else { _body = body; } replaces_id = partOf; CloseNotification(partOf); } } uint id = replaces_id ? replaces_id : m_nextId++; if (m_alwaysReplaceAppsList.contains(app_name)) { if (m_notificationsFromReplaceableApp.contains(app_name)) { id = m_notificationsFromReplaceableApp.value(app_name); } else { m_notificationsFromReplaceableApp.insert(app_name, id); } } QString appname_str = app_name; if (appname_str.isEmpty()) { appname_str = i18n("Unknown Application"); } bool isPersistent = timeout == 0; const int AVERAGE_WORD_LENGTH = 6; const int WORD_PER_MINUTE = 250; int count = summary.length() + body.length(); timeout = 60000 * count / AVERAGE_WORD_LENGTH / WORD_PER_MINUTE; timeout = 2000 + qMax(timeout, 3000); }
[ "CWE-200" ]
kde
8164beac15ea34ec0d1564f0557fe3e742bdd938
66626965994794909671436631171592255350
178,197
279
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
true
uint NotificationsEngine::Notify(const QString &app_name, uint replaces_id, const QString &app_icon, const QString &summary, const QString &body, const QStringList &actions, const QVariantMap &hints, int timeout) { uint partOf = 0; const QString appRealName = hints[QStringLiteral("x-kde-appname")].toString(); const QString eventId = hints[QStringLiteral("x-kde-eventId")].toString(); const bool skipGrouping = hints[QStringLiteral("x-kde-skipGrouping")].toBool(); if (!replaces_id && m_activeNotifications.values().contains(app_name + summary) && !skipGrouping && !m_alwaysReplaceAppsList.contains(app_name)) { partOf = m_activeNotifications.key(app_name + summary).midRef(13).toUInt(); } qDebug() << "Currrent active notifications:" << m_activeNotifications; qDebug() << "Guessing partOf as:" << partOf; qDebug() << " New Notification: " << summary << body << timeout << "& Part of:" << partOf; QString bodyFinal = NotificationSanitizer::parse(body); if (partOf > 0) { const QString source = QStringLiteral("notification %1").arg(partOf); Plasma::DataContainer *container = containerForSource(source); if (container) { const QString previousBody = container->data()[QStringLiteral("body")].toString(); if (previousBody != bodyFinal) { // FIXME: This will just append the entire old XML document to another one, leading to: // <?xml><html>old</html><br><?xml><html>new</html> // It works but is not very clean. bodyFinal = previousBody + QStringLiteral("<br/>") + bodyFinal; } replaces_id = partOf; CloseNotification(partOf); } } uint id = replaces_id ? replaces_id : m_nextId++; if (m_alwaysReplaceAppsList.contains(app_name)) { if (m_notificationsFromReplaceableApp.contains(app_name)) { id = m_notificationsFromReplaceableApp.value(app_name); } else { m_notificationsFromReplaceableApp.insert(app_name, id); } } QString appname_str = app_name; if (appname_str.isEmpty()) { appname_str = i18n("Unknown Application"); } bool isPersistent = timeout == 0; const int AVERAGE_WORD_LENGTH = 6; const int WORD_PER_MINUTE = 250; int count = summary.length() + body.length() - strlen("<?xml version=\"1.0\"><html></html>"); timeout = 60000 * count / AVERAGE_WORD_LENGTH / WORD_PER_MINUTE; timeout = 2000 + qMax(timeout, 3000); }
[ "CWE-200" ]
kde
8164beac15ea34ec0d1564f0557fe3e742bdd938
307726928526403562600043842982225149020
178,197
158,138
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
false
uint NotificationsEngine::Notify(const QString &app_name, uint replaces_id, const QString &app_icon, const QString &summary, const QString &body, const QStringList &actions, const QVariantMap &hints, int timeout) { uint partOf = 0; const QString appRealName = hints[QStringLiteral("x-kde-appname")].toString(); const QString eventId = hints[QStringLiteral("x-kde-eventId")].toString(); const bool skipGrouping = hints[QStringLiteral("x-kde-skipGrouping")].toBool(); if (!replaces_id && m_activeNotifications.values().contains(app_name + summary) && !skipGrouping && !m_alwaysReplaceAppsList.contains(app_name)) { partOf = m_activeNotifications.key(app_name + summary).midRef(13).toUInt(); } qDebug() << "Currrent active notifications:" << m_activeNotifications; qDebug() << "Guessing partOf as:" << partOf; qDebug() << " New Notification: " << summary << body << timeout << "& Part of:" << partOf; QString _body; if (partOf > 0) { const QString source = QStringLiteral("notification %1").arg(partOf); Plasma::DataContainer *container = containerForSource(source); if (container) { _body = container->data()[QStringLiteral("body")].toString(); if (_body != body) { _body.append("\n").append(body); } else { _body = body; } replaces_id = partOf; CloseNotification(partOf); } } uint id = replaces_id ? replaces_id : m_nextId++; if (m_alwaysReplaceAppsList.contains(app_name)) { if (m_notificationsFromReplaceableApp.contains(app_name)) { id = m_notificationsFromReplaceableApp.value(app_name); } else { m_notificationsFromReplaceableApp.insert(app_name, id); } } QString appname_str = app_name; if (appname_str.isEmpty()) { appname_str = i18n("Unknown Application"); } bool isPersistent = timeout == 0; const int AVERAGE_WORD_LENGTH = 6; const int WORD_PER_MINUTE = 250; int count = summary.length() + body.length(); if (timeout <= 0) { timeout = 60000 * count / AVERAGE_WORD_LENGTH / WORD_PER_MINUTE; timeout = 2000 + qMax(timeout, 3000); } const QString source = QStringLiteral("notification %1").arg(id); const QString source = QStringLiteral("notification %1").arg(id); QString bodyFinal = (partOf == 0 ? body : _body); bodyFinal = bodyFinal.trimmed(); bodyFinal = bodyFinal.replace(QLatin1String("\n"), QLatin1String("<br/>")); bodyFinal = bodyFinal.simplified(); bodyFinal.replace(QRegularExpression(QStringLiteral("<br/>\\s*<br/>(\\s|<br/>)*")), QLatin1String("<br/>")); bodyFinal.replace(QRegularExpression(QStringLiteral("&(?!(?:apos|quot|[gl]t|amp);|#)")), QLatin1String("&amp;")); bodyFinal.replace(QLatin1String("&apos;"), QChar('\'')); Plasma::DataEngine::Data notificationData; notificationData.insert(QStringLiteral("id"), QString::number(id)); bodyFinal = bodyFinal.simplified(); bodyFinal.replace(QRegularExpression(QStringLiteral("<br/>\\s*<br/>(\\s|<br/>)*")), QLatin1String("<br/>")); bodyFinal.replace(QRegularExpression(QStringLiteral("&(?!(?:apos|quot|[gl]t|amp);|#)")), QLatin1String("&amp;")); bodyFinal.replace(QLatin1String("&apos;"), QChar('\'')); Plasma::DataEngine::Data notificationData; notificationData.insert(QStringLiteral("id"), QString::number(id)); notificationData.insert(QStringLiteral("eventId"), eventId); notificationData.insert(QStringLiteral("appName"), appname_str); notificationData.insert(QStringLiteral("appIcon"), app_icon); notificationData.insert(QStringLiteral("summary"), summary); notificationData.insert(QStringLiteral("body"), bodyFinal); notificationData.insert(QStringLiteral("actions"), actions); notificationData.insert(QStringLiteral("isPersistent"), isPersistent); notificationData.insert(QStringLiteral("expireTimeout"), timeout); bool configurable = false; if (!appRealName.isEmpty()) { if (m_configurableApplications.contains(appRealName)) { configurable = m_configurableApplications.value(appRealName); } else { QScopedPointer<KConfig> config(new KConfig(appRealName + QStringLiteral(".notifyrc"), KConfig::NoGlobals)); config->addConfigSources(QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("knotifications5/") + appRealName + QStringLiteral(".notifyrc"))); const QRegularExpression regexp(QStringLiteral("^Event/([^/]*)$")); configurable = !config->groupList().filter(regexp).isEmpty(); m_configurableApplications.insert(appRealName, configurable); } } notificationData.insert(QStringLiteral("appRealName"), appRealName); notificationData.insert(QStringLiteral("configurable"), configurable); QImage image; if (hints.contains(QStringLiteral("image-data"))) { QDBusArgument arg = hints[QStringLiteral("image-data")].value<QDBusArgument>(); image = decodeNotificationSpecImageHint(arg); } else if (hints.contains(QStringLiteral("image_data"))) { QDBusArgument arg = hints[QStringLiteral("image_data")].value<QDBusArgument>(); image = decodeNotificationSpecImageHint(arg); } else if (hints.contains(QStringLiteral("image-path"))) { QString path = findImageForSpecImagePath(hints[QStringLiteral("image-path")].toString()); if (!path.isEmpty()) { image.load(path); } } else if (hints.contains(QStringLiteral("image_path"))) { QString path = findImageForSpecImagePath(hints[QStringLiteral("image_path")].toString()); if (!path.isEmpty()) { image.load(path); } } else if (hints.contains(QStringLiteral("icon_data"))) { QDBusArgument arg = hints[QStringLiteral("icon_data")].value<QDBusArgument>(); image = decodeNotificationSpecImageHint(arg); } notificationData.insert(QStringLiteral("image"), image.isNull() ? QVariant() : image); if (hints.contains(QStringLiteral("urgency"))) { notificationData.insert(QStringLiteral("urgency"), hints[QStringLiteral("urgency")].toInt()); } setData(source, notificationData); m_activeNotifications.insert(source, app_name + summary); return id; }
[ "CWE-200" ]
kde
5bc696b5abcdb460c1017592e80b2d7f6ed3107c
49080920792690681565819742613436372042
178,198
280
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
true
uint NotificationsEngine::Notify(const QString &app_name, uint replaces_id, const QString &app_icon, const QString &summary, const QString &body, const QStringList &actions, const QVariantMap &hints, int timeout) { uint partOf = 0; const QString appRealName = hints[QStringLiteral("x-kde-appname")].toString(); const QString eventId = hints[QStringLiteral("x-kde-eventId")].toString(); const bool skipGrouping = hints[QStringLiteral("x-kde-skipGrouping")].toBool(); if (!replaces_id && m_activeNotifications.values().contains(app_name + summary) && !skipGrouping && !m_alwaysReplaceAppsList.contains(app_name)) { partOf = m_activeNotifications.key(app_name + summary).midRef(13).toUInt(); } qDebug() << "Currrent active notifications:" << m_activeNotifications; qDebug() << "Guessing partOf as:" << partOf; qDebug() << " New Notification: " << summary << body << timeout << "& Part of:" << partOf; QString _body; if (partOf > 0) { const QString source = QStringLiteral("notification %1").arg(partOf); Plasma::DataContainer *container = containerForSource(source); if (container) { _body = container->data()[QStringLiteral("body")].toString(); if (_body != body) { _body.append("\n").append(body); } else { _body = body; } replaces_id = partOf; CloseNotification(partOf); } } uint id = replaces_id ? replaces_id : m_nextId++; if (m_alwaysReplaceAppsList.contains(app_name)) { if (m_notificationsFromReplaceableApp.contains(app_name)) { id = m_notificationsFromReplaceableApp.value(app_name); } else { m_notificationsFromReplaceableApp.insert(app_name, id); } } QString appname_str = app_name; if (appname_str.isEmpty()) { appname_str = i18n("Unknown Application"); } bool isPersistent = timeout == 0; const int AVERAGE_WORD_LENGTH = 6; const int WORD_PER_MINUTE = 250; int count = summary.length() + body.length(); if (timeout <= 0) { timeout = 60000 * count / AVERAGE_WORD_LENGTH / WORD_PER_MINUTE; timeout = 2000 + qMax(timeout, 3000); } const QString source = QStringLiteral("notification %1").arg(id); const QString source = QStringLiteral("notification %1").arg(id); QString bodyFinal = (partOf == 0 ? body : _body); bodyFinal = NotificationSanitizer::parse(bodyFinal); Plasma::DataEngine::Data notificationData; notificationData.insert(QStringLiteral("id"), QString::number(id)); bodyFinal = bodyFinal.simplified(); bodyFinal.replace(QRegularExpression(QStringLiteral("<br/>\\s*<br/>(\\s|<br/>)*")), QLatin1String("<br/>")); bodyFinal.replace(QRegularExpression(QStringLiteral("&(?!(?:apos|quot|[gl]t|amp);|#)")), QLatin1String("&amp;")); bodyFinal.replace(QLatin1String("&apos;"), QChar('\'')); Plasma::DataEngine::Data notificationData; notificationData.insert(QStringLiteral("id"), QString::number(id)); notificationData.insert(QStringLiteral("eventId"), eventId); notificationData.insert(QStringLiteral("appName"), appname_str); notificationData.insert(QStringLiteral("appIcon"), app_icon); notificationData.insert(QStringLiteral("summary"), summary); notificationData.insert(QStringLiteral("body"), bodyFinal); notificationData.insert(QStringLiteral("actions"), actions); notificationData.insert(QStringLiteral("isPersistent"), isPersistent); notificationData.insert(QStringLiteral("expireTimeout"), timeout); bool configurable = false; if (!appRealName.isEmpty()) { if (m_configurableApplications.contains(appRealName)) { configurable = m_configurableApplications.value(appRealName); } else { QScopedPointer<KConfig> config(new KConfig(appRealName + QStringLiteral(".notifyrc"), KConfig::NoGlobals)); config->addConfigSources(QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("knotifications5/") + appRealName + QStringLiteral(".notifyrc"))); const QRegularExpression regexp(QStringLiteral("^Event/([^/]*)$")); configurable = !config->groupList().filter(regexp).isEmpty(); m_configurableApplications.insert(appRealName, configurable); } } notificationData.insert(QStringLiteral("appRealName"), appRealName); notificationData.insert(QStringLiteral("configurable"), configurable); QImage image; if (hints.contains(QStringLiteral("image-data"))) { QDBusArgument arg = hints[QStringLiteral("image-data")].value<QDBusArgument>(); image = decodeNotificationSpecImageHint(arg); } else if (hints.contains(QStringLiteral("image_data"))) { QDBusArgument arg = hints[QStringLiteral("image_data")].value<QDBusArgument>(); image = decodeNotificationSpecImageHint(arg); } else if (hints.contains(QStringLiteral("image-path"))) { QString path = findImageForSpecImagePath(hints[QStringLiteral("image-path")].toString()); if (!path.isEmpty()) { image.load(path); } } else if (hints.contains(QStringLiteral("image_path"))) { QString path = findImageForSpecImagePath(hints[QStringLiteral("image_path")].toString()); if (!path.isEmpty()) { image.load(path); } } else if (hints.contains(QStringLiteral("icon_data"))) { QDBusArgument arg = hints[QStringLiteral("icon_data")].value<QDBusArgument>(); image = decodeNotificationSpecImageHint(arg); } notificationData.insert(QStringLiteral("image"), image.isNull() ? QVariant() : image); if (hints.contains(QStringLiteral("urgency"))) { notificationData.insert(QStringLiteral("urgency"), hints[QStringLiteral("urgency")].toInt()); } setData(source, notificationData); m_activeNotifications.insert(source, app_name + summary); return id; }
[ "CWE-200" ]
kde
5bc696b5abcdb460c1017592e80b2d7f6ed3107c
114483981526891060266771495911529009869
178,198
158,139
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
false
dns_stricmp(const char* str1, const char* str2) { char c1, c2; *----------------------------------------------------------------------------*/ /* DNS variables */ static struct udp_pcb *dns_pcb; static u8_t dns_seqno; static struct dns_table_entry dns_table[DNS_TABLE_SIZE]; static struct dns_req_entry dns_requests[DNS_MAX_REQUESTS]; if (c1_upc != c2_upc) { /* still not equal */ /* don't care for < or > */ return 1; } } else { /* characters are not equal but none is in the alphabet range */ return 1; }
[ "CWE-345" ]
savannah
9fb46e120655ac481b2af8f865d5ae56c39b831a
181259810056970673184917548254526485235
178,220
283
The product does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
true
dns_stricmp(const char* str1, const char* str2) { char c1, c2; *----------------------------------------------------------------------------*/ /* DNS variables */ static struct udp_pcb *dns_pcbs[DNS_MAX_SOURCE_PORTS]; #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0) static u8_t dns_last_pcb_idx; #endif static u8_t dns_seqno; static struct dns_table_entry dns_table[DNS_TABLE_SIZE]; static struct dns_req_entry dns_requests[DNS_MAX_REQUESTS]; if (c1_upc != c2_upc) { /* still not equal */ /* don't care for < or > */ return 1; } } else { /* characters are not equal but none is in the alphabet range */ return 1; }
[ "CWE-345" ]
savannah
9fb46e120655ac481b2af8f865d5ae56c39b831a
167319277236782062603877419055130451552
178,220
158,142
The product does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.
false
static void reply_sesssetup_and_X_spnego(struct smb_request *req) { const uint8 *p; DATA_BLOB blob1; size_t bufrem; char *tmp; const char *native_os; const char *native_lanman; const char *primary_domain; const char *p2; uint16 data_blob_len = SVAL(req->vwv+7, 0); enum remote_arch_types ra_type = get_remote_arch(); int vuid = req->vuid; user_struct *vuser = NULL; NTSTATUS status = NT_STATUS_OK; uint16 smbpid = req->smbpid; struct smbd_server_connection *sconn = smbd_server_conn; DEBUG(3,("Doing spnego session setup\n")); if (global_client_caps == 0) { global_client_caps = IVAL(req->vwv+10, 0); if (!(global_client_caps & CAP_STATUS32)) { remove_from_common_flags2(FLAGS2_32_BIT_ERROR_CODES); } } p = req->buf; if (data_blob_len == 0) { /* an invalid request */ reply_nterror(req, nt_status_squash(NT_STATUS_LOGON_FAILURE)); return; } bufrem = smbreq_bufrem(req, p); /* pull the spnego blob */ blob1 = data_blob(p, MIN(bufrem, data_blob_len)); #if 0 file_save("negotiate.dat", blob1.data, blob1.length); #endif p2 = (char *)req->buf + data_blob_len; p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2, STR_TERMINATE); native_os = tmp ? tmp : ""; p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2, STR_TERMINATE); native_lanman = tmp ? tmp : ""; p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2, STR_TERMINATE); primary_domain = tmp ? tmp : ""; DEBUG(3,("NativeOS=[%s] NativeLanMan=[%s] PrimaryDomain=[%s]\n", native_os, native_lanman, primary_domain)); if ( ra_type == RA_WIN2K ) { /* Vista sets neither the OS or lanman strings */ if ( !strlen(native_os) && !strlen(native_lanman) ) set_remote_arch(RA_VISTA); /* Windows 2003 doesn't set the native lanman string, but does set primary domain which is a bug I think */ if ( !strlen(native_lanman) ) { ra_lanman_string( primary_domain ); } else { ra_lanman_string( native_lanman ); } } /* Did we get a valid vuid ? */ if (!is_partial_auth_vuid(sconn, vuid)) { /* No, then try and see if this is an intermediate sessionsetup * for a large SPNEGO packet. */ struct pending_auth_data *pad; pad = get_pending_auth_data(sconn, smbpid); if (pad) { DEBUG(10,("reply_sesssetup_and_X_spnego: found " "pending vuid %u\n", (unsigned int)pad->vuid )); vuid = pad->vuid; } } /* Do we have a valid vuid now ? */ if (!is_partial_auth_vuid(sconn, vuid)) { /* No, start a new authentication setup. */ vuid = register_initial_vuid(sconn); if (vuid == UID_FIELD_INVALID) { data_blob_free(&blob1); reply_nterror(req, nt_status_squash( NT_STATUS_INVALID_PARAMETER)); return; } } vuser = get_partial_auth_user_struct(sconn, vuid); /* This MUST be valid. */ if (!vuser) { smb_panic("reply_sesssetup_and_X_spnego: invalid vuid."); } /* Large (greater than 4k) SPNEGO blobs are split into multiple * sessionsetup requests as the Windows limit on the security blob * field is 4k. Bug #4400. JRA. */ status = check_spnego_blob_complete(sconn, smbpid, vuid, &blob1); if (!NT_STATUS_IS_OK(status)) { if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) { /* Real error - kill the intermediate vuid */ invalidate_vuid(sconn, vuid); } data_blob_free(&blob1); reply_nterror(req, nt_status_squash(status)); return; } if (blob1.data[0] == ASN1_APPLICATION(0)) { /* its a negTokenTarg packet */ reply_spnego_negotiate(req, vuid, blob1, &vuser->auth_ntlmssp_state); data_blob_free(&blob1); return; } if (blob1.data[0] == ASN1_CONTEXT(1)) { /* its a auth packet */ reply_spnego_auth(req, vuid, blob1, &vuser->auth_ntlmssp_state); data_blob_free(&blob1); return; } if (strncmp((char *)(blob1.data), "NTLMSSP", 7) == 0) { DATA_BLOB chal; if (!vuser->auth_ntlmssp_state) { status = auth_ntlmssp_start(&vuser->auth_ntlmssp_state); if (!NT_STATUS_IS_OK(status)) { /* Kill the intermediate vuid */ invalidate_vuid(sconn, vuid); data_blob_free(&blob1); reply_nterror(req, nt_status_squash(status)); return; } } status = auth_ntlmssp_update(vuser->auth_ntlmssp_state, blob1, &chal); data_blob_free(&blob1); reply_spnego_ntlmssp(req, vuid, &vuser->auth_ntlmssp_state, &chal, status, OID_NTLMSSP, false); data_blob_free(&chal); return; } /* what sort of packet is this? */ DEBUG(1,("Unknown packet in reply_sesssetup_and_X_spnego\n")); data_blob_free(&blob1); reply_nterror(req, nt_status_squash(NT_STATUS_LOGON_FAILURE)); }
[ "CWE-119" ]
samba
9280051bfba337458722fb157f3082f93cbd9f2b
252100526266913255109910552885875245221
178,226
287
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
static void reply_sesssetup_and_X_spnego(struct smb_request *req) { const uint8 *p; DATA_BLOB blob1; size_t bufrem; char *tmp; const char *native_os; const char *native_lanman; const char *primary_domain; const char *p2; uint16 data_blob_len = SVAL(req->vwv+7, 0); enum remote_arch_types ra_type = get_remote_arch(); int vuid = req->vuid; user_struct *vuser = NULL; NTSTATUS status = NT_STATUS_OK; uint16 smbpid = req->smbpid; struct smbd_server_connection *sconn = smbd_server_conn; DEBUG(3,("Doing spnego session setup\n")); if (global_client_caps == 0) { global_client_caps = IVAL(req->vwv+10, 0); if (!(global_client_caps & CAP_STATUS32)) { remove_from_common_flags2(FLAGS2_32_BIT_ERROR_CODES); } } p = req->buf; if (data_blob_len == 0) { /* an invalid request */ reply_nterror(req, nt_status_squash(NT_STATUS_LOGON_FAILURE)); return; } bufrem = smbreq_bufrem(req, p); /* pull the spnego blob */ blob1 = data_blob(p, MIN(bufrem, data_blob_len)); #if 0 file_save("negotiate.dat", blob1.data, blob1.length); #endif p2 = (char *)req->buf + blob1.length; p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2, STR_TERMINATE); native_os = tmp ? tmp : ""; p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2, STR_TERMINATE); native_lanman = tmp ? tmp : ""; p2 += srvstr_pull_req_talloc(talloc_tos(), req, &tmp, p2, STR_TERMINATE); primary_domain = tmp ? tmp : ""; DEBUG(3,("NativeOS=[%s] NativeLanMan=[%s] PrimaryDomain=[%s]\n", native_os, native_lanman, primary_domain)); if ( ra_type == RA_WIN2K ) { /* Vista sets neither the OS or lanman strings */ if ( !strlen(native_os) && !strlen(native_lanman) ) set_remote_arch(RA_VISTA); /* Windows 2003 doesn't set the native lanman string, but does set primary domain which is a bug I think */ if ( !strlen(native_lanman) ) { ra_lanman_string( primary_domain ); } else { ra_lanman_string( native_lanman ); } } /* Did we get a valid vuid ? */ if (!is_partial_auth_vuid(sconn, vuid)) { /* No, then try and see if this is an intermediate sessionsetup * for a large SPNEGO packet. */ struct pending_auth_data *pad; pad = get_pending_auth_data(sconn, smbpid); if (pad) { DEBUG(10,("reply_sesssetup_and_X_spnego: found " "pending vuid %u\n", (unsigned int)pad->vuid )); vuid = pad->vuid; } } /* Do we have a valid vuid now ? */ if (!is_partial_auth_vuid(sconn, vuid)) { /* No, start a new authentication setup. */ vuid = register_initial_vuid(sconn); if (vuid == UID_FIELD_INVALID) { data_blob_free(&blob1); reply_nterror(req, nt_status_squash( NT_STATUS_INVALID_PARAMETER)); return; } } vuser = get_partial_auth_user_struct(sconn, vuid); /* This MUST be valid. */ if (!vuser) { smb_panic("reply_sesssetup_and_X_spnego: invalid vuid."); } /* Large (greater than 4k) SPNEGO blobs are split into multiple * sessionsetup requests as the Windows limit on the security blob * field is 4k. Bug #4400. JRA. */ status = check_spnego_blob_complete(sconn, smbpid, vuid, &blob1); if (!NT_STATUS_IS_OK(status)) { if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) { /* Real error - kill the intermediate vuid */ invalidate_vuid(sconn, vuid); } data_blob_free(&blob1); reply_nterror(req, nt_status_squash(status)); return; } if (blob1.data[0] == ASN1_APPLICATION(0)) { /* its a negTokenTarg packet */ reply_spnego_negotiate(req, vuid, blob1, &vuser->auth_ntlmssp_state); data_blob_free(&blob1); return; } if (blob1.data[0] == ASN1_CONTEXT(1)) { /* its a auth packet */ reply_spnego_auth(req, vuid, blob1, &vuser->auth_ntlmssp_state); data_blob_free(&blob1); return; } if (strncmp((char *)(blob1.data), "NTLMSSP", 7) == 0) { DATA_BLOB chal; if (!vuser->auth_ntlmssp_state) { status = auth_ntlmssp_start(&vuser->auth_ntlmssp_state); if (!NT_STATUS_IS_OK(status)) { /* Kill the intermediate vuid */ invalidate_vuid(sconn, vuid); data_blob_free(&blob1); reply_nterror(req, nt_status_squash(status)); return; } } status = auth_ntlmssp_update(vuser->auth_ntlmssp_state, blob1, &chal); data_blob_free(&blob1); reply_spnego_ntlmssp(req, vuid, &vuser->auth_ntlmssp_state, &chal, status, OID_NTLMSSP, false); data_blob_free(&chal); return; } /* what sort of packet is this? */ DEBUG(1,("Unknown packet in reply_sesssetup_and_X_spnego\n")); data_blob_free(&blob1); reply_nterror(req, nt_status_squash(NT_STATUS_LOGON_FAILURE)); }
[ "CWE-119" ]
samba
9280051bfba337458722fb157f3082f93cbd9f2b
264029160300950657613398871836569816502
178,226
158,146
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
_asn1_extract_der_octet (asn1_node node, const unsigned char *der, int der_len, unsigned flags) { int len2, len3; int counter, counter_end; int result; len2 = asn1_get_length_der (der, der_len, &len3); if (len2 < -1) return ASN1_DER_ERROR; counter = len3 + 1; DECR_LEN(der_len, len3); if (len2 == -1) counter_end = der_len - 2; else counter_end = der_len; while (counter < counter_end) { DECR_LEN(der_len, 1); if (len2 >= 0) { DECR_LEN(der_len, len2+len3); _asn1_append_value (node, der + counter + len3, len2); } else { /* indefinite */ DECR_LEN(der_len, len3); result = _asn1_extract_der_octet (node, der + counter + len3, der_len, flags); if (result != ASN1_SUCCESS) return result; len2 = 0; } counter += len2 + len3 + 1; } return ASN1_SUCCESS; cleanup: return result; }
[ "CWE-399" ]
savannah
f435825c0f527a8e52e6ffbc3ad0bc60531d537e
199202175349742229581148475563569699182
178,249
288
This vulnerability category highlights issues in resource management where failures to properly release memory, file handles, or other resources can degrade system performance or enable denial-of-service conditions.
true
_asn1_extract_der_octet (asn1_node node, const unsigned char *der, int der_len, unsigned flags) { int len2, len3; int counter, counter_end; int result; len2 = asn1_get_length_der (der, der_len, &len3); if (len2 < -1) return ASN1_DER_ERROR; counter = len3 + 1; DECR_LEN(der_len, len3); if (len2 == -1) { if (der_len < 2) return ASN1_DER_ERROR; counter_end = der_len - 2; } else counter_end = der_len; if (counter_end < counter) return ASN1_DER_ERROR; while (counter < counter_end) { DECR_LEN(der_len, 1); if (len2 >= 0) { DECR_LEN(der_len, len2+len3); _asn1_append_value (node, der + counter + len3, len2); } else { /* indefinite */ DECR_LEN(der_len, len3); result = _asn1_extract_der_octet (node, der + counter + len3, der_len, flags); if (result != ASN1_SUCCESS) return result; len2 = 0; } counter += len2 + len3 + 1; } return ASN1_SUCCESS; cleanup: return result; }
[ "CWE-399" ]
savannah
f435825c0f527a8e52e6ffbc3ad0bc60531d537e
67295952125339630714795122517192783264
178,249
158,148
This vulnerability category highlights issues in resource management where failures to properly release memory, file handles, or other resources can degrade system performance or enable denial-of-service conditions.
false
load(ImlibImage * im, ImlibProgressFunction progress, char progress_granularity, char immediate_load) { static const int intoffset[] = { 0, 4, 2, 1 }; static const int intjump[] = { 8, 8, 4, 2 }; int rc; DATA32 *ptr; GifFileType *gif; GifRowType *rows; GifRecordType rec; ColorMapObject *cmap; int i, j, done, bg, r, g, b, w = 0, h = 0; float per = 0.0, per_inc; int last_per = 0, last_y = 0; int transp; int fd; done = 0; rows = NULL; transp = -1; /* if immediate_load is 1, then dont delay image laoding as below, or */ /* already data in this image - dont load it again */ if (im->data) return 0; fd = open(im->real_file, O_RDONLY); if (fd < 0) return 0; #if GIFLIB_MAJOR >= 5 gif = DGifOpenFileHandle(fd, NULL); #else gif = DGifOpenFileHandle(fd); #endif if (!gif) { close(fd); return 0; } rc = 0; /* Failure */ do { if (DGifGetRecordType(gif, &rec) == GIF_ERROR) { /* PrintGifError(); */ rec = TERMINATE_RECORD_TYPE; } if ((rec == IMAGE_DESC_RECORD_TYPE) && (!done)) { if (DGifGetImageDesc(gif) == GIF_ERROR) { /* PrintGifError(); */ rec = TERMINATE_RECORD_TYPE; break; } w = gif->Image.Width; h = gif->Image.Height; if (!IMAGE_DIMENSIONS_OK(w, h)) goto quit2; rows = calloc(h, sizeof(GifRowType *)); if (!rows) goto quit2; for (i = 0; i < h; i++) { rows[i] = calloc(w, sizeof(GifPixelType)); if (!rows[i]) goto quit; } if (gif->Image.Interlace) { for (i = 0; i < 4; i++) { for (j = intoffset[i]; j < h; j += intjump[i]) { DGifGetLine(gif, rows[j], w); } } } else { for (i = 0; i < h; i++) { DGifGetLine(gif, rows[i], w); } } done = 1; } else if (rec == EXTENSION_RECORD_TYPE) { int ext_code; GifByteType *ext; ext = NULL; DGifGetExtension(gif, &ext_code, &ext); while (ext) { if ((ext_code == 0xf9) && (ext[1] & 1) && (transp < 0)) { transp = (int)ext[4]; } ext = NULL; DGifGetExtensionNext(gif, &ext); } } } while (rec != TERMINATE_RECORD_TYPE); if (transp >= 0) { SET_FLAG(im->flags, F_HAS_ALPHA); } else { UNSET_FLAG(im->flags, F_HAS_ALPHA); } if (!rows) { goto quit2; } /* set the format string member to the lower-case full extension */ /* name for the format - so example names would be: */ /* "png", "jpeg", "tiff", "ppm", "pgm", "pbm", "gif", "xpm" ... */ im->w = w; im->h = h; if (!im->format) im->format = strdup("gif"); if (im->loader || immediate_load || progress) { bg = gif->SBackGroundColor; cmap = (gif->Image.ColorMap ? gif->Image.ColorMap : gif->SColorMap); im->data = (DATA32 *) malloc(sizeof(DATA32) * w * h); if (!im->data) goto quit; { r = cmap->Colors[bg].Red; g = cmap->Colors[bg].Green; b = cmap->Colors[bg].Blue; *ptr++ = 0x00ffffff & ((r << 16) | (g << 8) | b); } else { r = cmap->Colors[rows[i][j]].Red; g = cmap->Colors[rows[i][j]].Green; b = cmap->Colors[rows[i][j]].Blue; *ptr++ = (0xff << 24) | (r << 16) | (g << 8) | b; { for (j = 0; j < w; j++) { if (rows[i][j] == transp) { r = cmap->Colors[bg].Red; g = cmap->Colors[bg].Green; b = cmap->Colors[bg].Blue; *ptr++ = 0x00ffffff & ((r << 16) | (g << 8) | b); } else { r = cmap->Colors[rows[i][j]].Red; g = cmap->Colors[rows[i][j]].Green; b = cmap->Colors[rows[i][j]].Blue; *ptr++ = (0xff << 24) | (r << 16) | (g << 8) | b; } per += per_inc; if (progress && (((int)per) != last_per) && (((int)per) % progress_granularity == 0)) { rc = 2; goto quit; } last_y = i; } } } finish: if (progress) progress(im, 100, 0, last_y, w, h); } rc = 1; /* Success */ quit: for (i = 0; i < h; i++) free(rows[i]); free(rows); quit2: #if GIFLIB_MAJOR > 5 || (GIFLIB_MAJOR == 5 && GIFLIB_MINOR >= 1) DGifCloseFile(gif, NULL); #else DGifCloseFile(gif); #endif return rc; }
[ "CWE-119" ]
enlightment
37a96801663b7b4cd3fbe56cc0eb8b6a17e766a8
29413401693515776488286177132255863480
178,251
289
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
load(ImlibImage * im, ImlibProgressFunction progress, char progress_granularity, char immediate_load) { static const int intoffset[] = { 0, 4, 2, 1 }; static const int intjump[] = { 8, 8, 4, 2 }; int rc; DATA32 *ptr; GifFileType *gif; GifRowType *rows; GifRecordType rec; ColorMapObject *cmap; int i, j, done, bg, r, g, b, w = 0, h = 0; float per = 0.0, per_inc; int last_per = 0, last_y = 0; int transp; int fd; done = 0; rows = NULL; transp = -1; /* if immediate_load is 1, then dont delay image laoding as below, or */ /* already data in this image - dont load it again */ if (im->data) return 0; fd = open(im->real_file, O_RDONLY); if (fd < 0) return 0; #if GIFLIB_MAJOR >= 5 gif = DGifOpenFileHandle(fd, NULL); #else gif = DGifOpenFileHandle(fd); #endif if (!gif) { close(fd); return 0; } rc = 0; /* Failure */ do { if (DGifGetRecordType(gif, &rec) == GIF_ERROR) { /* PrintGifError(); */ rec = TERMINATE_RECORD_TYPE; } if ((rec == IMAGE_DESC_RECORD_TYPE) && (!done)) { if (DGifGetImageDesc(gif) == GIF_ERROR) { /* PrintGifError(); */ rec = TERMINATE_RECORD_TYPE; break; } w = gif->Image.Width; h = gif->Image.Height; if (!IMAGE_DIMENSIONS_OK(w, h)) goto quit2; rows = calloc(h, sizeof(GifRowType *)); if (!rows) goto quit2; for (i = 0; i < h; i++) { rows[i] = calloc(w, sizeof(GifPixelType)); if (!rows[i]) goto quit; } if (gif->Image.Interlace) { for (i = 0; i < 4; i++) { for (j = intoffset[i]; j < h; j += intjump[i]) { DGifGetLine(gif, rows[j], w); } } } else { for (i = 0; i < h; i++) { DGifGetLine(gif, rows[i], w); } } done = 1; } else if (rec == EXTENSION_RECORD_TYPE) { int ext_code; GifByteType *ext; ext = NULL; DGifGetExtension(gif, &ext_code, &ext); while (ext) { if ((ext_code == 0xf9) && (ext[1] & 1) && (transp < 0)) { transp = (int)ext[4]; } ext = NULL; DGifGetExtensionNext(gif, &ext); } } } while (rec != TERMINATE_RECORD_TYPE); if (transp >= 0) { SET_FLAG(im->flags, F_HAS_ALPHA); } else { UNSET_FLAG(im->flags, F_HAS_ALPHA); } if (!rows) { goto quit2; } /* set the format string member to the lower-case full extension */ /* name for the format - so example names would be: */ /* "png", "jpeg", "tiff", "ppm", "pgm", "pbm", "gif", "xpm" ... */ im->w = w; im->h = h; if (!im->format) im->format = strdup("gif"); if (im->loader || immediate_load || progress) { DATA32 colormap[256]; bg = gif->SBackGroundColor; cmap = (gif->Image.ColorMap ? gif->Image.ColorMap : gif->SColorMap); memset (colormap, 0, sizeof(colormap)); if (cmap != NULL) { for (i = cmap->ColorCount > 256 ? 256 : cmap->ColorCount; i-- > 0;) { r = cmap->Colors[i].Red; g = cmap->Colors[i].Green; b = cmap->Colors[i].Blue; colormap[i] = (0xff << 24) | (r << 16) | (g << 8) | b; } /* if bg > cmap->ColorCount, it is transparent black already */ if (transp >= 0 && transp < 256) colormap[transp] = bg >= 0 && bg < 256 ? colormap[bg] & 0x00ffffff : 0x00000000; } im->data = (DATA32 *) malloc(sizeof(DATA32) * w * h); if (!im->data) goto quit; { r = cmap->Colors[bg].Red; g = cmap->Colors[bg].Green; b = cmap->Colors[bg].Blue; *ptr++ = 0x00ffffff & ((r << 16) | (g << 8) | b); } else { r = cmap->Colors[rows[i][j]].Red; g = cmap->Colors[rows[i][j]].Green; b = cmap->Colors[rows[i][j]].Blue; *ptr++ = (0xff << 24) | (r << 16) | (g << 8) | b; { for (j = 0; j < w; j++) { *ptr++ = colormap[rows[i][j]]; per += per_inc; if (progress && (((int)per) != last_per) && (((int)per) % progress_granularity == 0)) { rc = 2; goto quit; } last_y = i; } } } finish: if (progress) progress(im, 100, 0, last_y, w, h); } rc = 1; /* Success */ quit: for (i = 0; i < h; i++) free(rows[i]); free(rows); quit2: #if GIFLIB_MAJOR > 5 || (GIFLIB_MAJOR == 5 && GIFLIB_MINOR >= 1) DGifCloseFile(gif, NULL); #else DGifCloseFile(gif); #endif return rc; }
[ "CWE-119" ]
enlightment
37a96801663b7b4cd3fbe56cc0eb8b6a17e766a8
327794120807518814236575440422420435138
178,251
158,149
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
__imlib_MergeUpdate(ImlibUpdate * u, int w, int h, int hgapmax) { ImlibUpdate *nu = NULL, *uu; struct _tile *t; int tw, th, x, y, i; int *gaps = NULL; /* if theres no rects to process.. return NULL */ if (!u) return NULL; tw = w >> TB; if (w & TM) tw++; th = h >> TB; if (h & TM) th++; t = malloc(tw * th * sizeof(struct _tile)); /* fill in tiles to be all not used */ for (i = 0, y = 0; y < th; y++) { for (x = 0; x < tw; x++) t[i++].used = T_UNUSED; } /* fill in all tiles */ for (uu = u; uu; uu = uu->next) { CLIP(uu->x, uu->y, uu->w, uu->h, 0, 0, w, h); for (y = uu->y >> TB; y <= ((uu->y + uu->h - 1) >> TB); y++) { for (x = uu->x >> TB; x <= ((uu->x + uu->w - 1) >> TB); x++) T(x, y).used = T_USED; } } /* scan each line - if > hgapmax gaps between tiles, then fill smallest */ gaps = malloc(tw * sizeof(int)); for (y = 0; y < th; y++) { int hgaps = 0, start = -1, min; char have = 1, gap = 0; for (x = 0; x < tw; x++) gaps[x] = 0; for (x = 0; x < tw; x++) { if ((have) && (T(x, y).used == T_UNUSED)) { start = x; gap = 1; have = 0; } else if ((!have) && (gap) && (T(x, y).used & T_USED)) { gap = 0; hgaps++; have = 1; gaps[start] = x - start; } else if (T(x, y).used & T_USED) have = 1; } while (hgaps > hgapmax) { start = -1; min = tw; for (x = 0; x < tw; x++) { if ((gaps[x] > 0) && (gaps[x] < min)) { start = x; min = gaps[x]; } } if (start >= 0) { gaps[start] = 0; for (x = start; T(x, y).used == T_UNUSED; T(x++, y).used = T_USED); hgaps--; } } } free(gaps); /* coalesce tiles into larger blocks and make new rect list */ for (y = 0; y < th; y++) { for (x = 0; x < tw; x++) { if (T(x, y).used & T_USED) { int xx, yy, ww, hh, ok, xww; for (xx = x + 1, ww = 1; (T(xx, y).used & T_USED) && (xx < tw); xx++, ww++); xww = x + ww; for (yy = y + 1, hh = 1, ok = 1; (yy < th) && (ok); yy++, hh++) { for (xx = x; xx < xww; xx++) { if (!(T(xx, yy).used & T_USED)) { ok = 0; hh--; break; } } } for (yy = y; yy < (y + hh); yy++) { for (xx = x; xx < xww; xx++) T(xx, yy).used = T_UNUSED; } nu = __imlib_AddUpdate(nu, (x << TB), (y << TB), (ww << TB), (hh << TB)); } } } free(t); __imlib_FreeUpdates(u); return nu; }
[ "CWE-119" ]
enlightment
ce94edca1ccfbe314cb7cd9453433fad404ec7ef
36599931638812584056030971307038057704
178,252
290
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
true
__imlib_MergeUpdate(ImlibUpdate * u, int w, int h, int hgapmax) { ImlibUpdate *nu = NULL, *uu; struct _tile *t; int tw, th, x, y, i; int *gaps = NULL; /* if theres no rects to process.. return NULL */ if (!u) return NULL; tw = w >> TB; if (w & TM) tw++; th = h >> TB; if (h & TM) th++; t = malloc(tw * th * sizeof(struct _tile)); /* fill in tiles to be all not used */ for (i = 0, y = 0; y < th; y++) { for (x = 0; x < tw; x++) t[i++].used = T_UNUSED; } /* fill in all tiles */ for (uu = u; uu; uu = uu->next) { CLIP(uu->x, uu->y, uu->w, uu->h, 0, 0, w, h); for (y = uu->y >> TB; y <= ((uu->y + uu->h - 1) >> TB); y++) { for (x = uu->x >> TB; x <= ((uu->x + uu->w - 1) >> TB); x++) T(x, y).used = T_USED; } } /* scan each line - if > hgapmax gaps between tiles, then fill smallest */ gaps = malloc(tw * sizeof(int)); for (y = 0; y < th; y++) { int hgaps = 0, start = -1, min; char have = 1, gap = 0; for (x = 0; x < tw; x++) gaps[x] = 0; for (x = 0; x < tw; x++) { if ((have) && (T(x, y).used == T_UNUSED)) { start = x; gap = 1; have = 0; } else if ((!have) && (gap) && (T(x, y).used & T_USED)) { gap = 0; hgaps++; have = 1; gaps[start] = x - start; } else if (T(x, y).used & T_USED) have = 1; } while (hgaps > hgapmax) { start = -1; min = tw; for (x = 0; x < tw; x++) { if ((gaps[x] > 0) && (gaps[x] < min)) { start = x; min = gaps[x]; } } if (start >= 0) { gaps[start] = 0; for (x = start; T(x, y).used == T_UNUSED; T(x++, y).used = T_USED); hgaps--; } } } free(gaps); /* coalesce tiles into larger blocks and make new rect list */ for (y = 0; y < th; y++) { for (x = 0; x < tw; x++) { if (T(x, y).used & T_USED) { int xx, yy, ww, hh, ok, xww; for (xx = x + 1, ww = 1; (xx < tw) && (T(xx, y).used & T_USED); xx++, ww++); xww = x + ww; for (yy = y + 1, hh = 1, ok = 1; (yy < th) && (ok); yy++, hh++) { for (xx = x; xx < xww; xx++) { if (!(T(xx, yy).used & T_USED)) { ok = 0; hh--; break; } } } for (yy = y; yy < (y + hh); yy++) { for (xx = x; xx < xww; xx++) T(xx, yy).used = T_UNUSED; } nu = __imlib_AddUpdate(nu, (x << TB), (y << TB), (ww << TB), (hh << TB)); } } } free(t); __imlib_FreeUpdates(u); return nu; }
[ "CWE-119" ]
enlightment
ce94edca1ccfbe314cb7cd9453433fad404ec7ef
35689730528572601890660899349736969741
178,252
158,150
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
false
_gnutls_ciphertext2compressed (gnutls_session_t session, opaque * compress_data, int compress_size, gnutls_datum_t ciphertext, uint8_t type, record_parameters_st * params) { uint8_t MAC[MAX_HASH_SIZE]; uint16_t c_length; uint8_t pad; int length; uint16_t blocksize; int ret, i, pad_failed = 0; opaque preamble[PREAMBLE_SIZE]; int preamble_size; int ver = gnutls_protocol_get_version (session); int hash_size = _gnutls_hash_get_algo_len (params->mac_algorithm); blocksize = gnutls_cipher_get_block_size (params->cipher_algorithm); /* actual decryption (inplace) */ switch (_gnutls_cipher_is_block (params->cipher_algorithm)) { case CIPHER_STREAM: if ((ret = _gnutls_cipher_decrypt (&params->read.cipher_state, ciphertext.data, ciphertext.size)) < 0) { gnutls_assert (); return ret; } length = ciphertext.size - hash_size; break; case CIPHER_BLOCK: if ((ciphertext.size < blocksize) || (ciphertext.size % blocksize != 0)) { gnutls_assert (); return GNUTLS_E_DECRYPTION_FAILED; } if ((ret = _gnutls_cipher_decrypt (&params->read.cipher_state, ciphertext.data, ciphertext.size)) < 0) { gnutls_assert (); return ret; } /* ignore the IV in TLS 1.1. */ if (_gnutls_version_has_explicit_iv (session->security_parameters.version)) { ciphertext.size -= blocksize; ciphertext.data += blocksize; if (ciphertext.size == 0) { gnutls_assert (); return GNUTLS_E_DECRYPTION_FAILED; } } pad = ciphertext.data[ciphertext.size - 1] + 1; /* pad */ if ((int) pad > (int) ciphertext.size - hash_size) if ((int) pad > (int) ciphertext.size - hash_size) { gnutls_assert (); _gnutls_record_log ("REC[%p]: Short record length %d > %d - %d (under attack?)\n", session, pad, ciphertext.size, hash_size); /* We do not fail here. We check below for the * the pad_failed. If zero means success. */ pad_failed = GNUTLS_E_DECRYPTION_FAILED; } length = ciphertext.size - hash_size - pad; /* Check the pading bytes (TLS 1.x) */ if (_gnutls_version_has_variable_padding (ver) && pad_failed == 0) for (i = 2; i < pad; i++) { if (ciphertext.data[ciphertext.size - i] != ciphertext.data[ciphertext.size - 1]) pad_failed = GNUTLS_E_DECRYPTION_FAILED; } break; default: gnutls_assert (); return GNUTLS_E_INTERNAL_ERROR; } if (length < 0) length = 0; c_length = _gnutls_conv_uint16 ((uint16_t) length); /* Pass the type, version, length and compressed through * MAC. */ if (params->mac_algorithm != GNUTLS_MAC_NULL) { digest_hd_st td; ret = mac_init (&td, params->mac_algorithm, params->read.mac_secret.data, params->read.mac_secret.size, ver); if (ret < 0) { gnutls_assert (); return GNUTLS_E_INTERNAL_ERROR; } preamble_size = make_preamble (UINT64DATA (params->read.sequence_number), type, c_length, ver, preamble); mac_hash (&td, preamble, preamble_size, ver); if (length > 0) mac_hash (&td, ciphertext.data, length, ver); mac_deinit (&td, MAC, ver); } /* This one was introduced to avoid a timing attack against the TLS * 1.0 protocol. */ if (pad_failed != 0) { gnutls_assert (); return pad_failed; } /* HMAC was not the same. */ if (memcmp (MAC, &ciphertext.data[length], hash_size) != 0) { gnutls_assert (); return GNUTLS_E_DECRYPTION_FAILED; } /* copy the decrypted stuff to compress_data. */ if (compress_size < length) { gnutls_assert (); return GNUTLS_E_DECOMPRESSION_FAILED; } memcpy (compress_data, ciphertext.data, length); return length; }
[ "CWE-310" ]
savannah
422214868061370aeeb0ac9cd0f021a5c350a57d
124737111803029213599184263327276296012
178,253
291
This weakness pertains to the use of cryptographic functions that are weak, misconfigured, or outdated, which undermines the intended protection of encrypted data and communications.
true
_gnutls_ciphertext2compressed (gnutls_session_t session, opaque * compress_data, int compress_size, gnutls_datum_t ciphertext, uint8_t type, record_parameters_st * params) { uint8_t MAC[MAX_HASH_SIZE]; uint16_t c_length; uint8_t pad; int length; uint16_t blocksize; int ret, i, pad_failed = 0; opaque preamble[PREAMBLE_SIZE]; int preamble_size; int ver = gnutls_protocol_get_version (session); int hash_size = _gnutls_hash_get_algo_len (params->mac_algorithm); blocksize = gnutls_cipher_get_block_size (params->cipher_algorithm); /* actual decryption (inplace) */ switch (_gnutls_cipher_is_block (params->cipher_algorithm)) { case CIPHER_STREAM: if ((ret = _gnutls_cipher_decrypt (&params->read.cipher_state, ciphertext.data, ciphertext.size)) < 0) { gnutls_assert (); return ret; } length = ciphertext.size - hash_size; break; case CIPHER_BLOCK: if ((ciphertext.size < blocksize) || (ciphertext.size % blocksize != 0)) { gnutls_assert (); return GNUTLS_E_DECRYPTION_FAILED; } if ((ret = _gnutls_cipher_decrypt (&params->read.cipher_state, ciphertext.data, ciphertext.size)) < 0) { gnutls_assert (); return ret; } /* ignore the IV in TLS 1.1. */ if (_gnutls_version_has_explicit_iv (session->security_parameters.version)) { ciphertext.size -= blocksize; ciphertext.data += blocksize; } if (ciphertext.size < hash_size) { gnutls_assert (); return GNUTLS_E_DECRYPTION_FAILED; } pad = ciphertext.data[ciphertext.size - 1] + 1; /* pad */ if ((int) pad > (int) ciphertext.size - hash_size) if ((int) pad > (int) ciphertext.size - hash_size) { gnutls_assert (); _gnutls_record_log ("REC[%p]: Short record length %d > %d - %d (under attack?)\n", session, pad, ciphertext.size, hash_size); /* We do not fail here. We check below for the * the pad_failed. If zero means success. */ pad_failed = GNUTLS_E_DECRYPTION_FAILED; } length = ciphertext.size - hash_size - pad; /* Check the pading bytes (TLS 1.x) */ if (_gnutls_version_has_variable_padding (ver) && pad_failed == 0) for (i = 2; i < pad; i++) { if (ciphertext.data[ciphertext.size - i] != ciphertext.data[ciphertext.size - 1]) pad_failed = GNUTLS_E_DECRYPTION_FAILED; } break; default: gnutls_assert (); return GNUTLS_E_INTERNAL_ERROR; } if (length < 0) length = 0; c_length = _gnutls_conv_uint16 ((uint16_t) length); /* Pass the type, version, length and compressed through * MAC. */ if (params->mac_algorithm != GNUTLS_MAC_NULL) { digest_hd_st td; ret = mac_init (&td, params->mac_algorithm, params->read.mac_secret.data, params->read.mac_secret.size, ver); if (ret < 0) { gnutls_assert (); return GNUTLS_E_INTERNAL_ERROR; } preamble_size = make_preamble (UINT64DATA (params->read.sequence_number), type, c_length, ver, preamble); mac_hash (&td, preamble, preamble_size, ver); if (length > 0) mac_hash (&td, ciphertext.data, length, ver); mac_deinit (&td, MAC, ver); } /* This one was introduced to avoid a timing attack against the TLS * 1.0 protocol. */ if (pad_failed != 0) { gnutls_assert (); return pad_failed; } /* HMAC was not the same. */ if (memcmp (MAC, &ciphertext.data[length], hash_size) != 0) { gnutls_assert (); return GNUTLS_E_DECRYPTION_FAILED; } /* copy the decrypted stuff to compress_data. */ if (compress_size < length) { gnutls_assert (); return GNUTLS_E_DECOMPRESSION_FAILED; } memcpy (compress_data, ciphertext.data, length); return length; }
[ "CWE-310" ]
savannah
422214868061370aeeb0ac9cd0f021a5c350a57d
86024422305750338389798766305319221010
178,253
158,151
This weakness pertains to the use of cryptographic functions that are weak, misconfigured, or outdated, which undermines the intended protection of encrypted data and communications.