Ejemplo n.º 1
0
    def encrypt(self, gpg, keys):
        if self.is_encrypted():
            return

        payload = MIMEBase(self._message.get_content_maintype(), self._message.get_content_subtype())
        payload.set_charset(self._message.get_charset())
        payload.set_payload(self._message.get_payload())
        payload.set_boundary(self._message.get_boundary())
        self._mime_encrypt(payload.as_string(), gpg, keys)
Ejemplo n.º 2
0
    def __call__(self):
        # def sendHtmlMail(fro, to, subject, text, files,server, server_port = 25 ):

        # global part1,part2 ,part3

        COMMASPACE = ','
        # Create message container - the correct MIME type is multipart/alternative.
        msg = MIMEMultipart('alternative')
        msg["Accept-Language"] = "zh-CN"
        msg["Accept-Charset"] = "ISO-8859-1,utf-8"
        msg['Subject'] = self.subject
        msg['From'] = self.fro
        msg['To'] = COMMASPACE.join(self.to)
        # msg['To']=self.to



        # Create the body of the message (a plain-text and an HTML version).

        # Record the MIME types of both parts - text/plain and text/html.
        part1 = MIMEText(self.text, 'plain', "utf-8")
        part2 = MIMEText(self.text, 'html', "utf-8")

        # Attach parts into message container.
        # According to RFC 2046, the last part of a multipart message, in this case
        # the HTML message, is best and preferred.
        msg.attach(part1)
        msg.attach(part2)

        if len(self.files) > 0:
            part3 = MIMEBase('application', "octet-stream")
            for file in self.files:
                part3.set_charset('utf-8')
                part3.set_payload(open((file), "rb").read(), 'utf-8')
                encoders.encode_base64(part3)
                part3.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
                # %Header(os.path.basename(file),'utf-8'))
            msg.attach(part3)

        # Send the message via local SMTP server.
        RESENDCOUNT = 1
        for icount in range(RESENDCOUNT):
            try:
                s = smtplib.SMTP(self.server, self.server_port)
                print 'login use ', self.fro, self.pwd
                s.starttls()
                s.login(self.fro, self.pwd)
                s.sendmail(self.fro, self.to, msg.as_string())
                s.quit()
                return True
                pass
            except:
                printException()
                print datetime.datetime.now(), 'send failure ,resend after 5 seconds '
                time.sleep(5)
                continue
        return False
Ejemplo n.º 3
0
def add_attachment(message, attachment, rfc2231=True):
    """ Attach an attachment to a message as a side effect.
    Arguments:
        message: MIMEMultipart instance.
        attachment: Attachment instance.
    """
    data = attachment.read()

    part = MIMEBase('application', 'octet-stream')
    part.set_payload(data)
    part.set_charset('utf-8')
    filename = attachment.name if rfc2231 else Header(attachment.name).encode()
    part.add_header('Content-Disposition', 'attachment', filename=filename)

    message.attach(part)
Ejemplo n.º 4
0
    def send_mail(self,
                  mail_from=email_user,
                  mail_to=email_user,
                  path=mail_path,
                  files=["NSE_New_Symbol.csv"],
                  subject=send_subject,
                  body=send_body,
                  file_type='text',
                  file_format='octet-stream'):

        if 'str' in str(type(mail_to)):
            mail_to = [mail_to]
        if 'str' in str(type(files)):
            files = [files]

        mail = smtplib.SMTP_SSL(host="smtp.gmail.com", port=465)
        mail.login(self.email_user, self.email_pass)

        msg = MIMEMultipart(
        )  # multi part indicates mail contains mutiple part i.e., body,subject,attachments
        msg['subject'] = subject  # mail subject
        msg.attach(MIMEText(body + "\n"))  # attach the body (text format)

        if files != None:  # check if there are any input files to attach, if yes then attach

            for f in files:

                if os.path.isfile(path + f):
                    attachment = MIMEBase(file_type,
                                          file_format)  # type of attachment
                    attachment.set_charset('utf-16')
                    attachment.set_payload(open(
                        path + f, 'rb').read())  # read upload file
                    attachment.add_header(
                        'Content-Disposition',
                        'attachment',
                        filename=os.path.basename(path + f))  # upload filename
                    msg.attach(attachment)  # attach
                else:
                    msg.attach(
                        MIMEText("\n" + path + f + " file doesnot exist\n"))

        msg['To'] = ','.join(mail_to)

        mail.sendmail(mail_from, mail_to, msg=msg.as_string())  # send mail
        print("\nmail sent to " + str(mail_to) + "\n")

        mail.close()  # close connection
