idx int64 | func_before string | Vulnerability Classification string | vul int64 | func_after string | patch string | CWE ID string | lines_before string | lines_after string |
|---|---|---|---|---|---|---|---|---|
12,400 | pixman_image_create_bits_no_clear (pixman_format_code_t format,
int width,
int height,
uint32_t * bits,
int rowstride_bytes)
{
return create_bits_image_internal (
format, width, height, bits, rowstride_bytes, FALSE);
}
| DoS Exec Code Overflow | 0 | pixman_image_create_bits_no_clear (pixman_format_code_t format,
int width,
int height,
uint32_t * bits,
int rowstride_bytes)
{
return create_bits_image_internal (
format, width, height, bits, rowstride_bytes, FALSE);
}
| @@ -926,7 +926,7 @@ create_bits (pixman_format_code_t format,
if (_pixman_multiply_overflows_size (height, stride))
return NULL;
- buf_size = height * stride;
+ buf_size = (size_t)height * stride;
if (rowstride_bytes)
*rowstride_bytes = stride; | CWE-189 | null | null |
12,401 | replicate_pixel_32 (bits_image_t * bits,
int x,
int y,
int width,
uint32_t * buffer)
{
uint32_t color;
uint32_t *end;
color = bits->fetch_pixel_32 (bits, x, y);
end = buffer + width;
while (buffer < end)
*(buffer++) = color;
}
| DoS Exec Code Overflow | 0 | replicate_pixel_32 (bits_image_t * bits,
int x,
int y,
int width,
uint32_t * buffer)
{
uint32_t color;
uint32_t *end;
color = bits->fetch_pixel_32 (bits, x, y);
end = buffer + width;
while (buffer < end)
*(buffer++) = color;
}
| @@ -926,7 +926,7 @@ create_bits (pixman_format_code_t format,
if (_pixman_multiply_overflows_size (height, stride))
return NULL;
- buf_size = height * stride;
+ buf_size = (size_t)height * stride;
if (rowstride_bytes)
*rowstride_bytes = stride; | CWE-189 | null | null |
12,402 | formats(ImlibLoader * l)
{
static const char *const list_formats[] =
{ "pnm", "ppm", "pgm", "pbm", "pam" };
int i;
l->num_formats = sizeof(list_formats) / sizeof(char *);
l->formats = malloc(sizeof(char *) * l->num_formats);
for (i = 0; i < l->num_formats; i++)
l->formats[i] = strdup(list_formats[i]);
}
| DoS | 0 | formats(ImlibLoader * l)
{
static const char *const list_formats[] =
{ "pnm", "ppm", "pgm", "pbm", "pam" };
int i;
l->num_formats = sizeof(list_formats) / sizeof(char *);
l->formats = malloc(sizeof(char *) * l->num_formats);
for (i = 0; i < l->num_formats; i++)
l->formats[i] = strdup(list_formats[i]);
}
| @@ -229,7 +229,7 @@ load(ImlibImage * im, ImlibProgressFunction progress,
}
}
iptr = idata;
- if (v == 255)
+ if (v == 0 || v == 255)
{
for (x = 0; x < w; x++)
{
@@ -303,7 +303,7 @@ load(ImlibImage * im, ImlibProgressFunction progress,
}
}
iptr = idata;
- if (v == 255)
+ if (v == 0 || v == 255)
{
for (x = 0; x < w; x++)
{
@@ -376,7 +376,7 @@ load(ImlibImage * im, ImlibProgressFunction progress,
break;
ptr = data;
- if (v == 255)
+ if (v == 0 || v == 255)
{
for (x = 0; x < w; x++)
{
@@ -418,7 +418,7 @@ load(ImlibImage * im, ImlibProgressFunction progress,
break;
ptr = data;
- if (v == 255)
+ if (v == 0 || v == 255)
{
for (x = 0; x < w; x++)
{
@@ -493,7 +493,7 @@ load(ImlibImage * im, ImlibProgressFunction progress,
break;
ptr = data;
- if (v == 255)
+ if (v == 0 || v == 255)
{
for (x = 0; x < w; x++)
{ | CWE-189 | null | null |
12,403 | save(ImlibImage * im, ImlibProgressFunction progress, char progress_granularity)
{
int rc;
FILE *f;
DATA8 *buf, *bptr;
DATA32 *ptr;
int x, y, pl = 0;
char pper = 0;
/* no image data? abort */
if (!im->data)
return 0;
f = fopen(im->real_file, "wb");
if (!f)
return 0;
rc = 0; /* Error */
/* if the image has a useful alpha channel */
if (im->flags & F_HAS_ALPHA)
{
/* allocate a small buffer to convert image data */
buf = malloc(im->w * 4 * sizeof(DATA8));
if (!buf)
goto quit;
ptr = im->data;
fprintf(f, "P8\n" "# PNM File written by Imlib2\n" "%i %i\n" "255\n",
im->w, im->h);
for (y = 0; y < im->h; y++)
{
bptr = buf;
for (x = 0; x < im->w; x++)
{
bptr[0] = ((*ptr) >> 16) & 0xff;
bptr[1] = ((*ptr) >> 8) & 0xff;
bptr[2] = ((*ptr)) & 0xff;
bptr[3] = ((*ptr) >> 24) & 0xff;
bptr += 4;
ptr++;
}
fwrite(buf, im->w * 4, 1, f);
if (progress &&
do_progress(im, progress, progress_granularity, &pper, &pl, y))
goto quit_progress;
}
}
else
{
/* allocate a small buffer to convert image data */
buf = malloc(im->w * 3 * sizeof(DATA8));
if (!buf)
goto quit;
ptr = im->data;
fprintf(f, "P6\n" "# PNM File written by Imlib2\n" "%i %i\n" "255\n",
im->w, im->h);
for (y = 0; y < im->h; y++)
{
bptr = buf;
for (x = 0; x < im->w; x++)
{
bptr[0] = ((*ptr) >> 16) & 0xff;
bptr[1] = ((*ptr) >> 8) & 0xff;
bptr[2] = ((*ptr)) & 0xff;
bptr += 3;
ptr++;
}
fwrite(buf, im->w * 3, 1, f);
if (progress &&
do_progress(im, progress, progress_granularity, &pper, &pl, y))
goto quit_progress;
}
}
rc = 1; /* Ok */
/* finish off */
free(buf);
quit:
fclose(f);
return rc;
quit_progress:
rc = 2;
goto quit;
}
| DoS | 0 | save(ImlibImage * im, ImlibProgressFunction progress, char progress_granularity)
{
int rc;
FILE *f;
DATA8 *buf, *bptr;
DATA32 *ptr;
int x, y, pl = 0;
char pper = 0;
/* no image data? abort */
if (!im->data)
return 0;
f = fopen(im->real_file, "wb");
if (!f)
return 0;
rc = 0; /* Error */
/* if the image has a useful alpha channel */
if (im->flags & F_HAS_ALPHA)
{
/* allocate a small buffer to convert image data */
buf = malloc(im->w * 4 * sizeof(DATA8));
if (!buf)
goto quit;
ptr = im->data;
fprintf(f, "P8\n" "# PNM File written by Imlib2\n" "%i %i\n" "255\n",
im->w, im->h);
for (y = 0; y < im->h; y++)
{
bptr = buf;
for (x = 0; x < im->w; x++)
{
bptr[0] = ((*ptr) >> 16) & 0xff;
bptr[1] = ((*ptr) >> 8) & 0xff;
bptr[2] = ((*ptr)) & 0xff;
bptr[3] = ((*ptr) >> 24) & 0xff;
bptr += 4;
ptr++;
}
fwrite(buf, im->w * 4, 1, f);
if (progress &&
do_progress(im, progress, progress_granularity, &pper, &pl, y))
goto quit_progress;
}
}
else
{
/* allocate a small buffer to convert image data */
buf = malloc(im->w * 3 * sizeof(DATA8));
if (!buf)
goto quit;
ptr = im->data;
fprintf(f, "P6\n" "# PNM File written by Imlib2\n" "%i %i\n" "255\n",
im->w, im->h);
for (y = 0; y < im->h; y++)
{
bptr = buf;
for (x = 0; x < im->w; x++)
{
bptr[0] = ((*ptr) >> 16) & 0xff;
bptr[1] = ((*ptr) >> 8) & 0xff;
bptr[2] = ((*ptr)) & 0xff;
bptr += 3;
ptr++;
}
fwrite(buf, im->w * 3, 1, f);
if (progress &&
do_progress(im, progress, progress_granularity, &pper, &pl, y))
goto quit_progress;
}
}
rc = 1; /* Ok */
/* finish off */
free(buf);
quit:
fclose(f);
return rc;
quit_progress:
rc = 2;
goto quit;
}
| @@ -229,7 +229,7 @@ load(ImlibImage * im, ImlibProgressFunction progress,
}
}
iptr = idata;
- if (v == 255)
+ if (v == 0 || v == 255)
{
for (x = 0; x < w; x++)
{
@@ -303,7 +303,7 @@ load(ImlibImage * im, ImlibProgressFunction progress,
}
}
iptr = idata;
- if (v == 255)
+ if (v == 0 || v == 255)
{
for (x = 0; x < w; x++)
{
@@ -376,7 +376,7 @@ load(ImlibImage * im, ImlibProgressFunction progress,
break;
ptr = data;
- if (v == 255)
+ if (v == 0 || v == 255)
{
for (x = 0; x < w; x++)
{
@@ -418,7 +418,7 @@ load(ImlibImage * im, ImlibProgressFunction progress,
break;
ptr = data;
- if (v == 255)
+ if (v == 0 || v == 255)
{
for (x = 0; x < w; x++)
{
@@ -493,7 +493,7 @@ load(ImlibImage * im, ImlibProgressFunction progress,
break;
ptr = data;
- if (v == 255)
+ if (v == 0 || v == 255)
{
for (x = 0; x < w; x++)
{ | CWE-189 | null | null |
12,404 | cid_get_offset( FT_Byte* *start,
FT_Byte offsize )
{
FT_ULong result;
FT_Byte* p = *start;
for ( result = 0; offsize > 0; offsize-- )
{
result <<= 8;
result |= *p++;
}
*start = p;
return (FT_Long)result;
}
| DoS | 0 | cid_get_offset( FT_Byte* *start,
FT_Byte offsize )
{
FT_ULong result;
FT_Byte* p = *start;
for ( result = 0; offsize > 0; offsize-- )
{
result <<= 8;
result |= *p++;
}
*start = p;
return (FT_Long)result;
}
| @@ -4,7 +4,7 @@
/* */
/* CID-keyed Type1 font loader (body). */
/* */
-/* Copyright 1996-2006, 2009, 2011-2013 by */
+/* Copyright 1996-2006, 2009, 2011-2014 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
@@ -160,16 +160,26 @@
{
FT_Matrix* matrix;
FT_Vector* offset;
+ FT_Int result;
dict = face->cid.font_dicts + parser->num_dict;
matrix = &dict->font_matrix;
offset = &dict->font_offset;
- (void)cid_parser_to_fixed_array( parser, 6, temp, 3 );
+ result = cid_parser_to_fixed_array( parser, 6, temp, 3 );
+
+ if ( result < 6 )
+ return FT_THROW( Invalid_File_Format );
temp_scale = FT_ABS( temp[3] );
+ if ( temp_scale == 0 )
+ {
+ FT_ERROR(( "cid_parse_font_matrix: invalid font matrix\n" ));
+ return FT_THROW( Invalid_File_Format );
+ }
+
/* Set Units per EM based on FontMatrix values. We set the value to */
/* 1000 / temp_scale, because temp_scale was already multiplied by */
/* 1000 (in t1_tofixed, from psobjs.c). */
@@ -184,7 +194,7 @@
temp[2] = FT_DivFix( temp[2], temp_scale );
temp[4] = FT_DivFix( temp[4], temp_scale );
temp[5] = FT_DivFix( temp[5], temp_scale );
- temp[3] = 0x10000L;
+ temp[3] = temp[3] < 0 ? -0x10000L : 0x10000L;
}
matrix->xx = temp[0];
@@ -197,8 +207,7 @@
offset->y = temp[5] >> 16;
}
- return FT_Err_Ok; /* this is a callback function; */
- /* we must return an error code */
+ return FT_Err_Ok;
} | CWE-20 | null | null |
12,405 | cid_load_keyword( CID_Face face,
CID_Loader* loader,
const T1_Field keyword )
{
FT_Error error;
CID_Parser* parser = &loader->parser;
FT_Byte* object;
void* dummy_object;
CID_FaceInfo cid = &face->cid;
/* if the keyword has a dedicated callback, call it */
if ( keyword->type == T1_FIELD_TYPE_CALLBACK )
{
keyword->reader( (FT_Face)face, parser );
error = parser->root.error;
goto Exit;
}
/* we must now compute the address of our target object */
switch ( keyword->location )
{
case T1_FIELD_LOCATION_CID_INFO:
object = (FT_Byte*)cid;
break;
case T1_FIELD_LOCATION_FONT_INFO:
object = (FT_Byte*)&cid->font_info;
break;
case T1_FIELD_LOCATION_FONT_EXTRA:
object = (FT_Byte*)&face->font_extra;
break;
case T1_FIELD_LOCATION_BBOX:
object = (FT_Byte*)&cid->font_bbox;
break;
default:
{
CID_FaceDict dict;
if ( parser->num_dict < 0 || parser->num_dict >= cid->num_dicts )
{
FT_ERROR(( "cid_load_keyword: invalid use of `%s'\n",
keyword->ident ));
error = FT_THROW( Syntax_Error );
goto Exit;
}
dict = cid->font_dicts + parser->num_dict;
switch ( keyword->location )
{
case T1_FIELD_LOCATION_PRIVATE:
object = (FT_Byte*)&dict->private_dict;
break;
default:
object = (FT_Byte*)dict;
}
}
}
dummy_object = object;
/* now, load the keyword data in the object's field(s) */
if ( keyword->type == T1_FIELD_TYPE_INTEGER_ARRAY ||
keyword->type == T1_FIELD_TYPE_FIXED_ARRAY )
error = cid_parser_load_field_table( &loader->parser, keyword,
&dummy_object );
else
error = cid_parser_load_field( &loader->parser,
keyword, &dummy_object );
Exit:
return error;
}
| DoS | 0 | cid_load_keyword( CID_Face face,
CID_Loader* loader,
const T1_Field keyword )
{
FT_Error error;
CID_Parser* parser = &loader->parser;
FT_Byte* object;
void* dummy_object;
CID_FaceInfo cid = &face->cid;
/* if the keyword has a dedicated callback, call it */
if ( keyword->type == T1_FIELD_TYPE_CALLBACK )
{
keyword->reader( (FT_Face)face, parser );
error = parser->root.error;
goto Exit;
}
/* we must now compute the address of our target object */
switch ( keyword->location )
{
case T1_FIELD_LOCATION_CID_INFO:
object = (FT_Byte*)cid;
break;
case T1_FIELD_LOCATION_FONT_INFO:
object = (FT_Byte*)&cid->font_info;
break;
case T1_FIELD_LOCATION_FONT_EXTRA:
object = (FT_Byte*)&face->font_extra;
break;
case T1_FIELD_LOCATION_BBOX:
object = (FT_Byte*)&cid->font_bbox;
break;
default:
{
CID_FaceDict dict;
if ( parser->num_dict < 0 || parser->num_dict >= cid->num_dicts )
{
FT_ERROR(( "cid_load_keyword: invalid use of `%s'\n",
keyword->ident ));
error = FT_THROW( Syntax_Error );
goto Exit;
}
dict = cid->font_dicts + parser->num_dict;
switch ( keyword->location )
{
case T1_FIELD_LOCATION_PRIVATE:
object = (FT_Byte*)&dict->private_dict;
break;
default:
object = (FT_Byte*)dict;
}
}
}
dummy_object = object;
/* now, load the keyword data in the object's field(s) */
if ( keyword->type == T1_FIELD_TYPE_INTEGER_ARRAY ||
keyword->type == T1_FIELD_TYPE_FIXED_ARRAY )
error = cid_parser_load_field_table( &loader->parser, keyword,
&dummy_object );
else
error = cid_parser_load_field( &loader->parser,
keyword, &dummy_object );
Exit:
return error;
}
| @@ -4,7 +4,7 @@
/* */
/* CID-keyed Type1 font loader (body). */
/* */
-/* Copyright 1996-2006, 2009, 2011-2013 by */
+/* Copyright 1996-2006, 2009, 2011-2014 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
@@ -160,16 +160,26 @@
{
FT_Matrix* matrix;
FT_Vector* offset;
+ FT_Int result;
dict = face->cid.font_dicts + parser->num_dict;
matrix = &dict->font_matrix;
offset = &dict->font_offset;
- (void)cid_parser_to_fixed_array( parser, 6, temp, 3 );
+ result = cid_parser_to_fixed_array( parser, 6, temp, 3 );
+
+ if ( result < 6 )
+ return FT_THROW( Invalid_File_Format );
temp_scale = FT_ABS( temp[3] );
+ if ( temp_scale == 0 )
+ {
+ FT_ERROR(( "cid_parse_font_matrix: invalid font matrix\n" ));
+ return FT_THROW( Invalid_File_Format );
+ }
+
/* Set Units per EM based on FontMatrix values. We set the value to */
/* 1000 / temp_scale, because temp_scale was already multiplied by */
/* 1000 (in t1_tofixed, from psobjs.c). */
@@ -184,7 +194,7 @@
temp[2] = FT_DivFix( temp[2], temp_scale );
temp[4] = FT_DivFix( temp[4], temp_scale );
temp[5] = FT_DivFix( temp[5], temp_scale );
- temp[3] = 0x10000L;
+ temp[3] = temp[3] < 0 ? -0x10000L : 0x10000L;
}
matrix->xx = temp[0];
@@ -197,8 +207,7 @@
offset->y = temp[5] >> 16;
}
- return FT_Err_Ok; /* this is a callback function; */
- /* we must return an error code */
+ return FT_Err_Ok;
} | CWE-20 | null | null |
12,406 | parse_charstrings( T1_Face face,
T1_Loader loader )
{
T1_Parser parser = &loader->parser;
PS_Table code_table = &loader->charstrings;
PS_Table name_table = &loader->glyph_names;
PS_Table swap_table = &loader->swap_table;
FT_Memory memory = parser->root.memory;
FT_Error error;
PSAux_Service psaux = (PSAux_Service)face->psaux;
FT_Byte* cur;
FT_Byte* limit = parser->root.limit;
FT_Int n, num_glyphs;
FT_UInt notdef_index = 0;
FT_Byte notdef_found = 0;
num_glyphs = (FT_Int)T1_ToInt( parser );
if ( num_glyphs < 0 )
{
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* some fonts like Optima-Oblique not only define the /CharStrings */
/* array but access it also */
if ( num_glyphs == 0 || parser->root.error )
return;
/* initialize tables, leaving space for addition of .notdef, */
/* if necessary, and a few other glyphs to handle buggy */
/* fonts which have more glyphs than specified. */
/* for some non-standard fonts like `Optima' which provides */
/* different outlines depending on the resolution it is */
/* possible to get here twice */
if ( !loader->num_glyphs )
{
error = psaux->ps_table_funcs->init(
code_table, num_glyphs + 1 + TABLE_EXTEND, memory );
if ( error )
goto Fail;
error = psaux->ps_table_funcs->init(
name_table, num_glyphs + 1 + TABLE_EXTEND, memory );
if ( error )
goto Fail;
/* Initialize table for swapping index notdef_index and */
/* index 0 names and codes (if necessary). */
error = psaux->ps_table_funcs->init( swap_table, 4, memory );
if ( error )
goto Fail;
}
n = 0;
for (;;)
{
FT_Long size;
FT_Byte* base;
/* the format is simple: */
/* `/glyphname' + binary data */
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
if ( cur >= limit )
break;
/* we stop when we find a `def' or `end' keyword */
if ( cur + 3 < limit && IS_PS_DELIM( cur[3] ) )
{
if ( cur[0] == 'd' &&
cur[1] == 'e' &&
cur[2] == 'f' )
{
/* There are fonts which have this: */
/* */
/* /CharStrings 118 dict def */
/* Private begin */
/* CharStrings begin */
/* ... */
/* */
/* To catch this we ignore `def' if */
/* no charstring has actually been */
/* seen. */
if ( n )
break;
}
if ( cur[0] == 'e' &&
cur[1] == 'n' &&
cur[2] == 'd' )
break;
}
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
if ( *cur == '/' )
{
FT_PtrDist len;
if ( cur + 1 >= limit )
{
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
cur++; /* skip `/' */
len = parser->root.cursor - cur;
if ( !read_binary_data( parser, &size, &base, IS_INCREMENTAL ) )
return;
/* for some non-standard fonts like `Optima' which provides */
/* different outlines depending on the resolution it is */
/* possible to get here twice */
if ( loader->num_glyphs )
continue;
error = T1_Add_Table( name_table, n, cur, len + 1 );
if ( error )
goto Fail;
/* add a trailing zero to the name table */
name_table->elements[n][len] = '\0';
/* record index of /.notdef */
if ( *cur == '.' &&
ft_strcmp( ".notdef",
(const char*)(name_table->elements[n]) ) == 0 )
{
notdef_index = n;
notdef_found = 1;
}
if ( face->type1.private_dict.lenIV >= 0 &&
n < num_glyphs + TABLE_EXTEND )
{
FT_Byte* temp;
if ( size <= face->type1.private_dict.lenIV )
{
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* t1_decrypt() shouldn't write to base -- make temporary copy */
if ( FT_ALLOC( temp, size ) )
goto Fail;
FT_MEM_COPY( temp, base, size );
psaux->t1_decrypt( temp, size, 4330 );
size -= face->type1.private_dict.lenIV;
error = T1_Add_Table( code_table, n,
temp + face->type1.private_dict.lenIV, size );
FT_FREE( temp );
}
else
error = T1_Add_Table( code_table, n, base, size );
if ( error )
goto Fail;
n++;
}
}
loader->num_glyphs = n;
/* if /.notdef is found but does not occupy index 0, do our magic. */
if ( notdef_found &&
ft_strcmp( ".notdef", (const char*)name_table->elements[0] ) )
{
/* Swap glyph in index 0 with /.notdef glyph. First, add index 0 */
/* name and code entries to swap_table. Then place notdef_index */
/* name and code entries into swap_table. Then swap name and code */
/* entries at indices notdef_index and 0 using values stored in */
/* swap_table. */
/* Index 0 name */
error = T1_Add_Table( swap_table, 0,
name_table->elements[0],
name_table->lengths [0] );
if ( error )
goto Fail;
/* Index 0 code */
error = T1_Add_Table( swap_table, 1,
code_table->elements[0],
code_table->lengths [0] );
if ( error )
goto Fail;
/* Index notdef_index name */
error = T1_Add_Table( swap_table, 2,
name_table->elements[notdef_index],
name_table->lengths [notdef_index] );
if ( error )
goto Fail;
/* Index notdef_index code */
error = T1_Add_Table( swap_table, 3,
code_table->elements[notdef_index],
code_table->lengths [notdef_index] );
if ( error )
goto Fail;
error = T1_Add_Table( name_table, notdef_index,
swap_table->elements[0],
swap_table->lengths [0] );
if ( error )
goto Fail;
error = T1_Add_Table( code_table, notdef_index,
swap_table->elements[1],
swap_table->lengths [1] );
if ( error )
goto Fail;
error = T1_Add_Table( name_table, 0,
swap_table->elements[2],
swap_table->lengths [2] );
if ( error )
goto Fail;
error = T1_Add_Table( code_table, 0,
swap_table->elements[3],
swap_table->lengths [3] );
if ( error )
goto Fail;
}
else if ( !notdef_found )
{
/* notdef_index is already 0, or /.notdef is undefined in */
/* charstrings dictionary. Worry about /.notdef undefined. */
/* We take index 0 and add it to the end of the table(s) */
/* and add our own /.notdef glyph to index 0. */
/* 0 333 hsbw endchar */
FT_Byte notdef_glyph[] = { 0x8B, 0xF7, 0xE1, 0x0D, 0x0E };
char* notdef_name = (char *)".notdef";
error = T1_Add_Table( swap_table, 0,
name_table->elements[0],
name_table->lengths [0] );
if ( error )
goto Fail;
error = T1_Add_Table( swap_table, 1,
code_table->elements[0],
code_table->lengths [0] );
if ( error )
goto Fail;
error = T1_Add_Table( name_table, 0, notdef_name, 8 );
if ( error )
goto Fail;
error = T1_Add_Table( code_table, 0, notdef_glyph, 5 );
if ( error )
goto Fail;
error = T1_Add_Table( name_table, n,
swap_table->elements[0],
swap_table->lengths [0] );
if ( error )
goto Fail;
error = T1_Add_Table( code_table, n,
swap_table->elements[1],
swap_table->lengths [1] );
if ( error )
goto Fail;
/* we added a glyph. */
loader->num_glyphs += 1;
}
return;
Fail:
parser->root.error = error;
}
| DoS | 0 | parse_charstrings( T1_Face face,
T1_Loader loader )
{
T1_Parser parser = &loader->parser;
PS_Table code_table = &loader->charstrings;
PS_Table name_table = &loader->glyph_names;
PS_Table swap_table = &loader->swap_table;
FT_Memory memory = parser->root.memory;
FT_Error error;
PSAux_Service psaux = (PSAux_Service)face->psaux;
FT_Byte* cur;
FT_Byte* limit = parser->root.limit;
FT_Int n, num_glyphs;
FT_UInt notdef_index = 0;
FT_Byte notdef_found = 0;
num_glyphs = (FT_Int)T1_ToInt( parser );
if ( num_glyphs < 0 )
{
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* some fonts like Optima-Oblique not only define the /CharStrings */
/* array but access it also */
if ( num_glyphs == 0 || parser->root.error )
return;
/* initialize tables, leaving space for addition of .notdef, */
/* if necessary, and a few other glyphs to handle buggy */
/* fonts which have more glyphs than specified. */
/* for some non-standard fonts like `Optima' which provides */
/* different outlines depending on the resolution it is */
/* possible to get here twice */
if ( !loader->num_glyphs )
{
error = psaux->ps_table_funcs->init(
code_table, num_glyphs + 1 + TABLE_EXTEND, memory );
if ( error )
goto Fail;
error = psaux->ps_table_funcs->init(
name_table, num_glyphs + 1 + TABLE_EXTEND, memory );
if ( error )
goto Fail;
/* Initialize table for swapping index notdef_index and */
/* index 0 names and codes (if necessary). */
error = psaux->ps_table_funcs->init( swap_table, 4, memory );
if ( error )
goto Fail;
}
n = 0;
for (;;)
{
FT_Long size;
FT_Byte* base;
/* the format is simple: */
/* `/glyphname' + binary data */
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
if ( cur >= limit )
break;
/* we stop when we find a `def' or `end' keyword */
if ( cur + 3 < limit && IS_PS_DELIM( cur[3] ) )
{
if ( cur[0] == 'd' &&
cur[1] == 'e' &&
cur[2] == 'f' )
{
/* There are fonts which have this: */
/* */
/* /CharStrings 118 dict def */
/* Private begin */
/* CharStrings begin */
/* ... */
/* */
/* To catch this we ignore `def' if */
/* no charstring has actually been */
/* seen. */
if ( n )
break;
}
if ( cur[0] == 'e' &&
cur[1] == 'n' &&
cur[2] == 'd' )
break;
}
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
if ( *cur == '/' )
{
FT_PtrDist len;
if ( cur + 1 >= limit )
{
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
cur++; /* skip `/' */
len = parser->root.cursor - cur;
if ( !read_binary_data( parser, &size, &base, IS_INCREMENTAL ) )
return;
/* for some non-standard fonts like `Optima' which provides */
/* different outlines depending on the resolution it is */
/* possible to get here twice */
if ( loader->num_glyphs )
continue;
error = T1_Add_Table( name_table, n, cur, len + 1 );
if ( error )
goto Fail;
/* add a trailing zero to the name table */
name_table->elements[n][len] = '\0';
/* record index of /.notdef */
if ( *cur == '.' &&
ft_strcmp( ".notdef",
(const char*)(name_table->elements[n]) ) == 0 )
{
notdef_index = n;
notdef_found = 1;
}
if ( face->type1.private_dict.lenIV >= 0 &&
n < num_glyphs + TABLE_EXTEND )
{
FT_Byte* temp;
if ( size <= face->type1.private_dict.lenIV )
{
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* t1_decrypt() shouldn't write to base -- make temporary copy */
if ( FT_ALLOC( temp, size ) )
goto Fail;
FT_MEM_COPY( temp, base, size );
psaux->t1_decrypt( temp, size, 4330 );
size -= face->type1.private_dict.lenIV;
error = T1_Add_Table( code_table, n,
temp + face->type1.private_dict.lenIV, size );
FT_FREE( temp );
}
else
error = T1_Add_Table( code_table, n, base, size );
if ( error )
goto Fail;
n++;
}
}
loader->num_glyphs = n;
/* if /.notdef is found but does not occupy index 0, do our magic. */
if ( notdef_found &&
ft_strcmp( ".notdef", (const char*)name_table->elements[0] ) )
{
/* Swap glyph in index 0 with /.notdef glyph. First, add index 0 */
/* name and code entries to swap_table. Then place notdef_index */
/* name and code entries into swap_table. Then swap name and code */
/* entries at indices notdef_index and 0 using values stored in */
/* swap_table. */
/* Index 0 name */
error = T1_Add_Table( swap_table, 0,
name_table->elements[0],
name_table->lengths [0] );
if ( error )
goto Fail;
/* Index 0 code */
error = T1_Add_Table( swap_table, 1,
code_table->elements[0],
code_table->lengths [0] );
if ( error )
goto Fail;
/* Index notdef_index name */
error = T1_Add_Table( swap_table, 2,
name_table->elements[notdef_index],
name_table->lengths [notdef_index] );
if ( error )
goto Fail;
/* Index notdef_index code */
error = T1_Add_Table( swap_table, 3,
code_table->elements[notdef_index],
code_table->lengths [notdef_index] );
if ( error )
goto Fail;
error = T1_Add_Table( name_table, notdef_index,
swap_table->elements[0],
swap_table->lengths [0] );
if ( error )
goto Fail;
error = T1_Add_Table( code_table, notdef_index,
swap_table->elements[1],
swap_table->lengths [1] );
if ( error )
goto Fail;
error = T1_Add_Table( name_table, 0,
swap_table->elements[2],
swap_table->lengths [2] );
if ( error )
goto Fail;
error = T1_Add_Table( code_table, 0,
swap_table->elements[3],
swap_table->lengths [3] );
if ( error )
goto Fail;
}
else if ( !notdef_found )
{
/* notdef_index is already 0, or /.notdef is undefined in */
/* charstrings dictionary. Worry about /.notdef undefined. */
/* We take index 0 and add it to the end of the table(s) */
/* and add our own /.notdef glyph to index 0. */
/* 0 333 hsbw endchar */
FT_Byte notdef_glyph[] = { 0x8B, 0xF7, 0xE1, 0x0D, 0x0E };
char* notdef_name = (char *)".notdef";
error = T1_Add_Table( swap_table, 0,
name_table->elements[0],
name_table->lengths [0] );
if ( error )
goto Fail;
error = T1_Add_Table( swap_table, 1,
code_table->elements[0],
code_table->lengths [0] );
if ( error )
goto Fail;
error = T1_Add_Table( name_table, 0, notdef_name, 8 );
if ( error )
goto Fail;
error = T1_Add_Table( code_table, 0, notdef_glyph, 5 );
if ( error )
goto Fail;
error = T1_Add_Table( name_table, n,
swap_table->elements[0],
swap_table->lengths [0] );
if ( error )
goto Fail;
error = T1_Add_Table( code_table, n,
swap_table->elements[1],
swap_table->lengths [1] );
if ( error )
goto Fail;
/* we added a glyph. */
loader->num_glyphs += 1;
}
return;
Fail:
parser->root.error = error;
}
| @@ -4,7 +4,7 @@
/* */
/* Type 1 font loader (body). */
/* */
-/* Copyright 1996-2013 by */
+/* Copyright 1996-2014 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
@@ -1107,7 +1107,7 @@
result = T1_ToFixedArray( parser, 6, temp, 3 );
- if ( result < 0 )
+ if ( result < 6 )
{
parser->root.error = FT_THROW( Invalid_File_Format );
return; | CWE-20 | null | null |
12,407 | parse_encoding( T1_Face face,
T1_Loader loader )
{
T1_Parser parser = &loader->parser;
FT_Byte* cur;
FT_Byte* limit = parser->root.limit;
PSAux_Service psaux = (PSAux_Service)face->psaux;
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
if ( cur >= limit )
{
FT_ERROR(( "parse_encoding: out of bounds\n" ));
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
/* if we have a number or `[', the encoding is an array, */
/* and we must load it now */
if ( ft_isdigit( *cur ) || *cur == '[' )
{
T1_Encoding encode = &face->type1.encoding;
FT_Int count, n;
PS_Table char_table = &loader->encoding_table;
FT_Memory memory = parser->root.memory;
FT_Error error;
FT_Bool only_immediates = 0;
/* read the number of entries in the encoding; should be 256 */
if ( *cur == '[' )
{
count = 256;
only_immediates = 1;
parser->root.cursor++;
}
else
count = (FT_Int)T1_ToInt( parser );
T1_Skip_Spaces( parser );
if ( parser->root.cursor >= limit )
return;
/* we use a T1_Table to store our charnames */
loader->num_chars = encode->num_chars = count;
if ( FT_NEW_ARRAY( encode->char_index, count ) ||
FT_NEW_ARRAY( encode->char_name, count ) ||
FT_SET_ERROR( psaux->ps_table_funcs->init(
char_table, count, memory ) ) )
{
parser->root.error = error;
return;
}
/* We need to `zero' out encoding_table.elements */
for ( n = 0; n < count; n++ )
{
char* notdef = (char *)".notdef";
T1_Add_Table( char_table, n, notdef, 8 );
}
/* Now we need to read records of the form */
/* */
/* ... charcode /charname ... */
/* */
/* for each entry in our table. */
/* */
/* We simply look for a number followed by an immediate */
/* name. Note that this ignores correctly the sequence */
/* that is often seen in type1 fonts: */
/* */
/* 0 1 255 { 1 index exch /.notdef put } for dup */
/* */
/* used to clean the encoding array before anything else. */
/* */
/* Alternatively, if the array is directly given as */
/* */
/* /Encoding [ ... ] */
/* */
/* we only read immediates. */
n = 0;
T1_Skip_Spaces( parser );
while ( parser->root.cursor < limit )
{
cur = parser->root.cursor;
/* we stop when we encounter a `def' or `]' */
if ( *cur == 'd' && cur + 3 < limit )
{
if ( cur[1] == 'e' &&
cur[2] == 'f' &&
IS_PS_DELIM( cur[3] ) )
{
FT_TRACE6(( "encoding end\n" ));
cur += 3;
break;
}
}
if ( *cur == ']' )
{
FT_TRACE6(( "encoding end\n" ));
cur++;
break;
}
/* check whether we've found an entry */
if ( ft_isdigit( *cur ) || only_immediates )
{
FT_Int charcode;
if ( only_immediates )
charcode = n;
else
{
charcode = (FT_Int)T1_ToInt( parser );
T1_Skip_Spaces( parser );
}
cur = parser->root.cursor;
if ( cur + 2 < limit && *cur == '/' && n < count )
{
FT_PtrDist len;
cur++;
parser->root.cursor = cur;
T1_Skip_PS_Token( parser );
if ( parser->root.cursor >= limit )
return;
if ( parser->root.error )
return;
len = parser->root.cursor - cur;
parser->root.error = T1_Add_Table( char_table, charcode,
cur, len + 1 );
if ( parser->root.error )
return;
char_table->elements[charcode][len] = '\0';
n++;
}
else if ( only_immediates )
{
/* Since the current position is not updated for */
/* immediates-only mode we would get an infinite loop if */
/* we don't do anything here. */
/* */
/* This encoding array is not valid according to the type1 */
/* specification (it might be an encoding for a CID type1 */
/* font, however), so we conclude that this font is NOT a */
/* type1 font. */
parser->root.error = FT_THROW( Unknown_File_Format );
return;
}
}
else
{
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
}
T1_Skip_Spaces( parser );
}
face->type1.encoding_type = T1_ENCODING_TYPE_ARRAY;
parser->root.cursor = cur;
}
/* Otherwise, we should have either `StandardEncoding', */
/* `ExpertEncoding', or `ISOLatin1Encoding' */
else
{
if ( cur + 17 < limit &&
ft_strncmp( (const char*)cur, "StandardEncoding", 16 ) == 0 )
face->type1.encoding_type = T1_ENCODING_TYPE_STANDARD;
else if ( cur + 15 < limit &&
ft_strncmp( (const char*)cur, "ExpertEncoding", 14 ) == 0 )
face->type1.encoding_type = T1_ENCODING_TYPE_EXPERT;
else if ( cur + 18 < limit &&
ft_strncmp( (const char*)cur, "ISOLatin1Encoding", 17 ) == 0 )
face->type1.encoding_type = T1_ENCODING_TYPE_ISOLATIN1;
else
parser->root.error = FT_ERR( Ignore );
}
}
| DoS | 0 | parse_encoding( T1_Face face,
T1_Loader loader )
{
T1_Parser parser = &loader->parser;
FT_Byte* cur;
FT_Byte* limit = parser->root.limit;
PSAux_Service psaux = (PSAux_Service)face->psaux;
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
if ( cur >= limit )
{
FT_ERROR(( "parse_encoding: out of bounds\n" ));
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
/* if we have a number or `[', the encoding is an array, */
/* and we must load it now */
if ( ft_isdigit( *cur ) || *cur == '[' )
{
T1_Encoding encode = &face->type1.encoding;
FT_Int count, n;
PS_Table char_table = &loader->encoding_table;
FT_Memory memory = parser->root.memory;
FT_Error error;
FT_Bool only_immediates = 0;
/* read the number of entries in the encoding; should be 256 */
if ( *cur == '[' )
{
count = 256;
only_immediates = 1;
parser->root.cursor++;
}
else
count = (FT_Int)T1_ToInt( parser );
T1_Skip_Spaces( parser );
if ( parser->root.cursor >= limit )
return;
/* we use a T1_Table to store our charnames */
loader->num_chars = encode->num_chars = count;
if ( FT_NEW_ARRAY( encode->char_index, count ) ||
FT_NEW_ARRAY( encode->char_name, count ) ||
FT_SET_ERROR( psaux->ps_table_funcs->init(
char_table, count, memory ) ) )
{
parser->root.error = error;
return;
}
/* We need to `zero' out encoding_table.elements */
for ( n = 0; n < count; n++ )
{
char* notdef = (char *)".notdef";
T1_Add_Table( char_table, n, notdef, 8 );
}
/* Now we need to read records of the form */
/* */
/* ... charcode /charname ... */
/* */
/* for each entry in our table. */
/* */
/* We simply look for a number followed by an immediate */
/* name. Note that this ignores correctly the sequence */
/* that is often seen in type1 fonts: */
/* */
/* 0 1 255 { 1 index exch /.notdef put } for dup */
/* */
/* used to clean the encoding array before anything else. */
/* */
/* Alternatively, if the array is directly given as */
/* */
/* /Encoding [ ... ] */
/* */
/* we only read immediates. */
n = 0;
T1_Skip_Spaces( parser );
while ( parser->root.cursor < limit )
{
cur = parser->root.cursor;
/* we stop when we encounter a `def' or `]' */
if ( *cur == 'd' && cur + 3 < limit )
{
if ( cur[1] == 'e' &&
cur[2] == 'f' &&
IS_PS_DELIM( cur[3] ) )
{
FT_TRACE6(( "encoding end\n" ));
cur += 3;
break;
}
}
if ( *cur == ']' )
{
FT_TRACE6(( "encoding end\n" ));
cur++;
break;
}
/* check whether we've found an entry */
if ( ft_isdigit( *cur ) || only_immediates )
{
FT_Int charcode;
if ( only_immediates )
charcode = n;
else
{
charcode = (FT_Int)T1_ToInt( parser );
T1_Skip_Spaces( parser );
}
cur = parser->root.cursor;
if ( cur + 2 < limit && *cur == '/' && n < count )
{
FT_PtrDist len;
cur++;
parser->root.cursor = cur;
T1_Skip_PS_Token( parser );
if ( parser->root.cursor >= limit )
return;
if ( parser->root.error )
return;
len = parser->root.cursor - cur;
parser->root.error = T1_Add_Table( char_table, charcode,
cur, len + 1 );
if ( parser->root.error )
return;
char_table->elements[charcode][len] = '\0';
n++;
}
else if ( only_immediates )
{
/* Since the current position is not updated for */
/* immediates-only mode we would get an infinite loop if */
/* we don't do anything here. */
/* */
/* This encoding array is not valid according to the type1 */
/* specification (it might be an encoding for a CID type1 */
/* font, however), so we conclude that this font is NOT a */
/* type1 font. */
parser->root.error = FT_THROW( Unknown_File_Format );
return;
}
}
else
{
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
}
T1_Skip_Spaces( parser );
}
face->type1.encoding_type = T1_ENCODING_TYPE_ARRAY;
parser->root.cursor = cur;
}
/* Otherwise, we should have either `StandardEncoding', */
/* `ExpertEncoding', or `ISOLatin1Encoding' */
else
{
if ( cur + 17 < limit &&
ft_strncmp( (const char*)cur, "StandardEncoding", 16 ) == 0 )
face->type1.encoding_type = T1_ENCODING_TYPE_STANDARD;
else if ( cur + 15 < limit &&
ft_strncmp( (const char*)cur, "ExpertEncoding", 14 ) == 0 )
face->type1.encoding_type = T1_ENCODING_TYPE_EXPERT;
else if ( cur + 18 < limit &&
ft_strncmp( (const char*)cur, "ISOLatin1Encoding", 17 ) == 0 )
face->type1.encoding_type = T1_ENCODING_TYPE_ISOLATIN1;
else
parser->root.error = FT_ERR( Ignore );
}
}
| @@ -4,7 +4,7 @@
/* */
/* Type 1 font loader (body). */
/* */
-/* Copyright 1996-2013 by */
+/* Copyright 1996-2014 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
@@ -1107,7 +1107,7 @@
result = T1_ToFixedArray( parser, 6, temp, 3 );
- if ( result < 0 )
+ if ( result < 6 )
{
parser->root.error = FT_THROW( Invalid_File_Format );
return; | CWE-20 | null | null |
12,408 | _cdf_tole2(uint16_t sv)
{
uint16_t rv;
uint8_t *s = (uint8_t *)(void *)&sv;
uint8_t *d = (uint8_t *)(void *)&rv;
d[0] = s[1];
d[1] = s[0];
return rv;
}
| DoS | 0 | _cdf_tole2(uint16_t sv)
{
uint16_t rv;
uint8_t *s = (uint8_t *)(void *)&sv;
uint8_t *d = (uint8_t *)(void *)&rv;
d[0] = s[1];
d[1] = s[0];
return rv;
}
| @@ -35,7 +35,7 @@
#include "file.h"
#ifndef lint
-FILE_RCSID("@(#)$File: cdf.c,v 1.53 2013/02/26 16:20:42 christos Exp $")
+FILE_RCSID("@(#)$File: cdf.c,v 1.55 2014/02/27 23:26:17 christos Exp $")
#endif
#include <assert.h>
@@ -688,11 +688,13 @@ out:
int
cdf_read_short_stream(const cdf_info_t *info, const cdf_header_t *h,
- const cdf_sat_t *sat, const cdf_dir_t *dir, cdf_stream_t *scn)
+ const cdf_sat_t *sat, const cdf_dir_t *dir, cdf_stream_t *scn,
+ const cdf_directory_t **root)
{
size_t i;
const cdf_directory_t *d;
+ *root = NULL;
for (i = 0; i < dir->dir_len; i++)
if (dir->dir_tab[i].d_type == CDF_DIR_TYPE_ROOT_STORAGE)
break;
@@ -701,6 +703,7 @@ cdf_read_short_stream(const cdf_info_t *info, const cdf_header_t *h,
if (i == dir->dir_len)
goto out;
d = &dir->dir_tab[i];
+ *root = d;
/* If the it is not there, just fake it; some docs don't have it */
if (d->d_stream_first_sector < 0) | null | null | null |
12,409 | _cdf_tole8(uint64_t sv)
{
uint64_t rv;
uint8_t *s = (uint8_t *)(void *)&sv;
uint8_t *d = (uint8_t *)(void *)&rv;
d[0] = s[7];
d[1] = s[6];
d[2] = s[5];
d[3] = s[4];
d[4] = s[3];
d[5] = s[2];
d[6] = s[1];
d[7] = s[0];
return rv;
}
| DoS | 0 | _cdf_tole8(uint64_t sv)
{
uint64_t rv;
uint8_t *s = (uint8_t *)(void *)&sv;
uint8_t *d = (uint8_t *)(void *)&rv;
d[0] = s[7];
d[1] = s[6];
d[2] = s[5];
d[3] = s[4];
d[4] = s[3];
d[5] = s[2];
d[6] = s[1];
d[7] = s[0];
return rv;
}
| @@ -35,7 +35,7 @@
#include "file.h"
#ifndef lint
-FILE_RCSID("@(#)$File: cdf.c,v 1.53 2013/02/26 16:20:42 christos Exp $")
+FILE_RCSID("@(#)$File: cdf.c,v 1.55 2014/02/27 23:26:17 christos Exp $")
#endif
#include <assert.h>
@@ -688,11 +688,13 @@ out:
int
cdf_read_short_stream(const cdf_info_t *info, const cdf_header_t *h,
- const cdf_sat_t *sat, const cdf_dir_t *dir, cdf_stream_t *scn)
+ const cdf_sat_t *sat, const cdf_dir_t *dir, cdf_stream_t *scn,
+ const cdf_directory_t **root)
{
size_t i;
const cdf_directory_t *d;
+ *root = NULL;
for (i = 0; i < dir->dir_len; i++)
if (dir->dir_tab[i].d_type == CDF_DIR_TYPE_ROOT_STORAGE)
break;
@@ -701,6 +703,7 @@ cdf_read_short_stream(const cdf_info_t *info, const cdf_header_t *h,
if (i == dir->dir_len)
goto out;
d = &dir->dir_tab[i];
+ *root = d;
/* If the it is not there, just fake it; some docs don't have it */
if (d->d_stream_first_sector < 0) | null | null | null |
12,410 | cdf_check_stream_offset(const cdf_stream_t *sst, const cdf_header_t *h,
const void *p, size_t tail, int line)
{
const char *b = (const char *)sst->sst_tab;
const char *e = ((const char *)p) + tail;
(void)&line;
if (e >= b && (size_t)(e - b) <= CDF_SEC_SIZE(h) * sst->sst_len)
return 0;
DPRINTF(("%d: offset begin %p < end %p || %" SIZE_T_FORMAT "u"
" > %" SIZE_T_FORMAT "u [%" SIZE_T_FORMAT "u %"
SIZE_T_FORMAT "u]\n", line, b, e, (size_t)(e - b),
CDF_SEC_SIZE(h) * sst->sst_len, CDF_SEC_SIZE(h), sst->sst_len));
errno = EFTYPE;
return -1;
}
| DoS | 0 | cdf_check_stream_offset(const cdf_stream_t *sst, const cdf_header_t *h,
const void *p, size_t tail, int line)
{
const char *b = (const char *)sst->sst_tab;
const char *e = ((const char *)p) + tail;
(void)&line;
if (e >= b && (size_t)(e - b) <= CDF_SEC_SIZE(h) * sst->sst_len)
return 0;
DPRINTF(("%d: offset begin %p < end %p || %" SIZE_T_FORMAT "u"
" > %" SIZE_T_FORMAT "u [%" SIZE_T_FORMAT "u %"
SIZE_T_FORMAT "u]\n", line, b, e, (size_t)(e - b),
CDF_SEC_SIZE(h) * sst->sst_len, CDF_SEC_SIZE(h), sst->sst_len));
errno = EFTYPE;
return -1;
}
| @@ -35,7 +35,7 @@
#include "file.h"
#ifndef lint
-FILE_RCSID("@(#)$File: cdf.c,v 1.53 2013/02/26 16:20:42 christos Exp $")
+FILE_RCSID("@(#)$File: cdf.c,v 1.55 2014/02/27 23:26:17 christos Exp $")
#endif
#include <assert.h>
@@ -688,11 +688,13 @@ out:
int
cdf_read_short_stream(const cdf_info_t *info, const cdf_header_t *h,
- const cdf_sat_t *sat, const cdf_dir_t *dir, cdf_stream_t *scn)
+ const cdf_sat_t *sat, const cdf_dir_t *dir, cdf_stream_t *scn,
+ const cdf_directory_t **root)
{
size_t i;
const cdf_directory_t *d;
+ *root = NULL;
for (i = 0; i < dir->dir_len; i++)
if (dir->dir_tab[i].d_type == CDF_DIR_TYPE_ROOT_STORAGE)
break;
@@ -701,6 +703,7 @@ cdf_read_short_stream(const cdf_info_t *info, const cdf_header_t *h,
if (i == dir->dir_len)
goto out;
d = &dir->dir_tab[i];
+ *root = d;
/* If the it is not there, just fake it; some docs don't have it */
if (d->d_stream_first_sector < 0) | null | null | null |
12,411 | bool Tar::Create(const wxString& dmod_folder, double *compression_ratio, wxProgressDialog* aProgressDialog)
{
if (!bCanCompress)
return wxEmptyString;
wxString strCwd = ::wxGetCwd();
::wxSetWorkingDirectory(strCompressDir);
bool result = CreateReal(dmod_folder, compression_ratio, aProgressDialog);
::wxSetWorkingDirectory(strCwd);
return result;
}
| Dir. Trav. | 0 | bool Tar::Create(const wxString& dmod_folder, double *compression_ratio, wxProgressDialog* aProgressDialog)
{
if (!bCanCompress)
return wxEmptyString;
wxString strCwd = ::wxGetCwd();
::wxSetWorkingDirectory(strCompressDir);
bool result = CreateReal(dmod_folder, compression_ratio, aProgressDialog);
::wxSetWorkingDirectory(strCwd);
return result;
}
| @@ -3,7 +3,7 @@
* Copyright (C) 2004 Andrew Reading
* Copyright (C) 2005, 2006 Dan Walma
- * Copyright (C) 2008, 2014 Sylvain Beucler
+ * Copyright (C) 2008, 2014, 2018 Sylvain Beucler
* This file is part of GNU FreeDink
@@ -31,6 +31,7 @@
#include <wx/intl.h>
#include <wx/log.h>
#include <wx/filename.h>
+#include <wx/tokenzr.h>
#include <math.h>
#include <ext/stdio_filebuf.h>
@@ -427,7 +428,15 @@ int Tar::ReadHeaders( void )
wxString lPath(lRecord.Name, wxConvUTF8);
if (mInstalledDmodDirectory.Length() == 0)
{
- mInstalledDmodDirectory = lPath.SubString( 0, lPath.Find( '/' ) );
+ // Security: ensure the D-Mod directory is non-empty
+ wxString firstDir = GetFirstDir(lPath);
+ if (firstDir.IsSameAs("", true) || firstDir.IsSameAs("..", true) || firstDir.IsSameAs("dink", true))
+ {
+ wxLogError(_("Error: invalid D-Mod directory. Stopping."));
+ return 1;
+ }
+ mInstalledDmodDirectory = firstDir;
+
lDmodDizPath = mInstalledDmodDirectory + _T("dmod.diz");
lDmodDizPath.LowerCase();
}
@@ -472,10 +481,6 @@ int Tar::Extract(wxString destdir, wxProgressDialog* aProgressDialog)
wxString strBuf;
int lError = 0;
- // Remember current directory
- wxString strCwd = ::wxGetCwd();
-
-
// Open the file here so it doesn't error after changing.
wxFile wx_In(mFilePath, wxFile::read);
@@ -495,8 +500,6 @@ int Tar::Extract(wxString destdir, wxProgressDialog* aProgressDialog)
wxLogFatalError(_("Error: Cannot create directory '%s'. Cannot extract data."), destdir.c_str());
throw;
}
- // Move to the directory.
- ::wxSetWorkingDirectory(destdir);
// Put the data in the directories.
__gnu_cxx::stdio_filebuf<char> filebuf(wx_In.fd(), std::ios::in);
@@ -507,10 +510,6 @@ int Tar::Extract(wxString destdir, wxProgressDialog* aProgressDialog)
}
wx_In.Close();
-
- // We're done. Move back.
- ::wxSetWorkingDirectory(strCwd);
-
return lError;
}
@@ -527,10 +526,6 @@ int Tar::ExtractData(std::istream& aTarStreamIn, wxString destdir, wxProgressDia
aTarStreamIn.seekg(0, std::ios::beg);
lTotalBytes = lEnd - static_cast<unsigned long>(aTarStreamIn.tellg());
- // Move into the extract dir.
- wxString lPreviousWorkingDirectory(::wxGetCwd());
- ::wxSetWorkingDirectory(destdir);
-
// Extract the files.
int ebufsiz = 8192;
char buffer[ebufsiz];
@@ -543,7 +538,16 @@ int Tar::ExtractData(std::istream& aTarStreamIn, wxString destdir, wxProgressDia
/* Attempt convertion from latin-1 if not valid UTF-8 */
lCurrentFilePath = wxString(lCurrentTarRecord.Name, wxConvISO8859_1);
}
- wxString lCurrentDirectory(lCurrentFilePath.substr(0, lCurrentFilePath.find_last_of('/')));
+ // Security: check if archive tries to jump out of destination directory
+ if (IsPathInsecure(lCurrentFilePath))
+ {
+ wxLogError(_("Error: Insecure filename: '%s'. Stopping."), lCurrentFilePath);
+ lError = 1;
+ break;
+ }
+ // Security: ensure full, non-relative path, under destdir/
+ lCurrentFilePath = destdir + wxFileName::GetPathSeparator() + lCurrentFilePath;
+ wxString lCurrentDirectory = lCurrentFilePath.substr(0, lCurrentFilePath.find_last_of("/\\"));
// Odd bad file problem...
if (lCurrentFilePath.compare(_T("\xFF")) == 0) // "�"
@@ -612,7 +616,6 @@ int Tar::ExtractData(std::istream& aTarStreamIn, wxString destdir, wxProgressDia
}
}
aProgressDialog->Update(100, _("Done."));
- ::wxSetWorkingDirectory(lPreviousWorkingDirectory);
return lError;
}
@@ -687,3 +690,45 @@ int Tar::RoundTo512(int n)
return (n - (n % 512)) + 512;
}
}
+
+wxString Tar::GetFirstDir(wxString path) {
+ wxString firstDir = "";
+ wxString previousDir = "";
+ // tokenizer never returns empty strings + distinguish dir// and a/$
+ if (path.EndsWith("/") || path.EndsWith("\\"))
+ path += "dummy";
+ wxStringTokenizer tokenizer(path, "/\\", wxTOKEN_STRTOK);
+ while (tokenizer.HasMoreTokens()) {
+ wxString curDir = tokenizer.GetNextToken();
+ if (curDir == '.')
+ continue;
+ if (previousDir != "") {
+ firstDir = previousDir;
+ break;
+ }
+ previousDir = curDir;
+ }
+ return firstDir;
+}
+
+// Security: check if archive tries to jump out of destination directory
+bool Tar::IsPathInsecure(wxString path) {
+ // Avoid leading slashes (even if we preprend destdir)
+ if (path[0] == '/' || path[0] == '\\')
+ return true;
+ // Avoid ':' since wxFileName::Mkdir silently normalizes
+ // e.g. C:\test1\C:\test2 to C:\test2
+ if (path.Contains(":"))
+ return true;
+ // Ensure all files reside in the same subdirectory
+ if (GetFirstDir(path) != mInstalledDmodDirectory)
+ return true;
+ // Ensure there's no '..' path element
+ wxStringTokenizer tokenizer(path, "/\\");
+ while (tokenizer.HasMoreTokens()) {
+ wxString token = tokenizer.GetNextToken();
+ if (token == "..")
+ return true;
+ }
+ return false;
+} | CWE-22 | null | null |
12,412 | bool Tar::CreateReal(const wxString& dmod_folder, double *compression_ratio, wxProgressDialog* aProgressDialog)
{
bool aborted = false;
wxArrayString wxasFileList;
aProgressDialog->Update(0, _("Listing files..."));
IOUtils::GetAllDModFiles(strCompressDir, wxasFileList);
int iNumEntries = wxasFileList.GetCount();
fileinfo *fileinfos = new fileinfo[iNumEntries];
int total_file_data = 0;
for (unsigned int i = 0; i < wxasFileList.GetCount(); ++i)
{
fileinfos[i].fullpath = strCompressDir + _T("/") + wxasFileList.Item(i);
#if defined _WIN32 || defined __WIN32__ || defined __CYGWIN__
struct _stat sb;
if (_wstat(fileinfos[i].fullpath.fn_str(), &sb) < 0)
#else
struct stat sb;
if (stat(fileinfos[i].fullpath.fn_str(), &sb) < 0)
#endif
{
perror("stat");
fileinfos[i].mode = 0; // invalid, to skip
continue;
}
fileinfos[i].mode = sb.st_mode;
fileinfos[i].size = sb.st_size;
fileinfos[i].mtime = sb.st_mtime;
/* Preferred I/O block size */
#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
fileinfos[i].blksize = sb.st_blksize;
#else
fileinfos[i].blksize = 8192;
#endif
total_file_data += sb.st_size;
}
aProgressDialog->Update(0, _("Initializing..."));
FILE* out = fopen(mFilePath.fn_str(), "wb");
if (!out)
{
wxLogError(_("Error: Could not open tar file '%s' for bzip compression."), mFilePath.c_str());
return false;
}
/* libbz2 init */
BZFILE* bz_out = 0;
int iErr = 0;
int compress_factor = 9;
int debug_verbosity = 0;
int workFactor = 0;
bz_out = BZ2_bzWriteOpen(&iErr, out,
compress_factor,
debug_verbosity,
workFactor);
if (iErr != BZ_OK)
{
wxLogError(_("Error: Could not initialize compression method!"
" "
"Will not generate a correct .dmod file."
" "
"Quitting."));
fclose(out);
return false;
}
int total_file_data_written = 0;
for (unsigned int i = 0; i < wxasFileList.GetCount(); ++i)
{
if (aProgressDialog != NULL)
{
int lPercent = 98 * (long long)total_file_data_written / total_file_data;
aProgressDialog->Update(lPercent, wxasFileList.Item(i));
}
char header[512];
if (!FillHeader(wxasFileList.Item(i), dmod_folder, header, &fileinfos[i]))
continue;
BZ2_bzWrite(&iErr, bz_out, header, 512);
FILE *in = fopen(fileinfos[i].fullpath.fn_str(), "rb");
if (in == NULL)
{
wxLogFatalError(_("Error: File '%s' not found! Cannot archive file."),
fileinfos[i].fullpath.c_str());
throw;
}
int ebufsiz = fileinfos[i].blksize; // efficient buffer size
unsigned char* szBuf = (unsigned char*)malloc(ebufsiz);
int cur_file_nb_written = 0;
while(!feof(in))
{
int nb_read = fread(szBuf, 1, ebufsiz, in);
BZ2_bzWrite(&iErr, bz_out, szBuf, nb_read);
cur_file_nb_written += nb_read;
total_file_data_written += nb_read;
if (aProgressDialog != NULL)
{
int lPercent = 98 * (long long)total_file_data_written / total_file_data;
bool cont = aProgressDialog->Update(lPercent);
if (!cont)
{
aborted = true;
fclose(in);
free(szBuf);
goto clean_up;
}
}
}
fclose(in);
int iAmountToRound = (512 - (cur_file_nb_written % (512))) % 512;
memset(szBuf, 0, iAmountToRound);
BZ2_bzWrite(&iErr, bz_out, szBuf, iAmountToRound);
free(szBuf);
}
char eoa[2*512];
memset(eoa, 0, 2*512);
BZ2_bzWrite(&iErr, bz_out, eoa, 2*512);
clean_up:
aProgressDialog->Update(98, _("Closing..."));
int force_flush = 0; /* no force flush */
unsigned int nbytes_in = 0;
unsigned int nbytes_out = 0;
BZ2_bzWriteClose(&iErr, bz_out, force_flush, &nbytes_in, &nbytes_out);
*compression_ratio = (double) nbytes_in / nbytes_out;
fclose(out);
delete[] fileinfos;
aProgressDialog->Update(100); // Closes window
return !aborted;
}
| Dir. Trav. | 0 | bool Tar::CreateReal(const wxString& dmod_folder, double *compression_ratio, wxProgressDialog* aProgressDialog)
{
bool aborted = false;
wxArrayString wxasFileList;
aProgressDialog->Update(0, _("Listing files..."));
IOUtils::GetAllDModFiles(strCompressDir, wxasFileList);
int iNumEntries = wxasFileList.GetCount();
fileinfo *fileinfos = new fileinfo[iNumEntries];
int total_file_data = 0;
for (unsigned int i = 0; i < wxasFileList.GetCount(); ++i)
{
fileinfos[i].fullpath = strCompressDir + _T("/") + wxasFileList.Item(i);
#if defined _WIN32 || defined __WIN32__ || defined __CYGWIN__
struct _stat sb;
if (_wstat(fileinfos[i].fullpath.fn_str(), &sb) < 0)
#else
struct stat sb;
if (stat(fileinfos[i].fullpath.fn_str(), &sb) < 0)
#endif
{
perror("stat");
fileinfos[i].mode = 0; // invalid, to skip
continue;
}
fileinfos[i].mode = sb.st_mode;
fileinfos[i].size = sb.st_size;
fileinfos[i].mtime = sb.st_mtime;
/* Preferred I/O block size */
#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
fileinfos[i].blksize = sb.st_blksize;
#else
fileinfos[i].blksize = 8192;
#endif
total_file_data += sb.st_size;
}
aProgressDialog->Update(0, _("Initializing..."));
FILE* out = fopen(mFilePath.fn_str(), "wb");
if (!out)
{
wxLogError(_("Error: Could not open tar file '%s' for bzip compression."), mFilePath.c_str());
return false;
}
/* libbz2 init */
BZFILE* bz_out = 0;
int iErr = 0;
int compress_factor = 9;
int debug_verbosity = 0;
int workFactor = 0;
bz_out = BZ2_bzWriteOpen(&iErr, out,
compress_factor,
debug_verbosity,
workFactor);
if (iErr != BZ_OK)
{
wxLogError(_("Error: Could not initialize compression method!"
" "
"Will not generate a correct .dmod file."
" "
"Quitting."));
fclose(out);
return false;
}
int total_file_data_written = 0;
for (unsigned int i = 0; i < wxasFileList.GetCount(); ++i)
{
if (aProgressDialog != NULL)
{
int lPercent = 98 * (long long)total_file_data_written / total_file_data;
aProgressDialog->Update(lPercent, wxasFileList.Item(i));
}
char header[512];
if (!FillHeader(wxasFileList.Item(i), dmod_folder, header, &fileinfos[i]))
continue;
BZ2_bzWrite(&iErr, bz_out, header, 512);
FILE *in = fopen(fileinfos[i].fullpath.fn_str(), "rb");
if (in == NULL)
{
wxLogFatalError(_("Error: File '%s' not found! Cannot archive file."),
fileinfos[i].fullpath.c_str());
throw;
}
int ebufsiz = fileinfos[i].blksize; // efficient buffer size
unsigned char* szBuf = (unsigned char*)malloc(ebufsiz);
int cur_file_nb_written = 0;
while(!feof(in))
{
int nb_read = fread(szBuf, 1, ebufsiz, in);
BZ2_bzWrite(&iErr, bz_out, szBuf, nb_read);
cur_file_nb_written += nb_read;
total_file_data_written += nb_read;
if (aProgressDialog != NULL)
{
int lPercent = 98 * (long long)total_file_data_written / total_file_data;
bool cont = aProgressDialog->Update(lPercent);
if (!cont)
{
aborted = true;
fclose(in);
free(szBuf);
goto clean_up;
}
}
}
fclose(in);
int iAmountToRound = (512 - (cur_file_nb_written % (512))) % 512;
memset(szBuf, 0, iAmountToRound);
BZ2_bzWrite(&iErr, bz_out, szBuf, iAmountToRound);
free(szBuf);
}
char eoa[2*512];
memset(eoa, 0, 2*512);
BZ2_bzWrite(&iErr, bz_out, eoa, 2*512);
clean_up:
aProgressDialog->Update(98, _("Closing..."));
int force_flush = 0; /* no force flush */
unsigned int nbytes_in = 0;
unsigned int nbytes_out = 0;
BZ2_bzWriteClose(&iErr, bz_out, force_flush, &nbytes_in, &nbytes_out);
*compression_ratio = (double) nbytes_in / nbytes_out;
fclose(out);
delete[] fileinfos;
aProgressDialog->Update(100); // Closes window
return !aborted;
}
| @@ -3,7 +3,7 @@
* Copyright (C) 2004 Andrew Reading
* Copyright (C) 2005, 2006 Dan Walma
- * Copyright (C) 2008, 2014 Sylvain Beucler
+ * Copyright (C) 2008, 2014, 2018 Sylvain Beucler
* This file is part of GNU FreeDink
@@ -31,6 +31,7 @@
#include <wx/intl.h>
#include <wx/log.h>
#include <wx/filename.h>
+#include <wx/tokenzr.h>
#include <math.h>
#include <ext/stdio_filebuf.h>
@@ -427,7 +428,15 @@ int Tar::ReadHeaders( void )
wxString lPath(lRecord.Name, wxConvUTF8);
if (mInstalledDmodDirectory.Length() == 0)
{
- mInstalledDmodDirectory = lPath.SubString( 0, lPath.Find( '/' ) );
+ // Security: ensure the D-Mod directory is non-empty
+ wxString firstDir = GetFirstDir(lPath);
+ if (firstDir.IsSameAs("", true) || firstDir.IsSameAs("..", true) || firstDir.IsSameAs("dink", true))
+ {
+ wxLogError(_("Error: invalid D-Mod directory. Stopping."));
+ return 1;
+ }
+ mInstalledDmodDirectory = firstDir;
+
lDmodDizPath = mInstalledDmodDirectory + _T("dmod.diz");
lDmodDizPath.LowerCase();
}
@@ -472,10 +481,6 @@ int Tar::Extract(wxString destdir, wxProgressDialog* aProgressDialog)
wxString strBuf;
int lError = 0;
- // Remember current directory
- wxString strCwd = ::wxGetCwd();
-
-
// Open the file here so it doesn't error after changing.
wxFile wx_In(mFilePath, wxFile::read);
@@ -495,8 +500,6 @@ int Tar::Extract(wxString destdir, wxProgressDialog* aProgressDialog)
wxLogFatalError(_("Error: Cannot create directory '%s'. Cannot extract data."), destdir.c_str());
throw;
}
- // Move to the directory.
- ::wxSetWorkingDirectory(destdir);
// Put the data in the directories.
__gnu_cxx::stdio_filebuf<char> filebuf(wx_In.fd(), std::ios::in);
@@ -507,10 +510,6 @@ int Tar::Extract(wxString destdir, wxProgressDialog* aProgressDialog)
}
wx_In.Close();
-
- // We're done. Move back.
- ::wxSetWorkingDirectory(strCwd);
-
return lError;
}
@@ -527,10 +526,6 @@ int Tar::ExtractData(std::istream& aTarStreamIn, wxString destdir, wxProgressDia
aTarStreamIn.seekg(0, std::ios::beg);
lTotalBytes = lEnd - static_cast<unsigned long>(aTarStreamIn.tellg());
- // Move into the extract dir.
- wxString lPreviousWorkingDirectory(::wxGetCwd());
- ::wxSetWorkingDirectory(destdir);
-
// Extract the files.
int ebufsiz = 8192;
char buffer[ebufsiz];
@@ -543,7 +538,16 @@ int Tar::ExtractData(std::istream& aTarStreamIn, wxString destdir, wxProgressDia
/* Attempt convertion from latin-1 if not valid UTF-8 */
lCurrentFilePath = wxString(lCurrentTarRecord.Name, wxConvISO8859_1);
}
- wxString lCurrentDirectory(lCurrentFilePath.substr(0, lCurrentFilePath.find_last_of('/')));
+ // Security: check if archive tries to jump out of destination directory
+ if (IsPathInsecure(lCurrentFilePath))
+ {
+ wxLogError(_("Error: Insecure filename: '%s'. Stopping."), lCurrentFilePath);
+ lError = 1;
+ break;
+ }
+ // Security: ensure full, non-relative path, under destdir/
+ lCurrentFilePath = destdir + wxFileName::GetPathSeparator() + lCurrentFilePath;
+ wxString lCurrentDirectory = lCurrentFilePath.substr(0, lCurrentFilePath.find_last_of("/\\"));
// Odd bad file problem...
if (lCurrentFilePath.compare(_T("\xFF")) == 0) // "�"
@@ -612,7 +616,6 @@ int Tar::ExtractData(std::istream& aTarStreamIn, wxString destdir, wxProgressDia
}
}
aProgressDialog->Update(100, _("Done."));
- ::wxSetWorkingDirectory(lPreviousWorkingDirectory);
return lError;
}
@@ -687,3 +690,45 @@ int Tar::RoundTo512(int n)
return (n - (n % 512)) + 512;
}
}
+
+wxString Tar::GetFirstDir(wxString path) {
+ wxString firstDir = "";
+ wxString previousDir = "";
+ // tokenizer never returns empty strings + distinguish dir// and a/$
+ if (path.EndsWith("/") || path.EndsWith("\\"))
+ path += "dummy";
+ wxStringTokenizer tokenizer(path, "/\\", wxTOKEN_STRTOK);
+ while (tokenizer.HasMoreTokens()) {
+ wxString curDir = tokenizer.GetNextToken();
+ if (curDir == '.')
+ continue;
+ if (previousDir != "") {
+ firstDir = previousDir;
+ break;
+ }
+ previousDir = curDir;
+ }
+ return firstDir;
+}
+
+// Security: check if archive tries to jump out of destination directory
+bool Tar::IsPathInsecure(wxString path) {
+ // Avoid leading slashes (even if we preprend destdir)
+ if (path[0] == '/' || path[0] == '\\')
+ return true;
+ // Avoid ':' since wxFileName::Mkdir silently normalizes
+ // e.g. C:\test1\C:\test2 to C:\test2
+ if (path.Contains(":"))
+ return true;
+ // Ensure all files reside in the same subdirectory
+ if (GetFirstDir(path) != mInstalledDmodDirectory)
+ return true;
+ // Ensure there's no '..' path element
+ wxStringTokenizer tokenizer(path, "/\\");
+ while (tokenizer.HasMoreTokens()) {
+ wxString token = tokenizer.GetNextToken();
+ if (token == "..")
+ return true;
+ }
+ return false;
+} | CWE-22 | null | null |
12,413 | bool Tar::FillHeader(wxString &mFilePath, const wxString& dmod_folder, char *header512, fileinfo *finfo)
{
if (!S_ISREG(finfo->mode))
return false;
char* ptr = header512;
strncpy(ptr, (dmod_folder.Lower() + _T("/") + mFilePath.Lower()).mb_str(wxConvUTF8), 100);
ptr += 100;
strncpy(ptr, "0100644", 8);
ptr += 8;
strncpy(ptr, "0000000", 8);
ptr += 8;
strncpy(ptr, "0000000", 8);
ptr += 8;
sprintf(ptr, "%011o", finfo->size);
ptr += 12;
sprintf(ptr, "%011o", finfo->mtime);
ptr += 12;
memset(ptr, ' ', 8);
ptr += 8;
*ptr = '0'; // Normal file
ptr++;
strncpy(ptr, "", 100);
ptr += 100;
strncpy(ptr, "ustar ", 8);
ptr += 8;
strncpy(ptr, "root", 32);
ptr += 32;
strncpy(ptr, "root", 32);
ptr += 32;
strncpy(ptr, "", 8);
ptr += 8;
strncpy(ptr, "", 8);
ptr += 8;
strncpy(ptr, "", 167);
unsigned char* ptru = NULL; // use the (unsigned) ASCII value of characters
int iChksum = 0;
for (ptru = (unsigned char*) header512; ptru < (unsigned char*)(header512 + 512); ptru++)
iChksum += *ptru;
ptr = header512 + 148;
sprintf(ptr, "%07o", iChksum);
return true;
}
| Dir. Trav. | 0 | bool Tar::FillHeader(wxString &mFilePath, const wxString& dmod_folder, char *header512, fileinfo *finfo)
{
if (!S_ISREG(finfo->mode))
return false;
char* ptr = header512;
strncpy(ptr, (dmod_folder.Lower() + _T("/") + mFilePath.Lower()).mb_str(wxConvUTF8), 100);
ptr += 100;
strncpy(ptr, "0100644", 8);
ptr += 8;
strncpy(ptr, "0000000", 8);
ptr += 8;
strncpy(ptr, "0000000", 8);
ptr += 8;
sprintf(ptr, "%011o", finfo->size);
ptr += 12;
sprintf(ptr, "%011o", finfo->mtime);
ptr += 12;
memset(ptr, ' ', 8);
ptr += 8;
*ptr = '0'; // Normal file
ptr++;
strncpy(ptr, "", 100);
ptr += 100;
strncpy(ptr, "ustar ", 8);
ptr += 8;
strncpy(ptr, "root", 32);
ptr += 32;
strncpy(ptr, "root", 32);
ptr += 32;
strncpy(ptr, "", 8);
ptr += 8;
strncpy(ptr, "", 8);
ptr += 8;
strncpy(ptr, "", 167);
unsigned char* ptru = NULL; // use the (unsigned) ASCII value of characters
int iChksum = 0;
for (ptru = (unsigned char*) header512; ptru < (unsigned char*)(header512 + 512); ptru++)
iChksum += *ptru;
ptr = header512 + 148;
sprintf(ptr, "%07o", iChksum);
return true;
}
| @@ -3,7 +3,7 @@
* Copyright (C) 2004 Andrew Reading
* Copyright (C) 2005, 2006 Dan Walma
- * Copyright (C) 2008, 2014 Sylvain Beucler
+ * Copyright (C) 2008, 2014, 2018 Sylvain Beucler
* This file is part of GNU FreeDink
@@ -31,6 +31,7 @@
#include <wx/intl.h>
#include <wx/log.h>
#include <wx/filename.h>
+#include <wx/tokenzr.h>
#include <math.h>
#include <ext/stdio_filebuf.h>
@@ -427,7 +428,15 @@ int Tar::ReadHeaders( void )
wxString lPath(lRecord.Name, wxConvUTF8);
if (mInstalledDmodDirectory.Length() == 0)
{
- mInstalledDmodDirectory = lPath.SubString( 0, lPath.Find( '/' ) );
+ // Security: ensure the D-Mod directory is non-empty
+ wxString firstDir = GetFirstDir(lPath);
+ if (firstDir.IsSameAs("", true) || firstDir.IsSameAs("..", true) || firstDir.IsSameAs("dink", true))
+ {
+ wxLogError(_("Error: invalid D-Mod directory. Stopping."));
+ return 1;
+ }
+ mInstalledDmodDirectory = firstDir;
+
lDmodDizPath = mInstalledDmodDirectory + _T("dmod.diz");
lDmodDizPath.LowerCase();
}
@@ -472,10 +481,6 @@ int Tar::Extract(wxString destdir, wxProgressDialog* aProgressDialog)
wxString strBuf;
int lError = 0;
- // Remember current directory
- wxString strCwd = ::wxGetCwd();
-
-
// Open the file here so it doesn't error after changing.
wxFile wx_In(mFilePath, wxFile::read);
@@ -495,8 +500,6 @@ int Tar::Extract(wxString destdir, wxProgressDialog* aProgressDialog)
wxLogFatalError(_("Error: Cannot create directory '%s'. Cannot extract data."), destdir.c_str());
throw;
}
- // Move to the directory.
- ::wxSetWorkingDirectory(destdir);
// Put the data in the directories.
__gnu_cxx::stdio_filebuf<char> filebuf(wx_In.fd(), std::ios::in);
@@ -507,10 +510,6 @@ int Tar::Extract(wxString destdir, wxProgressDialog* aProgressDialog)
}
wx_In.Close();
-
- // We're done. Move back.
- ::wxSetWorkingDirectory(strCwd);
-
return lError;
}
@@ -527,10 +526,6 @@ int Tar::ExtractData(std::istream& aTarStreamIn, wxString destdir, wxProgressDia
aTarStreamIn.seekg(0, std::ios::beg);
lTotalBytes = lEnd - static_cast<unsigned long>(aTarStreamIn.tellg());
- // Move into the extract dir.
- wxString lPreviousWorkingDirectory(::wxGetCwd());
- ::wxSetWorkingDirectory(destdir);
-
// Extract the files.
int ebufsiz = 8192;
char buffer[ebufsiz];
@@ -543,7 +538,16 @@ int Tar::ExtractData(std::istream& aTarStreamIn, wxString destdir, wxProgressDia
/* Attempt convertion from latin-1 if not valid UTF-8 */
lCurrentFilePath = wxString(lCurrentTarRecord.Name, wxConvISO8859_1);
}
- wxString lCurrentDirectory(lCurrentFilePath.substr(0, lCurrentFilePath.find_last_of('/')));
+ // Security: check if archive tries to jump out of destination directory
+ if (IsPathInsecure(lCurrentFilePath))
+ {
+ wxLogError(_("Error: Insecure filename: '%s'. Stopping."), lCurrentFilePath);
+ lError = 1;
+ break;
+ }
+ // Security: ensure full, non-relative path, under destdir/
+ lCurrentFilePath = destdir + wxFileName::GetPathSeparator() + lCurrentFilePath;
+ wxString lCurrentDirectory = lCurrentFilePath.substr(0, lCurrentFilePath.find_last_of("/\\"));
// Odd bad file problem...
if (lCurrentFilePath.compare(_T("\xFF")) == 0) // "�"
@@ -612,7 +616,6 @@ int Tar::ExtractData(std::istream& aTarStreamIn, wxString destdir, wxProgressDia
}
}
aProgressDialog->Update(100, _("Done."));
- ::wxSetWorkingDirectory(lPreviousWorkingDirectory);
return lError;
}
@@ -687,3 +690,45 @@ int Tar::RoundTo512(int n)
return (n - (n % 512)) + 512;
}
}
+
+wxString Tar::GetFirstDir(wxString path) {
+ wxString firstDir = "";
+ wxString previousDir = "";
+ // tokenizer never returns empty strings + distinguish dir// and a/$
+ if (path.EndsWith("/") || path.EndsWith("\\"))
+ path += "dummy";
+ wxStringTokenizer tokenizer(path, "/\\", wxTOKEN_STRTOK);
+ while (tokenizer.HasMoreTokens()) {
+ wxString curDir = tokenizer.GetNextToken();
+ if (curDir == '.')
+ continue;
+ if (previousDir != "") {
+ firstDir = previousDir;
+ break;
+ }
+ previousDir = curDir;
+ }
+ return firstDir;
+}
+
+// Security: check if archive tries to jump out of destination directory
+bool Tar::IsPathInsecure(wxString path) {
+ // Avoid leading slashes (even if we preprend destdir)
+ if (path[0] == '/' || path[0] == '\\')
+ return true;
+ // Avoid ':' since wxFileName::Mkdir silently normalizes
+ // e.g. C:\test1\C:\test2 to C:\test2
+ if (path.Contains(":"))
+ return true;
+ // Ensure all files reside in the same subdirectory
+ if (GetFirstDir(path) != mInstalledDmodDirectory)
+ return true;
+ // Ensure there's no '..' path element
+ wxStringTokenizer tokenizer(path, "/\\");
+ while (tokenizer.HasMoreTokens()) {
+ wxString token = tokenizer.GetNextToken();
+ if (token == "..")
+ return true;
+ }
+ return false;
+} | CWE-22 | null | null |
12,414 | Tar::Tar(wxString& szFile) : DFile(szFile)
{
bCanCompress = false;
}
| Dir. Trav. | 0 | Tar::Tar(wxString& szFile) : DFile(szFile)
{
bCanCompress = false;
}
| @@ -3,7 +3,7 @@
* Copyright (C) 2004 Andrew Reading
* Copyright (C) 2005, 2006 Dan Walma
- * Copyright (C) 2008, 2014 Sylvain Beucler
+ * Copyright (C) 2008, 2014, 2018 Sylvain Beucler
* This file is part of GNU FreeDink
@@ -31,6 +31,7 @@
#include <wx/intl.h>
#include <wx/log.h>
#include <wx/filename.h>
+#include <wx/tokenzr.h>
#include <math.h>
#include <ext/stdio_filebuf.h>
@@ -427,7 +428,15 @@ int Tar::ReadHeaders( void )
wxString lPath(lRecord.Name, wxConvUTF8);
if (mInstalledDmodDirectory.Length() == 0)
{
- mInstalledDmodDirectory = lPath.SubString( 0, lPath.Find( '/' ) );
+ // Security: ensure the D-Mod directory is non-empty
+ wxString firstDir = GetFirstDir(lPath);
+ if (firstDir.IsSameAs("", true) || firstDir.IsSameAs("..", true) || firstDir.IsSameAs("dink", true))
+ {
+ wxLogError(_("Error: invalid D-Mod directory. Stopping."));
+ return 1;
+ }
+ mInstalledDmodDirectory = firstDir;
+
lDmodDizPath = mInstalledDmodDirectory + _T("dmod.diz");
lDmodDizPath.LowerCase();
}
@@ -472,10 +481,6 @@ int Tar::Extract(wxString destdir, wxProgressDialog* aProgressDialog)
wxString strBuf;
int lError = 0;
- // Remember current directory
- wxString strCwd = ::wxGetCwd();
-
-
// Open the file here so it doesn't error after changing.
wxFile wx_In(mFilePath, wxFile::read);
@@ -495,8 +500,6 @@ int Tar::Extract(wxString destdir, wxProgressDialog* aProgressDialog)
wxLogFatalError(_("Error: Cannot create directory '%s'. Cannot extract data."), destdir.c_str());
throw;
}
- // Move to the directory.
- ::wxSetWorkingDirectory(destdir);
// Put the data in the directories.
__gnu_cxx::stdio_filebuf<char> filebuf(wx_In.fd(), std::ios::in);
@@ -507,10 +510,6 @@ int Tar::Extract(wxString destdir, wxProgressDialog* aProgressDialog)
}
wx_In.Close();
-
- // We're done. Move back.
- ::wxSetWorkingDirectory(strCwd);
-
return lError;
}
@@ -527,10 +526,6 @@ int Tar::ExtractData(std::istream& aTarStreamIn, wxString destdir, wxProgressDia
aTarStreamIn.seekg(0, std::ios::beg);
lTotalBytes = lEnd - static_cast<unsigned long>(aTarStreamIn.tellg());
- // Move into the extract dir.
- wxString lPreviousWorkingDirectory(::wxGetCwd());
- ::wxSetWorkingDirectory(destdir);
-
// Extract the files.
int ebufsiz = 8192;
char buffer[ebufsiz];
@@ -543,7 +538,16 @@ int Tar::ExtractData(std::istream& aTarStreamIn, wxString destdir, wxProgressDia
/* Attempt convertion from latin-1 if not valid UTF-8 */
lCurrentFilePath = wxString(lCurrentTarRecord.Name, wxConvISO8859_1);
}
- wxString lCurrentDirectory(lCurrentFilePath.substr(0, lCurrentFilePath.find_last_of('/')));
+ // Security: check if archive tries to jump out of destination directory
+ if (IsPathInsecure(lCurrentFilePath))
+ {
+ wxLogError(_("Error: Insecure filename: '%s'. Stopping."), lCurrentFilePath);
+ lError = 1;
+ break;
+ }
+ // Security: ensure full, non-relative path, under destdir/
+ lCurrentFilePath = destdir + wxFileName::GetPathSeparator() + lCurrentFilePath;
+ wxString lCurrentDirectory = lCurrentFilePath.substr(0, lCurrentFilePath.find_last_of("/\\"));
// Odd bad file problem...
if (lCurrentFilePath.compare(_T("\xFF")) == 0) // "�"
@@ -612,7 +616,6 @@ int Tar::ExtractData(std::istream& aTarStreamIn, wxString destdir, wxProgressDia
}
}
aProgressDialog->Update(100, _("Done."));
- ::wxSetWorkingDirectory(lPreviousWorkingDirectory);
return lError;
}
@@ -687,3 +690,45 @@ int Tar::RoundTo512(int n)
return (n - (n % 512)) + 512;
}
}
+
+wxString Tar::GetFirstDir(wxString path) {
+ wxString firstDir = "";
+ wxString previousDir = "";
+ // tokenizer never returns empty strings + distinguish dir// and a/$
+ if (path.EndsWith("/") || path.EndsWith("\\"))
+ path += "dummy";
+ wxStringTokenizer tokenizer(path, "/\\", wxTOKEN_STRTOK);
+ while (tokenizer.HasMoreTokens()) {
+ wxString curDir = tokenizer.GetNextToken();
+ if (curDir == '.')
+ continue;
+ if (previousDir != "") {
+ firstDir = previousDir;
+ break;
+ }
+ previousDir = curDir;
+ }
+ return firstDir;
+}
+
+// Security: check if archive tries to jump out of destination directory
+bool Tar::IsPathInsecure(wxString path) {
+ // Avoid leading slashes (even if we preprend destdir)
+ if (path[0] == '/' || path[0] == '\\')
+ return true;
+ // Avoid ':' since wxFileName::Mkdir silently normalizes
+ // e.g. C:\test1\C:\test2 to C:\test2
+ if (path.Contains(":"))
+ return true;
+ // Ensure all files reside in the same subdirectory
+ if (GetFirstDir(path) != mInstalledDmodDirectory)
+ return true;
+ // Ensure there's no '..' path element
+ wxStringTokenizer tokenizer(path, "/\\");
+ while (tokenizer.HasMoreTokens()) {
+ wxString token = tokenizer.GetNextToken();
+ if (token == "..")
+ return true;
+ }
+ return false;
+} | CWE-22 | null | null |
12,415 | basic_authentication_encode (const char *user, const char *passwd)
{
char *t1, *t2;
int len1 = strlen (user) + 1 + strlen (passwd);
t1 = (char *)alloca (len1 + 1);
sprintf (t1, "%s:%s", user, passwd);
t2 = (char *)alloca (BASE64_LENGTH (len1) + 1);
wget_base64_encode (t1, len1, t2);
return concat_strings ("Basic ", t2, (char *) 0);
}
| null | 0 | basic_authentication_encode (const char *user, const char *passwd)
{
char *t1, *t2;
int len1 = strlen (user) + 1 + strlen (passwd);
t1 = (char *)alloca (len1 + 1);
sprintf (t1, "%s:%s", user, passwd);
t2 = (char *)alloca (BASE64_LENGTH (len1) + 1);
wget_base64_encode (t1, len1, t2);
return concat_strings ("Basic ", t2, (char *) 0);
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,416 | body_file_send (int sock, const char *file_name, wgint promised_size, FILE *warc_tmp)
{
static char chunk[8192];
wgint written = 0;
int write_error;
FILE *fp;
DEBUGP (("[writing BODY file %s ... ", file_name));
fp = fopen (file_name, "rb");
if (!fp)
return -1;
while (!feof (fp) && written < promised_size)
{
int towrite;
int length = fread (chunk, 1, sizeof (chunk), fp);
if (length == 0)
break;
towrite = MIN (promised_size - written, length);
write_error = fd_write (sock, chunk, towrite, -1);
if (write_error < 0)
{
fclose (fp);
return -1;
}
if (warc_tmp != NULL)
{
/* Write a copy of the data to the WARC record. */
int warc_tmp_written = fwrite (chunk, 1, towrite, warc_tmp);
if (warc_tmp_written != towrite)
{
fclose (fp);
return -2;
}
}
written += towrite;
}
fclose (fp);
/* If we've written less than was promised, report a (probably
nonsensical) error rather than break the promise. */
if (written < promised_size)
{
errno = EINVAL;
return -1;
}
assert (written == promised_size);
DEBUGP (("done]\n"));
return 0;
}
| null | 0 | body_file_send (int sock, const char *file_name, wgint promised_size, FILE *warc_tmp)
{
static char chunk[8192];
wgint written = 0;
int write_error;
FILE *fp;
DEBUGP (("[writing BODY file %s ... ", file_name));
fp = fopen (file_name, "rb");
if (!fp)
return -1;
while (!feof (fp) && written < promised_size)
{
int towrite;
int length = fread (chunk, 1, sizeof (chunk), fp);
if (length == 0)
break;
towrite = MIN (promised_size - written, length);
write_error = fd_write (sock, chunk, towrite, -1);
if (write_error < 0)
{
fclose (fp);
return -1;
}
if (warc_tmp != NULL)
{
/* Write a copy of the data to the WARC record. */
int warc_tmp_written = fwrite (chunk, 1, towrite, warc_tmp);
if (warc_tmp_written != towrite)
{
fclose (fp);
return -2;
}
}
written += towrite;
}
fclose (fp);
/* If we've written less than was promised, report a (probably
nonsensical) error rather than break the promise. */
if (written < promised_size)
{
errno = EINVAL;
return -1;
}
assert (written == promised_size);
DEBUGP (("done]\n"));
return 0;
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,417 | check_auth (const struct url *u, char *user, char *passwd, struct response *resp,
struct request *req, bool *ntlm_seen_ref, bool *retry,
bool *basic_auth_finished_ref, bool *auth_finished_ref)
{
uerr_t auth_err = RETROK;
bool basic_auth_finished = *basic_auth_finished_ref;
bool auth_finished = *auth_finished_ref;
bool ntlm_seen = *ntlm_seen_ref;
*retry = false;
if (!auth_finished && (user && passwd))
{
/* IIS sends multiple copies of WWW-Authenticate, one with
the value "negotiate", and other(s) with data. Loop over
all the occurrences and pick the one we recognize. */
int wapos;
char *buf;
const char *www_authenticate = NULL;
const char *wabeg, *waend;
const char *digest = NULL, *basic = NULL, *ntlm = NULL;
for (wapos = 0; !ntlm
&& (wapos = resp_header_locate (resp, "WWW-Authenticate", wapos,
&wabeg, &waend)) != -1;
++wapos)
{
param_token name, value;
BOUNDED_TO_ALLOCA (wabeg, waend, buf);
www_authenticate = buf;
for (;!ntlm;)
{
/* extract the auth-scheme */
while (c_isspace (*www_authenticate)) www_authenticate++;
name.e = name.b = www_authenticate;
while (*name.e && !c_isspace (*name.e)) name.e++;
if (name.b == name.e)
break;
DEBUGP (("Auth scheme found '%.*s'\n", (int) (name.e - name.b), name.b));
if (known_authentication_scheme_p (name.b, name.e))
{
if (BEGINS_WITH (name.b, "NTLM"))
{
ntlm = name.b;
break; /* this is the most secure challenge, stop here */
}
else if (!digest && BEGINS_WITH (name.b, "Digest"))
digest = name.b;
else if (!basic && BEGINS_WITH (name.b, "Basic"))
basic = name.b;
}
/* now advance over the auth-params */
www_authenticate = name.e;
DEBUGP (("Auth param list '%s'\n", www_authenticate));
while (extract_param (&www_authenticate, &name, &value, ',', NULL) && name.b && value.b)
{
DEBUGP (("Auth param %.*s=%.*s\n",
(int) (name.e - name.b), name.b, (int) (value.e - value.b), value.b));
}
}
}
if (!basic && !digest && !ntlm)
{
/* If the authentication header is missing or
unrecognized, there's no sense in retrying. */
logputs (LOG_NOTQUIET, _("Unknown authentication scheme.\n"));
}
else if (!basic_auth_finished
|| !basic)
{
char *pth = url_full_path (u);
const char *value;
uerr_t *auth_stat;
auth_stat = xmalloc (sizeof (uerr_t));
*auth_stat = RETROK;
if (ntlm)
www_authenticate = ntlm;
else if (digest)
www_authenticate = digest;
else
www_authenticate = basic;
logprintf (LOG_NOTQUIET, _("Authentication selected: %s\n"), www_authenticate);
value = create_authorization_line (www_authenticate,
user, passwd,
request_method (req),
pth,
&auth_finished,
auth_stat);
auth_err = *auth_stat;
if (auth_err == RETROK)
{
request_set_header (req, "Authorization", value, rel_value);
if (BEGINS_WITH (www_authenticate, "NTLM"))
ntlm_seen = true;
else if (!u->user && BEGINS_WITH (www_authenticate, "Basic"))
{
/* Need to register this host as using basic auth,
* so we automatically send creds next time. */
register_basic_auth_host (u->host);
}
xfree (pth);
xfree (auth_stat);
*retry = true;
goto cleanup;
}
else
{
/* Creating the Authorization header went wrong */
}
}
else
{
/* We already did Basic auth, and it failed. Gotta
* give up. */
}
}
cleanup:
*ntlm_seen_ref = ntlm_seen;
*basic_auth_finished_ref = basic_auth_finished;
*auth_finished_ref = auth_finished;
return auth_err;
}
| null | 0 | check_auth (const struct url *u, char *user, char *passwd, struct response *resp,
struct request *req, bool *ntlm_seen_ref, bool *retry,
bool *basic_auth_finished_ref, bool *auth_finished_ref)
{
uerr_t auth_err = RETROK;
bool basic_auth_finished = *basic_auth_finished_ref;
bool auth_finished = *auth_finished_ref;
bool ntlm_seen = *ntlm_seen_ref;
*retry = false;
if (!auth_finished && (user && passwd))
{
/* IIS sends multiple copies of WWW-Authenticate, one with
the value "negotiate", and other(s) with data. Loop over
all the occurrences and pick the one we recognize. */
int wapos;
char *buf;
const char *www_authenticate = NULL;
const char *wabeg, *waend;
const char *digest = NULL, *basic = NULL, *ntlm = NULL;
for (wapos = 0; !ntlm
&& (wapos = resp_header_locate (resp, "WWW-Authenticate", wapos,
&wabeg, &waend)) != -1;
++wapos)
{
param_token name, value;
BOUNDED_TO_ALLOCA (wabeg, waend, buf);
www_authenticate = buf;
for (;!ntlm;)
{
/* extract the auth-scheme */
while (c_isspace (*www_authenticate)) www_authenticate++;
name.e = name.b = www_authenticate;
while (*name.e && !c_isspace (*name.e)) name.e++;
if (name.b == name.e)
break;
DEBUGP (("Auth scheme found '%.*s'\n", (int) (name.e - name.b), name.b));
if (known_authentication_scheme_p (name.b, name.e))
{
if (BEGINS_WITH (name.b, "NTLM"))
{
ntlm = name.b;
break; /* this is the most secure challenge, stop here */
}
else if (!digest && BEGINS_WITH (name.b, "Digest"))
digest = name.b;
else if (!basic && BEGINS_WITH (name.b, "Basic"))
basic = name.b;
}
/* now advance over the auth-params */
www_authenticate = name.e;
DEBUGP (("Auth param list '%s'\n", www_authenticate));
while (extract_param (&www_authenticate, &name, &value, ',', NULL) && name.b && value.b)
{
DEBUGP (("Auth param %.*s=%.*s\n",
(int) (name.e - name.b), name.b, (int) (value.e - value.b), value.b));
}
}
}
if (!basic && !digest && !ntlm)
{
/* If the authentication header is missing or
unrecognized, there's no sense in retrying. */
logputs (LOG_NOTQUIET, _("Unknown authentication scheme.\n"));
}
else if (!basic_auth_finished
|| !basic)
{
char *pth = url_full_path (u);
const char *value;
uerr_t *auth_stat;
auth_stat = xmalloc (sizeof (uerr_t));
*auth_stat = RETROK;
if (ntlm)
www_authenticate = ntlm;
else if (digest)
www_authenticate = digest;
else
www_authenticate = basic;
logprintf (LOG_NOTQUIET, _("Authentication selected: %s\n"), www_authenticate);
value = create_authorization_line (www_authenticate,
user, passwd,
request_method (req),
pth,
&auth_finished,
auth_stat);
auth_err = *auth_stat;
if (auth_err == RETROK)
{
request_set_header (req, "Authorization", value, rel_value);
if (BEGINS_WITH (www_authenticate, "NTLM"))
ntlm_seen = true;
else if (!u->user && BEGINS_WITH (www_authenticate, "Basic"))
{
/* Need to register this host as using basic auth,
* so we automatically send creds next time. */
register_basic_auth_host (u->host);
}
xfree (pth);
xfree (auth_stat);
*retry = true;
goto cleanup;
}
else
{
/* Creating the Authorization header went wrong */
}
}
else
{
/* We already did Basic auth, and it failed. Gotta
* give up. */
}
}
cleanup:
*ntlm_seen_ref = ntlm_seen;
*basic_auth_finished_ref = basic_auth_finished;
*auth_finished_ref = auth_finished;
return auth_err;
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,418 | check_end (const char *p)
{
if (!p)
return false;
while (c_isspace (*p))
++p;
if (!*p
|| (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
|| ((p[0] == '+' || p[0] == '-') && c_isdigit (p[1])))
return true;
else
return false;
}
| null | 0 | check_end (const char *p)
{
if (!p)
return false;
while (c_isspace (*p))
++p;
if (!*p
|| (p[0] == 'G' && p[1] == 'M' && p[2] == 'T')
|| ((p[0] == '+' || p[0] == '-') && c_isdigit (p[1])))
return true;
else
return false;
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,419 | check_file_output (const struct url *u, struct http_stat *hs,
struct response *resp, char *hdrval, size_t hdrsize)
{
/* Determine the local filename if needed. Notice that if -O is used
* hstat.local_file is set by http_loop to the argument of -O. */
if (!hs->local_file)
{
char *local_file = NULL;
/* Honor Content-Disposition whether possible. */
if (!opt.content_disposition
|| !resp_header_copy (resp, "Content-Disposition",
hdrval, hdrsize)
|| !parse_content_disposition (hdrval, &local_file))
{
/* The Content-Disposition header is missing or broken.
* Choose unique file name according to given URL. */
hs->local_file = url_file_name (u, NULL);
}
else
{
DEBUGP (("Parsed filename from Content-Disposition: %s\n",
local_file));
hs->local_file = url_file_name (u, local_file);
}
xfree (local_file);
}
hs->temporary = opt.delete_after || opt.spider || !acceptable (hs->local_file);
if (hs->temporary)
{
char *tmp = aprintf ("%s.tmp", hs->local_file);
xfree (hs->local_file);
hs->local_file = tmp;
}
/* TODO: perform this check only once. */
if (!hs->existence_checked && file_exists_p (hs->local_file, NULL))
{
if (opt.noclobber && !opt.output_document)
{
/* If opt.noclobber is turned on and file already exists, do not
retrieve the file. But if the output_document was given, then this
test was already done and the file didn't exist. Hence the !opt.output_document */
return RETRUNNEEDED;
}
else if (!ALLOW_CLOBBER)
{
char *unique = unique_name (hs->local_file, true);
if (unique != hs->local_file)
xfree (hs->local_file);
hs->local_file = unique;
}
}
hs->existence_checked = true;
/* Support timestamping */
if (opt.timestamping && !hs->timestamp_checked)
{
uerr_t timestamp_err = set_file_timestamp (hs);
if (timestamp_err != RETROK)
return timestamp_err;
}
return RETROK;
}
| null | 0 | check_file_output (const struct url *u, struct http_stat *hs,
struct response *resp, char *hdrval, size_t hdrsize)
{
/* Determine the local filename if needed. Notice that if -O is used
* hstat.local_file is set by http_loop to the argument of -O. */
if (!hs->local_file)
{
char *local_file = NULL;
/* Honor Content-Disposition whether possible. */
if (!opt.content_disposition
|| !resp_header_copy (resp, "Content-Disposition",
hdrval, hdrsize)
|| !parse_content_disposition (hdrval, &local_file))
{
/* The Content-Disposition header is missing or broken.
* Choose unique file name according to given URL. */
hs->local_file = url_file_name (u, NULL);
}
else
{
DEBUGP (("Parsed filename from Content-Disposition: %s\n",
local_file));
hs->local_file = url_file_name (u, local_file);
}
xfree (local_file);
}
hs->temporary = opt.delete_after || opt.spider || !acceptable (hs->local_file);
if (hs->temporary)
{
char *tmp = aprintf ("%s.tmp", hs->local_file);
xfree (hs->local_file);
hs->local_file = tmp;
}
/* TODO: perform this check only once. */
if (!hs->existence_checked && file_exists_p (hs->local_file, NULL))
{
if (opt.noclobber && !opt.output_document)
{
/* If opt.noclobber is turned on and file already exists, do not
retrieve the file. But if the output_document was given, then this
test was already done and the file didn't exist. Hence the !opt.output_document */
return RETRUNNEEDED;
}
else if (!ALLOW_CLOBBER)
{
char *unique = unique_name (hs->local_file, true);
if (unique != hs->local_file)
xfree (hs->local_file);
hs->local_file = unique;
}
}
hs->existence_checked = true;
/* Support timestamping */
if (opt.timestamping && !hs->timestamp_checked)
{
uerr_t timestamp_err = set_file_timestamp (hs);
if (timestamp_err != RETROK)
return timestamp_err;
}
return RETROK;
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,420 | check_retry_on_http_error (const int statcode)
{
const char *tok = opt.retry_on_http_error;
while (tok && *tok)
{
if (atoi (tok) == statcode)
return true;
if ((tok = strchr (tok, ',')))
++tok;
}
return false;
}
| null | 0 | check_retry_on_http_error (const int statcode)
{
const char *tok = opt.retry_on_http_error;
while (tok && *tok)
{
if (atoi (tok) == statcode)
return true;
if ((tok = strchr (tok, ',')))
++tok;
}
return false;
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,421 | create_authorization_line (const char *au, const char *user,
const char *passwd, const char *method,
const char *path, bool *finished, uerr_t *auth_err)
{
/* We are called only with known schemes, so we can dispatch on the
first letter. */
switch (c_toupper (*au))
{
case 'B': /* Basic */
*finished = true;
return basic_authentication_encode (user, passwd);
#ifdef ENABLE_DIGEST
case 'D': /* Digest */
*finished = true;
return digest_authentication_encode (au, user, passwd, method, path, auth_err);
#endif
#ifdef ENABLE_NTLM
case 'N': /* NTLM */
if (!ntlm_input (&pconn.ntlm, au))
{
*finished = true;
return NULL;
}
return ntlm_output (&pconn.ntlm, user, passwd, finished);
#endif
default:
/* We shouldn't get here -- this function should be only called
with values approved by known_authentication_scheme_p. */
abort ();
}
}
| null | 0 | create_authorization_line (const char *au, const char *user,
const char *passwd, const char *method,
const char *path, bool *finished, uerr_t *auth_err)
{
/* We are called only with known schemes, so we can dispatch on the
first letter. */
switch (c_toupper (*au))
{
case 'B': /* Basic */
*finished = true;
return basic_authentication_encode (user, passwd);
#ifdef ENABLE_DIGEST
case 'D': /* Digest */
*finished = true;
return digest_authentication_encode (au, user, passwd, method, path, auth_err);
#endif
#ifdef ENABLE_NTLM
case 'N': /* NTLM */
if (!ntlm_input (&pconn.ntlm, au))
{
*finished = true;
return NULL;
}
return ntlm_output (&pconn.ntlm, user, passwd, finished);
#endif
default:
/* We shouldn't get here -- this function should be only called
with values approved by known_authentication_scheme_p. */
abort ();
}
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,422 | digest_authentication_encode (const char *au, const char *user,
const char *passwd, const char *method,
const char *path, uerr_t *auth_err)
{
static char *realm, *opaque, *nonce, *qop, *algorithm;
static struct {
const char *name;
char **variable;
} options[] = {
{ "realm", &realm },
{ "opaque", &opaque },
{ "nonce", &nonce },
{ "qop", &qop },
{ "algorithm", &algorithm }
};
char cnonce[16] = "";
char *res = NULL;
int res_len;
size_t res_size;
param_token name, value;
realm = opaque = nonce = algorithm = qop = NULL;
au += 6; /* skip over `Digest' */
while (extract_param (&au, &name, &value, ',', NULL))
{
size_t i;
size_t namelen = name.e - name.b;
for (i = 0; i < countof (options); i++)
if (namelen == strlen (options[i].name)
&& 0 == strncmp (name.b, options[i].name,
namelen))
{
*options[i].variable = strdupdelim (value.b, value.e);
break;
}
}
if (qop && strcmp (qop, "auth"))
{
logprintf (LOG_NOTQUIET, _("Unsupported quality of protection '%s'.\n"), qop);
xfree (qop); /* force freeing mem and continue */
}
else if (algorithm && strcmp (algorithm,"MD5") && strcmp (algorithm,"MD5-sess"))
{
logprintf (LOG_NOTQUIET, _("Unsupported algorithm '%s'.\n"), algorithm);
xfree (algorithm); /* force freeing mem and continue */
}
if (!realm || !nonce || !user || !passwd || !path || !method)
{
*auth_err = ATTRMISSING;
goto cleanup;
}
/* Calculate the digest value. */
{
struct md5_ctx ctx;
unsigned char hash[MD5_DIGEST_SIZE];
char a1buf[MD5_DIGEST_SIZE * 2 + 1], a2buf[MD5_DIGEST_SIZE * 2 + 1];
char response_digest[MD5_DIGEST_SIZE * 2 + 1];
/* A1BUF = H(user ":" realm ":" password) */
md5_init_ctx (&ctx);
md5_process_bytes ((unsigned char *)user, strlen (user), &ctx);
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)realm, strlen (realm), &ctx);
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)passwd, strlen (passwd), &ctx);
md5_finish_ctx (&ctx, hash);
dump_hash (a1buf, hash);
if (algorithm && !strcmp (algorithm, "MD5-sess"))
{
/* A1BUF = H( H(user ":" realm ":" password) ":" nonce ":" cnonce ) */
snprintf (cnonce, sizeof (cnonce), "%08x",
(unsigned) random_number (INT_MAX));
md5_init_ctx (&ctx);
/* md5_process_bytes (hash, MD5_DIGEST_SIZE, &ctx); */
md5_process_bytes (a1buf, MD5_DIGEST_SIZE * 2, &ctx);
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)nonce, strlen (nonce), &ctx);
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)cnonce, strlen (cnonce), &ctx);
md5_finish_ctx (&ctx, hash);
dump_hash (a1buf, hash);
}
/* A2BUF = H(method ":" path) */
md5_init_ctx (&ctx);
md5_process_bytes ((unsigned char *)method, strlen (method), &ctx);
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)path, strlen (path), &ctx);
md5_finish_ctx (&ctx, hash);
dump_hash (a2buf, hash);
if (qop && !strcmp (qop, "auth"))
{
/* RFC 2617 Digest Access Authentication */
/* generate random hex string */
if (!*cnonce)
snprintf (cnonce, sizeof (cnonce), "%08x",
(unsigned) random_number (INT_MAX));
/* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" noncecount ":" clientnonce ":" qop ": " A2BUF) */
md5_init_ctx (&ctx);
md5_process_bytes ((unsigned char *)a1buf, MD5_DIGEST_SIZE * 2, &ctx);
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)nonce, strlen (nonce), &ctx);
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)"00000001", 8, &ctx); /* TODO: keep track of server nonce values */
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)cnonce, strlen (cnonce), &ctx);
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)qop, strlen (qop), &ctx);
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)a2buf, MD5_DIGEST_SIZE * 2, &ctx);
md5_finish_ctx (&ctx, hash);
}
else
{
/* RFC 2069 Digest Access Authentication */
/* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
md5_init_ctx (&ctx);
md5_process_bytes ((unsigned char *)a1buf, MD5_DIGEST_SIZE * 2, &ctx);
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)nonce, strlen (nonce), &ctx);
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)a2buf, MD5_DIGEST_SIZE * 2, &ctx);
md5_finish_ctx (&ctx, hash);
}
dump_hash (response_digest, hash);
res_size = strlen (user)
+ strlen (realm)
+ strlen (nonce)
+ strlen (path)
+ 2 * MD5_DIGEST_SIZE /*strlen (response_digest)*/
+ (opaque ? strlen (opaque) : 0)
+ (algorithm ? strlen (algorithm) : 0)
+ (qop ? 128: 0)
+ strlen (cnonce)
+ 128;
res = xmalloc (res_size);
if (qop && !strcmp (qop, "auth"))
{
res_len = snprintf (res, res_size, "Digest "\
"username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\""\
", qop=auth, nc=00000001, cnonce=\"%s\"",
user, realm, nonce, path, response_digest, cnonce);
}
else
{
res_len = snprintf (res, res_size, "Digest "\
"username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
user, realm, nonce, path, response_digest);
}
if (opaque)
{
res_len += snprintf (res + res_len, res_size - res_len, ", opaque=\"%s\"", opaque);
}
if (algorithm)
{
snprintf (res + res_len, res_size - res_len, ", algorithm=\"%s\"", algorithm);
}
}
cleanup:
xfree (realm);
xfree (opaque);
xfree (nonce);
xfree (qop);
xfree (algorithm);
return res;
}
| null | 0 | digest_authentication_encode (const char *au, const char *user,
const char *passwd, const char *method,
const char *path, uerr_t *auth_err)
{
static char *realm, *opaque, *nonce, *qop, *algorithm;
static struct {
const char *name;
char **variable;
} options[] = {
{ "realm", &realm },
{ "opaque", &opaque },
{ "nonce", &nonce },
{ "qop", &qop },
{ "algorithm", &algorithm }
};
char cnonce[16] = "";
char *res = NULL;
int res_len;
size_t res_size;
param_token name, value;
realm = opaque = nonce = algorithm = qop = NULL;
au += 6; /* skip over `Digest' */
while (extract_param (&au, &name, &value, ',', NULL))
{
size_t i;
size_t namelen = name.e - name.b;
for (i = 0; i < countof (options); i++)
if (namelen == strlen (options[i].name)
&& 0 == strncmp (name.b, options[i].name,
namelen))
{
*options[i].variable = strdupdelim (value.b, value.e);
break;
}
}
if (qop && strcmp (qop, "auth"))
{
logprintf (LOG_NOTQUIET, _("Unsupported quality of protection '%s'.\n"), qop);
xfree (qop); /* force freeing mem and continue */
}
else if (algorithm && strcmp (algorithm,"MD5") && strcmp (algorithm,"MD5-sess"))
{
logprintf (LOG_NOTQUIET, _("Unsupported algorithm '%s'.\n"), algorithm);
xfree (algorithm); /* force freeing mem and continue */
}
if (!realm || !nonce || !user || !passwd || !path || !method)
{
*auth_err = ATTRMISSING;
goto cleanup;
}
/* Calculate the digest value. */
{
struct md5_ctx ctx;
unsigned char hash[MD5_DIGEST_SIZE];
char a1buf[MD5_DIGEST_SIZE * 2 + 1], a2buf[MD5_DIGEST_SIZE * 2 + 1];
char response_digest[MD5_DIGEST_SIZE * 2 + 1];
/* A1BUF = H(user ":" realm ":" password) */
md5_init_ctx (&ctx);
md5_process_bytes ((unsigned char *)user, strlen (user), &ctx);
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)realm, strlen (realm), &ctx);
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)passwd, strlen (passwd), &ctx);
md5_finish_ctx (&ctx, hash);
dump_hash (a1buf, hash);
if (algorithm && !strcmp (algorithm, "MD5-sess"))
{
/* A1BUF = H( H(user ":" realm ":" password) ":" nonce ":" cnonce ) */
snprintf (cnonce, sizeof (cnonce), "%08x",
(unsigned) random_number (INT_MAX));
md5_init_ctx (&ctx);
/* md5_process_bytes (hash, MD5_DIGEST_SIZE, &ctx); */
md5_process_bytes (a1buf, MD5_DIGEST_SIZE * 2, &ctx);
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)nonce, strlen (nonce), &ctx);
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)cnonce, strlen (cnonce), &ctx);
md5_finish_ctx (&ctx, hash);
dump_hash (a1buf, hash);
}
/* A2BUF = H(method ":" path) */
md5_init_ctx (&ctx);
md5_process_bytes ((unsigned char *)method, strlen (method), &ctx);
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)path, strlen (path), &ctx);
md5_finish_ctx (&ctx, hash);
dump_hash (a2buf, hash);
if (qop && !strcmp (qop, "auth"))
{
/* RFC 2617 Digest Access Authentication */
/* generate random hex string */
if (!*cnonce)
snprintf (cnonce, sizeof (cnonce), "%08x",
(unsigned) random_number (INT_MAX));
/* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" noncecount ":" clientnonce ":" qop ": " A2BUF) */
md5_init_ctx (&ctx);
md5_process_bytes ((unsigned char *)a1buf, MD5_DIGEST_SIZE * 2, &ctx);
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)nonce, strlen (nonce), &ctx);
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)"00000001", 8, &ctx); /* TODO: keep track of server nonce values */
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)cnonce, strlen (cnonce), &ctx);
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)qop, strlen (qop), &ctx);
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)a2buf, MD5_DIGEST_SIZE * 2, &ctx);
md5_finish_ctx (&ctx, hash);
}
else
{
/* RFC 2069 Digest Access Authentication */
/* RESPONSE_DIGEST = H(A1BUF ":" nonce ":" A2BUF) */
md5_init_ctx (&ctx);
md5_process_bytes ((unsigned char *)a1buf, MD5_DIGEST_SIZE * 2, &ctx);
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)nonce, strlen (nonce), &ctx);
md5_process_bytes ((unsigned char *)":", 1, &ctx);
md5_process_bytes ((unsigned char *)a2buf, MD5_DIGEST_SIZE * 2, &ctx);
md5_finish_ctx (&ctx, hash);
}
dump_hash (response_digest, hash);
res_size = strlen (user)
+ strlen (realm)
+ strlen (nonce)
+ strlen (path)
+ 2 * MD5_DIGEST_SIZE /*strlen (response_digest)*/
+ (opaque ? strlen (opaque) : 0)
+ (algorithm ? strlen (algorithm) : 0)
+ (qop ? 128: 0)
+ strlen (cnonce)
+ 128;
res = xmalloc (res_size);
if (qop && !strcmp (qop, "auth"))
{
res_len = snprintf (res, res_size, "Digest "\
"username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\""\
", qop=auth, nc=00000001, cnonce=\"%s\"",
user, realm, nonce, path, response_digest, cnonce);
}
else
{
res_len = snprintf (res, res_size, "Digest "\
"username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", response=\"%s\"",
user, realm, nonce, path, response_digest);
}
if (opaque)
{
res_len += snprintf (res + res_len, res_size - res_len, ", opaque=\"%s\"", opaque);
}
if (algorithm)
{
snprintf (res + res_len, res_size - res_len, ", algorithm=\"%s\"", algorithm);
}
}
cleanup:
xfree (realm);
xfree (opaque);
xfree (nonce);
xfree (qop);
xfree (algorithm);
return res;
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,423 | dump_hash (char *buf, const unsigned char *hash)
{
int i;
for (i = 0; i < MD5_DIGEST_SIZE; i++, hash++)
{
*buf++ = XNUM_TO_digit (*hash >> 4);
*buf++ = XNUM_TO_digit (*hash & 0xf);
}
*buf = '\0';
}
| null | 0 | dump_hash (char *buf, const unsigned char *hash)
{
int i;
for (i = 0; i < MD5_DIGEST_SIZE; i++, hash++)
{
*buf++ = XNUM_TO_digit (*hash >> 4);
*buf++ = XNUM_TO_digit (*hash & 0xf);
}
*buf = '\0';
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,424 | ensure_extension (struct http_stat *hs, const char *ext, int *dt)
{
char *last_period_in_local_filename = strrchr (hs->local_file, '.');
char shortext[8];
int len;
shortext[0] = '\0';
len = strlen (ext);
if (len == 5)
{
memcpy (shortext, ext, len - 1);
shortext[len - 1] = '\0';
}
if (last_period_in_local_filename == NULL
|| !(0 == strcasecmp (last_period_in_local_filename, shortext)
|| 0 == strcasecmp (last_period_in_local_filename, ext)))
{
int local_filename_len = strlen (hs->local_file);
/* Resize the local file, allowing for ".html" preceded by
optional ".NUMBER". */
hs->local_file = xrealloc (hs->local_file,
local_filename_len + 24 + len);
strcpy (hs->local_file + local_filename_len, ext);
/* If clobbering is not allowed and the file, as named,
exists, tack on ".NUMBER.html" instead. */
if (!ALLOW_CLOBBER && file_exists_p (hs->local_file, NULL))
{
int ext_num = 1;
do
sprintf (hs->local_file + local_filename_len,
".%d%s", ext_num++, ext);
while (file_exists_p (hs->local_file, NULL));
}
*dt |= ADDED_HTML_EXTENSION;
}
}
| null | 0 | ensure_extension (struct http_stat *hs, const char *ext, int *dt)
{
char *last_period_in_local_filename = strrchr (hs->local_file, '.');
char shortext[8];
int len;
shortext[0] = '\0';
len = strlen (ext);
if (len == 5)
{
memcpy (shortext, ext, len - 1);
shortext[len - 1] = '\0';
}
if (last_period_in_local_filename == NULL
|| !(0 == strcasecmp (last_period_in_local_filename, shortext)
|| 0 == strcasecmp (last_period_in_local_filename, ext)))
{
int local_filename_len = strlen (hs->local_file);
/* Resize the local file, allowing for ".html" preceded by
optional ".NUMBER". */
hs->local_file = xrealloc (hs->local_file,
local_filename_len + 24 + len);
strcpy (hs->local_file + local_filename_len, ext);
/* If clobbering is not allowed and the file, as named,
exists, tack on ".NUMBER.html" instead. */
if (!ALLOW_CLOBBER && file_exists_p (hs->local_file, NULL))
{
int ext_num = 1;
do
sprintf (hs->local_file + local_filename_len,
".%d%s", ext_num++, ext);
while (file_exists_p (hs->local_file, NULL));
}
*dt |= ADDED_HTML_EXTENSION;
}
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,425 | establish_connection (const struct url *u, const struct url **conn_ref,
struct http_stat *hs, struct url *proxy,
char **proxyauth,
struct request **req_ref, bool *using_ssl,
bool inhibit_keep_alive,
int *sock_ref)
{
bool host_lookup_failed = false;
int sock = *sock_ref;
struct request *req = *req_ref;
const struct url *conn = *conn_ref;
struct response *resp;
int write_error;
int statcode;
if (! inhibit_keep_alive)
{
/* Look for a persistent connection to target host, unless a
proxy is used. The exception is when SSL is in use, in which
case the proxy is nothing but a passthrough to the target
host, registered as a connection to the latter. */
const struct url *relevant = conn;
#ifdef HAVE_SSL
if (u->scheme == SCHEME_HTTPS)
relevant = u;
#endif
if (persistent_available_p (relevant->host, relevant->port,
#ifdef HAVE_SSL
relevant->scheme == SCHEME_HTTPS,
#else
0,
#endif
&host_lookup_failed))
{
int family = socket_family (pconn.socket, ENDPOINT_PEER);
sock = pconn.socket;
*using_ssl = pconn.ssl;
#if ENABLE_IPV6
if (family == AF_INET6)
logprintf (LOG_VERBOSE, _("Reusing existing connection to [%s]:%d.\n"),
quotearg_style (escape_quoting_style, pconn.host),
pconn.port);
else
#endif
logprintf (LOG_VERBOSE, _("Reusing existing connection to %s:%d.\n"),
quotearg_style (escape_quoting_style, pconn.host),
pconn.port);
DEBUGP (("Reusing fd %d.\n", sock));
if (pconn.authorized)
/* If the connection is already authorized, the "Basic"
authorization added by code above is unnecessary and
only hurts us. */
request_remove_header (req, "Authorization");
}
else if (host_lookup_failed)
{
logprintf(LOG_NOTQUIET,
_("%s: unable to resolve host address %s\n"),
exec_name, quote (relevant->host));
return HOSTERR;
}
else if (sock != -1)
{
sock = -1;
}
}
if (sock < 0)
{
sock = connect_to_host (conn->host, conn->port);
if (sock == E_HOST)
return HOSTERR;
else if (sock < 0)
return (retryable_socket_connect_error (errno)
? CONERROR : CONIMPOSSIBLE);
#ifdef HAVE_SSL
if (proxy && u->scheme == SCHEME_HTTPS)
{
char *head;
char *message;
/* When requesting SSL URLs through proxies, use the
CONNECT method to request passthrough. */
struct request *connreq = request_new ("CONNECT",
aprintf ("%s:%d", u->host, u->port));
SET_USER_AGENT (connreq);
if (proxyauth)
{
request_set_header (connreq, "Proxy-Authorization",
*proxyauth, rel_value);
/* Now that PROXYAUTH is part of the CONNECT request,
zero it out so we don't send proxy authorization with
the regular request below. */
*proxyauth = NULL;
}
request_set_header (connreq, "Host",
aprintf ("%s:%d", u->host, u->port),
rel_value);
write_error = request_send (connreq, sock, 0);
request_free (&connreq);
if (write_error < 0)
{
CLOSE_INVALIDATE (sock);
return WRITEFAILED;
}
head = read_http_response_head (sock);
if (!head)
{
logprintf (LOG_VERBOSE, _("Failed reading proxy response: %s\n"),
fd_errstr (sock));
CLOSE_INVALIDATE (sock);
return HERR;
}
message = NULL;
if (!*head)
{
xfree (head);
goto failed_tunnel;
}
DEBUGP (("proxy responded with: [%s]\n", head));
resp = resp_new (head);
statcode = resp_status (resp, &message);
if (statcode < 0)
{
char *tms = datetime_str (time (NULL));
logprintf (LOG_VERBOSE, "%d\n", statcode);
logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"), tms, statcode,
quotearg_style (escape_quoting_style,
_("Malformed status line")));
xfree (head);
return HERR;
}
xfree (hs->message);
hs->message = xstrdup (message);
resp_free (&resp);
xfree (head);
if (statcode != 200)
{
failed_tunnel:
logprintf (LOG_NOTQUIET, _("Proxy tunneling failed: %s"),
message ? quotearg_style (escape_quoting_style, message) : "?");
xfree (message);
return CONSSLERR;
}
xfree (message);
/* SOCK is now *really* connected to u->host, so update CONN
to reflect this. That way register_persistent will
register SOCK as being connected to u->host:u->port. */
conn = u;
}
if (conn->scheme == SCHEME_HTTPS)
{
if (!ssl_connect_wget (sock, u->host, NULL))
{
CLOSE_INVALIDATE (sock);
return CONSSLERR;
}
else if (!ssl_check_certificate (sock, u->host))
{
CLOSE_INVALIDATE (sock);
return VERIFCERTERR;
}
*using_ssl = true;
}
#endif /* HAVE_SSL */
}
*conn_ref = conn;
*req_ref = req;
*sock_ref = sock;
return RETROK;
}
| null | 0 | establish_connection (const struct url *u, const struct url **conn_ref,
struct http_stat *hs, struct url *proxy,
char **proxyauth,
struct request **req_ref, bool *using_ssl,
bool inhibit_keep_alive,
int *sock_ref)
{
bool host_lookup_failed = false;
int sock = *sock_ref;
struct request *req = *req_ref;
const struct url *conn = *conn_ref;
struct response *resp;
int write_error;
int statcode;
if (! inhibit_keep_alive)
{
/* Look for a persistent connection to target host, unless a
proxy is used. The exception is when SSL is in use, in which
case the proxy is nothing but a passthrough to the target
host, registered as a connection to the latter. */
const struct url *relevant = conn;
#ifdef HAVE_SSL
if (u->scheme == SCHEME_HTTPS)
relevant = u;
#endif
if (persistent_available_p (relevant->host, relevant->port,
#ifdef HAVE_SSL
relevant->scheme == SCHEME_HTTPS,
#else
0,
#endif
&host_lookup_failed))
{
int family = socket_family (pconn.socket, ENDPOINT_PEER);
sock = pconn.socket;
*using_ssl = pconn.ssl;
#if ENABLE_IPV6
if (family == AF_INET6)
logprintf (LOG_VERBOSE, _("Reusing existing connection to [%s]:%d.\n"),
quotearg_style (escape_quoting_style, pconn.host),
pconn.port);
else
#endif
logprintf (LOG_VERBOSE, _("Reusing existing connection to %s:%d.\n"),
quotearg_style (escape_quoting_style, pconn.host),
pconn.port);
DEBUGP (("Reusing fd %d.\n", sock));
if (pconn.authorized)
/* If the connection is already authorized, the "Basic"
authorization added by code above is unnecessary and
only hurts us. */
request_remove_header (req, "Authorization");
}
else if (host_lookup_failed)
{
logprintf(LOG_NOTQUIET,
_("%s: unable to resolve host address %s\n"),
exec_name, quote (relevant->host));
return HOSTERR;
}
else if (sock != -1)
{
sock = -1;
}
}
if (sock < 0)
{
sock = connect_to_host (conn->host, conn->port);
if (sock == E_HOST)
return HOSTERR;
else if (sock < 0)
return (retryable_socket_connect_error (errno)
? CONERROR : CONIMPOSSIBLE);
#ifdef HAVE_SSL
if (proxy && u->scheme == SCHEME_HTTPS)
{
char *head;
char *message;
/* When requesting SSL URLs through proxies, use the
CONNECT method to request passthrough. */
struct request *connreq = request_new ("CONNECT",
aprintf ("%s:%d", u->host, u->port));
SET_USER_AGENT (connreq);
if (proxyauth)
{
request_set_header (connreq, "Proxy-Authorization",
*proxyauth, rel_value);
/* Now that PROXYAUTH is part of the CONNECT request,
zero it out so we don't send proxy authorization with
the regular request below. */
*proxyauth = NULL;
}
request_set_header (connreq, "Host",
aprintf ("%s:%d", u->host, u->port),
rel_value);
write_error = request_send (connreq, sock, 0);
request_free (&connreq);
if (write_error < 0)
{
CLOSE_INVALIDATE (sock);
return WRITEFAILED;
}
head = read_http_response_head (sock);
if (!head)
{
logprintf (LOG_VERBOSE, _("Failed reading proxy response: %s\n"),
fd_errstr (sock));
CLOSE_INVALIDATE (sock);
return HERR;
}
message = NULL;
if (!*head)
{
xfree (head);
goto failed_tunnel;
}
DEBUGP (("proxy responded with: [%s]\n", head));
resp = resp_new (head);
statcode = resp_status (resp, &message);
if (statcode < 0)
{
char *tms = datetime_str (time (NULL));
logprintf (LOG_VERBOSE, "%d\n", statcode);
logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"), tms, statcode,
quotearg_style (escape_quoting_style,
_("Malformed status line")));
xfree (head);
return HERR;
}
xfree (hs->message);
hs->message = xstrdup (message);
resp_free (&resp);
xfree (head);
if (statcode != 200)
{
failed_tunnel:
logprintf (LOG_NOTQUIET, _("Proxy tunneling failed: %s"),
message ? quotearg_style (escape_quoting_style, message) : "?");
xfree (message);
return CONSSLERR;
}
xfree (message);
/* SOCK is now *really* connected to u->host, so update CONN
to reflect this. That way register_persistent will
register SOCK as being connected to u->host:u->port. */
conn = u;
}
if (conn->scheme == SCHEME_HTTPS)
{
if (!ssl_connect_wget (sock, u->host, NULL))
{
CLOSE_INVALIDATE (sock);
return CONSSLERR;
}
else if (!ssl_check_certificate (sock, u->host))
{
CLOSE_INVALIDATE (sock);
return VERIFCERTERR;
}
*using_ssl = true;
}
#endif /* HAVE_SSL */
}
*conn_ref = conn;
*req_ref = req;
*sock_ref = sock;
return RETROK;
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,426 | get_file_flags (const char *filename, int *dt)
{
logprintf (LOG_VERBOSE, _("\
File %s already there; not retrieving.\n\n"), quote (filename));
/* If the file is there, we suppose it's retrieved OK. */
*dt |= RETROKF;
/* #### Bogusness alert. */
/* If its suffix is "html" or "htm" or similar, assume text/html. */
if (has_html_suffix_p (filename))
*dt |= TEXTHTML;
}
| null | 0 | get_file_flags (const char *filename, int *dt)
{
logprintf (LOG_VERBOSE, _("\
File %s already there; not retrieving.\n\n"), quote (filename));
/* If the file is there, we suppose it's retrieved OK. */
*dt |= RETROKF;
/* #### Bogusness alert. */
/* If its suffix is "html" or "htm" or similar, assume text/html. */
if (has_html_suffix_p (filename))
*dt |= TEXTHTML;
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,427 | gethttp (const struct url *u, struct url *original_url, struct http_stat *hs,
int *dt, struct url *proxy, struct iri *iri, int count)
{
struct request *req = NULL;
char *type = NULL;
char *user, *passwd;
char *proxyauth;
int statcode;
int write_error;
wgint contlen, contrange;
const struct url *conn;
FILE *fp;
int err;
uerr_t retval;
#ifdef HAVE_HSTS
#ifdef TESTING
/* we don't link against main.o when we're testing */
hsts_store_t hsts_store = NULL;
#else
extern hsts_store_t hsts_store;
#endif
const char *hsts_params;
time_t max_age;
bool include_subdomains;
#endif
int sock = -1;
/* Set to 1 when the authorization has already been sent and should
not be tried again. */
bool auth_finished = false;
/* Set to 1 when just globally-set Basic authorization has been sent;
* should prevent further Basic negotiations, but not other
* mechanisms. */
bool basic_auth_finished = false;
/* Whether NTLM authentication is used for this request. */
bool ntlm_seen = false;
/* Whether our connection to the remote host is through SSL. */
bool using_ssl = false;
/* Whether a HEAD request will be issued (as opposed to GET or
POST). */
bool head_only = !!(*dt & HEAD_ONLY);
/* Whether conditional get request will be issued. */
bool cond_get = !!(*dt & IF_MODIFIED_SINCE);
#ifdef HAVE_METALINK
/* Are we looking for metalink info in HTTP headers? */
bool metalink = !!(*dt & METALINK_METADATA);
#endif
char *head = NULL;
struct response *resp = NULL;
char hdrval[512];
char *message = NULL;
/* Declare WARC variables. */
bool warc_enabled = (opt.warc_filename != NULL);
FILE *warc_tmp = NULL;
char warc_timestamp_str [21];
char warc_request_uuid [48];
ip_address *warc_ip = NULL;
off_t warc_payload_offset = -1;
/* Whether this connection will be kept alive after the HTTP request
is done. */
bool keep_alive;
/* Is the server using the chunked transfer encoding? */
bool chunked_transfer_encoding = false;
/* Whether keep-alive should be inhibited. */
bool inhibit_keep_alive =
!opt.http_keep_alive || opt.ignore_length;
/* Headers sent when using POST. */
wgint body_data_size = 0;
#ifdef HAVE_SSL
if (u->scheme == SCHEME_HTTPS)
{
/* Initialize the SSL context. After this has once been done,
it becomes a no-op. */
if (!ssl_init ())
{
scheme_disable (SCHEME_HTTPS);
logprintf (LOG_NOTQUIET,
_("Disabling SSL due to encountered errors.\n"));
retval = SSLINITFAILED;
goto cleanup;
}
}
#endif /* HAVE_SSL */
/* Initialize certain elements of struct http_stat. */
hs->len = 0;
hs->contlen = -1;
hs->res = -1;
hs->rderrmsg = NULL;
hs->newloc = NULL;
xfree (hs->remote_time);
hs->error = NULL;
hs->message = NULL;
hs->local_encoding = ENC_NONE;
hs->remote_encoding = ENC_NONE;
conn = u;
{
uerr_t ret;
req = initialize_request (u, hs, dt, proxy, inhibit_keep_alive,
&basic_auth_finished, &body_data_size,
&user, &passwd, &ret);
if (req == NULL)
{
retval = ret;
goto cleanup;
}
}
retry_with_auth:
/* We need to come back here when the initial attempt to retrieve
without authorization header fails. (Expected to happen at least
for the Digest authorization scheme.) */
if (opt.cookies)
request_set_header (req, "Cookie",
cookie_header (wget_cookie_jar,
u->host, u->port, u->path,
#ifdef HAVE_SSL
u->scheme == SCHEME_HTTPS
#else
0
#endif
),
rel_value);
/* Add the user headers. */
if (opt.user_headers)
{
int i;
for (i = 0; opt.user_headers[i]; i++)
request_set_user_header (req, opt.user_headers[i]);
}
proxyauth = NULL;
if (proxy)
{
conn = proxy;
initialize_proxy_configuration (u, req, proxy, &proxyauth);
}
keep_alive = true;
/* Establish the connection. */
if (inhibit_keep_alive)
keep_alive = false;
{
uerr_t conn_err = establish_connection (u, &conn, hs, proxy, &proxyauth, &req,
&using_ssl, inhibit_keep_alive, &sock);
if (conn_err != RETROK)
{
retval = conn_err;
goto cleanup;
}
}
/* Open the temporary file where we will write the request. */
if (warc_enabled)
{
warc_tmp = warc_tempfile ();
if (warc_tmp == NULL)
{
CLOSE_INVALIDATE (sock);
retval = WARC_TMP_FOPENERR;
goto cleanup;
}
if (! proxy)
{
warc_ip = (ip_address *) alloca (sizeof (ip_address));
socket_ip_address (sock, warc_ip, ENDPOINT_PEER);
}
}
/* Send the request to server. */
write_error = request_send (req, sock, warc_tmp);
if (write_error >= 0)
{
if (opt.body_data)
{
DEBUGP (("[BODY data: %s]\n", opt.body_data));
write_error = fd_write (sock, opt.body_data, body_data_size, -1);
if (write_error >= 0 && warc_tmp != NULL)
{
int warc_tmp_written;
/* Remember end of headers / start of payload. */
warc_payload_offset = ftello (warc_tmp);
/* Write a copy of the data to the WARC record. */
warc_tmp_written = fwrite (opt.body_data, 1, body_data_size, warc_tmp);
if (warc_tmp_written != body_data_size)
write_error = -2;
}
}
else if (opt.body_file && body_data_size != 0)
{
if (warc_tmp != NULL)
/* Remember end of headers / start of payload */
warc_payload_offset = ftello (warc_tmp);
write_error = body_file_send (sock, opt.body_file, body_data_size, warc_tmp);
}
}
if (write_error < 0)
{
CLOSE_INVALIDATE (sock);
if (warc_tmp != NULL)
fclose (warc_tmp);
if (write_error == -2)
retval = WARC_TMP_FWRITEERR;
else
retval = WRITEFAILED;
goto cleanup;
}
logprintf (LOG_VERBOSE, _("%s request sent, awaiting response... "),
proxy ? "Proxy" : "HTTP");
contlen = -1;
contrange = 0;
*dt &= ~RETROKF;
if (warc_enabled)
{
bool warc_result;
/* Generate a timestamp and uuid for this request. */
warc_timestamp (warc_timestamp_str, sizeof (warc_timestamp_str));
warc_uuid_str (warc_request_uuid);
/* Create a request record and store it in the WARC file. */
warc_result = warc_write_request_record (u->url, warc_timestamp_str,
warc_request_uuid, warc_ip,
warc_tmp, warc_payload_offset);
if (! warc_result)
{
CLOSE_INVALIDATE (sock);
retval = WARC_ERR;
goto cleanup;
}
/* warc_write_request_record has also closed warc_tmp. */
}
/* Repeat while we receive a 10x response code. */
{
bool _repeat;
do
{
head = read_http_response_head (sock);
if (!head)
{
if (errno == 0)
{
logputs (LOG_NOTQUIET, _("No data received.\n"));
CLOSE_INVALIDATE (sock);
retval = HEOF;
}
else
{
logprintf (LOG_NOTQUIET, _("Read error (%s) in headers.\n"),
fd_errstr (sock));
CLOSE_INVALIDATE (sock);
retval = HERR;
}
goto cleanup;
}
DEBUGP (("\n---response begin---\n%s---response end---\n", head));
resp = resp_new (head);
/* Check for status line. */
xfree (message);
statcode = resp_status (resp, &message);
if (statcode < 0)
{
char *tms = datetime_str (time (NULL));
logprintf (LOG_VERBOSE, "%d\n", statcode);
logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"), tms, statcode,
quotearg_style (escape_quoting_style,
_("Malformed status line")));
CLOSE_INVALIDATE (sock);
retval = HERR;
goto cleanup;
}
if (H_10X (statcode))
{
xfree (head);
resp_free (&resp);
_repeat = true;
DEBUGP (("Ignoring response\n"));
}
else
{
_repeat = false;
}
}
while (_repeat);
}
xfree (hs->message);
hs->message = xstrdup (message);
if (!opt.server_response)
logprintf (LOG_VERBOSE, "%2d %s\n", statcode,
message ? quotearg_style (escape_quoting_style, message) : "");
else
{
logprintf (LOG_VERBOSE, "\n");
print_server_response (resp, " ");
}
if (!opt.ignore_length
&& resp_header_copy (resp, "Content-Length", hdrval, sizeof (hdrval)))
{
wgint parsed;
errno = 0;
parsed = str_to_wgint (hdrval, NULL, 10);
if (parsed == WGINT_MAX && errno == ERANGE)
{
/* Out of range.
#### If Content-Length is out of range, it most likely
means that the file is larger than 2G and that we're
compiled without LFS. In that case we should probably
refuse to even attempt to download the file. */
contlen = -1;
}
else if (parsed < 0)
{
/* Negative Content-Length; nonsensical, so we can't
assume any information about the content to receive. */
contlen = -1;
}
else
contlen = parsed;
}
/* Check for keep-alive related responses. */
if (!inhibit_keep_alive)
{
if (resp_header_copy (resp, "Connection", hdrval, sizeof (hdrval)))
{
if (0 == c_strcasecmp (hdrval, "Close"))
keep_alive = false;
}
}
chunked_transfer_encoding = false;
if (resp_header_copy (resp, "Transfer-Encoding", hdrval, sizeof (hdrval))
&& 0 == c_strcasecmp (hdrval, "chunked"))
chunked_transfer_encoding = true;
/* Handle (possibly multiple instances of) the Set-Cookie header. */
if (opt.cookies)
{
int scpos;
const char *scbeg, *scend;
/* The jar should have been created by now. */
assert (wget_cookie_jar != NULL);
for (scpos = 0;
(scpos = resp_header_locate (resp, "Set-Cookie", scpos,
&scbeg, &scend)) != -1;
++scpos)
{
char *set_cookie; BOUNDED_TO_ALLOCA (scbeg, scend, set_cookie);
cookie_handle_set_cookie (wget_cookie_jar, u->host, u->port,
u->path, set_cookie);
}
}
if (keep_alive)
/* The server has promised that it will not close the connection
when we're done. This means that we can register it. */
register_persistent (conn->host, conn->port, sock, using_ssl);
#ifdef HAVE_METALINK
/* We need to check for the Metalink data in the very first response
we get from the server (before redirections, authorization, etc.). */
if (metalink)
{
hs->metalink = metalink_from_http (resp, hs, u);
/* Bugfix: hs->local_file is NULL (opt.content_disposition). */
if (!hs->local_file && hs->metalink && hs->metalink->origin)
hs->local_file = xstrdup (hs->metalink->origin);
xfree (hs->message);
retval = RETR_WITH_METALINK;
CLOSE_FINISH (sock);
goto cleanup;
}
#endif
if (statcode == HTTP_STATUS_UNAUTHORIZED)
{
/* Authorization is required. */
uerr_t auth_err = RETROK;
bool retry;
/* Normally we are not interested in the response body.
But if we are writing a WARC file we are: we like to keep everything. */
if (warc_enabled)
{
int _err;
type = resp_header_strdup (resp, "Content-Type");
_err = read_response_body (hs, sock, NULL, contlen, 0,
chunked_transfer_encoding,
u->url, warc_timestamp_str,
warc_request_uuid, warc_ip, type,
statcode, head);
xfree (type);
if (_err != RETRFINISHED || hs->res < 0)
{
CLOSE_INVALIDATE (sock);
retval = _err;
goto cleanup;
}
else
CLOSE_FINISH (sock);
}
else
{
/* Since WARC is disabled, we are not interested in the response body. */
if (keep_alive && !head_only
&& skip_short_body (sock, contlen, chunked_transfer_encoding))
CLOSE_FINISH (sock);
else
CLOSE_INVALIDATE (sock);
}
pconn.authorized = false;
{
auth_err = check_auth (u, user, passwd, resp, req,
&ntlm_seen, &retry,
&basic_auth_finished,
&auth_finished);
if (auth_err == RETROK && retry)
{
xfree (hs->message);
resp_free (&resp);
xfree (message);
xfree (head);
goto retry_with_auth;
}
}
if (auth_err == RETROK)
retval = AUTHFAILED;
else
retval = auth_err;
goto cleanup;
}
else /* statcode != HTTP_STATUS_UNAUTHORIZED */
{
/* Kludge: if NTLM is used, mark the TCP connection as authorized. */
if (ntlm_seen)
pconn.authorized = true;
}
{
uerr_t ret = check_file_output (u, hs, resp, hdrval, sizeof hdrval);
if (ret != RETROK)
{
retval = ret;
goto cleanup;
}
}
hs->statcode = statcode;
if (statcode == -1)
hs->error = xstrdup (_("Malformed status line"));
else if (!*message)
hs->error = xstrdup (_("(no description)"));
else
hs->error = xstrdup (message);
#ifdef HAVE_HSTS
if (opt.hsts && hsts_store)
{
hsts_params = resp_header_strdup (resp, "Strict-Transport-Security");
if (parse_strict_transport_security (hsts_params, &max_age, &include_subdomains))
{
/* process strict transport security */
if (hsts_store_entry (hsts_store, u->scheme, u->host, u->port, max_age, include_subdomains))
DEBUGP(("Added new HSTS host: %s:%u (max-age: %lu, includeSubdomains: %s)\n",
u->host,
(unsigned) u->port,
(unsigned long) max_age,
(include_subdomains ? "true" : "false")));
else
DEBUGP(("Updated HSTS host: %s:%u (max-age: %lu, includeSubdomains: %s)\n",
u->host,
(unsigned) u->port,
(unsigned long) max_age,
(include_subdomains ? "true" : "false")));
}
}
#endif
type = resp_header_strdup (resp, "Content-Type");
if (type)
{
char *tmp = strchr (type, ';');
if (tmp)
{
#ifdef ENABLE_IRI
/* sXXXav: only needed if IRI support is enabled */
char *tmp2 = tmp + 1;
#endif
while (tmp > type && c_isspace (tmp[-1]))
--tmp;
*tmp = '\0';
#ifdef ENABLE_IRI
/* Try to get remote encoding if needed */
if (opt.enable_iri && !opt.encoding_remote)
{
tmp = parse_charset (tmp2);
if (tmp)
set_content_encoding (iri, tmp);
xfree (tmp);
}
#endif
}
}
hs->newloc = resp_header_strdup (resp, "Location");
hs->remote_time = resp_header_strdup (resp, "Last-Modified");
if (!hs->remote_time) // now look for the Wayback Machine's timestamp
hs->remote_time = resp_header_strdup (resp, "X-Archive-Orig-last-modified");
if (resp_header_copy (resp, "Content-Range", hdrval, sizeof (hdrval)))
{
wgint first_byte_pos, last_byte_pos, entity_length;
if (parse_content_range (hdrval, &first_byte_pos, &last_byte_pos,
&entity_length))
{
contrange = first_byte_pos;
contlen = last_byte_pos - first_byte_pos + 1;
}
}
if (resp_header_copy (resp, "Content-Encoding", hdrval, sizeof (hdrval)))
{
hs->local_encoding = ENC_INVALID;
switch (hdrval[0])
{
case 'b': case 'B':
if (0 == c_strcasecmp(hdrval, "br"))
hs->local_encoding = ENC_BROTLI;
break;
case 'c': case 'C':
if (0 == c_strcasecmp(hdrval, "compress"))
hs->local_encoding = ENC_COMPRESS;
break;
case 'd': case 'D':
if (0 == c_strcasecmp(hdrval, "deflate"))
hs->local_encoding = ENC_DEFLATE;
break;
case 'g': case 'G':
if (0 == c_strcasecmp(hdrval, "gzip"))
hs->local_encoding = ENC_GZIP;
break;
case 'i': case 'I':
if (0 == c_strcasecmp(hdrval, "identity"))
hs->local_encoding = ENC_NONE;
break;
case 'x': case 'X':
if (0 == c_strcasecmp(hdrval, "x-compress"))
hs->local_encoding = ENC_COMPRESS;
else if (0 == c_strcasecmp(hdrval, "x-gzip"))
hs->local_encoding = ENC_GZIP;
break;
case '\0':
hs->local_encoding = ENC_NONE;
}
if (hs->local_encoding == ENC_INVALID)
{
DEBUGP (("Unrecognized Content-Encoding: %s\n", hdrval));
hs->local_encoding = ENC_NONE;
}
#ifdef HAVE_LIBZ
else if (hs->local_encoding == ENC_GZIP
&& opt.compression != compression_none)
{
const char *p;
/* Make sure the Content-Type is not gzip before decompressing */
if (type)
{
p = strchr (type, '/');
if (p == NULL)
{
hs->remote_encoding = ENC_GZIP;
hs->local_encoding = ENC_NONE;
}
else
{
p++;
if (c_tolower(p[0]) == 'x' && p[1] == '-')
p += 2;
if (0 != c_strcasecmp (p, "gzip"))
{
hs->remote_encoding = ENC_GZIP;
hs->local_encoding = ENC_NONE;
}
}
}
else
{
hs->remote_encoding = ENC_GZIP;
hs->local_encoding = ENC_NONE;
}
/* don't uncompress if a file ends with '.gz' or '.tgz' */
if (hs->remote_encoding == ENC_GZIP
&& (p = strrchr(u->file, '.'))
&& (c_strcasecmp(p, ".gz") == 0 || c_strcasecmp(p, ".tgz") == 0))
{
DEBUGP (("Enabling broken server workaround. Will not decompress this GZip file.\n"));
hs->remote_encoding = ENC_NONE;
}
}
#endif
}
/* 20x responses are counted among successful by default. */
if (H_20X (statcode))
*dt |= RETROKF;
if (statcode == HTTP_STATUS_NO_CONTENT)
{
/* 204 response has no body (RFC 2616, 4.3) */
/* In case the caller cares to look... */
hs->len = 0;
hs->res = 0;
hs->restval = 0;
CLOSE_FINISH (sock);
retval = RETRFINISHED;
goto cleanup;
}
/* Return if redirected. */
if (H_REDIRECTED (statcode) || statcode == HTTP_STATUS_MULTIPLE_CHOICES)
{
/* RFC2068 says that in case of the 300 (multiple choices)
response, the server can output a preferred URL through
`Location' header; otherwise, the request should be treated
like GET. So, if the location is set, it will be a
redirection; otherwise, just proceed normally. */
if (statcode == HTTP_STATUS_MULTIPLE_CHOICES && !hs->newloc)
*dt |= RETROKF;
else
{
logprintf (LOG_VERBOSE,
_("Location: %s%s\n"),
hs->newloc ? escnonprint_uri (hs->newloc) : _("unspecified"),
hs->newloc ? _(" [following]") : "");
/* In case the caller cares to look... */
hs->len = 0;
hs->res = 0;
hs->restval = 0;
/* Normally we are not interested in the response body of a redirect.
But if we are writing a WARC file we are: we like to keep everything. */
if (warc_enabled)
{
int _err = read_response_body (hs, sock, NULL, contlen, 0,
chunked_transfer_encoding,
u->url, warc_timestamp_str,
warc_request_uuid, warc_ip, type,
statcode, head);
if (_err != RETRFINISHED || hs->res < 0)
{
CLOSE_INVALIDATE (sock);
retval = _err;
goto cleanup;
}
else
CLOSE_FINISH (sock);
}
else
{
/* Since WARC is disabled, we are not interested in the response body. */
if (keep_alive && !head_only
&& skip_short_body (sock, contlen, chunked_transfer_encoding))
CLOSE_FINISH (sock);
else
CLOSE_INVALIDATE (sock);
}
/* From RFC2616: The status codes 303 and 307 have
been added for servers that wish to make unambiguously
clear which kind of reaction is expected of the client.
A 307 should be redirected using the same method,
in other words, a POST should be preserved and not
converted to a GET in that case.
With strict adherence to RFC2616, POST requests are not
converted to a GET request on 301 Permanent Redirect
or 302 Temporary Redirect.
A switch may be provided later based on the HTTPbis draft
that allows clients to convert POST requests to GET
requests on 301 and 302 response codes. */
switch (statcode)
{
case HTTP_STATUS_TEMPORARY_REDIRECT:
case HTTP_STATUS_PERMANENT_REDIRECT:
retval = NEWLOCATION_KEEP_POST;
goto cleanup;
case HTTP_STATUS_MOVED_PERMANENTLY:
if (opt.method && c_strcasecmp (opt.method, "post") != 0)
{
retval = NEWLOCATION_KEEP_POST;
goto cleanup;
}
break;
case HTTP_STATUS_MOVED_TEMPORARILY:
if (opt.method && c_strcasecmp (opt.method, "post") != 0)
{
retval = NEWLOCATION_KEEP_POST;
goto cleanup;
}
break;
}
retval = NEWLOCATION;
goto cleanup;
}
}
if (cond_get)
{
if (statcode == HTTP_STATUS_NOT_MODIFIED)
{
logprintf (LOG_VERBOSE,
_ ("File %s not modified on server. Omitting download.\n\n"),
quote (hs->local_file));
*dt |= RETROKF;
CLOSE_FINISH (sock);
retval = RETRUNNEEDED;
goto cleanup;
}
}
set_content_type (dt, type);
if (opt.adjust_extension)
{
const char *encoding_ext = NULL;
switch (hs->local_encoding)
{
case ENC_INVALID:
case ENC_NONE:
break;
case ENC_BROTLI:
encoding_ext = ".br";
break;
case ENC_COMPRESS:
encoding_ext = ".Z";
break;
case ENC_DEFLATE:
encoding_ext = ".zlib";
break;
case ENC_GZIP:
encoding_ext = ".gz";
break;
default:
DEBUGP (("No extension found for encoding %d\n",
hs->local_encoding));
}
if (encoding_ext != NULL)
{
char *file_ext = strrchr (hs->local_file, '.');
/* strip Content-Encoding extension (it will be re-added later) */
if (file_ext != NULL && 0 == strcasecmp (file_ext, encoding_ext))
*file_ext = '\0';
}
if (*dt & TEXTHTML)
/* -E / --adjust-extension / adjust_extension = on was specified,
and this is a text/html file. If some case-insensitive
variation on ".htm[l]" isn't already the file's suffix,
tack on ".html". */
{
ensure_extension (hs, ".html", dt);
}
else if (*dt & TEXTCSS)
{
ensure_extension (hs, ".css", dt);
}
if (encoding_ext != NULL)
{
ensure_extension (hs, encoding_ext, dt);
}
}
if (cond_get)
{
/* Handle the case when server ignores If-Modified-Since header. */
if (statcode == HTTP_STATUS_OK && hs->remote_time)
{
time_t tmr = http_atotm (hs->remote_time);
/* Check if the local file is up-to-date based on Last-Modified header
and content length. */
if (tmr != (time_t) - 1 && tmr <= hs->orig_file_tstamp
&& (contlen == -1 || contlen == hs->orig_file_size))
{
logprintf (LOG_VERBOSE,
_("Server ignored If-Modified-Since header for file %s.\n"
"You might want to add --no-if-modified-since option."
"\n\n"),
quote (hs->local_file));
*dt |= RETROKF;
CLOSE_INVALIDATE (sock);
retval = RETRUNNEEDED;
goto cleanup;
}
}
}
if (statcode == HTTP_STATUS_RANGE_NOT_SATISFIABLE
&& hs->restval < (contlen + contrange))
{
/* The file was not completely downloaded,
yet the server claims the range is invalid.
Bail out. */
CLOSE_INVALIDATE (sock);
retval = RANGEERR;
goto cleanup;
}
if (statcode == HTTP_STATUS_RANGE_NOT_SATISFIABLE
|| (!opt.timestamping && hs->restval > 0 && statcode == HTTP_STATUS_OK
&& contrange == 0 && contlen >= 0 && hs->restval >= contlen))
{
/* If `-c' is in use and the file has been fully downloaded (or
the remote file has shrunk), Wget effectively requests bytes
after the end of file and the server response with 416
(or 200 with a <= Content-Length. */
logputs (LOG_VERBOSE, _("\
\n The file is already fully retrieved; nothing to do.\n\n"));
/* In case the caller inspects. */
hs->len = contlen;
hs->res = 0;
/* Mark as successfully retrieved. */
*dt |= RETROKF;
/* Try to maintain the keep-alive connection. It is often cheaper to
* consume some bytes which have already been sent than to negotiate
* a new connection. However, if the body is too large, or we don't
* care about keep-alive, then simply terminate the connection */
if (keep_alive &&
skip_short_body (sock, contlen, chunked_transfer_encoding))
CLOSE_FINISH (sock);
else
CLOSE_INVALIDATE (sock);
retval = RETRUNNEEDED;
goto cleanup;
}
if ((contrange != 0 && contrange != hs->restval)
|| (H_PARTIAL (statcode) && !contrange && hs->restval))
{
/* The Range request was somehow misunderstood by the server.
Bail out. */
CLOSE_INVALIDATE (sock);
retval = RANGEERR;
goto cleanup;
}
if (contlen == -1)
hs->contlen = -1;
/* If the response is gzipped, the uncompressed size is unknown. */
else if (hs->remote_encoding == ENC_GZIP)
hs->contlen = -1;
else
hs->contlen = contlen + contrange;
if (opt.verbose)
{
if (*dt & RETROKF)
{
/* No need to print this output if the body won't be
downloaded at all, or if the original server response is
printed. */
logputs (LOG_VERBOSE, _("Length: "));
if (contlen != -1)
{
logputs (LOG_VERBOSE, number_to_static_string (contlen + contrange));
if (contlen + contrange >= 1024)
logprintf (LOG_VERBOSE, " (%s)",
human_readable (contlen + contrange, 10, 1));
if (contrange)
{
if (contlen >= 1024)
logprintf (LOG_VERBOSE, _(", %s (%s) remaining"),
number_to_static_string (contlen),
human_readable (contlen, 10, 1));
else
logprintf (LOG_VERBOSE, _(", %s remaining"),
number_to_static_string (contlen));
}
}
else
logputs (LOG_VERBOSE,
opt.ignore_length ? _("ignored") : _("unspecified"));
if (type)
logprintf (LOG_VERBOSE, " [%s]\n", quotearg_style (escape_quoting_style, type));
else
logputs (LOG_VERBOSE, "\n");
}
}
/* Return if we have no intention of further downloading. */
if ((!(*dt & RETROKF) && !opt.content_on_error) || head_only || (opt.spider && !opt.recursive))
{
/* In case the caller cares to look... */
hs->len = 0;
hs->res = 0;
hs->restval = 0;
/* Normally we are not interested in the response body of a error responses.
But if we are writing a WARC file we are: we like to keep everything. */
if (warc_enabled)
{
int _err = read_response_body (hs, sock, NULL, contlen, 0,
chunked_transfer_encoding,
u->url, warc_timestamp_str,
warc_request_uuid, warc_ip, type,
statcode, head);
if (_err != RETRFINISHED || hs->res < 0)
{
CLOSE_INVALIDATE (sock);
retval = _err;
goto cleanup;
}
CLOSE_FINISH (sock);
}
else
{
/* Since WARC is disabled, we are not interested in the response body. */
if (head_only)
/* Pre-1.10 Wget used CLOSE_INVALIDATE here. Now we trust the
servers not to send body in response to a HEAD request, and
those that do will likely be caught by test_socket_open.
If not, they can be worked around using
`--no-http-keep-alive'. */
CLOSE_FINISH (sock);
else if (opt.spider && !opt.recursive)
/* we just want to see if the page exists - no downloading required */
CLOSE_INVALIDATE (sock);
else if (keep_alive
&& skip_short_body (sock, contlen, chunked_transfer_encoding))
/* Successfully skipped the body; also keep using the socket. */
CLOSE_FINISH (sock);
else
CLOSE_INVALIDATE (sock);
}
if (statcode == HTTP_STATUS_GATEWAY_TIMEOUT)
retval = GATEWAYTIMEOUT;
else
retval = RETRFINISHED;
goto cleanup;
}
err = open_output_stream (hs, count, &fp);
if (err != RETROK)
{
CLOSE_INVALIDATE (sock);
retval = err;
goto cleanup;
}
#ifdef ENABLE_XATTR
if (opt.enable_xattr)
{
if (original_url != u)
set_file_metadata (u->url, original_url->url, fp);
else
set_file_metadata (u->url, NULL, fp);
}
#endif
err = read_response_body (hs, sock, fp, contlen, contrange,
chunked_transfer_encoding,
u->url, warc_timestamp_str,
warc_request_uuid, warc_ip, type,
statcode, head);
if (hs->res >= 0)
CLOSE_FINISH (sock);
else
CLOSE_INVALIDATE (sock);
if (!output_stream)
fclose (fp);
retval = err;
cleanup:
xfree (head);
xfree (type);
xfree (message);
resp_free (&resp);
request_free (&req);
return retval;
}
| null | 0 | gethttp (const struct url *u, struct url *original_url, struct http_stat *hs,
int *dt, struct url *proxy, struct iri *iri, int count)
{
struct request *req = NULL;
char *type = NULL;
char *user, *passwd;
char *proxyauth;
int statcode;
int write_error;
wgint contlen, contrange;
const struct url *conn;
FILE *fp;
int err;
uerr_t retval;
#ifdef HAVE_HSTS
#ifdef TESTING
/* we don't link against main.o when we're testing */
hsts_store_t hsts_store = NULL;
#else
extern hsts_store_t hsts_store;
#endif
const char *hsts_params;
time_t max_age;
bool include_subdomains;
#endif
int sock = -1;
/* Set to 1 when the authorization has already been sent and should
not be tried again. */
bool auth_finished = false;
/* Set to 1 when just globally-set Basic authorization has been sent;
* should prevent further Basic negotiations, but not other
* mechanisms. */
bool basic_auth_finished = false;
/* Whether NTLM authentication is used for this request. */
bool ntlm_seen = false;
/* Whether our connection to the remote host is through SSL. */
bool using_ssl = false;
/* Whether a HEAD request will be issued (as opposed to GET or
POST). */
bool head_only = !!(*dt & HEAD_ONLY);
/* Whether conditional get request will be issued. */
bool cond_get = !!(*dt & IF_MODIFIED_SINCE);
#ifdef HAVE_METALINK
/* Are we looking for metalink info in HTTP headers? */
bool metalink = !!(*dt & METALINK_METADATA);
#endif
char *head = NULL;
struct response *resp = NULL;
char hdrval[512];
char *message = NULL;
/* Declare WARC variables. */
bool warc_enabled = (opt.warc_filename != NULL);
FILE *warc_tmp = NULL;
char warc_timestamp_str [21];
char warc_request_uuid [48];
ip_address *warc_ip = NULL;
off_t warc_payload_offset = -1;
/* Whether this connection will be kept alive after the HTTP request
is done. */
bool keep_alive;
/* Is the server using the chunked transfer encoding? */
bool chunked_transfer_encoding = false;
/* Whether keep-alive should be inhibited. */
bool inhibit_keep_alive =
!opt.http_keep_alive || opt.ignore_length;
/* Headers sent when using POST. */
wgint body_data_size = 0;
#ifdef HAVE_SSL
if (u->scheme == SCHEME_HTTPS)
{
/* Initialize the SSL context. After this has once been done,
it becomes a no-op. */
if (!ssl_init ())
{
scheme_disable (SCHEME_HTTPS);
logprintf (LOG_NOTQUIET,
_("Disabling SSL due to encountered errors.\n"));
retval = SSLINITFAILED;
goto cleanup;
}
}
#endif /* HAVE_SSL */
/* Initialize certain elements of struct http_stat. */
hs->len = 0;
hs->contlen = -1;
hs->res = -1;
hs->rderrmsg = NULL;
hs->newloc = NULL;
xfree (hs->remote_time);
hs->error = NULL;
hs->message = NULL;
hs->local_encoding = ENC_NONE;
hs->remote_encoding = ENC_NONE;
conn = u;
{
uerr_t ret;
req = initialize_request (u, hs, dt, proxy, inhibit_keep_alive,
&basic_auth_finished, &body_data_size,
&user, &passwd, &ret);
if (req == NULL)
{
retval = ret;
goto cleanup;
}
}
retry_with_auth:
/* We need to come back here when the initial attempt to retrieve
without authorization header fails. (Expected to happen at least
for the Digest authorization scheme.) */
if (opt.cookies)
request_set_header (req, "Cookie",
cookie_header (wget_cookie_jar,
u->host, u->port, u->path,
#ifdef HAVE_SSL
u->scheme == SCHEME_HTTPS
#else
0
#endif
),
rel_value);
/* Add the user headers. */
if (opt.user_headers)
{
int i;
for (i = 0; opt.user_headers[i]; i++)
request_set_user_header (req, opt.user_headers[i]);
}
proxyauth = NULL;
if (proxy)
{
conn = proxy;
initialize_proxy_configuration (u, req, proxy, &proxyauth);
}
keep_alive = true;
/* Establish the connection. */
if (inhibit_keep_alive)
keep_alive = false;
{
uerr_t conn_err = establish_connection (u, &conn, hs, proxy, &proxyauth, &req,
&using_ssl, inhibit_keep_alive, &sock);
if (conn_err != RETROK)
{
retval = conn_err;
goto cleanup;
}
}
/* Open the temporary file where we will write the request. */
if (warc_enabled)
{
warc_tmp = warc_tempfile ();
if (warc_tmp == NULL)
{
CLOSE_INVALIDATE (sock);
retval = WARC_TMP_FOPENERR;
goto cleanup;
}
if (! proxy)
{
warc_ip = (ip_address *) alloca (sizeof (ip_address));
socket_ip_address (sock, warc_ip, ENDPOINT_PEER);
}
}
/* Send the request to server. */
write_error = request_send (req, sock, warc_tmp);
if (write_error >= 0)
{
if (opt.body_data)
{
DEBUGP (("[BODY data: %s]\n", opt.body_data));
write_error = fd_write (sock, opt.body_data, body_data_size, -1);
if (write_error >= 0 && warc_tmp != NULL)
{
int warc_tmp_written;
/* Remember end of headers / start of payload. */
warc_payload_offset = ftello (warc_tmp);
/* Write a copy of the data to the WARC record. */
warc_tmp_written = fwrite (opt.body_data, 1, body_data_size, warc_tmp);
if (warc_tmp_written != body_data_size)
write_error = -2;
}
}
else if (opt.body_file && body_data_size != 0)
{
if (warc_tmp != NULL)
/* Remember end of headers / start of payload */
warc_payload_offset = ftello (warc_tmp);
write_error = body_file_send (sock, opt.body_file, body_data_size, warc_tmp);
}
}
if (write_error < 0)
{
CLOSE_INVALIDATE (sock);
if (warc_tmp != NULL)
fclose (warc_tmp);
if (write_error == -2)
retval = WARC_TMP_FWRITEERR;
else
retval = WRITEFAILED;
goto cleanup;
}
logprintf (LOG_VERBOSE, _("%s request sent, awaiting response... "),
proxy ? "Proxy" : "HTTP");
contlen = -1;
contrange = 0;
*dt &= ~RETROKF;
if (warc_enabled)
{
bool warc_result;
/* Generate a timestamp and uuid for this request. */
warc_timestamp (warc_timestamp_str, sizeof (warc_timestamp_str));
warc_uuid_str (warc_request_uuid);
/* Create a request record and store it in the WARC file. */
warc_result = warc_write_request_record (u->url, warc_timestamp_str,
warc_request_uuid, warc_ip,
warc_tmp, warc_payload_offset);
if (! warc_result)
{
CLOSE_INVALIDATE (sock);
retval = WARC_ERR;
goto cleanup;
}
/* warc_write_request_record has also closed warc_tmp. */
}
/* Repeat while we receive a 10x response code. */
{
bool _repeat;
do
{
head = read_http_response_head (sock);
if (!head)
{
if (errno == 0)
{
logputs (LOG_NOTQUIET, _("No data received.\n"));
CLOSE_INVALIDATE (sock);
retval = HEOF;
}
else
{
logprintf (LOG_NOTQUIET, _("Read error (%s) in headers.\n"),
fd_errstr (sock));
CLOSE_INVALIDATE (sock);
retval = HERR;
}
goto cleanup;
}
DEBUGP (("\n---response begin---\n%s---response end---\n", head));
resp = resp_new (head);
/* Check for status line. */
xfree (message);
statcode = resp_status (resp, &message);
if (statcode < 0)
{
char *tms = datetime_str (time (NULL));
logprintf (LOG_VERBOSE, "%d\n", statcode);
logprintf (LOG_NOTQUIET, _("%s ERROR %d: %s.\n"), tms, statcode,
quotearg_style (escape_quoting_style,
_("Malformed status line")));
CLOSE_INVALIDATE (sock);
retval = HERR;
goto cleanup;
}
if (H_10X (statcode))
{
xfree (head);
resp_free (&resp);
_repeat = true;
DEBUGP (("Ignoring response\n"));
}
else
{
_repeat = false;
}
}
while (_repeat);
}
xfree (hs->message);
hs->message = xstrdup (message);
if (!opt.server_response)
logprintf (LOG_VERBOSE, "%2d %s\n", statcode,
message ? quotearg_style (escape_quoting_style, message) : "");
else
{
logprintf (LOG_VERBOSE, "\n");
print_server_response (resp, " ");
}
if (!opt.ignore_length
&& resp_header_copy (resp, "Content-Length", hdrval, sizeof (hdrval)))
{
wgint parsed;
errno = 0;
parsed = str_to_wgint (hdrval, NULL, 10);
if (parsed == WGINT_MAX && errno == ERANGE)
{
/* Out of range.
#### If Content-Length is out of range, it most likely
means that the file is larger than 2G and that we're
compiled without LFS. In that case we should probably
refuse to even attempt to download the file. */
contlen = -1;
}
else if (parsed < 0)
{
/* Negative Content-Length; nonsensical, so we can't
assume any information about the content to receive. */
contlen = -1;
}
else
contlen = parsed;
}
/* Check for keep-alive related responses. */
if (!inhibit_keep_alive)
{
if (resp_header_copy (resp, "Connection", hdrval, sizeof (hdrval)))
{
if (0 == c_strcasecmp (hdrval, "Close"))
keep_alive = false;
}
}
chunked_transfer_encoding = false;
if (resp_header_copy (resp, "Transfer-Encoding", hdrval, sizeof (hdrval))
&& 0 == c_strcasecmp (hdrval, "chunked"))
chunked_transfer_encoding = true;
/* Handle (possibly multiple instances of) the Set-Cookie header. */
if (opt.cookies)
{
int scpos;
const char *scbeg, *scend;
/* The jar should have been created by now. */
assert (wget_cookie_jar != NULL);
for (scpos = 0;
(scpos = resp_header_locate (resp, "Set-Cookie", scpos,
&scbeg, &scend)) != -1;
++scpos)
{
char *set_cookie; BOUNDED_TO_ALLOCA (scbeg, scend, set_cookie);
cookie_handle_set_cookie (wget_cookie_jar, u->host, u->port,
u->path, set_cookie);
}
}
if (keep_alive)
/* The server has promised that it will not close the connection
when we're done. This means that we can register it. */
register_persistent (conn->host, conn->port, sock, using_ssl);
#ifdef HAVE_METALINK
/* We need to check for the Metalink data in the very first response
we get from the server (before redirections, authorization, etc.). */
if (metalink)
{
hs->metalink = metalink_from_http (resp, hs, u);
/* Bugfix: hs->local_file is NULL (opt.content_disposition). */
if (!hs->local_file && hs->metalink && hs->metalink->origin)
hs->local_file = xstrdup (hs->metalink->origin);
xfree (hs->message);
retval = RETR_WITH_METALINK;
CLOSE_FINISH (sock);
goto cleanup;
}
#endif
if (statcode == HTTP_STATUS_UNAUTHORIZED)
{
/* Authorization is required. */
uerr_t auth_err = RETROK;
bool retry;
/* Normally we are not interested in the response body.
But if we are writing a WARC file we are: we like to keep everything. */
if (warc_enabled)
{
int _err;
type = resp_header_strdup (resp, "Content-Type");
_err = read_response_body (hs, sock, NULL, contlen, 0,
chunked_transfer_encoding,
u->url, warc_timestamp_str,
warc_request_uuid, warc_ip, type,
statcode, head);
xfree (type);
if (_err != RETRFINISHED || hs->res < 0)
{
CLOSE_INVALIDATE (sock);
retval = _err;
goto cleanup;
}
else
CLOSE_FINISH (sock);
}
else
{
/* Since WARC is disabled, we are not interested in the response body. */
if (keep_alive && !head_only
&& skip_short_body (sock, contlen, chunked_transfer_encoding))
CLOSE_FINISH (sock);
else
CLOSE_INVALIDATE (sock);
}
pconn.authorized = false;
{
auth_err = check_auth (u, user, passwd, resp, req,
&ntlm_seen, &retry,
&basic_auth_finished,
&auth_finished);
if (auth_err == RETROK && retry)
{
xfree (hs->message);
resp_free (&resp);
xfree (message);
xfree (head);
goto retry_with_auth;
}
}
if (auth_err == RETROK)
retval = AUTHFAILED;
else
retval = auth_err;
goto cleanup;
}
else /* statcode != HTTP_STATUS_UNAUTHORIZED */
{
/* Kludge: if NTLM is used, mark the TCP connection as authorized. */
if (ntlm_seen)
pconn.authorized = true;
}
{
uerr_t ret = check_file_output (u, hs, resp, hdrval, sizeof hdrval);
if (ret != RETROK)
{
retval = ret;
goto cleanup;
}
}
hs->statcode = statcode;
if (statcode == -1)
hs->error = xstrdup (_("Malformed status line"));
else if (!*message)
hs->error = xstrdup (_("(no description)"));
else
hs->error = xstrdup (message);
#ifdef HAVE_HSTS
if (opt.hsts && hsts_store)
{
hsts_params = resp_header_strdup (resp, "Strict-Transport-Security");
if (parse_strict_transport_security (hsts_params, &max_age, &include_subdomains))
{
/* process strict transport security */
if (hsts_store_entry (hsts_store, u->scheme, u->host, u->port, max_age, include_subdomains))
DEBUGP(("Added new HSTS host: %s:%u (max-age: %lu, includeSubdomains: %s)\n",
u->host,
(unsigned) u->port,
(unsigned long) max_age,
(include_subdomains ? "true" : "false")));
else
DEBUGP(("Updated HSTS host: %s:%u (max-age: %lu, includeSubdomains: %s)\n",
u->host,
(unsigned) u->port,
(unsigned long) max_age,
(include_subdomains ? "true" : "false")));
}
}
#endif
type = resp_header_strdup (resp, "Content-Type");
if (type)
{
char *tmp = strchr (type, ';');
if (tmp)
{
#ifdef ENABLE_IRI
/* sXXXav: only needed if IRI support is enabled */
char *tmp2 = tmp + 1;
#endif
while (tmp > type && c_isspace (tmp[-1]))
--tmp;
*tmp = '\0';
#ifdef ENABLE_IRI
/* Try to get remote encoding if needed */
if (opt.enable_iri && !opt.encoding_remote)
{
tmp = parse_charset (tmp2);
if (tmp)
set_content_encoding (iri, tmp);
xfree (tmp);
}
#endif
}
}
hs->newloc = resp_header_strdup (resp, "Location");
hs->remote_time = resp_header_strdup (resp, "Last-Modified");
if (!hs->remote_time) // now look for the Wayback Machine's timestamp
hs->remote_time = resp_header_strdup (resp, "X-Archive-Orig-last-modified");
if (resp_header_copy (resp, "Content-Range", hdrval, sizeof (hdrval)))
{
wgint first_byte_pos, last_byte_pos, entity_length;
if (parse_content_range (hdrval, &first_byte_pos, &last_byte_pos,
&entity_length))
{
contrange = first_byte_pos;
contlen = last_byte_pos - first_byte_pos + 1;
}
}
if (resp_header_copy (resp, "Content-Encoding", hdrval, sizeof (hdrval)))
{
hs->local_encoding = ENC_INVALID;
switch (hdrval[0])
{
case 'b': case 'B':
if (0 == c_strcasecmp(hdrval, "br"))
hs->local_encoding = ENC_BROTLI;
break;
case 'c': case 'C':
if (0 == c_strcasecmp(hdrval, "compress"))
hs->local_encoding = ENC_COMPRESS;
break;
case 'd': case 'D':
if (0 == c_strcasecmp(hdrval, "deflate"))
hs->local_encoding = ENC_DEFLATE;
break;
case 'g': case 'G':
if (0 == c_strcasecmp(hdrval, "gzip"))
hs->local_encoding = ENC_GZIP;
break;
case 'i': case 'I':
if (0 == c_strcasecmp(hdrval, "identity"))
hs->local_encoding = ENC_NONE;
break;
case 'x': case 'X':
if (0 == c_strcasecmp(hdrval, "x-compress"))
hs->local_encoding = ENC_COMPRESS;
else if (0 == c_strcasecmp(hdrval, "x-gzip"))
hs->local_encoding = ENC_GZIP;
break;
case '\0':
hs->local_encoding = ENC_NONE;
}
if (hs->local_encoding == ENC_INVALID)
{
DEBUGP (("Unrecognized Content-Encoding: %s\n", hdrval));
hs->local_encoding = ENC_NONE;
}
#ifdef HAVE_LIBZ
else if (hs->local_encoding == ENC_GZIP
&& opt.compression != compression_none)
{
const char *p;
/* Make sure the Content-Type is not gzip before decompressing */
if (type)
{
p = strchr (type, '/');
if (p == NULL)
{
hs->remote_encoding = ENC_GZIP;
hs->local_encoding = ENC_NONE;
}
else
{
p++;
if (c_tolower(p[0]) == 'x' && p[1] == '-')
p += 2;
if (0 != c_strcasecmp (p, "gzip"))
{
hs->remote_encoding = ENC_GZIP;
hs->local_encoding = ENC_NONE;
}
}
}
else
{
hs->remote_encoding = ENC_GZIP;
hs->local_encoding = ENC_NONE;
}
/* don't uncompress if a file ends with '.gz' or '.tgz' */
if (hs->remote_encoding == ENC_GZIP
&& (p = strrchr(u->file, '.'))
&& (c_strcasecmp(p, ".gz") == 0 || c_strcasecmp(p, ".tgz") == 0))
{
DEBUGP (("Enabling broken server workaround. Will not decompress this GZip file.\n"));
hs->remote_encoding = ENC_NONE;
}
}
#endif
}
/* 20x responses are counted among successful by default. */
if (H_20X (statcode))
*dt |= RETROKF;
if (statcode == HTTP_STATUS_NO_CONTENT)
{
/* 204 response has no body (RFC 2616, 4.3) */
/* In case the caller cares to look... */
hs->len = 0;
hs->res = 0;
hs->restval = 0;
CLOSE_FINISH (sock);
retval = RETRFINISHED;
goto cleanup;
}
/* Return if redirected. */
if (H_REDIRECTED (statcode) || statcode == HTTP_STATUS_MULTIPLE_CHOICES)
{
/* RFC2068 says that in case of the 300 (multiple choices)
response, the server can output a preferred URL through
`Location' header; otherwise, the request should be treated
like GET. So, if the location is set, it will be a
redirection; otherwise, just proceed normally. */
if (statcode == HTTP_STATUS_MULTIPLE_CHOICES && !hs->newloc)
*dt |= RETROKF;
else
{
logprintf (LOG_VERBOSE,
_("Location: %s%s\n"),
hs->newloc ? escnonprint_uri (hs->newloc) : _("unspecified"),
hs->newloc ? _(" [following]") : "");
/* In case the caller cares to look... */
hs->len = 0;
hs->res = 0;
hs->restval = 0;
/* Normally we are not interested in the response body of a redirect.
But if we are writing a WARC file we are: we like to keep everything. */
if (warc_enabled)
{
int _err = read_response_body (hs, sock, NULL, contlen, 0,
chunked_transfer_encoding,
u->url, warc_timestamp_str,
warc_request_uuid, warc_ip, type,
statcode, head);
if (_err != RETRFINISHED || hs->res < 0)
{
CLOSE_INVALIDATE (sock);
retval = _err;
goto cleanup;
}
else
CLOSE_FINISH (sock);
}
else
{
/* Since WARC is disabled, we are not interested in the response body. */
if (keep_alive && !head_only
&& skip_short_body (sock, contlen, chunked_transfer_encoding))
CLOSE_FINISH (sock);
else
CLOSE_INVALIDATE (sock);
}
/* From RFC2616: The status codes 303 and 307 have
been added for servers that wish to make unambiguously
clear which kind of reaction is expected of the client.
A 307 should be redirected using the same method,
in other words, a POST should be preserved and not
converted to a GET in that case.
With strict adherence to RFC2616, POST requests are not
converted to a GET request on 301 Permanent Redirect
or 302 Temporary Redirect.
A switch may be provided later based on the HTTPbis draft
that allows clients to convert POST requests to GET
requests on 301 and 302 response codes. */
switch (statcode)
{
case HTTP_STATUS_TEMPORARY_REDIRECT:
case HTTP_STATUS_PERMANENT_REDIRECT:
retval = NEWLOCATION_KEEP_POST;
goto cleanup;
case HTTP_STATUS_MOVED_PERMANENTLY:
if (opt.method && c_strcasecmp (opt.method, "post") != 0)
{
retval = NEWLOCATION_KEEP_POST;
goto cleanup;
}
break;
case HTTP_STATUS_MOVED_TEMPORARILY:
if (opt.method && c_strcasecmp (opt.method, "post") != 0)
{
retval = NEWLOCATION_KEEP_POST;
goto cleanup;
}
break;
}
retval = NEWLOCATION;
goto cleanup;
}
}
if (cond_get)
{
if (statcode == HTTP_STATUS_NOT_MODIFIED)
{
logprintf (LOG_VERBOSE,
_ ("File %s not modified on server. Omitting download.\n\n"),
quote (hs->local_file));
*dt |= RETROKF;
CLOSE_FINISH (sock);
retval = RETRUNNEEDED;
goto cleanup;
}
}
set_content_type (dt, type);
if (opt.adjust_extension)
{
const char *encoding_ext = NULL;
switch (hs->local_encoding)
{
case ENC_INVALID:
case ENC_NONE:
break;
case ENC_BROTLI:
encoding_ext = ".br";
break;
case ENC_COMPRESS:
encoding_ext = ".Z";
break;
case ENC_DEFLATE:
encoding_ext = ".zlib";
break;
case ENC_GZIP:
encoding_ext = ".gz";
break;
default:
DEBUGP (("No extension found for encoding %d\n",
hs->local_encoding));
}
if (encoding_ext != NULL)
{
char *file_ext = strrchr (hs->local_file, '.');
/* strip Content-Encoding extension (it will be re-added later) */
if (file_ext != NULL && 0 == strcasecmp (file_ext, encoding_ext))
*file_ext = '\0';
}
if (*dt & TEXTHTML)
/* -E / --adjust-extension / adjust_extension = on was specified,
and this is a text/html file. If some case-insensitive
variation on ".htm[l]" isn't already the file's suffix,
tack on ".html". */
{
ensure_extension (hs, ".html", dt);
}
else if (*dt & TEXTCSS)
{
ensure_extension (hs, ".css", dt);
}
if (encoding_ext != NULL)
{
ensure_extension (hs, encoding_ext, dt);
}
}
if (cond_get)
{
/* Handle the case when server ignores If-Modified-Since header. */
if (statcode == HTTP_STATUS_OK && hs->remote_time)
{
time_t tmr = http_atotm (hs->remote_time);
/* Check if the local file is up-to-date based on Last-Modified header
and content length. */
if (tmr != (time_t) - 1 && tmr <= hs->orig_file_tstamp
&& (contlen == -1 || contlen == hs->orig_file_size))
{
logprintf (LOG_VERBOSE,
_("Server ignored If-Modified-Since header for file %s.\n"
"You might want to add --no-if-modified-since option."
"\n\n"),
quote (hs->local_file));
*dt |= RETROKF;
CLOSE_INVALIDATE (sock);
retval = RETRUNNEEDED;
goto cleanup;
}
}
}
if (statcode == HTTP_STATUS_RANGE_NOT_SATISFIABLE
&& hs->restval < (contlen + contrange))
{
/* The file was not completely downloaded,
yet the server claims the range is invalid.
Bail out. */
CLOSE_INVALIDATE (sock);
retval = RANGEERR;
goto cleanup;
}
if (statcode == HTTP_STATUS_RANGE_NOT_SATISFIABLE
|| (!opt.timestamping && hs->restval > 0 && statcode == HTTP_STATUS_OK
&& contrange == 0 && contlen >= 0 && hs->restval >= contlen))
{
/* If `-c' is in use and the file has been fully downloaded (or
the remote file has shrunk), Wget effectively requests bytes
after the end of file and the server response with 416
(or 200 with a <= Content-Length. */
logputs (LOG_VERBOSE, _("\
\n The file is already fully retrieved; nothing to do.\n\n"));
/* In case the caller inspects. */
hs->len = contlen;
hs->res = 0;
/* Mark as successfully retrieved. */
*dt |= RETROKF;
/* Try to maintain the keep-alive connection. It is often cheaper to
* consume some bytes which have already been sent than to negotiate
* a new connection. However, if the body is too large, or we don't
* care about keep-alive, then simply terminate the connection */
if (keep_alive &&
skip_short_body (sock, contlen, chunked_transfer_encoding))
CLOSE_FINISH (sock);
else
CLOSE_INVALIDATE (sock);
retval = RETRUNNEEDED;
goto cleanup;
}
if ((contrange != 0 && contrange != hs->restval)
|| (H_PARTIAL (statcode) && !contrange && hs->restval))
{
/* The Range request was somehow misunderstood by the server.
Bail out. */
CLOSE_INVALIDATE (sock);
retval = RANGEERR;
goto cleanup;
}
if (contlen == -1)
hs->contlen = -1;
/* If the response is gzipped, the uncompressed size is unknown. */
else if (hs->remote_encoding == ENC_GZIP)
hs->contlen = -1;
else
hs->contlen = contlen + contrange;
if (opt.verbose)
{
if (*dt & RETROKF)
{
/* No need to print this output if the body won't be
downloaded at all, or if the original server response is
printed. */
logputs (LOG_VERBOSE, _("Length: "));
if (contlen != -1)
{
logputs (LOG_VERBOSE, number_to_static_string (contlen + contrange));
if (contlen + contrange >= 1024)
logprintf (LOG_VERBOSE, " (%s)",
human_readable (contlen + contrange, 10, 1));
if (contrange)
{
if (contlen >= 1024)
logprintf (LOG_VERBOSE, _(", %s (%s) remaining"),
number_to_static_string (contlen),
human_readable (contlen, 10, 1));
else
logprintf (LOG_VERBOSE, _(", %s remaining"),
number_to_static_string (contlen));
}
}
else
logputs (LOG_VERBOSE,
opt.ignore_length ? _("ignored") : _("unspecified"));
if (type)
logprintf (LOG_VERBOSE, " [%s]\n", quotearg_style (escape_quoting_style, type));
else
logputs (LOG_VERBOSE, "\n");
}
}
/* Return if we have no intention of further downloading. */
if ((!(*dt & RETROKF) && !opt.content_on_error) || head_only || (opt.spider && !opt.recursive))
{
/* In case the caller cares to look... */
hs->len = 0;
hs->res = 0;
hs->restval = 0;
/* Normally we are not interested in the response body of a error responses.
But if we are writing a WARC file we are: we like to keep everything. */
if (warc_enabled)
{
int _err = read_response_body (hs, sock, NULL, contlen, 0,
chunked_transfer_encoding,
u->url, warc_timestamp_str,
warc_request_uuid, warc_ip, type,
statcode, head);
if (_err != RETRFINISHED || hs->res < 0)
{
CLOSE_INVALIDATE (sock);
retval = _err;
goto cleanup;
}
CLOSE_FINISH (sock);
}
else
{
/* Since WARC is disabled, we are not interested in the response body. */
if (head_only)
/* Pre-1.10 Wget used CLOSE_INVALIDATE here. Now we trust the
servers not to send body in response to a HEAD request, and
those that do will likely be caught by test_socket_open.
If not, they can be worked around using
`--no-http-keep-alive'. */
CLOSE_FINISH (sock);
else if (opt.spider && !opt.recursive)
/* we just want to see if the page exists - no downloading required */
CLOSE_INVALIDATE (sock);
else if (keep_alive
&& skip_short_body (sock, contlen, chunked_transfer_encoding))
/* Successfully skipped the body; also keep using the socket. */
CLOSE_FINISH (sock);
else
CLOSE_INVALIDATE (sock);
}
if (statcode == HTTP_STATUS_GATEWAY_TIMEOUT)
retval = GATEWAYTIMEOUT;
else
retval = RETRFINISHED;
goto cleanup;
}
err = open_output_stream (hs, count, &fp);
if (err != RETROK)
{
CLOSE_INVALIDATE (sock);
retval = err;
goto cleanup;
}
#ifdef ENABLE_XATTR
if (opt.enable_xattr)
{
if (original_url != u)
set_file_metadata (u->url, original_url->url, fp);
else
set_file_metadata (u->url, NULL, fp);
}
#endif
err = read_response_body (hs, sock, fp, contlen, contrange,
chunked_transfer_encoding,
u->url, warc_timestamp_str,
warc_request_uuid, warc_ip, type,
statcode, head);
if (hs->res >= 0)
CLOSE_FINISH (sock);
else
CLOSE_INVALIDATE (sock);
if (!output_stream)
fclose (fp);
retval = err;
cleanup:
xfree (head);
xfree (type);
xfree (message);
resp_free (&resp);
request_free (&req);
return retval;
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,428 | http_atotm (const char *time_string)
{
/* NOTE: Solaris strptime man page claims that %n and %t match white
space, but that's not universally available. Instead, we simply
use ` ' to mean "skip all WS", which works under all strptime
implementations I've tested. */
static const char *time_formats[] = {
"%a, %d %b %Y %T", /* rfc1123: Thu, 29 Jan 1998 22:12:57 */
"%A, %d-%b-%y %T", /* rfc850: Thursday, 29-Jan-98 22:12:57 */
"%a %b %d %T %Y", /* asctime: Thu Jan 29 22:12:57 1998 */
"%a, %d-%b-%Y %T" /* cookies: Thu, 29-Jan-1998 22:12:57
(used in Set-Cookie, defined in the
Netscape cookie specification.) */
};
const char *oldlocale;
char savedlocale[256];
size_t i;
time_t ret = (time_t) -1;
/* Solaris strptime fails to recognize English month names in
non-English locales, which we work around by temporarily setting
locale to C before invoking strptime. */
oldlocale = setlocale (LC_TIME, NULL);
if (oldlocale)
{
size_t l = strlen (oldlocale) + 1;
if (l >= sizeof savedlocale)
savedlocale[0] = '\0';
else
memcpy (savedlocale, oldlocale, l);
}
else savedlocale[0] = '\0';
setlocale (LC_TIME, "C");
for (i = 0; i < countof (time_formats); i++)
{
struct tm t;
/* Some versions of strptime use the existing contents of struct
tm to recalculate the date according to format. Zero it out
to prevent stack garbage from influencing strptime. */
xzero (t);
if (check_end (strptime (time_string, time_formats[i], &t)))
{
ret = timegm (&t);
break;
}
}
/* Restore the previous locale. */
if (savedlocale[0])
setlocale (LC_TIME, savedlocale);
return ret;
}
| null | 0 | http_atotm (const char *time_string)
{
/* NOTE: Solaris strptime man page claims that %n and %t match white
space, but that's not universally available. Instead, we simply
use ` ' to mean "skip all WS", which works under all strptime
implementations I've tested. */
static const char *time_formats[] = {
"%a, %d %b %Y %T", /* rfc1123: Thu, 29 Jan 1998 22:12:57 */
"%A, %d-%b-%y %T", /* rfc850: Thursday, 29-Jan-98 22:12:57 */
"%a %b %d %T %Y", /* asctime: Thu Jan 29 22:12:57 1998 */
"%a, %d-%b-%Y %T" /* cookies: Thu, 29-Jan-1998 22:12:57
(used in Set-Cookie, defined in the
Netscape cookie specification.) */
};
const char *oldlocale;
char savedlocale[256];
size_t i;
time_t ret = (time_t) -1;
/* Solaris strptime fails to recognize English month names in
non-English locales, which we work around by temporarily setting
locale to C before invoking strptime. */
oldlocale = setlocale (LC_TIME, NULL);
if (oldlocale)
{
size_t l = strlen (oldlocale) + 1;
if (l >= sizeof savedlocale)
savedlocale[0] = '\0';
else
memcpy (savedlocale, oldlocale, l);
}
else savedlocale[0] = '\0';
setlocale (LC_TIME, "C");
for (i = 0; i < countof (time_formats); i++)
{
struct tm t;
/* Some versions of strptime use the existing contents of struct
tm to recalculate the date according to format. Zero it out
to prevent stack garbage from influencing strptime. */
xzero (t);
if (check_end (strptime (time_string, time_formats[i], &t)))
{
ret = timegm (&t);
break;
}
}
/* Restore the previous locale. */
if (savedlocale[0])
setlocale (LC_TIME, savedlocale);
return ret;
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,429 | http_cleanup (void)
{
xfree (pconn.host);
if (wget_cookie_jar)
cookie_jar_delete (wget_cookie_jar);
}
| null | 0 | http_cleanup (void)
{
xfree (pconn.host);
if (wget_cookie_jar)
cookie_jar_delete (wget_cookie_jar);
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,430 | known_authentication_scheme_p (const char *hdrbeg, const char *hdrend)
{
return STARTS ("Basic", hdrbeg, hdrend)
#ifdef ENABLE_DIGEST
|| STARTS ("Digest", hdrbeg, hdrend)
#endif
#ifdef ENABLE_NTLM
|| STARTS ("NTLM", hdrbeg, hdrend)
#endif
;
}
| null | 0 | known_authentication_scheme_p (const char *hdrbeg, const char *hdrend)
{
return STARTS ("Basic", hdrbeg, hdrend)
#ifdef ENABLE_DIGEST
|| STARTS ("Digest", hdrbeg, hdrend)
#endif
#ifdef ENABLE_NTLM
|| STARTS ("NTLM", hdrbeg, hdrend)
#endif
;
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,431 | maybe_send_basic_creds (const char *hostname, const char *user,
const char *passwd, struct request *req)
{
bool do_challenge = false;
if (opt.auth_without_challenge)
{
DEBUGP (("Auth-without-challenge set, sending Basic credentials.\n"));
do_challenge = true;
}
else if (basic_authed_hosts
&& hash_table_contains (basic_authed_hosts, hostname))
{
DEBUGP (("Found %s in basic_authed_hosts.\n", quote (hostname)));
do_challenge = true;
}
else
{
DEBUGP (("Host %s has not issued a general basic challenge.\n",
quote (hostname)));
}
if (do_challenge)
{
request_set_header (req, "Authorization",
basic_authentication_encode (user, passwd),
rel_value);
}
return do_challenge;
}
| null | 0 | maybe_send_basic_creds (const char *hostname, const char *user,
const char *passwd, struct request *req)
{
bool do_challenge = false;
if (opt.auth_without_challenge)
{
DEBUGP (("Auth-without-challenge set, sending Basic credentials.\n"));
do_challenge = true;
}
else if (basic_authed_hosts
&& hash_table_contains (basic_authed_hosts, hostname))
{
DEBUGP (("Found %s in basic_authed_hosts.\n", quote (hostname)));
do_challenge = true;
}
else
{
DEBUGP (("Host %s has not issued a general basic challenge.\n",
quote (hostname)));
}
if (do_challenge)
{
request_set_header (req, "Authorization",
basic_authentication_encode (user, passwd),
rel_value);
}
return do_challenge;
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,432 | metalink_from_http (const struct response *resp, const struct http_stat *hs,
const struct url *u)
{
metalink_t *metalink = NULL;
metalink_file_t *mfile = xnew0 (metalink_file_t);
const char *val_beg, *val_end;
int res_count = 0, meta_count = 0, hash_count = 0, sig_count = 0, i;
DEBUGP (("Checking for Metalink in HTTP response\n"));
/* Initialize metalink file for our simple use case. */
if (hs->local_file)
mfile->name = xstrdup (hs->local_file);
else
mfile->name = url_file_name (u, NULL);
/* Begin with 1-element array (for 0-termination). */
mfile->checksums = xnew0 (metalink_checksum_t *);
mfile->resources = xnew0 (metalink_resource_t *);
mfile->metaurls = xnew0 (metalink_metaurl_t *);
/* Process the Content-Type header. */
if (resp_header_locate (resp, "Content-Type", 0, &val_beg, &val_end) != -1)
{
metalink_metaurl_t murl = {0};
const char *type_beg, *type_end;
char *typestr = NULL;
char *namestr = NULL;
size_t type_len;
DEBUGP (("Processing Content-Type header...\n"));
/* Find beginning of type. */
type_beg = val_beg;
while (type_beg < val_end && c_isspace (*type_beg))
type_beg++;
/* Find end of type. */
type_end = type_beg + 1;
while (type_end < val_end &&
*type_end != ';' &&
*type_end != ' ' &&
*type_end != '\r' &&
*type_end != '\n')
type_end++;
if (type_beg >= val_end || type_end > val_end)
{
DEBUGP (("Invalid Content-Type header. Ignoring.\n"));
goto skip_content_type;
}
type_len = type_end - type_beg;
typestr = xstrndup (type_beg, type_len);
DEBUGP (("Content-Type: %s\n", typestr));
if (strcmp (typestr, "application/metalink4+xml"))
{
xfree (typestr);
goto skip_content_type;
}
/*
Valid ranges for the "pri" attribute are from
1 to 999999. Mirror servers with a lower value of the "pri"
attribute have a higher priority, while mirrors with an undefined
"pri" attribute are considered to have a value of 999999, which is
the lowest priority.
rfc6249 section 3.1
*/
murl.priority = DEFAULT_PRI;
murl.mediatype = typestr;
typestr = NULL;
if (opt.content_disposition
&& resp_header_locate (resp, "Content-Disposition", 0, &val_beg, &val_end) != -1)
{
find_key_value (val_beg, val_end, "filename", &namestr);
murl.name = namestr;
namestr = NULL;
}
murl.url = xstrdup (u->url);
DEBUGP (("URL=%s\n", murl.url));
DEBUGP (("MEDIATYPE=%s\n", murl.mediatype));
DEBUGP (("NAME=%s\n", murl.name ? murl.name : ""));
DEBUGP (("PRIORITY=%d\n", murl.priority));
/* 1 slot from new resource, 1 slot for null-termination. */
mfile->metaurls = xrealloc (mfile->metaurls,
sizeof (metalink_metaurl_t *) * (meta_count + 2));
mfile->metaurls[meta_count] = xnew0 (metalink_metaurl_t);
*mfile->metaurls[meta_count] = murl;
meta_count++;
}
skip_content_type:
/* Find all Link headers. */
for (i = 0;
(i = resp_header_locate (resp, "Link", i, &val_beg, &val_end)) != -1;
i++)
{
char *rel = NULL, *reltype = NULL;
char *urlstr = NULL;
const char *url_beg, *url_end, *attrs_beg;
size_t url_len;
/* Sample Metalink Link headers:
Link: <http://www2.example.com/dir1/dir2/dir3/dir4/dir5/example.ext>;
rel=duplicate; pri=1; pref; geo=gb; depth=4
Link: <http://example.com/example.ext.asc>; rel=describedby;
type="application/pgp-signature"
*/
/* Find beginning of URL. */
url_beg = val_beg;
while (url_beg < val_end - 1 && c_isspace (*url_beg))
url_beg++;
/* Find end of URL. */
/* The convention here is that end ptr points to one element after
end of string. In this case, it should be pointing to the '>', which
is one element after end of actual URL. Therefore, it should never point
to val_end, which is one element after entire header value string. */
url_end = url_beg + 1;
while (url_end < val_end - 1 && *url_end != '>')
url_end++;
if (url_beg >= val_end || url_end >= val_end ||
*url_beg != '<' || *url_end != '>')
{
DEBUGP (("This is not a valid Link header. Ignoring.\n"));
continue;
}
/* Skip <. */
url_beg++;
url_len = url_end - url_beg;
/* URL found. Now handle the attributes. */
attrs_beg = url_end + 1;
/* First we need to find out what type of link it is. Currently, we
support rel=duplicate and rel=describedby. */
if (!find_key_value (attrs_beg, val_end, "rel", &rel))
{
DEBUGP (("No rel value in Link header, skipping.\n"));
continue;
}
urlstr = xstrndup (url_beg, url_len);
DEBUGP (("URL=%s\n", urlstr));
DEBUGP (("rel=%s\n", rel));
if (!strcmp (rel, "describedby"))
find_key_value (attrs_beg, val_end, "type", &reltype);
/* Handle signatures.
Libmetalink only supports one signature per file. Therefore we stop
as soon as we successfully get first supported signature. */
if (sig_count == 0 &&
reltype && !strcmp (reltype, "application/pgp-signature"))
{
/* Download the signature to a temporary file. */
FILE *_output_stream = output_stream;
bool _output_stream_regular = output_stream_regular;
output_stream = tmpfile ();
if (output_stream)
{
struct iri *iri = iri_new ();
struct url *url;
int url_err;
set_uri_encoding (iri, opt.locale, true);
url = url_parse (urlstr, &url_err, iri, false);
if (!url)
{
char *error = url_error (urlstr, url_err);
logprintf (LOG_NOTQUIET, _("When downloading signature:\n"
"%s: %s.\n"), urlstr, error);
xfree (error);
iri_free (iri);
}
else
{
/* Avoid recursive Metalink from HTTP headers. */
bool _metalink_http = opt.metalink_over_http;
uerr_t retr_err;
opt.metalink_over_http = false;
retr_err = retrieve_url (url, urlstr, NULL, NULL,
NULL, NULL, false, iri, false);
opt.metalink_over_http = _metalink_http;
url_free (url);
iri_free (iri);
if (retr_err == RETROK)
{
/* Signature is in the temporary file. Read it into
metalink resource structure. */
metalink_signature_t msig;
size_t siglen;
fseek (output_stream, 0, SEEK_END);
siglen = ftell (output_stream);
fseek (output_stream, 0, SEEK_SET);
DEBUGP (("siglen=%lu\n", siglen));
msig.signature = xmalloc (siglen + 1);
if (fread (msig.signature, siglen, 1, output_stream) != 1)
{
logputs (LOG_NOTQUIET,
_("Unable to read signature content from "
"temporary file. Skipping.\n"));
xfree (msig.signature);
}
else
{
msig.signature[siglen] = '\0'; /* Just in case. */
msig.mediatype = xstrdup ("application/pgp-signature");
DEBUGP (("Signature (%s):\n%s\n",
msig.mediatype, msig.signature));
mfile->signature = xnew (metalink_signature_t);
*mfile->signature = msig;
sig_count++;
}
}
}
fclose (output_stream);
}
else
{
logputs (LOG_NOTQUIET, _("Could not create temporary file. "
"Skipping signature download.\n"));
}
output_stream_regular = _output_stream_regular;
output_stream = _output_stream;
} /* Iterate over signatures. */
/* Handle Metalink resources. */
else if (!strcmp (rel, "duplicate"))
{
metalink_resource_t mres = {0};
char *pristr;
/*
Valid ranges for the "pri" attribute are from
1 to 999999. Mirror servers with a lower value of the "pri"
attribute have a higher priority, while mirrors with an undefined
"pri" attribute are considered to have a value of 999999, which is
the lowest priority.
rfc6249 section 3.1
*/
mres.priority = DEFAULT_PRI;
if (find_key_value (url_end, val_end, "pri", &pristr))
{
long pri;
char *end_pristr;
/* Do not care for errno since 0 is error in this case. */
pri = strtol (pristr, &end_pristr, 10);
if (end_pristr != pristr + strlen (pristr) ||
!VALID_PRI_RANGE (pri))
{
/* This is against the specification, so let's inform the user. */
logprintf (LOG_NOTQUIET,
_("Invalid pri value. Assuming %d.\n"),
DEFAULT_PRI);
}
else
mres.priority = pri;
xfree (pristr);
}
switch (url_scheme (urlstr))
{
case SCHEME_HTTP:
mres.type = xstrdup ("http");
break;
#ifdef HAVE_SSL
case SCHEME_HTTPS:
mres.type = xstrdup ("https");
break;
case SCHEME_FTPS:
mres.type = xstrdup ("ftps");
break;
#endif
case SCHEME_FTP:
mres.type = xstrdup ("ftp");
break;
default:
DEBUGP (("Unsupported url scheme in %s. Skipping resource.\n", urlstr));
}
if (mres.type)
{
DEBUGP (("TYPE=%s\n", mres.type));
/* At this point we have validated the new resource. */
find_key_value (url_end, val_end, "geo", &mres.location);
mres.url = urlstr;
urlstr = NULL;
mres.preference = 0;
if (has_key (url_end, val_end, "pref"))
{
DEBUGP (("This resource has preference\n"));
mres.preference = 1;
}
/* 1 slot from new resource, 1 slot for null-termination. */
mfile->resources = xrealloc (mfile->resources,
sizeof (metalink_resource_t *) * (res_count + 2));
mfile->resources[res_count] = xnew0 (metalink_resource_t);
*mfile->resources[res_count] = mres;
res_count++;
}
} /* Handle resource link (rel=duplicate). */
/* Handle Metalink/XML resources. */
else if (reltype && !strcmp (reltype, "application/metalink4+xml"))
{
metalink_metaurl_t murl = {0};
char *pristr;
/*
Valid ranges for the "pri" attribute are from
1 to 999999. Mirror servers with a lower value of the "pri"
attribute have a higher priority, while mirrors with an undefined
"pri" attribute are considered to have a value of 999999, which is
the lowest priority.
rfc6249 section 3.1
*/
murl.priority = DEFAULT_PRI;
if (find_key_value (url_end, val_end, "pri", &pristr))
{
long pri;
char *end_pristr;
/* Do not care for errno since 0 is error in this case. */
pri = strtol (pristr, &end_pristr, 10);
if (end_pristr != pristr + strlen (pristr) ||
!VALID_PRI_RANGE (pri))
{
/* This is against the specification, so let's inform the user. */
logprintf (LOG_NOTQUIET,
_("Invalid pri value. Assuming %d.\n"),
DEFAULT_PRI);
}
else
murl.priority = pri;
xfree (pristr);
}
murl.mediatype = xstrdup (reltype);
DEBUGP (("MEDIATYPE=%s\n", murl.mediatype));
/* At this point we have validated the new resource. */
find_key_value (url_end, val_end, "name", &murl.name);
murl.url = urlstr;
urlstr = NULL;
/* 1 slot from new resource, 1 slot for null-termination. */
mfile->metaurls = xrealloc (mfile->metaurls,
sizeof (metalink_metaurl_t *) * (meta_count + 2));
mfile->metaurls[meta_count] = xnew0 (metalink_metaurl_t);
*mfile->metaurls[meta_count] = murl;
meta_count++;
} /* Handle resource link (rel=describedby). */
else
DEBUGP (("This link header was not used for Metalink\n"));
xfree (urlstr);
xfree (reltype);
xfree (rel);
} /* Iterate over link headers. */
/* Null-terminate resources array. */
mfile->resources[res_count] = 0;
mfile->metaurls[meta_count] = 0;
if (res_count == 0 && meta_count == 0)
{
DEBUGP (("No valid metalink references found.\n"));
goto fail;
}
/* Find all Digest headers. */
for (i = 0;
(i = resp_header_locate (resp, "Digest", i, &val_beg, &val_end)) != -1;
i++)
{
const char *dig_pos;
char *dig_type, *dig_hash;
/* Each Digest header can include multiple hashes. Example:
Digest: SHA=thvDyvhfIqlvFe+A9MYgxAfm1q5=,unixsum=30637
Digest: md5=HUXZLQLMuI/KZ5KDcJPcOA==
*/
for (dig_pos = val_beg;
(dig_pos = find_key_values (dig_pos, val_end, &dig_type, &dig_hash));
dig_pos++)
{
/* The hash here is assumed to be base64. We need the hash in hex.
Therefore we convert: base64 -> binary -> hex. */
const size_t dig_hash_str_len = strlen (dig_hash);
char *bin_hash = alloca (dig_hash_str_len * 3 / 4 + 1);
ssize_t hash_bin_len;
hash_bin_len = wget_base64_decode (dig_hash, bin_hash, dig_hash_str_len * 3 / 4 + 1);
/* Detect malformed base64 input. */
if (hash_bin_len < 0)
{
xfree (dig_type);
xfree (dig_hash);
continue;
}
/* One slot for me, one for zero-termination. */
mfile->checksums =
xrealloc (mfile->checksums,
sizeof (metalink_checksum_t *) * (hash_count + 2));
mfile->checksums[hash_count] = xnew (metalink_checksum_t);
mfile->checksums[hash_count]->type = dig_type;
mfile->checksums[hash_count]->hash = xmalloc ((size_t)hash_bin_len * 2 + 1);
wg_hex_to_string (mfile->checksums[hash_count]->hash, bin_hash, (size_t)hash_bin_len);
xfree (dig_hash);
hash_count++;
}
}
/* Zero-terminate checksums array. */
mfile->checksums[hash_count] = 0;
/*
If Instance Digests are not provided by the Metalink servers, the
Link header fields pertaining to this specification MUST be ignored.
rfc6249 section 6
*/
if (res_count && hash_count == 0)
{
logputs (LOG_VERBOSE,
_("Could not find acceptable digest for Metalink resources.\n"
"Ignoring them.\n"));
goto fail;
}
/* Metalink data is OK. Now we just need to sort the resources based
on their priorities, preference, and perhaps location. */
stable_sort (mfile->resources, res_count, sizeof (metalink_resource_t *), metalink_res_cmp);
stable_sort (mfile->metaurls, meta_count, sizeof (metalink_metaurl_t *), metalink_meta_cmp);
/* Restore sensible preference values (in case someone cares to look). */
for (i = 0; i < res_count; ++i)
mfile->resources[i]->preference = 1000000 - mfile->resources[i]->priority;
metalink = xnew0 (metalink_t);
metalink->files = xmalloc (sizeof (metalink_file_t *) * 2);
metalink->files[0] = mfile;
metalink->files[1] = 0;
metalink->origin = xstrdup (u->url);
metalink->version = METALINK_VERSION_4;
/* Leave other fields set to 0. */
return metalink;
fail:
/* Free all allocated memory. */
if (metalink)
metalink_delete (metalink);
else
metalink_file_delete (mfile);
return NULL;
}
| null | 0 | metalink_from_http (const struct response *resp, const struct http_stat *hs,
const struct url *u)
{
metalink_t *metalink = NULL;
metalink_file_t *mfile = xnew0 (metalink_file_t);
const char *val_beg, *val_end;
int res_count = 0, meta_count = 0, hash_count = 0, sig_count = 0, i;
DEBUGP (("Checking for Metalink in HTTP response\n"));
/* Initialize metalink file for our simple use case. */
if (hs->local_file)
mfile->name = xstrdup (hs->local_file);
else
mfile->name = url_file_name (u, NULL);
/* Begin with 1-element array (for 0-termination). */
mfile->checksums = xnew0 (metalink_checksum_t *);
mfile->resources = xnew0 (metalink_resource_t *);
mfile->metaurls = xnew0 (metalink_metaurl_t *);
/* Process the Content-Type header. */
if (resp_header_locate (resp, "Content-Type", 0, &val_beg, &val_end) != -1)
{
metalink_metaurl_t murl = {0};
const char *type_beg, *type_end;
char *typestr = NULL;
char *namestr = NULL;
size_t type_len;
DEBUGP (("Processing Content-Type header...\n"));
/* Find beginning of type. */
type_beg = val_beg;
while (type_beg < val_end && c_isspace (*type_beg))
type_beg++;
/* Find end of type. */
type_end = type_beg + 1;
while (type_end < val_end &&
*type_end != ';' &&
*type_end != ' ' &&
*type_end != '\r' &&
*type_end != '\n')
type_end++;
if (type_beg >= val_end || type_end > val_end)
{
DEBUGP (("Invalid Content-Type header. Ignoring.\n"));
goto skip_content_type;
}
type_len = type_end - type_beg;
typestr = xstrndup (type_beg, type_len);
DEBUGP (("Content-Type: %s\n", typestr));
if (strcmp (typestr, "application/metalink4+xml"))
{
xfree (typestr);
goto skip_content_type;
}
/*
Valid ranges for the "pri" attribute are from
1 to 999999. Mirror servers with a lower value of the "pri"
attribute have a higher priority, while mirrors with an undefined
"pri" attribute are considered to have a value of 999999, which is
the lowest priority.
rfc6249 section 3.1
*/
murl.priority = DEFAULT_PRI;
murl.mediatype = typestr;
typestr = NULL;
if (opt.content_disposition
&& resp_header_locate (resp, "Content-Disposition", 0, &val_beg, &val_end) != -1)
{
find_key_value (val_beg, val_end, "filename", &namestr);
murl.name = namestr;
namestr = NULL;
}
murl.url = xstrdup (u->url);
DEBUGP (("URL=%s\n", murl.url));
DEBUGP (("MEDIATYPE=%s\n", murl.mediatype));
DEBUGP (("NAME=%s\n", murl.name ? murl.name : ""));
DEBUGP (("PRIORITY=%d\n", murl.priority));
/* 1 slot from new resource, 1 slot for null-termination. */
mfile->metaurls = xrealloc (mfile->metaurls,
sizeof (metalink_metaurl_t *) * (meta_count + 2));
mfile->metaurls[meta_count] = xnew0 (metalink_metaurl_t);
*mfile->metaurls[meta_count] = murl;
meta_count++;
}
skip_content_type:
/* Find all Link headers. */
for (i = 0;
(i = resp_header_locate (resp, "Link", i, &val_beg, &val_end)) != -1;
i++)
{
char *rel = NULL, *reltype = NULL;
char *urlstr = NULL;
const char *url_beg, *url_end, *attrs_beg;
size_t url_len;
/* Sample Metalink Link headers:
Link: <http://www2.example.com/dir1/dir2/dir3/dir4/dir5/example.ext>;
rel=duplicate; pri=1; pref; geo=gb; depth=4
Link: <http://example.com/example.ext.asc>; rel=describedby;
type="application/pgp-signature"
*/
/* Find beginning of URL. */
url_beg = val_beg;
while (url_beg < val_end - 1 && c_isspace (*url_beg))
url_beg++;
/* Find end of URL. */
/* The convention here is that end ptr points to one element after
end of string. In this case, it should be pointing to the '>', which
is one element after end of actual URL. Therefore, it should never point
to val_end, which is one element after entire header value string. */
url_end = url_beg + 1;
while (url_end < val_end - 1 && *url_end != '>')
url_end++;
if (url_beg >= val_end || url_end >= val_end ||
*url_beg != '<' || *url_end != '>')
{
DEBUGP (("This is not a valid Link header. Ignoring.\n"));
continue;
}
/* Skip <. */
url_beg++;
url_len = url_end - url_beg;
/* URL found. Now handle the attributes. */
attrs_beg = url_end + 1;
/* First we need to find out what type of link it is. Currently, we
support rel=duplicate and rel=describedby. */
if (!find_key_value (attrs_beg, val_end, "rel", &rel))
{
DEBUGP (("No rel value in Link header, skipping.\n"));
continue;
}
urlstr = xstrndup (url_beg, url_len);
DEBUGP (("URL=%s\n", urlstr));
DEBUGP (("rel=%s\n", rel));
if (!strcmp (rel, "describedby"))
find_key_value (attrs_beg, val_end, "type", &reltype);
/* Handle signatures.
Libmetalink only supports one signature per file. Therefore we stop
as soon as we successfully get first supported signature. */
if (sig_count == 0 &&
reltype && !strcmp (reltype, "application/pgp-signature"))
{
/* Download the signature to a temporary file. */
FILE *_output_stream = output_stream;
bool _output_stream_regular = output_stream_regular;
output_stream = tmpfile ();
if (output_stream)
{
struct iri *iri = iri_new ();
struct url *url;
int url_err;
set_uri_encoding (iri, opt.locale, true);
url = url_parse (urlstr, &url_err, iri, false);
if (!url)
{
char *error = url_error (urlstr, url_err);
logprintf (LOG_NOTQUIET, _("When downloading signature:\n"
"%s: %s.\n"), urlstr, error);
xfree (error);
iri_free (iri);
}
else
{
/* Avoid recursive Metalink from HTTP headers. */
bool _metalink_http = opt.metalink_over_http;
uerr_t retr_err;
opt.metalink_over_http = false;
retr_err = retrieve_url (url, urlstr, NULL, NULL,
NULL, NULL, false, iri, false);
opt.metalink_over_http = _metalink_http;
url_free (url);
iri_free (iri);
if (retr_err == RETROK)
{
/* Signature is in the temporary file. Read it into
metalink resource structure. */
metalink_signature_t msig;
size_t siglen;
fseek (output_stream, 0, SEEK_END);
siglen = ftell (output_stream);
fseek (output_stream, 0, SEEK_SET);
DEBUGP (("siglen=%lu\n", siglen));
msig.signature = xmalloc (siglen + 1);
if (fread (msig.signature, siglen, 1, output_stream) != 1)
{
logputs (LOG_NOTQUIET,
_("Unable to read signature content from "
"temporary file. Skipping.\n"));
xfree (msig.signature);
}
else
{
msig.signature[siglen] = '\0'; /* Just in case. */
msig.mediatype = xstrdup ("application/pgp-signature");
DEBUGP (("Signature (%s):\n%s\n",
msig.mediatype, msig.signature));
mfile->signature = xnew (metalink_signature_t);
*mfile->signature = msig;
sig_count++;
}
}
}
fclose (output_stream);
}
else
{
logputs (LOG_NOTQUIET, _("Could not create temporary file. "
"Skipping signature download.\n"));
}
output_stream_regular = _output_stream_regular;
output_stream = _output_stream;
} /* Iterate over signatures. */
/* Handle Metalink resources. */
else if (!strcmp (rel, "duplicate"))
{
metalink_resource_t mres = {0};
char *pristr;
/*
Valid ranges for the "pri" attribute are from
1 to 999999. Mirror servers with a lower value of the "pri"
attribute have a higher priority, while mirrors with an undefined
"pri" attribute are considered to have a value of 999999, which is
the lowest priority.
rfc6249 section 3.1
*/
mres.priority = DEFAULT_PRI;
if (find_key_value (url_end, val_end, "pri", &pristr))
{
long pri;
char *end_pristr;
/* Do not care for errno since 0 is error in this case. */
pri = strtol (pristr, &end_pristr, 10);
if (end_pristr != pristr + strlen (pristr) ||
!VALID_PRI_RANGE (pri))
{
/* This is against the specification, so let's inform the user. */
logprintf (LOG_NOTQUIET,
_("Invalid pri value. Assuming %d.\n"),
DEFAULT_PRI);
}
else
mres.priority = pri;
xfree (pristr);
}
switch (url_scheme (urlstr))
{
case SCHEME_HTTP:
mres.type = xstrdup ("http");
break;
#ifdef HAVE_SSL
case SCHEME_HTTPS:
mres.type = xstrdup ("https");
break;
case SCHEME_FTPS:
mres.type = xstrdup ("ftps");
break;
#endif
case SCHEME_FTP:
mres.type = xstrdup ("ftp");
break;
default:
DEBUGP (("Unsupported url scheme in %s. Skipping resource.\n", urlstr));
}
if (mres.type)
{
DEBUGP (("TYPE=%s\n", mres.type));
/* At this point we have validated the new resource. */
find_key_value (url_end, val_end, "geo", &mres.location);
mres.url = urlstr;
urlstr = NULL;
mres.preference = 0;
if (has_key (url_end, val_end, "pref"))
{
DEBUGP (("This resource has preference\n"));
mres.preference = 1;
}
/* 1 slot from new resource, 1 slot for null-termination. */
mfile->resources = xrealloc (mfile->resources,
sizeof (metalink_resource_t *) * (res_count + 2));
mfile->resources[res_count] = xnew0 (metalink_resource_t);
*mfile->resources[res_count] = mres;
res_count++;
}
} /* Handle resource link (rel=duplicate). */
/* Handle Metalink/XML resources. */
else if (reltype && !strcmp (reltype, "application/metalink4+xml"))
{
metalink_metaurl_t murl = {0};
char *pristr;
/*
Valid ranges for the "pri" attribute are from
1 to 999999. Mirror servers with a lower value of the "pri"
attribute have a higher priority, while mirrors with an undefined
"pri" attribute are considered to have a value of 999999, which is
the lowest priority.
rfc6249 section 3.1
*/
murl.priority = DEFAULT_PRI;
if (find_key_value (url_end, val_end, "pri", &pristr))
{
long pri;
char *end_pristr;
/* Do not care for errno since 0 is error in this case. */
pri = strtol (pristr, &end_pristr, 10);
if (end_pristr != pristr + strlen (pristr) ||
!VALID_PRI_RANGE (pri))
{
/* This is against the specification, so let's inform the user. */
logprintf (LOG_NOTQUIET,
_("Invalid pri value. Assuming %d.\n"),
DEFAULT_PRI);
}
else
murl.priority = pri;
xfree (pristr);
}
murl.mediatype = xstrdup (reltype);
DEBUGP (("MEDIATYPE=%s\n", murl.mediatype));
/* At this point we have validated the new resource. */
find_key_value (url_end, val_end, "name", &murl.name);
murl.url = urlstr;
urlstr = NULL;
/* 1 slot from new resource, 1 slot for null-termination. */
mfile->metaurls = xrealloc (mfile->metaurls,
sizeof (metalink_metaurl_t *) * (meta_count + 2));
mfile->metaurls[meta_count] = xnew0 (metalink_metaurl_t);
*mfile->metaurls[meta_count] = murl;
meta_count++;
} /* Handle resource link (rel=describedby). */
else
DEBUGP (("This link header was not used for Metalink\n"));
xfree (urlstr);
xfree (reltype);
xfree (rel);
} /* Iterate over link headers. */
/* Null-terminate resources array. */
mfile->resources[res_count] = 0;
mfile->metaurls[meta_count] = 0;
if (res_count == 0 && meta_count == 0)
{
DEBUGP (("No valid metalink references found.\n"));
goto fail;
}
/* Find all Digest headers. */
for (i = 0;
(i = resp_header_locate (resp, "Digest", i, &val_beg, &val_end)) != -1;
i++)
{
const char *dig_pos;
char *dig_type, *dig_hash;
/* Each Digest header can include multiple hashes. Example:
Digest: SHA=thvDyvhfIqlvFe+A9MYgxAfm1q5=,unixsum=30637
Digest: md5=HUXZLQLMuI/KZ5KDcJPcOA==
*/
for (dig_pos = val_beg;
(dig_pos = find_key_values (dig_pos, val_end, &dig_type, &dig_hash));
dig_pos++)
{
/* The hash here is assumed to be base64. We need the hash in hex.
Therefore we convert: base64 -> binary -> hex. */
const size_t dig_hash_str_len = strlen (dig_hash);
char *bin_hash = alloca (dig_hash_str_len * 3 / 4 + 1);
ssize_t hash_bin_len;
hash_bin_len = wget_base64_decode (dig_hash, bin_hash, dig_hash_str_len * 3 / 4 + 1);
/* Detect malformed base64 input. */
if (hash_bin_len < 0)
{
xfree (dig_type);
xfree (dig_hash);
continue;
}
/* One slot for me, one for zero-termination. */
mfile->checksums =
xrealloc (mfile->checksums,
sizeof (metalink_checksum_t *) * (hash_count + 2));
mfile->checksums[hash_count] = xnew (metalink_checksum_t);
mfile->checksums[hash_count]->type = dig_type;
mfile->checksums[hash_count]->hash = xmalloc ((size_t)hash_bin_len * 2 + 1);
wg_hex_to_string (mfile->checksums[hash_count]->hash, bin_hash, (size_t)hash_bin_len);
xfree (dig_hash);
hash_count++;
}
}
/* Zero-terminate checksums array. */
mfile->checksums[hash_count] = 0;
/*
If Instance Digests are not provided by the Metalink servers, the
Link header fields pertaining to this specification MUST be ignored.
rfc6249 section 6
*/
if (res_count && hash_count == 0)
{
logputs (LOG_VERBOSE,
_("Could not find acceptable digest for Metalink resources.\n"
"Ignoring them.\n"));
goto fail;
}
/* Metalink data is OK. Now we just need to sort the resources based
on their priorities, preference, and perhaps location. */
stable_sort (mfile->resources, res_count, sizeof (metalink_resource_t *), metalink_res_cmp);
stable_sort (mfile->metaurls, meta_count, sizeof (metalink_metaurl_t *), metalink_meta_cmp);
/* Restore sensible preference values (in case someone cares to look). */
for (i = 0; i < res_count; ++i)
mfile->resources[i]->preference = 1000000 - mfile->resources[i]->priority;
metalink = xnew0 (metalink_t);
metalink->files = xmalloc (sizeof (metalink_file_t *) * 2);
metalink->files[0] = mfile;
metalink->files[1] = 0;
metalink->origin = xstrdup (u->url);
metalink->version = METALINK_VERSION_4;
/* Leave other fields set to 0. */
return metalink;
fail:
/* Free all allocated memory. */
if (metalink)
metalink_delete (metalink);
else
metalink_file_delete (mfile);
return NULL;
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,433 | register_basic_auth_host (const char *hostname)
{
if (!basic_authed_hosts)
{
basic_authed_hosts = make_nocase_string_hash_table (1);
}
if (!hash_table_contains (basic_authed_hosts, hostname))
{
hash_table_put (basic_authed_hosts, xstrdup (hostname), NULL);
DEBUGP (("Inserted %s into basic_authed_hosts\n", quote (hostname)));
}
}
| null | 0 | register_basic_auth_host (const char *hostname)
{
if (!basic_authed_hosts)
{
basic_authed_hosts = make_nocase_string_hash_table (1);
}
if (!hash_table_contains (basic_authed_hosts, hostname))
{
hash_table_put (basic_authed_hosts, xstrdup (hostname), NULL);
DEBUGP (("Inserted %s into basic_authed_hosts\n", quote (hostname)));
}
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,434 | release_header (struct request_header *hdr)
{
switch (hdr->release_policy)
{
case rel_none:
break;
case rel_name:
xfree (hdr->name);
break;
case rel_value:
xfree (hdr->value);
break;
case rel_both:
xfree (hdr->name);
xfree (hdr->value);
break;
}
}
| null | 0 | release_header (struct request_header *hdr)
{
switch (hdr->release_policy)
{
case rel_none:
break;
case rel_name:
xfree (hdr->name);
break;
case rel_value:
xfree (hdr->value);
break;
case rel_both:
xfree (hdr->name);
xfree (hdr->value);
break;
}
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,435 | request_method (const struct request *req)
{
return req->method;
}
| null | 0 | request_method (const struct request *req)
{
return req->method;
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,436 | request_new (const char *method, char *arg)
{
struct request *req = xnew0 (struct request);
req->hcapacity = 8;
req->headers = xnew_array (struct request_header, req->hcapacity);
req->method = method;
req->arg = arg;
return req;
}
| null | 0 | request_new (const char *method, char *arg)
{
struct request *req = xnew0 (struct request);
req->hcapacity = 8;
req->headers = xnew_array (struct request_header, req->hcapacity);
req->method = method;
req->arg = arg;
return req;
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,437 | request_remove_header (struct request *req, const char *name)
{
int i;
for (i = 0; i < req->hcount; i++)
{
struct request_header *hdr = &req->headers[i];
if (0 == c_strcasecmp (name, hdr->name))
{
release_header (hdr);
/* Move the remaining headers by one. */
if (i < req->hcount - 1)
memmove (hdr, hdr + 1, (req->hcount - i - 1) * sizeof (*hdr));
--req->hcount;
return true;
}
}
return false;
}
| null | 0 | request_remove_header (struct request *req, const char *name)
{
int i;
for (i = 0; i < req->hcount; i++)
{
struct request_header *hdr = &req->headers[i];
if (0 == c_strcasecmp (name, hdr->name))
{
release_header (hdr);
/* Move the remaining headers by one. */
if (i < req->hcount - 1)
memmove (hdr, hdr + 1, (req->hcount - i - 1) * sizeof (*hdr));
--req->hcount;
return true;
}
}
return false;
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,438 | request_send (const struct request *req, int fd, FILE *warc_tmp)
{
char *request_string, *p;
int i, size, write_error;
/* Count the request size. */
size = 0;
/* METHOD " " ARG " " "HTTP/1.0" "\r\n" */
size += strlen (req->method) + 1 + strlen (req->arg) + 1 + 8 + 2;
for (i = 0; i < req->hcount; i++)
{
struct request_header *hdr = &req->headers[i];
/* NAME ": " VALUE "\r\n" */
size += strlen (hdr->name) + 2 + strlen (hdr->value) + 2;
}
/* "\r\n\0" */
size += 3;
p = request_string = xmalloc (size);
/* Generate the request. */
APPEND (p, req->method); *p++ = ' ';
APPEND (p, req->arg); *p++ = ' ';
memcpy (p, "HTTP/1.1\r\n", 10); p += 10;
for (i = 0; i < req->hcount; i++)
{
struct request_header *hdr = &req->headers[i];
APPEND (p, hdr->name);
*p++ = ':', *p++ = ' ';
APPEND (p, hdr->value);
*p++ = '\r', *p++ = '\n';
}
*p++ = '\r', *p++ = '\n', *p++ = '\0';
assert (p - request_string == size);
#undef APPEND
DEBUGP (("\n---request begin---\n%s---request end---\n", request_string));
/* Send the request to the server. */
write_error = fd_write (fd, request_string, size - 1, -1);
if (write_error < 0)
logprintf (LOG_VERBOSE, _("Failed writing HTTP request: %s.\n"),
fd_errstr (fd));
else if (warc_tmp != NULL)
{
/* Write a copy of the data to the WARC record. */
int warc_tmp_written = fwrite (request_string, 1, size - 1, warc_tmp);
if (warc_tmp_written != size - 1)
write_error = -2;
}
xfree (request_string);
return write_error;
}
| null | 0 | request_send (const struct request *req, int fd, FILE *warc_tmp)
{
char *request_string, *p;
int i, size, write_error;
/* Count the request size. */
size = 0;
/* METHOD " " ARG " " "HTTP/1.0" "\r\n" */
size += strlen (req->method) + 1 + strlen (req->arg) + 1 + 8 + 2;
for (i = 0; i < req->hcount; i++)
{
struct request_header *hdr = &req->headers[i];
/* NAME ": " VALUE "\r\n" */
size += strlen (hdr->name) + 2 + strlen (hdr->value) + 2;
}
/* "\r\n\0" */
size += 3;
p = request_string = xmalloc (size);
/* Generate the request. */
APPEND (p, req->method); *p++ = ' ';
APPEND (p, req->arg); *p++ = ' ';
memcpy (p, "HTTP/1.1\r\n", 10); p += 10;
for (i = 0; i < req->hcount; i++)
{
struct request_header *hdr = &req->headers[i];
APPEND (p, hdr->name);
*p++ = ':', *p++ = ' ';
APPEND (p, hdr->value);
*p++ = '\r', *p++ = '\n';
}
*p++ = '\r', *p++ = '\n', *p++ = '\0';
assert (p - request_string == size);
#undef APPEND
DEBUGP (("\n---request begin---\n%s---request end---\n", request_string));
/* Send the request to the server. */
write_error = fd_write (fd, request_string, size - 1, -1);
if (write_error < 0)
logprintf (LOG_VERBOSE, _("Failed writing HTTP request: %s.\n"),
fd_errstr (fd));
else if (warc_tmp != NULL)
{
/* Write a copy of the data to the WARC record. */
int warc_tmp_written = fwrite (request_string, 1, size - 1, warc_tmp);
if (warc_tmp_written != size - 1)
write_error = -2;
}
xfree (request_string);
return write_error;
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,439 | request_set_header (struct request *req, const char *name, const char *value,
enum rp release_policy)
{
struct request_header *hdr;
int i;
if (!value)
{
/* A NULL value is a no-op; if freeing the name is requested,
free it now to avoid leaks. */
if (release_policy == rel_name || release_policy == rel_both)
xfree (name);
return;
}
for (i = 0; i < req->hcount; i++)
{
hdr = &req->headers[i];
if (0 == c_strcasecmp (name, hdr->name))
{
/* Replace existing header. */
release_header (hdr);
hdr->name = (void *)name;
hdr->value = (void *)value;
hdr->release_policy = release_policy;
return;
}
}
/* Install new header. */
if (req->hcount >= req->hcapacity)
{
req->hcapacity <<= 1;
req->headers = xrealloc (req->headers, req->hcapacity * sizeof (*hdr));
}
hdr = &req->headers[req->hcount++];
hdr->name = (void *)name;
hdr->value = (void *)value;
hdr->release_policy = release_policy;
}
| null | 0 | request_set_header (struct request *req, const char *name, const char *value,
enum rp release_policy)
{
struct request_header *hdr;
int i;
if (!value)
{
/* A NULL value is a no-op; if freeing the name is requested,
free it now to avoid leaks. */
if (release_policy == rel_name || release_policy == rel_both)
xfree (name);
return;
}
for (i = 0; i < req->hcount; i++)
{
hdr = &req->headers[i];
if (0 == c_strcasecmp (name, hdr->name))
{
/* Replace existing header. */
release_header (hdr);
hdr->name = (void *)name;
hdr->value = (void *)value;
hdr->release_policy = release_policy;
return;
}
}
/* Install new header. */
if (req->hcount >= req->hcapacity)
{
req->hcapacity <<= 1;
req->headers = xrealloc (req->headers, req->hcapacity * sizeof (*hdr));
}
hdr = &req->headers[req->hcount++];
hdr->name = (void *)name;
hdr->value = (void *)value;
hdr->release_policy = release_policy;
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,440 | request_set_user_header (struct request *req, const char *header)
{
char *name;
const char *p = strchr (header, ':');
if (!p)
return;
BOUNDED_TO_ALLOCA (header, p, name);
++p;
while (c_isspace (*p))
++p;
request_set_header (req, xstrdup (name), (char *) p, rel_name);
}
| null | 0 | request_set_user_header (struct request *req, const char *header)
{
char *name;
const char *p = strchr (header, ':');
if (!p)
return;
BOUNDED_TO_ALLOCA (header, p, name);
++p;
while (c_isspace (*p))
++p;
request_set_header (req, xstrdup (name), (char *) p, rel_name);
}
| @@ -613,9 +613,9 @@ struct response {
resp_header_*. */
static struct response *
-resp_new (const char *head)
+resp_new (char *head)
{
- const char *hdr;
+ char *hdr;
int count, size;
struct response *resp = xnew0 (struct response);
@@ -644,15 +644,23 @@ resp_new (const char *head)
break;
/* Find the end of HDR, including continuations. */
- do
+ for (;;)
{
- const char *end = strchr (hdr, '\n');
+ char *end = strchr (hdr, '\n');
+
if (end)
hdr = end + 1;
else
hdr += strlen (hdr);
+
+ if (*hdr != ' ' && *hdr != '\t')
+ break;
+
+ // continuation, transform \r and \n into spaces
+ *end = ' ';
+ if (end > head && end[-1] == '\r')
+ end[-1] = ' ';
}
- while (*hdr == ' ' || *hdr == '\t');
}
DO_REALLOC (resp->headers, size, count + 1, const char *);
resp->headers[count] = NULL; | CWE-20 | null | null |
12,441 | static NOINLINE void attach_option(
struct option_set **opt_list,
const struct dhcp_optflag *optflag,
char *buffer,
int length)
{
struct option_set *existing;
char *allocated;
allocated = allocate_tempopt_if_needed(optflag, buffer, &length);
#if ENABLE_FEATURE_UDHCP_RFC3397
if ((optflag->flags & OPTION_TYPE_MASK) == OPTION_DNS_STRING) {
/* reuse buffer and length for RFC1035-formatted string */
allocated = buffer = (char *)dname_enc(NULL, 0, buffer, &length);
}
#endif
existing = udhcp_find_option(*opt_list, optflag->code);
if (!existing) {
struct option_set *new, **curr;
/* make a new option */
log2("Attaching option %02x to list", optflag->code);
new = xmalloc(sizeof(*new));
new->data = xmalloc(length + OPT_DATA);
new->data[OPT_CODE] = optflag->code;
new->data[OPT_LEN] = length;
memcpy(new->data + OPT_DATA, (allocated ? allocated : buffer), length);
curr = opt_list;
while (*curr && (*curr)->data[OPT_CODE] < optflag->code)
curr = &(*curr)->next;
new->next = *curr;
*curr = new;
goto ret;
}
if (optflag->flags & OPTION_LIST) {
unsigned old_len;
/* add it to an existing option */
log2("Attaching option %02x to existing member of list", optflag->code);
old_len = existing->data[OPT_LEN];
if (old_len + length < 255) {
/* actually 255 is ok too, but adding a space can overlow it */
existing->data = xrealloc(existing->data, OPT_DATA + 1 + old_len + length);
if ((optflag->flags & OPTION_TYPE_MASK) == OPTION_STRING
|| (optflag->flags & OPTION_TYPE_MASK) == OPTION_STRING_HOST
) {
/* add space separator between STRING options in a list */
existing->data[OPT_DATA + old_len] = ' ';
old_len++;
}
memcpy(existing->data + OPT_DATA + old_len, (allocated ? allocated : buffer), length);
existing->data[OPT_LEN] = old_len + length;
} /* else, ignore the data, we could put this in a second option in the future */
} /* else, ignore the new data */
ret:
free(allocated);
}
| Overflow | 0 | static NOINLINE void attach_option(
struct option_set **opt_list,
const struct dhcp_optflag *optflag,
char *buffer,
int length)
{
struct option_set *existing;
char *allocated;
allocated = allocate_tempopt_if_needed(optflag, buffer, &length);
#if ENABLE_FEATURE_UDHCP_RFC3397
if ((optflag->flags & OPTION_TYPE_MASK) == OPTION_DNS_STRING) {
/* reuse buffer and length for RFC1035-formatted string */
allocated = buffer = (char *)dname_enc(NULL, 0, buffer, &length);
}
#endif
existing = udhcp_find_option(*opt_list, optflag->code);
if (!existing) {
struct option_set *new, **curr;
/* make a new option */
log2("Attaching option %02x to list", optflag->code);
new = xmalloc(sizeof(*new));
new->data = xmalloc(length + OPT_DATA);
new->data[OPT_CODE] = optflag->code;
new->data[OPT_LEN] = length;
memcpy(new->data + OPT_DATA, (allocated ? allocated : buffer), length);
curr = opt_list;
while (*curr && (*curr)->data[OPT_CODE] < optflag->code)
curr = &(*curr)->next;
new->next = *curr;
*curr = new;
goto ret;
}
if (optflag->flags & OPTION_LIST) {
unsigned old_len;
/* add it to an existing option */
log2("Attaching option %02x to existing member of list", optflag->code);
old_len = existing->data[OPT_LEN];
if (old_len + length < 255) {
/* actually 255 is ok too, but adding a space can overlow it */
existing->data = xrealloc(existing->data, OPT_DATA + 1 + old_len + length);
if ((optflag->flags & OPTION_TYPE_MASK) == OPTION_STRING
|| (optflag->flags & OPTION_TYPE_MASK) == OPTION_STRING_HOST
) {
/* add space separator between STRING options in a list */
existing->data[OPT_DATA + old_len] = ' ';
old_len++;
}
memcpy(existing->data + OPT_DATA + old_len, (allocated ? allocated : buffer), length);
existing->data[OPT_LEN] = old_len + length;
} /* else, ignore the data, we could put this in a second option in the future */
} /* else, ignore the new data */
ret:
free(allocated);
}
| @@ -142,7 +142,7 @@ const char dhcp_option_strings[] ALIGN1 =
* udhcp_str2optset: to determine how many bytes to allocate.
* xmalloc_optname_optval: to estimate string length
* from binary option length: (option[LEN] / dhcp_option_lengths[opt_type])
- * is the number of elements, multiply in by one element's string width
+ * is the number of elements, multiply it by one element's string width
* (len_of_option_as_string[opt_type]) and you know how wide string you need.
*/
const uint8_t dhcp_option_lengths[] ALIGN1 = {
@@ -162,7 +162,18 @@ const uint8_t dhcp_option_lengths[] ALIGN1 = {
[OPTION_S32] = 4,
/* Just like OPTION_STRING, we use minimum length here */
[OPTION_STATIC_ROUTES] = 5,
- [OPTION_6RD] = 22, /* ignored by udhcp_str2optset */
+ [OPTION_6RD] = 12, /* ignored by udhcp_str2optset */
+ /* The above value was chosen as follows:
+ * len_of_option_as_string[] for this option is >60: it's a string of the form
+ * "32 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 ".
+ * Each additional ipv4 address takes 4 bytes in binary option and appends
+ * another "255.255.255.255 " 16-byte string. We can set [OPTION_6RD] = 4
+ * but this severely overestimates string length: instead of 16 bytes,
+ * it adds >60 for every 4 bytes in binary option.
+ * We cheat and declare here that option is in units of 12 bytes.
+ * This adds more than 60 bytes for every three ipv4 addresses - more than enough.
+ * (Even 16 instead of 12 should work, but let's be paranoid).
+ */
}; | CWE-119 | null | null |
12,442 | void FAST_FUNC udhcp_add_binary_option(struct dhcp_packet *packet, uint8_t *addopt)
{
unsigned len;
uint8_t *optionptr = packet->options;
unsigned end = udhcp_end_option(optionptr);
len = OPT_DATA + addopt[OPT_LEN];
/* end position + (option code/length + addopt length) + end option */
if (end + len + 1 >= DHCP_OPTIONS_BUFSIZE) {
bb_error_msg("option 0x%02x did not fit into the packet",
addopt[OPT_CODE]);
return;
}
log_option("Adding option", addopt);
memcpy(optionptr + end, addopt, len);
optionptr[end + len] = DHCP_END;
}
| Overflow | 0 | void FAST_FUNC udhcp_add_binary_option(struct dhcp_packet *packet, uint8_t *addopt)
{
unsigned len;
uint8_t *optionptr = packet->options;
unsigned end = udhcp_end_option(optionptr);
len = OPT_DATA + addopt[OPT_LEN];
/* end position + (option code/length + addopt length) + end option */
if (end + len + 1 >= DHCP_OPTIONS_BUFSIZE) {
bb_error_msg("option 0x%02x did not fit into the packet",
addopt[OPT_CODE]);
return;
}
log_option("Adding option", addopt);
memcpy(optionptr + end, addopt, len);
optionptr[end + len] = DHCP_END;
}
| @@ -142,7 +142,7 @@ const char dhcp_option_strings[] ALIGN1 =
* udhcp_str2optset: to determine how many bytes to allocate.
* xmalloc_optname_optval: to estimate string length
* from binary option length: (option[LEN] / dhcp_option_lengths[opt_type])
- * is the number of elements, multiply in by one element's string width
+ * is the number of elements, multiply it by one element's string width
* (len_of_option_as_string[opt_type]) and you know how wide string you need.
*/
const uint8_t dhcp_option_lengths[] ALIGN1 = {
@@ -162,7 +162,18 @@ const uint8_t dhcp_option_lengths[] ALIGN1 = {
[OPTION_S32] = 4,
/* Just like OPTION_STRING, we use minimum length here */
[OPTION_STATIC_ROUTES] = 5,
- [OPTION_6RD] = 22, /* ignored by udhcp_str2optset */
+ [OPTION_6RD] = 12, /* ignored by udhcp_str2optset */
+ /* The above value was chosen as follows:
+ * len_of_option_as_string[] for this option is >60: it's a string of the form
+ * "32 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 ".
+ * Each additional ipv4 address takes 4 bytes in binary option and appends
+ * another "255.255.255.255 " 16-byte string. We can set [OPTION_6RD] = 4
+ * but this severely overestimates string length: instead of 16 bytes,
+ * it adds >60 for every 4 bytes in binary option.
+ * We cheat and declare here that option is in units of 12 bytes.
+ * This adds more than 60 bytes for every three ipv4 addresses - more than enough.
+ * (Even 16 instead of 12 should work, but let's be paranoid).
+ */
}; | CWE-119 | null | null |
12,443 | uint8_t* FAST_FUNC udhcp_get_option(struct dhcp_packet *packet, int code)
{
uint8_t *optionptr;
int len;
int rem;
int overload = 0;
enum {
FILE_FIELD101 = FILE_FIELD * 0x101,
SNAME_FIELD101 = SNAME_FIELD * 0x101,
};
/* option bytes: [code][len][data1][data2]..[dataLEN] */
optionptr = packet->options;
rem = sizeof(packet->options);
while (1) {
if (rem <= 0) {
bb_error_msg("bad packet, malformed option field");
return NULL;
}
if (optionptr[OPT_CODE] == DHCP_PADDING) {
rem--;
optionptr++;
continue;
}
if (optionptr[OPT_CODE] == DHCP_END) {
if ((overload & FILE_FIELD101) == FILE_FIELD) {
/* can use packet->file, and didn't look at it yet */
overload |= FILE_FIELD101; /* "we looked at it" */
optionptr = packet->file;
rem = sizeof(packet->file);
continue;
}
if ((overload & SNAME_FIELD101) == SNAME_FIELD) {
/* can use packet->sname, and didn't look at it yet */
overload |= SNAME_FIELD101; /* "we looked at it" */
optionptr = packet->sname;
rem = sizeof(packet->sname);
continue;
}
break;
}
len = 2 + optionptr[OPT_LEN];
rem -= len;
if (rem < 0)
continue; /* complain and return NULL */
if (optionptr[OPT_CODE] == code) {
log_option("Option found", optionptr);
return optionptr + OPT_DATA;
}
if (optionptr[OPT_CODE] == DHCP_OPTION_OVERLOAD) {
overload |= optionptr[OPT_DATA];
/* fall through */
}
optionptr += len;
}
/* log3 because udhcpc uses it a lot - very noisy */
log3("Option 0x%02x not found", code);
return NULL;
}
| Overflow | 0 | uint8_t* FAST_FUNC udhcp_get_option(struct dhcp_packet *packet, int code)
{
uint8_t *optionptr;
int len;
int rem;
int overload = 0;
enum {
FILE_FIELD101 = FILE_FIELD * 0x101,
SNAME_FIELD101 = SNAME_FIELD * 0x101,
};
/* option bytes: [code][len][data1][data2]..[dataLEN] */
optionptr = packet->options;
rem = sizeof(packet->options);
while (1) {
if (rem <= 0) {
bb_error_msg("bad packet, malformed option field");
return NULL;
}
if (optionptr[OPT_CODE] == DHCP_PADDING) {
rem--;
optionptr++;
continue;
}
if (optionptr[OPT_CODE] == DHCP_END) {
if ((overload & FILE_FIELD101) == FILE_FIELD) {
/* can use packet->file, and didn't look at it yet */
overload |= FILE_FIELD101; /* "we looked at it" */
optionptr = packet->file;
rem = sizeof(packet->file);
continue;
}
if ((overload & SNAME_FIELD101) == SNAME_FIELD) {
/* can use packet->sname, and didn't look at it yet */
overload |= SNAME_FIELD101; /* "we looked at it" */
optionptr = packet->sname;
rem = sizeof(packet->sname);
continue;
}
break;
}
len = 2 + optionptr[OPT_LEN];
rem -= len;
if (rem < 0)
continue; /* complain and return NULL */
if (optionptr[OPT_CODE] == code) {
log_option("Option found", optionptr);
return optionptr + OPT_DATA;
}
if (optionptr[OPT_CODE] == DHCP_OPTION_OVERLOAD) {
overload |= optionptr[OPT_DATA];
/* fall through */
}
optionptr += len;
}
/* log3 because udhcpc uses it a lot - very noisy */
log3("Option 0x%02x not found", code);
return NULL;
}
| @@ -142,7 +142,7 @@ const char dhcp_option_strings[] ALIGN1 =
* udhcp_str2optset: to determine how many bytes to allocate.
* xmalloc_optname_optval: to estimate string length
* from binary option length: (option[LEN] / dhcp_option_lengths[opt_type])
- * is the number of elements, multiply in by one element's string width
+ * is the number of elements, multiply it by one element's string width
* (len_of_option_as_string[opt_type]) and you know how wide string you need.
*/
const uint8_t dhcp_option_lengths[] ALIGN1 = {
@@ -162,7 +162,18 @@ const uint8_t dhcp_option_lengths[] ALIGN1 = {
[OPTION_S32] = 4,
/* Just like OPTION_STRING, we use minimum length here */
[OPTION_STATIC_ROUTES] = 5,
- [OPTION_6RD] = 22, /* ignored by udhcp_str2optset */
+ [OPTION_6RD] = 12, /* ignored by udhcp_str2optset */
+ /* The above value was chosen as follows:
+ * len_of_option_as_string[] for this option is >60: it's a string of the form
+ * "32 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 ".
+ * Each additional ipv4 address takes 4 bytes in binary option and appends
+ * another "255.255.255.255 " 16-byte string. We can set [OPTION_6RD] = 4
+ * but this severely overestimates string length: instead of 16 bytes,
+ * it adds >60 for every 4 bytes in binary option.
+ * We cheat and declare here that option is in units of 12 bytes.
+ * This adds more than 60 bytes for every three ipv4 addresses - more than enough.
+ * (Even 16 instead of 12 should work, but let's be paranoid).
+ */
}; | CWE-119 | null | null |
12,444 | unsigned FAST_FUNC udhcp_option_idx(const char *name)
{
int n = index_in_strings(dhcp_option_strings, name);
if (n >= 0)
return n;
{
char buf[sizeof(dhcp_option_strings)];
char *d = buf;
const char *s = dhcp_option_strings;
while (s < dhcp_option_strings + sizeof(dhcp_option_strings) - 2) {
*d++ = (*s == '\0' ? ' ' : *s);
s++;
}
*d = '\0';
bb_error_msg_and_die("unknown option '%s', known options: %s", name, buf);
}
}
| Overflow | 0 | unsigned FAST_FUNC udhcp_option_idx(const char *name)
{
int n = index_in_strings(dhcp_option_strings, name);
if (n >= 0)
return n;
{
char buf[sizeof(dhcp_option_strings)];
char *d = buf;
const char *s = dhcp_option_strings;
while (s < dhcp_option_strings + sizeof(dhcp_option_strings) - 2) {
*d++ = (*s == '\0' ? ' ' : *s);
s++;
}
*d = '\0';
bb_error_msg_and_die("unknown option '%s', known options: %s", name, buf);
}
}
| @@ -142,7 +142,7 @@ const char dhcp_option_strings[] ALIGN1 =
* udhcp_str2optset: to determine how many bytes to allocate.
* xmalloc_optname_optval: to estimate string length
* from binary option length: (option[LEN] / dhcp_option_lengths[opt_type])
- * is the number of elements, multiply in by one element's string width
+ * is the number of elements, multiply it by one element's string width
* (len_of_option_as_string[opt_type]) and you know how wide string you need.
*/
const uint8_t dhcp_option_lengths[] ALIGN1 = {
@@ -162,7 +162,18 @@ const uint8_t dhcp_option_lengths[] ALIGN1 = {
[OPTION_S32] = 4,
/* Just like OPTION_STRING, we use minimum length here */
[OPTION_STATIC_ROUTES] = 5,
- [OPTION_6RD] = 22, /* ignored by udhcp_str2optset */
+ [OPTION_6RD] = 12, /* ignored by udhcp_str2optset */
+ /* The above value was chosen as follows:
+ * len_of_option_as_string[] for this option is >60: it's a string of the form
+ * "32 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 ".
+ * Each additional ipv4 address takes 4 bytes in binary option and appends
+ * another "255.255.255.255 " 16-byte string. We can set [OPTION_6RD] = 4
+ * but this severely overestimates string length: instead of 16 bytes,
+ * it adds >60 for every 4 bytes in binary option.
+ * We cheat and declare here that option is in units of 12 bytes.
+ * This adds more than 60 bytes for every three ipv4 addresses - more than enough.
+ * (Even 16 instead of 12 should work, but let's be paranoid).
+ */
}; | CWE-119 | null | null |
12,445 | int FAST_FUNC udhcp_str2optset(const char *const_str, void *arg)
{
struct option_set **opt_list = arg;
char *opt, *val;
char *str;
const struct dhcp_optflag *optflag;
struct dhcp_optflag bin_optflag;
unsigned optcode;
int retval, length;
/* IP_PAIR needs 8 bytes, STATIC_ROUTES needs 9 max */
char buffer[9] ALIGNED(4);
uint16_t *result_u16 = (uint16_t *) buffer;
uint32_t *result_u32 = (uint32_t *) buffer;
/* Cheat, the only *const* str possible is "" */
str = (char *) const_str;
opt = strtok(str, " \t=");
if (!opt)
return 0;
optcode = bb_strtou(opt, NULL, 0);
if (!errno && optcode < 255) {
/* Raw (numeric) option code */
bin_optflag.flags = OPTION_BIN;
bin_optflag.code = optcode;
optflag = &bin_optflag;
} else {
optflag = &dhcp_optflags[udhcp_option_idx(opt)];
}
retval = 0;
do {
val = strtok(NULL, ", \t");
if (!val)
break;
length = dhcp_option_lengths[optflag->flags & OPTION_TYPE_MASK];
retval = 0;
opt = buffer; /* new meaning for variable opt */
switch (optflag->flags & OPTION_TYPE_MASK) {
case OPTION_IP:
retval = udhcp_str2nip(val, buffer);
break;
case OPTION_IP_PAIR:
retval = udhcp_str2nip(val, buffer);
val = strtok(NULL, ", \t/-");
if (!val)
retval = 0;
if (retval)
retval = udhcp_str2nip(val, buffer + 4);
break;
case OPTION_STRING:
case OPTION_STRING_HOST:
#if ENABLE_FEATURE_UDHCP_RFC3397
case OPTION_DNS_STRING:
#endif
length = strnlen(val, 254);
if (length > 0) {
opt = val;
retval = 1;
}
break;
case OPTION_U8:
buffer[0] = bb_strtou32(val, NULL, 0);
retval = (errno == 0);
break;
/* htonX are macros in older libc's, using temp var
* in code below for safety */
/* TODO: use bb_strtoX? */
case OPTION_U16: {
uint32_t tmp = bb_strtou32(val, NULL, 0);
*result_u16 = htons(tmp);
retval = (errno == 0 /*&& tmp < 0x10000*/);
break;
}
case OPTION_U32: {
uint32_t tmp = bb_strtou32(val, NULL, 0);
*result_u32 = htonl(tmp);
retval = (errno == 0);
break;
}
case OPTION_S32: {
int32_t tmp = bb_strtoi32(val, NULL, 0);
*result_u32 = htonl(tmp);
retval = (errno == 0);
break;
}
case OPTION_STATIC_ROUTES: {
/* Input: "a.b.c.d/m" */
/* Output: mask(1 byte),pfx(0-4 bytes),gw(4 bytes) */
unsigned mask;
char *slash = strchr(val, '/');
if (slash) {
*slash = '\0';
retval = udhcp_str2nip(val, buffer + 1);
buffer[0] = mask = bb_strtou(slash + 1, NULL, 10);
val = strtok(NULL, ", \t/-");
if (!val || mask > 32 || errno)
retval = 0;
if (retval) {
length = ((mask + 7) >> 3) + 5;
retval = udhcp_str2nip(val, buffer + (length - 4));
}
}
break;
}
case OPTION_BIN: /* handled in attach_option() */
opt = val;
retval = 1;
default:
break;
}
if (retval)
attach_option(opt_list, optflag, opt, length);
} while (retval && (optflag->flags & OPTION_LIST));
return retval;
}
| Overflow | 0 | int FAST_FUNC udhcp_str2optset(const char *const_str, void *arg)
{
struct option_set **opt_list = arg;
char *opt, *val;
char *str;
const struct dhcp_optflag *optflag;
struct dhcp_optflag bin_optflag;
unsigned optcode;
int retval, length;
/* IP_PAIR needs 8 bytes, STATIC_ROUTES needs 9 max */
char buffer[9] ALIGNED(4);
uint16_t *result_u16 = (uint16_t *) buffer;
uint32_t *result_u32 = (uint32_t *) buffer;
/* Cheat, the only *const* str possible is "" */
str = (char *) const_str;
opt = strtok(str, " \t=");
if (!opt)
return 0;
optcode = bb_strtou(opt, NULL, 0);
if (!errno && optcode < 255) {
/* Raw (numeric) option code */
bin_optflag.flags = OPTION_BIN;
bin_optflag.code = optcode;
optflag = &bin_optflag;
} else {
optflag = &dhcp_optflags[udhcp_option_idx(opt)];
}
retval = 0;
do {
val = strtok(NULL, ", \t");
if (!val)
break;
length = dhcp_option_lengths[optflag->flags & OPTION_TYPE_MASK];
retval = 0;
opt = buffer; /* new meaning for variable opt */
switch (optflag->flags & OPTION_TYPE_MASK) {
case OPTION_IP:
retval = udhcp_str2nip(val, buffer);
break;
case OPTION_IP_PAIR:
retval = udhcp_str2nip(val, buffer);
val = strtok(NULL, ", \t/-");
if (!val)
retval = 0;
if (retval)
retval = udhcp_str2nip(val, buffer + 4);
break;
case OPTION_STRING:
case OPTION_STRING_HOST:
#if ENABLE_FEATURE_UDHCP_RFC3397
case OPTION_DNS_STRING:
#endif
length = strnlen(val, 254);
if (length > 0) {
opt = val;
retval = 1;
}
break;
case OPTION_U8:
buffer[0] = bb_strtou32(val, NULL, 0);
retval = (errno == 0);
break;
/* htonX are macros in older libc's, using temp var
* in code below for safety */
/* TODO: use bb_strtoX? */
case OPTION_U16: {
uint32_t tmp = bb_strtou32(val, NULL, 0);
*result_u16 = htons(tmp);
retval = (errno == 0 /*&& tmp < 0x10000*/);
break;
}
case OPTION_U32: {
uint32_t tmp = bb_strtou32(val, NULL, 0);
*result_u32 = htonl(tmp);
retval = (errno == 0);
break;
}
case OPTION_S32: {
int32_t tmp = bb_strtoi32(val, NULL, 0);
*result_u32 = htonl(tmp);
retval = (errno == 0);
break;
}
case OPTION_STATIC_ROUTES: {
/* Input: "a.b.c.d/m" */
/* Output: mask(1 byte),pfx(0-4 bytes),gw(4 bytes) */
unsigned mask;
char *slash = strchr(val, '/');
if (slash) {
*slash = '\0';
retval = udhcp_str2nip(val, buffer + 1);
buffer[0] = mask = bb_strtou(slash + 1, NULL, 10);
val = strtok(NULL, ", \t/-");
if (!val || mask > 32 || errno)
retval = 0;
if (retval) {
length = ((mask + 7) >> 3) + 5;
retval = udhcp_str2nip(val, buffer + (length - 4));
}
}
break;
}
case OPTION_BIN: /* handled in attach_option() */
opt = val;
retval = 1;
default:
break;
}
if (retval)
attach_option(opt_list, optflag, opt, length);
} while (retval && (optflag->flags & OPTION_LIST));
return retval;
}
| @@ -142,7 +142,7 @@ const char dhcp_option_strings[] ALIGN1 =
* udhcp_str2optset: to determine how many bytes to allocate.
* xmalloc_optname_optval: to estimate string length
* from binary option length: (option[LEN] / dhcp_option_lengths[opt_type])
- * is the number of elements, multiply in by one element's string width
+ * is the number of elements, multiply it by one element's string width
* (len_of_option_as_string[opt_type]) and you know how wide string you need.
*/
const uint8_t dhcp_option_lengths[] ALIGN1 = {
@@ -162,7 +162,18 @@ const uint8_t dhcp_option_lengths[] ALIGN1 = {
[OPTION_S32] = 4,
/* Just like OPTION_STRING, we use minimum length here */
[OPTION_STATIC_ROUTES] = 5,
- [OPTION_6RD] = 22, /* ignored by udhcp_str2optset */
+ [OPTION_6RD] = 12, /* ignored by udhcp_str2optset */
+ /* The above value was chosen as follows:
+ * len_of_option_as_string[] for this option is >60: it's a string of the form
+ * "32 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 ".
+ * Each additional ipv4 address takes 4 bytes in binary option and appends
+ * another "255.255.255.255 " 16-byte string. We can set [OPTION_6RD] = 4
+ * but this severely overestimates string length: instead of 16 bytes,
+ * it adds >60 for every 4 bytes in binary option.
+ * We cheat and declare here that option is in units of 12 bytes.
+ * This adds more than 60 bytes for every three ipv4 addresses - more than enough.
+ * (Even 16 instead of 12 should work, but let's be paranoid).
+ */
}; | CWE-119 | null | null |
12,446 | static int bcast_or_ucast(struct dhcp_packet *packet, uint32_t ciaddr, uint32_t server)
{
if (server)
return udhcp_send_kernel_packet(packet,
ciaddr, CLIENT_PORT,
server, SERVER_PORT);
return raw_bcast_from_client_config_ifindex(packet);
}
| Overflow | 0 | static int bcast_or_ucast(struct dhcp_packet *packet, uint32_t ciaddr, uint32_t server)
{
if (server)
return udhcp_send_kernel_packet(packet,
ciaddr, CLIENT_PORT,
server, SERVER_PORT);
return raw_bcast_from_client_config_ifindex(packet);
}
| @@ -113,7 +113,7 @@ static const uint8_t len_of_option_as_string[] = {
[OPTION_IP ] = sizeof("255.255.255.255 "),
[OPTION_IP_PAIR ] = sizeof("255.255.255.255 ") * 2,
[OPTION_STATIC_ROUTES ] = sizeof("255.255.255.255/32 255.255.255.255 "),
- [OPTION_6RD ] = sizeof("32 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
+ [OPTION_6RD ] = sizeof("132 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
[OPTION_STRING ] = 1,
[OPTION_STRING_HOST ] = 1,
#if ENABLE_FEATURE_UDHCP_RFC3397
@@ -222,7 +222,7 @@ static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_
type = optflag->flags & OPTION_TYPE_MASK;
optlen = dhcp_option_lengths[type];
upper_length = len_of_option_as_string[type]
- * ((unsigned)(len + optlen - 1) / (unsigned)optlen);
+ * ((unsigned)(len + optlen) / (unsigned)optlen);
dest = ret = xmalloc(upper_length + strlen(opt_name) + 2);
dest += sprintf(ret, "%s=", opt_name); | CWE-119 | null | null |
12,447 | static void change_listen_mode(int new_mode)
{
log1("Entering listen mode: %s",
new_mode != LISTEN_NONE
? (new_mode == LISTEN_KERNEL ? "kernel" : "raw")
: "none"
);
listen_mode = new_mode;
if (sockfd >= 0) {
close(sockfd);
sockfd = -1;
}
if (new_mode == LISTEN_KERNEL)
sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT, client_config.interface);
else if (new_mode != LISTEN_NONE)
sockfd = udhcp_raw_socket(client_config.ifindex);
/* else LISTEN_NONE: sockfd stays closed */
}
| Overflow | 0 | static void change_listen_mode(int new_mode)
{
log1("Entering listen mode: %s",
new_mode != LISTEN_NONE
? (new_mode == LISTEN_KERNEL ? "kernel" : "raw")
: "none"
);
listen_mode = new_mode;
if (sockfd >= 0) {
close(sockfd);
sockfd = -1;
}
if (new_mode == LISTEN_KERNEL)
sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT, client_config.interface);
else if (new_mode != LISTEN_NONE)
sockfd = udhcp_raw_socket(client_config.ifindex);
/* else LISTEN_NONE: sockfd stays closed */
}
| @@ -113,7 +113,7 @@ static const uint8_t len_of_option_as_string[] = {
[OPTION_IP ] = sizeof("255.255.255.255 "),
[OPTION_IP_PAIR ] = sizeof("255.255.255.255 ") * 2,
[OPTION_STATIC_ROUTES ] = sizeof("255.255.255.255/32 255.255.255.255 "),
- [OPTION_6RD ] = sizeof("32 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
+ [OPTION_6RD ] = sizeof("132 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
[OPTION_STRING ] = 1,
[OPTION_STRING_HOST ] = 1,
#if ENABLE_FEATURE_UDHCP_RFC3397
@@ -222,7 +222,7 @@ static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_
type = optflag->flags & OPTION_TYPE_MASK;
optlen = dhcp_option_lengths[type];
upper_length = len_of_option_as_string[type]
- * ((unsigned)(len + optlen - 1) / (unsigned)optlen);
+ * ((unsigned)(len + optlen) / (unsigned)optlen);
dest = ret = xmalloc(upper_length + strlen(opt_name) + 2);
dest += sprintf(ret, "%s=", opt_name); | CWE-119 | null | null |
12,448 | static char **fill_envp(struct dhcp_packet *packet)
{
int envc;
int i;
char **envp, **curr;
const char *opt_name;
uint8_t *temp;
uint8_t overload = 0;
#define BITMAP unsigned
#define BBITS (sizeof(BITMAP) * 8)
#define BMASK(i) (1 << (i & (sizeof(BITMAP) * 8 - 1)))
#define FOUND_OPTS(i) (found_opts[(unsigned)i / BBITS])
BITMAP found_opts[256 / BBITS];
memset(found_opts, 0, sizeof(found_opts));
/* We need 6 elements for:
* "interface=IFACE"
* "ip=N.N.N.N" from packet->yiaddr
* "siaddr=IP" from packet->siaddr_nip (unless 0)
* "boot_file=FILE" from packet->file (unless overloaded)
* "sname=SERVER_HOSTNAME" from packet->sname (unless overloaded)
* terminating NULL
*/
envc = 6;
/* +1 element for each option, +2 for subnet option: */
if (packet) {
/* note: do not search for "pad" (0) and "end" (255) options */
for (i = 1; i < 255; i++) {
temp = udhcp_get_option(packet, i);
if (temp) {
if (i == DHCP_OPTION_OVERLOAD)
overload = *temp;
else if (i == DHCP_SUBNET)
envc++; /* for $mask */
envc++;
/*if (i != DHCP_MESSAGE_TYPE)*/
FOUND_OPTS(i) |= BMASK(i);
}
}
}
curr = envp = xzalloc(sizeof(envp[0]) * envc);
*curr = xasprintf("interface=%s", client_config.interface);
putenv(*curr++);
if (!packet)
return envp;
/* Export BOOTP fields. Fields we don't (yet?) export:
* uint8_t op; // always BOOTREPLY
* uint8_t htype; // hardware address type. 1 = 10mb ethernet
* uint8_t hlen; // hardware address length
* uint8_t hops; // used by relay agents only
* uint32_t xid;
* uint16_t secs; // elapsed since client began acquisition/renewal
* uint16_t flags; // only one flag so far: bcast. Never set by server
* uint32_t ciaddr; // client IP (usually == yiaddr. can it be different
* // if during renew server wants to give us differn IP?)
* uint32_t gateway_nip; // relay agent IP address
* uint8_t chaddr[16]; // link-layer client hardware address (MAC)
* TODO: export gateway_nip as $giaddr?
*/
/* Most important one: yiaddr as $ip */
*curr = xmalloc(sizeof("ip=255.255.255.255"));
sprint_nip(*curr, "ip=", (uint8_t *) &packet->yiaddr);
putenv(*curr++);
if (packet->siaddr_nip) {
/* IP address of next server to use in bootstrap */
*curr = xmalloc(sizeof("siaddr=255.255.255.255"));
sprint_nip(*curr, "siaddr=", (uint8_t *) &packet->siaddr_nip);
putenv(*curr++);
}
if (!(overload & FILE_FIELD) && packet->file[0]) {
/* watch out for invalid packets */
*curr = xasprintf("boot_file=%."DHCP_PKT_FILE_LEN_STR"s", packet->file);
putenv(*curr++);
}
if (!(overload & SNAME_FIELD) && packet->sname[0]) {
/* watch out for invalid packets */
*curr = xasprintf("sname=%."DHCP_PKT_SNAME_LEN_STR"s", packet->sname);
putenv(*curr++);
}
/* Export known DHCP options */
opt_name = dhcp_option_strings;
i = 0;
while (*opt_name) {
uint8_t code = dhcp_optflags[i].code;
BITMAP *found_ptr = &FOUND_OPTS(code);
BITMAP found_mask = BMASK(code);
if (!(*found_ptr & found_mask))
goto next;
*found_ptr &= ~found_mask; /* leave only unknown options */
temp = udhcp_get_option(packet, code);
*curr = xmalloc_optname_optval(temp, &dhcp_optflags[i], opt_name);
putenv(*curr++);
if (code == DHCP_SUBNET) {
/* Subnet option: make things like "$ip/$mask" possible */
uint32_t subnet;
move_from_unaligned32(subnet, temp);
*curr = xasprintf("mask=%u", mton(subnet));
putenv(*curr++);
}
next:
opt_name += strlen(opt_name) + 1;
i++;
}
/* Export unknown options */
for (i = 0; i < 256;) {
BITMAP bitmap = FOUND_OPTS(i);
if (!bitmap) {
i += BBITS;
continue;
}
if (bitmap & BMASK(i)) {
unsigned len, ofs;
temp = udhcp_get_option(packet, i);
/* udhcp_get_option returns ptr to data portion,
* need to go back to get len
*/
len = temp[-OPT_DATA + OPT_LEN];
*curr = xmalloc(sizeof("optNNN=") + 1 + len*2);
ofs = sprintf(*curr, "opt%u=", i);
*bin2hex(*curr + ofs, (void*) temp, len) = '\0';
putenv(*curr++);
}
i++;
}
return envp;
}
| Overflow | 0 | static char **fill_envp(struct dhcp_packet *packet)
{
int envc;
int i;
char **envp, **curr;
const char *opt_name;
uint8_t *temp;
uint8_t overload = 0;
#define BITMAP unsigned
#define BBITS (sizeof(BITMAP) * 8)
#define BMASK(i) (1 << (i & (sizeof(BITMAP) * 8 - 1)))
#define FOUND_OPTS(i) (found_opts[(unsigned)i / BBITS])
BITMAP found_opts[256 / BBITS];
memset(found_opts, 0, sizeof(found_opts));
/* We need 6 elements for:
* "interface=IFACE"
* "ip=N.N.N.N" from packet->yiaddr
* "siaddr=IP" from packet->siaddr_nip (unless 0)
* "boot_file=FILE" from packet->file (unless overloaded)
* "sname=SERVER_HOSTNAME" from packet->sname (unless overloaded)
* terminating NULL
*/
envc = 6;
/* +1 element for each option, +2 for subnet option: */
if (packet) {
/* note: do not search for "pad" (0) and "end" (255) options */
for (i = 1; i < 255; i++) {
temp = udhcp_get_option(packet, i);
if (temp) {
if (i == DHCP_OPTION_OVERLOAD)
overload = *temp;
else if (i == DHCP_SUBNET)
envc++; /* for $mask */
envc++;
/*if (i != DHCP_MESSAGE_TYPE)*/
FOUND_OPTS(i) |= BMASK(i);
}
}
}
curr = envp = xzalloc(sizeof(envp[0]) * envc);
*curr = xasprintf("interface=%s", client_config.interface);
putenv(*curr++);
if (!packet)
return envp;
/* Export BOOTP fields. Fields we don't (yet?) export:
* uint8_t op; // always BOOTREPLY
* uint8_t htype; // hardware address type. 1 = 10mb ethernet
* uint8_t hlen; // hardware address length
* uint8_t hops; // used by relay agents only
* uint32_t xid;
* uint16_t secs; // elapsed since client began acquisition/renewal
* uint16_t flags; // only one flag so far: bcast. Never set by server
* uint32_t ciaddr; // client IP (usually == yiaddr. can it be different
* // if during renew server wants to give us differn IP?)
* uint32_t gateway_nip; // relay agent IP address
* uint8_t chaddr[16]; // link-layer client hardware address (MAC)
* TODO: export gateway_nip as $giaddr?
*/
/* Most important one: yiaddr as $ip */
*curr = xmalloc(sizeof("ip=255.255.255.255"));
sprint_nip(*curr, "ip=", (uint8_t *) &packet->yiaddr);
putenv(*curr++);
if (packet->siaddr_nip) {
/* IP address of next server to use in bootstrap */
*curr = xmalloc(sizeof("siaddr=255.255.255.255"));
sprint_nip(*curr, "siaddr=", (uint8_t *) &packet->siaddr_nip);
putenv(*curr++);
}
if (!(overload & FILE_FIELD) && packet->file[0]) {
/* watch out for invalid packets */
*curr = xasprintf("boot_file=%."DHCP_PKT_FILE_LEN_STR"s", packet->file);
putenv(*curr++);
}
if (!(overload & SNAME_FIELD) && packet->sname[0]) {
/* watch out for invalid packets */
*curr = xasprintf("sname=%."DHCP_PKT_SNAME_LEN_STR"s", packet->sname);
putenv(*curr++);
}
/* Export known DHCP options */
opt_name = dhcp_option_strings;
i = 0;
while (*opt_name) {
uint8_t code = dhcp_optflags[i].code;
BITMAP *found_ptr = &FOUND_OPTS(code);
BITMAP found_mask = BMASK(code);
if (!(*found_ptr & found_mask))
goto next;
*found_ptr &= ~found_mask; /* leave only unknown options */
temp = udhcp_get_option(packet, code);
*curr = xmalloc_optname_optval(temp, &dhcp_optflags[i], opt_name);
putenv(*curr++);
if (code == DHCP_SUBNET) {
/* Subnet option: make things like "$ip/$mask" possible */
uint32_t subnet;
move_from_unaligned32(subnet, temp);
*curr = xasprintf("mask=%u", mton(subnet));
putenv(*curr++);
}
next:
opt_name += strlen(opt_name) + 1;
i++;
}
/* Export unknown options */
for (i = 0; i < 256;) {
BITMAP bitmap = FOUND_OPTS(i);
if (!bitmap) {
i += BBITS;
continue;
}
if (bitmap & BMASK(i)) {
unsigned len, ofs;
temp = udhcp_get_option(packet, i);
/* udhcp_get_option returns ptr to data portion,
* need to go back to get len
*/
len = temp[-OPT_DATA + OPT_LEN];
*curr = xmalloc(sizeof("optNNN=") + 1 + len*2);
ofs = sprintf(*curr, "opt%u=", i);
*bin2hex(*curr + ofs, (void*) temp, len) = '\0';
putenv(*curr++);
}
i++;
}
return envp;
}
| @@ -113,7 +113,7 @@ static const uint8_t len_of_option_as_string[] = {
[OPTION_IP ] = sizeof("255.255.255.255 "),
[OPTION_IP_PAIR ] = sizeof("255.255.255.255 ") * 2,
[OPTION_STATIC_ROUTES ] = sizeof("255.255.255.255/32 255.255.255.255 "),
- [OPTION_6RD ] = sizeof("32 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
+ [OPTION_6RD ] = sizeof("132 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
[OPTION_STRING ] = 1,
[OPTION_STRING_HOST ] = 1,
#if ENABLE_FEATURE_UDHCP_RFC3397
@@ -222,7 +222,7 @@ static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_
type = optflag->flags & OPTION_TYPE_MASK;
optlen = dhcp_option_lengths[type];
upper_length = len_of_option_as_string[type]
- * ((unsigned)(len + optlen - 1) / (unsigned)optlen);
+ * ((unsigned)(len + optlen) / (unsigned)optlen);
dest = ret = xmalloc(upper_length + strlen(opt_name) + 2);
dest += sprintf(ret, "%s=", opt_name); | CWE-119 | null | null |
12,449 | static void perform_release(uint32_t server_addr, uint32_t requested_ip)
{
char buffer[sizeof("255.255.255.255")];
struct in_addr temp_addr;
/* send release packet */
if (state == BOUND || state == RENEWING || state == REBINDING) {
temp_addr.s_addr = server_addr;
strcpy(buffer, inet_ntoa(temp_addr));
temp_addr.s_addr = requested_ip;
bb_info_msg("Unicasting a release of %s to %s",
inet_ntoa(temp_addr), buffer);
send_release(server_addr, requested_ip); /* unicast */
udhcp_run_script(NULL, "deconfig");
}
bb_info_msg("Entering released state");
change_listen_mode(LISTEN_NONE);
state = RELEASED;
}
| Overflow | 0 | static void perform_release(uint32_t server_addr, uint32_t requested_ip)
{
char buffer[sizeof("255.255.255.255")];
struct in_addr temp_addr;
/* send release packet */
if (state == BOUND || state == RENEWING || state == REBINDING) {
temp_addr.s_addr = server_addr;
strcpy(buffer, inet_ntoa(temp_addr));
temp_addr.s_addr = requested_ip;
bb_info_msg("Unicasting a release of %s to %s",
inet_ntoa(temp_addr), buffer);
send_release(server_addr, requested_ip); /* unicast */
udhcp_run_script(NULL, "deconfig");
}
bb_info_msg("Entering released state");
change_listen_mode(LISTEN_NONE);
state = RELEASED;
}
| @@ -113,7 +113,7 @@ static const uint8_t len_of_option_as_string[] = {
[OPTION_IP ] = sizeof("255.255.255.255 "),
[OPTION_IP_PAIR ] = sizeof("255.255.255.255 ") * 2,
[OPTION_STATIC_ROUTES ] = sizeof("255.255.255.255/32 255.255.255.255 "),
- [OPTION_6RD ] = sizeof("32 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
+ [OPTION_6RD ] = sizeof("132 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
[OPTION_STRING ] = 1,
[OPTION_STRING_HOST ] = 1,
#if ENABLE_FEATURE_UDHCP_RFC3397
@@ -222,7 +222,7 @@ static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_
type = optflag->flags & OPTION_TYPE_MASK;
optlen = dhcp_option_lengths[type];
upper_length = len_of_option_as_string[type]
- * ((unsigned)(len + optlen - 1) / (unsigned)optlen);
+ * ((unsigned)(len + optlen) / (unsigned)optlen);
dest = ret = xmalloc(upper_length + strlen(opt_name) + 2);
dest += sprintf(ret, "%s=", opt_name); | CWE-119 | null | null |
12,450 | static void perform_renew(void)
{
bb_info_msg("Performing a DHCP renew");
switch (state) {
case BOUND:
change_listen_mode(LISTEN_KERNEL);
case RENEWING:
case REBINDING:
state = RENEW_REQUESTED;
break;
case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
udhcp_run_script(NULL, "deconfig");
case REQUESTING:
case RELEASED:
change_listen_mode(LISTEN_RAW);
state = INIT_SELECTING;
break;
case INIT_SELECTING:
break;
}
}
| Overflow | 0 | static void perform_renew(void)
{
bb_info_msg("Performing a DHCP renew");
switch (state) {
case BOUND:
change_listen_mode(LISTEN_KERNEL);
case RENEWING:
case REBINDING:
state = RENEW_REQUESTED;
break;
case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
udhcp_run_script(NULL, "deconfig");
case REQUESTING:
case RELEASED:
change_listen_mode(LISTEN_RAW);
state = INIT_SELECTING;
break;
case INIT_SELECTING:
break;
}
}
| @@ -113,7 +113,7 @@ static const uint8_t len_of_option_as_string[] = {
[OPTION_IP ] = sizeof("255.255.255.255 "),
[OPTION_IP_PAIR ] = sizeof("255.255.255.255 ") * 2,
[OPTION_STATIC_ROUTES ] = sizeof("255.255.255.255/32 255.255.255.255 "),
- [OPTION_6RD ] = sizeof("32 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
+ [OPTION_6RD ] = sizeof("132 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
[OPTION_STRING ] = 1,
[OPTION_STRING_HOST ] = 1,
#if ENABLE_FEATURE_UDHCP_RFC3397
@@ -222,7 +222,7 @@ static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_
type = optflag->flags & OPTION_TYPE_MASK;
optlen = dhcp_option_lengths[type];
upper_length = len_of_option_as_string[type]
- * ((unsigned)(len + optlen - 1) / (unsigned)optlen);
+ * ((unsigned)(len + optlen) / (unsigned)optlen);
dest = ret = xmalloc(upper_length + strlen(opt_name) + 2);
dest += sprintf(ret, "%s=", opt_name); | CWE-119 | null | null |
12,451 | static int raw_bcast_from_client_config_ifindex(struct dhcp_packet *packet)
{
return udhcp_send_raw_packet(packet,
/*src*/ INADDR_ANY, CLIENT_PORT,
/*dst*/ INADDR_BROADCAST, SERVER_PORT, MAC_BCAST_ADDR,
client_config.ifindex);
}
| Overflow | 0 | static int raw_bcast_from_client_config_ifindex(struct dhcp_packet *packet)
{
return udhcp_send_raw_packet(packet,
/*src*/ INADDR_ANY, CLIENT_PORT,
/*dst*/ INADDR_BROADCAST, SERVER_PORT, MAC_BCAST_ADDR,
client_config.ifindex);
}
| @@ -113,7 +113,7 @@ static const uint8_t len_of_option_as_string[] = {
[OPTION_IP ] = sizeof("255.255.255.255 "),
[OPTION_IP_PAIR ] = sizeof("255.255.255.255 ") * 2,
[OPTION_STATIC_ROUTES ] = sizeof("255.255.255.255/32 255.255.255.255 "),
- [OPTION_6RD ] = sizeof("32 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
+ [OPTION_6RD ] = sizeof("132 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
[OPTION_STRING ] = 1,
[OPTION_STRING_HOST ] = 1,
#if ENABLE_FEATURE_UDHCP_RFC3397
@@ -222,7 +222,7 @@ static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_
type = optflag->flags & OPTION_TYPE_MASK;
optlen = dhcp_option_lengths[type];
upper_length = len_of_option_as_string[type]
- * ((unsigned)(len + optlen - 1) / (unsigned)optlen);
+ * ((unsigned)(len + optlen) / (unsigned)optlen);
dest = ret = xmalloc(upper_length + strlen(opt_name) + 2);
dest += sprintf(ret, "%s=", opt_name); | CWE-119 | null | null |
12,452 | static NOINLINE int send_decline(/*uint32_t xid,*/ uint32_t server, uint32_t requested)
{
struct dhcp_packet packet;
/* Fill in: op, htype, hlen, cookie, chaddr, random xid fields,
* client-id option (unless -C), message type option:
*/
init_packet(&packet, DHCPDECLINE);
#if 0
/* RFC 2131 says DHCPDECLINE's xid is randomly selected by client,
* but in case the server is buggy and wants DHCPDECLINE's xid
* to match the xid which started entire handshake,
* we use the same xid we used in initial DHCPDISCOVER:
*/
packet.xid = xid;
#endif
/* DHCPDECLINE uses "requested ip", not ciaddr, to store offered IP */
udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
bb_info_msg("Sending decline...");
return raw_bcast_from_client_config_ifindex(&packet);
}
| Overflow | 0 | static NOINLINE int send_decline(/*uint32_t xid,*/ uint32_t server, uint32_t requested)
{
struct dhcp_packet packet;
/* Fill in: op, htype, hlen, cookie, chaddr, random xid fields,
* client-id option (unless -C), message type option:
*/
init_packet(&packet, DHCPDECLINE);
#if 0
/* RFC 2131 says DHCPDECLINE's xid is randomly selected by client,
* but in case the server is buggy and wants DHCPDECLINE's xid
* to match the xid which started entire handshake,
* we use the same xid we used in initial DHCPDISCOVER:
*/
packet.xid = xid;
#endif
/* DHCPDECLINE uses "requested ip", not ciaddr, to store offered IP */
udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
bb_info_msg("Sending decline...");
return raw_bcast_from_client_config_ifindex(&packet);
}
| @@ -113,7 +113,7 @@ static const uint8_t len_of_option_as_string[] = {
[OPTION_IP ] = sizeof("255.255.255.255 "),
[OPTION_IP_PAIR ] = sizeof("255.255.255.255 ") * 2,
[OPTION_STATIC_ROUTES ] = sizeof("255.255.255.255/32 255.255.255.255 "),
- [OPTION_6RD ] = sizeof("32 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
+ [OPTION_6RD ] = sizeof("132 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
[OPTION_STRING ] = 1,
[OPTION_STRING_HOST ] = 1,
#if ENABLE_FEATURE_UDHCP_RFC3397
@@ -222,7 +222,7 @@ static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_
type = optflag->flags & OPTION_TYPE_MASK;
optlen = dhcp_option_lengths[type];
upper_length = len_of_option_as_string[type]
- * ((unsigned)(len + optlen - 1) / (unsigned)optlen);
+ * ((unsigned)(len + optlen) / (unsigned)optlen);
dest = ret = xmalloc(upper_length + strlen(opt_name) + 2);
dest += sprintf(ret, "%s=", opt_name); | CWE-119 | null | null |
12,453 | static NOINLINE int send_discover(uint32_t xid, uint32_t requested)
{
struct dhcp_packet packet;
/* Fill in: op, htype, hlen, cookie, chaddr fields,
* random xid field (we override it below),
* client-id option (unless -C), message type option:
*/
init_packet(&packet, DHCPDISCOVER);
packet.xid = xid;
if (requested)
udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
/* Add options: maxsize,
* optionally: hostname, fqdn, vendorclass,
* "param req" option according to -O, options specified with -x
*/
add_client_options(&packet);
bb_info_msg("Sending discover...");
return raw_bcast_from_client_config_ifindex(&packet);
}
| Overflow | 0 | static NOINLINE int send_discover(uint32_t xid, uint32_t requested)
{
struct dhcp_packet packet;
/* Fill in: op, htype, hlen, cookie, chaddr fields,
* random xid field (we override it below),
* client-id option (unless -C), message type option:
*/
init_packet(&packet, DHCPDISCOVER);
packet.xid = xid;
if (requested)
udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
/* Add options: maxsize,
* optionally: hostname, fqdn, vendorclass,
* "param req" option according to -O, options specified with -x
*/
add_client_options(&packet);
bb_info_msg("Sending discover...");
return raw_bcast_from_client_config_ifindex(&packet);
}
| @@ -113,7 +113,7 @@ static const uint8_t len_of_option_as_string[] = {
[OPTION_IP ] = sizeof("255.255.255.255 "),
[OPTION_IP_PAIR ] = sizeof("255.255.255.255 ") * 2,
[OPTION_STATIC_ROUTES ] = sizeof("255.255.255.255/32 255.255.255.255 "),
- [OPTION_6RD ] = sizeof("32 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
+ [OPTION_6RD ] = sizeof("132 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
[OPTION_STRING ] = 1,
[OPTION_STRING_HOST ] = 1,
#if ENABLE_FEATURE_UDHCP_RFC3397
@@ -222,7 +222,7 @@ static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_
type = optflag->flags & OPTION_TYPE_MASK;
optlen = dhcp_option_lengths[type];
upper_length = len_of_option_as_string[type]
- * ((unsigned)(len + optlen - 1) / (unsigned)optlen);
+ * ((unsigned)(len + optlen) / (unsigned)optlen);
dest = ret = xmalloc(upper_length + strlen(opt_name) + 2);
dest += sprintf(ret, "%s=", opt_name); | CWE-119 | null | null |
12,454 | static int send_release(uint32_t server, uint32_t ciaddr)
{
struct dhcp_packet packet;
/* Fill in: op, htype, hlen, cookie, chaddr, random xid fields,
* client-id option (unless -C), message type option:
*/
init_packet(&packet, DHCPRELEASE);
/* DHCPRELEASE uses ciaddr, not "requested ip", to store IP being released */
packet.ciaddr = ciaddr;
udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
bb_info_msg("Sending release...");
/* Note: normally we unicast here since "server" is not zero.
* However, there _are_ people who run "address-less" DHCP servers,
* and reportedly ISC dhcp client and Windows allow that.
*/
return bcast_or_ucast(&packet, ciaddr, server);
}
| Overflow | 0 | static int send_release(uint32_t server, uint32_t ciaddr)
{
struct dhcp_packet packet;
/* Fill in: op, htype, hlen, cookie, chaddr, random xid fields,
* client-id option (unless -C), message type option:
*/
init_packet(&packet, DHCPRELEASE);
/* DHCPRELEASE uses ciaddr, not "requested ip", to store IP being released */
packet.ciaddr = ciaddr;
udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
bb_info_msg("Sending release...");
/* Note: normally we unicast here since "server" is not zero.
* However, there _are_ people who run "address-less" DHCP servers,
* and reportedly ISC dhcp client and Windows allow that.
*/
return bcast_or_ucast(&packet, ciaddr, server);
}
| @@ -113,7 +113,7 @@ static const uint8_t len_of_option_as_string[] = {
[OPTION_IP ] = sizeof("255.255.255.255 "),
[OPTION_IP_PAIR ] = sizeof("255.255.255.255 ") * 2,
[OPTION_STATIC_ROUTES ] = sizeof("255.255.255.255/32 255.255.255.255 "),
- [OPTION_6RD ] = sizeof("32 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
+ [OPTION_6RD ] = sizeof("132 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
[OPTION_STRING ] = 1,
[OPTION_STRING_HOST ] = 1,
#if ENABLE_FEATURE_UDHCP_RFC3397
@@ -222,7 +222,7 @@ static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_
type = optflag->flags & OPTION_TYPE_MASK;
optlen = dhcp_option_lengths[type];
upper_length = len_of_option_as_string[type]
- * ((unsigned)(len + optlen - 1) / (unsigned)optlen);
+ * ((unsigned)(len + optlen) / (unsigned)optlen);
dest = ret = xmalloc(upper_length + strlen(opt_name) + 2);
dest += sprintf(ret, "%s=", opt_name); | CWE-119 | null | null |
12,455 | static NOINLINE int send_select(uint32_t xid, uint32_t server, uint32_t requested)
{
struct dhcp_packet packet;
struct in_addr addr;
/*
* RFC 2131 4.3.2 DHCPREQUEST message
* ...
* If the DHCPREQUEST message contains a 'server identifier'
* option, the message is in response to a DHCPOFFER message.
* Otherwise, the message is a request to verify or extend an
* existing lease. If the client uses a 'client identifier'
* in a DHCPREQUEST message, it MUST use that same 'client identifier'
* in all subsequent messages. If the client included a list
* of requested parameters in a DHCPDISCOVER message, it MUST
* include that list in all subsequent messages.
*/
/* Fill in: op, htype, hlen, cookie, chaddr fields,
* random xid field (we override it below),
* client-id option (unless -C), message type option:
*/
init_packet(&packet, DHCPREQUEST);
packet.xid = xid;
udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
/* Add options: maxsize,
* optionally: hostname, fqdn, vendorclass,
* "param req" option according to -O, and options specified with -x
*/
add_client_options(&packet);
addr.s_addr = requested;
bb_info_msg("Sending select for %s...", inet_ntoa(addr));
return raw_bcast_from_client_config_ifindex(&packet);
}
| Overflow | 0 | static NOINLINE int send_select(uint32_t xid, uint32_t server, uint32_t requested)
{
struct dhcp_packet packet;
struct in_addr addr;
/*
* RFC 2131 4.3.2 DHCPREQUEST message
* ...
* If the DHCPREQUEST message contains a 'server identifier'
* option, the message is in response to a DHCPOFFER message.
* Otherwise, the message is a request to verify or extend an
* existing lease. If the client uses a 'client identifier'
* in a DHCPREQUEST message, it MUST use that same 'client identifier'
* in all subsequent messages. If the client included a list
* of requested parameters in a DHCPDISCOVER message, it MUST
* include that list in all subsequent messages.
*/
/* Fill in: op, htype, hlen, cookie, chaddr fields,
* random xid field (we override it below),
* client-id option (unless -C), message type option:
*/
init_packet(&packet, DHCPREQUEST);
packet.xid = xid;
udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
/* Add options: maxsize,
* optionally: hostname, fqdn, vendorclass,
* "param req" option according to -O, and options specified with -x
*/
add_client_options(&packet);
addr.s_addr = requested;
bb_info_msg("Sending select for %s...", inet_ntoa(addr));
return raw_bcast_from_client_config_ifindex(&packet);
}
| @@ -113,7 +113,7 @@ static const uint8_t len_of_option_as_string[] = {
[OPTION_IP ] = sizeof("255.255.255.255 "),
[OPTION_IP_PAIR ] = sizeof("255.255.255.255 ") * 2,
[OPTION_STATIC_ROUTES ] = sizeof("255.255.255.255/32 255.255.255.255 "),
- [OPTION_6RD ] = sizeof("32 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
+ [OPTION_6RD ] = sizeof("132 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
[OPTION_STRING ] = 1,
[OPTION_STRING_HOST ] = 1,
#if ENABLE_FEATURE_UDHCP_RFC3397
@@ -222,7 +222,7 @@ static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_
type = optflag->flags & OPTION_TYPE_MASK;
optlen = dhcp_option_lengths[type];
upper_length = len_of_option_as_string[type]
- * ((unsigned)(len + optlen - 1) / (unsigned)optlen);
+ * ((unsigned)(len + optlen) / (unsigned)optlen);
dest = ret = xmalloc(upper_length + strlen(opt_name) + 2);
dest += sprintf(ret, "%s=", opt_name); | CWE-119 | null | null |
12,456 | static int udhcp_raw_socket(int ifindex)
{
int fd;
struct sockaddr_ll sock;
log1("Opening raw socket on ifindex %d", ifindex); //log2?
fd = xsocket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP));
/* ^^^^^
* SOCK_DGRAM: remove link-layer headers on input (SOCK_RAW keeps them)
* ETH_P_IP: want to receive only packets with IPv4 eth type
*/
log1("Got raw socket fd"); //log2?
sock.sll_family = AF_PACKET;
sock.sll_protocol = htons(ETH_P_IP);
sock.sll_ifindex = ifindex;
xbind(fd, (struct sockaddr *) &sock, sizeof(sock));
#if 0 /* Several users reported breakage when BPF filter is used */
if (CLIENT_PORT == 68) {
/* Use only if standard port is in use */
/*
* I've selected not to see LL header, so BPF doesn't see it, too.
* The filter may also pass non-IP and non-ARP packets, but we do
* a more complete check when receiving the message in userspace.
*
* and filter shamelessly stolen from:
*
* http://www.flamewarmaster.de/software/dhcpclient/
*
* There are a few other interesting ideas on that page (look under
* "Motivation"). Use of netlink events is most interesting. Think
* of various network servers listening for events and reconfiguring.
* That would obsolete sending HUP signals and/or make use of restarts.
*
* Copyright: 2006, 2007 Stefan Rompf <sux@loplof.de>.
* License: GPL v2.
*/
static const struct sock_filter filter_instr[] = {
/* load 9th byte (protocol) */
BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
/* jump to L1 if it is IPPROTO_UDP, else to L4 */
BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 0, 6),
/* L1: load halfword from offset 6 (flags and frag offset) */
BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 6),
/* jump to L4 if any bits in frag offset field are set, else to L2 */
BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K, 0x1fff, 4, 0),
/* L2: skip IP header (load index reg with header len) */
BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0),
/* load udp destination port from halfword[header_len + 2] */
BPF_STMT(BPF_LD|BPF_H|BPF_IND, 2),
/* jump to L3 if udp dport is CLIENT_PORT, else to L4 */
BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 68, 0, 1),
/* L3: accept packet ("accept 0x7fffffff bytes") */
/* Accepting 0xffffffff works too but kernel 2.6.19 is buggy */
BPF_STMT(BPF_RET|BPF_K, 0x7fffffff),
/* L4: discard packet ("accept zero bytes") */
BPF_STMT(BPF_RET|BPF_K, 0),
};
static const struct sock_fprog filter_prog = {
.len = sizeof(filter_instr) / sizeof(filter_instr[0]),
/* casting const away: */
.filter = (struct sock_filter *) filter_instr,
};
/* Ignoring error (kernel may lack support for this) */
if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog,
sizeof(filter_prog)) >= 0)
log1("Attached filter to raw socket fd"); // log?
}
#endif
if (setsockopt_1(fd, SOL_PACKET, PACKET_AUXDATA) != 0) {
if (errno != ENOPROTOOPT)
log1("Can't set PACKET_AUXDATA on raw socket");
}
log1("Created raw socket");
return fd;
}
| Overflow | 0 | static int udhcp_raw_socket(int ifindex)
{
int fd;
struct sockaddr_ll sock;
log1("Opening raw socket on ifindex %d", ifindex); //log2?
fd = xsocket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP));
/* ^^^^^
* SOCK_DGRAM: remove link-layer headers on input (SOCK_RAW keeps them)
* ETH_P_IP: want to receive only packets with IPv4 eth type
*/
log1("Got raw socket fd"); //log2?
sock.sll_family = AF_PACKET;
sock.sll_protocol = htons(ETH_P_IP);
sock.sll_ifindex = ifindex;
xbind(fd, (struct sockaddr *) &sock, sizeof(sock));
#if 0 /* Several users reported breakage when BPF filter is used */
if (CLIENT_PORT == 68) {
/* Use only if standard port is in use */
/*
* I've selected not to see LL header, so BPF doesn't see it, too.
* The filter may also pass non-IP and non-ARP packets, but we do
* a more complete check when receiving the message in userspace.
*
* and filter shamelessly stolen from:
*
* http://www.flamewarmaster.de/software/dhcpclient/
*
* There are a few other interesting ideas on that page (look under
* "Motivation"). Use of netlink events is most interesting. Think
* of various network servers listening for events and reconfiguring.
* That would obsolete sending HUP signals and/or make use of restarts.
*
* Copyright: 2006, 2007 Stefan Rompf <sux@loplof.de>.
* License: GPL v2.
*/
static const struct sock_filter filter_instr[] = {
/* load 9th byte (protocol) */
BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
/* jump to L1 if it is IPPROTO_UDP, else to L4 */
BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 0, 6),
/* L1: load halfword from offset 6 (flags and frag offset) */
BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 6),
/* jump to L4 if any bits in frag offset field are set, else to L2 */
BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K, 0x1fff, 4, 0),
/* L2: skip IP header (load index reg with header len) */
BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0),
/* load udp destination port from halfword[header_len + 2] */
BPF_STMT(BPF_LD|BPF_H|BPF_IND, 2),
/* jump to L3 if udp dport is CLIENT_PORT, else to L4 */
BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 68, 0, 1),
/* L3: accept packet ("accept 0x7fffffff bytes") */
/* Accepting 0xffffffff works too but kernel 2.6.19 is buggy */
BPF_STMT(BPF_RET|BPF_K, 0x7fffffff),
/* L4: discard packet ("accept zero bytes") */
BPF_STMT(BPF_RET|BPF_K, 0),
};
static const struct sock_fprog filter_prog = {
.len = sizeof(filter_instr) / sizeof(filter_instr[0]),
/* casting const away: */
.filter = (struct sock_filter *) filter_instr,
};
/* Ignoring error (kernel may lack support for this) */
if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog,
sizeof(filter_prog)) >= 0)
log1("Attached filter to raw socket fd"); // log?
}
#endif
if (setsockopt_1(fd, SOL_PACKET, PACKET_AUXDATA) != 0) {
if (errno != ENOPROTOOPT)
log1("Can't set PACKET_AUXDATA on raw socket");
}
log1("Created raw socket");
return fd;
}
| @@ -113,7 +113,7 @@ static const uint8_t len_of_option_as_string[] = {
[OPTION_IP ] = sizeof("255.255.255.255 "),
[OPTION_IP_PAIR ] = sizeof("255.255.255.255 ") * 2,
[OPTION_STATIC_ROUTES ] = sizeof("255.255.255.255/32 255.255.255.255 "),
- [OPTION_6RD ] = sizeof("32 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
+ [OPTION_6RD ] = sizeof("132 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
[OPTION_STRING ] = 1,
[OPTION_STRING_HOST ] = 1,
#if ENABLE_FEATURE_UDHCP_RFC3397
@@ -222,7 +222,7 @@ static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_
type = optflag->flags & OPTION_TYPE_MASK;
optlen = dhcp_option_lengths[type];
upper_length = len_of_option_as_string[type]
- * ((unsigned)(len + optlen - 1) / (unsigned)optlen);
+ * ((unsigned)(len + optlen) / (unsigned)optlen);
dest = ret = xmalloc(upper_length + strlen(opt_name) + 2);
dest += sprintf(ret, "%s=", opt_name); | CWE-119 | null | null |
12,457 | static const char *valid_domain_label(const char *label)
{
unsigned char ch;
unsigned pos = 0;
for (;;) {
ch = *label;
if ((ch|0x20) < 'a' || (ch|0x20) > 'z') {
if (ch < '0' || ch > '9') {
if (ch == '\0' || ch == '.')
return label;
/* DNS allows only '-', but we are more permissive */
if (ch != '-' && ch != '_')
return NULL;
}
}
label++;
pos++;
}
}
| Overflow | 0 | static const char *valid_domain_label(const char *label)
{
unsigned char ch;
unsigned pos = 0;
for (;;) {
ch = *label;
if ((ch|0x20) < 'a' || (ch|0x20) > 'z') {
if (ch < '0' || ch > '9') {
if (ch == '\0' || ch == '.')
return label;
/* DNS allows only '-', but we are more permissive */
if (ch != '-' && ch != '_')
return NULL;
}
}
label++;
pos++;
}
}
| @@ -113,7 +113,7 @@ static const uint8_t len_of_option_as_string[] = {
[OPTION_IP ] = sizeof("255.255.255.255 "),
[OPTION_IP_PAIR ] = sizeof("255.255.255.255 ") * 2,
[OPTION_STATIC_ROUTES ] = sizeof("255.255.255.255/32 255.255.255.255 "),
- [OPTION_6RD ] = sizeof("32 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
+ [OPTION_6RD ] = sizeof("132 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
[OPTION_STRING ] = 1,
[OPTION_STRING_HOST ] = 1,
#if ENABLE_FEATURE_UDHCP_RFC3397
@@ -222,7 +222,7 @@ static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_
type = optflag->flags & OPTION_TYPE_MASK;
optlen = dhcp_option_lengths[type];
upper_length = len_of_option_as_string[type]
- * ((unsigned)(len + optlen - 1) / (unsigned)optlen);
+ * ((unsigned)(len + optlen) / (unsigned)optlen);
dest = ret = xmalloc(upper_length + strlen(opt_name) + 2);
dest += sprintf(ret, "%s=", opt_name); | CWE-119 | null | null |
12,458 | compare_forward(struct Forward *a, struct Forward *b)
{
if (!compare_host(a->listen_host, b->listen_host))
return 0;
if (!compare_host(a->listen_path, b->listen_path))
return 0;
if (a->listen_port != b->listen_port)
return 0;
if (!compare_host(a->connect_host, b->connect_host))
return 0;
if (!compare_host(a->connect_path, b->connect_path))
return 0;
if (a->connect_port != b->connect_port)
return 0;
return 1;
}
| null | 0 | compare_forward(struct Forward *a, struct Forward *b)
{
if (!compare_host(a->listen_host, b->listen_host))
return 0;
if (!compare_host(a->listen_path, b->listen_path))
return 0;
if (a->listen_port != b->listen_port)
return 0;
if (!compare_host(a->connect_host, b->connect_host))
return 0;
if (!compare_host(a->connect_path, b->connect_path))
return 0;
if (a->connect_port != b->connect_port)
return 0;
return 1;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,459 | control_client_sighandler(int signo)
{
muxclient_terminate = signo;
}
| null | 0 | control_client_sighandler(int signo)
{
muxclient_terminate = signo;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,460 | control_client_sigrelay(int signo)
{
int save_errno = errno;
if (muxserver_pid > 1)
kill(muxserver_pid, signo);
errno = save_errno;
}
| null | 0 | control_client_sigrelay(int signo)
{
int save_errno = errno;
if (muxserver_pid > 1)
kill(muxserver_pid, signo);
errno = save_errno;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,461 | env_permitted(char *env)
{
int i, ret;
char name[1024], *cp;
if ((cp = strchr(env, '=')) == NULL || cp == env)
return 0;
ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
if (ret <= 0 || (size_t)ret >= sizeof(name)) {
error("env_permitted: name '%.100s...' too long", env);
return 0;
}
for (i = 0; i < options.num_send_env; i++)
if (match_pattern(name, options.send_env[i]))
return 1;
return 0;
}
| null | 0 | env_permitted(char *env)
{
int i, ret;
char name[1024], *cp;
if ((cp = strchr(env, '=')) == NULL || cp == env)
return 0;
ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
if (ret <= 0 || (size_t)ret >= sizeof(name)) {
error("env_permitted: name '%.100s...' too long", env);
return 0;
}
for (i = 0; i < options.num_send_env; i++)
if (match_pattern(name, options.send_env[i]))
return 1;
return 0;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,462 | format_forward(u_int ftype, struct Forward *fwd)
{
char *ret;
switch (ftype) {
case MUX_FWD_LOCAL:
xasprintf(&ret, "local forward %.200s:%d -> %.200s:%d",
(fwd->listen_path != NULL) ? fwd->listen_path :
(fwd->listen_host == NULL) ?
(options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
fwd->listen_host, fwd->listen_port,
(fwd->connect_path != NULL) ? fwd->connect_path :
fwd->connect_host, fwd->connect_port);
break;
case MUX_FWD_DYNAMIC:
xasprintf(&ret, "dynamic forward %.200s:%d -> *",
(fwd->listen_host == NULL) ?
(options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
fwd->listen_host, fwd->listen_port);
break;
case MUX_FWD_REMOTE:
xasprintf(&ret, "remote forward %.200s:%d -> %.200s:%d",
(fwd->listen_path != NULL) ? fwd->listen_path :
(fwd->listen_host == NULL) ?
"LOCALHOST" : fwd->listen_host,
fwd->listen_port,
(fwd->connect_path != NULL) ? fwd->connect_path :
fwd->connect_host, fwd->connect_port);
break;
default:
fatal("%s: unknown forward type %u", __func__, ftype);
}
return ret;
}
| null | 0 | format_forward(u_int ftype, struct Forward *fwd)
{
char *ret;
switch (ftype) {
case MUX_FWD_LOCAL:
xasprintf(&ret, "local forward %.200s:%d -> %.200s:%d",
(fwd->listen_path != NULL) ? fwd->listen_path :
(fwd->listen_host == NULL) ?
(options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
fwd->listen_host, fwd->listen_port,
(fwd->connect_path != NULL) ? fwd->connect_path :
fwd->connect_host, fwd->connect_port);
break;
case MUX_FWD_DYNAMIC:
xasprintf(&ret, "dynamic forward %.200s:%d -> *",
(fwd->listen_host == NULL) ?
(options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
fwd->listen_host, fwd->listen_port);
break;
case MUX_FWD_REMOTE:
xasprintf(&ret, "remote forward %.200s:%d -> %.200s:%d",
(fwd->listen_path != NULL) ? fwd->listen_path :
(fwd->listen_host == NULL) ?
"LOCALHOST" : fwd->listen_host,
fwd->listen_port,
(fwd->connect_path != NULL) ? fwd->connect_path :
fwd->connect_host, fwd->connect_port);
break;
default:
fatal("%s: unknown forward type %u", __func__, ftype);
}
return ret;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,463 | mux_client_forward(int fd, int cancel_flag, u_int ftype, struct Forward *fwd)
{
Buffer m;
char *e, *fwd_desc;
u_int type, rid;
fwd_desc = format_forward(ftype, fwd);
debug("Requesting %s %s",
cancel_flag ? "cancellation of" : "forwarding of", fwd_desc);
free(fwd_desc);
buffer_init(&m);
buffer_put_int(&m, cancel_flag ? MUX_C_CLOSE_FWD : MUX_C_OPEN_FWD);
buffer_put_int(&m, muxclient_request_id);
buffer_put_int(&m, ftype);
if (fwd->listen_path != NULL) {
buffer_put_cstring(&m, fwd->listen_path);
} else {
buffer_put_cstring(&m,
fwd->listen_host == NULL ? "" :
(*fwd->listen_host == '\0' ? "*" : fwd->listen_host));
}
buffer_put_int(&m, fwd->listen_port);
if (fwd->connect_path != NULL) {
buffer_put_cstring(&m, fwd->connect_path);
} else {
buffer_put_cstring(&m,
fwd->connect_host == NULL ? "" : fwd->connect_host);
}
buffer_put_int(&m, fwd->connect_port);
if (mux_client_write_packet(fd, &m) != 0)
fatal("%s: write packet: %s", __func__, strerror(errno));
buffer_clear(&m);
/* Read their reply */
if (mux_client_read_packet(fd, &m) != 0) {
buffer_free(&m);
return -1;
}
type = buffer_get_int(&m);
if ((rid = buffer_get_int(&m)) != muxclient_request_id)
fatal("%s: out of sequence reply: my id %u theirs %u",
__func__, muxclient_request_id, rid);
switch (type) {
case MUX_S_OK:
break;
case MUX_S_REMOTE_PORT:
if (cancel_flag)
fatal("%s: got MUX_S_REMOTE_PORT for cancel", __func__);
fwd->allocated_port = buffer_get_int(&m);
verbose("Allocated port %u for remote forward to %s:%d",
fwd->allocated_port,
fwd->connect_host ? fwd->connect_host : "",
fwd->connect_port);
if (muxclient_command == SSHMUX_COMMAND_FORWARD)
fprintf(stdout, "%i\n", fwd->allocated_port);
break;
case MUX_S_PERMISSION_DENIED:
e = buffer_get_string(&m, NULL);
buffer_free(&m);
error("Master refused forwarding request: %s", e);
return -1;
case MUX_S_FAILURE:
e = buffer_get_string(&m, NULL);
buffer_free(&m);
error("%s: forwarding request failed: %s", __func__, e);
return -1;
default:
fatal("%s: unexpected response from master 0x%08x",
__func__, type);
}
buffer_free(&m);
muxclient_request_id++;
return 0;
}
| null | 0 | mux_client_forward(int fd, int cancel_flag, u_int ftype, struct Forward *fwd)
{
Buffer m;
char *e, *fwd_desc;
u_int type, rid;
fwd_desc = format_forward(ftype, fwd);
debug("Requesting %s %s",
cancel_flag ? "cancellation of" : "forwarding of", fwd_desc);
free(fwd_desc);
buffer_init(&m);
buffer_put_int(&m, cancel_flag ? MUX_C_CLOSE_FWD : MUX_C_OPEN_FWD);
buffer_put_int(&m, muxclient_request_id);
buffer_put_int(&m, ftype);
if (fwd->listen_path != NULL) {
buffer_put_cstring(&m, fwd->listen_path);
} else {
buffer_put_cstring(&m,
fwd->listen_host == NULL ? "" :
(*fwd->listen_host == '\0' ? "*" : fwd->listen_host));
}
buffer_put_int(&m, fwd->listen_port);
if (fwd->connect_path != NULL) {
buffer_put_cstring(&m, fwd->connect_path);
} else {
buffer_put_cstring(&m,
fwd->connect_host == NULL ? "" : fwd->connect_host);
}
buffer_put_int(&m, fwd->connect_port);
if (mux_client_write_packet(fd, &m) != 0)
fatal("%s: write packet: %s", __func__, strerror(errno));
buffer_clear(&m);
/* Read their reply */
if (mux_client_read_packet(fd, &m) != 0) {
buffer_free(&m);
return -1;
}
type = buffer_get_int(&m);
if ((rid = buffer_get_int(&m)) != muxclient_request_id)
fatal("%s: out of sequence reply: my id %u theirs %u",
__func__, muxclient_request_id, rid);
switch (type) {
case MUX_S_OK:
break;
case MUX_S_REMOTE_PORT:
if (cancel_flag)
fatal("%s: got MUX_S_REMOTE_PORT for cancel", __func__);
fwd->allocated_port = buffer_get_int(&m);
verbose("Allocated port %u for remote forward to %s:%d",
fwd->allocated_port,
fwd->connect_host ? fwd->connect_host : "",
fwd->connect_port);
if (muxclient_command == SSHMUX_COMMAND_FORWARD)
fprintf(stdout, "%i\n", fwd->allocated_port);
break;
case MUX_S_PERMISSION_DENIED:
e = buffer_get_string(&m, NULL);
buffer_free(&m);
error("Master refused forwarding request: %s", e);
return -1;
case MUX_S_FAILURE:
e = buffer_get_string(&m, NULL);
buffer_free(&m);
error("%s: forwarding request failed: %s", __func__, e);
return -1;
default:
fatal("%s: unexpected response from master 0x%08x",
__func__, type);
}
buffer_free(&m);
muxclient_request_id++;
return 0;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,464 | mux_client_forwards(int fd, int cancel_flag)
{
int i, ret = 0;
debug3("%s: %s forwardings: %d local, %d remote", __func__,
cancel_flag ? "cancel" : "request",
options.num_local_forwards, options.num_remote_forwards);
/* XXX ExitOnForwardingFailure */
for (i = 0; i < options.num_local_forwards; i++) {
if (mux_client_forward(fd, cancel_flag,
options.local_forwards[i].connect_port == 0 ?
MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
options.local_forwards + i) != 0)
ret = -1;
}
for (i = 0; i < options.num_remote_forwards; i++) {
if (mux_client_forward(fd, cancel_flag, MUX_FWD_REMOTE,
options.remote_forwards + i) != 0)
ret = -1;
}
return ret;
}
| null | 0 | mux_client_forwards(int fd, int cancel_flag)
{
int i, ret = 0;
debug3("%s: %s forwardings: %d local, %d remote", __func__,
cancel_flag ? "cancel" : "request",
options.num_local_forwards, options.num_remote_forwards);
/* XXX ExitOnForwardingFailure */
for (i = 0; i < options.num_local_forwards; i++) {
if (mux_client_forward(fd, cancel_flag,
options.local_forwards[i].connect_port == 0 ?
MUX_FWD_DYNAMIC : MUX_FWD_LOCAL,
options.local_forwards + i) != 0)
ret = -1;
}
for (i = 0; i < options.num_remote_forwards; i++) {
if (mux_client_forward(fd, cancel_flag, MUX_FWD_REMOTE,
options.remote_forwards + i) != 0)
ret = -1;
}
return ret;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,465 | mux_client_hello_exchange(int fd)
{
Buffer m;
u_int type, ver;
buffer_init(&m);
buffer_put_int(&m, MUX_MSG_HELLO);
buffer_put_int(&m, SSHMUX_VER);
/* no extensions */
if (mux_client_write_packet(fd, &m) != 0)
fatal("%s: write packet: %s", __func__, strerror(errno));
buffer_clear(&m);
/* Read their HELLO */
if (mux_client_read_packet(fd, &m) != 0) {
buffer_free(&m);
return -1;
}
type = buffer_get_int(&m);
if (type != MUX_MSG_HELLO)
fatal("%s: expected HELLO (%u) received %u",
__func__, MUX_MSG_HELLO, type);
ver = buffer_get_int(&m);
if (ver != SSHMUX_VER)
fatal("Unsupported multiplexing protocol version %d "
"(expected %d)", ver, SSHMUX_VER);
debug2("%s: master version %u", __func__, ver);
/* No extensions are presently defined */
while (buffer_len(&m) > 0) {
char *name = buffer_get_string(&m, NULL);
char *value = buffer_get_string(&m, NULL);
debug2("Unrecognised master extension \"%s\"", name);
free(name);
free(value);
}
buffer_free(&m);
return 0;
}
| null | 0 | mux_client_hello_exchange(int fd)
{
Buffer m;
u_int type, ver;
buffer_init(&m);
buffer_put_int(&m, MUX_MSG_HELLO);
buffer_put_int(&m, SSHMUX_VER);
/* no extensions */
if (mux_client_write_packet(fd, &m) != 0)
fatal("%s: write packet: %s", __func__, strerror(errno));
buffer_clear(&m);
/* Read their HELLO */
if (mux_client_read_packet(fd, &m) != 0) {
buffer_free(&m);
return -1;
}
type = buffer_get_int(&m);
if (type != MUX_MSG_HELLO)
fatal("%s: expected HELLO (%u) received %u",
__func__, MUX_MSG_HELLO, type);
ver = buffer_get_int(&m);
if (ver != SSHMUX_VER)
fatal("Unsupported multiplexing protocol version %d "
"(expected %d)", ver, SSHMUX_VER);
debug2("%s: master version %u", __func__, ver);
/* No extensions are presently defined */
while (buffer_len(&m) > 0) {
char *name = buffer_get_string(&m, NULL);
char *value = buffer_get_string(&m, NULL);
debug2("Unrecognised master extension \"%s\"", name);
free(name);
free(value);
}
buffer_free(&m);
return 0;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,466 | mux_client_read_packet(int fd, Buffer *m)
{
Buffer queue;
u_int need, have;
const u_char *ptr;
int oerrno;
buffer_init(&queue);
if (mux_client_read(fd, &queue, 4) != 0) {
if ((oerrno = errno) == EPIPE)
debug3("%s: read header failed: %s", __func__,
strerror(errno));
buffer_free(&queue);
errno = oerrno;
return -1;
}
need = get_u32(buffer_ptr(&queue));
if (mux_client_read(fd, &queue, need) != 0) {
oerrno = errno;
debug3("%s: read body failed: %s", __func__, strerror(errno));
buffer_free(&queue);
errno = oerrno;
return -1;
}
ptr = buffer_get_string_ptr(&queue, &have);
buffer_append(m, ptr, have);
buffer_free(&queue);
return 0;
}
| null | 0 | mux_client_read_packet(int fd, Buffer *m)
{
Buffer queue;
u_int need, have;
const u_char *ptr;
int oerrno;
buffer_init(&queue);
if (mux_client_read(fd, &queue, 4) != 0) {
if ((oerrno = errno) == EPIPE)
debug3("%s: read header failed: %s", __func__,
strerror(errno));
buffer_free(&queue);
errno = oerrno;
return -1;
}
need = get_u32(buffer_ptr(&queue));
if (mux_client_read(fd, &queue, need) != 0) {
oerrno = errno;
debug3("%s: read body failed: %s", __func__, strerror(errno));
buffer_free(&queue);
errno = oerrno;
return -1;
}
ptr = buffer_get_string_ptr(&queue, &have);
buffer_append(m, ptr, have);
buffer_free(&queue);
return 0;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,467 | mux_client_request_alive(int fd)
{
Buffer m;
char *e;
u_int pid, type, rid;
debug3("%s: entering", __func__);
buffer_init(&m);
buffer_put_int(&m, MUX_C_ALIVE_CHECK);
buffer_put_int(&m, muxclient_request_id);
if (mux_client_write_packet(fd, &m) != 0)
fatal("%s: write packet: %s", __func__, strerror(errno));
buffer_clear(&m);
/* Read their reply */
if (mux_client_read_packet(fd, &m) != 0) {
buffer_free(&m);
return 0;
}
type = buffer_get_int(&m);
if (type != MUX_S_ALIVE) {
e = buffer_get_string(&m, NULL);
fatal("%s: master returned error: %s", __func__, e);
}
if ((rid = buffer_get_int(&m)) != muxclient_request_id)
fatal("%s: out of sequence reply: my id %u theirs %u",
__func__, muxclient_request_id, rid);
pid = buffer_get_int(&m);
buffer_free(&m);
debug3("%s: done pid = %u", __func__, pid);
muxclient_request_id++;
return pid;
}
| null | 0 | mux_client_request_alive(int fd)
{
Buffer m;
char *e;
u_int pid, type, rid;
debug3("%s: entering", __func__);
buffer_init(&m);
buffer_put_int(&m, MUX_C_ALIVE_CHECK);
buffer_put_int(&m, muxclient_request_id);
if (mux_client_write_packet(fd, &m) != 0)
fatal("%s: write packet: %s", __func__, strerror(errno));
buffer_clear(&m);
/* Read their reply */
if (mux_client_read_packet(fd, &m) != 0) {
buffer_free(&m);
return 0;
}
type = buffer_get_int(&m);
if (type != MUX_S_ALIVE) {
e = buffer_get_string(&m, NULL);
fatal("%s: master returned error: %s", __func__, e);
}
if ((rid = buffer_get_int(&m)) != muxclient_request_id)
fatal("%s: out of sequence reply: my id %u theirs %u",
__func__, muxclient_request_id, rid);
pid = buffer_get_int(&m);
buffer_free(&m);
debug3("%s: done pid = %u", __func__, pid);
muxclient_request_id++;
return pid;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,468 | mux_client_request_session(int fd)
{
Buffer m;
char *e, *term;
u_int i, rid, sid, esid, exitval, type, exitval_seen;
extern char **environ;
int devnull, rawmode;
debug3("%s: entering", __func__);
if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
error("%s: master alive request failed", __func__);
return -1;
}
signal(SIGPIPE, SIG_IGN);
if (stdin_null_flag) {
if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
fatal("open(/dev/null): %s", strerror(errno));
if (dup2(devnull, STDIN_FILENO) == -1)
fatal("dup2: %s", strerror(errno));
if (devnull > STDERR_FILENO)
close(devnull);
}
term = getenv("TERM");
buffer_init(&m);
buffer_put_int(&m, MUX_C_NEW_SESSION);
buffer_put_int(&m, muxclient_request_id);
buffer_put_cstring(&m, ""); /* reserved */
buffer_put_int(&m, tty_flag);
buffer_put_int(&m, options.forward_x11);
buffer_put_int(&m, options.forward_agent);
buffer_put_int(&m, subsystem_flag);
buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
0xffffffff : (u_int)options.escape_char);
buffer_put_cstring(&m, term == NULL ? "" : term);
buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
if (options.num_send_env > 0 && environ != NULL) {
/* Pass environment */
for (i = 0; environ[i] != NULL; i++) {
if (env_permitted(environ[i])) {
buffer_put_cstring(&m, environ[i]);
}
}
}
if (mux_client_write_packet(fd, &m) != 0)
fatal("%s: write packet: %s", __func__, strerror(errno));
/* Send the stdio file descriptors */
if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
mm_send_fd(fd, STDOUT_FILENO) == -1 ||
mm_send_fd(fd, STDERR_FILENO) == -1)
fatal("%s: send fds failed", __func__);
debug3("%s: session request sent", __func__);
/* Read their reply */
buffer_clear(&m);
if (mux_client_read_packet(fd, &m) != 0) {
error("%s: read from master failed: %s",
__func__, strerror(errno));
buffer_free(&m);
return -1;
}
type = buffer_get_int(&m);
if ((rid = buffer_get_int(&m)) != muxclient_request_id)
fatal("%s: out of sequence reply: my id %u theirs %u",
__func__, muxclient_request_id, rid);
switch (type) {
case MUX_S_SESSION_OPENED:
sid = buffer_get_int(&m);
debug("%s: master session id: %u", __func__, sid);
break;
case MUX_S_PERMISSION_DENIED:
e = buffer_get_string(&m, NULL);
buffer_free(&m);
error("Master refused session request: %s", e);
return -1;
case MUX_S_FAILURE:
e = buffer_get_string(&m, NULL);
buffer_free(&m);
error("%s: session request failed: %s", __func__, e);
return -1;
default:
buffer_free(&m);
error("%s: unexpected response from master 0x%08x",
__func__, type);
return -1;
}
muxclient_request_id++;
if (pledge("stdio proc tty", NULL) == -1)
fatal("%s pledge(): %s", __func__, strerror(errno));
platform_pledge_mux();
signal(SIGHUP, control_client_sighandler);
signal(SIGINT, control_client_sighandler);
signal(SIGTERM, control_client_sighandler);
signal(SIGWINCH, control_client_sigrelay);
rawmode = tty_flag;
if (tty_flag)
enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
/*
* Stick around until the controlee closes the client_fd.
* Before it does, it is expected to write an exit message.
* This process must read the value and wait for the closure of
* the client_fd; if this one closes early, the multiplex master will
* terminate early too (possibly losing data).
*/
for (exitval = 255, exitval_seen = 0;;) {
buffer_clear(&m);
if (mux_client_read_packet(fd, &m) != 0)
break;
type = buffer_get_int(&m);
switch (type) {
case MUX_S_TTY_ALLOC_FAIL:
if ((esid = buffer_get_int(&m)) != sid)
fatal("%s: tty alloc fail on unknown session: "
"my id %u theirs %u",
__func__, sid, esid);
leave_raw_mode(options.request_tty ==
REQUEST_TTY_FORCE);
rawmode = 0;
continue;
case MUX_S_EXIT_MESSAGE:
if ((esid = buffer_get_int(&m)) != sid)
fatal("%s: exit on unknown session: "
"my id %u theirs %u",
__func__, sid, esid);
if (exitval_seen)
fatal("%s: exitval sent twice", __func__);
exitval = buffer_get_int(&m);
exitval_seen = 1;
continue;
default:
e = buffer_get_string(&m, NULL);
fatal("%s: master returned error: %s", __func__, e);
}
}
close(fd);
if (rawmode)
leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
if (muxclient_terminate) {
debug2("Exiting on signal %d", muxclient_terminate);
exitval = 255;
} else if (!exitval_seen) {
debug2("Control master terminated unexpectedly");
exitval = 255;
} else
debug2("Received exit status from master %d", exitval);
if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
fprintf(stderr, "Shared connection to %s closed.\r\n", host);
exit(exitval);
}
| null | 0 | mux_client_request_session(int fd)
{
Buffer m;
char *e, *term;
u_int i, rid, sid, esid, exitval, type, exitval_seen;
extern char **environ;
int devnull, rawmode;
debug3("%s: entering", __func__);
if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
error("%s: master alive request failed", __func__);
return -1;
}
signal(SIGPIPE, SIG_IGN);
if (stdin_null_flag) {
if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
fatal("open(/dev/null): %s", strerror(errno));
if (dup2(devnull, STDIN_FILENO) == -1)
fatal("dup2: %s", strerror(errno));
if (devnull > STDERR_FILENO)
close(devnull);
}
term = getenv("TERM");
buffer_init(&m);
buffer_put_int(&m, MUX_C_NEW_SESSION);
buffer_put_int(&m, muxclient_request_id);
buffer_put_cstring(&m, ""); /* reserved */
buffer_put_int(&m, tty_flag);
buffer_put_int(&m, options.forward_x11);
buffer_put_int(&m, options.forward_agent);
buffer_put_int(&m, subsystem_flag);
buffer_put_int(&m, options.escape_char == SSH_ESCAPECHAR_NONE ?
0xffffffff : (u_int)options.escape_char);
buffer_put_cstring(&m, term == NULL ? "" : term);
buffer_put_string(&m, buffer_ptr(&command), buffer_len(&command));
if (options.num_send_env > 0 && environ != NULL) {
/* Pass environment */
for (i = 0; environ[i] != NULL; i++) {
if (env_permitted(environ[i])) {
buffer_put_cstring(&m, environ[i]);
}
}
}
if (mux_client_write_packet(fd, &m) != 0)
fatal("%s: write packet: %s", __func__, strerror(errno));
/* Send the stdio file descriptors */
if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
mm_send_fd(fd, STDOUT_FILENO) == -1 ||
mm_send_fd(fd, STDERR_FILENO) == -1)
fatal("%s: send fds failed", __func__);
debug3("%s: session request sent", __func__);
/* Read their reply */
buffer_clear(&m);
if (mux_client_read_packet(fd, &m) != 0) {
error("%s: read from master failed: %s",
__func__, strerror(errno));
buffer_free(&m);
return -1;
}
type = buffer_get_int(&m);
if ((rid = buffer_get_int(&m)) != muxclient_request_id)
fatal("%s: out of sequence reply: my id %u theirs %u",
__func__, muxclient_request_id, rid);
switch (type) {
case MUX_S_SESSION_OPENED:
sid = buffer_get_int(&m);
debug("%s: master session id: %u", __func__, sid);
break;
case MUX_S_PERMISSION_DENIED:
e = buffer_get_string(&m, NULL);
buffer_free(&m);
error("Master refused session request: %s", e);
return -1;
case MUX_S_FAILURE:
e = buffer_get_string(&m, NULL);
buffer_free(&m);
error("%s: session request failed: %s", __func__, e);
return -1;
default:
buffer_free(&m);
error("%s: unexpected response from master 0x%08x",
__func__, type);
return -1;
}
muxclient_request_id++;
if (pledge("stdio proc tty", NULL) == -1)
fatal("%s pledge(): %s", __func__, strerror(errno));
platform_pledge_mux();
signal(SIGHUP, control_client_sighandler);
signal(SIGINT, control_client_sighandler);
signal(SIGTERM, control_client_sighandler);
signal(SIGWINCH, control_client_sigrelay);
rawmode = tty_flag;
if (tty_flag)
enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
/*
* Stick around until the controlee closes the client_fd.
* Before it does, it is expected to write an exit message.
* This process must read the value and wait for the closure of
* the client_fd; if this one closes early, the multiplex master will
* terminate early too (possibly losing data).
*/
for (exitval = 255, exitval_seen = 0;;) {
buffer_clear(&m);
if (mux_client_read_packet(fd, &m) != 0)
break;
type = buffer_get_int(&m);
switch (type) {
case MUX_S_TTY_ALLOC_FAIL:
if ((esid = buffer_get_int(&m)) != sid)
fatal("%s: tty alloc fail on unknown session: "
"my id %u theirs %u",
__func__, sid, esid);
leave_raw_mode(options.request_tty ==
REQUEST_TTY_FORCE);
rawmode = 0;
continue;
case MUX_S_EXIT_MESSAGE:
if ((esid = buffer_get_int(&m)) != sid)
fatal("%s: exit on unknown session: "
"my id %u theirs %u",
__func__, sid, esid);
if (exitval_seen)
fatal("%s: exitval sent twice", __func__);
exitval = buffer_get_int(&m);
exitval_seen = 1;
continue;
default:
e = buffer_get_string(&m, NULL);
fatal("%s: master returned error: %s", __func__, e);
}
}
close(fd);
if (rawmode)
leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
if (muxclient_terminate) {
debug2("Exiting on signal %d", muxclient_terminate);
exitval = 255;
} else if (!exitval_seen) {
debug2("Control master terminated unexpectedly");
exitval = 255;
} else
debug2("Received exit status from master %d", exitval);
if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
fprintf(stderr, "Shared connection to %s closed.\r\n", host);
exit(exitval);
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,469 | mux_client_request_stdio_fwd(int fd)
{
Buffer m;
char *e;
u_int type, rid, sid;
int devnull;
debug3("%s: entering", __func__);
if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
error("%s: master alive request failed", __func__);
return -1;
}
signal(SIGPIPE, SIG_IGN);
if (stdin_null_flag) {
if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
fatal("open(/dev/null): %s", strerror(errno));
if (dup2(devnull, STDIN_FILENO) == -1)
fatal("dup2: %s", strerror(errno));
if (devnull > STDERR_FILENO)
close(devnull);
}
buffer_init(&m);
buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
buffer_put_int(&m, muxclient_request_id);
buffer_put_cstring(&m, ""); /* reserved */
buffer_put_cstring(&m, stdio_forward_host);
buffer_put_int(&m, stdio_forward_port);
if (mux_client_write_packet(fd, &m) != 0)
fatal("%s: write packet: %s", __func__, strerror(errno));
/* Send the stdio file descriptors */
if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
mm_send_fd(fd, STDOUT_FILENO) == -1)
fatal("%s: send fds failed", __func__);
if (pledge("stdio proc tty", NULL) == -1)
fatal("%s pledge(): %s", __func__, strerror(errno));
platform_pledge_mux();
debug3("%s: stdio forward request sent", __func__);
/* Read their reply */
buffer_clear(&m);
if (mux_client_read_packet(fd, &m) != 0) {
error("%s: read from master failed: %s",
__func__, strerror(errno));
buffer_free(&m);
return -1;
}
type = buffer_get_int(&m);
if ((rid = buffer_get_int(&m)) != muxclient_request_id)
fatal("%s: out of sequence reply: my id %u theirs %u",
__func__, muxclient_request_id, rid);
switch (type) {
case MUX_S_SESSION_OPENED:
sid = buffer_get_int(&m);
debug("%s: master session id: %u", __func__, sid);
break;
case MUX_S_PERMISSION_DENIED:
e = buffer_get_string(&m, NULL);
buffer_free(&m);
fatal("Master refused stdio forwarding request: %s", e);
case MUX_S_FAILURE:
e = buffer_get_string(&m, NULL);
buffer_free(&m);
fatal("Stdio forwarding request failed: %s", e);
default:
buffer_free(&m);
error("%s: unexpected response from master 0x%08x",
__func__, type);
return -1;
}
muxclient_request_id++;
signal(SIGHUP, control_client_sighandler);
signal(SIGINT, control_client_sighandler);
signal(SIGTERM, control_client_sighandler);
signal(SIGWINCH, control_client_sigrelay);
/*
* Stick around until the controlee closes the client_fd.
*/
buffer_clear(&m);
if (mux_client_read_packet(fd, &m) != 0) {
if (errno == EPIPE ||
(errno == EINTR && muxclient_terminate != 0))
return 0;
fatal("%s: mux_client_read_packet: %s",
__func__, strerror(errno));
}
fatal("%s: master returned unexpected message %u", __func__, type);
}
| null | 0 | mux_client_request_stdio_fwd(int fd)
{
Buffer m;
char *e;
u_int type, rid, sid;
int devnull;
debug3("%s: entering", __func__);
if ((muxserver_pid = mux_client_request_alive(fd)) == 0) {
error("%s: master alive request failed", __func__);
return -1;
}
signal(SIGPIPE, SIG_IGN);
if (stdin_null_flag) {
if ((devnull = open(_PATH_DEVNULL, O_RDONLY)) == -1)
fatal("open(/dev/null): %s", strerror(errno));
if (dup2(devnull, STDIN_FILENO) == -1)
fatal("dup2: %s", strerror(errno));
if (devnull > STDERR_FILENO)
close(devnull);
}
buffer_init(&m);
buffer_put_int(&m, MUX_C_NEW_STDIO_FWD);
buffer_put_int(&m, muxclient_request_id);
buffer_put_cstring(&m, ""); /* reserved */
buffer_put_cstring(&m, stdio_forward_host);
buffer_put_int(&m, stdio_forward_port);
if (mux_client_write_packet(fd, &m) != 0)
fatal("%s: write packet: %s", __func__, strerror(errno));
/* Send the stdio file descriptors */
if (mm_send_fd(fd, STDIN_FILENO) == -1 ||
mm_send_fd(fd, STDOUT_FILENO) == -1)
fatal("%s: send fds failed", __func__);
if (pledge("stdio proc tty", NULL) == -1)
fatal("%s pledge(): %s", __func__, strerror(errno));
platform_pledge_mux();
debug3("%s: stdio forward request sent", __func__);
/* Read their reply */
buffer_clear(&m);
if (mux_client_read_packet(fd, &m) != 0) {
error("%s: read from master failed: %s",
__func__, strerror(errno));
buffer_free(&m);
return -1;
}
type = buffer_get_int(&m);
if ((rid = buffer_get_int(&m)) != muxclient_request_id)
fatal("%s: out of sequence reply: my id %u theirs %u",
__func__, muxclient_request_id, rid);
switch (type) {
case MUX_S_SESSION_OPENED:
sid = buffer_get_int(&m);
debug("%s: master session id: %u", __func__, sid);
break;
case MUX_S_PERMISSION_DENIED:
e = buffer_get_string(&m, NULL);
buffer_free(&m);
fatal("Master refused stdio forwarding request: %s", e);
case MUX_S_FAILURE:
e = buffer_get_string(&m, NULL);
buffer_free(&m);
fatal("Stdio forwarding request failed: %s", e);
default:
buffer_free(&m);
error("%s: unexpected response from master 0x%08x",
__func__, type);
return -1;
}
muxclient_request_id++;
signal(SIGHUP, control_client_sighandler);
signal(SIGINT, control_client_sighandler);
signal(SIGTERM, control_client_sighandler);
signal(SIGWINCH, control_client_sigrelay);
/*
* Stick around until the controlee closes the client_fd.
*/
buffer_clear(&m);
if (mux_client_read_packet(fd, &m) != 0) {
if (errno == EPIPE ||
(errno == EINTR && muxclient_terminate != 0))
return 0;
fatal("%s: mux_client_read_packet: %s",
__func__, strerror(errno));
}
fatal("%s: master returned unexpected message %u", __func__, type);
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,470 | mux_client_request_stop_listening(int fd)
{
Buffer m;
char *e;
u_int type, rid;
debug3("%s: entering", __func__);
buffer_init(&m);
buffer_put_int(&m, MUX_C_STOP_LISTENING);
buffer_put_int(&m, muxclient_request_id);
if (mux_client_write_packet(fd, &m) != 0)
fatal("%s: write packet: %s", __func__, strerror(errno));
buffer_clear(&m);
/* Read their reply */
if (mux_client_read_packet(fd, &m) != 0)
fatal("%s: read from master failed: %s",
__func__, strerror(errno));
type = buffer_get_int(&m);
if ((rid = buffer_get_int(&m)) != muxclient_request_id)
fatal("%s: out of sequence reply: my id %u theirs %u",
__func__, muxclient_request_id, rid);
switch (type) {
case MUX_S_OK:
break;
case MUX_S_PERMISSION_DENIED:
e = buffer_get_string(&m, NULL);
fatal("Master refused stop listening request: %s", e);
case MUX_S_FAILURE:
e = buffer_get_string(&m, NULL);
fatal("%s: stop listening request failed: %s", __func__, e);
default:
fatal("%s: unexpected response from master 0x%08x",
__func__, type);
}
buffer_free(&m);
muxclient_request_id++;
}
| null | 0 | mux_client_request_stop_listening(int fd)
{
Buffer m;
char *e;
u_int type, rid;
debug3("%s: entering", __func__);
buffer_init(&m);
buffer_put_int(&m, MUX_C_STOP_LISTENING);
buffer_put_int(&m, muxclient_request_id);
if (mux_client_write_packet(fd, &m) != 0)
fatal("%s: write packet: %s", __func__, strerror(errno));
buffer_clear(&m);
/* Read their reply */
if (mux_client_read_packet(fd, &m) != 0)
fatal("%s: read from master failed: %s",
__func__, strerror(errno));
type = buffer_get_int(&m);
if ((rid = buffer_get_int(&m)) != muxclient_request_id)
fatal("%s: out of sequence reply: my id %u theirs %u",
__func__, muxclient_request_id, rid);
switch (type) {
case MUX_S_OK:
break;
case MUX_S_PERMISSION_DENIED:
e = buffer_get_string(&m, NULL);
fatal("Master refused stop listening request: %s", e);
case MUX_S_FAILURE:
e = buffer_get_string(&m, NULL);
fatal("%s: stop listening request failed: %s", __func__, e);
default:
fatal("%s: unexpected response from master 0x%08x",
__func__, type);
}
buffer_free(&m);
muxclient_request_id++;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,471 | mux_client_write_packet(int fd, Buffer *m)
{
Buffer queue;
u_int have, need;
int oerrno, len;
u_char *ptr;
struct pollfd pfd;
pfd.fd = fd;
pfd.events = POLLOUT;
buffer_init(&queue);
buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
need = buffer_len(&queue);
ptr = buffer_ptr(&queue);
for (have = 0; have < need; ) {
if (muxclient_terminate) {
buffer_free(&queue);
errno = EINTR;
return -1;
}
len = write(fd, ptr + have, need - have);
if (len < 0) {
switch (errno) {
#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
case EWOULDBLOCK:
#endif
case EAGAIN:
(void)poll(&pfd, 1, -1);
/* FALLTHROUGH */
case EINTR:
continue;
default:
oerrno = errno;
buffer_free(&queue);
errno = oerrno;
return -1;
}
}
if (len == 0) {
buffer_free(&queue);
errno = EPIPE;
return -1;
}
have += (u_int)len;
}
buffer_free(&queue);
return 0;
}
| null | 0 | mux_client_write_packet(int fd, Buffer *m)
{
Buffer queue;
u_int have, need;
int oerrno, len;
u_char *ptr;
struct pollfd pfd;
pfd.fd = fd;
pfd.events = POLLOUT;
buffer_init(&queue);
buffer_put_string(&queue, buffer_ptr(m), buffer_len(m));
need = buffer_len(&queue);
ptr = buffer_ptr(&queue);
for (have = 0; have < need; ) {
if (muxclient_terminate) {
buffer_free(&queue);
errno = EINTR;
return -1;
}
len = write(fd, ptr + have, need - have);
if (len < 0) {
switch (errno) {
#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
case EWOULDBLOCK:
#endif
case EAGAIN:
(void)poll(&pfd, 1, -1);
/* FALLTHROUGH */
case EINTR:
continue;
default:
oerrno = errno;
buffer_free(&queue);
errno = oerrno;
return -1;
}
}
if (len == 0) {
buffer_free(&queue);
errno = EPIPE;
return -1;
}
have += (u_int)len;
}
buffer_free(&queue);
return 0;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,472 | mux_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
{
struct mux_channel_confirm_ctx *fctx = ctxt;
char *failmsg = NULL;
struct Forward *rfwd;
Channel *c;
Buffer out;
if ((c = channel_by_id(fctx->cid)) == NULL) {
/* no channel for reply */
error("%s: unknown channel", __func__);
return;
}
buffer_init(&out);
if (fctx->fid >= options.num_remote_forwards ||
(options.remote_forwards[fctx->fid].connect_path == NULL &&
options.remote_forwards[fctx->fid].connect_host == NULL)) {
xasprintf(&failmsg, "unknown forwarding id %d", fctx->fid);
goto fail;
}
rfwd = &options.remote_forwards[fctx->fid];
debug("%s: %s for: listen %d, connect %s:%d", __func__,
type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
rfwd->connect_host, rfwd->connect_port);
if (type == SSH2_MSG_REQUEST_SUCCESS) {
if (rfwd->listen_port == 0) {
rfwd->allocated_port = packet_get_int();
debug("Allocated port %u for mux remote forward"
" to %s:%d", rfwd->allocated_port,
rfwd->connect_host, rfwd->connect_port);
buffer_put_int(&out, MUX_S_REMOTE_PORT);
buffer_put_int(&out, fctx->rid);
buffer_put_int(&out, rfwd->allocated_port);
channel_update_permitted_opens(rfwd->handle,
rfwd->allocated_port);
} else {
buffer_put_int(&out, MUX_S_OK);
buffer_put_int(&out, fctx->rid);
}
goto out;
} else {
if (rfwd->listen_port == 0)
channel_update_permitted_opens(rfwd->handle, -1);
if (rfwd->listen_path != NULL)
xasprintf(&failmsg, "remote port forwarding failed for "
"listen path %s", rfwd->listen_path);
else
xasprintf(&failmsg, "remote port forwarding failed for "
"listen port %d", rfwd->listen_port);
debug2("%s: clearing registered forwarding for listen %d, "
"connect %s:%d", __func__, rfwd->listen_port,
rfwd->connect_path ? rfwd->connect_path :
rfwd->connect_host, rfwd->connect_port);
free(rfwd->listen_host);
free(rfwd->listen_path);
free(rfwd->connect_host);
free(rfwd->connect_path);
memset(rfwd, 0, sizeof(*rfwd));
}
fail:
error("%s: %s", __func__, failmsg);
buffer_put_int(&out, MUX_S_FAILURE);
buffer_put_int(&out, fctx->rid);
buffer_put_cstring(&out, failmsg);
free(failmsg);
out:
buffer_put_string(&c->output, buffer_ptr(&out), buffer_len(&out));
buffer_free(&out);
if (c->mux_pause <= 0)
fatal("%s: mux_pause %d", __func__, c->mux_pause);
c->mux_pause = 0; /* start processing messages again */
}
| null | 0 | mux_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
{
struct mux_channel_confirm_ctx *fctx = ctxt;
char *failmsg = NULL;
struct Forward *rfwd;
Channel *c;
Buffer out;
if ((c = channel_by_id(fctx->cid)) == NULL) {
/* no channel for reply */
error("%s: unknown channel", __func__);
return;
}
buffer_init(&out);
if (fctx->fid >= options.num_remote_forwards ||
(options.remote_forwards[fctx->fid].connect_path == NULL &&
options.remote_forwards[fctx->fid].connect_host == NULL)) {
xasprintf(&failmsg, "unknown forwarding id %d", fctx->fid);
goto fail;
}
rfwd = &options.remote_forwards[fctx->fid];
debug("%s: %s for: listen %d, connect %s:%d", __func__,
type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
rfwd->connect_host, rfwd->connect_port);
if (type == SSH2_MSG_REQUEST_SUCCESS) {
if (rfwd->listen_port == 0) {
rfwd->allocated_port = packet_get_int();
debug("Allocated port %u for mux remote forward"
" to %s:%d", rfwd->allocated_port,
rfwd->connect_host, rfwd->connect_port);
buffer_put_int(&out, MUX_S_REMOTE_PORT);
buffer_put_int(&out, fctx->rid);
buffer_put_int(&out, rfwd->allocated_port);
channel_update_permitted_opens(rfwd->handle,
rfwd->allocated_port);
} else {
buffer_put_int(&out, MUX_S_OK);
buffer_put_int(&out, fctx->rid);
}
goto out;
} else {
if (rfwd->listen_port == 0)
channel_update_permitted_opens(rfwd->handle, -1);
if (rfwd->listen_path != NULL)
xasprintf(&failmsg, "remote port forwarding failed for "
"listen path %s", rfwd->listen_path);
else
xasprintf(&failmsg, "remote port forwarding failed for "
"listen port %d", rfwd->listen_port);
debug2("%s: clearing registered forwarding for listen %d, "
"connect %s:%d", __func__, rfwd->listen_port,
rfwd->connect_path ? rfwd->connect_path :
rfwd->connect_host, rfwd->connect_port);
free(rfwd->listen_host);
free(rfwd->listen_path);
free(rfwd->connect_host);
free(rfwd->connect_path);
memset(rfwd, 0, sizeof(*rfwd));
}
fail:
error("%s: %s", __func__, failmsg);
buffer_put_int(&out, MUX_S_FAILURE);
buffer_put_int(&out, fctx->rid);
buffer_put_cstring(&out, failmsg);
free(failmsg);
out:
buffer_put_string(&c->output, buffer_ptr(&out), buffer_len(&out));
buffer_free(&out);
if (c->mux_pause <= 0)
fatal("%s: mux_pause %d", __func__, c->mux_pause);
c->mux_pause = 0; /* start processing messages again */
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,473 | mux_exit_message(Channel *c, int exitval)
{
Buffer m;
Channel *mux_chan;
debug3("%s: channel %d: exit message, exitval %d", __func__, c->self,
exitval);
if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
fatal("%s: channel %d missing mux channel %d",
__func__, c->self, c->ctl_chan);
/* Append exit message packet to control socket output queue */
buffer_init(&m);
buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
buffer_put_int(&m, c->self);
buffer_put_int(&m, exitval);
buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
buffer_free(&m);
}
| null | 0 | mux_exit_message(Channel *c, int exitval)
{
Buffer m;
Channel *mux_chan;
debug3("%s: channel %d: exit message, exitval %d", __func__, c->self,
exitval);
if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
fatal("%s: channel %d missing mux channel %d",
__func__, c->self, c->ctl_chan);
/* Append exit message packet to control socket output queue */
buffer_init(&m);
buffer_put_int(&m, MUX_S_EXIT_MESSAGE);
buffer_put_int(&m, c->self);
buffer_put_int(&m, exitval);
buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
buffer_free(&m);
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,474 | mux_master_control_cleanup_cb(int cid, void *unused)
{
Channel *sc, *c = channel_by_id(cid);
debug3("%s: entering for channel %d", __func__, cid);
if (c == NULL)
fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
if (c->remote_id != -1) {
if ((sc = channel_by_id(c->remote_id)) == NULL)
fatal("%s: channel %d missing session channel %d",
__func__, c->self, c->remote_id);
c->remote_id = -1;
sc->ctl_chan = -1;
if (sc->type != SSH_CHANNEL_OPEN &&
sc->type != SSH_CHANNEL_OPENING) {
debug2("%s: channel %d: not open", __func__, sc->self);
chan_mark_dead(sc);
} else {
if (sc->istate == CHAN_INPUT_OPEN)
chan_read_failed(sc);
if (sc->ostate == CHAN_OUTPUT_OPEN)
chan_write_failed(sc);
}
}
channel_cancel_cleanup(c->self);
}
| null | 0 | mux_master_control_cleanup_cb(int cid, void *unused)
{
Channel *sc, *c = channel_by_id(cid);
debug3("%s: entering for channel %d", __func__, cid);
if (c == NULL)
fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
if (c->remote_id != -1) {
if ((sc = channel_by_id(c->remote_id)) == NULL)
fatal("%s: channel %d missing session channel %d",
__func__, c->self, c->remote_id);
c->remote_id = -1;
sc->ctl_chan = -1;
if (sc->type != SSH_CHANNEL_OPEN &&
sc->type != SSH_CHANNEL_OPENING) {
debug2("%s: channel %d: not open", __func__, sc->self);
chan_mark_dead(sc);
} else {
if (sc->istate == CHAN_INPUT_OPEN)
chan_read_failed(sc);
if (sc->ostate == CHAN_OUTPUT_OPEN)
chan_write_failed(sc);
}
}
channel_cancel_cleanup(c->self);
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,475 | mux_master_read_cb(Channel *c)
{
struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
Buffer in, out;
const u_char *ptr;
u_int type, rid, have, i;
int ret = -1;
/* Setup ctx and */
if (c->mux_ctx == NULL) {
state = xcalloc(1, sizeof(*state));
c->mux_ctx = state;
channel_register_cleanup(c->self,
mux_master_control_cleanup_cb, 0);
/* Send hello */
buffer_init(&out);
buffer_put_int(&out, MUX_MSG_HELLO);
buffer_put_int(&out, SSHMUX_VER);
/* no extensions */
buffer_put_string(&c->output, buffer_ptr(&out),
buffer_len(&out));
buffer_free(&out);
debug3("%s: channel %d: hello sent", __func__, c->self);
return 0;
}
buffer_init(&in);
buffer_init(&out);
/* Channel code ensures that we receive whole packets */
if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
malf:
error("%s: malformed message", __func__);
goto out;
}
buffer_append(&in, ptr, have);
if (buffer_get_int_ret(&type, &in) != 0)
goto malf;
debug3("%s: channel %d packet type 0x%08x len %u",
__func__, c->self, type, buffer_len(&in));
if (type == MUX_MSG_HELLO)
rid = 0;
else {
if (!state->hello_rcvd) {
error("%s: expected MUX_MSG_HELLO(0x%08x), "
"received 0x%08x", __func__, MUX_MSG_HELLO, type);
goto out;
}
if (buffer_get_int_ret(&rid, &in) != 0)
goto malf;
}
for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
if (type == mux_master_handlers[i].type) {
ret = mux_master_handlers[i].handler(rid, c, &in, &out);
break;
}
}
if (mux_master_handlers[i].handler == NULL) {
error("%s: unsupported mux message 0x%08x", __func__, type);
buffer_put_int(&out, MUX_S_FAILURE);
buffer_put_int(&out, rid);
buffer_put_cstring(&out, "unsupported request");
ret = 0;
}
/* Enqueue reply packet */
if (buffer_len(&out) != 0) {
buffer_put_string(&c->output, buffer_ptr(&out),
buffer_len(&out));
}
out:
buffer_free(&in);
buffer_free(&out);
return ret;
}
| null | 0 | mux_master_read_cb(Channel *c)
{
struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
Buffer in, out;
const u_char *ptr;
u_int type, rid, have, i;
int ret = -1;
/* Setup ctx and */
if (c->mux_ctx == NULL) {
state = xcalloc(1, sizeof(*state));
c->mux_ctx = state;
channel_register_cleanup(c->self,
mux_master_control_cleanup_cb, 0);
/* Send hello */
buffer_init(&out);
buffer_put_int(&out, MUX_MSG_HELLO);
buffer_put_int(&out, SSHMUX_VER);
/* no extensions */
buffer_put_string(&c->output, buffer_ptr(&out),
buffer_len(&out));
buffer_free(&out);
debug3("%s: channel %d: hello sent", __func__, c->self);
return 0;
}
buffer_init(&in);
buffer_init(&out);
/* Channel code ensures that we receive whole packets */
if ((ptr = buffer_get_string_ptr_ret(&c->input, &have)) == NULL) {
malf:
error("%s: malformed message", __func__);
goto out;
}
buffer_append(&in, ptr, have);
if (buffer_get_int_ret(&type, &in) != 0)
goto malf;
debug3("%s: channel %d packet type 0x%08x len %u",
__func__, c->self, type, buffer_len(&in));
if (type == MUX_MSG_HELLO)
rid = 0;
else {
if (!state->hello_rcvd) {
error("%s: expected MUX_MSG_HELLO(0x%08x), "
"received 0x%08x", __func__, MUX_MSG_HELLO, type);
goto out;
}
if (buffer_get_int_ret(&rid, &in) != 0)
goto malf;
}
for (i = 0; mux_master_handlers[i].handler != NULL; i++) {
if (type == mux_master_handlers[i].type) {
ret = mux_master_handlers[i].handler(rid, c, &in, &out);
break;
}
}
if (mux_master_handlers[i].handler == NULL) {
error("%s: unsupported mux message 0x%08x", __func__, type);
buffer_put_int(&out, MUX_S_FAILURE);
buffer_put_int(&out, rid);
buffer_put_cstring(&out, "unsupported request");
ret = 0;
}
/* Enqueue reply packet */
if (buffer_len(&out) != 0) {
buffer_put_string(&c->output, buffer_ptr(&out),
buffer_len(&out));
}
out:
buffer_free(&in);
buffer_free(&out);
return ret;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,476 | mux_master_session_cleanup_cb(int cid, void *unused)
{
Channel *cc, *c = channel_by_id(cid);
debug3("%s: entering for channel %d", __func__, cid);
if (c == NULL)
fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
if (c->ctl_chan != -1) {
if ((cc = channel_by_id(c->ctl_chan)) == NULL)
fatal("%s: channel %d missing control channel %d",
__func__, c->self, c->ctl_chan);
c->ctl_chan = -1;
cc->remote_id = -1;
chan_rcvd_oclose(cc);
}
channel_cancel_cleanup(c->self);
}
| null | 0 | mux_master_session_cleanup_cb(int cid, void *unused)
{
Channel *cc, *c = channel_by_id(cid);
debug3("%s: entering for channel %d", __func__, cid);
if (c == NULL)
fatal("%s: channel_by_id(%i) == NULL", __func__, cid);
if (c->ctl_chan != -1) {
if ((cc = channel_by_id(c->ctl_chan)) == NULL)
fatal("%s: channel %d missing control channel %d",
__func__, c->self, c->ctl_chan);
c->ctl_chan = -1;
cc->remote_id = -1;
chan_rcvd_oclose(cc);
}
channel_cancel_cleanup(c->self);
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,477 | mux_stdio_confirm(int id, int success, void *arg)
{
struct mux_stdio_confirm_ctx *cctx = arg;
Channel *c, *cc;
Buffer reply;
if (cctx == NULL)
fatal("%s: cctx == NULL", __func__);
if ((c = channel_by_id(id)) == NULL)
fatal("%s: no channel for id %d", __func__, id);
if ((cc = channel_by_id(c->ctl_chan)) == NULL)
fatal("%s: channel %d lacks control channel %d", __func__,
id, c->ctl_chan);
if (!success) {
debug3("%s: sending failure reply", __func__);
/* prepare reply */
buffer_init(&reply);
buffer_put_int(&reply, MUX_S_FAILURE);
buffer_put_int(&reply, cctx->rid);
buffer_put_cstring(&reply, "Session open refused by peer");
goto done;
}
debug3("%s: sending success reply", __func__);
/* prepare reply */
buffer_init(&reply);
buffer_put_int(&reply, MUX_S_SESSION_OPENED);
buffer_put_int(&reply, cctx->rid);
buffer_put_int(&reply, c->self);
done:
/* Send reply */
buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
buffer_free(&reply);
if (cc->mux_pause <= 0)
fatal("%s: mux_pause %d", __func__, cc->mux_pause);
cc->mux_pause = 0; /* start processing messages again */
c->open_confirm_ctx = NULL;
free(cctx);
}
| null | 0 | mux_stdio_confirm(int id, int success, void *arg)
{
struct mux_stdio_confirm_ctx *cctx = arg;
Channel *c, *cc;
Buffer reply;
if (cctx == NULL)
fatal("%s: cctx == NULL", __func__);
if ((c = channel_by_id(id)) == NULL)
fatal("%s: no channel for id %d", __func__, id);
if ((cc = channel_by_id(c->ctl_chan)) == NULL)
fatal("%s: channel %d lacks control channel %d", __func__,
id, c->ctl_chan);
if (!success) {
debug3("%s: sending failure reply", __func__);
/* prepare reply */
buffer_init(&reply);
buffer_put_int(&reply, MUX_S_FAILURE);
buffer_put_int(&reply, cctx->rid);
buffer_put_cstring(&reply, "Session open refused by peer");
goto done;
}
debug3("%s: sending success reply", __func__);
/* prepare reply */
buffer_init(&reply);
buffer_put_int(&reply, MUX_S_SESSION_OPENED);
buffer_put_int(&reply, cctx->rid);
buffer_put_int(&reply, c->self);
done:
/* Send reply */
buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply));
buffer_free(&reply);
if (cc->mux_pause <= 0)
fatal("%s: mux_pause %d", __func__, cc->mux_pause);
cc->mux_pause = 0; /* start processing messages again */
c->open_confirm_ctx = NULL;
free(cctx);
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,478 | mux_tty_alloc_failed(Channel *c)
{
Buffer m;
Channel *mux_chan;
debug3("%s: channel %d: TTY alloc failed", __func__, c->self);
if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
fatal("%s: channel %d missing mux channel %d",
__func__, c->self, c->ctl_chan);
/* Append exit message packet to control socket output queue */
buffer_init(&m);
buffer_put_int(&m, MUX_S_TTY_ALLOC_FAIL);
buffer_put_int(&m, c->self);
buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
buffer_free(&m);
}
| null | 0 | mux_tty_alloc_failed(Channel *c)
{
Buffer m;
Channel *mux_chan;
debug3("%s: channel %d: TTY alloc failed", __func__, c->self);
if ((mux_chan = channel_by_id(c->ctl_chan)) == NULL)
fatal("%s: channel %d missing mux channel %d",
__func__, c->self, c->ctl_chan);
/* Append exit message packet to control socket output queue */
buffer_init(&m);
buffer_put_int(&m, MUX_S_TTY_ALLOC_FAIL);
buffer_put_int(&m, c->self);
buffer_put_string(&mux_chan->output, buffer_ptr(&m), buffer_len(&m));
buffer_free(&m);
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,479 | muxclient(const char *path)
{
struct sockaddr_un addr;
socklen_t sun_len;
int sock;
u_int pid;
if (muxclient_command == 0) {
if (stdio_forward_host != NULL)
muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
else
muxclient_command = SSHMUX_COMMAND_OPEN;
}
switch (options.control_master) {
case SSHCTL_MASTER_AUTO:
case SSHCTL_MASTER_AUTO_ASK:
debug("auto-mux: Trying existing master");
/* FALLTHROUGH */
case SSHCTL_MASTER_NO:
break;
default:
return;
}
memset(&addr, '\0', sizeof(addr));
addr.sun_family = AF_UNIX;
sun_len = offsetof(struct sockaddr_un, sun_path) +
strlen(path) + 1;
if (strlcpy(addr.sun_path, path,
sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
fatal("ControlPath too long");
if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
fatal("%s socket(): %s", __func__, strerror(errno));
if (connect(sock, (struct sockaddr *)&addr, sun_len) == -1) {
switch (muxclient_command) {
case SSHMUX_COMMAND_OPEN:
case SSHMUX_COMMAND_STDIO_FWD:
break;
default:
fatal("Control socket connect(%.100s): %s", path,
strerror(errno));
}
if (errno == ECONNREFUSED &&
options.control_master != SSHCTL_MASTER_NO) {
debug("Stale control socket %.100s, unlinking", path);
unlink(path);
} else if (errno == ENOENT) {
debug("Control socket \"%.100s\" does not exist", path);
} else {
error("Control socket connect(%.100s): %s", path,
strerror(errno));
}
close(sock);
return;
}
set_nonblock(sock);
if (mux_client_hello_exchange(sock) != 0) {
error("%s: master hello exchange failed", __func__);
close(sock);
return;
}
switch (muxclient_command) {
case SSHMUX_COMMAND_ALIVE_CHECK:
if ((pid = mux_client_request_alive(sock)) == 0)
fatal("%s: master alive check failed", __func__);
fprintf(stderr, "Master running (pid=%u)\r\n", pid);
exit(0);
case SSHMUX_COMMAND_TERMINATE:
mux_client_request_terminate(sock);
fprintf(stderr, "Exit request sent.\r\n");
exit(0);
case SSHMUX_COMMAND_FORWARD:
if (mux_client_forwards(sock, 0) != 0)
fatal("%s: master forward request failed", __func__);
exit(0);
case SSHMUX_COMMAND_OPEN:
if (mux_client_forwards(sock, 0) != 0) {
error("%s: master forward request failed", __func__);
return;
}
mux_client_request_session(sock);
return;
case SSHMUX_COMMAND_STDIO_FWD:
mux_client_request_stdio_fwd(sock);
exit(0);
case SSHMUX_COMMAND_STOP:
mux_client_request_stop_listening(sock);
fprintf(stderr, "Stop listening request sent.\r\n");
exit(0);
case SSHMUX_COMMAND_CANCEL_FWD:
if (mux_client_forwards(sock, 1) != 0)
error("%s: master cancel forward request failed",
__func__);
exit(0);
default:
fatal("unrecognised muxclient_command %d", muxclient_command);
}
}
| null | 0 | muxclient(const char *path)
{
struct sockaddr_un addr;
socklen_t sun_len;
int sock;
u_int pid;
if (muxclient_command == 0) {
if (stdio_forward_host != NULL)
muxclient_command = SSHMUX_COMMAND_STDIO_FWD;
else
muxclient_command = SSHMUX_COMMAND_OPEN;
}
switch (options.control_master) {
case SSHCTL_MASTER_AUTO:
case SSHCTL_MASTER_AUTO_ASK:
debug("auto-mux: Trying existing master");
/* FALLTHROUGH */
case SSHCTL_MASTER_NO:
break;
default:
return;
}
memset(&addr, '\0', sizeof(addr));
addr.sun_family = AF_UNIX;
sun_len = offsetof(struct sockaddr_un, sun_path) +
strlen(path) + 1;
if (strlcpy(addr.sun_path, path,
sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
fatal("ControlPath too long");
if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
fatal("%s socket(): %s", __func__, strerror(errno));
if (connect(sock, (struct sockaddr *)&addr, sun_len) == -1) {
switch (muxclient_command) {
case SSHMUX_COMMAND_OPEN:
case SSHMUX_COMMAND_STDIO_FWD:
break;
default:
fatal("Control socket connect(%.100s): %s", path,
strerror(errno));
}
if (errno == ECONNREFUSED &&
options.control_master != SSHCTL_MASTER_NO) {
debug("Stale control socket %.100s, unlinking", path);
unlink(path);
} else if (errno == ENOENT) {
debug("Control socket \"%.100s\" does not exist", path);
} else {
error("Control socket connect(%.100s): %s", path,
strerror(errno));
}
close(sock);
return;
}
set_nonblock(sock);
if (mux_client_hello_exchange(sock) != 0) {
error("%s: master hello exchange failed", __func__);
close(sock);
return;
}
switch (muxclient_command) {
case SSHMUX_COMMAND_ALIVE_CHECK:
if ((pid = mux_client_request_alive(sock)) == 0)
fatal("%s: master alive check failed", __func__);
fprintf(stderr, "Master running (pid=%u)\r\n", pid);
exit(0);
case SSHMUX_COMMAND_TERMINATE:
mux_client_request_terminate(sock);
fprintf(stderr, "Exit request sent.\r\n");
exit(0);
case SSHMUX_COMMAND_FORWARD:
if (mux_client_forwards(sock, 0) != 0)
fatal("%s: master forward request failed", __func__);
exit(0);
case SSHMUX_COMMAND_OPEN:
if (mux_client_forwards(sock, 0) != 0) {
error("%s: master forward request failed", __func__);
return;
}
mux_client_request_session(sock);
return;
case SSHMUX_COMMAND_STDIO_FWD:
mux_client_request_stdio_fwd(sock);
exit(0);
case SSHMUX_COMMAND_STOP:
mux_client_request_stop_listening(sock);
fprintf(stderr, "Stop listening request sent.\r\n");
exit(0);
case SSHMUX_COMMAND_CANCEL_FWD:
if (mux_client_forwards(sock, 1) != 0)
error("%s: master cancel forward request failed",
__func__);
exit(0);
default:
fatal("unrecognised muxclient_command %d", muxclient_command);
}
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,480 | muxserver_listen(void)
{
mode_t old_umask;
char *orig_control_path = options.control_path;
char rbuf[16+1];
u_int i, r;
int oerrno;
if (options.control_path == NULL ||
options.control_master == SSHCTL_MASTER_NO)
return;
debug("setting up multiplex master socket");
/*
* Use a temporary path before listen so we can pseudo-atomically
* establish the listening socket in its final location to avoid
* other processes racing in between bind() and listen() and hitting
* an unready socket.
*/
for (i = 0; i < sizeof(rbuf) - 1; i++) {
r = arc4random_uniform(26+26+10);
rbuf[i] = (r < 26) ? 'a' + r :
(r < 26*2) ? 'A' + r - 26 :
'0' + r - 26 - 26;
}
rbuf[sizeof(rbuf) - 1] = '\0';
options.control_path = NULL;
xasprintf(&options.control_path, "%s.%s", orig_control_path, rbuf);
debug3("%s: temporary control path %s", __func__, options.control_path);
old_umask = umask(0177);
muxserver_sock = unix_listener(options.control_path, 64, 0);
oerrno = errno;
umask(old_umask);
if (muxserver_sock < 0) {
if (oerrno == EINVAL || oerrno == EADDRINUSE) {
error("ControlSocket %s already exists, "
"disabling multiplexing", options.control_path);
disable_mux_master:
if (muxserver_sock != -1) {
close(muxserver_sock);
muxserver_sock = -1;
}
free(orig_control_path);
free(options.control_path);
options.control_path = NULL;
options.control_master = SSHCTL_MASTER_NO;
return;
} else {
/* unix_listener() logs the error */
cleanup_exit(255);
}
}
/* Now atomically "move" the mux socket into position */
if (link(options.control_path, orig_control_path) != 0) {
if (errno != EEXIST) {
fatal("%s: link mux listener %s => %s: %s", __func__,
options.control_path, orig_control_path,
strerror(errno));
}
error("ControlSocket %s already exists, disabling multiplexing",
orig_control_path);
unlink(options.control_path);
goto disable_mux_master;
}
unlink(options.control_path);
free(options.control_path);
options.control_path = orig_control_path;
set_nonblock(muxserver_sock);
mux_listener_channel = channel_new("mux listener",
SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
0, options.control_path, 1);
mux_listener_channel->mux_rcb = mux_master_read_cb;
debug3("%s: mux listener channel %d fd %d", __func__,
mux_listener_channel->self, mux_listener_channel->sock);
}
| null | 0 | muxserver_listen(void)
{
mode_t old_umask;
char *orig_control_path = options.control_path;
char rbuf[16+1];
u_int i, r;
int oerrno;
if (options.control_path == NULL ||
options.control_master == SSHCTL_MASTER_NO)
return;
debug("setting up multiplex master socket");
/*
* Use a temporary path before listen so we can pseudo-atomically
* establish the listening socket in its final location to avoid
* other processes racing in between bind() and listen() and hitting
* an unready socket.
*/
for (i = 0; i < sizeof(rbuf) - 1; i++) {
r = arc4random_uniform(26+26+10);
rbuf[i] = (r < 26) ? 'a' + r :
(r < 26*2) ? 'A' + r - 26 :
'0' + r - 26 - 26;
}
rbuf[sizeof(rbuf) - 1] = '\0';
options.control_path = NULL;
xasprintf(&options.control_path, "%s.%s", orig_control_path, rbuf);
debug3("%s: temporary control path %s", __func__, options.control_path);
old_umask = umask(0177);
muxserver_sock = unix_listener(options.control_path, 64, 0);
oerrno = errno;
umask(old_umask);
if (muxserver_sock < 0) {
if (oerrno == EINVAL || oerrno == EADDRINUSE) {
error("ControlSocket %s already exists, "
"disabling multiplexing", options.control_path);
disable_mux_master:
if (muxserver_sock != -1) {
close(muxserver_sock);
muxserver_sock = -1;
}
free(orig_control_path);
free(options.control_path);
options.control_path = NULL;
options.control_master = SSHCTL_MASTER_NO;
return;
} else {
/* unix_listener() logs the error */
cleanup_exit(255);
}
}
/* Now atomically "move" the mux socket into position */
if (link(options.control_path, orig_control_path) != 0) {
if (errno != EEXIST) {
fatal("%s: link mux listener %s => %s: %s", __func__,
options.control_path, orig_control_path,
strerror(errno));
}
error("ControlSocket %s already exists, disabling multiplexing",
orig_control_path);
unlink(options.control_path);
goto disable_mux_master;
}
unlink(options.control_path);
free(options.control_path);
options.control_path = orig_control_path;
set_nonblock(muxserver_sock);
mux_listener_channel = channel_new("mux listener",
SSH_CHANNEL_MUX_LISTENER, muxserver_sock, muxserver_sock, -1,
CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
0, options.control_path, 1);
mux_listener_channel->mux_rcb = mux_master_read_cb;
debug3("%s: mux listener channel %d fd %d", __func__,
mux_listener_channel->self, mux_listener_channel->sock);
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,481 | process_mux_alive_check(u_int rid, Channel *c, Buffer *m, Buffer *r)
{
debug2("%s: channel %d: alive check", __func__, c->self);
/* prepare reply */
buffer_put_int(r, MUX_S_ALIVE);
buffer_put_int(r, rid);
buffer_put_int(r, (u_int)getpid());
return 0;
}
| null | 0 | process_mux_alive_check(u_int rid, Channel *c, Buffer *m, Buffer *r)
{
debug2("%s: channel %d: alive check", __func__, c->self);
/* prepare reply */
buffer_put_int(r, MUX_S_ALIVE);
buffer_put_int(r, rid);
buffer_put_int(r, (u_int)getpid());
return 0;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,482 | process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
{
struct Forward fwd, *found_fwd;
char *fwd_desc = NULL;
const char *error_reason = NULL;
char *listen_addr = NULL, *connect_addr = NULL;
u_int ftype;
int i, ret = 0;
u_int lport, cport;
memset(&fwd, 0, sizeof(fwd));
if (buffer_get_int_ret(&ftype, m) != 0 ||
(listen_addr = buffer_get_string_ret(m, NULL)) == NULL ||
buffer_get_int_ret(&lport, m) != 0 ||
(connect_addr = buffer_get_string_ret(m, NULL)) == NULL ||
buffer_get_int_ret(&cport, m) != 0 ||
(lport != (u_int)PORT_STREAMLOCAL && lport > 65535) ||
(cport != (u_int)PORT_STREAMLOCAL && cport > 65535)) {
error("%s: malformed message", __func__);
ret = -1;
goto out;
}
if (*listen_addr == '\0') {
free(listen_addr);
listen_addr = NULL;
}
if (*connect_addr == '\0') {
free(connect_addr);
connect_addr = NULL;
}
memset(&fwd, 0, sizeof(fwd));
fwd.listen_port = lport;
if (fwd.listen_port == PORT_STREAMLOCAL)
fwd.listen_path = listen_addr;
else
fwd.listen_host = listen_addr;
fwd.connect_port = cport;
if (fwd.connect_port == PORT_STREAMLOCAL)
fwd.connect_path = connect_addr;
else
fwd.connect_host = connect_addr;
debug2("%s: channel %d: request cancel %s", __func__, c->self,
(fwd_desc = format_forward(ftype, &fwd)));
/* make sure this has been requested */
found_fwd = NULL;
switch (ftype) {
case MUX_FWD_LOCAL:
case MUX_FWD_DYNAMIC:
for (i = 0; i < options.num_local_forwards; i++) {
if (compare_forward(&fwd,
options.local_forwards + i)) {
found_fwd = options.local_forwards + i;
break;
}
}
break;
case MUX_FWD_REMOTE:
for (i = 0; i < options.num_remote_forwards; i++) {
if (compare_forward(&fwd,
options.remote_forwards + i)) {
found_fwd = options.remote_forwards + i;
break;
}
}
break;
}
if (found_fwd == NULL)
error_reason = "port not forwarded";
else if (ftype == MUX_FWD_REMOTE) {
/*
* This shouldn't fail unless we confused the host/port
* between options.remote_forwards and permitted_opens.
* However, for dynamic allocated listen ports we need
* to use the actual listen port.
*/
if (channel_request_rforward_cancel(found_fwd) == -1)
error_reason = "port not in permitted opens";
} else { /* local and dynamic forwards */
/* Ditto */
if (channel_cancel_lport_listener(&fwd, fwd.connect_port,
&options.fwd_opts) == -1)
error_reason = "port not found";
}
if (error_reason == NULL) {
buffer_put_int(r, MUX_S_OK);
buffer_put_int(r, rid);
free(found_fwd->listen_host);
free(found_fwd->listen_path);
free(found_fwd->connect_host);
free(found_fwd->connect_path);
found_fwd->listen_host = found_fwd->connect_host = NULL;
found_fwd->listen_path = found_fwd->connect_path = NULL;
found_fwd->listen_port = found_fwd->connect_port = 0;
} else {
buffer_put_int(r, MUX_S_FAILURE);
buffer_put_int(r, rid);
buffer_put_cstring(r, error_reason);
}
out:
free(fwd_desc);
free(listen_addr);
free(connect_addr);
return ret;
}
| null | 0 | process_mux_close_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
{
struct Forward fwd, *found_fwd;
char *fwd_desc = NULL;
const char *error_reason = NULL;
char *listen_addr = NULL, *connect_addr = NULL;
u_int ftype;
int i, ret = 0;
u_int lport, cport;
memset(&fwd, 0, sizeof(fwd));
if (buffer_get_int_ret(&ftype, m) != 0 ||
(listen_addr = buffer_get_string_ret(m, NULL)) == NULL ||
buffer_get_int_ret(&lport, m) != 0 ||
(connect_addr = buffer_get_string_ret(m, NULL)) == NULL ||
buffer_get_int_ret(&cport, m) != 0 ||
(lport != (u_int)PORT_STREAMLOCAL && lport > 65535) ||
(cport != (u_int)PORT_STREAMLOCAL && cport > 65535)) {
error("%s: malformed message", __func__);
ret = -1;
goto out;
}
if (*listen_addr == '\0') {
free(listen_addr);
listen_addr = NULL;
}
if (*connect_addr == '\0') {
free(connect_addr);
connect_addr = NULL;
}
memset(&fwd, 0, sizeof(fwd));
fwd.listen_port = lport;
if (fwd.listen_port == PORT_STREAMLOCAL)
fwd.listen_path = listen_addr;
else
fwd.listen_host = listen_addr;
fwd.connect_port = cport;
if (fwd.connect_port == PORT_STREAMLOCAL)
fwd.connect_path = connect_addr;
else
fwd.connect_host = connect_addr;
debug2("%s: channel %d: request cancel %s", __func__, c->self,
(fwd_desc = format_forward(ftype, &fwd)));
/* make sure this has been requested */
found_fwd = NULL;
switch (ftype) {
case MUX_FWD_LOCAL:
case MUX_FWD_DYNAMIC:
for (i = 0; i < options.num_local_forwards; i++) {
if (compare_forward(&fwd,
options.local_forwards + i)) {
found_fwd = options.local_forwards + i;
break;
}
}
break;
case MUX_FWD_REMOTE:
for (i = 0; i < options.num_remote_forwards; i++) {
if (compare_forward(&fwd,
options.remote_forwards + i)) {
found_fwd = options.remote_forwards + i;
break;
}
}
break;
}
if (found_fwd == NULL)
error_reason = "port not forwarded";
else if (ftype == MUX_FWD_REMOTE) {
/*
* This shouldn't fail unless we confused the host/port
* between options.remote_forwards and permitted_opens.
* However, for dynamic allocated listen ports we need
* to use the actual listen port.
*/
if (channel_request_rforward_cancel(found_fwd) == -1)
error_reason = "port not in permitted opens";
} else { /* local and dynamic forwards */
/* Ditto */
if (channel_cancel_lport_listener(&fwd, fwd.connect_port,
&options.fwd_opts) == -1)
error_reason = "port not found";
}
if (error_reason == NULL) {
buffer_put_int(r, MUX_S_OK);
buffer_put_int(r, rid);
free(found_fwd->listen_host);
free(found_fwd->listen_path);
free(found_fwd->connect_host);
free(found_fwd->connect_path);
found_fwd->listen_host = found_fwd->connect_host = NULL;
found_fwd->listen_path = found_fwd->connect_path = NULL;
found_fwd->listen_port = found_fwd->connect_port = 0;
} else {
buffer_put_int(r, MUX_S_FAILURE);
buffer_put_int(r, rid);
buffer_put_cstring(r, error_reason);
}
out:
free(fwd_desc);
free(listen_addr);
free(connect_addr);
return ret;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,483 | process_mux_master_hello(u_int rid, Channel *c, Buffer *m, Buffer *r)
{
u_int ver;
struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
if (state == NULL)
fatal("%s: channel %d: c->mux_ctx == NULL", __func__, c->self);
if (state->hello_rcvd) {
error("%s: HELLO received twice", __func__);
return -1;
}
if (buffer_get_int_ret(&ver, m) != 0) {
malf:
error("%s: malformed message", __func__);
return -1;
}
if (ver != SSHMUX_VER) {
error("Unsupported multiplexing protocol version %d "
"(expected %d)", ver, SSHMUX_VER);
return -1;
}
debug2("%s: channel %d slave version %u", __func__, c->self, ver);
/* No extensions are presently defined */
while (buffer_len(m) > 0) {
char *name = buffer_get_string_ret(m, NULL);
char *value = buffer_get_string_ret(m, NULL);
if (name == NULL || value == NULL) {
free(name);
free(value);
goto malf;
}
debug2("Unrecognised slave extension \"%s\"", name);
free(name);
free(value);
}
state->hello_rcvd = 1;
return 0;
}
| null | 0 | process_mux_master_hello(u_int rid, Channel *c, Buffer *m, Buffer *r)
{
u_int ver;
struct mux_master_state *state = (struct mux_master_state *)c->mux_ctx;
if (state == NULL)
fatal("%s: channel %d: c->mux_ctx == NULL", __func__, c->self);
if (state->hello_rcvd) {
error("%s: HELLO received twice", __func__);
return -1;
}
if (buffer_get_int_ret(&ver, m) != 0) {
malf:
error("%s: malformed message", __func__);
return -1;
}
if (ver != SSHMUX_VER) {
error("Unsupported multiplexing protocol version %d "
"(expected %d)", ver, SSHMUX_VER);
return -1;
}
debug2("%s: channel %d slave version %u", __func__, c->self, ver);
/* No extensions are presently defined */
while (buffer_len(m) > 0) {
char *name = buffer_get_string_ret(m, NULL);
char *value = buffer_get_string_ret(m, NULL);
if (name == NULL || value == NULL) {
free(name);
free(value);
goto malf;
}
debug2("Unrecognised slave extension \"%s\"", name);
free(name);
free(value);
}
state->hello_rcvd = 1;
return 0;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,484 | process_mux_new_session(u_int rid, Channel *c, Buffer *m, Buffer *r)
{
Channel *nc;
struct mux_session_confirm_ctx *cctx;
char *reserved, *cmd, *cp;
u_int i, j, len, env_len, escape_char, window, packetmax;
int new_fd[3];
/* Reply for SSHMUX_COMMAND_OPEN */
cctx = xcalloc(1, sizeof(*cctx));
cctx->term = NULL;
cctx->rid = rid;
cmd = reserved = NULL;
cctx->env = NULL;
env_len = 0;
if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
buffer_get_int_ret(&cctx->want_tty, m) != 0 ||
buffer_get_int_ret(&cctx->want_x_fwd, m) != 0 ||
buffer_get_int_ret(&cctx->want_agent_fwd, m) != 0 ||
buffer_get_int_ret(&cctx->want_subsys, m) != 0 ||
buffer_get_int_ret(&escape_char, m) != 0 ||
(cctx->term = buffer_get_string_ret(m, &len)) == NULL ||
(cmd = buffer_get_string_ret(m, &len)) == NULL) {
malf:
free(cmd);
free(reserved);
for (j = 0; j < env_len; j++)
free(cctx->env[j]);
free(cctx->env);
free(cctx->term);
free(cctx);
error("%s: malformed message", __func__);
return -1;
}
free(reserved);
reserved = NULL;
while (buffer_len(m) > 0) {
#define MUX_MAX_ENV_VARS 4096
if ((cp = buffer_get_string_ret(m, &len)) == NULL)
goto malf;
if (!env_permitted(cp)) {
free(cp);
continue;
}
cctx->env = xreallocarray(cctx->env, env_len + 2,
sizeof(*cctx->env));
cctx->env[env_len++] = cp;
cctx->env[env_len] = NULL;
if (env_len > MUX_MAX_ENV_VARS) {
error(">%d environment variables received, ignoring "
"additional", MUX_MAX_ENV_VARS);
break;
}
}
debug2("%s: channel %d: request tty %d, X %d, agent %d, subsys %d, "
"term \"%s\", cmd \"%s\", env %u", __func__, c->self,
cctx->want_tty, cctx->want_x_fwd, cctx->want_agent_fwd,
cctx->want_subsys, cctx->term, cmd, env_len);
buffer_init(&cctx->cmd);
buffer_append(&cctx->cmd, cmd, strlen(cmd));
free(cmd);
cmd = NULL;
/* Gather fds from client */
for(i = 0; i < 3; i++) {
if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
error("%s: failed to receive fd %d from slave",
__func__, i);
for (j = 0; j < i; j++)
close(new_fd[j]);
for (j = 0; j < env_len; j++)
free(cctx->env[j]);
free(cctx->env);
free(cctx->term);
buffer_free(&cctx->cmd);
free(cctx);
/* prepare reply */
buffer_put_int(r, MUX_S_FAILURE);
buffer_put_int(r, rid);
buffer_put_cstring(r,
"did not receive file descriptors");
return -1;
}
}
debug3("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
new_fd[0], new_fd[1], new_fd[2]);
/* XXX support multiple child sessions in future */
if (c->remote_id != -1) {
debug2("%s: session already open", __func__);
/* prepare reply */
buffer_put_int(r, MUX_S_FAILURE);
buffer_put_int(r, rid);
buffer_put_cstring(r, "Multiple sessions not supported");
cleanup:
close(new_fd[0]);
close(new_fd[1]);
close(new_fd[2]);
free(cctx->term);
if (env_len != 0) {
for (i = 0; i < env_len; i++)
free(cctx->env[i]);
free(cctx->env);
}
buffer_free(&cctx->cmd);
free(cctx);
return 0;
}
if (options.control_master == SSHCTL_MASTER_ASK ||
options.control_master == SSHCTL_MASTER_AUTO_ASK) {
if (!ask_permission("Allow shared connection to %s? ", host)) {
debug2("%s: session refused by user", __func__);
/* prepare reply */
buffer_put_int(r, MUX_S_PERMISSION_DENIED);
buffer_put_int(r, rid);
buffer_put_cstring(r, "Permission denied");
goto cleanup;
}
}
/* Try to pick up ttymodes from client before it goes raw */
if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
error("%s: tcgetattr: %s", __func__, strerror(errno));
/* enable nonblocking unless tty */
if (!isatty(new_fd[0]))
set_nonblock(new_fd[0]);
if (!isatty(new_fd[1]))
set_nonblock(new_fd[1]);
if (!isatty(new_fd[2]))
set_nonblock(new_fd[2]);
window = CHAN_SES_WINDOW_DEFAULT;
packetmax = CHAN_SES_PACKET_DEFAULT;
if (cctx->want_tty) {
window >>= 1;
packetmax >>= 1;
}
nc = channel_new("session", SSH_CHANNEL_OPENING,
new_fd[0], new_fd[1], new_fd[2], window, packetmax,
CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
nc->ctl_chan = c->self; /* link session -> control channel */
c->remote_id = nc->self; /* link control -> session channel */
if (cctx->want_tty && escape_char != 0xffffffff) {
channel_register_filter(nc->self,
client_simple_escape_filter, NULL,
client_filter_cleanup,
client_new_escape_filter_ctx((int)escape_char));
}
debug2("%s: channel_new: %d linked to control channel %d",
__func__, nc->self, nc->ctl_chan);
channel_send_open(nc->self);
channel_register_open_confirm(nc->self, mux_session_confirm, cctx);
c->mux_pause = 1; /* stop handling messages until open_confirm done */
channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
/* reply is deferred, sent by mux_session_confirm */
return 0;
}
| null | 0 | process_mux_new_session(u_int rid, Channel *c, Buffer *m, Buffer *r)
{
Channel *nc;
struct mux_session_confirm_ctx *cctx;
char *reserved, *cmd, *cp;
u_int i, j, len, env_len, escape_char, window, packetmax;
int new_fd[3];
/* Reply for SSHMUX_COMMAND_OPEN */
cctx = xcalloc(1, sizeof(*cctx));
cctx->term = NULL;
cctx->rid = rid;
cmd = reserved = NULL;
cctx->env = NULL;
env_len = 0;
if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
buffer_get_int_ret(&cctx->want_tty, m) != 0 ||
buffer_get_int_ret(&cctx->want_x_fwd, m) != 0 ||
buffer_get_int_ret(&cctx->want_agent_fwd, m) != 0 ||
buffer_get_int_ret(&cctx->want_subsys, m) != 0 ||
buffer_get_int_ret(&escape_char, m) != 0 ||
(cctx->term = buffer_get_string_ret(m, &len)) == NULL ||
(cmd = buffer_get_string_ret(m, &len)) == NULL) {
malf:
free(cmd);
free(reserved);
for (j = 0; j < env_len; j++)
free(cctx->env[j]);
free(cctx->env);
free(cctx->term);
free(cctx);
error("%s: malformed message", __func__);
return -1;
}
free(reserved);
reserved = NULL;
while (buffer_len(m) > 0) {
#define MUX_MAX_ENV_VARS 4096
if ((cp = buffer_get_string_ret(m, &len)) == NULL)
goto malf;
if (!env_permitted(cp)) {
free(cp);
continue;
}
cctx->env = xreallocarray(cctx->env, env_len + 2,
sizeof(*cctx->env));
cctx->env[env_len++] = cp;
cctx->env[env_len] = NULL;
if (env_len > MUX_MAX_ENV_VARS) {
error(">%d environment variables received, ignoring "
"additional", MUX_MAX_ENV_VARS);
break;
}
}
debug2("%s: channel %d: request tty %d, X %d, agent %d, subsys %d, "
"term \"%s\", cmd \"%s\", env %u", __func__, c->self,
cctx->want_tty, cctx->want_x_fwd, cctx->want_agent_fwd,
cctx->want_subsys, cctx->term, cmd, env_len);
buffer_init(&cctx->cmd);
buffer_append(&cctx->cmd, cmd, strlen(cmd));
free(cmd);
cmd = NULL;
/* Gather fds from client */
for(i = 0; i < 3; i++) {
if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
error("%s: failed to receive fd %d from slave",
__func__, i);
for (j = 0; j < i; j++)
close(new_fd[j]);
for (j = 0; j < env_len; j++)
free(cctx->env[j]);
free(cctx->env);
free(cctx->term);
buffer_free(&cctx->cmd);
free(cctx);
/* prepare reply */
buffer_put_int(r, MUX_S_FAILURE);
buffer_put_int(r, rid);
buffer_put_cstring(r,
"did not receive file descriptors");
return -1;
}
}
debug3("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
new_fd[0], new_fd[1], new_fd[2]);
/* XXX support multiple child sessions in future */
if (c->remote_id != -1) {
debug2("%s: session already open", __func__);
/* prepare reply */
buffer_put_int(r, MUX_S_FAILURE);
buffer_put_int(r, rid);
buffer_put_cstring(r, "Multiple sessions not supported");
cleanup:
close(new_fd[0]);
close(new_fd[1]);
close(new_fd[2]);
free(cctx->term);
if (env_len != 0) {
for (i = 0; i < env_len; i++)
free(cctx->env[i]);
free(cctx->env);
}
buffer_free(&cctx->cmd);
free(cctx);
return 0;
}
if (options.control_master == SSHCTL_MASTER_ASK ||
options.control_master == SSHCTL_MASTER_AUTO_ASK) {
if (!ask_permission("Allow shared connection to %s? ", host)) {
debug2("%s: session refused by user", __func__);
/* prepare reply */
buffer_put_int(r, MUX_S_PERMISSION_DENIED);
buffer_put_int(r, rid);
buffer_put_cstring(r, "Permission denied");
goto cleanup;
}
}
/* Try to pick up ttymodes from client before it goes raw */
if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
error("%s: tcgetattr: %s", __func__, strerror(errno));
/* enable nonblocking unless tty */
if (!isatty(new_fd[0]))
set_nonblock(new_fd[0]);
if (!isatty(new_fd[1]))
set_nonblock(new_fd[1]);
if (!isatty(new_fd[2]))
set_nonblock(new_fd[2]);
window = CHAN_SES_WINDOW_DEFAULT;
packetmax = CHAN_SES_PACKET_DEFAULT;
if (cctx->want_tty) {
window >>= 1;
packetmax >>= 1;
}
nc = channel_new("session", SSH_CHANNEL_OPENING,
new_fd[0], new_fd[1], new_fd[2], window, packetmax,
CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
nc->ctl_chan = c->self; /* link session -> control channel */
c->remote_id = nc->self; /* link control -> session channel */
if (cctx->want_tty && escape_char != 0xffffffff) {
channel_register_filter(nc->self,
client_simple_escape_filter, NULL,
client_filter_cleanup,
client_new_escape_filter_ctx((int)escape_char));
}
debug2("%s: channel_new: %d linked to control channel %d",
__func__, nc->self, nc->ctl_chan);
channel_send_open(nc->self);
channel_register_open_confirm(nc->self, mux_session_confirm, cctx);
c->mux_pause = 1; /* stop handling messages until open_confirm done */
channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
/* reply is deferred, sent by mux_session_confirm */
return 0;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,485 | process_mux_open_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
{
struct Forward fwd;
char *fwd_desc = NULL;
char *listen_addr, *connect_addr;
u_int ftype;
u_int lport, cport;
int i, ret = 0, freefwd = 1;
memset(&fwd, 0, sizeof(fwd));
/* XXX - lport/cport check redundant */
if (buffer_get_int_ret(&ftype, m) != 0 ||
(listen_addr = buffer_get_string_ret(m, NULL)) == NULL ||
buffer_get_int_ret(&lport, m) != 0 ||
(connect_addr = buffer_get_string_ret(m, NULL)) == NULL ||
buffer_get_int_ret(&cport, m) != 0 ||
(lport != (u_int)PORT_STREAMLOCAL && lport > 65535) ||
(cport != (u_int)PORT_STREAMLOCAL && cport > 65535)) {
error("%s: malformed message", __func__);
ret = -1;
goto out;
}
if (*listen_addr == '\0') {
free(listen_addr);
listen_addr = NULL;
}
if (*connect_addr == '\0') {
free(connect_addr);
connect_addr = NULL;
}
memset(&fwd, 0, sizeof(fwd));
fwd.listen_port = lport;
if (fwd.listen_port == PORT_STREAMLOCAL)
fwd.listen_path = listen_addr;
else
fwd.listen_host = listen_addr;
fwd.connect_port = cport;
if (fwd.connect_port == PORT_STREAMLOCAL)
fwd.connect_path = connect_addr;
else
fwd.connect_host = connect_addr;
debug2("%s: channel %d: request %s", __func__, c->self,
(fwd_desc = format_forward(ftype, &fwd)));
if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
ftype != MUX_FWD_DYNAMIC) {
logit("%s: invalid forwarding type %u", __func__, ftype);
invalid:
free(listen_addr);
free(connect_addr);
buffer_put_int(r, MUX_S_FAILURE);
buffer_put_int(r, rid);
buffer_put_cstring(r, "Invalid forwarding request");
return 0;
}
if (ftype == MUX_FWD_DYNAMIC && fwd.listen_path) {
logit("%s: streamlocal and dynamic forwards "
"are mutually exclusive", __func__);
goto invalid;
}
if (fwd.listen_port != PORT_STREAMLOCAL && fwd.listen_port >= 65536) {
logit("%s: invalid listen port %u", __func__,
fwd.listen_port);
goto invalid;
}
if ((fwd.connect_port != PORT_STREAMLOCAL && fwd.connect_port >= 65536)
|| (ftype != MUX_FWD_DYNAMIC && ftype != MUX_FWD_REMOTE && fwd.connect_port == 0)) {
logit("%s: invalid connect port %u", __func__,
fwd.connect_port);
goto invalid;
}
if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL && fwd.connect_path == NULL) {
logit("%s: missing connect host", __func__);
goto invalid;
}
/* Skip forwards that have already been requested */
switch (ftype) {
case MUX_FWD_LOCAL:
case MUX_FWD_DYNAMIC:
for (i = 0; i < options.num_local_forwards; i++) {
if (compare_forward(&fwd,
options.local_forwards + i)) {
exists:
debug2("%s: found existing forwarding",
__func__);
buffer_put_int(r, MUX_S_OK);
buffer_put_int(r, rid);
goto out;
}
}
break;
case MUX_FWD_REMOTE:
for (i = 0; i < options.num_remote_forwards; i++) {
if (compare_forward(&fwd,
options.remote_forwards + i)) {
if (fwd.listen_port != 0)
goto exists;
debug2("%s: found allocated port",
__func__);
buffer_put_int(r, MUX_S_REMOTE_PORT);
buffer_put_int(r, rid);
buffer_put_int(r,
options.remote_forwards[i].allocated_port);
goto out;
}
}
break;
}
if (options.control_master == SSHCTL_MASTER_ASK ||
options.control_master == SSHCTL_MASTER_AUTO_ASK) {
if (!ask_permission("Open %s on %s?", fwd_desc, host)) {
debug2("%s: forwarding refused by user", __func__);
buffer_put_int(r, MUX_S_PERMISSION_DENIED);
buffer_put_int(r, rid);
buffer_put_cstring(r, "Permission denied");
goto out;
}
}
if (ftype == MUX_FWD_LOCAL || ftype == MUX_FWD_DYNAMIC) {
if (!channel_setup_local_fwd_listener(&fwd,
&options.fwd_opts)) {
fail:
logit("slave-requested %s failed", fwd_desc);
buffer_put_int(r, MUX_S_FAILURE);
buffer_put_int(r, rid);
buffer_put_cstring(r, "Port forwarding failed");
goto out;
}
add_local_forward(&options, &fwd);
freefwd = 0;
} else {
struct mux_channel_confirm_ctx *fctx;
fwd.handle = channel_request_remote_forwarding(&fwd);
if (fwd.handle < 0)
goto fail;
add_remote_forward(&options, &fwd);
fctx = xcalloc(1, sizeof(*fctx));
fctx->cid = c->self;
fctx->rid = rid;
fctx->fid = options.num_remote_forwards - 1;
client_register_global_confirm(mux_confirm_remote_forward,
fctx);
freefwd = 0;
c->mux_pause = 1; /* wait for mux_confirm_remote_forward */
/* delayed reply in mux_confirm_remote_forward */
goto out;
}
buffer_put_int(r, MUX_S_OK);
buffer_put_int(r, rid);
out:
free(fwd_desc);
if (freefwd) {
free(fwd.listen_host);
free(fwd.listen_path);
free(fwd.connect_host);
free(fwd.connect_path);
}
return ret;
}
| null | 0 | process_mux_open_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
{
struct Forward fwd;
char *fwd_desc = NULL;
char *listen_addr, *connect_addr;
u_int ftype;
u_int lport, cport;
int i, ret = 0, freefwd = 1;
memset(&fwd, 0, sizeof(fwd));
/* XXX - lport/cport check redundant */
if (buffer_get_int_ret(&ftype, m) != 0 ||
(listen_addr = buffer_get_string_ret(m, NULL)) == NULL ||
buffer_get_int_ret(&lport, m) != 0 ||
(connect_addr = buffer_get_string_ret(m, NULL)) == NULL ||
buffer_get_int_ret(&cport, m) != 0 ||
(lport != (u_int)PORT_STREAMLOCAL && lport > 65535) ||
(cport != (u_int)PORT_STREAMLOCAL && cport > 65535)) {
error("%s: malformed message", __func__);
ret = -1;
goto out;
}
if (*listen_addr == '\0') {
free(listen_addr);
listen_addr = NULL;
}
if (*connect_addr == '\0') {
free(connect_addr);
connect_addr = NULL;
}
memset(&fwd, 0, sizeof(fwd));
fwd.listen_port = lport;
if (fwd.listen_port == PORT_STREAMLOCAL)
fwd.listen_path = listen_addr;
else
fwd.listen_host = listen_addr;
fwd.connect_port = cport;
if (fwd.connect_port == PORT_STREAMLOCAL)
fwd.connect_path = connect_addr;
else
fwd.connect_host = connect_addr;
debug2("%s: channel %d: request %s", __func__, c->self,
(fwd_desc = format_forward(ftype, &fwd)));
if (ftype != MUX_FWD_LOCAL && ftype != MUX_FWD_REMOTE &&
ftype != MUX_FWD_DYNAMIC) {
logit("%s: invalid forwarding type %u", __func__, ftype);
invalid:
free(listen_addr);
free(connect_addr);
buffer_put_int(r, MUX_S_FAILURE);
buffer_put_int(r, rid);
buffer_put_cstring(r, "Invalid forwarding request");
return 0;
}
if (ftype == MUX_FWD_DYNAMIC && fwd.listen_path) {
logit("%s: streamlocal and dynamic forwards "
"are mutually exclusive", __func__);
goto invalid;
}
if (fwd.listen_port != PORT_STREAMLOCAL && fwd.listen_port >= 65536) {
logit("%s: invalid listen port %u", __func__,
fwd.listen_port);
goto invalid;
}
if ((fwd.connect_port != PORT_STREAMLOCAL && fwd.connect_port >= 65536)
|| (ftype != MUX_FWD_DYNAMIC && ftype != MUX_FWD_REMOTE && fwd.connect_port == 0)) {
logit("%s: invalid connect port %u", __func__,
fwd.connect_port);
goto invalid;
}
if (ftype != MUX_FWD_DYNAMIC && fwd.connect_host == NULL && fwd.connect_path == NULL) {
logit("%s: missing connect host", __func__);
goto invalid;
}
/* Skip forwards that have already been requested */
switch (ftype) {
case MUX_FWD_LOCAL:
case MUX_FWD_DYNAMIC:
for (i = 0; i < options.num_local_forwards; i++) {
if (compare_forward(&fwd,
options.local_forwards + i)) {
exists:
debug2("%s: found existing forwarding",
__func__);
buffer_put_int(r, MUX_S_OK);
buffer_put_int(r, rid);
goto out;
}
}
break;
case MUX_FWD_REMOTE:
for (i = 0; i < options.num_remote_forwards; i++) {
if (compare_forward(&fwd,
options.remote_forwards + i)) {
if (fwd.listen_port != 0)
goto exists;
debug2("%s: found allocated port",
__func__);
buffer_put_int(r, MUX_S_REMOTE_PORT);
buffer_put_int(r, rid);
buffer_put_int(r,
options.remote_forwards[i].allocated_port);
goto out;
}
}
break;
}
if (options.control_master == SSHCTL_MASTER_ASK ||
options.control_master == SSHCTL_MASTER_AUTO_ASK) {
if (!ask_permission("Open %s on %s?", fwd_desc, host)) {
debug2("%s: forwarding refused by user", __func__);
buffer_put_int(r, MUX_S_PERMISSION_DENIED);
buffer_put_int(r, rid);
buffer_put_cstring(r, "Permission denied");
goto out;
}
}
if (ftype == MUX_FWD_LOCAL || ftype == MUX_FWD_DYNAMIC) {
if (!channel_setup_local_fwd_listener(&fwd,
&options.fwd_opts)) {
fail:
logit("slave-requested %s failed", fwd_desc);
buffer_put_int(r, MUX_S_FAILURE);
buffer_put_int(r, rid);
buffer_put_cstring(r, "Port forwarding failed");
goto out;
}
add_local_forward(&options, &fwd);
freefwd = 0;
} else {
struct mux_channel_confirm_ctx *fctx;
fwd.handle = channel_request_remote_forwarding(&fwd);
if (fwd.handle < 0)
goto fail;
add_remote_forward(&options, &fwd);
fctx = xcalloc(1, sizeof(*fctx));
fctx->cid = c->self;
fctx->rid = rid;
fctx->fid = options.num_remote_forwards - 1;
client_register_global_confirm(mux_confirm_remote_forward,
fctx);
freefwd = 0;
c->mux_pause = 1; /* wait for mux_confirm_remote_forward */
/* delayed reply in mux_confirm_remote_forward */
goto out;
}
buffer_put_int(r, MUX_S_OK);
buffer_put_int(r, rid);
out:
free(fwd_desc);
if (freefwd) {
free(fwd.listen_host);
free(fwd.listen_path);
free(fwd.connect_host);
free(fwd.connect_path);
}
return ret;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,486 | process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
{
Channel *nc;
char *reserved, *chost;
u_int cport, i, j;
int new_fd[2];
struct mux_stdio_confirm_ctx *cctx;
chost = reserved = NULL;
if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
(chost = buffer_get_string_ret(m, NULL)) == NULL ||
buffer_get_int_ret(&cport, m) != 0) {
free(reserved);
free(chost);
error("%s: malformed message", __func__);
return -1;
}
free(reserved);
debug2("%s: channel %d: request stdio fwd to %s:%u",
__func__, c->self, chost, cport);
/* Gather fds from client */
for(i = 0; i < 2; i++) {
if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
error("%s: failed to receive fd %d from slave",
__func__, i);
for (j = 0; j < i; j++)
close(new_fd[j]);
free(chost);
/* prepare reply */
buffer_put_int(r, MUX_S_FAILURE);
buffer_put_int(r, rid);
buffer_put_cstring(r,
"did not receive file descriptors");
return -1;
}
}
debug3("%s: got fds stdin %d, stdout %d", __func__,
new_fd[0], new_fd[1]);
/* XXX support multiple child sessions in future */
if (c->remote_id != -1) {
debug2("%s: session already open", __func__);
/* prepare reply */
buffer_put_int(r, MUX_S_FAILURE);
buffer_put_int(r, rid);
buffer_put_cstring(r, "Multiple sessions not supported");
cleanup:
close(new_fd[0]);
close(new_fd[1]);
free(chost);
return 0;
}
if (options.control_master == SSHCTL_MASTER_ASK ||
options.control_master == SSHCTL_MASTER_AUTO_ASK) {
if (!ask_permission("Allow forward to %s:%u? ",
chost, cport)) {
debug2("%s: stdio fwd refused by user", __func__);
/* prepare reply */
buffer_put_int(r, MUX_S_PERMISSION_DENIED);
buffer_put_int(r, rid);
buffer_put_cstring(r, "Permission denied");
goto cleanup;
}
}
/* enable nonblocking unless tty */
if (!isatty(new_fd[0]))
set_nonblock(new_fd[0]);
if (!isatty(new_fd[1]))
set_nonblock(new_fd[1]);
nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
nc->ctl_chan = c->self; /* link session -> control channel */
c->remote_id = nc->self; /* link control -> session channel */
debug2("%s: channel_new: %d linked to control channel %d",
__func__, nc->self, nc->ctl_chan);
channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
cctx = xcalloc(1, sizeof(*cctx));
cctx->rid = rid;
channel_register_open_confirm(nc->self, mux_stdio_confirm, cctx);
c->mux_pause = 1; /* stop handling messages until open_confirm done */
/* reply is deferred, sent by mux_session_confirm */
return 0;
}
| null | 0 | process_mux_stdio_fwd(u_int rid, Channel *c, Buffer *m, Buffer *r)
{
Channel *nc;
char *reserved, *chost;
u_int cport, i, j;
int new_fd[2];
struct mux_stdio_confirm_ctx *cctx;
chost = reserved = NULL;
if ((reserved = buffer_get_string_ret(m, NULL)) == NULL ||
(chost = buffer_get_string_ret(m, NULL)) == NULL ||
buffer_get_int_ret(&cport, m) != 0) {
free(reserved);
free(chost);
error("%s: malformed message", __func__);
return -1;
}
free(reserved);
debug2("%s: channel %d: request stdio fwd to %s:%u",
__func__, c->self, chost, cport);
/* Gather fds from client */
for(i = 0; i < 2; i++) {
if ((new_fd[i] = mm_receive_fd(c->sock)) == -1) {
error("%s: failed to receive fd %d from slave",
__func__, i);
for (j = 0; j < i; j++)
close(new_fd[j]);
free(chost);
/* prepare reply */
buffer_put_int(r, MUX_S_FAILURE);
buffer_put_int(r, rid);
buffer_put_cstring(r,
"did not receive file descriptors");
return -1;
}
}
debug3("%s: got fds stdin %d, stdout %d", __func__,
new_fd[0], new_fd[1]);
/* XXX support multiple child sessions in future */
if (c->remote_id != -1) {
debug2("%s: session already open", __func__);
/* prepare reply */
buffer_put_int(r, MUX_S_FAILURE);
buffer_put_int(r, rid);
buffer_put_cstring(r, "Multiple sessions not supported");
cleanup:
close(new_fd[0]);
close(new_fd[1]);
free(chost);
return 0;
}
if (options.control_master == SSHCTL_MASTER_ASK ||
options.control_master == SSHCTL_MASTER_AUTO_ASK) {
if (!ask_permission("Allow forward to %s:%u? ",
chost, cport)) {
debug2("%s: stdio fwd refused by user", __func__);
/* prepare reply */
buffer_put_int(r, MUX_S_PERMISSION_DENIED);
buffer_put_int(r, rid);
buffer_put_cstring(r, "Permission denied");
goto cleanup;
}
}
/* enable nonblocking unless tty */
if (!isatty(new_fd[0]))
set_nonblock(new_fd[0]);
if (!isatty(new_fd[1]))
set_nonblock(new_fd[1]);
nc = channel_connect_stdio_fwd(chost, cport, new_fd[0], new_fd[1]);
nc->ctl_chan = c->self; /* link session -> control channel */
c->remote_id = nc->self; /* link control -> session channel */
debug2("%s: channel_new: %d linked to control channel %d",
__func__, nc->self, nc->ctl_chan);
channel_register_cleanup(nc->self, mux_master_session_cleanup_cb, 1);
cctx = xcalloc(1, sizeof(*cctx));
cctx->rid = rid;
channel_register_open_confirm(nc->self, mux_stdio_confirm, cctx);
c->mux_pause = 1; /* stop handling messages until open_confirm done */
/* reply is deferred, sent by mux_session_confirm */
return 0;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,487 | process_mux_stop_listening(u_int rid, Channel *c, Buffer *m, Buffer *r)
{
debug("%s: channel %d: stop listening", __func__, c->self);
if (options.control_master == SSHCTL_MASTER_ASK ||
options.control_master == SSHCTL_MASTER_AUTO_ASK) {
if (!ask_permission("Disable further multiplexing on shared "
"connection to %s? ", host)) {
debug2("%s: stop listen refused by user", __func__);
buffer_put_int(r, MUX_S_PERMISSION_DENIED);
buffer_put_int(r, rid);
buffer_put_cstring(r, "Permission denied");
return 0;
}
}
if (mux_listener_channel != NULL) {
channel_free(mux_listener_channel);
client_stop_mux();
free(options.control_path);
options.control_path = NULL;
mux_listener_channel = NULL;
muxserver_sock = -1;
}
/* prepare reply */
buffer_put_int(r, MUX_S_OK);
buffer_put_int(r, rid);
return 0;
}
| null | 0 | process_mux_stop_listening(u_int rid, Channel *c, Buffer *m, Buffer *r)
{
debug("%s: channel %d: stop listening", __func__, c->self);
if (options.control_master == SSHCTL_MASTER_ASK ||
options.control_master == SSHCTL_MASTER_AUTO_ASK) {
if (!ask_permission("Disable further multiplexing on shared "
"connection to %s? ", host)) {
debug2("%s: stop listen refused by user", __func__);
buffer_put_int(r, MUX_S_PERMISSION_DENIED);
buffer_put_int(r, rid);
buffer_put_cstring(r, "Permission denied");
return 0;
}
}
if (mux_listener_channel != NULL) {
channel_free(mux_listener_channel);
client_stop_mux();
free(options.control_path);
options.control_path = NULL;
mux_listener_channel = NULL;
muxserver_sock = -1;
}
/* prepare reply */
buffer_put_int(r, MUX_S_OK);
buffer_put_int(r, rid);
return 0;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: mux.c,v 1.57 2015/12/26 07:46:03 semarie Exp $ */
+/* $OpenBSD: mux.c,v 1.58 2016/01/13 23:04:47 djm Exp $ */
/*
* Copyright (c) 2002-2008 Damien Miller <djm@openbsd.org>
*
@@ -1354,16 +1354,18 @@ mux_session_confirm(int id, int success, void *arg)
char *proto, *data;
/* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
+ if (client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted, options.forward_x11_timeout,
- &proto, &data);
- /* Request forwarding with authentication spoofing. */
- debug("Requesting X11 forwarding with authentication "
- "spoofing.");
- x11_request_forwarding_with_spoofing(id, display, proto,
- data, 1);
- client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
- /* XXX exit_on_forward_failure */
+ &proto, &data) == 0) {
+ /* Request forwarding with authentication spoofing. */
+ debug("Requesting X11 forwarding with authentication "
+ "spoofing.");
+ x11_request_forwarding_with_spoofing(id, display, proto,
+ data, 1);
+ /* XXX exit_on_forward_failure */
+ client_expect_confirm(id, "X11 forwarding",
+ CONFIRM_WARN);
+ }
}
if (cctx->want_agent_fwd && options.forward_agent) { | CWE-254 | null | null |
12,488 | check_agent_present(void)
{
int r;
if (options.forward_agent) {
/* Clear agent forwarding if we don't have an agent. */
if ((r = ssh_get_authentication_socket(NULL)) != 0) {
options.forward_agent = 0;
if (r != SSH_ERR_AGENT_NOT_PRESENT)
debug("ssh_get_authentication_socket: %s",
ssh_err(r));
}
}
}
| null | 0 | check_agent_present(void)
{
int r;
if (options.forward_agent) {
/* Clear agent forwarding if we don't have an agent. */
if ((r = ssh_get_authentication_socket(NULL)) != 0) {
options.forward_agent = 0;
if (r != SSH_ERR_AGENT_NOT_PRESENT)
debug("ssh_get_authentication_socket: %s",
ssh_err(r));
}
}
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: ssh.c,v 1.432 2015/12/11 03:20:09 djm Exp $ */
+/* $OpenBSD: ssh.c,v 1.433 2016/01/13 23:04:47 djm Exp $ */
/*
* Author: Tatu Ylonen <ylo@cs.hut.fi>
* Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
@@ -1626,6 +1626,7 @@ ssh_session(void)
struct winsize ws;
char *cp;
const char *display;
+ char *proto = NULL, *data = NULL;
/* Enable compression if requested. */
if (options.compression) {
@@ -1696,13 +1697,9 @@ ssh_session(void)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout,
- &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing.");
@@ -1792,6 +1789,7 @@ ssh_session2_setup(int id, int success, void *arg)
extern char **environ;
const char *display;
int interactive = tty_flag;
+ char *proto = NULL, *data = NULL;
if (!success)
return; /* No need for error message, channels code sens one */
@@ -1799,12 +1797,9 @@ ssh_session2_setup(int id, int success, void *arg)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout, &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing."); | CWE-254 | null | null |
12,489 | check_follow_cname(char **namep, const char *cname)
{
int i;
struct allowed_cname *rule;
if (*cname == '\0' || options.num_permitted_cnames == 0 ||
strcmp(*namep, cname) == 0)
return 0;
if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
return 0;
/*
* Don't attempt to canonicalize names that will be interpreted by
* a proxy unless the user specifically requests so.
*/
if (!option_clear_or_none(options.proxy_command) &&
options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
return 0;
debug3("%s: check \"%s\" CNAME \"%s\"", __func__, *namep, cname);
for (i = 0; i < options.num_permitted_cnames; i++) {
rule = options.permitted_cnames + i;
if (match_pattern_list(*namep, rule->source_list, 1) != 1 ||
match_pattern_list(cname, rule->target_list, 1) != 1)
continue;
verbose("Canonicalized DNS aliased hostname "
"\"%s\" => \"%s\"", *namep, cname);
free(*namep);
*namep = xstrdup(cname);
return 1;
}
return 0;
}
| null | 0 | check_follow_cname(char **namep, const char *cname)
{
int i;
struct allowed_cname *rule;
if (*cname == '\0' || options.num_permitted_cnames == 0 ||
strcmp(*namep, cname) == 0)
return 0;
if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
return 0;
/*
* Don't attempt to canonicalize names that will be interpreted by
* a proxy unless the user specifically requests so.
*/
if (!option_clear_or_none(options.proxy_command) &&
options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
return 0;
debug3("%s: check \"%s\" CNAME \"%s\"", __func__, *namep, cname);
for (i = 0; i < options.num_permitted_cnames; i++) {
rule = options.permitted_cnames + i;
if (match_pattern_list(*namep, rule->source_list, 1) != 1 ||
match_pattern_list(cname, rule->target_list, 1) != 1)
continue;
verbose("Canonicalized DNS aliased hostname "
"\"%s\" => \"%s\"", *namep, cname);
free(*namep);
*namep = xstrdup(cname);
return 1;
}
return 0;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: ssh.c,v 1.432 2015/12/11 03:20:09 djm Exp $ */
+/* $OpenBSD: ssh.c,v 1.433 2016/01/13 23:04:47 djm Exp $ */
/*
* Author: Tatu Ylonen <ylo@cs.hut.fi>
* Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
@@ -1626,6 +1626,7 @@ ssh_session(void)
struct winsize ws;
char *cp;
const char *display;
+ char *proto = NULL, *data = NULL;
/* Enable compression if requested. */
if (options.compression) {
@@ -1696,13 +1697,9 @@ ssh_session(void)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout,
- &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing.");
@@ -1792,6 +1789,7 @@ ssh_session2_setup(int id, int success, void *arg)
extern char **environ;
const char *display;
int interactive = tty_flag;
+ char *proto = NULL, *data = NULL;
if (!success)
return; /* No need for error message, channels code sens one */
@@ -1799,12 +1797,9 @@ ssh_session2_setup(int id, int success, void *arg)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout, &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing."); | CWE-254 | null | null |
12,490 | client_cleanup_stdio_fwd(int id, void *arg)
{
debug("stdio forwarding: done");
cleanup_exit(0);
}
| null | 0 | client_cleanup_stdio_fwd(int id, void *arg)
{
debug("stdio forwarding: done");
cleanup_exit(0);
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: ssh.c,v 1.432 2015/12/11 03:20:09 djm Exp $ */
+/* $OpenBSD: ssh.c,v 1.433 2016/01/13 23:04:47 djm Exp $ */
/*
* Author: Tatu Ylonen <ylo@cs.hut.fi>
* Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
@@ -1626,6 +1626,7 @@ ssh_session(void)
struct winsize ws;
char *cp;
const char *display;
+ char *proto = NULL, *data = NULL;
/* Enable compression if requested. */
if (options.compression) {
@@ -1696,13 +1697,9 @@ ssh_session(void)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout,
- &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing.");
@@ -1792,6 +1789,7 @@ ssh_session2_setup(int id, int success, void *arg)
extern char **environ;
const char *display;
int interactive = tty_flag;
+ char *proto = NULL, *data = NULL;
if (!success)
return; /* No need for error message, channels code sens one */
@@ -1799,12 +1797,9 @@ ssh_session2_setup(int id, int success, void *arg)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout, &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing."); | CWE-254 | null | null |
12,491 | control_persist_detach(void)
{
pid_t pid;
int devnull;
debug("%s: backgrounding master process", __func__);
/*
* master (current process) into the background, and make the
* foreground process a client of the backgrounded master.
*/
switch ((pid = fork())) {
case -1:
fatal("%s: fork: %s", __func__, strerror(errno));
case 0:
/* Child: master process continues mainloop */
break;
default:
/* Parent: set up mux slave to connect to backgrounded master */
debug2("%s: background process is %ld", __func__, (long)pid);
stdin_null_flag = ostdin_null_flag;
options.request_tty = orequest_tty;
tty_flag = otty_flag;
close(muxserver_sock);
muxserver_sock = -1;
options.control_master = SSHCTL_MASTER_NO;
muxclient(options.control_path);
/* muxclient() doesn't return on success. */
fatal("Failed to connect to new control master");
}
if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
error("%s: open(\"/dev/null\"): %s", __func__,
strerror(errno));
} else {
if (dup2(devnull, STDIN_FILENO) == -1 ||
dup2(devnull, STDOUT_FILENO) == -1)
error("%s: dup2: %s", __func__, strerror(errno));
if (devnull > STDERR_FILENO)
close(devnull);
}
daemon(1, 1);
setproctitle("%s [mux]", options.control_path);
}
| null | 0 | control_persist_detach(void)
{
pid_t pid;
int devnull;
debug("%s: backgrounding master process", __func__);
/*
* master (current process) into the background, and make the
* foreground process a client of the backgrounded master.
*/
switch ((pid = fork())) {
case -1:
fatal("%s: fork: %s", __func__, strerror(errno));
case 0:
/* Child: master process continues mainloop */
break;
default:
/* Parent: set up mux slave to connect to backgrounded master */
debug2("%s: background process is %ld", __func__, (long)pid);
stdin_null_flag = ostdin_null_flag;
options.request_tty = orequest_tty;
tty_flag = otty_flag;
close(muxserver_sock);
muxserver_sock = -1;
options.control_master = SSHCTL_MASTER_NO;
muxclient(options.control_path);
/* muxclient() doesn't return on success. */
fatal("Failed to connect to new control master");
}
if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
error("%s: open(\"/dev/null\"): %s", __func__,
strerror(errno));
} else {
if (dup2(devnull, STDIN_FILENO) == -1 ||
dup2(devnull, STDOUT_FILENO) == -1)
error("%s: dup2: %s", __func__, strerror(errno));
if (devnull > STDERR_FILENO)
close(devnull);
}
daemon(1, 1);
setproctitle("%s [mux]", options.control_path);
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: ssh.c,v 1.432 2015/12/11 03:20:09 djm Exp $ */
+/* $OpenBSD: ssh.c,v 1.433 2016/01/13 23:04:47 djm Exp $ */
/*
* Author: Tatu Ylonen <ylo@cs.hut.fi>
* Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
@@ -1626,6 +1626,7 @@ ssh_session(void)
struct winsize ws;
char *cp;
const char *display;
+ char *proto = NULL, *data = NULL;
/* Enable compression if requested. */
if (options.compression) {
@@ -1696,13 +1697,9 @@ ssh_session(void)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout,
- &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing.");
@@ -1792,6 +1789,7 @@ ssh_session2_setup(int id, int success, void *arg)
extern char **environ;
const char *display;
int interactive = tty_flag;
+ char *proto = NULL, *data = NULL;
if (!success)
return; /* No need for error message, channels code sens one */
@@ -1799,12 +1797,9 @@ ssh_session2_setup(int id, int success, void *arg)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout, &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing."); | CWE-254 | null | null |
12,492 | main(int ac, char **av)
{
int i, r, opt, exit_status, use_syslog, config_test = 0;
char *p, *cp, *line, *argv0, buf[PATH_MAX], *host_arg, *logfile;
char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
char cname[NI_MAXHOST], uidstr[32], *conn_hash_hex;
struct stat st;
struct passwd *pw;
int timeout_ms;
extern int optind, optreset;
extern char *optarg;
struct Forward fwd;
struct addrinfo *addrs = NULL;
struct ssh_digest_ctx *md;
u_char conn_hash[SSH_DIGEST_MAX_LENGTH];
/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
sanitise_stdfd();
__progname = ssh_get_progname(av[0]);
#ifndef HAVE_SETPROCTITLE
/* Prepare for later setproctitle emulation */
/* Save argv so it isn't clobbered by setproctitle() emulation */
saved_av = xcalloc(ac + 1, sizeof(*saved_av));
for (i = 0; i < ac; i++)
saved_av[i] = xstrdup(av[i]);
saved_av[i] = NULL;
compat_init_setproctitle(ac, av);
av = saved_av;
#endif
/*
* Discard other fds that are hanging around. These can cause problem
* with backgrounded ssh processes started by ControlPersist.
*/
closefrom(STDERR_FILENO + 1);
/*
* Save the original real uid. It will be needed later (uid-swapping
* may clobber the real uid).
*/
original_real_uid = getuid();
original_effective_uid = geteuid();
/*
* Use uid-swapping to give up root privileges for the duration of
* option processing. We will re-instantiate the rights when we are
* ready to create the privileged port, and will permanently drop
* them when the port has been created (actually, when the connection
* has been made, as we may need to create the port several times).
*/
PRIV_END;
#ifdef HAVE_SETRLIMIT
/* If we are installed setuid root be careful to not drop core. */
if (original_real_uid != original_effective_uid) {
struct rlimit rlim;
rlim.rlim_cur = rlim.rlim_max = 0;
if (setrlimit(RLIMIT_CORE, &rlim) < 0)
fatal("setrlimit failed: %.100s", strerror(errno));
}
#endif
/* Get user data. */
pw = getpwuid(original_real_uid);
if (!pw) {
logit("No user exists for uid %lu", (u_long)original_real_uid);
exit(255);
}
/* Take a copy of the returned structure. */
pw = pwcopy(pw);
/*
* Set our umask to something reasonable, as some files are created
* with the default umask. This will make them world-readable but
* writable only by the owner, which is ok for all files for which we
* don't set the modes explicitly.
*/
umask(022);
/*
* Initialize option structure to indicate that no values have been
* set.
*/
initialize_options(&options);
/* Parse command-line arguments. */
host = NULL;
use_syslog = 0;
logfile = NULL;
argv0 = av[0];
again:
while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
"ACD:E:F:GI:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
switch (opt) {
case '1':
options.protocol = SSH_PROTO_1;
break;
case '2':
options.protocol = SSH_PROTO_2;
break;
case '4':
options.address_family = AF_INET;
break;
case '6':
options.address_family = AF_INET6;
break;
case 'n':
stdin_null_flag = 1;
break;
case 'f':
fork_after_authentication_flag = 1;
stdin_null_flag = 1;
break;
case 'x':
options.forward_x11 = 0;
break;
case 'X':
options.forward_x11 = 1;
break;
case 'y':
use_syslog = 1;
break;
case 'E':
logfile = optarg;
break;
case 'G':
config_test = 1;
break;
case 'Y':
options.forward_x11 = 1;
options.forward_x11_trusted = 1;
break;
case 'g':
options.fwd_opts.gateway_ports = 1;
break;
case 'O':
if (stdio_forward_host != NULL)
fatal("Cannot specify multiplexing "
"command with -W");
else if (muxclient_command != 0)
fatal("Multiplexing command already specified");
if (strcmp(optarg, "check") == 0)
muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
else if (strcmp(optarg, "forward") == 0)
muxclient_command = SSHMUX_COMMAND_FORWARD;
else if (strcmp(optarg, "exit") == 0)
muxclient_command = SSHMUX_COMMAND_TERMINATE;
else if (strcmp(optarg, "stop") == 0)
muxclient_command = SSHMUX_COMMAND_STOP;
else if (strcmp(optarg, "cancel") == 0)
muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
else
fatal("Invalid multiplex command.");
break;
case 'P': /* deprecated */
options.use_privileged_port = 0;
break;
case 'Q':
cp = NULL;
if (strcmp(optarg, "cipher") == 0)
cp = cipher_alg_list('\n', 0);
else if (strcmp(optarg, "cipher-auth") == 0)
cp = cipher_alg_list('\n', 1);
else if (strcmp(optarg, "mac") == 0)
cp = mac_alg_list('\n');
else if (strcmp(optarg, "kex") == 0)
cp = kex_alg_list('\n');
else if (strcmp(optarg, "key") == 0)
cp = key_alg_list(0, 0);
else if (strcmp(optarg, "key-cert") == 0)
cp = key_alg_list(1, 0);
else if (strcmp(optarg, "key-plain") == 0)
cp = key_alg_list(0, 1);
else if (strcmp(optarg, "protocol-version") == 0) {
#ifdef WITH_SSH1
cp = xstrdup("1\n2");
#else
cp = xstrdup("2");
#endif
}
if (cp == NULL)
fatal("Unsupported query \"%s\"", optarg);
printf("%s\n", cp);
free(cp);
exit(0);
break;
case 'a':
options.forward_agent = 0;
break;
case 'A':
options.forward_agent = 1;
break;
case 'k':
options.gss_deleg_creds = 0;
break;
case 'K':
options.gss_authentication = 1;
options.gss_deleg_creds = 1;
break;
case 'i':
p = tilde_expand_filename(optarg, original_real_uid);
if (stat(p, &st) < 0)
fprintf(stderr, "Warning: Identity file %s "
"not accessible: %s.\n", p,
strerror(errno));
else
add_identity_file(&options, NULL, p, 1);
free(p);
break;
case 'I':
#ifdef ENABLE_PKCS11
free(options.pkcs11_provider);
options.pkcs11_provider = xstrdup(optarg);
#else
fprintf(stderr, "no support for PKCS#11.\n");
#endif
break;
case 't':
if (options.request_tty == REQUEST_TTY_YES)
options.request_tty = REQUEST_TTY_FORCE;
else
options.request_tty = REQUEST_TTY_YES;
break;
case 'v':
if (debug_flag == 0) {
debug_flag = 1;
options.log_level = SYSLOG_LEVEL_DEBUG1;
} else {
if (options.log_level < SYSLOG_LEVEL_DEBUG3)
options.log_level++;
}
break;
case 'V':
fprintf(stderr, "%s, %s\n",
SSH_RELEASE,
#ifdef WITH_OPENSSL
SSLeay_version(SSLEAY_VERSION)
#else
"without OpenSSL"
#endif
);
if (opt == 'V')
exit(0);
break;
case 'w':
if (options.tun_open == -1)
options.tun_open = SSH_TUNMODE_DEFAULT;
options.tun_local = a2tun(optarg, &options.tun_remote);
if (options.tun_local == SSH_TUNID_ERR) {
fprintf(stderr,
"Bad tun device '%s'\n", optarg);
exit(255);
}
break;
case 'W':
if (stdio_forward_host != NULL)
fatal("stdio forward already specified");
if (muxclient_command != 0)
fatal("Cannot specify stdio forward with -O");
if (parse_forward(&fwd, optarg, 1, 0)) {
stdio_forward_host = fwd.listen_host;
stdio_forward_port = fwd.listen_port;
free(fwd.connect_host);
} else {
fprintf(stderr,
"Bad stdio forwarding specification '%s'\n",
optarg);
exit(255);
}
options.request_tty = REQUEST_TTY_NO;
no_shell_flag = 1;
options.clear_forwardings = 1;
options.exit_on_forward_failure = 1;
break;
case 'q':
options.log_level = SYSLOG_LEVEL_QUIET;
break;
case 'e':
if (optarg[0] == '^' && optarg[2] == 0 &&
(u_char) optarg[1] >= 64 &&
(u_char) optarg[1] < 128)
options.escape_char = (u_char) optarg[1] & 31;
else if (strlen(optarg) == 1)
options.escape_char = (u_char) optarg[0];
else if (strcmp(optarg, "none") == 0)
options.escape_char = SSH_ESCAPECHAR_NONE;
else {
fprintf(stderr, "Bad escape character '%s'.\n",
optarg);
exit(255);
}
break;
case 'c':
if (ciphers_valid(*optarg == '+' ?
optarg + 1 : optarg)) {
/* SSH2 only */
free(options.ciphers);
options.ciphers = xstrdup(optarg);
options.cipher = SSH_CIPHER_INVALID;
break;
}
/* SSH1 only */
options.cipher = cipher_number(optarg);
if (options.cipher == -1) {
fprintf(stderr, "Unknown cipher type '%s'\n",
optarg);
exit(255);
}
if (options.cipher == SSH_CIPHER_3DES)
options.ciphers = xstrdup("3des-cbc");
else if (options.cipher == SSH_CIPHER_BLOWFISH)
options.ciphers = xstrdup("blowfish-cbc");
else
options.ciphers = xstrdup(KEX_CLIENT_ENCRYPT);
break;
case 'm':
if (mac_valid(optarg)) {
free(options.macs);
options.macs = xstrdup(optarg);
} else {
fprintf(stderr, "Unknown mac type '%s'\n",
optarg);
exit(255);
}
break;
case 'M':
if (options.control_master == SSHCTL_MASTER_YES)
options.control_master = SSHCTL_MASTER_ASK;
else
options.control_master = SSHCTL_MASTER_YES;
break;
case 'p':
options.port = a2port(optarg);
if (options.port <= 0) {
fprintf(stderr, "Bad port '%s'\n", optarg);
exit(255);
}
break;
case 'l':
options.user = optarg;
break;
case 'L':
if (parse_forward(&fwd, optarg, 0, 0))
add_local_forward(&options, &fwd);
else {
fprintf(stderr,
"Bad local forwarding specification '%s'\n",
optarg);
exit(255);
}
break;
case 'R':
if (parse_forward(&fwd, optarg, 0, 1)) {
add_remote_forward(&options, &fwd);
} else {
fprintf(stderr,
"Bad remote forwarding specification "
"'%s'\n", optarg);
exit(255);
}
break;
case 'D':
if (parse_forward(&fwd, optarg, 1, 0)) {
add_local_forward(&options, &fwd);
} else {
fprintf(stderr,
"Bad dynamic forwarding specification "
"'%s'\n", optarg);
exit(255);
}
break;
case 'C':
options.compression = 1;
break;
case 'N':
no_shell_flag = 1;
options.request_tty = REQUEST_TTY_NO;
break;
case 'T':
options.request_tty = REQUEST_TTY_NO;
break;
case 'o':
line = xstrdup(optarg);
if (process_config_line(&options, pw,
host ? host : "", host ? host : "", line,
"command-line", 0, NULL, SSHCONF_USERCONF) != 0)
exit(255);
free(line);
break;
case 's':
subsystem_flag = 1;
break;
case 'S':
free(options.control_path);
options.control_path = xstrdup(optarg);
break;
case 'b':
options.bind_address = optarg;
break;
case 'F':
config = optarg;
break;
default:
usage();
}
}
ac -= optind;
av += optind;
if (ac > 0 && !host) {
if (strrchr(*av, '@')) {
p = xstrdup(*av);
cp = strrchr(p, '@');
if (cp == NULL || cp == p)
usage();
options.user = p;
*cp = '\0';
host = xstrdup(++cp);
} else
host = xstrdup(*av);
if (ac > 1) {
optind = optreset = 1;
goto again;
}
ac--, av++;
}
/* Check that we got a host name. */
if (!host)
usage();
host_arg = xstrdup(host);
#ifdef WITH_OPENSSL
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
#endif
/* Initialize the command to execute on remote host. */
buffer_init(&command);
/*
* Save the command to execute on the remote host in a buffer. There
* is no limit on the length of the command, except by the maximum
* packet size. Also sets the tty flag if there is no command.
*/
if (!ac) {
/* No command specified - execute shell on a tty. */
if (subsystem_flag) {
fprintf(stderr,
"You must specify a subsystem to invoke.\n");
usage();
}
} else {
/* A command has been specified. Store it into the buffer. */
for (i = 0; i < ac; i++) {
if (i)
buffer_append(&command, " ", 1);
buffer_append(&command, av[i], strlen(av[i]));
}
}
/* Cannot fork to background if no command. */
if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
!no_shell_flag)
fatal("Cannot fork into background without a command "
"to execute.");
/*
* Initialize "log" output. Since we are the client all output
* goes to stderr unless otherwise specified by -y or -E.
*/
if (use_syslog && logfile != NULL)
fatal("Can't specify both -y and -E");
if (logfile != NULL)
log_redirect_stderr_to(logfile);
log_init(argv0,
options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
SYSLOG_FACILITY_USER, !use_syslog);
if (debug_flag)
logit("%s, %s", SSH_RELEASE,
#ifdef WITH_OPENSSL
SSLeay_version(SSLEAY_VERSION)
#else
"without OpenSSL"
#endif
);
/* Parse the configuration files */
process_config_files(host_arg, pw, 0);
/* Hostname canonicalisation needs a few options filled. */
fill_default_options_for_canonicalization(&options);
/* If the user has replaced the hostname then take it into use now */
if (options.hostname != NULL) {
/* NB. Please keep in sync with readconf.c:match_cfg_line() */
cp = percent_expand(options.hostname,
"h", host, (char *)NULL);
free(host);
host = cp;
free(options.hostname);
options.hostname = xstrdup(host);
}
/* If canonicalization requested then try to apply it */
lowercase(host);
if (options.canonicalize_hostname != SSH_CANONICALISE_NO)
addrs = resolve_canonicalize(&host, options.port);
/*
* If CanonicalizePermittedCNAMEs have been specified but
* other canonicalization did not happen (by not being requested
* or by failing with fallback) then the hostname may still be changed
* as a result of CNAME following.
*
* Try to resolve the bare hostname name using the system resolver's
* usual search rules and then apply the CNAME follow rules.
*
* Skip the lookup if a ProxyCommand is being used unless the user
* has specifically requested canonicalisation for this case via
* CanonicalizeHostname=always
*/
if (addrs == NULL && options.num_permitted_cnames != 0 &&
(option_clear_or_none(options.proxy_command) ||
options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
if ((addrs = resolve_host(host, options.port,
option_clear_or_none(options.proxy_command),
cname, sizeof(cname))) == NULL) {
/* Don't fatal proxied host names not in the DNS */
if (option_clear_or_none(options.proxy_command))
cleanup_exit(255); /* logged in resolve_host */
} else
check_follow_cname(&host, cname);
}
/*
* If canonicalisation is enabled then re-parse the configuration
* files as new stanzas may match.
*/
if (options.canonicalize_hostname != 0) {
debug("Re-reading configuration after hostname "
"canonicalisation");
free(options.hostname);
options.hostname = xstrdup(host);
process_config_files(host_arg, pw, 1);
/*
* Address resolution happens early with canonicalisation
* enabled and the port number may have changed since, so
* reset it in address list
*/
if (addrs != NULL && options.port > 0)
set_addrinfo_port(addrs, options.port);
}
/* Fill configuration defaults. */
fill_default_options(&options);
if (options.port == 0)
options.port = default_ssh_port();
channel_set_af(options.address_family);
/* Tidy and check options */
if (options.host_key_alias != NULL)
lowercase(options.host_key_alias);
if (options.proxy_command != NULL &&
strcmp(options.proxy_command, "-") == 0 &&
options.proxy_use_fdpass)
fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
if (options.control_persist &&
options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
debug("UpdateHostKeys=ask is incompatible with ControlPersist; "
"disabling");
options.update_hostkeys = 0;
}
if (options.connection_attempts <= 0)
fatal("Invalid number of ConnectionAttempts");
#ifndef HAVE_CYGWIN
if (original_effective_uid != 0)
options.use_privileged_port = 0;
#endif
/* reinit */
log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
if (options.request_tty == REQUEST_TTY_YES ||
options.request_tty == REQUEST_TTY_FORCE)
tty_flag = 1;
/* Allocate a tty by default if no command specified. */
if (buffer_len(&command) == 0)
tty_flag = options.request_tty != REQUEST_TTY_NO;
/* Force no tty */
if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0)
tty_flag = 0;
/* Do not allocate a tty if stdin is not a tty. */
if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
options.request_tty != REQUEST_TTY_FORCE) {
if (tty_flag)
logit("Pseudo-terminal will not be allocated because "
"stdin is not a terminal.");
tty_flag = 0;
}
seed_rng();
if (options.user == NULL)
options.user = xstrdup(pw->pw_name);
if (gethostname(thishost, sizeof(thishost)) == -1)
fatal("gethostname: %s", strerror(errno));
strlcpy(shorthost, thishost, sizeof(shorthost));
shorthost[strcspn(thishost, ".")] = '\0';
snprintf(portstr, sizeof(portstr), "%d", options.port);
snprintf(uidstr, sizeof(uidstr), "%d", pw->pw_uid);
if ((md = ssh_digest_start(SSH_DIGEST_SHA1)) == NULL ||
ssh_digest_update(md, thishost, strlen(thishost)) < 0 ||
ssh_digest_update(md, host, strlen(host)) < 0 ||
ssh_digest_update(md, portstr, strlen(portstr)) < 0 ||
ssh_digest_update(md, options.user, strlen(options.user)) < 0 ||
ssh_digest_final(md, conn_hash, sizeof(conn_hash)) < 0)
fatal("%s: mux digest failed", __func__);
ssh_digest_free(md);
conn_hash_hex = tohex(conn_hash, ssh_digest_bytes(SSH_DIGEST_SHA1));
if (options.local_command != NULL) {
debug3("expanding LocalCommand: %s", options.local_command);
cp = options.local_command;
options.local_command = percent_expand(cp,
"C", conn_hash_hex,
"L", shorthost,
"d", pw->pw_dir,
"h", host,
"l", thishost,
"n", host_arg,
"p", portstr,
"r", options.user,
"u", pw->pw_name,
(char *)NULL);
debug3("expanded LocalCommand: %s", options.local_command);
free(cp);
}
if (options.control_path != NULL) {
cp = tilde_expand_filename(options.control_path,
original_real_uid);
free(options.control_path);
options.control_path = percent_expand(cp,
"C", conn_hash_hex,
"L", shorthost,
"h", host,
"l", thishost,
"n", host_arg,
"p", portstr,
"r", options.user,
"u", pw->pw_name,
"i", uidstr,
(char *)NULL);
free(cp);
}
free(conn_hash_hex);
if (config_test) {
dump_client_config(&options, host);
exit(0);
}
if (muxclient_command != 0 && options.control_path == NULL)
fatal("No ControlPath specified for \"-O\" command");
if (options.control_path != NULL)
muxclient(options.control_path);
/*
* If hostname canonicalisation was not enabled, then we may not
* have yet resolved the hostname. Do so now.
*/
if (addrs == NULL && options.proxy_command == NULL) {
debug2("resolving \"%s\" port %d", host, options.port);
if ((addrs = resolve_host(host, options.port, 1,
cname, sizeof(cname))) == NULL)
cleanup_exit(255); /* resolve_host logs the error */
}
timeout_ms = options.connection_timeout * 1000;
/* Open a connection to the remote host. */
if (ssh_connect(host, addrs, &hostaddr, options.port,
options.address_family, options.connection_attempts,
&timeout_ms, options.tcp_keep_alive,
options.use_privileged_port) != 0)
exit(255);
if (addrs != NULL)
freeaddrinfo(addrs);
packet_set_timeout(options.server_alive_interval,
options.server_alive_count_max);
if (timeout_ms > 0)
debug3("timeout: %d ms remain after connect", timeout_ms);
/*
* If we successfully made the connection, load the host private key
* in case we will need it later for combined rsa-rhosts
* authentication. This must be done before releasing extra
* privileges, because the file is only readable by root.
* If we cannot access the private keys, load the public keys
* instead and try to execute the ssh-keysign helper instead.
*/
sensitive_data.nkeys = 0;
sensitive_data.keys = NULL;
sensitive_data.external_keysign = 0;
if (options.rhosts_rsa_authentication ||
options.hostbased_authentication) {
sensitive_data.nkeys = 9;
sensitive_data.keys = xcalloc(sensitive_data.nkeys,
sizeof(Key));
for (i = 0; i < sensitive_data.nkeys; i++)
sensitive_data.keys[i] = NULL;
PRIV_START;
#if WITH_SSH1
sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
_PATH_HOST_KEY_FILE, "", NULL, NULL);
#endif
#ifdef OPENSSL_HAS_ECC
sensitive_data.keys[1] = key_load_private_cert(KEY_ECDSA,
_PATH_HOST_ECDSA_KEY_FILE, "", NULL);
#endif
sensitive_data.keys[2] = key_load_private_cert(KEY_ED25519,
_PATH_HOST_ED25519_KEY_FILE, "", NULL);
sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
_PATH_HOST_RSA_KEY_FILE, "", NULL);
sensitive_data.keys[4] = key_load_private_cert(KEY_DSA,
_PATH_HOST_DSA_KEY_FILE, "", NULL);
#ifdef OPENSSL_HAS_ECC
sensitive_data.keys[5] = key_load_private_type(KEY_ECDSA,
_PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
#endif
sensitive_data.keys[6] = key_load_private_type(KEY_ED25519,
_PATH_HOST_ED25519_KEY_FILE, "", NULL, NULL);
sensitive_data.keys[7] = key_load_private_type(KEY_RSA,
_PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
sensitive_data.keys[8] = key_load_private_type(KEY_DSA,
_PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
PRIV_END;
if (options.hostbased_authentication == 1 &&
sensitive_data.keys[0] == NULL &&
sensitive_data.keys[5] == NULL &&
sensitive_data.keys[6] == NULL &&
sensitive_data.keys[7] == NULL &&
sensitive_data.keys[8] == NULL) {
#ifdef OPENSSL_HAS_ECC
sensitive_data.keys[1] = key_load_cert(
_PATH_HOST_ECDSA_KEY_FILE);
#endif
sensitive_data.keys[2] = key_load_cert(
_PATH_HOST_ED25519_KEY_FILE);
sensitive_data.keys[3] = key_load_cert(
_PATH_HOST_RSA_KEY_FILE);
sensitive_data.keys[4] = key_load_cert(
_PATH_HOST_DSA_KEY_FILE);
#ifdef OPENSSL_HAS_ECC
sensitive_data.keys[5] = key_load_public(
_PATH_HOST_ECDSA_KEY_FILE, NULL);
#endif
sensitive_data.keys[6] = key_load_public(
_PATH_HOST_ED25519_KEY_FILE, NULL);
sensitive_data.keys[7] = key_load_public(
_PATH_HOST_RSA_KEY_FILE, NULL);
sensitive_data.keys[8] = key_load_public(
_PATH_HOST_DSA_KEY_FILE, NULL);
sensitive_data.external_keysign = 1;
}
}
/*
* Get rid of any extra privileges that we may have. We will no
* longer need them. Also, extra privileges could make it very hard
* to read identity files and other non-world-readable files from the
* user's home directory if it happens to be on a NFS volume where
* root is mapped to nobody.
*/
if (original_effective_uid == 0) {
PRIV_START;
permanently_set_uid(pw);
}
/*
* Now that we are back to our own permissions, create ~/.ssh
* directory if it doesn't already exist.
*/
if (config == NULL) {
r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) {
#ifdef WITH_SELINUX
ssh_selinux_setfscreatecon(buf);
#endif
if (mkdir(buf, 0700) < 0)
error("Could not create directory '%.200s'.",
buf);
#ifdef WITH_SELINUX
ssh_selinux_setfscreatecon(NULL);
#endif
}
}
/* load options.identity_files */
load_public_identity_files();
/* Expand ~ in known host file names. */
tilde_expand_paths(options.system_hostfiles,
options.num_system_hostfiles);
tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
signal(SIGCHLD, main_sigchld_handler);
/* Log into the remote system. Never returns if the login fails. */
ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
options.port, pw, timeout_ms);
if (packet_connection_is_on_socket()) {
verbose("Authenticated to %s ([%s]:%d).", host,
get_remote_ipaddr(), get_remote_port());
} else {
verbose("Authenticated to %s (via proxy).", host);
}
/* We no longer need the private host keys. Clear them now. */
if (sensitive_data.nkeys != 0) {
for (i = 0; i < sensitive_data.nkeys; i++) {
if (sensitive_data.keys[i] != NULL) {
/* Destroys contents safely */
debug3("clear hostkey %d", i);
key_free(sensitive_data.keys[i]);
sensitive_data.keys[i] = NULL;
}
}
free(sensitive_data.keys);
}
for (i = 0; i < options.num_identity_files; i++) {
free(options.identity_files[i]);
options.identity_files[i] = NULL;
if (options.identity_keys[i]) {
key_free(options.identity_keys[i]);
options.identity_keys[i] = NULL;
}
}
for (i = 0; i < options.num_certificate_files; i++) {
free(options.certificate_files[i]);
options.certificate_files[i] = NULL;
}
exit_status = compat20 ? ssh_session2() : ssh_session();
packet_close();
if (options.control_path != NULL && muxserver_sock != -1)
unlink(options.control_path);
/* Kill ProxyCommand if it is running. */
ssh_kill_proxy_command();
return exit_status;
}
| null | 0 | main(int ac, char **av)
{
int i, r, opt, exit_status, use_syslog, config_test = 0;
char *p, *cp, *line, *argv0, buf[PATH_MAX], *host_arg, *logfile;
char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
char cname[NI_MAXHOST], uidstr[32], *conn_hash_hex;
struct stat st;
struct passwd *pw;
int timeout_ms;
extern int optind, optreset;
extern char *optarg;
struct Forward fwd;
struct addrinfo *addrs = NULL;
struct ssh_digest_ctx *md;
u_char conn_hash[SSH_DIGEST_MAX_LENGTH];
/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
sanitise_stdfd();
__progname = ssh_get_progname(av[0]);
#ifndef HAVE_SETPROCTITLE
/* Prepare for later setproctitle emulation */
/* Save argv so it isn't clobbered by setproctitle() emulation */
saved_av = xcalloc(ac + 1, sizeof(*saved_av));
for (i = 0; i < ac; i++)
saved_av[i] = xstrdup(av[i]);
saved_av[i] = NULL;
compat_init_setproctitle(ac, av);
av = saved_av;
#endif
/*
* Discard other fds that are hanging around. These can cause problem
* with backgrounded ssh processes started by ControlPersist.
*/
closefrom(STDERR_FILENO + 1);
/*
* Save the original real uid. It will be needed later (uid-swapping
* may clobber the real uid).
*/
original_real_uid = getuid();
original_effective_uid = geteuid();
/*
* Use uid-swapping to give up root privileges for the duration of
* option processing. We will re-instantiate the rights when we are
* ready to create the privileged port, and will permanently drop
* them when the port has been created (actually, when the connection
* has been made, as we may need to create the port several times).
*/
PRIV_END;
#ifdef HAVE_SETRLIMIT
/* If we are installed setuid root be careful to not drop core. */
if (original_real_uid != original_effective_uid) {
struct rlimit rlim;
rlim.rlim_cur = rlim.rlim_max = 0;
if (setrlimit(RLIMIT_CORE, &rlim) < 0)
fatal("setrlimit failed: %.100s", strerror(errno));
}
#endif
/* Get user data. */
pw = getpwuid(original_real_uid);
if (!pw) {
logit("No user exists for uid %lu", (u_long)original_real_uid);
exit(255);
}
/* Take a copy of the returned structure. */
pw = pwcopy(pw);
/*
* Set our umask to something reasonable, as some files are created
* with the default umask. This will make them world-readable but
* writable only by the owner, which is ok for all files for which we
* don't set the modes explicitly.
*/
umask(022);
/*
* Initialize option structure to indicate that no values have been
* set.
*/
initialize_options(&options);
/* Parse command-line arguments. */
host = NULL;
use_syslog = 0;
logfile = NULL;
argv0 = av[0];
again:
while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
"ACD:E:F:GI:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
switch (opt) {
case '1':
options.protocol = SSH_PROTO_1;
break;
case '2':
options.protocol = SSH_PROTO_2;
break;
case '4':
options.address_family = AF_INET;
break;
case '6':
options.address_family = AF_INET6;
break;
case 'n':
stdin_null_flag = 1;
break;
case 'f':
fork_after_authentication_flag = 1;
stdin_null_flag = 1;
break;
case 'x':
options.forward_x11 = 0;
break;
case 'X':
options.forward_x11 = 1;
break;
case 'y':
use_syslog = 1;
break;
case 'E':
logfile = optarg;
break;
case 'G':
config_test = 1;
break;
case 'Y':
options.forward_x11 = 1;
options.forward_x11_trusted = 1;
break;
case 'g':
options.fwd_opts.gateway_ports = 1;
break;
case 'O':
if (stdio_forward_host != NULL)
fatal("Cannot specify multiplexing "
"command with -W");
else if (muxclient_command != 0)
fatal("Multiplexing command already specified");
if (strcmp(optarg, "check") == 0)
muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
else if (strcmp(optarg, "forward") == 0)
muxclient_command = SSHMUX_COMMAND_FORWARD;
else if (strcmp(optarg, "exit") == 0)
muxclient_command = SSHMUX_COMMAND_TERMINATE;
else if (strcmp(optarg, "stop") == 0)
muxclient_command = SSHMUX_COMMAND_STOP;
else if (strcmp(optarg, "cancel") == 0)
muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
else
fatal("Invalid multiplex command.");
break;
case 'P': /* deprecated */
options.use_privileged_port = 0;
break;
case 'Q':
cp = NULL;
if (strcmp(optarg, "cipher") == 0)
cp = cipher_alg_list('\n', 0);
else if (strcmp(optarg, "cipher-auth") == 0)
cp = cipher_alg_list('\n', 1);
else if (strcmp(optarg, "mac") == 0)
cp = mac_alg_list('\n');
else if (strcmp(optarg, "kex") == 0)
cp = kex_alg_list('\n');
else if (strcmp(optarg, "key") == 0)
cp = key_alg_list(0, 0);
else if (strcmp(optarg, "key-cert") == 0)
cp = key_alg_list(1, 0);
else if (strcmp(optarg, "key-plain") == 0)
cp = key_alg_list(0, 1);
else if (strcmp(optarg, "protocol-version") == 0) {
#ifdef WITH_SSH1
cp = xstrdup("1\n2");
#else
cp = xstrdup("2");
#endif
}
if (cp == NULL)
fatal("Unsupported query \"%s\"", optarg);
printf("%s\n", cp);
free(cp);
exit(0);
break;
case 'a':
options.forward_agent = 0;
break;
case 'A':
options.forward_agent = 1;
break;
case 'k':
options.gss_deleg_creds = 0;
break;
case 'K':
options.gss_authentication = 1;
options.gss_deleg_creds = 1;
break;
case 'i':
p = tilde_expand_filename(optarg, original_real_uid);
if (stat(p, &st) < 0)
fprintf(stderr, "Warning: Identity file %s "
"not accessible: %s.\n", p,
strerror(errno));
else
add_identity_file(&options, NULL, p, 1);
free(p);
break;
case 'I':
#ifdef ENABLE_PKCS11
free(options.pkcs11_provider);
options.pkcs11_provider = xstrdup(optarg);
#else
fprintf(stderr, "no support for PKCS#11.\n");
#endif
break;
case 't':
if (options.request_tty == REQUEST_TTY_YES)
options.request_tty = REQUEST_TTY_FORCE;
else
options.request_tty = REQUEST_TTY_YES;
break;
case 'v':
if (debug_flag == 0) {
debug_flag = 1;
options.log_level = SYSLOG_LEVEL_DEBUG1;
} else {
if (options.log_level < SYSLOG_LEVEL_DEBUG3)
options.log_level++;
}
break;
case 'V':
fprintf(stderr, "%s, %s\n",
SSH_RELEASE,
#ifdef WITH_OPENSSL
SSLeay_version(SSLEAY_VERSION)
#else
"without OpenSSL"
#endif
);
if (opt == 'V')
exit(0);
break;
case 'w':
if (options.tun_open == -1)
options.tun_open = SSH_TUNMODE_DEFAULT;
options.tun_local = a2tun(optarg, &options.tun_remote);
if (options.tun_local == SSH_TUNID_ERR) {
fprintf(stderr,
"Bad tun device '%s'\n", optarg);
exit(255);
}
break;
case 'W':
if (stdio_forward_host != NULL)
fatal("stdio forward already specified");
if (muxclient_command != 0)
fatal("Cannot specify stdio forward with -O");
if (parse_forward(&fwd, optarg, 1, 0)) {
stdio_forward_host = fwd.listen_host;
stdio_forward_port = fwd.listen_port;
free(fwd.connect_host);
} else {
fprintf(stderr,
"Bad stdio forwarding specification '%s'\n",
optarg);
exit(255);
}
options.request_tty = REQUEST_TTY_NO;
no_shell_flag = 1;
options.clear_forwardings = 1;
options.exit_on_forward_failure = 1;
break;
case 'q':
options.log_level = SYSLOG_LEVEL_QUIET;
break;
case 'e':
if (optarg[0] == '^' && optarg[2] == 0 &&
(u_char) optarg[1] >= 64 &&
(u_char) optarg[1] < 128)
options.escape_char = (u_char) optarg[1] & 31;
else if (strlen(optarg) == 1)
options.escape_char = (u_char) optarg[0];
else if (strcmp(optarg, "none") == 0)
options.escape_char = SSH_ESCAPECHAR_NONE;
else {
fprintf(stderr, "Bad escape character '%s'.\n",
optarg);
exit(255);
}
break;
case 'c':
if (ciphers_valid(*optarg == '+' ?
optarg + 1 : optarg)) {
/* SSH2 only */
free(options.ciphers);
options.ciphers = xstrdup(optarg);
options.cipher = SSH_CIPHER_INVALID;
break;
}
/* SSH1 only */
options.cipher = cipher_number(optarg);
if (options.cipher == -1) {
fprintf(stderr, "Unknown cipher type '%s'\n",
optarg);
exit(255);
}
if (options.cipher == SSH_CIPHER_3DES)
options.ciphers = xstrdup("3des-cbc");
else if (options.cipher == SSH_CIPHER_BLOWFISH)
options.ciphers = xstrdup("blowfish-cbc");
else
options.ciphers = xstrdup(KEX_CLIENT_ENCRYPT);
break;
case 'm':
if (mac_valid(optarg)) {
free(options.macs);
options.macs = xstrdup(optarg);
} else {
fprintf(stderr, "Unknown mac type '%s'\n",
optarg);
exit(255);
}
break;
case 'M':
if (options.control_master == SSHCTL_MASTER_YES)
options.control_master = SSHCTL_MASTER_ASK;
else
options.control_master = SSHCTL_MASTER_YES;
break;
case 'p':
options.port = a2port(optarg);
if (options.port <= 0) {
fprintf(stderr, "Bad port '%s'\n", optarg);
exit(255);
}
break;
case 'l':
options.user = optarg;
break;
case 'L':
if (parse_forward(&fwd, optarg, 0, 0))
add_local_forward(&options, &fwd);
else {
fprintf(stderr,
"Bad local forwarding specification '%s'\n",
optarg);
exit(255);
}
break;
case 'R':
if (parse_forward(&fwd, optarg, 0, 1)) {
add_remote_forward(&options, &fwd);
} else {
fprintf(stderr,
"Bad remote forwarding specification "
"'%s'\n", optarg);
exit(255);
}
break;
case 'D':
if (parse_forward(&fwd, optarg, 1, 0)) {
add_local_forward(&options, &fwd);
} else {
fprintf(stderr,
"Bad dynamic forwarding specification "
"'%s'\n", optarg);
exit(255);
}
break;
case 'C':
options.compression = 1;
break;
case 'N':
no_shell_flag = 1;
options.request_tty = REQUEST_TTY_NO;
break;
case 'T':
options.request_tty = REQUEST_TTY_NO;
break;
case 'o':
line = xstrdup(optarg);
if (process_config_line(&options, pw,
host ? host : "", host ? host : "", line,
"command-line", 0, NULL, SSHCONF_USERCONF) != 0)
exit(255);
free(line);
break;
case 's':
subsystem_flag = 1;
break;
case 'S':
free(options.control_path);
options.control_path = xstrdup(optarg);
break;
case 'b':
options.bind_address = optarg;
break;
case 'F':
config = optarg;
break;
default:
usage();
}
}
ac -= optind;
av += optind;
if (ac > 0 && !host) {
if (strrchr(*av, '@')) {
p = xstrdup(*av);
cp = strrchr(p, '@');
if (cp == NULL || cp == p)
usage();
options.user = p;
*cp = '\0';
host = xstrdup(++cp);
} else
host = xstrdup(*av);
if (ac > 1) {
optind = optreset = 1;
goto again;
}
ac--, av++;
}
/* Check that we got a host name. */
if (!host)
usage();
host_arg = xstrdup(host);
#ifdef WITH_OPENSSL
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
#endif
/* Initialize the command to execute on remote host. */
buffer_init(&command);
/*
* Save the command to execute on the remote host in a buffer. There
* is no limit on the length of the command, except by the maximum
* packet size. Also sets the tty flag if there is no command.
*/
if (!ac) {
/* No command specified - execute shell on a tty. */
if (subsystem_flag) {
fprintf(stderr,
"You must specify a subsystem to invoke.\n");
usage();
}
} else {
/* A command has been specified. Store it into the buffer. */
for (i = 0; i < ac; i++) {
if (i)
buffer_append(&command, " ", 1);
buffer_append(&command, av[i], strlen(av[i]));
}
}
/* Cannot fork to background if no command. */
if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
!no_shell_flag)
fatal("Cannot fork into background without a command "
"to execute.");
/*
* Initialize "log" output. Since we are the client all output
* goes to stderr unless otherwise specified by -y or -E.
*/
if (use_syslog && logfile != NULL)
fatal("Can't specify both -y and -E");
if (logfile != NULL)
log_redirect_stderr_to(logfile);
log_init(argv0,
options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
SYSLOG_FACILITY_USER, !use_syslog);
if (debug_flag)
logit("%s, %s", SSH_RELEASE,
#ifdef WITH_OPENSSL
SSLeay_version(SSLEAY_VERSION)
#else
"without OpenSSL"
#endif
);
/* Parse the configuration files */
process_config_files(host_arg, pw, 0);
/* Hostname canonicalisation needs a few options filled. */
fill_default_options_for_canonicalization(&options);
/* If the user has replaced the hostname then take it into use now */
if (options.hostname != NULL) {
/* NB. Please keep in sync with readconf.c:match_cfg_line() */
cp = percent_expand(options.hostname,
"h", host, (char *)NULL);
free(host);
host = cp;
free(options.hostname);
options.hostname = xstrdup(host);
}
/* If canonicalization requested then try to apply it */
lowercase(host);
if (options.canonicalize_hostname != SSH_CANONICALISE_NO)
addrs = resolve_canonicalize(&host, options.port);
/*
* If CanonicalizePermittedCNAMEs have been specified but
* other canonicalization did not happen (by not being requested
* or by failing with fallback) then the hostname may still be changed
* as a result of CNAME following.
*
* Try to resolve the bare hostname name using the system resolver's
* usual search rules and then apply the CNAME follow rules.
*
* Skip the lookup if a ProxyCommand is being used unless the user
* has specifically requested canonicalisation for this case via
* CanonicalizeHostname=always
*/
if (addrs == NULL && options.num_permitted_cnames != 0 &&
(option_clear_or_none(options.proxy_command) ||
options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
if ((addrs = resolve_host(host, options.port,
option_clear_or_none(options.proxy_command),
cname, sizeof(cname))) == NULL) {
/* Don't fatal proxied host names not in the DNS */
if (option_clear_or_none(options.proxy_command))
cleanup_exit(255); /* logged in resolve_host */
} else
check_follow_cname(&host, cname);
}
/*
* If canonicalisation is enabled then re-parse the configuration
* files as new stanzas may match.
*/
if (options.canonicalize_hostname != 0) {
debug("Re-reading configuration after hostname "
"canonicalisation");
free(options.hostname);
options.hostname = xstrdup(host);
process_config_files(host_arg, pw, 1);
/*
* Address resolution happens early with canonicalisation
* enabled and the port number may have changed since, so
* reset it in address list
*/
if (addrs != NULL && options.port > 0)
set_addrinfo_port(addrs, options.port);
}
/* Fill configuration defaults. */
fill_default_options(&options);
if (options.port == 0)
options.port = default_ssh_port();
channel_set_af(options.address_family);
/* Tidy and check options */
if (options.host_key_alias != NULL)
lowercase(options.host_key_alias);
if (options.proxy_command != NULL &&
strcmp(options.proxy_command, "-") == 0 &&
options.proxy_use_fdpass)
fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
if (options.control_persist &&
options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
debug("UpdateHostKeys=ask is incompatible with ControlPersist; "
"disabling");
options.update_hostkeys = 0;
}
if (options.connection_attempts <= 0)
fatal("Invalid number of ConnectionAttempts");
#ifndef HAVE_CYGWIN
if (original_effective_uid != 0)
options.use_privileged_port = 0;
#endif
/* reinit */
log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
if (options.request_tty == REQUEST_TTY_YES ||
options.request_tty == REQUEST_TTY_FORCE)
tty_flag = 1;
/* Allocate a tty by default if no command specified. */
if (buffer_len(&command) == 0)
tty_flag = options.request_tty != REQUEST_TTY_NO;
/* Force no tty */
if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0)
tty_flag = 0;
/* Do not allocate a tty if stdin is not a tty. */
if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
options.request_tty != REQUEST_TTY_FORCE) {
if (tty_flag)
logit("Pseudo-terminal will not be allocated because "
"stdin is not a terminal.");
tty_flag = 0;
}
seed_rng();
if (options.user == NULL)
options.user = xstrdup(pw->pw_name);
if (gethostname(thishost, sizeof(thishost)) == -1)
fatal("gethostname: %s", strerror(errno));
strlcpy(shorthost, thishost, sizeof(shorthost));
shorthost[strcspn(thishost, ".")] = '\0';
snprintf(portstr, sizeof(portstr), "%d", options.port);
snprintf(uidstr, sizeof(uidstr), "%d", pw->pw_uid);
if ((md = ssh_digest_start(SSH_DIGEST_SHA1)) == NULL ||
ssh_digest_update(md, thishost, strlen(thishost)) < 0 ||
ssh_digest_update(md, host, strlen(host)) < 0 ||
ssh_digest_update(md, portstr, strlen(portstr)) < 0 ||
ssh_digest_update(md, options.user, strlen(options.user)) < 0 ||
ssh_digest_final(md, conn_hash, sizeof(conn_hash)) < 0)
fatal("%s: mux digest failed", __func__);
ssh_digest_free(md);
conn_hash_hex = tohex(conn_hash, ssh_digest_bytes(SSH_DIGEST_SHA1));
if (options.local_command != NULL) {
debug3("expanding LocalCommand: %s", options.local_command);
cp = options.local_command;
options.local_command = percent_expand(cp,
"C", conn_hash_hex,
"L", shorthost,
"d", pw->pw_dir,
"h", host,
"l", thishost,
"n", host_arg,
"p", portstr,
"r", options.user,
"u", pw->pw_name,
(char *)NULL);
debug3("expanded LocalCommand: %s", options.local_command);
free(cp);
}
if (options.control_path != NULL) {
cp = tilde_expand_filename(options.control_path,
original_real_uid);
free(options.control_path);
options.control_path = percent_expand(cp,
"C", conn_hash_hex,
"L", shorthost,
"h", host,
"l", thishost,
"n", host_arg,
"p", portstr,
"r", options.user,
"u", pw->pw_name,
"i", uidstr,
(char *)NULL);
free(cp);
}
free(conn_hash_hex);
if (config_test) {
dump_client_config(&options, host);
exit(0);
}
if (muxclient_command != 0 && options.control_path == NULL)
fatal("No ControlPath specified for \"-O\" command");
if (options.control_path != NULL)
muxclient(options.control_path);
/*
* If hostname canonicalisation was not enabled, then we may not
* have yet resolved the hostname. Do so now.
*/
if (addrs == NULL && options.proxy_command == NULL) {
debug2("resolving \"%s\" port %d", host, options.port);
if ((addrs = resolve_host(host, options.port, 1,
cname, sizeof(cname))) == NULL)
cleanup_exit(255); /* resolve_host logs the error */
}
timeout_ms = options.connection_timeout * 1000;
/* Open a connection to the remote host. */
if (ssh_connect(host, addrs, &hostaddr, options.port,
options.address_family, options.connection_attempts,
&timeout_ms, options.tcp_keep_alive,
options.use_privileged_port) != 0)
exit(255);
if (addrs != NULL)
freeaddrinfo(addrs);
packet_set_timeout(options.server_alive_interval,
options.server_alive_count_max);
if (timeout_ms > 0)
debug3("timeout: %d ms remain after connect", timeout_ms);
/*
* If we successfully made the connection, load the host private key
* in case we will need it later for combined rsa-rhosts
* authentication. This must be done before releasing extra
* privileges, because the file is only readable by root.
* If we cannot access the private keys, load the public keys
* instead and try to execute the ssh-keysign helper instead.
*/
sensitive_data.nkeys = 0;
sensitive_data.keys = NULL;
sensitive_data.external_keysign = 0;
if (options.rhosts_rsa_authentication ||
options.hostbased_authentication) {
sensitive_data.nkeys = 9;
sensitive_data.keys = xcalloc(sensitive_data.nkeys,
sizeof(Key));
for (i = 0; i < sensitive_data.nkeys; i++)
sensitive_data.keys[i] = NULL;
PRIV_START;
#if WITH_SSH1
sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
_PATH_HOST_KEY_FILE, "", NULL, NULL);
#endif
#ifdef OPENSSL_HAS_ECC
sensitive_data.keys[1] = key_load_private_cert(KEY_ECDSA,
_PATH_HOST_ECDSA_KEY_FILE, "", NULL);
#endif
sensitive_data.keys[2] = key_load_private_cert(KEY_ED25519,
_PATH_HOST_ED25519_KEY_FILE, "", NULL);
sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
_PATH_HOST_RSA_KEY_FILE, "", NULL);
sensitive_data.keys[4] = key_load_private_cert(KEY_DSA,
_PATH_HOST_DSA_KEY_FILE, "", NULL);
#ifdef OPENSSL_HAS_ECC
sensitive_data.keys[5] = key_load_private_type(KEY_ECDSA,
_PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
#endif
sensitive_data.keys[6] = key_load_private_type(KEY_ED25519,
_PATH_HOST_ED25519_KEY_FILE, "", NULL, NULL);
sensitive_data.keys[7] = key_load_private_type(KEY_RSA,
_PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
sensitive_data.keys[8] = key_load_private_type(KEY_DSA,
_PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
PRIV_END;
if (options.hostbased_authentication == 1 &&
sensitive_data.keys[0] == NULL &&
sensitive_data.keys[5] == NULL &&
sensitive_data.keys[6] == NULL &&
sensitive_data.keys[7] == NULL &&
sensitive_data.keys[8] == NULL) {
#ifdef OPENSSL_HAS_ECC
sensitive_data.keys[1] = key_load_cert(
_PATH_HOST_ECDSA_KEY_FILE);
#endif
sensitive_data.keys[2] = key_load_cert(
_PATH_HOST_ED25519_KEY_FILE);
sensitive_data.keys[3] = key_load_cert(
_PATH_HOST_RSA_KEY_FILE);
sensitive_data.keys[4] = key_load_cert(
_PATH_HOST_DSA_KEY_FILE);
#ifdef OPENSSL_HAS_ECC
sensitive_data.keys[5] = key_load_public(
_PATH_HOST_ECDSA_KEY_FILE, NULL);
#endif
sensitive_data.keys[6] = key_load_public(
_PATH_HOST_ED25519_KEY_FILE, NULL);
sensitive_data.keys[7] = key_load_public(
_PATH_HOST_RSA_KEY_FILE, NULL);
sensitive_data.keys[8] = key_load_public(
_PATH_HOST_DSA_KEY_FILE, NULL);
sensitive_data.external_keysign = 1;
}
}
/*
* Get rid of any extra privileges that we may have. We will no
* longer need them. Also, extra privileges could make it very hard
* to read identity files and other non-world-readable files from the
* user's home directory if it happens to be on a NFS volume where
* root is mapped to nobody.
*/
if (original_effective_uid == 0) {
PRIV_START;
permanently_set_uid(pw);
}
/*
* Now that we are back to our own permissions, create ~/.ssh
* directory if it doesn't already exist.
*/
if (config == NULL) {
r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) {
#ifdef WITH_SELINUX
ssh_selinux_setfscreatecon(buf);
#endif
if (mkdir(buf, 0700) < 0)
error("Could not create directory '%.200s'.",
buf);
#ifdef WITH_SELINUX
ssh_selinux_setfscreatecon(NULL);
#endif
}
}
/* load options.identity_files */
load_public_identity_files();
/* Expand ~ in known host file names. */
tilde_expand_paths(options.system_hostfiles,
options.num_system_hostfiles);
tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
signal(SIGCHLD, main_sigchld_handler);
/* Log into the remote system. Never returns if the login fails. */
ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
options.port, pw, timeout_ms);
if (packet_connection_is_on_socket()) {
verbose("Authenticated to %s ([%s]:%d).", host,
get_remote_ipaddr(), get_remote_port());
} else {
verbose("Authenticated to %s (via proxy).", host);
}
/* We no longer need the private host keys. Clear them now. */
if (sensitive_data.nkeys != 0) {
for (i = 0; i < sensitive_data.nkeys; i++) {
if (sensitive_data.keys[i] != NULL) {
/* Destroys contents safely */
debug3("clear hostkey %d", i);
key_free(sensitive_data.keys[i]);
sensitive_data.keys[i] = NULL;
}
}
free(sensitive_data.keys);
}
for (i = 0; i < options.num_identity_files; i++) {
free(options.identity_files[i]);
options.identity_files[i] = NULL;
if (options.identity_keys[i]) {
key_free(options.identity_keys[i]);
options.identity_keys[i] = NULL;
}
}
for (i = 0; i < options.num_certificate_files; i++) {
free(options.certificate_files[i]);
options.certificate_files[i] = NULL;
}
exit_status = compat20 ? ssh_session2() : ssh_session();
packet_close();
if (options.control_path != NULL && muxserver_sock != -1)
unlink(options.control_path);
/* Kill ProxyCommand if it is running. */
ssh_kill_proxy_command();
return exit_status;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: ssh.c,v 1.432 2015/12/11 03:20:09 djm Exp $ */
+/* $OpenBSD: ssh.c,v 1.433 2016/01/13 23:04:47 djm Exp $ */
/*
* Author: Tatu Ylonen <ylo@cs.hut.fi>
* Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
@@ -1626,6 +1626,7 @@ ssh_session(void)
struct winsize ws;
char *cp;
const char *display;
+ char *proto = NULL, *data = NULL;
/* Enable compression if requested. */
if (options.compression) {
@@ -1696,13 +1697,9 @@ ssh_session(void)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout,
- &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing.");
@@ -1792,6 +1789,7 @@ ssh_session2_setup(int id, int success, void *arg)
extern char **environ;
const char *display;
int interactive = tty_flag;
+ char *proto = NULL, *data = NULL;
if (!success)
return; /* No need for error message, channels code sens one */
@@ -1799,12 +1797,9 @@ ssh_session2_setup(int id, int success, void *arg)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout, &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing."); | CWE-254 | null | null |
12,493 | process_config_files(const char *host_arg, struct passwd *pw, int post_canon)
{
char buf[PATH_MAX];
int r;
if (config != NULL) {
if (strcasecmp(config, "none") != 0 &&
!read_config_file(config, pw, host, host_arg, &options,
SSHCONF_USERCONF | (post_canon ? SSHCONF_POSTCANON : 0)))
fatal("Can't open user config file %.100s: "
"%.100s", config, strerror(errno));
} else {
r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
_PATH_SSH_USER_CONFFILE);
if (r > 0 && (size_t)r < sizeof(buf))
(void)read_config_file(buf, pw, host, host_arg,
&options, SSHCONF_CHECKPERM | SSHCONF_USERCONF |
(post_canon ? SSHCONF_POSTCANON : 0));
/* Read systemwide configuration file after user config. */
(void)read_config_file(_PATH_HOST_CONFIG_FILE, pw,
host, host_arg, &options,
post_canon ? SSHCONF_POSTCANON : 0);
}
}
| null | 0 | process_config_files(const char *host_arg, struct passwd *pw, int post_canon)
{
char buf[PATH_MAX];
int r;
if (config != NULL) {
if (strcasecmp(config, "none") != 0 &&
!read_config_file(config, pw, host, host_arg, &options,
SSHCONF_USERCONF | (post_canon ? SSHCONF_POSTCANON : 0)))
fatal("Can't open user config file %.100s: "
"%.100s", config, strerror(errno));
} else {
r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
_PATH_SSH_USER_CONFFILE);
if (r > 0 && (size_t)r < sizeof(buf))
(void)read_config_file(buf, pw, host, host_arg,
&options, SSHCONF_CHECKPERM | SSHCONF_USERCONF |
(post_canon ? SSHCONF_POSTCANON : 0));
/* Read systemwide configuration file after user config. */
(void)read_config_file(_PATH_HOST_CONFIG_FILE, pw,
host, host_arg, &options,
post_canon ? SSHCONF_POSTCANON : 0);
}
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: ssh.c,v 1.432 2015/12/11 03:20:09 djm Exp $ */
+/* $OpenBSD: ssh.c,v 1.433 2016/01/13 23:04:47 djm Exp $ */
/*
* Author: Tatu Ylonen <ylo@cs.hut.fi>
* Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
@@ -1626,6 +1626,7 @@ ssh_session(void)
struct winsize ws;
char *cp;
const char *display;
+ char *proto = NULL, *data = NULL;
/* Enable compression if requested. */
if (options.compression) {
@@ -1696,13 +1697,9 @@ ssh_session(void)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout,
- &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing.");
@@ -1792,6 +1789,7 @@ ssh_session2_setup(int id, int success, void *arg)
extern char **environ;
const char *display;
int interactive = tty_flag;
+ char *proto = NULL, *data = NULL;
if (!success)
return; /* No need for error message, channels code sens one */
@@ -1799,12 +1797,9 @@ ssh_session2_setup(int id, int success, void *arg)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout, &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing."); | CWE-254 | null | null |
12,494 | resolve_canonicalize(char **hostp, int port)
{
int i, ndots;
char *cp, *fullhost, newname[NI_MAXHOST];
struct addrinfo *addrs;
if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
return NULL;
/*
* Don't attempt to canonicalize names that will be interpreted by
* a proxy unless the user specifically requests so.
*/
if (!option_clear_or_none(options.proxy_command) &&
options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
return NULL;
/* Try numeric hostnames first */
if ((addrs = resolve_addr(*hostp, port,
newname, sizeof(newname))) != NULL) {
debug2("%s: hostname %.100s is address", __func__, *hostp);
if (strcasecmp(*hostp, newname) != 0) {
debug2("%s: canonicalised address \"%s\" => \"%s\"",
__func__, *hostp, newname);
free(*hostp);
*hostp = xstrdup(newname);
}
return addrs;
}
/* If domain name is anchored, then resolve it now */
if ((*hostp)[strlen(*hostp) - 1] == '.') {
debug3("%s: name is fully qualified", __func__);
fullhost = xstrdup(*hostp);
if ((addrs = resolve_host(fullhost, port, 0,
newname, sizeof(newname))) != NULL)
goto found;
free(fullhost);
goto notfound;
}
/* Don't apply canonicalization to sufficiently-qualified hostnames */
ndots = 0;
for (cp = *hostp; *cp != '\0'; cp++) {
if (*cp == '.')
ndots++;
}
if (ndots > options.canonicalize_max_dots) {
debug3("%s: not canonicalizing hostname \"%s\" (max dots %d)",
__func__, *hostp, options.canonicalize_max_dots);
return NULL;
}
/* Attempt each supplied suffix */
for (i = 0; i < options.num_canonical_domains; i++) {
*newname = '\0';
xasprintf(&fullhost, "%s.%s.", *hostp,
options.canonical_domains[i]);
debug3("%s: attempting \"%s\" => \"%s\"", __func__,
*hostp, fullhost);
if ((addrs = resolve_host(fullhost, port, 0,
newname, sizeof(newname))) == NULL) {
free(fullhost);
continue;
}
found:
/* Remove trailing '.' */
fullhost[strlen(fullhost) - 1] = '\0';
/* Follow CNAME if requested */
if (!check_follow_cname(&fullhost, newname)) {
debug("Canonicalized hostname \"%s\" => \"%s\"",
*hostp, fullhost);
}
free(*hostp);
*hostp = fullhost;
return addrs;
}
notfound:
if (!options.canonicalize_fallback_local)
fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
debug2("%s: host %s not found in any suffix", __func__, *hostp);
return NULL;
}
| null | 0 | resolve_canonicalize(char **hostp, int port)
{
int i, ndots;
char *cp, *fullhost, newname[NI_MAXHOST];
struct addrinfo *addrs;
if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
return NULL;
/*
* Don't attempt to canonicalize names that will be interpreted by
* a proxy unless the user specifically requests so.
*/
if (!option_clear_or_none(options.proxy_command) &&
options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
return NULL;
/* Try numeric hostnames first */
if ((addrs = resolve_addr(*hostp, port,
newname, sizeof(newname))) != NULL) {
debug2("%s: hostname %.100s is address", __func__, *hostp);
if (strcasecmp(*hostp, newname) != 0) {
debug2("%s: canonicalised address \"%s\" => \"%s\"",
__func__, *hostp, newname);
free(*hostp);
*hostp = xstrdup(newname);
}
return addrs;
}
/* If domain name is anchored, then resolve it now */
if ((*hostp)[strlen(*hostp) - 1] == '.') {
debug3("%s: name is fully qualified", __func__);
fullhost = xstrdup(*hostp);
if ((addrs = resolve_host(fullhost, port, 0,
newname, sizeof(newname))) != NULL)
goto found;
free(fullhost);
goto notfound;
}
/* Don't apply canonicalization to sufficiently-qualified hostnames */
ndots = 0;
for (cp = *hostp; *cp != '\0'; cp++) {
if (*cp == '.')
ndots++;
}
if (ndots > options.canonicalize_max_dots) {
debug3("%s: not canonicalizing hostname \"%s\" (max dots %d)",
__func__, *hostp, options.canonicalize_max_dots);
return NULL;
}
/* Attempt each supplied suffix */
for (i = 0; i < options.num_canonical_domains; i++) {
*newname = '\0';
xasprintf(&fullhost, "%s.%s.", *hostp,
options.canonical_domains[i]);
debug3("%s: attempting \"%s\" => \"%s\"", __func__,
*hostp, fullhost);
if ((addrs = resolve_host(fullhost, port, 0,
newname, sizeof(newname))) == NULL) {
free(fullhost);
continue;
}
found:
/* Remove trailing '.' */
fullhost[strlen(fullhost) - 1] = '\0';
/* Follow CNAME if requested */
if (!check_follow_cname(&fullhost, newname)) {
debug("Canonicalized hostname \"%s\" => \"%s\"",
*hostp, fullhost);
}
free(*hostp);
*hostp = fullhost;
return addrs;
}
notfound:
if (!options.canonicalize_fallback_local)
fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
debug2("%s: host %s not found in any suffix", __func__, *hostp);
return NULL;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: ssh.c,v 1.432 2015/12/11 03:20:09 djm Exp $ */
+/* $OpenBSD: ssh.c,v 1.433 2016/01/13 23:04:47 djm Exp $ */
/*
* Author: Tatu Ylonen <ylo@cs.hut.fi>
* Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
@@ -1626,6 +1626,7 @@ ssh_session(void)
struct winsize ws;
char *cp;
const char *display;
+ char *proto = NULL, *data = NULL;
/* Enable compression if requested. */
if (options.compression) {
@@ -1696,13 +1697,9 @@ ssh_session(void)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout,
- &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing.");
@@ -1792,6 +1789,7 @@ ssh_session2_setup(int id, int success, void *arg)
extern char **environ;
const char *display;
int interactive = tty_flag;
+ char *proto = NULL, *data = NULL;
if (!success)
return; /* No need for error message, channels code sens one */
@@ -1799,12 +1797,9 @@ ssh_session2_setup(int id, int success, void *arg)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout, &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing."); | CWE-254 | null | null |
12,495 | resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
{
char strport[NI_MAXSERV];
struct addrinfo hints, *res;
int gaierr, loglevel = SYSLOG_LEVEL_DEBUG1;
if (port <= 0)
port = default_ssh_port();
snprintf(strport, sizeof strport, "%d", port);
memset(&hints, 0, sizeof(hints));
hints.ai_family = options.address_family == -1 ?
AF_UNSPEC : options.address_family;
hints.ai_socktype = SOCK_STREAM;
if (cname != NULL)
hints.ai_flags = AI_CANONNAME;
if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
loglevel = SYSLOG_LEVEL_ERROR;
do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
__progname, name, ssh_gai_strerror(gaierr));
return NULL;
}
if (cname != NULL && res->ai_canonname != NULL) {
if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
error("%s: host \"%s\" cname \"%s\" too long (max %lu)",
__func__, name, res->ai_canonname, (u_long)clen);
if (clen > 0)
*cname = '\0';
}
}
return res;
}
| null | 0 | resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
{
char strport[NI_MAXSERV];
struct addrinfo hints, *res;
int gaierr, loglevel = SYSLOG_LEVEL_DEBUG1;
if (port <= 0)
port = default_ssh_port();
snprintf(strport, sizeof strport, "%d", port);
memset(&hints, 0, sizeof(hints));
hints.ai_family = options.address_family == -1 ?
AF_UNSPEC : options.address_family;
hints.ai_socktype = SOCK_STREAM;
if (cname != NULL)
hints.ai_flags = AI_CANONNAME;
if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
loglevel = SYSLOG_LEVEL_ERROR;
do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
__progname, name, ssh_gai_strerror(gaierr));
return NULL;
}
if (cname != NULL && res->ai_canonname != NULL) {
if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
error("%s: host \"%s\" cname \"%s\" too long (max %lu)",
__func__, name, res->ai_canonname, (u_long)clen);
if (clen > 0)
*cname = '\0';
}
}
return res;
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: ssh.c,v 1.432 2015/12/11 03:20:09 djm Exp $ */
+/* $OpenBSD: ssh.c,v 1.433 2016/01/13 23:04:47 djm Exp $ */
/*
* Author: Tatu Ylonen <ylo@cs.hut.fi>
* Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
@@ -1626,6 +1626,7 @@ ssh_session(void)
struct winsize ws;
char *cp;
const char *display;
+ char *proto = NULL, *data = NULL;
/* Enable compression if requested. */
if (options.compression) {
@@ -1696,13 +1697,9 @@ ssh_session(void)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout,
- &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing.");
@@ -1792,6 +1789,7 @@ ssh_session2_setup(int id, int success, void *arg)
extern char **environ;
const char *display;
int interactive = tty_flag;
+ char *proto = NULL, *data = NULL;
if (!success)
return; /* No need for error message, channels code sens one */
@@ -1799,12 +1797,9 @@ ssh_session2_setup(int id, int success, void *arg)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout, &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing."); | CWE-254 | null | null |
12,496 | set_addrinfo_port(struct addrinfo *addrs, int port)
{
struct addrinfo *addr;
for (addr = addrs; addr != NULL; addr = addr->ai_next) {
switch (addr->ai_family) {
case AF_INET:
((struct sockaddr_in *)addr->ai_addr)->
sin_port = htons(port);
break;
case AF_INET6:
((struct sockaddr_in6 *)addr->ai_addr)->
sin6_port = htons(port);
break;
}
}
}
| null | 0 | set_addrinfo_port(struct addrinfo *addrs, int port)
{
struct addrinfo *addr;
for (addr = addrs; addr != NULL; addr = addr->ai_next) {
switch (addr->ai_family) {
case AF_INET:
((struct sockaddr_in *)addr->ai_addr)->
sin_port = htons(port);
break;
case AF_INET6:
((struct sockaddr_in6 *)addr->ai_addr)->
sin6_port = htons(port);
break;
}
}
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: ssh.c,v 1.432 2015/12/11 03:20:09 djm Exp $ */
+/* $OpenBSD: ssh.c,v 1.433 2016/01/13 23:04:47 djm Exp $ */
/*
* Author: Tatu Ylonen <ylo@cs.hut.fi>
* Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
@@ -1626,6 +1626,7 @@ ssh_session(void)
struct winsize ws;
char *cp;
const char *display;
+ char *proto = NULL, *data = NULL;
/* Enable compression if requested. */
if (options.compression) {
@@ -1696,13 +1697,9 @@ ssh_session(void)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout,
- &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing.");
@@ -1792,6 +1789,7 @@ ssh_session2_setup(int id, int success, void *arg)
extern char **environ;
const char *display;
int interactive = tty_flag;
+ char *proto = NULL, *data = NULL;
if (!success)
return; /* No need for error message, channels code sens one */
@@ -1799,12 +1797,9 @@ ssh_session2_setup(int id, int success, void *arg)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout, &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing."); | CWE-254 | null | null |
12,497 | ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
{
struct Forward *rfwd = (struct Forward *)ctxt;
/* XXX verbose() on failure? */
debug("remote forward %s for: listen %s%s%d, connect %s:%d",
type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
rfwd->listen_path ? rfwd->listen_path :
rfwd->listen_host ? rfwd->listen_host : "",
(rfwd->listen_path || rfwd->listen_host) ? ":" : "",
rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
rfwd->connect_host, rfwd->connect_port);
if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
if (type == SSH2_MSG_REQUEST_SUCCESS) {
rfwd->allocated_port = packet_get_int();
logit("Allocated port %u for remote forward to %s:%d",
rfwd->allocated_port,
rfwd->connect_host, rfwd->connect_port);
channel_update_permitted_opens(rfwd->handle,
rfwd->allocated_port);
} else {
channel_update_permitted_opens(rfwd->handle, -1);
}
}
if (type == SSH2_MSG_REQUEST_FAILURE) {
if (options.exit_on_forward_failure) {
if (rfwd->listen_path != NULL)
fatal("Error: remote port forwarding failed "
"for listen path %s", rfwd->listen_path);
else
fatal("Error: remote port forwarding failed "
"for listen port %d", rfwd->listen_port);
} else {
if (rfwd->listen_path != NULL)
logit("Warning: remote port forwarding failed "
"for listen path %s", rfwd->listen_path);
else
logit("Warning: remote port forwarding failed "
"for listen port %d", rfwd->listen_port);
}
}
if (++remote_forward_confirms_received == options.num_remote_forwards) {
debug("All remote forwarding requests processed");
if (fork_after_authentication_flag)
fork_postauth();
}
}
| null | 0 | ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
{
struct Forward *rfwd = (struct Forward *)ctxt;
/* XXX verbose() on failure? */
debug("remote forward %s for: listen %s%s%d, connect %s:%d",
type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
rfwd->listen_path ? rfwd->listen_path :
rfwd->listen_host ? rfwd->listen_host : "",
(rfwd->listen_path || rfwd->listen_host) ? ":" : "",
rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
rfwd->connect_host, rfwd->connect_port);
if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
if (type == SSH2_MSG_REQUEST_SUCCESS) {
rfwd->allocated_port = packet_get_int();
logit("Allocated port %u for remote forward to %s:%d",
rfwd->allocated_port,
rfwd->connect_host, rfwd->connect_port);
channel_update_permitted_opens(rfwd->handle,
rfwd->allocated_port);
} else {
channel_update_permitted_opens(rfwd->handle, -1);
}
}
if (type == SSH2_MSG_REQUEST_FAILURE) {
if (options.exit_on_forward_failure) {
if (rfwd->listen_path != NULL)
fatal("Error: remote port forwarding failed "
"for listen path %s", rfwd->listen_path);
else
fatal("Error: remote port forwarding failed "
"for listen port %d", rfwd->listen_port);
} else {
if (rfwd->listen_path != NULL)
logit("Warning: remote port forwarding failed "
"for listen path %s", rfwd->listen_path);
else
logit("Warning: remote port forwarding failed "
"for listen port %d", rfwd->listen_port);
}
}
if (++remote_forward_confirms_received == options.num_remote_forwards) {
debug("All remote forwarding requests processed");
if (fork_after_authentication_flag)
fork_postauth();
}
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: ssh.c,v 1.432 2015/12/11 03:20:09 djm Exp $ */
+/* $OpenBSD: ssh.c,v 1.433 2016/01/13 23:04:47 djm Exp $ */
/*
* Author: Tatu Ylonen <ylo@cs.hut.fi>
* Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
@@ -1626,6 +1626,7 @@ ssh_session(void)
struct winsize ws;
char *cp;
const char *display;
+ char *proto = NULL, *data = NULL;
/* Enable compression if requested. */
if (options.compression) {
@@ -1696,13 +1697,9 @@ ssh_session(void)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout,
- &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing.");
@@ -1792,6 +1789,7 @@ ssh_session2_setup(int id, int success, void *arg)
extern char **environ;
const char *display;
int interactive = tty_flag;
+ char *proto = NULL, *data = NULL;
if (!success)
return; /* No need for error message, channels code sens one */
@@ -1799,12 +1797,9 @@ ssh_session2_setup(int id, int success, void *arg)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout, &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing."); | CWE-254 | null | null |
12,498 | ssh_init_forwarding(void)
{
int success = 0;
int i;
/* Initiate local TCP/IP port forwardings. */
for (i = 0; i < options.num_local_forwards; i++) {
debug("Local connections to %.200s:%d forwarded to remote "
"address %.200s:%d",
(options.local_forwards[i].listen_path != NULL) ?
options.local_forwards[i].listen_path :
(options.local_forwards[i].listen_host == NULL) ?
(options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
options.local_forwards[i].listen_host,
options.local_forwards[i].listen_port,
(options.local_forwards[i].connect_path != NULL) ?
options.local_forwards[i].connect_path :
options.local_forwards[i].connect_host,
options.local_forwards[i].connect_port);
success += channel_setup_local_fwd_listener(
&options.local_forwards[i], &options.fwd_opts);
}
if (i > 0 && success != i && options.exit_on_forward_failure)
fatal("Could not request local forwarding.");
if (i > 0 && success == 0)
error("Could not request local forwarding.");
/* Initiate remote TCP/IP port forwardings. */
for (i = 0; i < options.num_remote_forwards; i++) {
debug("Remote connections from %.200s:%d forwarded to "
"local address %.200s:%d",
(options.remote_forwards[i].listen_path != NULL) ?
options.remote_forwards[i].listen_path :
(options.remote_forwards[i].listen_host == NULL) ?
"LOCALHOST" : options.remote_forwards[i].listen_host,
options.remote_forwards[i].listen_port,
(options.remote_forwards[i].connect_path != NULL) ?
options.remote_forwards[i].connect_path :
options.remote_forwards[i].connect_host,
options.remote_forwards[i].connect_port);
options.remote_forwards[i].handle =
channel_request_remote_forwarding(
&options.remote_forwards[i]);
if (options.remote_forwards[i].handle < 0) {
if (options.exit_on_forward_failure)
fatal("Could not request remote forwarding.");
else
logit("Warning: Could not request remote "
"forwarding.");
} else {
client_register_global_confirm(ssh_confirm_remote_forward,
&options.remote_forwards[i]);
}
}
/* Initiate tunnel forwarding. */
if (options.tun_open != SSH_TUNMODE_NO) {
if (client_request_tun_fwd(options.tun_open,
options.tun_local, options.tun_remote) == -1) {
if (options.exit_on_forward_failure)
fatal("Could not request tunnel forwarding.");
else
error("Could not request tunnel forwarding.");
}
}
}
| null | 0 | ssh_init_forwarding(void)
{
int success = 0;
int i;
/* Initiate local TCP/IP port forwardings. */
for (i = 0; i < options.num_local_forwards; i++) {
debug("Local connections to %.200s:%d forwarded to remote "
"address %.200s:%d",
(options.local_forwards[i].listen_path != NULL) ?
options.local_forwards[i].listen_path :
(options.local_forwards[i].listen_host == NULL) ?
(options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
options.local_forwards[i].listen_host,
options.local_forwards[i].listen_port,
(options.local_forwards[i].connect_path != NULL) ?
options.local_forwards[i].connect_path :
options.local_forwards[i].connect_host,
options.local_forwards[i].connect_port);
success += channel_setup_local_fwd_listener(
&options.local_forwards[i], &options.fwd_opts);
}
if (i > 0 && success != i && options.exit_on_forward_failure)
fatal("Could not request local forwarding.");
if (i > 0 && success == 0)
error("Could not request local forwarding.");
/* Initiate remote TCP/IP port forwardings. */
for (i = 0; i < options.num_remote_forwards; i++) {
debug("Remote connections from %.200s:%d forwarded to "
"local address %.200s:%d",
(options.remote_forwards[i].listen_path != NULL) ?
options.remote_forwards[i].listen_path :
(options.remote_forwards[i].listen_host == NULL) ?
"LOCALHOST" : options.remote_forwards[i].listen_host,
options.remote_forwards[i].listen_port,
(options.remote_forwards[i].connect_path != NULL) ?
options.remote_forwards[i].connect_path :
options.remote_forwards[i].connect_host,
options.remote_forwards[i].connect_port);
options.remote_forwards[i].handle =
channel_request_remote_forwarding(
&options.remote_forwards[i]);
if (options.remote_forwards[i].handle < 0) {
if (options.exit_on_forward_failure)
fatal("Could not request remote forwarding.");
else
logit("Warning: Could not request remote "
"forwarding.");
} else {
client_register_global_confirm(ssh_confirm_remote_forward,
&options.remote_forwards[i]);
}
}
/* Initiate tunnel forwarding. */
if (options.tun_open != SSH_TUNMODE_NO) {
if (client_request_tun_fwd(options.tun_open,
options.tun_local, options.tun_remote) == -1) {
if (options.exit_on_forward_failure)
fatal("Could not request tunnel forwarding.");
else
error("Could not request tunnel forwarding.");
}
}
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: ssh.c,v 1.432 2015/12/11 03:20:09 djm Exp $ */
+/* $OpenBSD: ssh.c,v 1.433 2016/01/13 23:04:47 djm Exp $ */
/*
* Author: Tatu Ylonen <ylo@cs.hut.fi>
* Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
@@ -1626,6 +1626,7 @@ ssh_session(void)
struct winsize ws;
char *cp;
const char *display;
+ char *proto = NULL, *data = NULL;
/* Enable compression if requested. */
if (options.compression) {
@@ -1696,13 +1697,9 @@ ssh_session(void)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout,
- &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing.");
@@ -1792,6 +1789,7 @@ ssh_session2_setup(int id, int success, void *arg)
extern char **environ;
const char *display;
int interactive = tty_flag;
+ char *proto = NULL, *data = NULL;
if (!success)
return; /* No need for error message, channels code sens one */
@@ -1799,12 +1797,9 @@ ssh_session2_setup(int id, int success, void *arg)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout, &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing."); | CWE-254 | null | null |
12,499 | ssh_init_stdio_forwarding(void)
{
Channel *c;
int in, out;
if (stdio_forward_host == NULL)
return;
if (!compat20)
fatal("stdio forwarding require Protocol 2");
debug3("%s: %s:%d", __func__, stdio_forward_host, stdio_forward_port);
if ((in = dup(STDIN_FILENO)) < 0 ||
(out = dup(STDOUT_FILENO)) < 0)
fatal("channel_connect_stdio_fwd: dup() in/out failed");
if ((c = channel_connect_stdio_fwd(stdio_forward_host,
stdio_forward_port, in, out)) == NULL)
fatal("%s: channel_connect_stdio_fwd failed", __func__);
channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
channel_register_open_confirm(c->self, ssh_stdio_confirm, NULL);
}
| null | 0 | ssh_init_stdio_forwarding(void)
{
Channel *c;
int in, out;
if (stdio_forward_host == NULL)
return;
if (!compat20)
fatal("stdio forwarding require Protocol 2");
debug3("%s: %s:%d", __func__, stdio_forward_host, stdio_forward_port);
if ((in = dup(STDIN_FILENO)) < 0 ||
(out = dup(STDOUT_FILENO)) < 0)
fatal("channel_connect_stdio_fwd: dup() in/out failed");
if ((c = channel_connect_stdio_fwd(stdio_forward_host,
stdio_forward_port, in, out)) == NULL)
fatal("%s: channel_connect_stdio_fwd failed", __func__);
channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
channel_register_open_confirm(c->self, ssh_stdio_confirm, NULL);
}
| @@ -1,4 +1,4 @@
-/* $OpenBSD: ssh.c,v 1.432 2015/12/11 03:20:09 djm Exp $ */
+/* $OpenBSD: ssh.c,v 1.433 2016/01/13 23:04:47 djm Exp $ */
/*
* Author: Tatu Ylonen <ylo@cs.hut.fi>
* Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
@@ -1626,6 +1626,7 @@ ssh_session(void)
struct winsize ws;
char *cp;
const char *display;
+ char *proto = NULL, *data = NULL;
/* Enable compression if requested. */
if (options.compression) {
@@ -1696,13 +1697,9 @@ ssh_session(void)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout,
- &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing.");
@@ -1792,6 +1789,7 @@ ssh_session2_setup(int id, int success, void *arg)
extern char **environ;
const char *display;
int interactive = tty_flag;
+ char *proto = NULL, *data = NULL;
if (!success)
return; /* No need for error message, channels code sens one */
@@ -1799,12 +1797,9 @@ ssh_session2_setup(int id, int success, void *arg)
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
- if (options.forward_x11 && display != NULL) {
- char *proto, *data;
- /* Get reasonable local authentication information. */
- client_x11_get_proto(display, options.xauth_location,
- options.forward_x11_trusted,
- options.forward_x11_timeout, &proto, &data);
+ if (options.forward_x11 && client_x11_get_proto(display,
+ options.xauth_location, options.forward_x11_trusted,
+ options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing."); | CWE-254 | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.