db-d2/primevul-codebert-embeddings huggingface dataset:
Commit message: cmd/snap-confine: chown private /tmp parent to root.root

When snap-confine creates a private /tmp directory for a given snap it
first creates a temporary directory in /tmp/ named after the snap, along
with a random name. Inside that directory it creates a /tmp directory
with permissions appropriate for a future /tmp, namely 1777.

Up until recently the that directory was owned by the user who first
invoked snap-confine. Since the directory is reused by all the users on
the system this logic makes no sense.

This patch changes the related logic so that the private /tmp directory
is owned by root, just like the real one.

Signed-off-by: Zygmunt Krynicki <zygmunt.krynicki@canonical.com>
CVE: CVE-2019-11502
CWE: CWE-703
Vulnerability description: snap-confine in snapd before 2.38 incorrectly set the ownership of a snap application to the uid and gid of the first calling user. Consequently, that user had unintended access to a private /tmp directory.

Project: snapd
File: mount-support.c

static void setup_private_mount(const char *snap_name)
{
	uid_t uid = getuid();
	gid_t gid = getgid();
	char tmpdir[MAX_BUF] = { 0 };

	// Create a 0700 base directory, this is the base dir that is
	// protected from other users.
	//
	// Under that basedir, we put a 1777 /tmp dir that is then bind
	// mounted for the applications to use
	sc_must_snprintf(tmpdir, sizeof(tmpdir), "/tmp/snap.%s_XXXXXX", snap_name);
	if (mkdtemp(tmpdir) == NULL) {
		die("cannot create temporary directory essential for private /tmp");
	}
	// now we create a 1777 /tmp inside our private dir
	mode_t old_mask = umask(0);
	char *d = sc_strdup(tmpdir);
	sc_must_snprintf(tmpdir, sizeof(tmpdir), "%s/tmp", d);
	free(d);

	if (mkdir(tmpdir, 01777) != 0) {
		die("cannot create temporary directory for private /tmp");
	}
	umask(old_mask);

	// chdir to '/' since the mount won't apply to the current directory
	char *pwd = get_current_dir_name();
	if (pwd == NULL)
		die("cannot get current working directory");
	if (chdir("/") != 0)
		die("cannot change directory to '/'");

	// MS_BIND is there from linux 2.4
	sc_do_mount(tmpdir, "/tmp", NULL, MS_BIND, NULL);
	// MS_PRIVATE needs linux > 2.6.11
	sc_do_mount("none", "/tmp", NULL, MS_PRIVATE, NULL);
	// do the chown after the bind mount to avoid potential shenanigans
	if (chown("/tmp/", uid, gid) < 0) {
		die("cannot change ownership of /tmp");
	}
	// chdir to original directory
	if (chdir(pwd) != 0)
		die("cannot change current working directory to the original directory");
	free(pwd);
}
Commit message: TRQ-2885 - limit tm_adopt() to only adopt a session id that
is owned by the calling user.
CVE: CVE-2014-3684
CWE: CWE-264
Vulnerability description: The tm_adopt function in lib/Libifl/tm.c in Terascale Open-Source Resource and Queue Manager (aka TORQUE Resource Manager) 5.0.x, 4.5.x, 4.2.x, and earlier does not validate that the owner of the process also owns the adopted session id, which allows remote authenticated users to kill arbitrary processes via a crafted executable.

Project: torque