Ejemplo n.º 5
0
    def accion(correo, nombre, numero):

        mensaje = MIMEMultipart("plain")
        mensaje["From"] = "*****@*****.**"
        mensaje["To"] = correo
        str = "Factura de compra número " + numero + " - VaporBlack"
        mensaje["subject"] = (str)
        adjunto = MIMEBase("application", "octect-stream")
        adjunto.set_payload(open(nombre, "rb").read())
        adjunto.set_charset("lolazo")
        adjunto.add_header("content-Disposition",
                           'attachment; filename=' + nombre)
        mensaje.attach(adjunto)
        smtp = SMTP("smtp.gmail.com")
        smtp.starttls()
        smtp.login("*****@*****.**", "FixParty0115")

        smtp.sendmail("*****@*****.**", correo,
                      mensaje.as_string())
        smtp.quit()
        print("enviado correctamente")
Ejemplo n.º 6
0
def sendArf(item, spam=False):
    global reportSender
    global mailSmtp
    global reportEmailCc
    global reportEmailSpamCc

    msg = MIMEBase('multipart', 'report')
    msg.set_param('report-type', 'feedback-report', requote=False)

    msg["To"] = str(item['emailAbuse'])
    msg["From"] = reportSender
    msg["Subject"] = "Abuse report for: " + str(item['subject'])

    if spam:
        text = "This is an email in the abuse report format (ARF) for an email message coming via these \r\n"
        text = text + "IPs " + str(item['sourceIp']) + " on " + str(
            item['arrivalDate']) + ".\r\n"
        text = text + "This report indicates that the attached email was not wanted by the recipient.\r\n"
        text = text + "This report may indicates a compromised machine and may contain URLs to malware, treat with caution!\r\n\r\n"
        text = text + "This ARF report contains all the information you will need to assess the problem.\r\n"
        text = text + "The zip attachment is the complete email encrypted with the password " + str(
            arfPassword) + "\r\n"
        text = text + "For more information about this format please see http://tools.ietf.org/html/rfc5965.\r\n"
    else:
        text = "This is an email in the abuse report format (ARF) for an email message received from \r\n"
        text = text + "IP " + str(item['sourceIp']) + " " + str(
            item['sourceDomain']) + " on " + str(
                item['arrivalDate']) + " UTC.\r\n"
        text = text + "This report likely indicates a compromised machine and may contain URLs to malware, treat with caution!\r\n\r\n"
        text = text + "The attached email was selected amongst emails that failed DMARC,\r\n"
        text = text + "therefore it indicates that the author tried to pass for someone else\r\n"
        text = text + "indicating fraud and not spam. The faster you fix or isolate the compromised machine, \r\n"
        text = text + "the better you protect your customers or members and the Internet at large.\r\n\r\n"
        text = text + "This ARF report contains all the information you will need to assess the problem.\r\n"
        text = text + "The zip attachment is the complete email encrypted with the password " + str(
            arfPassword) + "\r\n"
        text = text + "For more information about this format please see http://tools.ietf.org/html/rfc5965.\r\n"

    msgtxt = MIMEText(text)
    msg.attach(msgtxt)

    msgreport = MIMEBase('message', "feedback-report")
    msgreport.set_charset("US-ASCII")

    if spam:
        text = "Feedback-Type: abuse\r\n"
    else:
        text = "Feedback-Type: fraud\r\n"
    text = text + "User-Agent: pyforensic/1.1\r\n"
    text = text + "Version: 1.0\r\n"
    if not spam:
        text = text + "Source-IP: " + str(item['sourceIp']) + "\r\n"
    else:
        ipList = item['sourceIp'].split(", ")
        for ip in ipList:
            text = text + "Source-IP: " + str(ip) + "\r\n"

    text = text + "Arrival-Date: " + str(item['arrivalDate']) + " UTC\r\n"

    text = text + "Attachment-Password: "******"\r\n"

    if 'urlList' in item:
        for uri in item['urlList']:
            o = urlparse.urlparse(uri)
            urlReport = True
            if o.hostname is not None:
                for domain in wldomain:
                    if o.hostname[-len(domain):] == domain:
                        urlReport = False
                if urlReport == True:
                    text = text + "Reported-Uri: " + str(uri) + "\r\n"

    msgreport.set_payload(text)
    msg.attach(msgreport)

    #msgrfc822 = MIMEBase('message', "rfc822")
    msgrfc822 = MIMEBase('text', "rfc822-headers")
    msgrfc822.add_header('Content-Disposition', 'inline')
    parts = re.split(r'\r\n\r\n|\n\n', item['content'])
    rfc822headers = parts[0]
    #msgrfc822.set_payload(item['content'])
    msgrfc822.set_payload(rfc822headers)

    msg.attach(msgrfc822)

    #prepare the zip encrypted
    temp = tempfile.NamedTemporaryFile(prefix='mail',
                                       suffix='.eml',
                                       delete=False)
    tempname = temp.name
    temp.write(item['content'])
    temp.flush()
    ziptemp = tempfile.NamedTemporaryFile(prefix='mail',
                                          suffix='.zip',
                                          delete=True)
    ziptempname = ziptemp.name
    ziptemp.close()
    workdir = os.path.dirname(ziptempname)
    filenamezip = os.path.basename(ziptempname)
    filenameemail = os.path.basename(tempname)
    os.chdir(workdir)
    option = '-P%s' % arfPassword
    rc = subprocess.call(['zip', option] + [filenamezip, filenameemail])
    temp.close()

    ziptemp = open(ziptempname, "r")
    msgzip = MIMEBase('application', "zip")
    msgzip.set_payload(ziptemp.read())
    encoders.encode_base64(msgzip)
    msgzip.add_header('Content-Disposition',
                      'attachment',
                      filename=filenamezip)
    ziptemp.close()

    msg.attach(msgzip)

    #delete created files
    os.remove(ziptempname)
    os.remove(tempname)

    #print "******************\r\n"
    #print msg.as_string()
    #print "******************\r\n"

    s = smtplib.SMTP(mailSmtp)
    # send to IP owners first
    if msg["To"] != "":
        toList = msg["To"].split(",")
        s.sendmail(msg["From"], toList, msg.as_string())
    # send a copy
    reportEmail = reportEmailCc
    if spam:
        reportEmail = reportEmailSpamCc
    if reportEmail != "":
        toList = reportEmail.split(",")
        for emailAddress in toList:
            if msg.has_key("To"):
                msg.replace_header("To", str(emailAddress))
            else:
                msg["To"] = str(emailAddress)
            s.sendmail(msg["From"], emailAddress, msg.as_string())

    s.quit()
Ejemplo n.º 7
0
    def Compile(self):
        """Check message for error and compile it"""
        # self._Message = Message()
        self._Message = MIMEMultipart()
        m = self._Message
        if len(self._Body) == 0:
            raise EmptyBody("Please set Body")
        if len(self._Recipients['To']) + len(self._Recipients['Cc']) + len(self._Recipients['Bcc']) == 0:
            raise EmptyAddr("Recipients address not set")
        # if len(self._AltBody) > 0:
        #     self.ContentType = "multipart/alternative"
        if len(self._MessageDate) != 0:
            m.add_header("Date", self._MessageDate)
        else:
            m.add_header("Date", time.strftime("%a, %d %b %Y %T %z"))
        if len(self._ReturnPath) != 0:
            m.add_header("Return-path", self._ReturnPath)
        elif len(self._Sender) != 0:
            m.add_header("Return-path", self._Sender)
        else:
            m.add_header("Return-path", self._From)
            self._Sender = self._From

        for rcpt in self._Recipients.keys():
            if len(self._Recipients[rcpt]) > 0:
                for each in self._Recipients[rcpt]:
                    if len(each['text']) > 0:
                        m.add_header(rcpt, '"%s" <%s>' % (str(Header(each['text'], 'utf-8')), each['email']))
                    else:
                        m.add_header(rcpt, '<%s>' % (each['email']))
        if m.get("To") in (None, ''):
            m.add_header("To", 'undisclosed-recipients:;')
        m.add_header("From", self._From)

        if self._ReplyTo != '':
            reply_to = self._ReplyTo
            if len(reply_to['text']) > 0:
                m.add_header("Reply-To", '<%s>' (reply_to['email']))
            else:
                m.add_header("Reply-To", '"%s" <%s>' % (str(Header(reply_to['text'], 'utf-8')), reply_to['email']))

        if len(self._MessageID) != 0:
            m.add_header("Message-ID", self._MessageID)
        else:
            m.add_header("Message-ID", '<%s@%s>' % (self.uniqid(), self._Hostname))

        m.add_header('X-Priority', str(self._Priority))
        m.add_header("X-Mailer", self._XMailer)
        m.add_header("Subject", str(Header(self._Subject, 'utf-8')))


        if len(self._AltBody) > 0:
            # alt_body = MIMEText(self._AltBody, )
            # alt_body.set_type(self._AltBodyType)
            alt_body = MIMEBase(self._AltBodyType.split('/')[0], self._AltBodyType.split('/')[1])
            alt_body.set_payload(self._AltBody)
            if self._Encoding == 'base64':
                encoders.encode_base64(alt_body)
            elif self._Encoding == 'quoted':
                encoders.encode_quopri(alt_body)                
            elif self._Encoding in ('8bit', '7bit'):
                encoders.encode_7or8bit(alt_body)
            alt_body.set_charset(self._CharSet)

            # body = MIMEText(self._Body)
            # body.set_type(self._BodyType)
            body = MIMEBase(self._BodyType.split('/')[0], self._BodyType.split('/')[1])
            body.set_payload(self._Body)
            if self._Encoding == 'base64':
                encoders.encode_base64(body)
            elif self._Encoding == 'quoted':
                encoders.encode_quopri(body)
            elif self._Encoding in ('8bit', '7bit'):
                encoders.encode_7or8bit(body)            
            body.set_charset(self._CharSet)

            m.attach(alt_body)
            m.attach(body)
        else:
            # body = MIMEText(self._Body)
            # body.set_type(self._BodyType)
            body = MIMEBase(self._BodyType.split('/')[0], self._BodyType.split('/')[1])
            body.set_payload(self._Body)
            encoders.encode_base64(body)
            body.set_charset(self._CharSet)
            m.attach(body)

        # m.set_charset(self._CharSet)
        m.set_type('multipart/alternative')
        
        self._isCompile = True
