db-d2/primevul-codebert-embeddings huggingface dataset:
Commit message: lib-imap: Don't generate invalid BODYSTRUCTURE when reaching MIME part limit

If the last MIME part was message/rfc822 and its child was truncated away,
BODYSTRUCTURE was missing the ENVELOPE and BODY[STRUCTURE] parts. Fixed by
writing empty dummy ones.
CVE: CVE-2020-25275
CWE: CWE-20
Vulnerability description: Dovecot before 2.3.13 has Improper Input Validation in lda, lmtp, and imap, leading to an application crash via a crafted email message with certain choices for ten thousand MIME parts.

Project: core

static void part_write_body(const struct message_part *part,
			    string_t *str, bool extended)
{
	const struct message_part_data *data = part->data;
	bool text;

	i_assert(part->data != NULL);

	if ((part->flags & MESSAGE_PART_FLAG_MESSAGE_RFC822) != 0) {
		str_append(str, "\"message\" \"rfc822\"");
		text = FALSE;
	} else {
		/* "content type" "subtype" */
		if (data->content_type == NULL) {
			text = TRUE;
			str_append(str, "\"text\" \"plain\"");
		} else {
			text = (strcasecmp(data->content_type, "text") == 0);
			imap_append_string(str, data->content_type);
			str_append_c(str, ' ');
			imap_append_string(str, data->content_subtype);
		}
	}

	/* ("content type param key" "value" ...) */
	str_append_c(str, ' ');
	params_write(data->content_type_params,
		data->content_type_params_count, str, text);

	str_append_c(str, ' ');
	imap_append_nstring_nolf(str, data->content_id);
	str_append_c(str, ' ');
	imap_append_nstring_nolf(str, data->content_description);
	str_append_c(str, ' ');
	if (data->content_transfer_encoding != NULL)
		imap_append_string(str, data->content_transfer_encoding);
	else
		str_append(str, "\"7bit\"");
	str_printfa(str, " %"PRIuUOFF_T, part->body_size.virtual_size);

	if (text) {
		/* text/.. contains line count */
		str_printfa(str, " %u", part->body_size.lines);
	} else if ((part->flags & MESSAGE_PART_FLAG_MESSAGE_RFC822) != 0) {
		/* message/rfc822 contains envelope + body + line count */
		const struct message_part_data *child_data;

		i_assert(part->children != NULL);
		i_assert(part->children->next == NULL);

		child_data = part->children->data;

		str_append(str, " (");
		imap_envelope_write(child_data->envelope, str);
		str_append(str, ") ");

		part_write_bodystructure_siblings(part->children, str, extended);
		str_printfa(str, " %u", part->body_size.lines);
	}

	if (!extended)
		return;

	/* BODYSTRUCTURE data */

	/* "md5" ("content disposition" ("disposition" "params"))
	   ("body" "language" "params") "location" */
	str_append_c(str, ' ');
	imap_append_nstring_nolf(str, data->content_md5);
	part_write_bodystructure_common(data, str);
}
Commit message: src: retain pointers to WriteWrap/ShutdownWrap

Avoids potential use-after-free when wrap req's are synchronously
destroyed.

CVE-ID: CVE-2020-8265
Fixes: https://github.com/nodejs-private/node-private/issues/227
Refs: https://hackerone.com/bugs?subject=nodejs&report_id=988103
PR-URL: https://github.com/nodejs-private/node-private/pull/23
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
CVE: CVE-2020-8265
CWE: CWE-416
Vulnerability description: Node.js versions before 10.23.1, 12.20.1, 14.15.4, 15.5.1 are vulnerable to a use-after-free bug in its TLS implementation. When writing to a TLS enabled socket, node::StreamBase::Write calls node::TLSWrap::DoWrite with a freshly allocated WriteWrap object as first argument. If the DoWrite method does not return an error, this object is passed back to the caller as part of a StreamWriteResult structure. This may be exploited to corrupt memory leading to a Denial of Service or potentially other exploits.

Project: node