int tm_adopt(
    
  char  *id,
  int    adoptCmd,
  pid_t  pid)

  {
  int rc = TM_SUCCESS;
  int status, ret;
  pid_t sid;
  char *env;
  struct tcp_chan *chan = NULL;

  sid = getsid(pid);

  /* Must be the only call to call to tm and
     must only be called once */

  if (init_done) return TM_BADINIT;

  init_done = 1;

  /* Fabricate the tm state as best we can - not really needed */

  if ((tm_jobid = getenv("PBS_JOBID")) == NULL)
    tm_jobid = (char *)"ADOPT JOB";

  tm_jobid_len = strlen(tm_jobid);

  if ((tm_jobcookie = getenv("PBS_JOBCOOKIE")) == NULL)
    tm_jobcookie = (char *)"ADOPT COOKIE";

  tm_jobcookie_len = strlen(tm_jobcookie);

  /* We dont have the (right) node id or task id */
  tm_jobndid = 0;

  tm_jobtid = 0;

  /* Fallback is system default MOM port if not known */
  if ((env = getenv("PBS_MOMPORT")) == NULL || (tm_momport = atoi(env)) == 0)
    tm_momport = PBS_MANAGER_SERVICE_PORT;


  /* DJH 27 Feb 2002. two kinds of adoption now */
  if (adoptCmd != TM_ADOPT_ALTID && adoptCmd != TM_ADOPT_JOBID)
    return TM_EUNKNOWNCMD;

  if (startcom(adoptCmd, TM_NULL_EVENT, &chan) != DIS_SUCCESS)
    return TM_ESYSTEM;

  /* send session id */
  if (diswsi(chan, sid) != DIS_SUCCESS)
    {
    rc = TM_ENOTCONNECTED;
    goto tm_adopt_cleanup;
    }

  /* write the pid so the adopted process can be part of the cpuset if needed */
  if (diswsi(chan, pid) != DIS_SUCCESS)
    {
    rc =  TM_ENOTCONNECTED;
    goto tm_adopt_cleanup;
    }

  /* send job or alternative id */
  if (diswcs(chan, id, strlen(id)) != DIS_SUCCESS)
    {
    rc =  TM_ENOTCONNECTED;
    goto tm_adopt_cleanup;
    }

  DIS_tcp_wflush(chan);

  /* The mom should now attempt to adopt the task and will send back a
     status flag to indicate whether it was successful or not. */

  status = disrsi(chan, &ret);

  if (ret != DIS_SUCCESS)
    {
    rc = TM_ENOTCONNECTED;
    goto tm_adopt_cleanup;
    }

  /* Don't allow any more tm_* calls in this process. As well as
     closing an unused socket it also prevents any problems related to
     the fact that all adopted processes have a fake task id which
     might break the tm mechanism */
  tm_finalize();

  /* Since we're not using events, tm_finalize won't actually
     close the socket, so do it here. */
  if (local_conn > -1)
    {
    close(local_conn);
    local_conn = -1;
    }

  DIS_tcp_cleanup(chan);
  return (status == TM_OKAY ?

          TM_SUCCESS :
          TM_ENOTFOUND);

tm_adopt_cleanup:
  if (chan != NULL)
    DIS_tcp_cleanup(chan);
  return rc;
  }
Commit message: mISDN: enforce CAP_NET_RAW for raw sockets

When creating a raw AF_ISDN socket, CAP_NET_RAW needs to be checked
first.

Signed-off-by: Ori Nimron <orinimron123@gmail.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Signed-off-by: David S. Miller <davem@davemloft.net>
CVE: CVE-2019-17055
CWE: CWE-862
Vulnerability description: base_sock_create in drivers/isdn/mISDN/socket.c in the AF_ISDN network module in the Linux kernel through 5.3.2 does not enforce CAP_NET_RAW, which means that unprivileged users can create a raw socket, aka CID-b91ee4aa2a21.

Project: linux
File: socket.c

base_sock_create(struct net *net, struct socket *sock, int protocol, int kern)
{
	struct sock *sk;

	if (sock->type != SOCK_RAW)
		return -ESOCKTNOSUPPORT;

	sk = sk_alloc(net, PF_ISDN, GFP_KERNEL, &mISDN_proto, kern);
	if (!sk)
		return -ENOMEM;

	sock_init_data(sock, sk);
	sock->ops = &base_sock_ops;
	sock->state = SS_UNCONNECTED;
	sock_reset_flag(sk, SOCK_ZAPPED);
	sk->sk_protocol = protocol;
	sk->sk_state    = MISDN_OPEN;
	mISDN_sock_link(&base_sockets, sk);

	return 0;
}
Commit message: Prevent segfault for formUpdateBuffer