Ejemplo n.º 8
0
def email(configuration):
    if not 'TEXT_TEMPLATE' in configuration or configuration[
            'TEXT_TEMPLATE'] is None:
        return None
    if not 'HTML_TEMPLATE' in configuration or configuration[
            'HTML_TEMPLATE'] is None:
        return None
    log('Sending e-mail from <{SSH_MAIL_USER_FROM}@{SSH_MAIL_USER_FROMDOMAIN}> to <{SSH_MAIL_USER_TO}@{SSH_MAIL_USER_TODOMAIN}>'
        .format(**configuration),
        level=LOG_LEVELS.DEBUG)

    configuration['HASH'] = md5(
        bytes(
            '{SSH_MAIL_USER_FROM}@{SSH_MAIL_USER_FROMDOMAIN}+{SSH_MAIL_USER_TO}@{SSH_MAIL_USER_TODOMAIN}'
            .format(**configuration), 'UTF-8')).hexdigest()
    configuration[
        'Message-ID'] = '<{RAW_TIME}.{HASH}@{SSH_MAIL_USER_FROMDOMAIN}>'.format(
            **configuration)

    ## TODO: https://support.google.com/mail/answer/81126
    ## TODO:(DKIM) https://russell.ballestrini.net/quickstart-to-dkim-sign-email-with-python/
    ## TODO:(S/MIME) https://tools.ietf.org/doc/python-m2crypto/howto.smime.html
    ## TODO: https://support.rackspace.com/how-to/create-an-spf-txt-record/
    ##
    ## https://toolbox.googleapps.com/apps/checkmx/check?domain={DOMAIN}&dkim_selector=
    ## https://github.com/PowerDNS/pdns/issues/2881

    email = MIMEMultipart('alternative')
    email['Subject'] = configuration['SUBJECT']
    email[
        'From'] = "{SSH_MAIL_USER_FROM} <{SSH_MAIL_USER_FROM}@{SSH_MAIL_USER_FROMDOMAIN}>".format(
            **configuration)
    email['To'] = "<{SSH_MAIL_USER_TO}@{SSH_MAIL_USER_TODOMAIN}>".format(
        **configuration)
    email['Message-ID'] = configuration['Message-ID']
    email.preamble = configuration['SUBJECT']

    text = configuration['TEXT_TEMPLATE'].format(**configuration)
    html = configuration['HTML_TEMPLATE'].format(**configuration)

    email_body_text = MIMEText(text, 'plain')
    email_body_html = MIMEBase('text', 'html')
    email_body_html.set_payload(html)
    encoders.encode_quopri(email_body_html)
    email_body_html.set_charset('UTF-8')

    email.attach(email_body_text)
    email.attach(email_body_html)

    email["DKIM-Signature"] = sign_email(email, configuration)

    context = ssl.create_default_context()
    for mx_record in dns.resolver.query(
            configuration['SSH_MAIL_USER_TODOMAIN'], 'MX'):
        mail_server = mx_record.to_text().split()[1][:-1]
        try:
            server = smtplib.SMTP(mail_server,
                                  local_hostname='hvornum.se',
                                  port=25,
                                  timeout=10)  # 587 = TLS, 465 = SSL

            if server.starttls(context=context)[0] != 220:
                log('Could not start TLS.', level=3, origin='mailer')

            configuration['mail_server'] = mail_server
            log('Mail via {mail_server} | from {SSH_MAIL_USER_FROM}@{SSH_MAIL_USER_FROMDOMAIN} -> {SSH_MAIL_USER_TO}@{SSH_MAIL_USER_TODOMAIN}'
                .format(**configuration),
                origin='mailer',
                level=LOG_LEVELS.DEBUG)

            server.sendmail(
                '{SSH_MAIL_USER_FROM}@{SSH_MAIL_USER_FROMDOMAIN}'.format(
                    **configuration),
                '{SSH_MAIL_USER_TO}@{SSH_MAIL_USER_TODOMAIN}'.format(
                    **configuration), email.as_string())
            server.quit()
            #		server.close()

            configuration['mail_server'] = mail_server
            log("Sent email from {SSH_MAIL_USER_FROM}@{SSH_MAIL_USER_FROMDOMAIN} to {SSH_MAIL_USER_TO}@{SSH_MAIL_USER_TODOMAIN} about via {mail_server}."
                .format(**configuration),
                level=LOG_LEVELS.INFO,
                origin='mailer')

            return True
        except Exception as e:
            log("Could not send email via: {}!!".format(mail_server),
                level=3,
                origin='mailer')
            log("{}".format(e), level=3, origin='mailer')

            if configuration['TRY_ONE_MAILSERVER']:
                break

    return False