StreamWriteResult StreamBase::Write(
    uv_buf_t* bufs,
    size_t count,
    uv_stream_t* send_handle,
    v8::Local<v8::Object> req_wrap_obj) {
  Environment* env = stream_env();
  int err;

  size_t total_bytes = 0;
  for (size_t i = 0; i < count; ++i)
    total_bytes += bufs[i].len;
  bytes_written_ += total_bytes;

  if (send_handle == nullptr) {
    err = DoTryWrite(&bufs, &count);
    if (err != 0 || count == 0) {
      return StreamWriteResult { false, err, nullptr, total_bytes };
    }
  }

  v8::HandleScope handle_scope(env->isolate());

  if (req_wrap_obj.IsEmpty()) {
    if (!env->write_wrap_template()
             ->NewInstance(env->context())
             .ToLocal(&req_wrap_obj)) {
      return StreamWriteResult { false, UV_EBUSY, nullptr, 0 };
    }
    StreamReq::ResetObject(req_wrap_obj);
  }

  AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(GetAsyncWrap());
  WriteWrap* req_wrap = CreateWriteWrap(req_wrap_obj);

  err = DoWrite(req_wrap, bufs, count, send_handle);
  bool async = err == 0;

  if (!async) {
    req_wrap->Dispose();
    req_wrap = nullptr;
  }

  const char* msg = Error();
  if (msg != nullptr) {
    req_wrap_obj->Set(env->context(),
                      env->error_string(),
                      OneByteString(env->isolate(), msg)).Check();
    ClearError();
  }

  return StreamWriteResult { async, err, req_wrap, total_bytes };
}
Commit message: Fix Null pointer deref in X509_issuer_and_serial_hash()

The OpenSSL public API function X509_issuer_and_serial_hash() attempts
to create a unique hash value based on the issuer and serial number data
contained within an X509 certificate. However it fails to correctly
handle any errors that may occur while parsing the issuer field (which
might occur if the issuer field is maliciously constructed). This may
subsequently result in a NULL pointer deref and a crash leading to a
potential denial of service attack.

The function X509_issuer_and_serial_hash() is never directly called by
OpenSSL itself so applications are only vulnerable if they use this
function directly and they use it on certificates that may have been
obtained from untrusted sources.

CVE-2021-23841

Reviewed-by: Richard Levitte <levitte@openssl.org>
Reviewed-by: Paul Dale <pauli@openssl.org>
CVE: CVE-2021-23841
CWE: CWE-476
Vulnerability description: The OpenSSL public API function X509_issuer_and_serial_hash() attempts to create a unique hash value based on the issuer and serial number data contained within an X509 certificate. However it fails to correctly handle any errors that may occur while parsing the issuer field (which might occur if the issuer field is maliciously constructed). This may subsequently result in a NULL pointer deref and a crash leading to a potential denial of service attack. The function X509_issuer_and_serial_hash() is never directly called by OpenSSL itself so applications are only vulnerable if they use this function directly and they use it on certificates that may have been obtained from untrusted sources. OpenSSL versions 1.1.1i and below are affected by this issue. Users of these versions should upgrade to OpenSSL 1.1.1j. OpenSSL versions 1.0.2x and below are affected by this issue. However OpenSSL 1.0.2 is out of support and no longer receiving public updates. Premium support customers of OpenSSL 1.0.2 should upgrade to 1.0.2y. Other users should upgrade to 1.1.1j. Fixed in OpenSSL 1.1.1j (Affected 1.1.1-1.1.1i). Fixed in OpenSSL 1.0.2y (Affected 1.0.2-1.0.2x).

Project: openssl

unsigned long X509_issuer_and_serial_hash(X509 *a)
{
    unsigned long ret = 0;
    EVP_MD_CTX *ctx = EVP_MD_CTX_new();
    unsigned char md[16];
    char *f;

    if (ctx == NULL)
        goto err;
    f = X509_NAME_oneline(a->cert_info.issuer, NULL, 0);
    if (!EVP_DigestInit_ex(ctx, EVP_md5(), NULL))
        goto err;
    if (!EVP_DigestUpdate(ctx, (unsigned char *)f, strlen(f)))
        goto err;
    OPENSSL_free(f);
    if (!EVP_DigestUpdate
        (ctx, (unsigned char *)a->cert_info.serialNumber.data,
         (unsigned long)a->cert_info.serialNumber.length))
        goto err;
    if (!EVP_DigestFinal_ex(ctx, &(md[0]), NULL))
        goto err;
    ret = (((unsigned long)md[0]) | ((unsigned long)md[1] << 8L) |
           ((unsigned long)md[2] << 16L) | ((unsigned long)md[3] << 24L)
        ) & 0xffffffffL;
 err:
    EVP_MD_CTX_free(ctx);
    return ret;
}
Commit message: Test that X509_issuer_and_serial_hash doesn't crash

Provide a certificate with a bad issuer and check that
X509_issuer_and_serial_hash doesn't crash.

Reviewed-by: Richard Levitte <levitte@openssl.org>
Reviewed-by: Paul Dale <pauli@openssl.org>
CVE: CVE-2021-23841
CWE: CWE-476
Vulnerability description: The OpenSSL public API function X509_issuer_and_serial_hash() attempts to create a unique hash value based on the issuer and serial number data contained within an X509 certificate. However it fails to correctly handle any errors that may occur while parsing the issuer field (which might occur if the issuer field is maliciously constructed). This may subsequently result in a NULL pointer deref and a crash leading to a potential denial of service attack. The function X509_issuer_and_serial_hash() is never directly called by OpenSSL itself so applications are only vulnerable if they use this function directly and they use it on certificates that may have been obtained from untrusted sources. OpenSSL versions 1.1.1i and below are affected by this issue. Users of these versions should upgrade to OpenSSL 1.1.1j. OpenSSL versions 1.0.2x and below are affected by this issue. However OpenSSL 1.0.2 is out of support and no longer receiving public updates. Premium support customers of OpenSSL 1.0.2 should upgrade to 1.0.2y. Other users should upgrade to 1.1.1j. Fixed in OpenSSL 1.1.1j (Affected 1.1.1-1.1.1i). Fixed in OpenSSL 1.0.2y (Affected 1.0.2-1.0.2x).

Project: openssl

int FuzzerTestOneInput(const uint8_t *buf, size_t len)
{
    const unsigned char *p = buf;
    unsigned char *der = NULL;

    X509 *x509 = d2i_X509(NULL, &p, len);
    if (x509 != NULL) {
        BIO *bio = BIO_new(BIO_s_null());
        /* This will load and print the public key as well as extensions */
        X509_print(bio, x509);
        BIO_free(bio);

        i2d_X509(x509, &der);
        OPENSSL_free(der);

        X509_free(x509);
    }
    ERR_clear_error();
    return 0;
}
Commit message: ssl sigalg extension: fix NULL pointer dereference

As the variable peer_sigalgslen is not cleared on ssl rehandshake, it's
possible to crash an openssl tls secured server remotely by sending a
manipulated hello message in a rehandshake.

On such a manipulated rehandshake, tls1_set_shared_sigalgs() calls
tls12_shared_sigalgs() with the peer_sigalgslen of the previous
handshake, while the peer_sigalgs has been freed.
As a result tls12_shared_sigalgs() walks over the available
peer_sigalgs and tries to access data of a NULL pointer.

This issue was introduced by c589c34e61 (Add support for the TLS 1.3
signature_algorithms_cert extension, 2018-01-11).

Signed-off-by: Peter Kästle <peter.kaestle@nokia.com>
Signed-off-by: Samuel Sapalski <samuel.sapalski@nokia.com>

CVE-2021-3449

CLA: trivial

Reviewed-by: Tomas Mraz <tomas@openssl.org>
Reviewed-by: Paul Dale <pauli@openssl.org>
Reviewed-by: Matt Caswell <matt@openssl.org>
CVE: CVE-2021-3449
CWE: CWE-476
Vulnerability description: An OpenSSL TLS server may crash if sent a maliciously crafted renegotiation ClientHello message from a client. If a TLSv1.2 renegotiation ClientHello omits the signature_algorithms extension (where it was present in the initial ClientHello), but includes a signature_algorithms_cert extension then a NULL pointer dereference will result, leading to a crash and a denial of service attack. A server is only vulnerable if it has TLSv1.2 and renegotiation enabled (which is the default configuration). OpenSSL TLS clients are not impacted by this issue. All OpenSSL 1.1.1 versions are affected by this issue. Users of these versions should upgrade to OpenSSL 1.1.1k. OpenSSL 1.0.2 is not impacted by this issue. Fixed in OpenSSL 1.1.1k (Affected 1.1.1-1.1.1j).