Bug-Debian: https://github.com/tats/w3m/issues/13
CVE: CVE-2016-9432
CWE: CWE-119
Vulnerability description: An issue was discovered in the Tatsuya Kinoshita w3m fork before 0.5.3-31. w3m allows remote attackers to cause a denial of service (memory corruption, segmentation fault, and crash) via a crafted HTML page.

Project: w3m
File: form.c

formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form)
{
    Buffer save;
    char *p;
    int spos, epos, rows, c_rows, pos, col = 0;
    Line *l;

    copyBuffer(&save, buf);
    gotoLine(buf, a->start.line);
    switch (form->type) {
    case FORM_TEXTAREA:
    case FORM_INPUT_TEXT:
    case FORM_INPUT_FILE:
    case FORM_INPUT_PASSWORD:
    case FORM_INPUT_CHECKBOX:
    case FORM_INPUT_RADIO:
#ifdef MENU_SELECT
    case FORM_SELECT:
#endif				/* MENU_SELECT */
	spos = a->start.pos;
	epos = a->end.pos;
	break;
    default:
	spos = a->start.pos + 1;
	epos = a->end.pos - 1;
    }
    switch (form->type) {
    case FORM_INPUT_CHECKBOX:
    case FORM_INPUT_RADIO:
	if (form->checked)
	    buf->currentLine->lineBuf[spos] = '*';
	else
	    buf->currentLine->lineBuf[spos] = ' ';
	break;
    case FORM_INPUT_TEXT:
    case FORM_INPUT_FILE:
    case FORM_INPUT_PASSWORD:
    case FORM_TEXTAREA:
#ifdef MENU_SELECT
    case FORM_SELECT:
	if (form->type == FORM_SELECT) {
	    p = form->label->ptr;
	    updateSelectOption(form, form->select_option);
	}
	else
#endif				/* MENU_SELECT */
	    p = form->value->ptr;
	l = buf->currentLine;
	if (form->type == FORM_TEXTAREA) {
	    int n = a->y - buf->currentLine->linenumber;
	    if (n > 0)
		for (; l && n; l = l->prev, n--) ;
	    else if (n < 0)
		for (; l && n; l = l->prev, n++) ;
	    if (!l)
		break;
	}
	rows = form->rows ? form->rows : 1;
	col = COLPOS(l, a->start.pos);
	for (c_rows = 0; c_rows < rows; c_rows++, l = l->next) {
	    if (rows > 1) {
		pos = columnPos(l, col);
		a = retrieveAnchor(buf->formitem, l->linenumber, pos);
		if (a == NULL)
		    break;
		spos = a->start.pos;
		epos = a->end.pos;
	    }
	    if (a->start.line != a->end.line || spos > epos)
		epos = spos;
	    pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col,
				   rows > 1,
				   form->type == FORM_INPUT_PASSWORD);
	    if (pos != epos) {
		shiftAnchorPosition(buf->href, buf->hmarklist,
				    a->start.line, spos, pos - epos);
		shiftAnchorPosition(buf->name, buf->hmarklist,
				    a->start.line, spos, pos - epos);
		shiftAnchorPosition(buf->img, buf->hmarklist,
				    a->start.line, spos, pos - epos);
		shiftAnchorPosition(buf->formitem, buf->hmarklist,
				    a->start.line, spos, pos - epos);
	    }
	}
	break;
    }
    copyBuffer(buf, &save);
    arrangeLine(buf);
}
Commit message: Avoid infinite wait reading secrets file.
CVE: CVE-2014-2855
CWE: CWE-20
Vulnerability description: The check_secret function in authenticate.c in rsync 3.1.0 and earlier allows remote attackers to cause a denial of service (infinite loop and CPU consumption) via a user name which does not exist in the secrets file.

Project: rsync
File: authenticate.c

static const char *check_secret(int module, const char *user, const char *group,
				const char *challenge, const char *pass)
{
	char line[1024];
	char pass2[MAX_DIGEST_LEN*2];
	const char *fname = lp_secrets_file(module);
	STRUCT_STAT st;
	int fd, ok = 1;
	int user_len = strlen(user);
	int group_len = group ? strlen(group) : 0;
	char *err;

	if (!fname || !*fname || (fd = open(fname, O_RDONLY)) < 0)
		return "no secrets file";

	if (do_fstat(fd, &st) == -1) {
		rsyserr(FLOG, errno, "fstat(%s)", fname);
		ok = 0;
	} else if (lp_strict_modes(module)) {
		if ((st.st_mode & 06) != 0) {
			rprintf(FLOG, "secrets file must not be other-accessible (see strict modes option)\n");
			ok = 0;
		} else if (MY_UID() == 0 && st.st_uid != 0) {
			rprintf(FLOG, "secrets file must be owned by root when running as root (see strict modes)\n");
			ok = 0;
		}
	}
	if (!ok) {
		close(fd);
		return "ignoring secrets file";
	}

	if (*user == '#') {
		/* Reject attempt to match a comment. */
		close(fd);
		return "invalid username";
	}

	/* Try to find a line that starts with the user (or @group) name and a ':'. */
	err = "secret not found";
	while ((user || group) && read_line_old(fd, line, sizeof line, 1)) {
		const char **ptr, *s;
		int len;
		if (*line == '@') {
			ptr = &group;
			len = group_len;
			s = line+1;
		} else {
			ptr = &user;
			len = user_len;
			s = line;
		}
		if (!*ptr || strncmp(s, *ptr, len) != 0 || s[len] != ':')
			continue;
		generate_hash(s+len+1, challenge, pass2);
		if (strcmp(pass, pass2) == 0) {
			err = NULL;
			break;
		}
		err = "password mismatch";
		*ptr = NULL; /* Don't look for name again. */
	}

	close(fd);

	memset(line, 0, sizeof line);
	memset(pass2, 0, sizeof pass2);

	return err;
}
Commit message: Fix #76449: SIGSEGV in firebird_handle_doer

We need to verify that the `result_size` is not larger than our buffer,
and also should make sure that the `len` which is passed to
`isc_vax_integer()` has a permissible value; otherwise we bail out.
CVE: CVE-2021-21704
CWE: CWE-787
Vulnerability description: In PHP versions 7.3.x below 7.3.29, 7.4.x below 7.4.21 and 8.0.x below 8.0.8, when using Firebird PDO driver extension, a malicious database server could cause crashes in various database functions, such as getAttribute(), execute(), fetch() and others by returning invalid response data that is not parsed correctly by the driver. This can result in crashes, denial of service or potentially memory corruption.

Project: php-src
File: firebird_driver.c

static zend_long firebird_handle_doer(pdo_dbh_t *dbh, const char *sql, size_t sql_len) /* {{{ */
{
	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
	isc_stmt_handle stmt = PDO_FIREBIRD_HANDLE_INITIALIZER;
	static char const info_count[] = { isc_info_sql_records };
	char result[64];
	int ret = 0;
	XSQLDA in_sqlda, out_sqlda;

	/* TODO no placeholders in exec() for now */
	in_sqlda.version = out_sqlda.version = PDO_FB_SQLDA_VERSION;
	in_sqlda.sqld = out_sqlda.sqld = 0;
	out_sqlda.sqln = 1;

	/* allocate and prepare statement */
	if (!firebird_alloc_prepare_stmt(dbh, sql, sql_len, &out_sqlda, &stmt, 0)) {
		return -1;
	}

	/* execute the statement */
	if (isc_dsql_execute2(H->isc_status, &H->tr, &stmt, PDO_FB_SQLDA_VERSION, &in_sqlda, &out_sqlda)) {
		RECORD_ERROR(dbh);
		ret = -1;
		goto free_statement;
	}

	/* find out how many rows were affected */
	if (isc_dsql_sql_info(H->isc_status, &stmt, sizeof(info_count), const_cast(info_count),
			sizeof(result),	result)) {
		RECORD_ERROR(dbh);
		ret = -1;
		goto free_statement;
	}

	if (result[0] == isc_info_sql_records) {
		unsigned i = 3, result_size = isc_vax_integer(&result[1],2);

		while (result[i] != isc_info_end && i < result_size) {
			short len = (short)isc_vax_integer(&result[i+1],2);
			if (result[i] != isc_info_req_select_count) {
				ret += isc_vax_integer(&result[i+3],len);
			}
			i += len+3;
		}
	}

	/* commit if we're in auto_commit mode */
	if (dbh->auto_commit && isc_commit_retaining(H->isc_status, &H->tr)) {
		RECORD_ERROR(dbh);
	}

free_statement:

	if (isc_dsql_free_statement(H->isc_status, &stmt, DSQL_drop)) {
		RECORD_ERROR(dbh);
	}

	return ret;
}
Commit message: NTLMv2 responses support
CVE: CVE-2019-17266
CWE: CWE-125
Vulnerability description: libsoup from versions 2.65.1 until 2.68.1 have a heap-based buffer over-read because soup_ntlm_parse_challenge() in soup-auth-ntlm.c does not properly check an NTLM message's length before proceeding with a memcpy.

Project: libsoup
File: soup-auth-ntlm.c

soup_ntlm_parse_challenge (const char *challenge,
			   char      **nonce,
			   char      **default_domain,
			   gboolean   *ntlmv2_session)
{
	gsize clen;
	NTLMString domain;
	guchar *chall;
	guint32 flags;

	chall = g_base64_decode (challenge, &clen);
	if (clen < NTLM_CHALLENGE_DOMAIN_STRING_OFFSET ||
	    clen < NTLM_CHALLENGE_NONCE_OFFSET + NTLM_CHALLENGE_NONCE_LENGTH) {
		g_free (chall);
		return FALSE;
	}

	memcpy (&flags, chall + NTLM_CHALLENGE_FLAGS_OFFSET, sizeof(flags));
	flags = GUINT_FROM_LE (flags);
	*ntlmv2_session = (flags & NTLM_FLAGS_NEGOTIATE_NTLMV2) ? TRUE : FALSE;

	if (default_domain) {
		memcpy (&domain, chall + NTLM_CHALLENGE_DOMAIN_STRING_OFFSET, sizeof (domain));
		domain.length = GUINT16_FROM_LE (domain.length);
		domain.offset = GUINT16_FROM_LE (domain.offset);

		if (clen < domain.length + domain.offset) {
			g_free (chall);
			return FALSE;
		}

		*default_domain = g_convert ((char *)chall + domain.offset,
					     domain.length, "UTF-8", "UCS-2LE",
					     NULL, NULL, NULL);
	}

	if (nonce) {
		*nonce = g_memdup (chall + NTLM_CHALLENGE_NONCE_OFFSET,
				   NTLM_CHALLENGE_NONCE_LENGTH);
	}

	g_free (chall);
	return TRUE;
}
Commit message: Check size of path buffer before writing into it

This prevents a buffer overrun that could otherwise be triggered by
creating a file called '.git' with contents

  gitdir: (something really long)

Signed-off-by: Greg Brockman <gdb@mit.edu>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
CVE: CVE-2010-2542
CWE: CWE-787
Vulnerability description: Stack-based buffer overflow in the is_git_directory function in setup.c in Git before 1.7.2.1 allows local users to gain privileges via a long gitdir: field in a .git file in a working copy.

Project: git
File: setup.c

static int is_git_directory(const char *suspect)
{
	char path[PATH_MAX];
	size_t len = strlen(suspect);

	strcpy(path, suspect);
	if (getenv(DB_ENVIRONMENT)) {
		if (access(getenv(DB_ENVIRONMENT), X_OK))
			return 0;
	}
	else {
		strcpy(path + len, "/objects");
		if (access(path, X_OK))
			return 0;
	}

	strcpy(path + len, "/refs");
	if (access(path, X_OK))
		return 0;

	strcpy(path + len, "/HEAD");
	if (validate_headref(path))
		return 0;

	return 1;
}
Commit message: Fix memory leak in `parse_ie_keyword_arg`

`kwd_arg` would never get freed when there was a parse error in
`parse_ie_keyword_arg`.

Closes #2656
CVE: CVE-2018-11697
CWE: CWE-125
Vulnerability description: An issue was discovered in LibSass through 3.5.4. An out-of-bounds read of a memory region was found in the function Sass::Prelexer::exactly() which could be leveraged by an attacker to disclose information or manipulated to read from unmapped memory causing a denial of service.

Project: libsass
File: parser.cpp

  String_Obj Parser::parse_ie_keyword_arg()
  {
    String_Schema_Ptr kwd_arg = SASS_MEMORY_NEW(String_Schema, pstate, 3);
    if (lex< variable >()) {
      kwd_arg->append(SASS_MEMORY_NEW(Variable, pstate, Util::normalize_underscores(lexed)));
    } else {
      lex< alternatives< identifier_schema, identifier > >();
      kwd_arg->append(SASS_MEMORY_NEW(String_Constant, pstate, lexed));
    }
    lex< exactly<'='> >();
    kwd_arg->append(SASS_MEMORY_NEW(String_Constant, pstate, lexed));
    if (peek< variable >()) kwd_arg->append(parse_list());
    else if (lex< number >()) {
      std::string parsed(lexed);
      Util::normalize_decimals(parsed);
      kwd_arg->append(lexed_number(parsed));
    }
    else if (peek < ie_keyword_arg_value >()) { kwd_arg->append(parse_list()); }
    return kwd_arg;
  }
Commit message: dvi: Mitigate command injection attacks by quoting filename

With commit 1fcca0b8041de0d6074d7e17fba174da36c65f99 came a DVI backend.
It exports to PDF via the dvipdfm tool.
It calls that tool with the filename of the currently loaded document.
If that filename is cleverly crafted, it can escape the currently
used manual quoting of the filename.  Instead of manually quoting the
filename, we use g_shell_quote.

https://bugzilla.gnome.org/show_bug.cgi?id=784947
CVE: CVE-2017-1000159
CWE: CWE-78
Vulnerability description: Command injection in evince via filename when printing to PDF. This affects versions earlier than 3.25.91.

Project: evince
File: dvi-document.c

dvi_document_file_exporter_end (EvFileExporter *exporter)
{
	gchar *command_line;
	gint exit_stat;
	GError *err = NULL;
	gboolean success;
	
	DviDocument *dvi_document = DVI_DOCUMENT(exporter);
	
	command_line = g_strdup_printf ("dvipdfm %s -o %s \"%s\"", /* dvipdfm -s 1,2,.., -o exporter_filename dvi_filename */
					dvi_document->exporter_opts->str,
					dvi_document->exporter_filename,
					dvi_document->context->filename);
	
	success = g_spawn_command_line_sync (command_line,
					     NULL,
					     NULL,
					     &exit_stat,
					     &err);

	g_free (command_line);

	if (success == FALSE) {
		g_warning ("Error: %s", err->message);
	} else if (!WIFEXITED(exit_stat) || WEXITSTATUS(exit_stat) != EXIT_SUCCESS){
		g_warning ("Error: dvipdfm does not end normally or exit with a failure status.");
	}

	if (err)
		g_error_free (err);
}
Commit message: patch 9.0.0105: illegal memory access when pattern starts with illegal byte

Problem:    Illegal memory access when pattern starts with illegal byte.
Solution:   Do not match a character with an illegal byte.
CVE: CVE-2022-2581
CWE: CWE-125
Vulnerability description: Out-of-bounds Read in GitHub repository vim/vim prior to 9.0.0104.

Project: vim
File: regexp.c

cstrchr(char_u *s, int c)
{
    char_u	*p;
    int		cc;

    if (!rex.reg_ic || (!enc_utf8 && mb_char2len(c) > 1))
	return vim_strchr(s, c);

    // tolower() and toupper() can be slow, comparing twice should be a lot
    // faster (esp. when using MS Visual C++!).
    // For UTF-8 need to use folded case.
    if (enc_utf8 && c > 0x80)
	cc = utf_fold(c);
    else
	 if (MB_ISUPPER(c))
	cc = MB_TOLOWER(c);
    else if (MB_ISLOWER(c))
	cc = MB_TOUPPER(c);
    else
	return vim_strchr(s, c);

    if (has_mbyte)
    {
	for (p = s; *p != NUL; p += (*mb_ptr2len)(p))
	{
	    if (enc_utf8 && c > 0x80)
	    {
		if (utf_fold(utf_ptr2char(p)) == cc)
		    return p;
	    }
	    else if (*p == c || *p == cc)
		return p;
	}
    }
    else
	// Faster version for when there are no multi-byte characters.
	for (p = s; *p != NUL; ++p)
	    if (*p == c || *p == cc)
		return p;

    return NULL;
}
Commit message: CVE-2021-20277 ldb/attrib_handlers casefold: stay in bounds

For a string that had N spaces at the beginning, we would
try to move N bytes beyond the end of the string.

BUG: https://bugzilla.samba.org/show_bug.cgi?id=14655

Signed-off-by: Douglas Bagnall <douglas.bagnall@catalyst.net.nz>
Reviewed-by: Andrew Bartlett <abartlet@samba.org>

(cherry-picked from commit for master)
CVE: CVE-2021-20277
CWE: CWE-787
Vulnerability description: A flaw was found in Samba's libldb. Multiple, consecutive leading spaces in an LDAP attribute can lead to an out-of-bounds memory write, leading to a crash of the LDAP server process handling the request. The highest threat from this vulnerability is to system availability.

Project: samba
File: attrib_handlers.c

int ldb_handler_fold(struct ldb_context *ldb, void *mem_ctx,
			    const struct ldb_val *in, struct ldb_val *out)
{
	char *s, *t;
	size_t l;

	if (!in || !out || !(in->data)) {
		return -1;
	}

	out->data = (uint8_t *)ldb_casefold(ldb, mem_ctx, (const char *)(in->data), in->length);
	if (out->data == NULL) {
		ldb_debug(ldb, LDB_DEBUG_ERROR, "ldb_handler_fold: unable to casefold string [%.*s]", (int)in->length, (const char *)in->data);
		return -1;
	}

	s = (char *)(out->data);
	
	/* remove trailing spaces if any */
	l = strlen(s);
	while (l > 0 && s[l - 1] == ' ') l--;
	s[l] = '\0';
	
	/* remove leading spaces if any */
	if (*s == ' ') {
		for (t = s; *s == ' '; s++) ;

		/* remove leading spaces by moving down the string */
		memmove(t, s, l);

		s = t;
	}

	/* check middle spaces */
	while ((t = strchr(s, ' ')) != NULL) {
		for (s = t; *s == ' '; s++) ;

		if ((s - t) > 1) {
			l = strlen(s);

			/* remove all spaces but one by moving down the string */
			memmove(t + 1, s, l);
		}
	}

	out->length = strlen((char *)out->data);
	return 0;
}