Ejemplo n.º 9
0
def send_mail(host_server, host_port, username, password, sender, receiver, cc,
              mail_title, mail_content, attachment_img, attachment_txt,
              attachment_pdf, attachment_excel, attachment_word):

    #收件人多人的问题
    try:
        receiver = receiver.split(',')
    except:
        traceback.print_exc()
        sys.exit()

    #抄送多人的问题
    try:
        cc = cc.split(",")
        receiver_all = receiver + cc
    except:
        cc = list("")
        receiver_all = receiver + cc

    try:
        smtp = smtplib.SMTP(host_server, host_port)
        smtp.ehlo()  # 向邮箱发送SMTP 'ehlo' 命令
        smtp.starttls()

        smtp.login(username, password)  #登录邮箱
        msg = MIMEMultipart('related')
        msg['Subject'] = Header(mail_title, 'utf-8')
        msg["From"] = sender
        msg["To"] = ','.join(receiver)
        msg["Cc"] = ','.join(cc)
        msgAlternative = MIMEMultipart('alternative')
        msg.attach(msgAlternative)

        #邮件正文中换行符的问题
        try:
            mail_content = mail_content.replace("\\n", "\n")
        except:
            mail_content = ""

        #邮件正文
        content = MIMEText(mail_content, 'plain', 'utf-8')
        msgAlternative.attach(content)

        #image attach
        if attachment_img:
            mail_body = '<b>%s</b><br><img src="cid:%s"><br>' % (
                mail_content, attachment_img)
            msgText = MIMEText(mail_body, 'html', 'utf-8')
            msgAlternative.attach(msgText)
            with open(attachment_img, "rb") as fp:
                msgImage = MIMEImage(fp.read())
            msgImage.add_header('Content_id', '<{}>'.format(attachment_img))
            msg.attach(msgImage)

        #pdf attach
        if attachment_pdf:
            with open(attachment_pdf, "rb") as fp:
                fileMsg = MIMEBase('application', 'pdf')
                fileMsg.setpayload(fp.read())
                encode_base64(fileMsg)
                fileMsg.add_header('Content-Disposition',
                                   'attachment',
                                   filename=os.path.split(attachment_pdf)[1])
                msg.attach(fileMsg)

        #txt attach
        if attachment_txt:
            file_name = os.path.split(attachment_txt[1])
            att1 = MIMEText(open(attachment_txt, 'rb').read(), 'base', 'utf-8')
            att1["Content-Disposition"] = f'attachment;filename="{file_name}"'
            msg.attach(att1)

        #excel attach
        if attachment_excel:
            part = MIMEBase('application', 'vnd.ms-excel')
            with open(attachment_excel, "rb") as fp:
                part.set_payload(fp.read())
                encode_base64(part)
                part.add_header('Content-Disposition',
                                'attachment',
                                filename=os.path.split(attachment_excel)[1])
            msg.attach(part)

        #word attach
        if attachment_word:
            with open(attachment_word, "rb") as fp:
                part = MIMEApplication(fp.read())
                part.add_header('Content-Disposition',
                                'attachment',
                                filename=os.path.split(attachment_word)[1])
                part.set_charset('utf-8')
                part.attach(part)

        smtp.sendmail(sender, receiver_all, msg.as_string())  #发送邮件
        smtp.quit()
        print('执行发送结果:Success!~')
    except:
        print('执行发送结果:Fail!~')
        traceback.print_exc()