Project: openssl

static int init_sig_algs(SSL *s, unsigned int context)
{
    /* Clear any signature algorithms extension received */
    OPENSSL_free(s->s3->tmp.peer_sigalgs);
    s->s3->tmp.peer_sigalgs = NULL;

    return 1;
}
Commit message: fix: out-of-bounds write on invalid label

When the label for a node cannot be parsed (due to it being malformed), it falls
back on the symbol name of the node itself. I.e. the default label the node
would have had if it had no label attribute at all. However, this is applied by
dynamically altering the node's label to "\N", a shortcut for the symbol name of
the node. All of this is fine, however if the hand written label itself is
shorter than the literal string "\N", not enough memory would have been
allocated to write "\N" into the label text.

Here we account for the possibility of error during label parsing, and assume
that the label text may need to be overwritten with "\N" after the fact. Fixes
issue #1700.
CVE: CVE-2020-18032
CWE: CWE-120
Vulnerability description: Buffer Overflow in Graphviz Graph Visualization Tools from commit ID f8b9e035 and earlier allows remote attackers to execute arbitrary code or cause a denial of service (application crash) by loading a crafted file into the "lib/common/shapes.c" component.

Project: graphviz

static void record_init(node_t * n)
{
    field_t *info;
    pointf ul, sz;
    int flip, len;
    char *textbuf;		/* temp buffer for storing labels */
    int sides = BOTTOM | RIGHT | TOP | LEFT;

    /* Always use rankdir to determine how records are laid out */
    flip = NOT(GD_realflip(agraphof(n)));
    reclblp = ND_label(n)->text;
    len = strlen(reclblp);
    /* For some forgotten reason, an empty label is parsed into a space, so
     * we need at least two bytes in textbuf.
     */
    len = MAX(len, 1);
    textbuf = N_NEW(len + 1, char);
    if (!(info = parse_reclbl(n, flip, TRUE, textbuf))) {
	agerr(AGERR, "bad label format %s\n", ND_label(n)->text);
	reclblp = "\\N";
	info = parse_reclbl(n, flip, TRUE, textbuf);
    }
    free(textbuf);
    size_reclbl(n, info);
    sz.x = POINTS(ND_width(n));
    sz.y = POINTS(ND_height(n));
    if (mapbool(late_string(n, N_fixed, "false"))) {
	if ((sz.x < info->size.x) || (sz.y < info->size.y)) {
/* should check that the record really won't fit, e.g., there may be no text.
			agerr(AGWARN, "node '%s' size may be too small\n", agnameof(n));
*/
	}
    } else {
	sz.x = MAX(info->size.x, sz.x);
	sz.y = MAX(info->size.y, sz.y);
    }
    resize_reclbl(info, sz, mapbool(late_string(n, N_nojustify, "false")));
    ul = pointfof(-sz.x / 2., sz.y / 2.);	/* FIXME - is this still true:    suspected to introduce ronding error - see Kluge below */
    pos_reclbl(info, ul, sides);
    ND_width(n) = PS2INCH(info->size.x);
    ND_height(n) = PS2INCH(info->size.y + 1);	/* Kluge!!  +1 to fix rounding diff between layout and rendering 
						   otherwise we can get -1 coords in output */
    ND_shape_info(n) = (void *) info;
}
Commit message: lib-oauth2: Add missing test_begin/test_end to token escape
CVE: CVE-2021-29157
CWE: CWE-22
Vulnerability description: Dovecot before 2.3.15 allows ../ Path Traversal. An attacker with access to the local filesystem can trick OAuth2 authentication into using an HS256 validation key from an attacker-controlled location. This occurs during use of local JWT validation with the posix fs driver.

Project: core

