From 11734fe1817c468cca9cb6fcf54b8dd99f7456f1 Mon Sep 17 00:00:00 2001 From: Ranjiwei <32759763+r350178982@users.noreply.github.com> Date: Fri, 25 Apr 2025 18:12:27 +0800 Subject: [PATCH] update (#7753) * update * code optimize * Update mail.py --- seahub/settings.py | 1 + seahub/utils/__init__.py | 4 +- seahub/utils/mail.py | 86 ++++++++++++++++++++++++++++++++++++++-- 3 files changed, 87 insertions(+), 4 deletions(-) diff --git a/seahub/settings.py b/seahub/settings.py index 37c7b56d63..dd10df2087 100644 --- a/seahub/settings.py +++ b/seahub/settings.py @@ -942,6 +942,7 @@ FILESERVER_TOKEN_ONCE_ONLY = True SEND_EMAIL_ON_ADDING_SYSTEM_MEMBER = True # Whether to send email when a system staff adding new member. SEND_EMAIL_ON_RESETTING_USER_PASSWD = True # Whether to send email when a system staff resetting user's password. +ENABLE_SMIME = False ########################## diff --git a/seahub/utils/__init__.py b/seahub/utils/__init__.py index a467403f0a..a524e9e3ed 100644 --- a/seahub/utils/__init__.py +++ b/seahub/utils/__init__.py @@ -1000,6 +1000,7 @@ def send_html_email(subject, con_template, con_context, from_email, to_email, """ # get logo path + from seahub.utils.mail import SmimeEmailMessage logo_path = LOGO_PATH custom_logo_file = os.path.join(MEDIA_ROOT, CUSTOM_LOGO_PATH) if os.path.exists(custom_logo_file): @@ -1019,9 +1020,10 @@ def send_html_email(subject, con_template, con_context, from_email, to_email, if reply_to is not None: headers['Reply-to'] = reply_to - msg = EmailMessage(subject, t.render(con_context), from_email, + msg = SmimeEmailMessage(subject, t.render(con_context), from_email, to_email, headers=headers) msg.content_subtype = "html" + msg.send() def gen_dir_share_link(token): diff --git a/seahub/utils/mail.py b/seahub/utils/mail.py index 245880e730..497abd530d 100644 --- a/seahub/utils/mail.py +++ b/seahub/utils/mail.py @@ -1,15 +1,95 @@ # Copyright (c) 2012-2016 Seafile Ltd. import os import logging +from email.mime.application import MIMEApplication +from cryptography.hazmat.primitives import serialization, hashes +from cryptography.hazmat.primitives.serialization import pkcs7 + +from cryptography import x509 +import base64 from django.template import loader from django.core.mail import EmailMessage - +from django.core.mail.message import SafeMIMEMultipart from seahub.utils import get_site_scheme_and_netloc, get_site_name from seahub.settings import MEDIA_URL, LOGO_PATH, \ - MEDIA_ROOT, CUSTOM_LOGO_PATH + MEDIA_ROOT, CUSTOM_LOGO_PATH, ENABLE_SMIME + +from seahub import settings logger = logging.getLogger(__name__) +class SmimeEmailMessage(EmailMessage): + + def __init__(self, *args, **kwargs): + super(SmimeEmailMessage, self).__init__(*args, **kwargs) + + + def _signed(self, msg): + if not ENABLE_SMIME: + return msg + + CERTS_DIR = getattr(settings, 'SMIME_CERTS_DIR', '/opt/seafile/seahub-data/certs') + cert_file = os.path.join(CERTS_DIR, 'cert.pem') + key_file = os.path.join(CERTS_DIR, 'private_key.pem') + + if not os.path.exists(cert_file): + logger.warning(f'smime cert file {cert_file} does not exist.') + return msg + if not os.path.exists(key_file): + logger.warning(f'smime key file {key_file} does not exist.') + return msg + + try: + # Load the private key + with open(key_file, "rb") as f: + private_key = serialization.load_pem_private_key(f.read(), password=None) + + # Load the certificate + with open(cert_file, "rb") as f: + certificate = x509.load_pem_x509_certificate(f.read()) + except Exception as e: + logger.warning(f'smime key/certificates invalid, error: {e}') + return msg + + original_msg = msg + msg_payload = msg.as_string().encode() + + builder = pkcs7.PKCS7SignatureBuilder() \ + .set_data(msg_payload) \ + .add_signer(certificate, private_key, hashes.SHA256()) + pkcs7_signature = builder.sign(serialization.Encoding.DER, [pkcs7.PKCS7Options.DetachedSignature]) + + signed_msg = SafeMIMEMultipart( + _subtype='signed', + protocol='application/pkcs7-signature', + micalg='sha-256' + ) + + + for header in ['Subject', 'From', 'To', 'Date']: + if header in original_msg.keys(): + signed_msg[header] = original_msg[header] + + signed_msg.attach(original_msg) + + sig_part = MIMEApplication( + pkcs7_signature, + 'pkcs7-signature', + name='smime.p7s', + ) + sig_part.add_header( + 'Content-Disposition', + 'attachment; filename="smime.p7s"' + ) + signed_msg.attach(sig_part) + + return signed_msg + + + def message(self): + original_msg = super().message() + return self._signed(original_msg) + def send_html_email_with_dj_template(recipients, subject, dj_template, context={}): """ @@ -38,7 +118,7 @@ def send_html_email_with_dj_template(recipients, subject, dj_template, context={ t = loader.get_template(dj_template) html_message = t.render(context) - mail = EmailMessage(subject=subject, body=html_message, to=[recipients]) + mail = SmimeEmailMessage(subject=subject, body=html_message, to=[recipients]) mail.content_subtype = "html" try: