CVE-2021-25978 (JSON, published 2021-11-07T18:15Z)
Description: value: Apostrophe CMS versions between 2.63.0 to 3.3.1 are vulnerable to Stored XSS where an editor uploads an SVG file that contains malicious JavaScript onto the Images module, which triggers XSS once viewed.
Severity: LOW (CVSS v3 base score: 5.4)
Weakness: CWE-79 \u2014 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
Repository: https://github.com/apostrophecms/apostrophe
Files changed:
CHANGELOG.md
modules/@apostrophecms/attachment/index.js
modules/@apostrophecms/i18n/i18n/en.json
package.json
Commit message: sanitize SVG uploads, including previous uploads


Vulnerable code:
          const docs = await self.db.find({ _id: { $gt: lastId } }).limit(batchSize).sort({ _id: 1 }).toArray();

Fixed code:
## 3.3.2 - 2021-09-07

### Security

Users with permission to upload SVG files were previously able to do so even if they contained XSS attacks. In Apostrophe 3.x, the general public so far never has access to upload SVG files, so the risk is minor but could be used to phish access from an admin user uploading a file. While Apostrophe typically displays SVG files using the `img` tag, which ignores XSS vectors, an XSS attack could still be carried out if the image were opened directly via the Apostrophe media library's convenience link for doing so. Beginning in version 3.3.2 all SVG uploads are sanitized via DOMPurify to remove XSS attack vectors. In addition, all existing SVG attachments not already validated are passed through DOMPurify during a migration upon deployment of version 3.3.2. 

const createDOMPurify = require('dompurify');
const { JSDOM } = require('jsdom');
    self.addSvgSanitizationMigration();
        if (info.extension === 'svg') {
          try {
            await self.sanitizeSvg(file, info);
          } catch (e) {
            // Currently DOMPurify passes invalid SVG content without comment as long
            // as it's not an SVG XSS attack vector, but make provision to report
            // a relevant error if that changes
            throw self.apos.error('invalid', req.t('apostrophe:fileInvalid'));
          }
        }
      // Given a path to a local svg file, sanitize any XSS attack vectors that
      // may be present in the file. The caller is responsible for catching any
      // exception thrown and treating that as an invalid file but there is no
      // guarantee that invalid SVG files will be detected or cleaned up, only
      // XSS attacks.
      async sanitizeSvg(path) {
        const readFile = require('util').promisify(fs.readFile);
        const writeFile = require('util').promisify(fs.writeFile);
        const window = new JSDOM('').window;
        const DOMPurify = createDOMPurify(window);
        const dirty = await readFile(path);
        const clean = DOMPurify.sanitize(dirty);
        return writeFile(path, clean);
      },
          const docs = await self.db.find({
            ...(criteria || {}),
            _id: { $gt: lastId }
          }).limit(batchSize).sort({ _id: 1 }).toArray();
      async addSvgSanitizationMigration() {
        self.apos.migration.add('svg-sanitization', async () => {
          return self.each({
            extension: 'svg',
            sanitized: {
              $ne: true
            },
          }, 1, async attachment => {
            const tempFile = self.uploadfs.getTempPath() + '/' + self.apos.util.generateId() + '.' + attachment.extension;
            const copyIn = require('util').promisify(self.uploadfs.copyIn);
            const copyOut = require('util').promisify(self.uploadfs.copyOut);
            const uploadfsPath = self.url(attachment, { uploadfsPath: true });
            try {
              await copyOut(uploadfsPath, tempFile);
              await self.sanitizeSvg(tempFile);
              await copyIn(tempFile, uploadfsPath);
              await self.db.update({
                _id: attachment._id
              }, {
                $set: {
                  sanitized: true
                }
              });
            } catch (e) {
              console.error(e);
              // This condition shouldn't occur, but do warn the operator if it does
              // (possibly on input that is not really an SVG file at all)
              self.apos.util.error(`Warning: unable to sanitize SVG file ${uploadfsPath}`);
            }
          });
        });
      },
  "fileInvalid": "File was not accepted. It may be corrupted or its content may not match its file extension.",
    "dompurify": "^2.3.1",
    "jsdom": "^17.0.0",