Subject: bug#47616: 27.1; hardening mail-envelope-from

From: Francesco Potortì <[email-masked]>
Date: Tue, 06 Apr 2021 14:42:41 +0200

in mail-utils.el the function mail-fetch-field thus notes in the doc
string:

  The buffer should be narrowed to just the header, else false
  matches may be returned from the message body.

In fact, both sendmail-send-it and smtp-send-it use mail-envelope-from,
which calls mail-fetch-field without narrowing, which in fact causes a
false match if:

- you forward a message with "From: " at begining of line
- message-forward-as-mime is nil
- mail-specify-envelope-from is t
- mail-envelope-from is 'header

In this case, both sendmail-send-it and smptmail-send-it try to see if
they should set the From: field and the sender, and both get a false
match from mail-envelope-from.

Apparently, the problem with sendmail-send-it is corrected later in the
code (I don't know where) so the mail is sent correctly, which is why I
had never realised this until I started using smtpmail-send-it, which
sets a wrong From: header copied from the forwarded message.

Hardening mail-envelope-from from sendmail.el by narrowing to the
headers, as the doc says, corrects the problem that I observed.

(defun mail-envelope-from ()
  "Return the envelope mail address to use when sending mail.
This function uses `mail-envelope-from'."
  (or (if (eq mail-envelope-from 'header)
	  (nth 1 (mail-extract-address-components
		  (save-restriction
		    (save-excursion
		      (goto-char (point-max))
		      (re-search-backward
		       (concat "^" (regexp-quote mail-header-separator) "\n")
		       nil t)
		      (narrow-to-region (point-min) (point))
		      (mail-fetch-field "From")))))
	mail-envelope-from)
      user-mail-address))

This introduces a small semantic change for the meaning of the
mail-envelope-from variable.  Currently, the docs says:

If non-nil, designate the envelope-from address when sending mail.
This only has an effect if `mail-specify-envelope-from’ is non-nil.
The value should be either a string, or the symbol `header’ (in
which case the contents of the "From" header of the message
being sent is used), or nil (in which case the value of
‘user-mail-address’ is used).

The last two lines should be instead:

...
being sent is used, if one exists).  If the value is nil, or if it is
`header' and no "From" header is found in the message, the value of
‘user-mail-address’ is used.