db-d2/primevul-codebert-embeddings huggingface dataset:
Commit message: allow referencing of compressed label directly before another compressed label, thanks @giganteous
CVE: CVE-2015-1868
Vulnerability description: The label decompression functionality in PowerDNS Recursor 3.5.x, 3.6.x before 3.6.3, and 3.7.x before 3.7.2 and Authoritative (Auth) Server 3.2.x, 3.3.x before 3.3.2, and 3.4.x before 3.4.4 allows remote attackers to cause a denial of service (CPU consumption or crash) via a request with a name that refers to itself.

Project: pdns
File: dnsparser.cc

void PacketReader::getLabelFromContent(const vector<uint8_t>& content, uint16_t& frompos, string& ret, int recurs) 
{
  if(recurs > 100) // the forward reference-check below should make this test 100% obsolete
    throw MOADNSException("Loop");
  // it is tempting to call reserve on ret, but it turns out it creates a malloc/free storm in the loop
  int pos = frompos;
  for(;;) {
    unsigned char labellen=content.at(frompos++);

    if(!labellen) {
      if(ret.empty())
              ret.append(1,'.');
      break;
    }
    else if((labellen & 0xc0) == 0xc0) {
      uint16_t offset=256*(labellen & ~0xc0) + (unsigned int)content.at(frompos++) - sizeof(dnsheader);
      //        cout<<"This is an offset, need to go to: "<<offset<<endl;

      if(offset >= pos)
        throw MOADNSException("forward reference during label decompression");
      return getLabelFromContent(content, offset, ret, ++recurs);
    }
    else if(labellen > 63) 
      throw MOADNSException("Overly long label during label decompression ("+lexical_cast<string>((unsigned int)labellen)+")");
    else {
      // XXX FIXME THIS MIGHT BE VERY SLOW!

      for(string::size_type n = 0 ; n < labellen; ++n, frompos++) {
        if(content.at(frompos)=='.' || content.at(frompos)=='\\') {
          ret.append(1, '\\');
          ret.append(1, content[frompos]);
        }
        else if(content.at(frompos)==' ') {
          ret+="\\032";
        }
        else 
          ret.append(1, content[frompos]);
      }
      ret.append(1,'.');
    }
  }
}
Commit message: ALSA: usb-audio: Minor code cleanup in create_fixed_stream_quirk()

Just a minor code cleanup: unify the error paths.

Signed-off-by: Takashi Iwai <tiwai@suse.de>
CVE: CVE-2016-2184
CWE: NVD-CWE-Other
Vulnerability description: The create_fixed_stream_quirk function in sound/usb/quirks.c in the snd-usb-audio driver in the Linux kernel before 4.5.1 allows physically proximate attackers to cause a denial of service (NULL pointer dereference or double free, and system crash) via a crafted endpoints value in a USB device descriptor.

Project: linux
File: quirks.c

bool snd_usb_get_sample_rate_quirk(struct snd_usb_audio *chip)
{
	/* devices which do not support reading the sample rate. */
	switch (chip->usb_id) {
	case USB_ID(0x045E, 0x075D): /* MS Lifecam Cinema  */
	case USB_ID(0x045E, 0x076D): /* MS Lifecam HD-5000 */
	case USB_ID(0x045E, 0x076F): /* MS Lifecam HD-6000 */
	case USB_ID(0x045E, 0x0772): /* MS Lifecam Studio */
	case USB_ID(0x045E, 0x0779): /* MS Lifecam HD-3000 */
	case USB_ID(0x047F, 0xAA05): /* Plantronics DA45 */
	case USB_ID(0x04D8, 0xFEEA): /* Benchmark DAC1 Pre */
	case USB_ID(0x074D, 0x3553): /* Outlaw RR2150 (Micronas UAC3553B) */
	case USB_ID(0x21B4, 0x0081): /* AudioQuest DragonFly */
		return true;
	}
	return false;
}
Commit message: Fix #70064: imagescale(..., IMG_BICUBIC) leaks memory

