CVE-2021-23400: Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') (CWE-74)
value: The package nodemailer before 6.6.1 are vulnerable to HTTP Header Injection if unsanitized user input that may contain newlines and carriage returns is passed into an address object.
CWE description: The product constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
CVSS v3 base score: 8.8
Published: 2021-06-29T12:15Z
Repository: https://github.com/nodemailer/nodemailer
Language: JavaScript
Files changed: .travis.yml, CHANGELOG.md, examples/mailcomposer.js, lib/mime-node/index.js, package.json
Commit date: 2021-05-23 13:18:53 +0300
Commit message: v6.6.1

Diff: diff --git a/.travis.yml b/.travis.yml
index a58016f..18b39e7 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -2,11 +2,11 @@ language: node_js
 sudo: false
 node_js:
     - 10
     - 12
     - 14
-    - 15
+    - 16
 notifications:
     email:
         - andris@kreata.ee
     webhooks:
         urls:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 41e9317..966caa0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,7 +1,11 @@
 # CHANGELOG
 
+## 6.6.1 2021-05-23
+
+-   Fixed address formatting issue where newlines in an email address, if provided via address object, were not properly removed. Reported by tmazeika (#1289)
+
 ## 6.6.0 2021-04-28
 
 -   Added new option `newline` for MailComposer
 -   aws ses connection verification (Ognjen Jevremovic)
 
diff --git a/examples/mailcomposer.js b/examples/mailcomposer.js
index 82270ea..ee724a5 100644
--- a/examples/mailcomposer.js
+++ b/examples/mailcomposer.js
@@ -7,11 +7,13 @@ const mailOptions = {
     to: 'daemon@kreata.ee',
     envelope: {
         from: 'Daemon <deamon@kreata.ee>',
         to: 'mailer@kreata.ee, Mailer <mailer2@kreata.ee>'
     },
-    text: 'Test\n 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ö\r\nsage',
+    text: `Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, 'and what is the use of a book,' thought Alice 'without pictures or conversations?'
+
+So she was considering in her own mind (as well as she could, for the hot day made her feel very sleepy and stupid), whether the pleasure of making a daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly a White Rabbit with pink eyes ran close by her.`,
     newline: '\r\n'
 };
 
 async function main() {
     let raw = await new MailComposer(mailOptions).compile().build();
diff --git a/lib/mime-node/index.js b/lib/mime-node/index.js
index daa9661..c27d806 100644
--- a/lib/mime-node/index.js
+++ b/lib/mime-node/index.js
@@ -1145,24 +1145,23 @@ class MimeNode {
         [].concat(addresses || []).forEach(address => {
             if (address.address) {
                 address.address = this._normalizeAddress(address.address);
 
                 if (!address.name) {
-                    values.push(address.address);
+                    values.push(address.address.indexOf(' ') >= 0 ? `<${address.address}>` : `${address.address}`);
                 } else if (address.name) {
-                    values.push(this._encodeAddressName(address.name) + ' <' + address.address + '>');
+                    values.push(`${this._encodeAddressName(address.name)} <${address.address}>`);
                 }
 
                 if (address.address) {
                     if (!uniqueList.filter(a => a.address === address.address).length) {
                         uniqueList.push(address);
                     }
                 }
             } else if (address.group) {
-                values.push(
-                    this._encodeAddressName(address.name) + ':' + (address.group.length ? this._convertAddresses(address.group, uniqueList) : '').trim() + ';'
-                );
+                let groupListAddresses = (address.group.length ? this._convertAddresses(address.group, uniqueList) : '').trim();
+                values.push(`${this._encodeAddressName(address.name)}:${groupListAddresses};`);
             }
         });
 
         return values.join(', ');
     }
@@ -1172,26 +1171,47 @@ class MimeNode {
      *
      * @param {Array} address An array of address objects
      * @return {String} address string
      */
     _normalizeAddress(address) {
-        address = (address || '').toString().trim();
+        address = (address || '')
+            .toString()
+            .replace(/[\x00-\x1F<>]+/g, ' ') // remove unallowed characters
+            .trim();
 
         let lastAt = address.lastIndexOf('@');
         if (lastAt < 0) {
             // Bare username
             return address;
         }
+
         let user = address.substr(0, lastAt);
         let domain = address.substr(lastAt + 1);
 
         // Usernames are not touched and are kept as is even if these include unicode
         // Domains are punycoded by default
         // 'jõgeva.ee' will be converted to 'xn--jgeva-dua.ee'
         // non-unicode domains are left as is
 
-        return user + '@' + punycode.toASCII(domain.toLowerCase());
+        let encodedDomain;
+
+        try {
+            encodedDomain = punycode.toASCII(domain.toLowerCase());
+        } catch (err) {
+            // keep as is?
+        }
+
+        if (user.indexOf(' ') >= 0) {
+            if (user.charAt(0) !== '"') {
+                user = '"' + user;
+            }
+            if (user.substr(-1) !== '"') {
+                user = user + '"';
+            }
+        }
+
+        return `${user}@${encodedDomain}`;
     }
 
     /**
      * If needed, mime encodes the name part
      *
diff --git a/package.json b/package.json
index d207007..bbb54d0 100644
--- a/package.json
+++ b/package.json
@@ -1,8 +1,8 @@
 {
     "name": "nodemailer",
-    "version": "6.6.0",
+    "version": "6.6.1",
     "description": "Easy as cake e-mail sending from your Node.js applications",
     "main": "lib/nodemailer.js",
     "scripts": {
         "test": "grunt"
     },
@@ -29,11 +29,11 @@
         "grunt-eslint": "23.0.0",
         "grunt-mocha-test": "0.13.3",
         "libbase64": "1.2.1",
         "libmime": "5.0.0",
         "libqp": "1.1.0",
-        "mocha": "8.3.2",
+        "mocha": "8.4.0",
         "nodemailer-ntlm-auth": "1.0.1",
         "proxy": "1.0.2",
         "proxy-test-server": "1.0.0",
         "sinon": "10.0.0",
         "smtp-server": "3.8.0"

Vulnerable code:     - 15
    text: 'Test\n 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ö\r\nsage',
                    values.push(address.address);
                    values.push(this._encodeAddressName(address.name) + ' <' + address.address + '>');
                values.push(
                    this._encodeAddressName(address.name) + ':' + (address.group.length ? this._convertAddresses(address.group, uniqueList) : '').trim() + ';'
                );
        address = (address || '').toString().trim();
        return user + '@' + punycode.toASCII(domain.toLowerCase());
    "version": "6.6.0",
        "mocha": "8.3.2",
Fixed code:     - 16
## 6.6.1 2021-05-23

-   Fixed address formatting issue where newlines in an email address, if provided via address object, were not properly removed. Reported by tmazeika (#1289)

    text: `Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, 'and what is the use of a book,' thought Alice 'without pictures or conversations?'

So she was considering in her own mind (as well as she could, for the hot day made her feel very sleepy and stupid), whether the pleasure of making a daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly a White Rabbit with pink eyes ran close by her.`,
                    values.push(address.address.indexOf(' ') >= 0 ? `<${address.address}>` : `${address.address}`);
                    values.push(`${this._encodeAddressName(address.name)} <${address.address}>`);
                let groupListAddresses = (address.group.length ? this._convertAddresses(address.group, uniqueList) : '').trim();
                values.push(`${this._encodeAddressName(address.name)}:${groupListAddresses};`);
        address = (address || '')
            .toString()
            .replace(/[\x00-\x1F<>]+/g, ' ') // remove unallowed characters
            .trim();

        let encodedDomain;

        try {
            encodedDomain = punycode.toASCII(domain.toLowerCase());
        } catch (err) {
            // keep as is?
        }

        if (user.indexOf(' ') >= 0) {
            if (user.charAt(0) !== '"') {
                user = '"' + user;
            }
            if (user.substr(-1) !== '"') {
                user = user + '"';
            }
        }

        return `${user}@${encodedDomain}`;
    "version": "6.6.1",
        "mocha": "8.4.0",