CVE-2021-29433: Improper Input Validation (CWE-20)
value: Sydent is a reference Matrix identity server. In Sydent versions 2.2.0 and prior, sissing input validation of some parameters on the endpoints used to confirm third-party identifiers could cause excessive use of disk space and memory leading to resource exhaustion. A patch for the vulnerability is in version 2.3.0. No workarounds are known to exist.
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: 4.3
Published: 2021-04-15T18:15Z
Repository: https://github.com/matrix-org/sydent
Language: Python
Files changed: sydent/http/servlets/emailservlet.py, sydent/http/servlets/store_invite_servlet.py, sydent/util/stringutils.py
Commit date: 2021-04-12 16:32:03 +0100
Commit message: Validation improvements

Add some more validation to `client_secret` and `email` parameters.

Diff: diff --git a/sydent/http/servlets/emailservlet.py b/sydent/http/servlets/emailservlet.py
index 077d15f5..1513cdf4 100644
--- a/sydent/http/servlets/emailservlet.py
+++ b/sydent/http/servlets/emailservlet.py
@@ -15,11 +15,11 @@
 # limitations under the License.
 from __future__ import absolute_import
 
 from twisted.web.resource import Resource
 
-from sydent.util.stringutils import is_valid_client_secret
+from sydent.util.stringutils import is_valid_client_secret, MAX_EMAIL_ADDRESS_LENGTH
 from sydent.util.emailutils import EmailAddressException, EmailSendException
 from sydent.validators import (
     IncorrectClientSecretException,
     InvalidSessionIdException,
     IncorrectSessionTokenException,
@@ -56,10 +56,17 @@ class EmailRequestCodeServlet(Resource):
             return {
                 'errcode': 'M_INVALID_PARAM',
                 'error': 'Invalid client_secret provided'
             }
 
+        if not (0 < len(email) <= MAX_EMAIL_ADDRESS_LENGTH):
+            request.setResponseCode(400)
+            return {
+                'errcode': 'M_INVALID_PARAM',
+                'error': 'Invalid email provided'
+            }
+
         ipaddress = self.sydent.ip_from_request(request)
         brand = self.sydent.brand_from_request(request)
 
         nextLink = None
         if 'next_link' in args and not args['next_link'].startswith("file:///"):
diff --git a/sydent/http/servlets/store_invite_servlet.py b/sydent/http/servlets/store_invite_servlet.py
index 3dce2a11..e30b9c19 100644
--- a/sydent/http/servlets/store_invite_servlet.py
+++ b/sydent/http/servlets/store_invite_servlet.py
@@ -28,10 +28,12 @@ from sydent.db.invite_tokens import JoinTokenStore
 from sydent.db.threepid_associations import GlobalAssociationStore
 
 from sydent.http.servlets import get_args, send_cors, jsonwrap, MatrixRestError
 from sydent.http.auth import authV2
 from sydent.util.emailutils import sendEmail
+from sydent.util.stringutils import MAX_EMAIL_ADDRESS_LENGTH
+
 
 class StoreInviteServlet(Resource):
     def __init__(self, syd, require_auth=False):
         self.sydent = syd
         self.random = random.SystemRandom()
@@ -69,10 +71,17 @@ class StoreInviteServlet(Resource):
             return {
                 "errcode": "M_UNRECOGNIZED",
                 "error": "Didn't understand medium '%s'" % (medium,),
             }
 
+        if not (0 < len(address) <= MAX_EMAIL_ADDRESS_LENGTH):
+            request.setResponseCode(400)
+            return {
+                'errcode': 'M_INVALID_PARAM',
+                'error': 'Invalid email provided'
+            }
+
         token = self._randomString(128)
 
         tokenStore = JoinTokenStore(self.sydent)
 
         ephemeralPrivateKey = nacl.signing.SigningKey.generate()
diff --git a/sydent/util/stringutils.py b/sydent/util/stringutils.py
index fdf24009..b4726403 100644
--- a/sydent/util/stringutils.py
+++ b/sydent/util/stringutils.py
@@ -16,29 +16,41 @@ import re
 from typing import Optional, Tuple
 
 from twisted.internet.abstract import isIPAddress, isIPv6Address
 
 # https://matrix.org/docs/spec/client_server/r0.6.0#post-matrix-client-r0-register-email-requesttoken
-client_secret_regex = re.compile(r"^[0-9a-zA-Z\.\=\_\-]+$")
+CLIENT_SECRET_REGEX = re.compile(r"^[0-9a-zA-Z\.=_\-]+$")
 
 # hostname/domain name
 # https://regex101.com/r/OyN1lg/2
 hostname_regex = re.compile(
     r"^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$",
     flags=re.IGNORECASE)
 
+# it's unclear what the maximum length of an email address is. RFC3696 (as corrected
+# by errata) says:
+#    the upper limit on address lengths should normally be considered to be 254.
+#
+# In practice, mail servers appear to be more tolerant and allow 400 characters
+# or so. Let's allow 500, which should be plenty for everyone.
+#
+MAX_EMAIL_ADDRESS_LENGTH = 500
+
 
 def is_valid_client_secret(client_secret):
     """Validate that a given string matches the client_secret regex defined by the spec
 
     :param client_secret: The client_secret to validate
     :type client_secret: str
 
     :return: Whether the client_secret is valid
     :rtype: bool
     """
-    return client_secret_regex.match(client_secret) is not None
+    return (
+        0 < len(client_secret) <= 255
+        and CLIENT_SECRET_REGEX.match(client_secret) is not None
+    )
 
 
 def is_valid_hostname(string: str) -> bool:
     """Validate that a given string is a valid hostname or domain name.
 

Vulnerable code: from sydent.util.stringutils import is_valid_client_secret
client_secret_regex = re.compile(r"^[0-9a-zA-Z\.\=\_\-]+$")
    return client_secret_regex.match(client_secret) is not None
Fixed code: from sydent.util.stringutils import is_valid_client_secret, MAX_EMAIL_ADDRESS_LENGTH
        if not (0 < len(email) <= MAX_EMAIL_ADDRESS_LENGTH):
            request.setResponseCode(400)
            return {
                'errcode': 'M_INVALID_PARAM',
                'error': 'Invalid email provided'
            }

from sydent.util.stringutils import MAX_EMAIL_ADDRESS_LENGTH

        if not (0 < len(address) <= MAX_EMAIL_ADDRESS_LENGTH):
            request.setResponseCode(400)
            return {
                'errcode': 'M_INVALID_PARAM',
                'error': 'Invalid email provided'
            }

CLIENT_SECRET_REGEX = re.compile(r"^[0-9a-zA-Z\.=_\-]+$")
# it's unclear what the maximum length of an email address is. RFC3696 (as corrected
# by errata) says:
#    the upper limit on address lengths should normally be considered to be 254.
#
# In practice, mail servers appear to be more tolerant and allow 400 characters
# or so. Let's allow 500, which should be plenty for everyone.
#
MAX_EMAIL_ADDRESS_LENGTH = 500

    return (
        0 < len(client_secret) <= 255
        and CLIENT_SECRET_REGEX.match(client_secret) is not None
    )