Exemplo n.º 1
0
    def testKeywordCookie(self):
        for (keyword, cookie) in self.keyword_cookies:
            calculated = Cookie.make_keyword_cookie(keyword)
            self.assertEqual(calculated, cookie)

        # With uppercase characters (not allowed in keyword addresses).
        self.assertEqual(Cookie.make_keyword_cookie('KeyWordTest0123'),
                         'KeyWordTest0123.51993d')
Exemplo n.º 2
0
    def testSenderAddress(self):
        calculated = Cookie.make_sender_address(self.user_address,
                                                self.sender_address.lower())
        self.assertEqual(calculated, '*****@*****.**')

        calculated = Cookie.make_sender_address(self.user_address,
                                                self.sender_address)
        self.assertEqual(calculated, '*****@*****.**')
Exemplo n.º 3
0
    def testSenderAddress(self):
        calculated = Cookie.make_sender_address(self.user_address,
                                                self.sender_address.lower())
        self.assertEqual(calculated, '*****@*****.**')

        calculated = Cookie.make_sender_address(self.user_address,
                                                self.sender_address)
        self.assertEqual(calculated, '*****@*****.**')
Exemplo n.º 4
0
    def testKeywordCookie(self):
        for (keyword, cookie) in self.keyword_cookies:
            calculated = Cookie.make_keyword_cookie(keyword)
            self.assertEqual(calculated, cookie)

        # With uppercase characters (not allowed in keyword addresses).
        self.assertEqual(
            Cookie.make_keyword_cookie('KeyWordTest0123'),
            'KeyWordTest0123.51993d'
        )
Exemplo n.º 5
0
    def testConfirmAddress(self):
        calculated = Cookie.make_confirm_address(self.user_address, self.time,
                                                 self.pid)
        self.assertEqual(calculated,
            '*****@*****.**')

        calculated = Cookie.make_confirm_address(self.user_address, self.time,
                                                 self.pid, 'keyword')
        self.assertEqual(calculated,
            '*****@*****.**')
Exemplo n.º 6
0
    def testDatedAddress(self):
        calculated = Cookie.make_dated_address(self.user_address, self.time)
        self.assertEqual(calculated,
            '*****@*****.**')

        # "Now" address. Can't predict exactly how it will come out,
        # but make sure it at least succeeds.
        import re
        pattern = re.compile(r'testuser-dated-\d{10}\.[0-9a-f]{6}@testsite\.com')
        calculated = Cookie.make_dated_address(self.user_address)
        self.assertTrue(pattern.match(calculated))
Exemplo n.º 7
0
    def testDatedAddress(self):
        calculated = Cookie.make_dated_address(self.user_address, self.time)
        self.assertEqual(calculated,
                         '*****@*****.**')

        # "Now" address. Can't predict exactly how it will come out,
        # but make sure it at least succeeds.
        import re
        pattern = re.compile(
            r'testuser-dated-\d{10}\.[0-9a-f]{6}@testsite\.com')
        calculated = Cookie.make_dated_address(self.user_address)
        self.assertTrue(pattern.match(calculated))
Exemplo n.º 8
0
    def testConfirmAddress(self):
        calculated = Cookie.make_confirm_address(self.user_address, self.time,
                                                 self.pid)
        self.assertEqual(
            calculated,
            '*****@*****.**')

        calculated = Cookie.make_confirm_address(self.user_address, self.time,
                                                 self.pid, 'keyword')
        self.assertEqual(
            calculated,
            '*****@*****.**')
Exemplo n.º 9
0
    def testFingerprint(self):
        headers = ['foo', 'bar', 'baz', '012456789', ' ' * 40]

        fingerprints = [
            b'afqG6DMhSxO4KpBDUsu56bh2INg',
            b'tfw9skV5Y0+l/rfwjzjCjt/cjqY',
            b'h4Hss53veo3tdIHjdjsKXqbxrmY',
            b'zJVrBypI7Sk46bTy5WPJbikGgGc',
            b'vIKcOmXJedx4BUbWwN/u3xohzTA',
        ]
        for (i, header) in enumerate(headers):
            calculated = Cookie.make_fingerprint(headers[:i+1])
            self.assertEqual(calculated, fingerprints[i])

        fingerprints = [
            b'vIKcOmXJedx4BUbWwN/u3xohzTA',
            b'vYzrXyiBag83ut1pRtRsmjZVxUI',
            b'4sWBNkCH3NK6xnOqaLOoEY8kIc8',
            b'BJ5xPBh0C9zby06hUTz9zUMdQVE',
            b'yejQZ5jg5Lc35uit/xLz8oAmAN4',
        ]
        for (i, header) in enumerate(headers):
            calculated = Cookie.make_fingerprint(headers[i:])
            self.assertEqual(calculated, fingerprints[i])