Ejemplo n.º 10
0
                  'UTF-8')).hexdigest()

        mail_struct = MIMEMultipart('alternative')
        mail_struct['Subject'] = 'Verify SSH login'
        mail_struct['From'] = f"SSH Guard <sshguard@{CONFIG['domain']}>"
        mail_struct[
            'To'] = f"{USERS[user]['real_name']} <{USERS[user]['mail']}>"
        mail_struct[
            'Message-ID'] = f"<{mail_time}.{mail_hash}@{CONFIG['domain']}>"
        mail_struct.preamble = 'Verify SSH login'

        email_body_text = MIMEText(text, 'plain')
        email_body_html = MIMEBase('text', 'html')
        email_body_html.set_payload(html)
        email.encoders.encode_quopri(email_body_html)
        email_body_html.set_charset('UTF-8')

        mail_struct.attach(email_body_text)
        mail_struct.attach(email_body_html)

        mail_struct["DKIM-Signature"] = sign_email(mail_struct,
                                                   CONFIG['domain'],
                                                   CONFIG['domain_priv_key'],
                                                   CONFIG['domain_selector'])

        context = ssl.create_default_context()
        for mx_record in dns.resolver.query(
                USERS[user]['mail'].split('@', 1)[1], 'MX'):
            mail_server = mx_record.to_text().split()[1][:-1]
            try:
                server = smtplib.SMTP(mail_server, port=25,
Ejemplo n.º 11
0
def sendArf(item, spam=False):
    global reportSender
    global mailSmtp
    global reportEmailCc
    global reportEmailSpamCc

    msg = MIMEBase('multipart','report')
    msg.set_param('report-type','feedback-report',requote=False)

    msg["To"] = str(item['emailAbuse'])
    msg["From"] = reportSender
    msg["Subject"] = "Abuse report for: "+str(item['subject'])

    if spam:
        text = "This is an email in the abuse report format (ARF) for an email message coming via these \r\n"
        text = text+"IPs "+str(item['sourceIp'])+" on "+str(item['arrivalDate'])+".\r\n"
        text = text+"This report indicates that the attached email was not wanted by the recipient.\r\n"
        text = text+"This report may indicates a compromised machine and may contain URLs to malware, treat with caution!\r\n\r\n"
        text = text+"This ARF report contains all the information you will need to assess the problem.\r\n"
        text = text+"The zip attachment is the complete email encrypted with the password "+str(arfPassword)+"\r\n";
        text = text+"For more information about this format please see http://tools.ietf.org/html/rfc5965.\r\n";
    else:
        text = "This is an email in the abuse report format (ARF) for an email message received from \r\n"
        text = text+"IP "+str(item['sourceIp'])+" "+str(item['sourceDomain'])+" on "+str(item['arrivalDate'])+" UTC.\r\n"
        text = text+"This report likely indicates a compromised machine and may contain URLs to malware, treat with caution!\r\n\r\n"
        text = text+"The attached email was selected amongst emails that failed DMARC,\r\n"
        text = text+"therefore it indicates that the author tried to pass for someone else\r\n"
        text = text+"indicating fraud and not spam. The faster you fix or isolate the compromised machine, \r\n"
        text = text+"the better you protect your customers or members and the Internet at large.\r\n\r\n"
        text = text+"This ARF report contains all the information you will need to assess the problem.\r\n"
        text = text+"The zip attachment is the complete email encrypted with the password "+str(arfPassword)+"\r\n";
        text = text+"For more information about this format please see http://tools.ietf.org/html/rfc5965.\r\n";

    msgtxt = MIMEText(text)
    msg.attach(msgtxt)

    msgreport = MIMEBase('message', "feedback-report")
    msgreport.set_charset("US-ASCII")
    
    if spam:
        text = "Feedback-Type: abuse\r\n"
    else:
        text = "Feedback-Type: fraud\r\n"
    text = text + "User-Agent: pyforensic/1.1\r\n"
    text = text + "Version: 1.0\r\n"
    if not spam:
        text = text + "Source-IP: "+str(item['sourceIp'])+"\r\n"
    else:
        ipList = item['sourceIp'].split(", ")
        for ip in ipList:
            text = text + "Source-IP: "+str(ip)+"\r\n"

    text = text + "Arrival-Date: "+str(item['arrivalDate'])+" UTC\r\n"

    text = text + "Attachment-Password: "******"\r\n"

    if 'urlList' in item:
        for uri in item['urlList']:
            o = urlparse.urlparse(uri)
            urlReport=True
            if o.hostname is not None:
                for domain in wldomain:
                    if o.hostname[-len(domain):]==domain:
                        urlReport=False
                if urlReport==True:
                    text = text + "Reported-Uri: "+str(uri)+"\r\n"

    msgreport.set_payload(text)
    msg.attach(msgreport)

    #msgrfc822 = MIMEBase('message', "rfc822")
    msgrfc822 = MIMEBase('text', "rfc822-headers")
    msgrfc822.add_header('Content-Disposition','inline')
    parts=re.split(r'\r\n\r\n|\n\n',item['content'])
    rfc822headers=parts[0]
    #msgrfc822.set_payload(item['content'])
    msgrfc822.set_payload(rfc822headers)
    
    msg.attach(msgrfc822)

    #prepare the zip encrypted
    temp=tempfile.NamedTemporaryFile(prefix='mail',suffix='.eml',delete=False)
    tempname=temp.name
    temp.write(item['content'])
    temp.flush()
    ziptemp = tempfile.NamedTemporaryFile(prefix='mail',suffix='.zip',delete=True)
    ziptempname=ziptemp.name
    ziptemp.close()
    workdir = os.path.dirname(ziptempname)
    filenamezip = os.path.basename(ziptempname)
    filenameemail = os.path.basename(tempname)
    os.chdir(workdir)
    option = '-P%s' % arfPassword
    rc = subprocess.call(['zip', option] + [filenamezip, filenameemail])
    temp.close()

    
    ziptemp = open(ziptempname,"r")
    msgzip = MIMEBase('application', "zip")
    msgzip.set_payload(ziptemp.read())
    encoders.encode_base64(msgzip)
    msgzip.add_header('Content-Disposition', 'attachment', filename=filenamezip)
    ziptemp.close()

    msg.attach(msgzip)

    #delete created files
    os.remove(ziptempname)
    os.remove(tempname)


    #print "******************\r\n"
    #print msg.as_string()
    #print "******************\r\n"

    s = smtplib.SMTP(mailSmtp)
    # send to IP owners first
    if msg["To"] != "":
        toList = msg["To"].split(",")
        s.sendmail(msg["From"], toList, msg.as_string())
    # send a copy
    reportEmail=reportEmailCc
    if spam:
        reportEmail=reportEmailSpamCc
    if reportEmail != "":
        toList = reportEmail.split(",")
        for emailAddress in toList:
            if msg.has_key("To"):
                msg.replace_header("To",str(emailAddress))
            else:
                msg["To"]=str(emailAddress)
            s.sendmail(msg["From"], emailAddress, msg.as_string())
            
    s.quit()
Ejemplo n.º 12
0
				<li><b>Time of occurance:</b> {TIME}</li>
				<li><b>Environment Variable:</b> {ENVIRON}</li>
				<li><b>Parameters:</b> {PARAMS}</li>
				<li><b>Logged On Users:</b> {USERS}</li>
			</ul>
		</div>
	</body>
</html>""".format(IP=IP, RESOLV=RESOLV, TIME=time(), ENVIRON=os.environ, PARAMS=argv, USERS=psutil.users(), SUBJECT="SSH Login: {}@{}".format(USER, DOMAIN))

email_body_text = MIMEText(text, 'plain')

#email_body_html = MIMEText(html, 'html')
email_body_html = MIMEBase('text', 'html')
email_body_html.set_payload(html)
encoders.encode_quopri(email_body_html)
email_body_html.set_charset('UTF-8')

email.attach(email_body_text)
email.attach(email_body_html)

if not PROXY_MAIL:
	for mx_record in dns.resolver.query(TO_DOMAIN, 'MX'):
		mail_server = mx_record.to_text().split()[1][:-1]
		try:
			server = smtplib.SMTP(mail_server)
			server.sendmail(FROM, '{}@{}'.format(TO), email.as_string())
			server.close()
			break
		except Exception as e:
			log.warning("Could not notify our chief of command @ {}!!".format(mail_server))
			log.warning("{}".format(e))