A temporary image (tmp_im) is created with gdImageTrueColor() and freed with
gdFree() instead of gdImageDestroy(). Let's fix that.
CVE: CVE-2015-8877
CWE: CWE-399
Vulnerability description: The gdImageScaleTwoPass function in gd_interpolation.c in the GD Graphics Library (aka libgd) before 2.2.0, as used in PHP before 5.6.12, uses inconsistent allocate and free approaches, which allows remote attackers to cause a denial of service (memory consumption) via a crafted call, as demonstrated by a call to the PHP imagescale function.

Project: php-src
File: gd_interpolation.c

gdImagePtr gdImageScaleTwoPass(const gdImagePtr src, const unsigned int src_width, const unsigned int src_height, const unsigned int new_width, const unsigned int new_height)
{
	gdImagePtr tmp_im;
	gdImagePtr dst;

	/* Convert to truecolor if it isn't; this code requires it. */
	if (!src->trueColor) {
		gdImagePaletteToTrueColor(src);
	}

	tmp_im = gdImageCreateTrueColor(new_width, src_height);
	if (tmp_im == NULL) {
		return NULL;
	}
	gdImageSetInterpolationMethod(tmp_im, src->interpolation_id);
	_gdScaleHoriz(src, src_width, src_height, tmp_im, new_width, src_height);

	dst = gdImageCreateTrueColor(new_width, new_height);
	if (dst == NULL) {
		gdImageDestroy(tmp_im);
		return NULL;
	}
	gdImageSetInterpolationMethod(dst, src->interpolation_id);
	_gdScaleVert(tmp_im, new_width, src_height, dst, new_width, new_height);
	gdImageDestroy(tmp_im);

	return dst;
}
Commit message: Bug #22295186:  CERTIFICATE VALIDATION BUG IN MYSQL MAY ALLOW MITM
CVE: CVE-2016-2047
CWE: CWE-254
Vulnerability description: The ssl_verify_server_cert function in sql-common/client.c in MariaDB before 5.5.47, 10.0.x before 10.0.23, and 10.1.x before 10.1.10; Oracle MySQL 5.5.48 and earlier, 5.6.29 and earlier, and 5.7.11 and earlier; and Percona Server do not properly verify that the server hostname matches a domain name in the subject's Common Name (CN) or subjectAltName field of the X.509 certificate, which allows man-in-the-middle attackers to spoof SSL servers via a "/CN=" string in a field in a certificate, as demonstrated by "/OU=/CN=bar.com/CN=foo.com."

Project: mysql-server
File: client.c