Exemplo n.º 10
0
    def testFingerprint(self):
        headers = ['foo', 'bar', 'baz', '012456789', ' ' * 40]

        fingerprints = [
            'afqG6DMhSxO4KpBDUsu56bh2INg',
            'tfw9skV5Y0+l/rfwjzjCjt/cjqY',
            'h4Hss53veo3tdIHjdjsKXqbxrmY',
            'zJVrBypI7Sk46bTy5WPJbikGgGc',
            'vIKcOmXJedx4BUbWwN/u3xohzTA',
        ]
        for (i, header) in enumerate(headers):
            calculated = Cookie.make_fingerprint(headers[:i + 1])
            self.assertEqual(calculated, fingerprints[i])

        fingerprints = [
            'vIKcOmXJedx4BUbWwN/u3xohzTA',
            'vYzrXyiBag83ut1pRtRsmjZVxUI',
            '4sWBNkCH3NK6xnOqaLOoEY8kIc8',
            'BJ5xPBh0C9zby06hUTz9zUMdQVE',
            'yejQZ5jg5Lc35uit/xLz8oAmAN4',
        ]
        for (i, header) in enumerate(headers):
            calculated = Cookie.make_fingerprint(headers[i:])
            self.assertEqual(calculated, fingerprints[i])
Exemplo n.º 11
0
 def testKeywordAddress(self):
     for (keyword, cookie) in self.keyword_cookies:
         calculated = Cookie.make_keyword_address(self.user_address,
                                                  keyword)
         expected = '*****@*****.**' % cookie
         self.assertEqual(calculated, expected)
Exemplo n.º 12
0
    def testSenderCookie(self):
        calculated = Cookie.make_sender_cookie(self.sender_address.lower())
        self.assertEqual(calculated, '23834d')

        calculated = Cookie.make_sender_cookie(self.sender_address)
        self.assertEqual(calculated, '23834d')
Exemplo n.º 13
0
    def testDatedCookie(self):
        calculated = Cookie.make_dated_cookie(self.time)
        self.assertEqual(calculated, '1263369386.df2137')

        calculated = Cookie.make_dated_cookie(self.time, '1m')
        self.assertEqual(calculated, '1262937446.926a58')
Exemplo n.º 14
0
    def testSenderCookie(self):
        calculated = Cookie.make_sender_cookie(self.sender_address.lower())
        self.assertEqual(calculated, '23834d')

        calculated = Cookie.make_sender_cookie(self.sender_address)
        self.assertEqual(calculated, '23834d')
Exemplo n.º 15
0
 def testKeywordAddress(self):
     for (keyword, cookie) in self.keyword_cookies:
         calculated = Cookie.make_keyword_address(self.user_address,
                                                  keyword)
         expected = '*****@*****.**' % cookie
         self.assertEqual(calculated, expected)
Exemplo n.º 16
0
    def testDatedCookie(self):
        calculated = Cookie.make_dated_cookie(self.time)
        self.assertEqual(calculated, '1263369386.df2137')

        calculated = Cookie.make_dated_cookie(self.time, '1m')
        self.assertEqual(calculated, '1262937446.926a58')
Exemplo n.º 17
0
def Release(QueryString):
    """Release the message represented in the QueryString.

QueryString is in one of two formats, real users MAY confirm with:

<UID>.<confirm_cookie>

Virtual users MUST confirm with:

<UID>&<recipient_address>&<confirm_cookie>

Where <UID> is the UID of the TMDA account, <recipient_address> is the untagged
address of the original message recipient, and <confirm_cookie> is used to find
and validate the pending email in question."""

    # Prepare the traceback in case of uncaught exception
    MyCgiTb.ErrTemplate = "prog_err2.html"
    CgiUtil.ErrTemplate = "error2.html"

    try:
        UID, Recipient, Cookie = QueryString.split("&")
        UID = int(UID)
        OldStyle = 0

        # Get base address from Recipient
        RecipUser, RecipDomain = Recipient.split("@")
        User = RecipUser.split('-')[0] + "@" + RecipDomain
    except (ValueError, KeyError):
        try:
            # Check for old-style format
            UID, Cookie = QueryString.split(".", 1)
            UID = int(UID)
            User = pwd.getpwuid(UID)[0]
            OldStyle = 1
        except (ValueError, KeyError):
            CgiUtil.TermError(
                "Unable to parse query string.",
                "Program error / corrupted link.", "locate pending e-mail", "",
                """Please check the link you followed and
make sure that it is typed in exactly as it was sent to you.""")
    try:
        # Get real user from UID
        Timestamp, PID, HMAC = Cookie.split(".")
    except ValueError:
        CgiUtil.TermError(
            "Unable to parse query string.", "Program error / corrupted link.",
            "locate pending e-mail", "",
            """Please check the link you followed and
make sure that it is typed in exactly as it was sent to you.""")

    MsgID = "%s.%s.msg" % (Timestamp, PID)
    # Check to make sure they're not trying to access anything other than email
    if not re.compile("^\d+\.\d+\.msg$").search(MsgID):
        CgiUtil.TermError("<tt>%s.%s.%s</tt> is not a valid message ID." % \
          (Timestamp, PID, HMAC), "Program error / corrupted link.",
          "retrieve pending e-mail", "", """Please check the link you followed and
make sure that it is typed in exactly as it was sent to you.""")

    # Set up the user's home directory.
    try:
        os.seteuid(0)
        os.setegid(0)
        os.setuid(0)
    except OSError:
        pass
    try:
        if os.environ.has_key("TMDA_VLOOKUP") and not OldStyle:
            VLookup = \
              CgiUtil.ParseString(os.environ["TMDA_VLOOKUP"], User )
            List = Util.RunTask(VLookup[1:])
            Sandbox = {"User": User}
            Filename = os.path.join("stubs", "%s.py" % VLookup[0])
            try:
                execfile(Filename, Sandbox)
            except IOError:
                CgiUtil.TermError(
                    "Can't load virtual user stub.",
                    "Cannot execute %s" % Filename, "execute stub",
                    "TMDA_VLOOKUP = %s" % os.environ["TMDA_VLOOKUP"],
                    """Contact this message's sender by an alternate means and inform them
of this error, or try confirming your message using an alternate method.""")
            Home, UID, GID = Sandbox["getuserparams"](List)[0:3]
        else:
            Home, UID, GID = Util.getuserparams(pwd.getpwuid(UID)[0])
    except KeyError:
        CgiUtil.TermError(
            "No such user", "User %s not found" % User, "find user %s" % User,
            "",
            """Contact this message's sender by an alternate means and inform them
of this error, or try confirming your message using an alternate method.""")
    if UID < 2:
        PasswordRecord = pwd.getpwnam(os.environ["TMDA_VUSER"])
        UID = PasswordRecord[2]
        GID = PasswordRecord[3]
        if not int(UID):
            CgiUtil.TermError(
                "TMDA_VUSER is UID 0.", "It is not safe to run "
                "tmda-cgi as root.", "set euid",
                "TMDA_VUSER = %s" % os.environ["TMDA_VUSER"],
                """Contact this message's sender by an alternate means and inform them
of this error, or try confirming your message using an alternate method.""")

    # We now have the home directory and the User.  Set this in the environment.
    os.environ["USER"] = User
    os.environ["LOGNAME"] = User
    os.environ["HOME"] = Home

    # Is there a TMDARC variable?
    if os.environ.has_key("TMDARC"):
        # Yes, replace it
        os.environ["TMDARC"] = os.environ["TMDARC"].replace(
            "/~/", "/%s/" % User)

    # Try to change users
    try:
        os.seteuid(0)
        os.setegid(0)
        os.setgid(int(GID))
        os.setuid(int(UID))
    except OSError:
        pass

    # Now that we know who we are, get our defaults
    try:
        from TMDA import Defaults
    except Errors.ConfigError:
        CgiUtil.TermError(
            "Confirm Failed",
            "Old-style URL is not compatible with virtual users",
            "use incompatible URL", "", """Contact this message's sender by an
alternate means and inform them of this error, or try confirming your message
using an alternate method.""")
    from TMDA import Pending
    from TMDA import Cookie

    try:
        Defaults.CRYPT_KEY
    except AttributeError:
        CgiUtil.TermError(
            "Could not read CRYPT_KEY.",
            "CRYPT_KEY can not be read by group %d." % os.getegid(),
            "read CRYPT_KEY", "ALLOW_MODE_640 = %d<br>%s" %
            (Defaults.ALLOW_MODE_640,
             CgiUtil.FileDetails("Cryptography key", Defaults.CRYPT_KEY_FILE)),
            """Any of the following solutions:<br>
1. Place <tt>%s</tt> in any of the groups that user %d belongs to.<br>
2. Do all three of the following:<br>
&nbsp;&nbsp;&nbsp;&#8226; Place <tt>%s</tt> in group %d.<br>
&nbsp;&nbsp;&nbsp;&#8226; Assign permissions 640 to <tt>%s</tt>.<br>
&nbsp;&nbsp;&nbsp;&#8226; Set ALLOW_MODE_640 = 1 in your configuration file.<br>
3. Disable URL confirmation in your confirmation template.""" %
            (Defaults.CRYPT_KEY_FILE, os.geteuid(), Defaults.CRYPT_KEY_FILE,
             os.getegid(), Defaults.CRYPT_KEY_FILE))

    # Validate the HMAC
    if Cookie.confirmationmac(Timestamp, PID, "accept") != HMAC:
        CgiUtil.TermError("<tt>%s.%s.%s</tt> is not a valid message ID." % \
          (Timestamp, PID, HMAC), "Program error / corrupted link.",
          "retrieve pending e-mail", "",
          "Recheck link or contact TMDA programmers.")

    # Read in e-mail
    try:
        MsgObj = Pending.Message(MsgID)
    except Errors.MessageError:
        CgiUtil.TermError("Message could not be fetched.",
                          "Message has already been released or deleted.",
                          "retrieve pending e-mail", "",
                          "Inquire with recipient about e-mail.")

    T = Template.Template("released.html")

    # Fetch row
    Row = T["Row"]

    # Generate header rows
    for Header in Defaults.SUMMARY_HEADERS:
        T["Name"] = Header.capitalize()
        T["Value"] = CgiUtil.Escape(MsgObj.msgobj[Header])
        Row.Add()

    # Can we add this address to a do-not-confirm-again list?
    if Defaults.CONFIRM_APPEND:
        ConfirmAddr = Util.confirm_append_address \
        (
          parseaddr(MsgObj.msgobj["x-primary-address"])[1],
          parseaddr(MsgObj.msgobj["return-path"])[1]
        )
        if ConfirmAddr:
            Util.append_to_file(ConfirmAddr, Defaults.CONFIRM_APPEND)
            T["Address"] = ConfirmAddr
        else:
            T["Future"]
    else:
        T["Future"]

    print T

    # Make sure release does not write to PENDING_RELEASE_APPEND
    Defaults.PENDING_RELEASE_APPEND = None

    MsgObj.release()