static void test_jwt_token_escape(void)
{
	struct test_case {
		const char *azp;
		const char *alg;
		const char *kid;
		const char *esc_azp;
		const char *esc_kid;
	} test_cases[] = {
		{ "", "hs256", "", "default", "default" },
		{ "", "hs256", "test", "default", "test" },
		{ "test", "hs256", "test", "test", "test" },
		{
			"http://test.unit/local%key",
			"hs256",
			"http://test.unit/local%key",
			"http:%2f%2ftest%2eunit%2flocal%25key",
			"http:%2f%2ftest%2eunit%2flocal%25key"
		},
		{ "../", "hs256", "../", "%2e%2e%2f", "%2e%2e%2f" },
	};
	buffer_t *b64_key =
		t_base64_encode(0, SIZE_MAX, hs_sign_key->data, hs_sign_key->used);
	ARRAY_TYPE(oauth2_field) fields;
	t_array_init(&fields, 8);

	for (size_t i = 0; i < N_ELEMENTS(test_cases); i++) {
		const struct test_case *test_case = &test_cases[i];
		array_clear(&fields);
		struct oauth2_field *field = array_append_space(&fields);
		field->name = "sub";
		field->value = "testuser";
		if (*test_case->azp != '\0') {
			field = array_append_space(&fields);
			field->name = "azp";
			field->value = test_case->azp;
		}
		if (*test_case->kid != '\0') {
			field = array_append_space(&fields);
			field->name = "kid";
			field->value = test_case->kid;
		}
		save_key_azp_to(test_case->alg, test_case->esc_azp, test_case->esc_kid,
				str_c(b64_key));
		buffer_t *token = create_jwt_token_fields_kid(test_case->alg,
							      test_case->kid,
							      time(NULL)+500,
							      time(NULL)-500,
							      0, &fields);
		sign_jwt_token_hs256(token, hs_sign_key);
		test_jwt_token(str_c(token));
	}
}
Commit message: lib-oauth2: Improve identifier escaping function
CVE: CVE-2021-29157
CWE: CWE-22
Vulnerability description: Dovecot before 2.3.15 allows ../ Path Traversal. An attacker with access to the local filesystem can trick OAuth2 authentication into using an HS256 validation key from an attacker-controlled location. This occurs during use of local JWT validation with the posix fs driver.

Project: core

static const char *escape_identifier(const char *identifier)
{
	size_t pos = strcspn(identifier, "./%");
	if (pos < strlen(identifier)) {
		/* sanitize identifier, cannot allow dots or / in it, so we
		  encode them */
		string_t *new_id = t_str_new(strlen(identifier));
		/* put initial data */
		str_append_data(new_id, identifier, pos);

		for (const char *c = identifier+pos; *c != '\0'; c++) {
			switch (*c) {
			case '.':
				str_append(new_id, "%2e");
				break;
			case '/':
				str_append(new_id, "%2f");
				break;
			case '%':
				str_append(new_id, "%25");
				break;
			default:
				str_append_c(new_id, *c);
				break;
			}
		}
		return str_c(new_id);
	}
	return identifier;
}
Commit message: lib-oauth2: Move identifier escaping to own function
CVE: CVE-2021-29157
CWE: CWE-22
Vulnerability description: Dovecot before 2.3.15 allows ../ Path Traversal. An attacker with access to the local filesystem can trick OAuth2 authentication into using an HS256 validation key from an attacker-controlled location. This occurs during use of local JWT validation with the posix fs driver.

Project: core

int oauth2_try_parse_jwt(const struct oauth2_settings *set,
			 const char *token, ARRAY_TYPE(oauth2_field) *fields,
			 bool *is_jwt_r, const char **error_r)
{
	const char *const *blobs = t_strsplit(token, ".");
	int ret;

	i_assert(set->key_dict != NULL);

	/* we don't know if it's JWT token yet */
	*is_jwt_r = FALSE;

	if (str_array_length(blobs) != 3) {
		*error_r = "Not a JWT token";
		return -1;
	}

	/* attempt to decode header */
	buffer_t *header =
		t_base64url_decode_str(BASE64_DECODE_FLAG_NO_PADDING, blobs[0]);

	if (header->used == 0) {
		*error_r = "Not a JWT token";
		return -1;
	}

	struct json_tree *header_tree;
	if (oauth2_json_tree_build(header, &header_tree, error_r) < 0)
		return -1;

	const char *alg, *kid;
	ret = oauth2_jwt_header_process(header_tree, &alg, &kid, error_r);
	json_tree_deinit(&header_tree);
	if (ret < 0)
		return -1;

	/* it is now assumed to be a JWT token */
	*is_jwt_r = TRUE;

	if (kid == NULL)
		kid = "default";
	else if (*kid == '\0') {
		*error_r = "'kid' field is empty";
		return -1;
	}

	size_t pos = strcspn(kid, "./%");
	if (pos < strlen(kid)) {
		/* sanitize kid, cannot allow dots or / in it, so we encode them
		 */
		string_t *new_kid = t_str_new(strlen(kid));
		/* put initial data */
		str_append_data(new_kid, kid, pos);
		for (const char *c = kid+pos; *c != '\0'; c++) {
			switch (*c) {
			case '.':
				str_append(new_kid, "%2e");
				break;
			case '/':
				str_append(new_kid, "%2f");
				break;
			case '%':
				str_append(new_kid, "%25");
				break;
			default:
				str_append_c(new_kid, *c);
				break;
			}
		}
		kid = str_c(new_kid);
	}

	/* parse body */
	struct json_tree *body_tree;
	buffer_t *body =
		t_base64url_decode_str(BASE64_DECODE_FLAG_NO_PADDING, blobs[1]);
	if (oauth2_json_tree_build(body, &body_tree, error_r) == -1)
		return -1;
	ret = oauth2_jwt_body_process(set, alg, kid, fields, body_tree, blobs,
				      error_r);
	json_tree_deinit(&body_tree);

	return ret;
}
Commit message: http2: update handling of rst_stream with error code NGHTTP2_CANCEL

The PR updates the handling of rst_stream frames and adds all streams
to the pending list on receiving rst frames with the error code
NGHTTP2_CANCEL.

The changes will remove dependency on the stream state that may allow
bypassing the checks in certain cases. I think a better solution is to
delay streams in all cases if rst_stream is received for the cancel
events.

The rst_stream frames can be received for protocol/connection error as
well it should be handled immediately. Adding streams to the pending
list in such cases may cause errors.

CVE-ID: CVE-2021-22930
Refs: https://nvd.nist.gov/vuln/detail/CVE-2021-22930
PR-URL: https://github.com/nodejs/node/pull/39622
Refs: https://github.com/nodejs/node/pull/39423
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Beth Griggs <bgriggs@redhat.com>
CVE: CVE-2021-22940
CWE: CWE-416
Vulnerability description: Node.js before 16.6.1, 14.17.5, and 12.22.5 is vulnerable to a use after free attack where an attacker might be able to exploit the memory corruption, to change process behavior.

Project: node

void Http2Stream::SubmitRstStream(const uint32_t code) {
  CHECK(!this->is_destroyed());
  code_ = code;

  // If RST_STREAM frame is received and stream is not writable
  // because it is busy reading data, don't try force purging it.
  // Instead add the stream to pending stream list and process
  // the pending data when it is safe to do so. This is to avoid
  // double free error due to unwanted behavior of nghttp2.
  // Ref:https://github.com/nodejs/node/issues/38964

  // Add stream to the pending list if it is received with scope
  // below in the stack. The pending list may not get processed
  // if RST_STREAM received is not in scope and added to the list
  // causing endpoint to hang.
  if (session_->is_in_scope() &&
      !is_writable() && is_reading()) {
    session_->AddPendingRstStream(id_);
    return;
  }


  // If possible, force a purge of any currently pending data here to make sure
  // it is sent before closing the stream. If it returns non-zero then we need
  // to wait until the current write finishes and try again to avoid nghttp2
  // behaviour where it prioritizes RstStream over everything else.
  if (session_->SendPendingData() != 0) {
    session_->AddPendingRstStream(id_);
    return;
  }

  FlushRstStream();
}
Commit message: MDEV-26423 MariaDB server crash in Create_tmp_table::finalize

Removed prohibition of creating temporary field of Item_default_value
(added by mistake by 1d9b043a1f5db7ff229d5200652cff7a78ea6266 fix of
MDEV-10780 and MDEV-11265).
CVE: CVE-2022-27378
CWE: CWE-89
Vulnerability description: An issue in the component Create_tmp_table::finalize of MariaDB Server v10.7 and below was discovered to allow attackers to cause a Denial of Service (DoS) via specially crafted SQL statements.

Project: server

  Field *get_tmp_table_field() { return 0; }