my_bool STDCALL
mysql_ssl_set(MYSQL *mysql __attribute__((unused)) ,
	      const char *key __attribute__((unused)),
	      const char *cert __attribute__((unused)),
	      const char *ca __attribute__((unused)),
	      const char *capath __attribute__((unused)),
	      const char *cipher __attribute__((unused)))
{
  DBUG_ENTER("mysql_ssl_set");
#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
  mysql->options.ssl_key=    strdup_if_not_null(key);
  mysql->options.ssl_cert=   strdup_if_not_null(cert);
  mysql->options.ssl_ca=     strdup_if_not_null(ca);
  mysql->options.ssl_capath= strdup_if_not_null(capath);
  mysql->options.ssl_cipher= strdup_if_not_null(cipher);
#endif /* HAVE_OPENSSL && !EMBEDDED_LIBRARY */
  DBUG_RETURN(0);
Commit message: bootp: check bootp_input buffer size

Fixes: CVE-2021-3592
Fixes: https://gitlab.freedesktop.org/slirp/libslirp/-/issues/44

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
CVE: None
Vulnerability description: None

Project: libslirp
File: bootp.c

void bootp_input(struct mbuf *m)
{
    struct bootp_t *bp = mtod_check(m, sizeof(struct bootp_t));

    if (bp && bp->bp_op == BOOTP_REQUEST) {
        bootp_reply(m->slirp, bp, m_end(m));
    }
}
Commit message: fix CVE-2012-2143
CVE: CVE-2012-2143
CWE: CWE-310
Vulnerability description: The crypt_des (aka DES-based crypt) function in FreeBSD before 9.0-RELEASE-p2, as used in PHP, PostgreSQL, and other products, does not process the complete cleartext password if this password contains a 0x80 character, which makes it easier for context-dependent attackers to obtain access via an authentication attempt with an initial substring of the intended password, as demonstrated by a Unicode password.

Project: php-src
File: crypt_freesec.c

_crypt_extended_r(const char *key, const char *setting,
	struct php_crypt_extended_data *data)
{
	int		i;
	uint32_t	count, salt, l, r0, r1, keybuf[2];
	u_char		*p, *q;

	if (!data->initialized)
		des_init_local(data);

	/*
	 * Copy the key, shifting each character up by one bit
	 * and padding with zeros.
	 */
	q = (u_char *) keybuf;
	while (q - (u_char *) keybuf < sizeof(keybuf)) {
		*q++ = *key << 1;
		if (*key)
			key++;
	}
	if (des_setkey((u_char *) keybuf, data))
		return(NULL);

	if (*setting == _PASSWORD_EFMT1) {
		/*
		 * "new"-style:
		 *	setting - underscore, 4 chars of count, 4 chars of salt
		 *	key - unlimited characters
		 */
		for (i = 1, count = 0; i < 5; i++) {
			int value = ascii_to_bin(setting[i]);
			if (ascii64[value] != setting[i])
				return(NULL);
			count |= value << (i - 1) * 6;
		}
		if (!count)
			return(NULL);

		for (i = 5, salt = 0; i < 9; i++) {
			int value = ascii_to_bin(setting[i]);
			if (ascii64[value] != setting[i])
				return(NULL);
			salt |= value << (i - 5) * 6;
		}

		while (*key) {
			/*
			 * Encrypt the key with itself.
			 */
			if (des_cipher((u_char *) keybuf, (u_char *) keybuf,
			    0, 1, data))
				return(NULL);
			/*
			 * And XOR with the next 8 characters of the key.
			 */
			q = (u_char *) keybuf;
			while (q - (u_char *) keybuf < sizeof(keybuf) && *key)
				*q++ ^= *key++ << 1;

			if (des_setkey((u_char *) keybuf, data))
				return(NULL);
		}
		memcpy(data->output, setting, 9);
		data->output[9] = '\0';
		p = (u_char *) data->output + 9;
	} else {
		/*
		 * "old"-style:
		 *	setting - 2 chars of salt
		 *	key - up to 8 characters
		 */
		count = 25;

		if (ascii_is_unsafe(setting[0]) || ascii_is_unsafe(setting[1]))
			return(NULL);

		salt = (ascii_to_bin(setting[1]) << 6)
		     |  ascii_to_bin(setting[0]);

		data->output[0] = setting[0];
		data->output[1] = setting[1];
		p = (u_char *) data->output + 2;
	}
	setup_salt(salt, data);
	/*
	 * Do it.
	 */
	if (do_des(0, 0, &r0, &r1, count, data))
		return(NULL);
	/*
	 * Now encode the result...
	 */
	l = (r0 >> 8);
	*p++ = ascii64[(l >> 18) & 0x3f];
	*p++ = ascii64[(l >> 12) & 0x3f];
	*p++ = ascii64[(l >> 6) & 0x3f];
	*p++ = ascii64[l & 0x3f];

	l = (r0 << 16) | ((r1 >> 16) & 0xffff);
	*p++ = ascii64[(l >> 18) & 0x3f];
	*p++ = ascii64[(l >> 12) & 0x3f];
	*p++ = ascii64[(l >> 6) & 0x3f];
	*p++ = ascii64[l & 0x3f];

	l = r1 << 2;
	*p++ = ascii64[(l >> 12) & 0x3f];
	*p++ = ascii64[(l >> 6) & 0x3f];
	*p++ = ascii64[l & 0x3f];
	*p = 0;

	return(data->output);
}
Commit message: CVE-2016-1577
CVE: CVE-2016-1577
CWE: NVD-CWE-Other
Vulnerability description: Double free vulnerability in the jas_iccattrval_destroy function in JasPer 1.900.1 and earlier allows remote attackers to cause a denial of service (crash) or possibly execute arbitrary code via a crafted ICC color profile in a JPEG 2000 image file, a different vulnerability than CVE-2014-8137.

Project: jasper
File: jas_icc.c

jas_iccprof_t *jas_iccprof_load(jas_stream_t *in)
{
	jas_iccprof_t *prof;
	int numtags;
	long curoff;
	long reloff;
	long prevoff;
	jas_iccsig_t type;
	jas_iccattrval_t *attrval;
	jas_iccattrval_t *prevattrval;
	jas_icctagtabent_t *tagtabent;
	jas_iccattrvalinfo_t *attrvalinfo;
	int i;
	int len;

	prof = 0;
	attrval = 0;

	if (!(prof = jas_iccprof_create())) {
		goto error;
	}

	if (jas_iccprof_readhdr(in, &prof->hdr)) {
		jas_eprintf("cannot get header\n");
		goto error;
	}
	if (jas_iccprof_gettagtab(in, &prof->tagtab)) {
		jas_eprintf("cannot get tab table\n");
		goto error;
	}
	jas_iccprof_sorttagtab(&prof->tagtab);

	numtags = prof->tagtab.numents;
	curoff = JAS_ICC_HDRLEN + 4 + 12 * numtags;
	prevoff = 0;
	prevattrval = 0;
	for (i = 0; i < numtags; ++i) {
		tagtabent = &prof->tagtab.ents[i];
		if (tagtabent->off == JAS_CAST(jas_iccuint32_t, prevoff)) {
			if (prevattrval) {
				if (!(attrval = jas_iccattrval_clone(prevattrval)))
					goto error;
				if (jas_iccprof_setattr(prof, tagtabent->tag, attrval))
					goto error;
				jas_iccattrval_destroy(attrval);
				attrval = 0;
			} else {
#if 0
				jas_eprintf("warning: skipping unknown tag type\n");
#endif
			}
			continue;
		}
		reloff = tagtabent->off - curoff;
		if (reloff > 0) {
			if (jas_stream_gobble(in, reloff) != reloff)
				goto error;
			curoff += reloff;
		} else if (reloff < 0) {
			/* This should never happen since we read the tagged
			element data in a single pass. */
			abort();
		}
		prevoff = curoff;
		if (jas_iccgetuint32(in, &type)) {
			goto error;
		}
		if (jas_stream_gobble(in, 4) != 4) {
			goto error;
		}
		curoff += 8;
		if (!(attrvalinfo = jas_iccattrvalinfo_lookup(type))) {
#if 0
			jas_eprintf("warning: skipping unknown tag type\n");
#endif
			prevattrval = 0;
			continue;
		}
		if (!(attrval = jas_iccattrval_create(type))) {
			goto error;
		}
		len = tagtabent->len - 8;
		if ((*attrval->ops->input)(attrval, in, len)) {
			goto error;
		}
		curoff += len;
		if (jas_iccprof_setattr(prof, tagtabent->tag, attrval)) {
			goto error;
		}
		prevattrval = attrval; /* This is correct, but slimey. */
		jas_iccattrval_destroy(attrval);
		attrval = 0;
	}

	return prof;

error:
	if (prof)
		jas_iccprof_destroy(prof);
	if (attrval)
		jas_iccattrval_destroy(attrval);
	return 0;
}
Commit message: Added a check in the JP2 encoder to ensure that the image to be coded
has at least one component.
Also, made some small changes to a private build script.
CVE: CVE-2017-1000050
CWE: CWE-476
Vulnerability description: JasPer 2.0.12 is vulnerable to a NULL pointer exception in the function jp2_encode which failed to check to see if the image contained at least one component resulting in a denial-of-service.

Project: jasper
File: jp2_enc.c

static uint_fast32_t jp2_gettypeasoc(int colorspace, int ctype)
{
	int type;
	int asoc;

	if (ctype & JAS_IMAGE_CT_OPACITY) {
		type = JP2_CDEF_TYPE_OPACITY;
		asoc = JP2_CDEF_ASOC_ALL;
		goto done;
	}

	type = JP2_CDEF_TYPE_UNSPEC;
	asoc = JP2_CDEF_ASOC_NONE;
	switch (jas_clrspc_fam(colorspace)) {
	case JAS_CLRSPC_FAM_RGB:
		switch (JAS_IMAGE_CT_COLOR(ctype)) {
		case JAS_IMAGE_CT_RGB_R:
			type = JP2_CDEF_TYPE_COLOR;
			asoc = JP2_CDEF_RGB_R;
			break;
		case JAS_IMAGE_CT_RGB_G:
			type = JP2_CDEF_TYPE_COLOR;
			asoc = JP2_CDEF_RGB_G;
			break;
		case JAS_IMAGE_CT_RGB_B:
			type = JP2_CDEF_TYPE_COLOR;
			asoc = JP2_CDEF_RGB_B;
			break;
		}
		break;
	case JAS_CLRSPC_FAM_YCBCR:
		switch (JAS_IMAGE_CT_COLOR(ctype)) {
		case JAS_IMAGE_CT_YCBCR_Y:
			type = JP2_CDEF_TYPE_COLOR;
			asoc = JP2_CDEF_YCBCR_Y;
			break;
		case JAS_IMAGE_CT_YCBCR_CB:
			type = JP2_CDEF_TYPE_COLOR;
			asoc = JP2_CDEF_YCBCR_CB;
			break;
		case JAS_IMAGE_CT_YCBCR_CR:
			type = JP2_CDEF_TYPE_COLOR;
			asoc = JP2_CDEF_YCBCR_CR;
			break;
		}
		break;
	case JAS_CLRSPC_FAM_GRAY:
		type = JP2_CDEF_TYPE_COLOR;
		asoc = JP2_CDEF_GRAY_Y;
		break;
	}

done:
	return (type << 16) | asoc;
}

Project: jasper
File: jp2_enc.c

static int clrspctojp2(jas_clrspc_t clrspc)
{
	switch (clrspc) {
	case JAS_CLRSPC_SRGB:
		return JP2_COLR_SRGB;
	case JAS_CLRSPC_SYCBCR:
		return JP2_COLR_SYCC;
	case JAS_CLRSPC_SGRAY:
		return JP2_COLR_SGRAY;
	default:
		abort();
		break;
	}
}
Commit message: fix a used-before-set error in im_vips2dz

we were reading an uninited string in a vips7 compatibility wrapper, thanks
yifengchen-cc

see https://github.com/libvips/libvips/issues/1419
CVE: CVE-2020-20739
CWE: CWE-369
Vulnerability description: im_vips2dz in /libvips/libvips/deprecated/im_vips2dz.c in libvips before 8.8.2 has an uninitialized variable which may cause the leakage of remote server path or stack address.

Project: libvips
File: im_vips2dz.c

im_vips2dz( IMAGE *in, const char *filename )
{
	char *p, *q;
	char name[FILENAME_MAX];
	char mode[FILENAME_MAX];
	char buf[FILENAME_MAX];

	int i;
	VipsForeignDzLayout layout = VIPS_FOREIGN_DZ_LAYOUT_DZ; 
	char *suffix = ".jpeg";
	int overlap = 0;
	int tile_size = 256;
	VipsForeignDzDepth depth = VIPS_FOREIGN_DZ_DEPTH_ONEPIXEL; 
	gboolean centre = FALSE;
	VipsAngle angle = VIPS_ANGLE_D0; 

	/* We can't use im_filename_split() --- it assumes that we have a
	 * filename with an extension before the ':', and filename here is
	 * actually a dirname.
	 *
	 * Just split on the first ':'.
	 */
	im_strncpy( name, filename, FILENAME_MAX ); 
	if( (p = strchr( name, ':' )) ) {
		*p = '\0';
		im_strncpy( mode, p + 1, FILENAME_MAX ); 
	}
	else 
		strcpy( mode, "" ); 

	strcpy( buf, mode ); 
	p = &buf[0];

	if( (q = im_getnextoption( &p )) ) {
		if( (i = vips_enum_from_nick( "im_vips2dz", 
			VIPS_TYPE_FOREIGN_DZ_LAYOUT, q )) < 0 ) 
			return( -1 );
		layout = i;
	}

	if( (q = im_getnextoption( &p )) ) 
		suffix = g_strdup( q );
	if( (q = im_getnextoption( &p )) ) 
		overlap = atoi( q ); 
	if( (q = im_getnextoption( &p )) ) 
		tile_size = atoi( q ); 

	if( (q = im_getnextoption( &p )) ) {
		if( (i = vips_enum_from_nick( "im_vips2dz", 
			VIPS_TYPE_FOREIGN_DZ_DEPTH, q )) < 0 )
			return( -1 );
		depth = i;
	}

	if( (q = im_getnextoption( &p )) ) {
		if( im_isprefix( "cen", q ) ) 
			centre = TRUE;
	}

	if( (q = im_getnextoption( &p )) ) {
		if( (i = vips_enum_from_nick( "im_vips2dz", 
			VIPS_TYPE_ANGLE, q )) < 0 )
			return( -1 );
		angle = i;
	}

	if( vips_dzsave( in, name,
		"layout", layout,
		"suffix", suffix,
		"overlap", overlap,
		"tile_size", tile_size,
		"depth", depth,
		"centre", centre,
		"angle", angle,
		NULL ) )
		return( -1 );

	return( 0 );
}
Commit message: [libpng16] Prevent reading over-length PLTE chunk (Cosmin Truta).
CVE: CVE-2015-8126
CWE: CWE-120
Vulnerability description: Multiple buffer overflows in the (1) png_set_PLTE and (2) png_get_PLTE functions in libpng before 1.0.64, 1.1.x and 1.2.x before 1.2.54, 1.3.x and 1.4.x before 1.4.17, 1.5.x before 1.5.24, and 1.6.x before 1.6.19 allow remote attackers to cause a denial of service (application crash) or possibly have unspecified other impact via a small bit-depth value in an IHDR (aka image header) chunk in a PNG image.

Project: libpng
File: pngwutil.c

png_write_PLTE(png_structrp png_ptr, png_const_colorp palette,
    png_uint_32 num_pal)
{
   png_uint_32 max_palette_length, i;
   png_const_colorp pal_ptr;
   png_byte buf[3];

   png_debug(1, "in png_write_PLTE");

   max_palette_length = (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ?
      (1 << png_ptr->bit_depth) : PNG_MAX_PALETTE_LENGTH;

   if ((
#ifdef PNG_MNG_FEATURES_SUPPORTED
       (png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) == 0 &&
#endif
       num_pal == 0) || num_pal > max_palette_length)
   {
      if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
      {
         png_error(png_ptr, "Invalid number of colors in palette");
      }

      else
      {
         png_warning(png_ptr, "Invalid number of colors in palette");
         return;
      }
   }

   if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0)
   {
      png_warning(png_ptr,
          "Ignoring request to write a PLTE chunk in grayscale PNG");

      return;
   }

   png_ptr->num_palette = (png_uint_16)num_pal;
   png_debug1(3, "num_palette = %d", png_ptr->num_palette);

   png_write_chunk_header(png_ptr, png_PLTE, (png_uint_32)(num_pal * 3));
#ifdef PNG_POINTER_INDEXING_SUPPORTED

   for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
   {
      buf[0] = pal_ptr->red;
      buf[1] = pal_ptr->green;
      buf[2] = pal_ptr->blue;
      png_write_chunk_data(png_ptr, buf, (png_size_t)3);
   }

#else
   /* This is a little slower but some buggy compilers need to do this
    * instead
    */
   pal_ptr=palette;

   for (i = 0; i < num_pal; i++)
   {
      buf[0] = pal_ptr[i].red;
      buf[1] = pal_ptr[i].green;
      buf[2] = pal_ptr[i].blue;
      png_write_chunk_data(png_ptr, buf, (png_size_t)3);
   }

#endif
   png_write_chunk_end(png_ptr);
   png_ptr->mode |= PNG_HAVE_PLTE;
}
Commit message: buffer: Add NULL check for 'buffer' argument

Signed-off-by: Andreas Schneider <asn@cryptomilk.org>
Reviewed-by: Anderson Toshiyuki Sasaki <ansasaki@redhat.com>
Reviewed-by: Jakub Jelen <jjelen@redhat.com>
CVE: CVE-2020-16135
CWE: CWE-476
Vulnerability description: libssh 0.9.4 has a NULL pointer dereference in tftpserver.c if ssh_buffer_new returns NULL.

Project: libssh-mirror
File: buffer.c

int ssh_buffer_add_data(struct ssh_buffer_struct *buffer, const void *data, uint32_t len)
{
    if (buffer == NULL) {
        return -1;
    }

    buffer_verify(buffer);

    if (data == NULL) {
        return -1;
    }

    if (buffer->used + len < len) {
        return -1;
    }

    if (buffer->allocated < (buffer->used + len)) {
        if (buffer->pos > 0) {
            buffer_shift(buffer);
        }
        if (realloc_buffer(buffer, buffer->used + len) < 0) {
            return -1;
        }
    }

    memcpy(buffer->data + buffer->used, data, len);
    buffer->used += len;
    buffer_verify(buffer);
    return 0;
}
Commit message: tpm2: Activate SEED_COMPAT_LEVEL_RSA_PRIME_ADJUST_FIX

Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>
CVE: CVE-2021-3505
CWE: CWE-331
Vulnerability description: A flaw was found in libtpms in versions before 0.8.0. The TPM 2 implementation returns 2048 bit keys with ~1984 bit strength due to a bug in the TCG specification. The bug is in the key creation algorithm in RsaAdjustPrimeCandidate(), which is called before the prime number check. The highest threat from this vulnerability is to data confidentiality.

Project: libtpms

BnGeneratePrimeForRSA(
		      bigNum          prime,          // IN/OUT: points to the BN that will get the
		      //  random value
		      UINT32          bits,           // IN: number of bits to get
		      UINT32          exponent,       // IN: the exponent
		      RAND_STATE      *rand           // IN: the random state
		      )
{
    BOOL            found = FALSE;
    //
    // Make sure that the prime is large enough
    pAssert(prime->allocated >= BITS_TO_CRYPT_WORDS(bits));
    // Only try to handle specific sizes of keys in order to save overhead
    pAssert((bits % 32) == 0);
    
    prime->size = BITS_TO_CRYPT_WORDS(bits);
    
    while(!found)
	{
	    // The change below is to make sure that all keys that are generated from the same
	    // seed value will be the same regardless of the endianess or word size of the CPU.
	    //       DRBG_Generate(rand, (BYTE *)prime->d, (UINT16)BITS_TO_BYTES(bits));// old
	    //       if(g_inFailureMode)                                                // old
	// libtpms changed begin
	    switch (DRBG_GetSeedCompatLevel(rand)) {
	    case SEED_COMPAT_LEVEL_ORIGINAL:
		DRBG_Generate(rand, (BYTE *)prime->d, (UINT16)BITS_TO_BYTES(bits));
		if (g_inFailureMode)
		    return TPM_RC_FAILURE;
		break;
	    case SEED_COMPAT_LEVEL_LAST:
            /* case SEED_COMPAT_LEVEL_RSA_PRIME_ADJUST_FIX: */
		if(!BnGetRandomBits(prime, bits, rand))                              // new
		    return TPM_RC_FAILURE;
                break;
            default:
                FAIL(FATAL_ERROR_INTERNAL);
	    }
	    RsaAdjustPrimeCandidate(prime, DRBG_GetSeedCompatLevel(rand));
	// libtpms changed end
	    found = RsaCheckPrime(prime, exponent, rand) == TPM_RC_SUCCESS;
	}
    return TPM_RC_SUCCESS;
}

Project: libtpms

RsaAdjustPrimeCandidate(
			bigNum          prime,
			SEED_COMPAT_LEVEL seedCompatLevel  // IN: compatibility level; libtpms added
			)
{
    switch (seedCompatLevel) {
    case SEED_COMPAT_LEVEL_ORIGINAL:
        RsaAdjustPrimeCandidate_PreRev155(prime);
        break;
    case SEED_COMPAT_LEVEL_LAST:
    /* case SEED_COMPAT_LEVEL_RSA_PRIME_ADJUST_FIX: */
        RsaAdjustPrimeCandidate_New(prime);
        break;
    default:
        FAIL(FATAL_ERROR_INTERNAL);
    }
}