Exemplo n.º 18
0
    def testConfirmCookie(self):
        calculated = Cookie.make_confirm_cookie(self.time, self.pid)
        self.assertEqual(calculated, '1262937386.12345.a45167')

        calculated = Cookie.make_confirm_cookie(self.time, self.pid, 'keyword')
        self.assertEqual(calculated, '1262937386.12345.f5ee35')
Exemplo n.º 19
0
def Release(QueryString):
  """Release the message represented in the QueryString.

QueryString is in one of two formats, real users MAY confirm with:

<UID>.<confirm_cookie>

Virtual users MUST confirm with:

<UID>&<recipient_address>&<confirm_cookie>

Where <UID> is the UID of the TMDA account, <recipient_address> is the untagged
address of the original message recipient, and <confirm_cookie> is used to find
and validate the pending email in question."""

  # Prepare the traceback in case of uncaught exception
  MyCgiTb.ErrTemplate = "prog_err2.html"
  CgiUtil.ErrTemplate = "error2.html"

  try:
    UID, Recipient, Cookie = QueryString.split("&")
    UID = int(UID)
    OldStyle = 0

    # Get base address from Recipient
    RecipUser, RecipDomain = Recipient.split("@")
    User = RecipUser.split('-')[0] + "@" + RecipDomain
  except (ValueError, KeyError):
    try:
      # Check for old-style format
      UID, Cookie = QueryString.split(".", 1)
      UID = int(UID)
      User = pwd.getpwuid(UID)[0]
      OldStyle = 1
    except (ValueError, KeyError):
      CgiUtil.TermError("Unable to parse query string.",
        "Program error / corrupted link.",
        "locate pending e-mail", "", """Please check the link you followed and
make sure that it is typed in exactly as it was sent to you.""")
  try:
    # Get real user from UID
    Timestamp, PID, HMAC = Cookie.split(".")
  except ValueError:
    CgiUtil.TermError("Unable to parse query string.",
      "Program error / corrupted link.",
      "locate pending e-mail", "", """Please check the link you followed and
make sure that it is typed in exactly as it was sent to you.""")

  MsgID = "%s.%s" % (Timestamp, PID)
  # Check to make sure they're not trying to access anything other than email
  if not re.compile("^\d+\.\d+$").search(MsgID):
    CgiUtil.TermError("<tt>%s.%s.%s</tt> is not a valid message ID." % \
      (Timestamp, PID, HMAC), "Program error / corrupted link.",
      "retrieve pending e-mail", "", """Please check the link you followed and
make sure that it is typed in exactly as it was sent to you.""")

  # Set up the user's home directory.
  try:
    os.seteuid(0)
    os.setegid(0)
    os.setuid(0)
  except OSError:
    pass
  try:
    if os.environ.has_key("TMDA_VLOOKUP") and not OldStyle:
      VLookup = \
        CgiUtil.ParseString(os.environ["TMDA_VLOOKUP"], User )
      List = Util.RunTask(VLookup[1:])
      Sandbox = {"User": User}
      Filename = os.path.join("stubs", "%s.py" % VLookup[0])
      try:
        execfile(Filename, Sandbox)
      except IOError:
        CgiUtil.TermError("Can't load virtual user stub.",
          "Cannot execute %s" % Filename, "execute stub",
          "TMDA_VLOOKUP = %s" % os.environ["TMDA_VLOOKUP"],
          """Contact this message's sender by an alternate means and inform them
of this error, or try confirming your message using an alternate method.""")
      Home, UID, GID = Sandbox["getuserparams"](List)[0:3]
    else:
      Home, UID, GID = Util.getuserparams(pwd.getpwuid(UID)[0])
  except KeyError:
    CgiUtil.TermError("No such user", "User %s not found" % User,
      "find user %s" % User, "",
      """Contact this message's sender by an alternate means and inform them
of this error, or try confirming your message using an alternate method.""")
  if UID < 2:
    PasswordRecord = pwd.getpwnam(os.environ["TMDA_VUSER"])
    UID = PasswordRecord[2]
    GID = PasswordRecord[3]
    if not int(UID):
      CgiUtil.TermError("TMDA_VUSER is UID 0.", "It is not safe to run "
        "tmda-cgi as root.", "set euid",
        "TMDA_VUSER = %s" % os.environ["TMDA_VUSER"],
        """Contact this message's sender by an alternate means and inform them
of this error, or try confirming your message using an alternate method.""")

  # We now have the home directory and the User.  Set this in the environment.
  os.environ["USER"] = User
  os.environ["LOGNAME"] = User
  os.environ["HOME"] = Home

  # Is there a TMDARC variable?
  if os.environ.has_key("TMDARC"):
    # Yes, replace it
    if os.environ.has_key("TMDA_DOMAIN_CONFIG"):
      userinfo = User.split('@', 1)
      user = userinfo[0]
      if len(userinfo) > 1:
          domain = userinfo[1]
      else:
          domain = '' 
      os.environ["TMDARC"] = os.environ["TMDARC"].replace("/~/", "/%s/%s/" % (domain, user))
    else:
      os.environ["TMDARC"] = os.environ["TMDARC"].replace("/~/", "/%s/" % User)

  # Try to change users
  try:
    os.seteuid(0)
    os.setegid(0)
    os.setgid(int(GID))
    os.setuid(int(UID))
  except OSError:
    pass

  # Now that we know who we are, get our defaults
  try:
    from TMDA import Defaults
  except Errors.ConfigError:
        CgiUtil.TermError("Confirm Failed",
          "Old-style URL is not compatible with virtual users",
          "use incompatible URL", "", """Contact this message's sender by an
alternate means and inform them of this error, or try confirming your message
using an alternate method.""")
  from TMDA import Pending
  from TMDA import Cookie

  try:
    Defaults.CRYPT_KEY
  except AttributeError:
    CgiUtil.TermError("Could not read CRYPT_KEY.",
      "CRYPT_KEY can not be read by group %d." % os.getegid(),
      "read CRYPT_KEY", "ALLOW_MODE_640 = %d<br>%s" % (Defaults.ALLOW_MODE_640,
      CgiUtil.FileDetails("Cryptography key", Defaults.CRYPT_KEY_FILE)),
      """Any of the following solutions:<br>
1. Place <tt>%s</tt> in any of the groups that user %d belongs to.<br>
2. Do all three of the following:<br>
&nbsp;&nbsp;&nbsp;&#8226; Place <tt>%s</tt> in group %d.<br>
&nbsp;&nbsp;&nbsp;&#8226; Assign permissions 640 to <tt>%s</tt>.<br>
&nbsp;&nbsp;&nbsp;&#8226; Set ALLOW_MODE_640 = 1 in your configuration file.<br>
3. Disable URL confirmation in your confirmation template.""" %
(Defaults.CRYPT_KEY_FILE, os.geteuid(), Defaults.CRYPT_KEY_FILE, os.getegid(),
Defaults.CRYPT_KEY_FILE))

  # Validate the HMAC
  if Cookie.confirmationmac(Timestamp, PID, "accept") != HMAC:
    CgiUtil.TermError("<tt>%s.%s.%s</tt> is not a valid message ID." % \
      (Timestamp, PID, HMAC), "Program error / corrupted link.",
      "retrieve pending e-mail", "",
      "Recheck link or contact TMDA programmers.")

  # Read in e-mail
  try:
    MsgObj = Pending.Message(MsgID)
  except Errors.MessageError:
    CgiUtil.TermError("Message could not be fetched.",
      "Message has already been released or deleted.",
      "retrieve pending e-mail", "",
      "Inquire with recipient about e-mail.")

  T = Template.Template("released.html")

  # Fetch row
  Row = T["Row"]

  # Generate header rows
  for Header in Defaults.SUMMARY_HEADERS:
    T["Name"]  = Header.capitalize()
    T["Value"] = CgiUtil.Escape(MsgObj.msgobj[Header])
    Row.Add()

  # Can we add this address to a do-not-confirm-again list?
  if Defaults.CONFIRM_APPEND:
    ConfirmAddr = Util.confirm_append_address \
    (
      parseaddr(MsgObj.msgobj["x-primary-address"])[1],
      parseaddr(MsgObj.msgobj["return-path"])[1]
    )
    if ConfirmAddr:
      Util.append_to_file(ConfirmAddr, Defaults.CONFIRM_APPEND)
      T["Address"] = ConfirmAddr
    else:
      T["Future"]
  else:
    T["Future"]

  print T

  # Make sure release does not write to PENDING_RELEASE_APPEND
  Defaults.PENDING_RELEASE_APPEND = None

  MsgObj.release()
Exemplo n.º 20
0
    def testConfirmCookie(self):
        calculated = Cookie.make_confirm_cookie(self.time, self.pid)
        self.assertEqual(calculated, '1262937386.12345.a45167')

        calculated = Cookie.make_confirm_cookie(self.time, self.pid, 'keyword')
        self.assertEqual(calculated, '1262937386.12345.f5ee35')