Publicus/cvefixes-security-ir-graphrag huggingface dataset:
CVE-2018-14345: Insufficient Session Expiration (CWE-613)
value: An issue was discovered in SDDM through 0.17.0. If configured with ReuseSession=true, the password is not checked for users with an already existing session. Any user with access to the system D-Bus can therefore unlock any graphical session. This is related to daemon/Display.cpp and helper/backend/PamBackend.cpp.
CWE description: According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
CVSS v3 base score: 7.5
Published: 2018-07-17T14:29Z
Repository: https://github.com/sddm/sddm
Language: C++
Files changed: src/daemon/Display.cpp, src/helper/backend/PamBackend.cpp
Commit date: 2018-07-17 13:09:58 +0200
Commit message: Fix authentication when reusing an existing session

- Check the success value before unlocking the session
- Don't attempt to use the nonexistant "sddm-check" PAM service

Diff: diff --git a/src/daemon/Display.cpp b/src/daemon/Display.cpp
index 5abfc9a..57d7ecb 100644
--- a/src/daemon/Display.cpp
+++ b/src/daemon/Display.cpp
@@ -337,11 +337,13 @@ namespace SDDM {
         if (existingSessionId.isNull()) {
             m_auth->setSession(session.exec());
         } else {
             //we only want to unlock the session if we can lock in, so we want to go via PAM auth, but not start a new session
             //by not setting the session and the helper will emit authentication and then quit
-            connect(m_auth, &Auth::authentication, this, [=](){
+            connect(m_auth, &Auth::authentication, this, [=](const QString &, bool success){
+                if(!success)
+                    return;
                 qDebug() << "activating existing seat";
                 OrgFreedesktopLogin1ManagerInterface manager(Logind::serviceName(), Logind::managerPath(), QDBusConnection::systemBus());
                 manager.UnlockSession(existingSessionId);
                 manager.ActivateSession(existingSessionId);
             });
diff --git a/src/helper/backend/PamBackend.cpp b/src/helper/backend/PamBackend.cpp
index 69cbd2c..5467282 100644
--- a/src/helper/backend/PamBackend.cpp
+++ b/src/helper/backend/PamBackend.cpp
@@ -217,12 +217,10 @@ namespace SDDM {
 
         QString service = QStringLiteral("sddm");
 
         if (user == QStringLiteral("sddm") && m_greeter)
             service = QStringLiteral("sddm-greeter");
-        else if (m_app->session()->path().isEmpty())
-            service = QStringLiteral("sddm-check");
         else if (m_autologin)
             service = QStringLiteral("sddm-autologin");
         result = m_pam->start(service, user);
 
         if (!result)

Vulnerable code:             connect(m_auth, &Auth::authentication, this, [=](){
        else if (m_app->session()->path().isEmpty())
            service = QStringLiteral("sddm-check");
Fixed code:             connect(m_auth, &Auth::authentication, this, [=](const QString &, bool success){
                if(!success)
                    return;
CVE-2015-2298: Exposure of Sensitive Information to an Unauthorized Actor (CWE-200)
value: node/utils/ExportEtherpad.js in Etherpad 1.5.x before 1.5.2 might allow remote attackers to obtain sensitive information by leveraging an improper substring check when exporting a padID.
CWE description: The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
CVSS v3 base score: 7.5
Published: 2018-01-12T17:29Z
Repository: https://github.com/ether/etherpad-lite
Language: JavaScript
Files changed: src/node/utils/ExportEtherpad.js
Commit date: 2015-03-14 00:02:23 +0100
Commit message: oops, fix export with wildcards

Diff: diff --git a/src/node/utils/ExportEtherpad.js b/src/node/utils/ExportEtherpad.js
index b7d43852..46ae0d7a 100644
--- a/src/node/utils/ExportEtherpad.js
+++ b/src/node/utils/ExportEtherpad.js
@@ -21,13 +21,23 @@ var ERR = require("async-stacktrace");
 
 exports.getPadRaw = function(padId, callback){
   async.waterfall([
   function(cb){
 
+    // Get the Pad
+    db.findKeys("pad:"+padId, null, function(err,padcontent){
+      if(!err){
+        cb(err, padcontent);
+      }
+    })
+  },
+  function(padcontent,cb){
+
     // Get the Pad available content keys
-    db.findKeys("pad:"+padId+"*", null, function(err,records){
+    db.findKeys("pad:"+padId+":*", null, function(err,records){
       if(!err){
+        for (var key in padcontent) { records.push(padcontent[key]);}
         cb(err, records);
       }
     })
   },
   function(records, cb){

Vulnerable code:     db.findKeys("pad:"+padId+"*", null, function(err,records){
Fixed code:     // Get the Pad
    db.findKeys("pad:"+padId, null, function(err,padcontent){
      if(!err){
        cb(err, padcontent);
      }
    })
  },
  function(padcontent,cb){

    db.findKeys("pad:"+padId+":*", null, function(err,records){
        for (var key in padcontent) { records.push(padcontent[key]);}
CVE-2015-3309: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') (CWE-22)
value: Directory traversal vulnerability in node/utils/Minify.js in Etherpad 1.1.2 through 1.5.4 allows remote attackers to read arbitrary files with permissions of the user running the service via a .. (dot dot) in the path parameter of HTTP API requests. NOTE: This vulnerability is due to an incomplete fix to CVE-2015-3297.
CWE description: The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
CVSS v3 base score: 7.5
Published: 2020-02-13T20:15Z
Repository: https://github.com/ether/etherpad-lite
Language: JavaScript
Files changed: src/node/utils/Minify.js
Commit date: 2015-04-12 17:12:35 +0200
Commit message: dont allow directory traversal #2

Diff: diff --git a/src/node/utils/Minify.js b/src/node/utils/Minify.js
index ba45ab75..3b0be38c 100644
--- a/src/node/utils/Minify.js
+++ b/src/node/utils/Minify.js
@@ -163,11 +163,10 @@ function minify(req, res, next)
 
     if (plugins.plugins[library] && match[3]) {
       var plugin = plugins.plugins[library];
       var pluginPath = plugin.package.realPath;
       filename = path.relative(ROOT_DIR, pluginPath + libraryPath);
-      filename = filename.replace(/\\/g, '/'); // Windows (safe generally?)
     } else if (LIBRARY_WHITELIST.indexOf(library) != -1) {
       // Go straight into node_modules
       // Avoid `require.resolve()`, since 'mustache' and 'mustache/index.js'
       // would end up resolving to logically distinct resources.
       filename = '../node_modules/' + library + libraryPath;

Vulnerable code:       filename = filename.replace(/\\/g, '/'); // Windows (safe generally?)
CVE-2015-4085: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') (CWE-22)
value: Directory traversal vulnerability in node/hooks/express/tests.js in Etherpad frontend tests before 1.6.1.
CWE description: The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
CVSS v3 base score: 7.5
Published: 2017-09-07T20:29Z
Repository: https://github.com/ether/etherpad-lite
Language: JavaScript
Files changed: src/node/hooks/express/tests.js
Commit date: 2015-04-11 09:05:32 +0100
Commit message: fix an issue in the path handling that allowed directory traversal

Diff: diff --git a/src/node/hooks/express/tests.js b/src/node/hooks/express/tests.js
index 3157d68e..dfe02c2a 100644
--- a/src/node/hooks/express/tests.js
+++ b/src/node/hooks/express/tests.js
@@ -21,19 +21,23 @@ exports.expressCreateServer = function (hook_name, args, cb) {
       res.send("var specs_list = " + JSON.stringify(files.sort()) + ";\n");
     });
 
   });
 
+  var rootTestFolder = path.join(npm.root, "..", "/tests/frontend/");
   var url2FilePath = function(url){
     var subPath = url.substr("/tests/frontend".length);
     if (subPath == ""){
       subPath = "index.html"
     }
     subPath = subPath.split("?")[0];
 
-    var filePath = path.normalize(npm.root + "/../tests/frontend/")
-    filePath += subPath.replace("..", "");
+    var filePath = path.normalize(path.join(rootTestFolder, subPath));
+    // make sure we jail the paths to the test folder, otherwise serve index
+    if (filePath.indexOf(rootTestFolder) !== 0) {
+      filePath = path.normalize(path.join(rootTestFolder, "index.html"));
+    }
     return filePath;
   }
 
   args.app.get('/tests/frontend/specs/*', function (req, res) {
     var specFilePath = url2FilePath(req.url);

Vulnerable code:     var filePath = path.normalize(npm.root + "/../tests/frontend/")
    filePath += subPath.replace("..", "");
Fixed code:   var rootTestFolder = path.join(npm.root, "..", "/tests/frontend/");
    var filePath = path.normalize(path.join(rootTestFolder, subPath));
    // make sure we jail the paths to the test folder, otherwise serve index
    if (filePath.indexOf(rootTestFolder) !== 0) {
      filePath = path.normalize(path.join(rootTestFolder, "index.html"));
    }
CVE-2018-6834: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') (CWE-79)
value: static/js/pad_utils.js in Etherpad Lite before v1.6.3 has XSS via window.location.href.
CWE description: 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.
CVSS v3 base score: 6.1
Published: 2018-02-08T07:29Z
Repository: https://github.com/ether/etherpad-lite
Language: Unknown
Commit date: 2018-01-31 08:25:59 +0000
Commit message: Merge pull request #3313 from rhelmer/sanitize-window-location

better sanitize window location in error messages
CVE-2018-6835: Improper Input Validation (CWE-20)
value: node/hooks/express/apicalls.js in Etherpad Lite before v1.6.3 mishandles JSONP, which allows remote attackers to bypass intended access restrictions.
CWE description: The product receives input or data, but it does
        not validate or incorrectly validates that the input has the
        properties that are required to process the data safely and
        correctly.
CVSS v3 base score: 9.8
Published: 2018-02-08T07:29Z
Repository: https://github.com/ether/etherpad-lite
Language: Unknown
Commit date: 2018-01-31 08:25:43 +0000
Commit message: Merge pull request #3314 from rhelmer/sanitize-jsonp

better sanitize jsonp
CVE-2018-9845: Improper Handling of Case Sensitivity (CWE-178)
value: Etherpad Lite before 1.6.4 is exploitable for admin access.
CWE description: The product does not properly account for differences in case sensitivity when accessing or determining the properties of a resource, leading to inconsistent results.
CVSS v3 base score: 9.8
Published: 2018-04-29T18:29Z
Repository: https://github.com/ether/etherpad-lite
Language: JavaScript
Files changed: src/node/hooks/express/webaccess.js
Commit date: 2018-04-06 22:21:33 +0200
Commit message: Update webaccess.js
Diff: diff --git a/src/node/hooks/express/webaccess.js b/src/node/hooks/express/webaccess.js
index 1faceec7c..294750374 100644
--- a/src/node/hooks/express/webaccess.js
+++ b/src/node/hooks/express/webaccess.js
@@ -18,11 +18,11 @@ exports.basicAuth = function (req, res, next) {
 
   var authorize = function (cb) {
     // Do not require auth for static paths and the API...this could be a bit brittle
     if (req.path.match(/^\/(static|javascripts|pluginfw|api)/)) return cb(true);
 
-    if (req.path.indexOf('/admin') != 0) {
+    if (req.path.toLowerCase().indexOf('/admin') != 0) {
       if (!settings.requireAuthentication) return cb(true);
       if (!settings.requireAuthorization && req.session && req.session.user) return cb(true);
     }
 
     if (req.session && req.session.user && req.session.user.is_admin) return cb(true);

Vulnerable code:     if (req.path.indexOf('/admin') != 0) {
Fixed code:     if (req.path.toLowerCase().indexOf('/admin') != 0) {
CVE-2019-18209: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') (CWE-79)
value: templates/pad.html in Etherpad-Lite 1.7.5 has XSS when the browser does not encode the path of the URL, as demonstrated by Internet Explorer.
CWE description: 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.
CVSS v3 base score: 6.1
Published: 2019-10-19T01:15Z
Repository: https://github.com/ether/etherpad-lite
Language: HTML
Files changed: src/templates/pad.html
Commit date: 2019-10-18 21:00:11 +0100
Commit message: security: support for clean & safe error handling on IE 11

Added pad_utils sanitization for clean and safe error handling on browsers that
do not encode the path of the URL.

Edited by muxator based on https://github.com/ether/etherpad-lite/pull/3647,
to be able to apply the patch on develop (the PR was for master), and perform
minor cleanups (mainly spurious statements).

Closes #3647.

Diff: diff --git a/src/templates/pad.html b/src/templates/pad.html
index 61b9f2268..0d3b7e476 100644
--- a/src/templates/pad.html
+++ b/src/templates/pad.html
@@ -359,20 +359,22 @@
 
         <% e.end_block(); %>
 
         <% e.begin_block("scripts"); %>
         <script type="text/javascript">
+            var padutils = require('../static/js/pad_utils').padutils;
+
             // @license magnet:?xt=urn:btih:8e4f440f4c65981c5bf93c76d35135ba5064d8b7&dn=apache-2.0.txt
             (function() {
               // Display errors on page load to the user
               // (Gets overridden by padutils.setupGlobalExceptionHandler)
               var originalHandler = window.onerror;
               window.onerror = function(msg, url, line) {
                 var box   = document.getElementById('editorloadingbox');
                 box.innerHTML = '<p><b>An error occurred while loading the pad</b></p>'
                               + '<p><b>'+msg+'</b> '
-                              + '<small>in '+ url +' (line '+ line +')</small></p>';
+                              + '<small>in '+ padutils.escapeHTML(url) +' (line '+ line +')</small></p>';
                 // call original error handler
                 if(typeof(originalHandler) == 'function') originalHandler.call(null, arguments);
               };
             })();
             // @license-end

Vulnerable code:                               + '<small>in '+ url +' (line '+ line +')</small></p>';
Fixed code:             var padutils = require('../static/js/pad_utils').padutils;

                              + '<small>in '+ padutils.escapeHTML(url) +' (line '+ line +')</small></p>';
CVE-2020-22783: Cleartext Storage of Sensitive Information (CWE-312)
value: Etherpad <1.8.3 stored passwords used by users insecurely in the database and in log files. This affects every database backend supported by Etherpad.
CWE description: The product stores sensitive information in cleartext within a resource that might be accessible to another control sphere.
CVSS v3 base score: 6.5
Published: 2021-04-28T21:15Z
Repository: https://github.com/ether/etherpad-lite
Language: JavaScript
Files changed: src/node/db/SessionStore.js
Commit date: 2020-04-01 03:39:05 +0200
Commit message: SessionStore: replace password with PASSWORD_HIDDEN when storing in db

Fixes #3421.

Diff: diff --git a/src/node/db/SessionStore.js b/src/node/db/SessionStore.js
index 647cbbc8d..263c7d6ee 100644
--- a/src/node/db/SessionStore.js
+++ b/src/node/db/SessionStore.js
@@ -36,10 +36,15 @@ SessionStore.prototype.get = function(sid, fn) {
 };
 
 SessionStore.prototype.set = function(sid, sess, fn) {
   messageLogger.debug('SET ' + sid);
 
+  // don't store passwords in DB
+  if (sess.user && sess.user.password) {
+    sess.user.password = "PASSWORD_HIDDEN";
+  }
+
   db.set("sessionstorage:" + sid, sess);
   if (fn) {
     process.nextTick(fn);
   }
 };

Fixed code:   // don't store passwords in DB
  if (sess.user && sess.user.password) {
    sess.user.password = "PASSWORD_HIDDEN";
  }
CVE-2021-34817: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') (CWE-79)
value: A Cross-Site Scripting (XSS) issue in the chat component of Etherpad 1.8.13 allows remote attackers to inject arbitrary JavaScript or HTML by importing a crafted pad.
CWE description: 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.
CVSS v3 base score: 6.1
Published: 2021-07-19T14:15Z
Repository: https://github.com/ether/etherpad-lite
Language: JavaScript
Files changed: src/static/js/chat.js
Commit date: 2021-04-07 23:29:27 -0400
Commit message: escape userId before setting it as HTML attribute

Diff: diff --git a/src/static/js/chat.js b/src/static/js/chat.js
index a3c475616..00811ff44 100755
--- a/src/static/js/chat.js
+++ b/src/static/js/chat.js
@@ -127,10 +127,11 @@ exports.chat = (() => {
         console.warn(
             'The "userId" field of a chat message coming from the server was not present. ' +
             'Replacing with "unknown". This may be a bug or a database corruption.');
       }
 
+      msg.userId = padutils.escapeHtml(msg.userId);
       const authorClass = `author-${msg.userId.replace(/[^a-y0-9]/g, (c) => {
         if (c === '.') return '-';
         return `z${c.charCodeAt(0)}z`;
       })}`;
 

Fixed code:       msg.userId = padutils.escapeHtml(msg.userId);
CVE-2018-9275: Exposure of Sensitive Information to an Unauthorized Actor (CWE-200)
value: In check_user_token in util.c in the Yubico PAM module (aka pam_yubico) 2.18 through 2.25, successful logins can leak file descriptors to the auth mapping file, which can lead to information disclosure (serial number of a device) and/or DoS (reaching the maximum number of file descriptors).
CWE description: The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
CVSS v3 base score: 8.2
Published: 2018-04-04T18:29Z
Repository: https://github.com/Yubico/yubico-pam
Language: C
Files changed: util.c
Commit date: 2018-04-03 09:19:53 +0200
Commit message: util: make sure to close the authfile before returning success

fixes #136

Diff: diff --git a/util.c b/util.c
index 6cb4a79..32bca06 100644
--- a/util.c
+++ b/util.c
@@ -165,10 +165,12 @@ check_user_token (const char *authfile,
 		  D (debug_file, "Authorization token: %s", s_token);
 	      if (s_token && otp_id && strcmp (otp_id, s_token) == 0)
 		{
 		  if(verbose)
 		      D (debug_file, "Match user/token as %s/%s", username, otp_id);
+
+		  fclose(opwfile);
 		  return AUTH_FOUND;
 		}
 	    }
 	  while (s_token != NULL);
 	}

Fixed code: 
		  fclose(opwfile);
CVE-2012-3542: Permissions, Privileges, and Access Controls (CWE-264)
value: OpenStack Keystone, as used in OpenStack Folsom before folsom-rc1 and OpenStack Essex (2012.1), allows remote attackers to add an arbitrary user to an arbitrary tenant via a request to update the user's default tenant to the administrative API.  NOTE: this identifier was originally incorrectly assigned to an open redirect issue, but the correct identifier for that issue is CVE-2012-3540.
CWE description: Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.
Published: 2012-09-05T23:55Z
Repository: https://github.com/openstack/keystone
Language: Python
Files changed: keystone/identity/core.py
Commit date: 2012-08-23 08:02:55 -0500
Commit message: Require authz to update user's tenant (bug 1040626)

Change-Id: I82f80b84af2bc4db00b3dcb87a2ec338816a82e9

Diff: diff --git a/keystone/identity/core.py b/keystone/identity/core.py
index aec0b753..c9c496c2 100644
--- a/keystone/identity/core.py
+++ b/keystone/identity/core.py
@@ -513,10 +513,11 @@ class UserController(wsgi.Application):
     def set_user_password(self, context, user_id, user):
         return self.update_user(context, user_id, user)
 
     def update_user_tenant(self, context, user_id, user):
         """Update the default tenant."""
+        self.assert_admin(context)
         # ensure that we're a member of that tenant
         tenant_id = user.get('tenantId')
         self.identity_api.add_user_to_tenant(context, tenant_id, user_id)
         return self.update_user(context, user_id, user)
 

Fixed code:         self.assert_admin(context)
CVE-2012-4456: Improper Authentication (CWE-287)
value: The (1) OS-KSADM/services and (2) tenant APIs in OpenStack Keystone Essex before 2012.1.2 and Folsom before folsom-2 do not properly validate X-Auth-Token, which allow remote attackers to read the roles for an arbitrary user or get, create, or delete arbitrary services.
CWE description: When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct.
Published: 2012-10-09T15:55Z
Repository: https://github.com/openstack/keystone
Language: Python
Files changed: keystone/identity/core.py, tests/test_content_types.py
Commit date: 2012-06-03 12:24:10 -0500
Commit message: Require authz for user role list (bug 1006815)

Change-Id: I65f25dcca3e265f44746930917434b45e64de15e

Diff: diff --git a/keystone/identity/core.py b/keystone/identity/core.py
index 57654b85..3128c706 100644
--- a/keystone/identity/core.py
+++ b/keystone/identity/core.py
@@ -465,10 +465,11 @@ class RoleController(wsgi.Application):
 
         Since we're trying to ignore the idea of user-only roles we're
         not implementing them in hopes that the idea will die off.
 
         """
+        self.assert_admin(context)
         if tenant_id is None:
             raise exception.NotImplemented(message='User roles not supported: '
                                                    'tenant ID required')
 
         user = self.identity_api.get_user(context, user_id)
diff --git a/tests/test_content_types.py b/tests/test_content_types.py
index df73dff6..49550848 100644
--- a/tests/test_content_types.py
+++ b/tests/test_content_types.py
@@ -585,10 +585,21 @@ class JsonTestCase(RestfulTestCase, CoreApiTests):
         r = self.admin_request(method='DELETE',
                                path=service_path,
                                expected_status=401)
         self.assertValidErrorResponse(r)
 
+    def test_user_role_list_requires_auth(self):
+        """User role list should 401 without an X-Auth-Token (bug 1006815)."""
+        # values here don't matter because we should 401 before they're checked
+        path = '/v2.0/tenants/%(tenant_id)s/users/%(user_id)s/roles' % {
+                'tenant_id': uuid.uuid4().hex,
+                'user_id': uuid.uuid4().hex,
+        }
+
+        r = self.admin_request(path=path, expected_status=401)
+        self.assertValidErrorResponse(r)
+
 
 class XmlTestCase(RestfulTestCase, CoreApiTests):
     xmlns = 'http://docs.openstack.org/identity/api/v2.0'
     content_type = 'xml'
 

Fixed code:         self.assert_admin(context)
    def test_user_role_list_requires_auth(self):
        """User role list should 401 without an X-Auth-Token (bug 1006815)."""
        # values here don't matter because we should 401 before they're checked
        path = '/v2.0/tenants/%(tenant_id)s/users/%(user_id)s/roles' % {
                'tenant_id': uuid.uuid4().hex,
                'user_id': uuid.uuid4().hex,
        }

        r = self.admin_request(path=path, expected_status=401)
        self.assertValidErrorResponse(r)
CVE-2021-31597: Improper Certificate Validation (CWE-295)
value: The xmlhttprequest-ssl package before 1.6.1 for Node.js disables SSL certificate validation by default, because rejectUnauthorized (when the property exists but is undefined) is considered to be false within the https.request function of Node.js. In other words, no certificate is ever rejected.
CWE description: The product does not validate, or incorrectly validates, a certificate.
CVSS v3 base score: 9.4
Published: 2021-04-23T00:15Z
Repository: https://github.com/mjwwit/node-XMLHttpRequest
Language: JSON
Files changed: lib/XMLHttpRequest.js, package.json
Commit date: 2021-04-19 12:21:05 +0200
Commit message: Fix issue where rejectUnauthorized would default to false instead of true

Diff: diff --git a/lib/XMLHttpRequest.js b/lib/XMLHttpRequest.js
index 2814f5d..3c23907 100644
--- a/lib/XMLHttpRequest.js
+++ b/lib/XMLHttpRequest.js
@@ -395,11 +395,11 @@ function XMLHttpRequest(opts) {
       options.key = opts.key;
       options.passphrase = opts.passphrase;
       options.cert = opts.cert;
       options.ca = opts.ca;
       options.ciphers = opts.ciphers;
-      options.rejectUnauthorized = opts.rejectUnauthorized;
+      options.rejectUnauthorized = opts.rejectUnauthorized === false ? false : true;
     }
 
     // Reset error flag
     errorFlag = false;
     // Handle async requests
@@ -440,11 +440,11 @@ function XMLHttpRequest(opts) {
             newOptions.key = opts.key;
             newOptions.passphrase = opts.passphrase;
             newOptions.cert = opts.cert;
             newOptions.ca = opts.ca;
             newOptions.ciphers = opts.ciphers;
-            newOptions.rejectUnauthorized = opts.rejectUnauthorized;
+            newOptions.rejectUnauthorized = opts.rejectUnauthorized === false ? false : true;
           }
 
           // Issue the new request
           request = doRequest(newOptions, responseHandler).on('error', errorHandler);
           request.end();
diff --git a/package.json b/package.json
index a6c8bc4..235564a 100644
--- a/package.json
+++ b/package.json
@@ -1,9 +1,9 @@
 {
   "name": "xmlhttprequest-ssl",
   "description": "XMLHttpRequest for Node",
-  "version": "1.6.0",
+  "version": "1.6.1",
   "author": {
     "name": "Michael de Wit"
   },
   "keywords": [
     "xhr",

Vulnerable code:       options.rejectUnauthorized = opts.rejectUnauthorized;
            newOptions.rejectUnauthorized = opts.rejectUnauthorized;
  "version": "1.6.0",
Fixed code:       options.rejectUnauthorized = opts.rejectUnauthorized === false ? false : true;
            newOptions.rejectUnauthorized = opts.rejectUnauthorized === false ? false : true;
  "version": "1.6.1",
CVE-2018-16789: Loop with Unreachable Exit Condition ('Infinite Loop') (CWE-835)
value: libhttp/url.c in shellinabox through 2.20 has an implementation flaw in the HTTP request parsing logic. By sending a crafted multipart/form-data HTTP request, an attacker could exploit this to force shellinaboxd into an infinite loop, exhausting available CPU resources and taking the service down.
CWE description: The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
CVSS v3 base score: 7.5
Published: 2019-03-21T16:00Z
Repository: https://github.com/shellinabox/shellinabox
Language: Other
Files changed: debian/changelog, libhttp/url.c
Commit date: 2019-01-27 20:18:48 -0800
Commit message: Rolling code for version 2.21

Diff: diff --git a/debian/changelog b/debian/changelog
index 4d2f7cd..52e8aa4 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,5 +1,11 @@
+shellinabox (2.21) unstable; urgency=medium
+
+  * Patched DoS vulnerability reported by Imre Rad.
+
+ -- Marc Singer <elf@debian.org>  Sun, 09 Sep 2018 12:10:40 -0700
+
 shellinabox (2.20) unstable; urgency=medium
 
   * Fixed issue #222, LOGIN service
   * Fixed issue #360, ignore escape sequences to fix dir listing
   * Fix for function key presses
diff --git a/libhttp/url.c b/libhttp/url.c
index ed29475..a73cde9 100644
--- a/libhttp/url.c
+++ b/libhttp/url.c
@@ -311,10 +311,25 @@ static void urlParsePostBody(struct URL *url,
 				     "form-data\"!");
               }
             }
           }
         }
+        /* elf-2018.09.09: Detection of broken multipart/form-data
+           fixes DoS vulnerability.
+
+           On 9/9/18 10:43 AM, Imre Rad wrote:
+           Hi Markus, Marc!
+
+           I identified a vulnerability today in Shellinabox, it is
+           remote a denial of service, shellinaboxd eating up 100% cpu
+           and not processing subsequent requests after the attack was
+           mounted.
+        */
+        else {
+          warn ("[http] Ignorning broken multipart/form-data");
+          break;
+        }
       }
       if (lastPart) {
         warn("[http] Missing final \"boundary\" for \"multipart/form-data\"!");
       }
     } else {

Fixed code: shellinabox (2.21) unstable; urgency=medium

  * Patched DoS vulnerability reported by Imre Rad.

 -- Marc Singer <elf@debian.org>  Sun, 09 Sep 2018 12:10:40 -0700

        /* elf-2018.09.09: Detection of broken multipart/form-data
           fixes DoS vulnerability.

           On 9/9/18 10:43 AM, Imre Rad wrote:
           Hi Markus, Marc!

           I identified a vulnerability today in Shellinabox, it is
           remote a denial of service, shellinaboxd eating up 100% cpu
           and not processing subsequent requests after the attack was
           mounted.
        */
        else {
          warn ("[http] Ignorning broken multipart/form-data");
          break;
        }
CVE-2020-26300: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') (CWE-78)
value: systeminformation is an npm package that provides system and OS information library for node.js. In systeminformation before version 4.26.2 there is a command injection vulnerability. Problem was fixed in version 4.26.2 with a shell string sanitation fix.
CWE description: The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
CVSS v3 base score: 9.8
Published: 2021-09-09T01:15Z
Repository: https://github.com/sebhildebrandt/systeminformation
Language: JavaScript
Files changed: lib/util.js
Commit date: 2020-05-19 17:02:51 +0200
Commit message: improved shell sanitation

Diff: diff --git a/lib/util.js b/lib/util.js
index 19df5e7..e7a87dc 100644
--- a/lib/util.js
+++ b/lib/util.js
@@ -501,10 +501,13 @@ function sanitizeShellString(str) {
   result = result.replace(/\)/g, "");
   result = result.replace(/\(/g, "");
   result = result.replace(/\$/g, "");
   result = result.replace(/#/g, "");
   result = result.replace(/\\/g, "");
+  result = result.replace(/\t/g, "");
+  result = result.replace(/\n/g, "");
+  result = result.replace(/\"/g, "");
   return result
 }
 
 function noop() { }
 

Fixed code:   result = result.replace(/\t/g, "");
  result = result.replace(/\n/g, "");
  result = result.replace(/\"/g, "");
CVE-2021-21388: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') (CWE-78)
value: systeminformation is an open source system and OS information library for node.js. A command injection vulnerability has been discovered in versions of systeminformation prior to 5.6.4. The issue has been fixed with a parameter check on user input. Please upgrade to version >= 5.6.4. If you cannot upgrade, be sure to check or sanitize service parameters that are passed to si.inetLatency(), si.inetChecksite(), si.services(), si.processLoad() and other commands. Only allow strings, reject any arrays. String sanitation works as expected.
CWE description: The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
CVSS v3 base score: 9.8
Published: 2021-04-29T18:15Z
Repository: https://github.com/sebhildebrandt/systeminformation
Language: JavaScript
Files changed: lib/internet.js
Commit date: 2021-03-15 11:51:30 +0100
Commit message: sanitizeShellString() and other security improvements

Diff: diff --git a/lib/internet.js b/lib/internet.js
index 1f75a712..2dc0d5a0 100644
--- a/lib/internet.js
+++ b/lib/internet.js
@@ -12,11 +12,10 @@
 // ==================================================================================
 // 12. Internet
 // ----------------------------------------------------------------------------------
 
 // const exec = require('child_process').exec;
-const execFile = require('child_process').execFile;
 const util = require('./util');
 
 let _platform = process.platform;
 
 const _linux = (_platform === 'linux');
@@ -211,13 +210,13 @@ function inetLatency(host, callback) {
       }
       if (_windows) {
         let result = null;
         try {
           const params = hostSanitized + ' -n 1';
-          execFile('ping', params.split(' '), util.execOptsWin, function (error, stdout) {
-            if (!error) {
-              let lines = stdout.toString().split('\r\n');
+          util.execSave('ping', params.split(' '), util.execOptsWin).then((stdout) => {
+            if (stdout) {
+              let lines = stdout.split('\r\n');
               lines.shift();
               lines.forEach(function (line) {
                 if ((line.toLowerCase().match(/ms/g) || []).length === 3) {
                   let l = line.replace(/ +/g, ' ').split(' ');
                   if (l.length > 6) {

Vulnerable code: const execFile = require('child_process').execFile;
          execFile('ping', params.split(' '), util.execOptsWin, function (error, stdout) {
            if (!error) {
              let lines = stdout.toString().split('\r\n');
Fixed code:           util.execSave('ping', params.split(' '), util.execOptsWin).then((stdout) => {
            if (stdout) {
              let lines = stdout.split('\r\n');
CVE-2024-24819: Cross-Site Request Forgery (CSRF) (CWE-352)
value: icingaweb2-module-incubator is a working project of bleeding edge Icinga Web 2 libraries. In affected versions the class `gipfl\Web\Form` is the base for various concrete form implementations [1] and provides protection against cross site request forgery (CSRF) by default. This is done by automatically adding an element with a CSRF token to any form, unless explicitly disabled, but even if enabled, the CSRF token (sent during a client's submission of a form relying on it) is not validated. This enables attackers to perform changes on behalf of a user which, unknowingly, interacts with a prepared link or website. The version 0.22.0 is available to remedy this issue. Users are advised to upgrade. There are no known workarounds for this vulnerability.
CWE description: The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
CVSS v3 base score: 8.8
Published: 2024-02-09T01:15Z
Repository: https://github.com/Icinga/icingaweb2-module-incubator
Language: Unknown
Commit date: 2024-02-08 15:57:40 +0100
Commit message: Merge pull request from GHSA-p8vv-9pqq-rm8p

`gipfl/web/Form`: Fix form validation
CVE-2021-23365: Improper Authentication (CWE-287)
value: The package github.com/tyktechnologies/tyk-identity-broker before 1.1.1 are vulnerable to Authentication Bypass via the Go XML parser which can cause SAML authentication bypass. This is because the XML parser doesn’t guarantee integrity in the XML round-trip (encoding/decoding XML data).
CWE description: When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct.
CVSS v3 base score: 9.1
Published: 2021-04-26T10:15Z
Repository: https://github.com/TykTechnologies/tyk-identity-broker
Language: Unknown
Commit date: 2021-03-24 14:57:48 -0500
Commit message: Merge pull request #147 from TykTechnologies/fix/saml-vuln-and-broken-tests

TT-13322-Fix SAML vuln and broken tests
CVE-2021-32820: Improper Control of Generation of Code ('Code Injection') (CWE-94)
value: Express-handlebars is a Handlebars view engine for Express. Express-handlebars mixes pure template data with engine configuration options through the Express render API. More specifically, the layout parameter may trigger file disclosure vulnerabilities in downstream applications. This potential vulnerability is somewhat restricted in that only files with existing extentions (i.e. file.extension) can be included, files that lack an extension will have .handlebars appended to them. For complete details refer to the referenced GHSL-2021-018 report. Notes in documentation have been added to help users avoid this potential information exposure vulnerability.
CWE description: The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
CVSS v3 base score: 8.6
Published: 2021-05-14T19:15Z
Repository: https://github.com/express-handlebars/express-handlebars
Language: Markdown
Files changed: README.md
Commit date: 2021-05-04 09:04:07 -0500
Commit message: fix: add note about security
Diff: diff --git a/README.md b/README.md
index f4a0f81..b6ad8d3 100644
--- a/README.md
+++ b/README.md
@@ -61,10 +61,13 @@ Install using npm:
 
 ```shell
 $ npm install express-handlebars
 ```
 
+## Danger 🔥
+ 
+Never put objects on the `req` object straight in as the data, this can allow hackers to run XSS attacks. Always make sure you are destructuring the values on objects like `req.query` and `req.params`. See https://blog.shoebpatel.com/2021/01/23/The-Secret-Parameter-LFR-and-Potential-RCE-in-NodeJS-Apps/ for more details.
 
 ## Usage
 
 This view engine uses sensible defaults that leverage the "Express-way" of structuring an app's views. This makes it trivial to use in basic apps:
 

Fixed code: ## Danger 🔥
 
Never put objects on the `req` object straight in as the data, this can allow hackers to run XSS attacks. Always make sure you are destructuring the values on objects like `req.query` and `req.params`. See https://blog.shoebpatel.com/2021/01/23/The-Secret-Parameter-LFR-and-Potential-RCE-in-NodeJS-Apps/ for more details.
CVE-2014-125026: Out-of-bounds Write (CWE-787)
value: LZ4 bindings use a deprecated C API that is vulnerable to memory corruption, which could lead to arbitrary code execution if called with untrusted user input.
CWE description: The product writes data past the end, or before the beginning, of the intended buffer.
CVSS v3 base score: 9.8
Published: 2022-12-27T22:15Z
Repository: https://github.com/cloudflare/golz4
Language: Go
Files changed: lz4.go
Commit date: 2014-07-11 08:47:35 -0700
Commit message: Use LZ4_decompress_safe instead of LZ4_uncompress

LZ4_uncompress is deprecated and has security problems.

Diff: diff --git a/lz4.go b/lz4.go
index 7e63ecf..f9abcb2 100644
--- a/lz4.go
+++ b/lz4.go
@@ -4,10 +4,11 @@ package lz4
 // #include "src/lz4.h"
 // #include "src/lz4.c"
 import "C"
 
 import (
+	"errors"
 	"fmt"
 	"unsafe"
 )
 
 // p gets a char pointer to the first byte of a []byte slice
@@ -23,18 +24,16 @@ func clen(s []byte) C.int {
 	return C.int(len(s))
 }
 
 // Uncompress with a known output size. len(out) should be equal to
 // the length of the uncompressed out.
-func Uncompress(in, out []byte) (err error) {
-	read := int(C.LZ4_uncompress(p(in), p(out), clen(out)))
-
-	if read != len(in) {
-		err = fmt.Errorf("uncompress read %d bytes should have read %d",
-			read, len(in))
+func Uncompress(in, out []byte) (error) {
+	if int(C.LZ4_decompress_safe(p(in), p(out), clen(in), clen(out))) < 0 {
+		return errors.New("Malformed compression stream")
 	}
-	return
+
+	return nil
 }
 
 // CompressBound calculates the size of the output buffer needed by
 // Compress. This is based on the following macro:
 //

Vulnerable code: func Uncompress(in, out []byte) (err error) {
	read := int(C.LZ4_uncompress(p(in), p(out), clen(out)))

	if read != len(in) {
		err = fmt.Errorf("uncompress read %d bytes should have read %d",
			read, len(in))
	return
Fixed code: 	"errors"
func Uncompress(in, out []byte) (error) {
	if int(C.LZ4_decompress_safe(p(in), p(out), clen(in), clen(out))) < 0 {
		return errors.New("Malformed compression stream")

	return nil
CVE-2023-5832: Improper Input Validation (CWE-20)
value: Improper Input Validation in GitHub repository mintplex-labs/anything-llm prior to 0.1.0.
CWE description: The product receives input or data, but it does
        not validate or incorrectly validates that the input has the
        properties that are required to process the data safely and
        correctly.
CVSS v3 base score: 9.1
Published: 2023-10-30T13:15Z
Repository: https://github.com/mintplex-labs/anything-llm
Language: Python
Files changed: collector/api.py
Commit date: 2023-09-29 11:04:47 -0700
Commit message: prevent deletion of documents not in hotdir via director traversal (#258)

resolves #257
Diff: diff --git a/collector/api.py b/collector/api.py
index 71d3af5..abe6163 100644
--- a/collector/api.py
+++ b/collector/api.py
@@ -1,15 +1,16 @@
+import os
 from flask import Flask, json, request
 from scripts.watch.process_single import process_single
 from scripts.watch.filetypes import ACCEPTED_MIMES
 api = Flask(__name__)
 
 WATCH_DIRECTORY = "hotdir"
 @api.route('/process', methods=['POST'])
 def process_file():
   content = request.json
-  target_filename = content.get('filename')
+  target_filename = os.path.normpath(content.get('filename')).lstrip(os.pardir + os.sep)
   print(f"Processing {target_filename}")
   success, reason = process_single(WATCH_DIRECTORY, target_filename)
   return json.dumps({'filename': target_filename, 'success': success, 'reason': reason})
 
 @api.route('/accepts', methods=['GET'])

Vulnerable code:   target_filename = content.get('filename')
Fixed code: import os
  target_filename = os.path.normpath(content.get('filename')).lstrip(os.pardir + os.sep)
CVE-2024-0404: Improperly Controlled Modification of Dynamically-Determined Object Attributes (CWE-915)
value: A mass assignment vulnerability exists in the `/api/invite/:code` endpoint of the mintplex-labs/anything-llm repository, allowing unauthorized creation of high-privileged accounts. By intercepting and modifying the HTTP request during the account creation process via an invitation link, an attacker can add a `role` property with `admin` value, thereby gaining administrative access. This issue arises due to the lack of property allowlisting and blocklisting, enabling the attacker to exploit the system and perform actions as an administrator.
CWE description: The product receives input from an upstream component that specifies multiple attributes, properties, or fields that are to be initialized or updated in an object, but it does not properly control which attributes can be modified.
Published: 2024-04-16T00:15Z
Repository: https://github.com/mintplex-labs/anything-llm
Language: JavaScript
Files changed: server/endpoints/invite.js
Commit date: 2024-01-10 08:42:03 -0800
Commit message: [BUG] Fixed mass_assignment vuln (#566)

Fixed mass_assignment vuln

Co-authored-by: dastaj <78434825+dastaj@users.noreply.github.com>
Diff: diff --git a/server/endpoints/invite.js b/server/endpoints/invite.js
index 08f9a14..c5c3445 100644
--- a/server/endpoints/invite.js
+++ b/server/endpoints/invite.js
@@ -31,20 +31,24 @@ function inviteEndpoints(app) {
   });
 
   app.post("/invite/:code", async (request, response) => {
     try {
       const { code } = request.params;
-      const userParams = reqBody(request);
+      const { username, password } = reqBody(request);
       const invite = await Invite.get({ code });
       if (!invite || invite.status !== "pending") {
         response
           .status(200)
           .json({ success: false, error: "Invite not found or is invalid." });
         return;
       }
 
-      const { user, error } = await User.create(userParams);
+      const { user, error } = await User.create(({
+        username,
+        password,
+        role: "default",
+      }));
       if (!user) {
         console.error("Accepting invite:", error);
         response
           .status(200)
           .json({ success: false, error: "Could not create user." });

Vulnerable code:       const userParams = reqBody(request);
      const { user, error } = await User.create(userParams);
Fixed code:       const { username, password } = reqBody(request);
      const { user, error } = await User.create(({
        username,
        password,
        role: "default",
      }));
CVE-2024-0439: Improper Privilege Management (CWE-269)
value: As a manager, you should not be able to modify a series of settings. In the UI this is indeed hidden as a convenience for the role since most managers would not be savvy enough to modify these settings. They can use their token to still modify those settings though through a standard HTTP request

While this is not a critical vulnerability, it does indeed need to be patched to enforce the expected permission level.
CWE description: The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.
Published: 2024-02-26T16:27Z
Repository: https://github.com/mintplex-labs/anything-llm
Language: JavaScript
Files changed: server/endpoints/system.js, server/utils/http/index.js
Commit date: 2024-01-11 12:11:45 -0800
Commit message: prevent manager in multi-user from updatingENV via HTTP (#576)

* prevent manager in multi-user from updatingENV via HTTP

* remove unneeded args
Diff: diff --git a/server/endpoints/system.js b/server/endpoints/system.js
index d2a13d10..345bd230 100644
--- a/server/endpoints/system.js
+++ b/server/endpoints/system.js
@@ -281,10 +281,16 @@ function systemEndpoints(app) {
   app.post(
     "/system/update-env",
     [validatedRequest, flexUserRoleValid],
     async (request, response) => {
       try {
+        const user = await userFromSession(request, response);
+        if (!!user && user.role !== "admin") {
+          response.sendStatus(401).end();
+          return;
+        }
+
         const body = reqBody(request);
         const { newValues, error } = updateENV(body);
         if (process.env.NODE_ENV === "production") await dumpENV();
         response.status(200).json({ newValues, error });
       } catch (e) {
diff --git a/server/utils/http/index.js b/server/utils/http/index.js
index cb57c4a2..83e3fa5d 100644
--- a/server/utils/http/index.js
+++ b/server/utils/http/index.js
@@ -18,10 +18,12 @@ function makeJWT(info = {}, expiry = "30d") {
   if (!process.env.JWT_SECRET)
     throw new Error("Cannot create JWT as JWT_SECRET is unset.");
   return JWT.sign(info, process.env.JWT_SECRET, { expiresIn: expiry });
 }
 
+// Note: Only valid for finding users in multi-user mode
+// as single-user mode with password is not a "user"
 async function userFromSession(request, response = null) {
   if (!!response && !!response.locals?.user) {
     return response.locals.user;
   }
 

Fixed code:         const user = await userFromSession(request, response);
        if (!!user && user.role !== "admin") {
          response.sendStatus(401).end();
          return;
        }

// Note: Only valid for finding users in multi-user mode
// as single-user mode with password is not a "user"