Example #1
0
def rcpt_builder_f_inputs():

    #from core.data import smtp,fpr,tc,tr
    #from core.func import append_uniq,get_inputs,dbglog
    #from core.msg.utils import get_addresses

    fpr('Load recipients list using input. Press Ctrl+D to proceed.')
    print
    fpr('Paste your recipients in one or multiplea lines seperate by comma or newline'
        )
    fpr('Use Ctrl-D with new line to continue.')

    fpr.info('_' * (tc - 4))
    print
    inputs = get_inputs()
    fpr.info('_' * (tc - 4))

    if inputs != '':
        #print inputs
        r = get_addresses(inputs)
        append_uniq(smtp['addrlist']['rcpts'], r)
        #print get_addresses(", ".join(inputs))
        dbglog(smtp['addrlist']['rcpts'])
        print
        fpr('Processing recipients ..')
        print
        fpr(' Addresses found with input : %d' % len(r))
        fpr(' Total number of recipients : %d' %
            len(smtp['addrlist']['rcpts']))
Example #2
0
def viewDKIMSignTag(_all=0):
    #TODO:
    # add Less funct with condition
    #

    d = smtp['sign']['dkim']
    if not d.get(0):
        fpr('No DKIM Signature')
        return

    for k in range(d['dstat'] + 1):
        #print d
        #print k

        # if not _all then show current only
        if not _all and k != d['dstat']:
            k += 1
        else:
            if k in d:
                dn = d[k]
            if smtp.get('h' + str(k) + '_DKIM-Signature'):
                fpr('Signature attached (#%s)' % k, adj='r')
            else:
                fpr('Signature not attached (current #%s)' % k, adj='r')
            fpr.info('_' * (tc - 4))
            print
            fpr('DKIM signature set tags:')
            print
            fpr('  version            : v=%s' % dn.get('version', '1'))
            fpr('  alghoritm          : a=%s' %
                dn.get('alghoritm', 'rsa-sha256'))
            fpr('  canonicalization   : c=%s' % dn.get('canonicalize', ''))
            fpr('  selector           : s=%s' % dn.get('selector', ''))
            fpr('  domain             : d=%s' % dn.get('domain', ''))
            fpr('  header             : h=%s' %
                dn.get('header', "from : to : subject"))
            fpr('  identity           : i=%s' % dn.get('identity', ''))
            fpr('  length             : l=%s' % dn.get('length', ''))

            print
            if dn.get('privkey'):
                fpr('Private Key  status   : -- Loaded -- ')
            else:
                fpr.warn('Private Key  status   : -- Not loaded -- ')

            print
            if dn.get('sig'):
                fpr('DKIM-Signature: %s' % dn.get('sig', ''), adj='l')
            else:
                fpr.warn('DKIM-Signature: -- Not generated --')

            print
            if smtp['headers'].get('h' + str(k) + '_DKIM-Signature'):
                fpr('DKIM-Signature was attached')
            else:
                fpr.warn('DKIM-Signature was not attached')

            print

    fpr.info('_' * (tc - 4))
Example #3
0
def flushRecipients():

    from core.data import smtp, fpr

    if raw_input('  Flush envelope recipients list [y/N]:> ') in ['y', 'Y']:
        if type(smtp['addrlist']['rcpts']) is list:
            del smtp['addrlist']['rcpts'][:]
        else:
            fpr.err('Err: rcpts is not a list !')
        smtp['addrlist']['rcpt_to'] = None
        fpr.info('Recipients were flushed !')
Example #4
0
def viewSmtpSess():

    #from core.msg.builder import msg_builder
    size = len(msg_builder().as_string(unixfrom=False))
    #from core.msg.threads import get_rcpts

    unknown = '-- undefined --'

    if cfgs['conv_logs']:
        fpr.green('Conversation Logs: ON', 'r')

    fpr.info('_' * (tc - 4))
    print

    #FIXME:
    d = smtp['connect']['hosts'][0]

    fpr('SMTP Host             : %s:%s' %
        (d.get('host', unknown), d.get('port', unknown)))
    if d.get('smtp_auth_user'):
        fpr('SMTP Authentication   : %s:%s' % (d.get(
            'smtp_auth_user', unknown), d.get('smtp_auth_pass', unknown)))
    else:
        fpr('SMTP Authentication   : NoAuth')
    fpr('SMTP Encryption       : %s' % d.get('tls_mode', unknown))
    fpr('SMTP HELO             : %s' % d.get('helo', unknown))

    print
    if smtp['addrlist']['mail_from']:
        fpr('Envelope Sender       : %s' % smtp['addrlist']['mail_from'])
    else:
        fpr.err('Envelope Sender       : %s' % unknown)

    # shown only 1st rcpt if more than one
    r = list(smtp['addrlist']['rcpts'])
    #if smtp['addrlist']['rcpt_to']:
    #   r.insert(0,smtp['addrlist']['rcpt_to'])
    if r:
        if len(r) > 1:
            fpr('Envelope Recipient(s) : %s .. + %d more' % (r[0], len(r) - 1))
        else:
            fpr('Envelope Recipient(s) : %s' % r[0])
    else:
        fpr.err('Envelope Recipient(s) : %s' % unknown)
    del r[:]

    print
    fpr('Number of Recipients  : %s' % get_rcpts('NoR'))
    fpr('Message Size          : %s bytes' % size)
    fpr('Message Subject       : %s' %
        smtp['headers'].get('h_Subject', unknown))

    fpr.info('_' * (tc - 4))
    print
Example #5
0
def flushThrValues():

    if get_yesno_input('  Flush thread settings [y/N]: '):

        smtp['replay']['threads']['delay'] = TH_DELAY
        smtp['replay']['threads'].pop('rate', None)
        smtp['replay']['threads'].pop('not', None)
        smtp['replay']['threads'].pop('rpm', None)
        smtp['replay']['threads'].pop('mpt', None)
        smtp['replay']['threads']['reals'].pop('not', None)
        smtp['replay']['threads']['reals'].pop('rpm', None)
        smtp['replay']['threads']['reals'].pop('mpt', None)
        fpr.info('Threads values were flushed !')
Example #6
0
File: dha.py Project: bkzk/minja
def flushDHAThrValues():



    if get_yesno_input('  Flush DHA thread settings [y/N]: '):
        smtp['dha']['cmd'] = 'RCPT TO'
        smtp['dha']['threads']['not'] = None
        smtp['dha']['threads']['delay'] = TH_DELAY
        smtp['dha']['threads']['timeout'] = TH_TIMEOUT
        smtp['dha']['threads'].pop('cpt', None)
        smtp['dha']['threads']['reals'].pop('not',None)
        smtp['dha']['threads']['reals'].pop('cpt',None)
        fpr.info('DHA threads settings were flushed !')
Example #7
0
def get_spfHeaders():

    fpr('Please provide your input')
    fpr('Use Ctrl-D with new line to continue.')
    print
    fpr.info('_' * (tc - 4))
    print
    inputs = get_inputs(nl=True)
    fpr.info('_' * (tc - 4))

    if inputs:
        #dbglog(inputs)
        #inputs = [x.lstrip() for x in inputs]
        return splitHeaders(inputs, crlf=True)
Example #8
0
def viewSPFvalues(dd):

    if 'id' in dd:
        fpr('SPF values')
        print

        fpr('  Identities')
        fpr('    id MAIL FROM        : %s' % dd['id'].get('mfrom', ''))
        fpr('    id HELO/EHLO        : %s' % dd['id'].get('helo', ''))
        fpr.info('    id PRA              : %s' % dd['id'].get('pra', ''))
        fpr('  Client IP             : %s' % dd.get('ip', ''))
        print
        fpr('  Receiver address      : %s' % dd.get('receiver', ''))
        print
    else:
        fpr('No SPF values')
Example #9
0
def viewThreadsSummary():

    from core.data import smtp, fpr, tc, tr
    from core.msg.builder import msg_builder
    from core.func import waitin

    #    bancls()
    fpr('Running SMTP Replay:')
    print
    #    fpr.info(' -- rate limits --')
    #    print
    fpr.info('                               -   set  - counted -')
    fpr(' NOT - Number Of Threads       :  %4s  |  %4s  ' %
        (smtp['replay']['threads'].get(
            'not', None), smtp['replay']['threads']['reals'].get('not', None)))

    fpr(' RPM - Recipients Per Message  :  %4s  |  %4s  ' %
        (smtp['replay']['threads'].get(
            'rpm', None), smtp['replay']['threads']['reals'].get('rpm', None)))
    fpr(' MPT - Message Per Thread      :  %4s  |  %4s  ' %
        (smtp['replay']['threads'].get(
            'mpt', None), smtp['replay']['threads']['reals'].get('mpt', None)))

    fpr.info(' RT  - Recipients Per H/M/S    :  %s ' %
             smtp['replay']['threads'].get('rate', None))
    fpr(' DELAY between threads run     :  %s ms' %
        smtp['replay']['threads'].get('delay', None))

    #   print
    #   fpr.info(' -- recipients --')
    print
    fpr(' NOR - Number of Recipients    : %d' % get_rcpts('NoR'))
    fpr.info(' Number of Destination Domains : %d' % get_rcpts('domains'))
    fpr.info(' Number of Destination Hosts   : %d' % get_rcpts('hosts'))

    print
    fpr.info(' -- message --')

    message = msg_builder()
    # confirm  - TODO [ msgx is always true
    if message:
        print
        fpr(' Message Size     : %s' %
            repr(len(message.as_string(unixfrom=False))))
    else:
        print
        fpr('No content data was defined !')
Example #10
0
def d_headers():

    fpr('Diagnostics: Header decoder')
    print
    if raw_input('  Would you like to decode some headers [y/N]> ') in [
            'y', 'Y'
    ]:
        print
        fpr('Please provide an encoded part of the header:')
        #ehead = raw_input('  ')
        fpr('Use Ctrl-D with new line to continue.')
        fpr.blue('_' * (tc - 4))
        print

        inputs = get_inputs(nl=True)

        fpr.info('_' * (tc - 4))
        # decode multiline email headers
        ehead = coders.decode_mheaders(inputs)
        waitin()
        if ehead.keys():
            fpr('Decoded Headers')
            fpr.info('_' * (tc - 4))
            #print
            for k in ehead.keys():
                print
                dhead, enc = decode_header(''.join(ehead[k]).replace(
                    '?==?', '?= =?'))[0]
                if re.match('-no-hn-', k):
                    fpr('Header-name: <None>')
                else:
                    fpr('Header-Name: %s' % k)
                fpr('Header: %s' % dhead)
                ##print dhead
                fpr('Encoding: %s' % enc)
            print
            fpr.blue('_' * (tc - 4))
            waitin()
        # _end_of_decode_multiline_headers
        else:
            fpr('Sorry! No header to decode')
            waitin()
        ehead.clear()
    else:
        waitin()
Example #11
0
def rcpt_builder(op):

    #from core.data import smtp,fpr
    #from core.func import append_uniq
    #from core.msg.utils import get_addresses

    opmap = {
        '1': 'h_To',
        '2': 'h_Cc',
        '3': 'h_Bcc',
    }

    print
    fpr.info('Note: Only unique addresses are going to be included')
    print

    ops = []
    if op == '4':  # all
        #ops = ['h_To', 'h_Cc', 'h_Bcc']
        ops = ['1', '2', '3']
    else:
        ops = [op]

    for op in ops:
        if smtp['headers'].get(opmap[op], None):
            fpr('Processing %s header .. ' % opmap[op])
            print
            r = get_addresses(smtp['headers'][opmap[op]])

            if type(r) is list:
                append_uniq(smtp['addrlist']['rcpts'], r)
                fpr(' Addresses found with header  : %d' % len(r))
                fpr(' Total number of recipients : %d' %
                    len(smtp['addrlist']['rcpts']))
                print
                #fpr('%s' % smtp['addrlist']['rcpts'] )
            else:
                fpr.err('Header %s: contains unproper list of recipients!' %
                        opmap[op])
                #fpr('Recipients not included!')
        else:
            fpr('No %s header' % op)
Example #12
0
File: func.py Project: bkzk/minja
def dbginfo(itype,msg,log=None):

    if itype.lower() == 'error':
        fpr.err( ('-'*(tc-4-len('-- Error --')) + '-- Error --' ))
        fpr.info(msg)
        if log:
            fpr.err('_'*(tc-4))
            print
            fpr(log)
            fpr.err('_'*(tc-4))
        fpr.err('-'*(tc-4))

    if itype.lower() == 'warrning':
        fpr.warn( ('-'*(tc-4-len('-- Warrning --')) + '-- Warrning --' ))
        fpr.info(msg)
        if log:
            fpr.warn('_'*(tc-4))
            print
            fpr(log)
            fpr.warn('_'*(tc-4))
        fpr.warn('-'*(tc-4))

    if itype.lower() == 'debug':
        #from core.data import DEBUG
        if not DEBUG:
            return 0
        fpr.purple( ('-'*(tc-4-len('-- Debug --')) + '-- Debug --' ))
        fpr.info(msg)
        if log:
            fpr.purple('_'*(tc-4))
            print
            fpr(log)
            fpr.purple('_'*(tc-4))
        fpr.purple('-'*(tc-4))
Example #13
0
File: dha.py Project: bkzk/minja
def viewDHAThreadsSummary():

    print
    print
    fpr(' SMTP Command                  : %s' % smtp['dha'].get('cmd') )
    print
    fpr(' Defaults: NOT=1, CPT=NOR')

    fpr.info('                               |   set  | counted ')
    fpr(' NOT - Number Of Threads       :  %4s  |  %4s  ' % 
          ( smtp['dha']['threads'].get('not',None),
            smtp['dha']['threads']['reals'].get('not',None) ) )
    fpr(' CPT - Commands Per Thread     :  %4s  |  %4s  ' % 
          ( smtp['dha']['threads'].get('cpt',None),
            smtp['dha']['threads']['reals'].get('cpt',None) ) )
    print
    fpr(' TIMEOUT between queries run   :  %s ms' % 
            smtp['dha']['threads'].get('timeout',None))
    fpr(' DELAY between threads run     :  %s ms' % 
            smtp['dha']['threads'].get('delay',None))

#    print 
#    fpr.info(' -- recipients --')
    print
    fpr(' NOR - Number of Recipients    : %d' % get_rcpts('NoR')  )
    fpr.info(' Number of Destination Domains : %d' % get_rcpts('domains') )
    fpr.info(' Number of Destination Hosts   : %d' % get_rcpts('hosts')   ) 
    
    print 
Example #14
0
def att_cont_as_string(content=''):

    #from core.data import smtp,fpr,tc,tr,DEBUG
    #from core.func import waitin,get_inputs,dbglog,dbginfo

    if content:
        fpr('Body content has been created')
        smtp['content']['string'] = content
        dbginfo('debug', smtp['content']['string'])
        smtp['use_mime'] = False

    else:
        while True:
            #if smpls[smtype]['astat'] != 0:
            #    fpr('It seems you have already attached this type of sample')
            #    if not raw_input('  Do you want to append another one [y/N]:') in ['y','Y']:
            #         break
            fpr.info('_' * (tc - 4))
            print
            inputs = get_inputs(nl=True)
            fpr.info('_' * (tc - 4))

            if inputs:
                dbglog(inputs)
                smtp['content']['string'] = '\r\n'.join(inputs)
                dbginfo('debug', smtp['content']['string'])

                # change the way how msg_builder build the message
                # even if you paste a proparly formatted mime message do not
                # treat this as MIME because you are not anymore responsible for building
                # a mime parts, you only need to attach this content as it is

                smtp['use_mime'] = False
                # TODO
                # Since now all other function should be aware when usemime() is FALSE and
                # than not be able to attach any of predefined sample
                break
            else:
                fpr('Leaving ..')
                break
Example #15
0
def auth_spf(dd, spfid='all'):

    #TODO: validate value ip, helo (fqdn), mfrom (isemail)

    fpr('SPF Values')
    fpr('_' * (tc - 4) + '\n\n')
    fpr('  id MAIL FROM  : %s' % dd['id'].get('mfrom'))
    fpr('  id HELO/EHLO  : %s' % dd['id'].get('helo'))
    fpr.info('  id PRA        : %s' % dd['id'].get('pra'))
    fpr('  Client IP     : %s' % dd.get('ip'))
    fpr('_' * (tc - 4) + '\n\n')

    try:
        #if spfid == 'mfrom':
        qs = spf.query(
            i=dd.get('ip'),
            s=dd['id'].get('mfrom'),
            #s='',
            h=dd['id'].get('helo'),
            timeout=20,
            verbose=False,
            querytime=0)
        #if spfid == 'helo':
        qh = spf.query(
            i=dd.get('ip'),
            #   s=dd['id'].get('mfrom'),
            s='',
            h=dd['id'].get('helo'),
            timeout=20,
            verbose=False,
            querytime=0)

    except Exception, e:
        fpr.err('Err: %s' % e)
        waitin()
        return
Example #16
0
File: func.py Project: bkzk/minja
def info(itype,msg,log=None,adj='c',frame='warn'):
#TODO: add color option for frame  
# 
   if itype.lower() == 'info':

      fpr.warn( ('_'*(tc-4-len('__')) + '__' ))
      print
      fpr(msg,adj=adj)
      if log:
         fpr.info('_'*(tc-4))
         print
         fpr.info(log)
         fpr.info('_'*(tc-4))

      fpr.warn('_'*(tc-4))
Example #17
0
def viewMsg(part='all'):

    #import re
    d = {'p': 0}
    if part in ['envelope', 'all']:

        e = 0
        #for k in ['helo','mail_from','rcpt_to']:
        for k in ['mail_from', 'rcpt_to']:
            if not smtp.get(k):
                e += 1
        if e == 3:
            d['p'] += 1
            fpr.info('_' * (tc - 4))
            print
            fpr.info(
                'It looks like you have not specified any envelope field!')
            fpr.info('_' * (tc - 4))
        else:
            fpr.info('%-12s | %s' % ('Envelope', ' Content'))
            fpr.info('_' * (tc - 4))
            print
            #fpr('%+12s | %s' % ('HELO',smtp.get('helo','')))
            fpr('%+12s | %s' % ('MAIL FROM', smtp['addrlist'].get(
                'mail_from', '--- not defined ---')))
            #fpr('%+12s | %s' % ('RCPT TO',smtp['addrlist'].get('rcpt_to','')))
            #fpr('%+12s | %s' % ('RCPT TO',smtp['addrlist'].get('rcpts')))
            # shown only 1st rcpt if more than one
            r = list(smtp['addrlist']['rcpts'])
            if r:
                if len(r) > 1:
                    fpr('%+12s | %s .. + %s more' %
                        ('RCPT TO', r[0], len(r) - 1))
                else:
                    fpr('%+12s | %s' % ('RCPT TO', r[0]))
            #        fpr('RCPT : %s' % r[0] )
            else:
                fpr('%+12s | %s' % ('RCPT TO', '-- not defined --'))
            del r[:]

            fpr.info('_' * (tc - 4))
    #print d['p']
    if part in ['headers', 'all']:
        h = 0
        for k in smtp['headers'].keys():
            # find key for smtp headers only, these which start with 'h_'
            if re.match(r'^h\d*_', k):
                #    fpr ('%+12s: %s ' % (k,smtp[k]) )
                h += 1
        if h == 0:
            d['p'] += 1
            print
            fpr.info('It looks like you have not included any header !')
            fpr.info('_' * (tc - 4))
        else:
            print
            fpr.info('%-15s | %s' % ('Header name', 'Header content'))
            fpr.info('_' * (tc - 4))
            for k in smtp['headers'].keys():
                m = re.match(r'^h\d*_(.*)', k)
                if m:
                    fpr('%+15s | %s ' % (m.group(1), smtp['headers'][k]))
            fpr.info('_' * (tc - 4))

    #print d['p']
    if part in ['data', 'body', 'all']:
        lsOfNonEmptyContKey = [
            k for k, v in smtp['content'].iteritems() if len(v) > 0
        ]
        #contentKeyLen = [len(smtp['content'][t]) for t in smtp['content'].keys() ]
        #print contentKeyLen
        #print lsOfNonEmptyContKey
        if not lsOfNonEmptyContKey:
            d['p'] += 1
            print
            fpr.info('It looks like you have not defined any content data !')
            fpr.info('_' * (tc - 4))
        else:
            viewTheMsg()

    #print d['p']
    if part == 'all':
        #print d['p']
        if d['p'] == 3:
            fpr.info('_' * (tc - 4))
            print
            fpr.err('Man what you are doing? Do something! ;)')
            fpr.info('_' * (tc - 4))
Example #18
0
                    print
                    fpr.warn(
                        'Verification skipped. Missing client IP address!')
            except spf.TempError, e:
                fpr.err('Error: %s' % e)
        print
        if not valid:
            fpr.fail('SPF policy validation')
            return

        fpr.ok('SPF policy validation')
        print

        fpr('SPF Verification result')
        fpr('_' * (tc - 4) + '\n\n')
        fpr.info('%s,%s,%s' % (res, code, expl))

        print
        fpr('SPF status  : %s' % res)
        fpr.info('SPF code    : %s ' % code)
        fpr('SPF info    : %s' % expl)
        fpr('_' * (tc - 4) + '\n\n')
        """
         |  get_header(self, res, receiver=None, header_type='spf', aid=None, **kv)
         |      Generate Received-SPF or Authentication Results header based on the
         |       last lookup.
         |
         |      >>> q = query(s='*****@*****.**', h='mx.example.org',
         |      ...           i='192.0.2.3')
         |      >>> q.r='*****@*****.**'
         |      >>> q.check(spf='v=spf1 ?all')
Example #19
0
def viewSmtpConv(s):

    #import re
    #import sys
    #from StringIO import StringIO
    #from core.ui.cless import Less

    if s:
        if raw_input(
                '  Would you like to view SMTP conversation [y/N]:> ') not in [
                    'y', 'Y'
                ]:
            return True
        else:
            print

    dl = len(s.splitlines())

    for line in s.splitlines():
        if len(line) > tc:
            dl += len(line) / tc

    if dl > tr:
        fpr('SMTP conversation logs are much bigger than your screen (%s lines)'
            % dl)
        if raw_input(
                '  Would like to use system pager to view it [y/N]:> ') in [
                    'y', 'Y'
                ]:
            fpr.blue('_' * (tc - 4))
            print
            # use Less if output is much bigger than one screen
            pager = Less(num_lines=tr)
            # fetch output from fancy print as Less input must be a string
            # make copy of original stdout han redirect stdout to string
            sto = sys.stdout
            sys.stdout = StringIO()

            for line in s.splitlines():
                if re.search('^send:', line):
                    fpr.cyan(line)
                elif re.search('^reply:', line):
                    fpr.green(line)
                elif re.search('^data:', line):
                    fpr.purple(line)
                else:
                    fpr.info(line)

            x = sys.stdout.getvalue()
            sys.stdout.close()
            sys.stdout = sto
            print x | pager

            return True
        #else:
        #   fpr.blue( '_'*(tc-4))
        #   print
        #   fpr.blue( '_'*(tc-4))

    #else:
    fpr.blue('_' * (tc - 4))
    print
    for line in s.splitlines():
        if re.search('^send:', line):
            fpr.cyan(line)
        elif re.search('^reply:', line):
            fpr.green(line)
        elif re.search('^data:', line):
            fpr.purple(line)
        else:
            fpr.info(line)
    fpr.blue('_' * (tc - 4))
Example #20
0
def att_custom_header():
    #import re
    print
    if raw_input('  Would you like to include your own headers [y/N]> ') in [
            'y', 'Y'
    ]:
        while True:
            print
            fpr('Please provide a header in format: >> Header-name: header-value <<'
                )
            fpr('Use Ctrl-D with new line to save it and continue.')
            fpr.blue('_' * (tc - 4))
            print
            #            inputs = []
            #            while True:
            #                try:
            #                    line = raw_input("")
            #                except EOFError:
            #                    break
            #                inputs.append(line)
            # to preserve new line pass nl=True with get_inputs()
            inputs = get_inputs()
            if inputs != '':
                thead = {}
                ####### TODO: move this to def encode_mheaders()
                for (i, hline) in enumerate(inputs):
                    #print hline
                    m1 = re.match(r'(.*):(.*)', hline)  # it is a header
                    m2 = re.match(r'^(\s+)(.*)',
                                  hline)  # it is a continuation of prev header
                    if hline == '\n':
                        key = ''
                    elif m1:
                        if m1.group(1):
                            key = m1.group(1)
                            thead.setdefault(key, []).append(m1.group(2))
                    elif m2:
                        if key == '' and inputs[i - 1] != '\n':
                            key = '-no-hn-'
                            while key in thead.keys():
                                key += '-'
                        thead.setdefault(key,
                                         []).append(m2.group(1) + m2.group(2))
                #############
                fpr.blue('_' * (tc - 4))
                for k in thead.keys():
                    fpr.info('_' * (tc - 4))
                    print
                    if re.match('-no-hn-', k):
                        fpr('Header-name: <None>')
                    else:
                        fpr('Header-Name: %s' % k)
                        fpr('Header: %s' % thead[k])
                        #fpr('Encoding: %s' % enc)

                    fpr.info('_' * (tc - 4))
                fpr.blue('_' * (tc - 4))
                print

                #print theadi
                if thead.keys():
                    if raw_input('  Are your headers parsed correctly [Y/n]:> '
                                 ) in ['n', 'N']:
                        if raw_input(
                                '  Would you like to add them one more time [Y/n]:> '
                        ) in ['n', 'N']:
                            break
                        else:
                            waitin()

                    else:

                        # if RFC: format header-name, format header length,
                        #                        rfcline = 1
                        #                        if raw_input('  Should lines follow the RFC or leave it as you put it [Y/n]> ') in ['n', 'N']:
                        #                            rfcline = 0

                        ####
                        for k in thead.keys():
                            smtp['headers']["h_%s" % k] = thead[k]
                        ####
                        dbglog(smtp['headers'])
                        waitin()
                        break
                else:
                    fpr('No header was specified')
                    waitin()
                    break
Example #21
0
def att_zip_input(mbody, smtype, sn):

    #mbody  = mbody
    #sn     = '1'
    #smtype = 'img'

    #import os
    #from core.data import smpls,fpr,tc,tr,smtp
    #from core.func import waitin,get_zipfile,get_inputs,get_sample,dbginfo

    smtype = 'zip-input'
    while True:
        if smpls['zip'].get(smtype) and smpls['zip'][smtype]['astat'] != 0:
            fpr('It seems you have already attached one of USER input sample')
            if not raw_input('  Do you want to append another one [y/N]:') in [
                    'y', 'Y'
            ]:
                break
        else:
            smpls['zip'].setdefault(smtype, {})['astat'] = 0

        fpr.info('Zip your own text content')
        fpr.info('Use Ctrl-D with new line to continue.')
        print
        fpr.info('_' * (tc - 4))
        print

        inputs = get_inputs(nl=True)
        fpr.info('_' * (tc - 4))

        if inputs != '':
            print
            if raw_input('  Zip it [Y/n]:> ') in ['N', 'n']:
                break
            print
            # zipit
            zipinputs = get_zipfile({'val': '\n'.join(inputs)},
                                    fn='user-input.txt')

            n = 1
            if mbody.keys():
                n = max(mbody.keys())
                n += 1
                #print max(mbody.keys())

            mbody.setdefault(n, {})['raw'] = zipinputs

            mbody[n]['h_Content-Type'] = \
                 raw_input('  Content-Type: [%s]> ' %  'application/zip') \
                     or 'application/zip'

            mbody[n]['h_Content-Disposition'] = \
                 raw_input('  Content-Disposition: [%s]> ' %  'attachments; filename=%s' % 'uin-test.zip' ) \
                     or 'attachments; filename=%s' % 'test.zip'

            mbody[n]['h_Content-Transfer-Encoding'] = \
                 raw_input('  Content-transfer-encoding: [%s]> ' %  'base64') \
                     or 'base64'

            # if no cid - client like Mail.app does not
            # show the attachment
            mbody[n]['h_Content-ID'] = \
                 raw_input('  Content-ID: [%s]> ' %  '') \
                     or ''

            mbody[n]['h_Content-Description'] = \
                 raw_input('  Content-Description: [%s]> ' % '') \
                     or ''

            smpls['zip']['astat'] += 1
            smpls['zip'].setdefault(smtype, {})['astat'] += 1
            print
            fpr('Zipped %s attached (x%d)' %
                ('INPUT', smpls['zip'][smtype]['astat']))
        break
    waitin()
Example #22
0
def att_load_base64(mbody):

    # attachment: paste base64 encoded part
    #from core.data import smtp,fpr,tc,tr,DEBUG
    #from core.func import waitin,get_inputs,dbglog,dbginfo
    #from core.msg.coders import isBase64

    while True:
        fpr.info('_' * (tc - 4))
        print

        inputs = get_inputs()

        fpr.info('_' * (tc - 4))

        if inputs != '':
            dbglog(inputs)
            b64result = 1
            for i in inputs:
                if not isBase64(i):

                    dbginfo('error', 'Err: Line is not a proper base64 line',
                            i)

                    b64result = 0
                    break
            if b64result and inputs:
                print
                fpr('Message seems to have proper base64 lines')
                print
                fpr('Please define MIME headers for this attachment')
                print
                n = 1
                if mbody.keys():
                    #global n
                    n = max(mbody.keys())
                    n += 1
                    #print max(mbody.keys())

                fpr('Attachment no: %d' % n, adj='c')
                print
                mbody.setdefault(n, {})['b64'] = inputs
                #mbody['0']['b64'] = inputs

                mbody[n]['h_Content-Type'] = \
                      raw_input('  Content-Type: [%s]> ' %  '') \
                           or ''
                mbody[n]['h_Content-Disposition'] = \
                      raw_input('  Content-Disposition: [%s]> ' % '') \
                           or ''
                mbody[n]['h_Content-transfer-encoding'] = \
                      raw_input('  Content-transfer-encoding: [%s]> ' %  'base64') \
                           or 'base64'
                mbody[n]['h_Content-ID'] = \
                      raw_input('  Content-ID: [%s]> ' %  '') \
                           or ''
                mbody[n]['h_Content-Description'] = \
                      raw_input('  Content-Description: [%s]> ' %  '') \
                           or ''
            waitin()
            break
Example #23
0
def parse_spfHeaders2(h):

    from email.message import Message
    import re

    if not h:
        return False

    #print type(h)
    #print h

    #h1 = h.replace('\n','')
    #print h1

    # re.DOTALL '.'match everything inludinf newline
    # re.IGNORECASE is used at the splitHeaders() function first
    AUTHRE = re.compile('^(Authentication-Results):(.*)', re.DOTALL)
    RECSPF = re.compile('^(Received-SPF):(.*)', re.DOTALL)

    m1 = re.match(AUTHRE, h)
    m2 = re.match(RECSPF, h)

    if DDDEBUG: fpr.purple(h)

    dd = {'hn': '', 'hv': ''}

    #""" Authentication-Results """
    if m1:
        dd['hn'] = m1.group(1)
        dd['hv'] = m1.group(2)

        fpr.info('_' * (tc - 4))
        print
        fpr('Header-name  : %s' % m1.group(1))
        fpr('Header-value : %s' % m1.group(2))
        fpr.info('_' * (tc - 4))
        print

        try:
            import authres

            # FIXME: fast workaround for authres module
            #
            # remove "d=" tag from dmarc auth method as authres
            # does recognize only below ptype
            # ->  elif ptype.lower() not in ['smtp', 'header', 'body', 'policy']
            # and it raise a Syntax error for d=
            h = h.replace('\n', '')
            h = h.replace('\r', '')
            h = h.replace('\t', ' ')
            DTAG = re.compile('.*dmarc=.* \(.*\)* d=([a-z0-9\.\-]+)',
                              re.IGNORECASE)
            md = re.match(DTAG, h)
            if md:
                fpr.warn('Stripping "d=" tag from dmarc method: d=%s' %
                         md.group(1))
                #fpr.green( '%s ---- %s' % (md.group(1), md.group()))
                h = re.sub('d=%s' % md.group(1), '', h)
                if DDDEBUG: print h

            #else:
            #    print 'no d-tag'

            arh = authres.AuthenticationResultsHeader.parse(h)

            #if DDDEBUG:
            #  from pprint import pprint
            #  pprint(str(arh))

        except Exception, e:
            fpr.err('Exception: %s' % e)

        p = {}

        if str(arh.authserv_id):
            p['authserv_id'] = str(arh.authserv_id)

        print len(arh.results)
        for i in arh.results:

            if DDDEBUG:
                pprint(i)
                fpr('method: %s' % str(i.method))

            if str(i.method) == 'spf':
                p.setdefault('spf', {})
                p['spf'].setdefault('mailfrom', {})
                p['spf'].setdefault('helo', {})
                p['spf'].setdefault('pra', {})

                if DDDEBUG:
                    fpr('result        : %s' % str(i.result))
                    if hasattr(i, 'smtp_mailfrom'):
                        fpr('smtp.mailfrom : %s' % str(i.smtp_mailfrom))
                    if hasattr(i, 'smtp_helo'):
                        fpr('smtp.helo     : %s' % str(i.smtp_helo))
                    if hasattr(i, 'smtp_pra'):
                        fpr('smtp.pra      : %s' % str(i.smtp_pra))

                for j in i.properties:
                    if j.name == 'mailfrom':
                        p['spf']['mailfrom']['result'] = str(i.result)
                        p['spf']['mailfrom']['type'] = str(j.type)
                        p['spf']['mailfrom']['name'] = str(j.name)
                        p['spf']['mailfrom']['value'] = str(j.value)
                    if j.name == 'helo':
                        p['spf']['helo']['result'] = str(i.result)
                        p['spf']['helo']['type'] = str(j.type)
                        p['spf']['helo']['name'] = str(j.name)
                        p['spf']['helo']['value'] = str(j.value)
                    if j.name == 'pra':
                        p['spf']['pra']['result'] = str(i.result)
                        p['spf']['pra']['type'] = str(j.type)
                        p['spf']['pra']['name'] = str(j.name)
                        p['spf']['pra']['value'] = str(j.value)
                    if DDDEBUG:
                        fpr.green('  type: %s' % str(j.type))
                        fpr('  name: %s' % str(j.name))
                        fpr('  value: %s' % str(j.value))

            if str(i.method) == 'dkim':
                p.setdefault('dkim', {})
                p['dkim']['result'] = str(i.result)
                if DDDEBUG:
                    fpr('result        : %s' % str(i.result))
                    fpr('header_i      : %s' % str(i.header_i))
                for j in i.properties:
                    # dkim header identity
                    p['dkim']['header_i'] = str(j.value)
                    if DDDEBUG:
                        fpr.green('  type: %s' % str(j.type))
                        fpr('  name: %s' % str(j.name))
                        fpr('  value: %s' % str(j.value))

            if str(i.method) == 'dmarc':
                p.setdefault('dmarc', {})
                p['dmarc']['result'] = str(i.result)
                if DDDEBUG:
                    fpr('result        : %s' % str(i.result))

        p['h_value'] = dd['hv']
        return p
Example #24
0
def spfmech(spfpl, q, mode, level=0):

    #MODE = 0 : syntax validation mode QUITE
    #MODE = 1 : syntax validation mode VERBOSE
    #MODE = 2 : spf validation (req spf values) - show flow

    #mode = 0

    #if mode:
    #    fpr('SPF Policy: "%s"' % spfpl)
    #    print

    RE_SPFMODS = re.compile(br'^(redirect=|explanation=)', re.IGNORECASE)
    RE_SPFMODRED = re.compile(br'^redirect=(.*)', re.IGNORECASE)
    RE_SPFMODEXP = re.compile(br'^explanation=(.*)', re.IGNORECASE)

    for m in spfpl.split():
        #FIXME: exclude' v=spf'
        # validate query against each mechanism spearately

        if m != 'v=spf1':

            try:
                #                  mech,mtype,arg,cidrlength,result = None,None,None,None,None
                # do not validate SPF modifiers
                # http://www.openspf.org/Mechanisms
                m_m = re.match(RE_SPFMODS, m)
                if m_m:
                    fpr(' -> modifier: %s' % m)
                    m_m2 = re.match(RE_SPFMODRED, m)
                    if m_m2:
                        if mode:
                            red = q.dns_spf(m_m2.group(1))
                            level += 1
                            #fpr.info('    ************************************************************************')
                            #fpr.info(' <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
                            print
                            fpr('%sFallowing DNS/TXT RR of %s' %
                                ('_' * level, m_m2.group(1)))
                            fpr('_' * (tc - 4))
                            print
                            fpr.info('%s' % red)
                            fpr('_' * (tc - 4))
                            print
                            spfmech(red, q, 1, level)
                            print
                            fpr('%sFinishing recursive evaluating of %s' %
                                ('_' * level, m_m2.group(1)))
                            print
                            #fpr.info(' >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<')
                            #fpr.info('    ************************************************************************')
                            #fpr.info('    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
                else:
                    if mode:
                        fpr(' -> mechanism: %s' % m)
                    try:
                        mech, mtype, arg, cidrlength, result = q.validate_mechanism(
                            m)
                    except Exception, e:
                        fpr.err('Err: %s' % e)

                    if mode:
                        #fpr('    %s,%s,%s,%s,%s' %(mech,mtype,arg,cidrlength,result) )
                        fpr.info('    %s -> %s, cidr: %s, prefix value: %s' %
                                 (mtype, arg, cidrlength, result))
                        if mtype == 'include':
                            try:
                                inc = q.dns_spf(arg)
                                if mode:
                                    level += 1
                                    #   fpr.info('    ************************************************************************')
                                    #   fpr.info('    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
                                    #fpr.info('    <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
                                    print
                                    fpr('%sFallowing DNS/TXT RR of %s' %
                                        ('_' * level, arg))
                                    fpr('_' * (tc - 4))
                                    print
                                    fpr.info('%s' % inc)
                                    fpr('_' * (tc - 4))
                                    print
                                    spfmech(inc, q, 1, level)
                                    #fpr.info('    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<')
                                    #fpr.info('    ************************************************************************')
                                    print
                                    fpr('%sFinishing recursive evaluating of %s'
                                        % ('_' * level, arg))
                                    print
                            except spf.PermError, e:
                                if mode:
                                    print
                                    fpr.err('SPF policy error: %s' % e)
                                    print

            except spf.PermError, e:
                if mode:
                    print
                    fpr.err('SPF policy error: %s' % e)
                    print
                return False
Example #25
0
def e_headers():

    fpr('Diagnostics: Header encoder')
    print
    if raw_input('  Would you like to encode some headers [y/N]> ') in [
            'y', 'Y'
    ]:

        if True:
            print
            fpr('Please provide a header in format: >> Header-name: header-value <<'
                )
            fpr('Use Ctrl-D to continue.')
            fpr.blue('_' * (tc - 4))
            print
            # to preserve new line pass nl=True with get_inputs()
            inputs = get_inputs()
            if inputs != '':
                thead = {}
                ####### TODO: move this to def encode_mheaders()
                for (i, hline) in enumerate(inputs):
                    #print hline
                    m1 = re.match(r'(.*):(.*)', hline)  # it is a header
                    m2 = re.match(r'^(\s+)(.*)',
                                  hline)  # it is a continuation of prev header
                    if hline == '\n':
                        key = ''
                    elif m1:
                        if m1.group(1):
                            key = m1.group(1)
                            thead.setdefault(key, []).append(m1.group(2))
                    elif m2:
                        if key == '' and inputs[i - 1] != '\n':
                            key = '-no-hn-'
                            while key in thead.keys():
                                key += '-'
                        thead.setdefault(key,
                                         []).append(m2.group(1) + m2.group(2))
                #############
                fpr.blue('_' * (tc - 4))
                print
                fpr('Found headers')
                print
                for k in thead.keys():
                    fpr.info('_' * (tc - 4))
                    print
                    if re.match('-no-hn-', k):
                        fpr('Header-name: <None>')
                    else:
                        fpr('Header-Name: %s' % k)
                        fpr('Header: %s' % thead[k])
                        #fpr('Encoding: %s' % enc)

                    fpr.info('_' * (tc - 4))

                if thead.keys():
                    print
                    chset = raw_input(
                        '  Define headers encoding or leave empty to use a default one\n  [us-ascii]: '
                    ) or 'us-ascii'
                    fpr.blue('_' * (tc - 4))
                    print
                    #print
                    if chset:

                        #from email.message import Message
                        #from email.header import Header
                        for hn in thead.keys():
                            try:
                                h = Header(''.join(thead[hn]),
                                           charset=chset,
                                           maxlinelen=76,
                                           header_name=hn)
                                #print h.encode()
                                print
                                msg = Message()
                                msg[hn] = h
                                print msg.as_string()
                            except UnicodeDecodeError, e:
                                print
                                fpr.err('UnicodeDecodeError: %s' % e)
                                print
                                fpr('Try to set proper encoder! ')
                            print
                    fpr.blue('_' * (tc - 4))

                waitin()
                """ 
Example #26
0
def setSPFvalues(deauth, sh, x):
    # deauth - dictionary with current SPF values
    # sh - dictionary with parsed headers
    # xhv - header number

    def cldeauth(death=deauth):
        del deauth['spf']
        deauth.setdefault(
            'spf',
            dict({
                'id': {
                    'mfrom': '',
                    'helo': '',
                    'pra': ''
                },
                'ip': None
            }))

    from pprint import pprint
    from core.func import get_single_input
    n = 0
    for i in sh:
        #fpr("%s" % i)
        for j in sh[i]:
            n += 1
            if n == x:
                #               pprint(sh[i][j])
                if i == 'Received-SPF':
                    if sh[i][j].get('identity') == 'mailfrom':
                        cldeauth()
                        deauth['spf']['id']['mfrom'] = sh[i][j].get(
                            'envelope-from')
                        deauth['spf']['ip'] = sh[i][j].get('client-ip')
                    # x-sender - container of helo value (Cisco ESA)
                    if sh[i][j].get('identity') == 'helo':
                        cldeauth()
                        if sh[i][j].get('x'):
                            deauth['spf']['id']['helo'] = sh[i][j]['x'].get(
                                'x-sender')
                        deauth['spf']['ip'] = sh[i][j].get('client-ip')

                if i == 'Authentication-Results':
                    if sh[i][j].get('spf'):
                        if sh[i][j]['spf'].get('helo') and sh[i][j]['spf'].get(
                                'mailfrom'):
                            fpr('The Authentication-Results store more than one SPF identity'
                                )
                            fpr('Choose identity:')
                            print
                            fpr(' 1) mailfrom')
                            fpr(' 2) helo')
                            fpr.info(' 3) pra')
                            x = get_single_input('', '')

                            if x == '1':
                                cldeauth()
                                deauth['spf']['id']['mfrom'] = sh[i][j]['spf'][
                                    'mailfrom'].get('value')
                            if x == '2':
                                cldeauth()
                                deauth['spf']['id']['helo'] = sh[i][j]['spf'][
                                    'helo'].get('value')

    #from core.msg.viewers import viewers
    bancls()
    import core.msg.viewers as viewers
    viewers.viewSPFvalues(deauth['spf'])
    fpr.ok('SPF values has been set')

    if DDDEBUG: pprint(deauth)
Example #27
0
File: dha.py Project: bkzk/minja
def chDHAThrDep(t=None,cpt=None):

#VERIFY:  In Python 2.x : int/int --> int and int/float --> float In Python 3.x : int/int can result in a float 

    r=get_rcpts('NoR')
    t_s=None
    cpt_s=None

    if not r:
       fpr.err('Recipients not defined. Build a list of recipients first.')
       fpr.err('Flush the values if the recipient list has been modified.')
       return

    if t:
       smtp['dha']['threads']['not'] = int(t)
       
    if cpt:
       smtp['dha']['threads']['cpt'] = int(cpt)
       

    fpr.info('_'*(tc-4))
    print
    fpr.warn('Your limits:')
    fpr.warn('t_set = %s : cpt_set = %s :  r = %s' % 
             (smtp['dha']['threads'].get('not',None),
              smtp['dha']['threads'].get('cpt',None),r) 
           )
    print 
#    fpr.err('Maximum possible limits to met Essential Conditions:')
#    fpr.err('t = %s : rpm = %s : mpt = %s - r = %s' % (t,rpm,mpt,r) )
#    fpr.info('_'*(tc-4))

    print

    def setReals(t,cpt):
        
        if t and cpt :
           smtp['dha']['threads']['reals'].setdefault('not',t)
           smtp['dha']['threads']['reals'].setdefault('cpt',cpt)

           smtp['dha']['threads']['reals']['not']=t
           smtp['dha']['threads']['reals']['cpt']=cpt
           fpr.ok('Reals were set!')



    if r:

       # count the cpt - based on r and t
       # -------------------------------------------------------------------- #
       if t:
           fpr.green('%s : %s : %s' % (t,cpt,r) )
           # cpt = r / t
           # t = r / cpt
           if t >= r:
              t_new = r
              cpt = 1
              fpr.err('realistic returns would be: t = %s, cpt = %s  for r = %s' %
                   (t_new,cpt,r))
              setReals(t_new,cpt)
           if t < r:
             # I - validate CPT - CPT < R
             cpt = float(r) / t
             fpr.green('counted cpt = %s' % cpt)
             # round up - if there is a remainder 
             if (r %  t > 0):
                 cpt = r / t + (r % t > 0)
                 fpr.green('rounding up cpt = %s' % cpt)

                 # find the lowest T for rounded CpT
                 t_new = float(r) / cpt 
                 fpr.green('counted new t = %s' % t_new)
 
                 #if (r % cpt > 0): # if remainder
                 #    t_new = r /  cpt + ( r % cpt > 0)
                 #    fpr.green('rounding up new t = %s' % t_new)
                 #    fpr.err('realistic returns would be: *t = %s, cpt = %s  for r = %s' %
                 #       (int(t_new),int(cpt),r))
                 #    setReals(int(t_new),int(cpt))
                 #else:
                 fpr.err('realistic returns would be: *t = %s, cpt = %s  for r = %s' %
                     (int(t_new),int(cpt),r))
                 setReals(int(t_new),int(cpt))

             else:
                 fpr.err('realistic returns would be: t = %s, cpt = %s  for r = %s' %
                    (t,int(cpt),r))
                 setReals(int(t),int(cpt))
       elif cpt:

           fpr.green('%s : %s : %s' % (t,cpt,r) )
           # cpt = r / t
           # t = r / cpt
           if cpt >= r:
              cpt_new = r
              t = 1
              fpr.err('realistic returns would be: t = %s, cpt = %s  for r = %s' %
                   (t,cpt_new,r))
              setReals(t,cpt_new)
           if cpt < r:
             # I - validate T - t < R
             t = float(r) / cpt
             fpr.green('counted t = %s' % t)
             # round up - if there is a remainder 
             if (r %  cpt > 0):
                 t = r / cpt + (r % cpt > 0)
                 fpr.green('rounding up t = %s' % t)

                 # find the lowest T for rounded CpT
                 cpt_new = float(r) / t 
                 fpr.green('counted new cpt = %s' % cpt_new)
 
                 fpr.err('realistic returns would be: *t = %s, cpt = %s  for r = %s' %
                     (int(t),int(cpt_new),r))
                 setReals(int(t),int(cpt_new))

             else:
                 fpr.err('realistic returns would be: t = %s, cpt = %s  for r = %s' %
                    (t,int(cpt),r))
                 setReals(int(t),int(cpt))
       else:
            fpr.err('err')


    else:
       fpr.err('Recipients not defined. Build a list of recipients first.')
       fpr.err('Flush the values if the recipient list has been modified.')
Example #28
0
File: parser.py Project: bkzk/minja
def mail_body_parser(body):

    if not hasattr(body, 'as_string'):
        fpr.err('Message can not be processed or not loaded !')
        return

    b = email.message_from_string(body.as_string())
    btype = b.get_content_type()

    dbginfo('debug', 'btype is %s' % btype)
    print

    # parse the body and save split parts in dictionary
    dparts = dict()
    body_parser(dparts, b)

    fpr.cyan('=' * (tc - 4))
    #    pprint(dparts)

    if DEBUG: dbginfo('debug', str(dparts.keys()))

    fpr.cyan('=' * (tc - 4))

    ## build a dictionary

    print
    if not dparts.keys():
        fpr('No MIME parts found')
        return

    mimemulti = ['multipart/mixed', 'multipart/alternative']
    print mimemulti

    while True:
        bancls()
        fpr('Message MIME structure')
        print
        fpr('_' * (tc - 4))
        print
        bstrio = StringIO()
        _structure(b, bstrio)
        fpr.warn('%s' % bstrio.getvalue())
        #fpr.warn(_structure(bpart))
        fpr('_' * (tc - 4))
        print
        fpr('MIME parts ready to review:')
        print
        for k in dparts.keys():
            #print k
            #print type(k)
            if dparts[k]['type'] in mimemulti:
                fpr.info('  [%s] %s ' % (k, dparts[k]['type'][:69]))
            else:
                fpr('  [%s] %s ' % (k, dparts[k]['type'][:69]))
        print
        op = raw_input('  []> ')

        # dparts keys are int not strings
        if op.isdigit():
            k = int(op)
        if op == '':
            break
        while k in dparts.keys():
            bancls()
            fpr('MIME Headers: %s' % k)
            fpr('_' * (tc - 4))
            print
            for (h, hv) in dparts[k]['mheaders']:
                fpr('%s: %s' % (h, hv))
            fpr('_' * (tc - 4))

            print
            #           pprint(dparts)
            #           waitin()
            if dparts[k].get('type') in mimemulti:
                fpr.warn('This part is not directly viewable')
                waitin()
                break
            elif dparts[k].get('payload'):
                fpr('Choose option:')
                print
                fpr('  1) view payload')
                fpr('  2) save payload')
                fpr.off('  3) attach payload to composer [?future feature?]')
                print
                op = raw_input('  []> ')
                if op == '':
                    waitin()
                    break
                # --- view payload ---
                if op in ['1']:
                    bancls()
                    fpr('MIME Payload ')
                    print
                    fpr.warn('%s' % dparts[k].get('type'))
                    print

                    xe = 0
                    for (h, hv) in dparts[k].get('mheaders'):
                        #fpr('%s: %s' % (h,hv))
                        if h.lower() == 'content-transfer-encoding':
                            #part['encext'] = '.'+hv.lower()
                            if hv in ['base64']:
                                info(
                                    'info',
                                    'This payload is base64 encoded. You can view it as it is or try to decode it first.'
                                )
                                print
                                if get_yesno_input(
                                        '  Would like to decode the payload first [y/N]:> '
                                ):

                                    dp = decode_attch(dparts[k]['payload'])
                                    #pprint(dp)
                                    #print len(dp.get('raw'))
                                    #print len(str(dp))
                                    if len(dp.get('raw')) > tr:
                                        #if True:
                                        if get_yesno_input(
                                                '  Would like to use system pager to view it [y/N]:> '
                                        ):

                                            fpr('_' * (tc - 4))
                                            print
                                            pager = Less(num_lines=tr)
                                            print dp.get('raw') | pager
                                            fpr('_' * (tc - 4))
                                        else:
                                            fpr('_' * (tc - 4))
                                            print
                                            fpr(dp.get('raw'))
                                            print
                                            fpr('_' * (tc - 4))

                                    waitin()
                                    xe = 1
                                    break
                    # if viewed decoded part do not display encoded one
                    if xe:
                        break
                    print
                    if len(dparts[k].get('payload')) > tr:
                        if get_yesno_input(
                                '  Would like to use system pager to view it [y/N]:> '
                        ):

                            fpr('_' * (tc - 4))
                            print
                            pager = Less(num_lines=tr)
                            print dparts[k]['payload'] | pager
                            fpr('_' * (tc - 4))
                        else:
                            fpr('_' * (tc - 4))
                            print
                            fpr(dparts[k]['payload'])
                            print
                            fpr('_' * (tc - 4))
                    else:

                        fpr('_' * (tc - 4))
                        print
                        if type(dparts[k].get('payload')) is not 'str':
                            fpr.err('An error occured')
                        else:
                            fpr(dparts[k].get('payload'))
                        print
                        fpr('_' * (tc - 4))

                    waitin()
                if op in ['2']:
                    bancls()
                    fpr('MIME Payload export')

                    fpr('Choose option:')
                    print
                    fpr('  1) save payload, as it is (no decoding)')
                    fpr('  2) save payload - base64 decoded')
                    print
                    op = raw_input('  []> ')
                    print
                    if op == '':
                        waitin()
                        break
                    if op in ['1']:
                        bancls()
                        mpart_saver(dparts[k], 1)
                        waitin()
                    if op in ['2']:
                        bancls()
                        mpart_saver(dparts[k], 2)
                        waitin()
                break
            else:
                fpr.warn(
                    'Wrr: Empty payloyd. Message malformed or parsing has failed.'
                )
                waitin()
                break
Example #29
0
def chThrDep(t=None, rpm=None, mpt=None):

    #VERIFY:  In Python 2.x : int/int --> int and int/float --> float In Python 3.x : int/int can result in a float

    from core.data import smtp, fpr, tc, tr
    from core.func import waitin

    r = get_rcpts('NoR')

    #Warunki Konieczne - Essential Conditions
    # to met WK1, WK2, WK3
    if not t:
        t = smtp['replay']['threads'].get('not', None)
    elif t and not (1 <= int(t) <= r):
        if r > 1:
            t = r
        if r == 1:  #special case
            pass
    if t:
        smtp['replay']['threads']['not'] = int(t)

    if not rpm:
        rpm = smtp['replay']['threads'].get('rpm', None)
    elif rpm and not (1 <= int(rpm) <= r):
        rpm = int(r)
    if rpm:
        fpr.ok('Saving RpM as %s' % rpm)
        smtp['replay']['threads']['rpm'] = int(rpm)

    if not mpt:
        mpt = smtp['replay']['threads'].get('mpt', None)
    elif mpt and not (1 <= int(mpt) <= r):
        mpt = int(r)
    if mpt:
        fpr.ok('Saving MpT as %s' % mpt)
        smtp['replay']['threads']['mpt'] = int(mpt)

    if r:

        # specific feature: the result depends from number of recipients
        # -------------------------------------------------------------------- #
        if t and not rpm and not mpt:
            fpr.warn('%s : %s : %s - %s' % (t, rpm, mpt, r))
            # allow to set t if no rpm or mpt values and number of rcpt > 1
            # but t must be <= r, so if t greater then r => it will be equal to r
            if r > 1:
                smtp['replay']['threads']['not'] = int(t)
                fpr.ok('Saving NoT as %s' % t)
                return t

            # special case when r == 1 , not related to our Equation
            # for r = 1 allow to set T > 1 but do not allow than set rpm or mpt
            # in this special case the sam message is flooding a sepcific rcpt
            # with this smae message in multiple threads/connection !
            if r == 1:
                #pass
                smtp['replay']['threads']['not'] = int(t)
                fpr.ok('Saving NoT as %s' % t)
                return t

        # set initial
        elif rpm and not t and not mpt:
            fpr.warn('%s : %s : %s - %s' % (t, rpm, mpt, r))
            if r > 1:
                smtp['replay']['threads']['rpm'] = int(rpm)
                #return rpm
                #return True
            if r == 1:
                fpr.warn('It doesn\'t make sense to define RpM when NoR = 1')
                return False
        #
        elif mpt and not t and not rpm:
            fpr.warn('%s : %s : %s - %s' % (t, rpm, mpt, r))
            if r > 1:
                smtp['replay']['threads']['mpt'] = int(mpt)
                #return mpt
                #return True
            if r == 1:
                fpr.warn('It doesn\'t make sense to define MpT when NoR = 1')
                return False

    else:
        fpr.err('Recipients not defined. Build a list of recipients first.')
        fpr.err('Flush the values if the recipient list has been modified.')
        return

    # Some maths :)
    #
    # rpm - recipient per message
    # r - number of recipients (all)
    # m - number of messages (all)
    #
    # rpm = r / m ==> m = r / rpm

    # mpt - messages per thread
    # t - number of threads
    # m - number of messages (all)
    #
    # mpt = m / t ==> m = mpt * t

    # r / rpm = mpt * t
    #
    # ==>   t = r / (rpm * mpt)
    #
    # ==> rpm = r / (mpt * t)
    #
    # ==> mpt = r / (rpm * t)

    fpr.info('_' * (tc - 4))
    print
    fpr.warn('Your limits:')
    fpr.warn('t = %s : rpm = %s : mpt = %s - r = %s' %
             (smtp['replay']['threads'].get(
                 'not', None), smtp['replay']['threads'].get('rpm', None),
              smtp['replay']['threads'].get('mpt', None), r))
    print
    fpr.err('Maximum possible limits to met Essential Conditions:')
    fpr.err('t = %s : rpm = %s : mpt = %s - r = %s' % (t, rpm, mpt, r))
    fpr.info('_' * (tc - 4))

    print

    def chEque():
        print
        if r:

            # compare float
            # https://ubuntuforums.org/showthread.php?t=840665
            def float_eq(a, b, epsilon=0.00000001):
                fpr.cyan('<float_eq> %s' % abs(a - b))
                if abs(a - b) < epsilon:
                    return True
                return False

            m1 = float(r) / rpm
            m2 = mpt * float(t)

            fpr.cyan('r/rpm = %s, mpt * t = %s' % (m1, m2))

            if float_eq(m1, m2):
                fpr.green('Equetion is met')
                waitin()
                return True
            else:
                fpr.err('Equetion is false')
                waitin()
                return False

    def setReals(t, rpm, mpt):

        if t and rpm and mpt:
            smtp['replay']['threads']['reals'].setdefault('not', t)
            smtp['replay']['threads']['reals'].setdefault('rpm', rpm)
            smtp['replay']['threads']['reals'].setdefault('mpt', mpt)

            smtp['replay']['threads']['reals']['not'] = t
            smtp['replay']['threads']['reals']['rpm'] = rpm
            smtp['replay']['threads']['reals']['mpt'] = mpt
            fpr.ok('Reals were set!')

    if r:

        # count the mpt - based on rpm and t
        # -------------------------------------------------------------------- #
        if t and rpm and not mpt:
            fpr.green('%s : %s : %s - %s' % (t, rpm, mpt, r))

            # m = r / rpm
            # mpt = m / t

            # I - validate MPT - MPT <= R
            mpt = float(r) / (rpm * t)
            fpr.green('counting mpt = %s' % mpt)

            chEque()

            # round up - if there is a remainder
            if (r % (rpm * t) > 0):
                mpt = r / (rpm * t) + (r % (rpm * t) > 0)
                fpr.green('rounding up mpt = %s' % mpt)

                # find the lowest T for rounded MpT to met RpM
                t_new = float(r) / (rpm * mpt)  #+ (r % (rpm * mpt) > 0)
                fpr.green('counting new t = %s' % t_new)

                if (r % (rpm * mpt) > 0):  # if remainder
                    t_new = r / (rpm * mpt) + (r % (rpm * mpt) > 0)
                    fpr.green('rounding up new t = %s' % t_new)

                fpr.err(
                    'realistic returns would be: *t = %s, rpm = %s, mpt = %s  for r = %s'
                    % (int(t_new), rpm, int(mpt), r))
                setReals(int(t_new), rpm, int(mpt))
            else:
                fpr.err(
                    'realistic returns would be: t = %s, rpm = %s, mpt = %s  for r = %s'
                    % (t, rpm, int(mpt), r))
                setReals(t, rpm, int(mpt))

        # count the rpm - for mpt and t
        # -------------------------------------------------------------------- #
        elif t and mpt and not rpm:
            fpr.blue('%s : %s : %s - %s' % (t, rpm, mpt, r))

            # m = mpt * t
            # m = r / rpm

            # TODO
            # WK: validate RPM , RPM <= R

            rpm = float(r) / (mpt * t)
            fpr.blue('counting: rpm = %s' % rpm)

            chEque()

            # if there is a remainder
            if (r % (mpt * t) > 0):
                rpm = r / (mpt * t) + (r % (mpt * t) > 0)
                fpr.blue('rounding up rpm = %s' % rpm)

                # find the lowest T for rounded MpT to met RpM
                t_new = float(r) / (rpm * mpt)  #+ (r % (rpm * mpt) > 0)
                fpr.green('counting new t = %s' % t_new)

                if (r % (rpm * mpt) > 0):  # if remainder
                    t_new = r / (rpm * mpt) + (r % (rpm * mpt) > 0)
                    fpr.green('rounding up new t = %s' % t_new)

                fpr.err(
                    'realistic returns would be: *t = %s, rpm = %s, mpt = %s  for r = %s'
                    % (int(t_new), int(rpm), mpt, r))
                setReals(int(t_new), int(rpm), mpt)

            else:
                fpr.err(
                    'realistic returns would be: t = %s, rpm = %s, mpt = %s  for r = %s'
                    % (t, int(rpm), mpt, r))
                setReals(t, int(rpm), mpt)

        # count the mpt ( use t = 1 )
        # -------------------------------------------------------------------- #
        elif rpm and not t and not mpt:
            t = 1
            fpr.purple('assuming t eq 1 for equation')
            fpr.purple('%s : %s : %s - %s' % (t, rpm, mpt, r))

            mpt = float(r) / rpm
            fpr.purple('counting: mpt = %s' % mpt)

            chEque()

            #if there is a remainder
            if (r % rpm > 0):

                mpt = r / rpm + (r % rpm > 0)
                fpr.purple('rounding up mpt = %s' % mpt)

                # find the lowest T for rounded MpT to met RpM
                t_new = float(r) / (rpm * mpt)  #+ (r % (rpm * mpt) > 0)
                fpr.green('counting new t = %s' % t_new)

                if (r % (rpm * mpt) > 0):  # if remainder
                    t_new = r / (rpm * mpt) + (r % (rpm * mpt) > 0)
                    fpr.green('rounding up new t = %s' % t_new)

                fpr.err(
                    'realistic returns would be: *t = %s, rpm = %s, mpt = %s  for r = %s'
                    % (int(t_new), rpm, mpt, r))
                setReals(int(t_new), rpm, mpt)

            else:
                fpr.err(
                    'realistic returns would be: t = %s, rpm = %s, mpt = %s  for r = %s'
                    % (t, rpm, int(mpt), r))
                setReals(t, rpm, int(mpt))

        # count the rpm ( use t = 1 )
        # -------------------------------------------------------------------- #
        elif mpt and not t and not rpm:
            t = 1
            fpr.purple('assuming t eq 1 for equation')
            fpr.purple('%s : %s : %s - %s' % (t, rpm, mpt, r))

            rpm = float(r) / mpt
            fpr.purple('counting: rpm = %s' % rpm)
            t = 1
            chEque()

            #if there is a remainder
            if (r % mpt > 0):

                rpm = r / mpt + (r % mpt > 0)
                fpr.purple('rounding up rpm = %s' % rpm)

                # find the lowest T for rounded MpT to met RpM
                t_new = float(r) / (rpm * mpt)  #+ (r % (rpm * mpt) > 0)
                fpr.green('counting new t = %s' % t_new)

                if (r % (rpm * mpt) > 0):  # if remainder
                    t_new = r / (rpm * mpt) + (r % (rpm * mpt) > 0)
                    fpr.green('rounding up new t = %s' % t_new)

                fpr.err(
                    'realistic returns would be: *t = %s, rpm = %s, mpt = %s  for r = %s'
                    % (int(t_new), int(rpm), mpt, r))
                setReals(int(t_new), int(rpm), mpt)

            else:
                fpr.err(
                    'realistic returns would be: t = %s, rpm = %s, mpt = %s  for r = %s'
                    % (t, int(rpm), mpt, r))
                setReals(t, int(rpm), mpt)

        # count t - for rpm and mpt
        # -------------------------------------------------------------------- #
        elif mpt and rpm and not t:
            fpr.white('%s : %s : %s - %s' % (t, rpm, mpt, r))
            print type(mpt)

            # add 1 to round up a result
            # (r % (rpm * mpt) > 0) it will return True which is 1
            # if there is a remainder and 0 if not
            t = float(r) / (rpm * mpt)  #+ (r % (rpm * mpt) > 0)

            fpr.white('counted: t = %s' % t)

            chEque()

            # round up
            if (r % (rpm * mpt) > 0):
                t = r / (rpm * mpt) + (r % (rpm * mpt) > 0)
                fpr.white('rounding up t = %s' % t)

            # validate WK
            # t = <1,r>
            # if t < 1
            if (float(r) / (rpm * mpt)) < 1:
                fpr.info('Now to met equetion for t=1 it is not possible for %s (R) recipients '\
                         'to send %s (MpT) messeges in one thread with %s (RpM) recipient in message' %
                         (r,mpt,rpm))

                print
                fpr.info('New RpM value can be counted based on existing MpT or new MpT ' \
                         'value can be counted based on existing RpM' )
                print
                fpr.info('For simplicity it is assumed that RpM limits is more important so MpT ' \
                         'is going to be recounted to met an equation')
                print

                mpt_new = float(r) / rpm
                fpr.white('New MpT to met equetion is %s' % mpt_new)
                mpt = mpt_new

                chEque()

                # now just round up
                mpt_new = r / rpm + (r % rpm > 0)
                fpr.white('rounding up new mpt = %s' % mpt_new)

                fpr.err(
                    'realistic returns would be: t = %s, rpm = %s, *mpt = %s  for r = %s'
                    % (int(t), rpm, int(mpt_new), r))
                setReals(int(t), rpm, int(mpt_new))
            else:
                # so if t > 1 and it was counted
                fpr.err(
                    'realistic returns would be: t = %s, rpm = %s, mpt = %s  for r = %s'
                    % (int(t), rpm, int(mpt), r))
                setReals(int(t), rpm, int(mpt))

        # only true if r / rpm = mpt * t
        # -------------------------------------------------------------------- #
        elif t and rpm and mpt:
            fpr.cyan('%s : %s : %s - %s' % (t, rpm, mpt, r))
            if not chEque():
                fpr.info('_' * (tc - 4))
                print
                fpr.warn('It is not recommended trying to set NoT with RpM and MpT.  ' \
                         'Suggested action would be to flush these values.' )
                fpr.info('_' * (tc - 4))
                print
                waitin()
                return False
            else:
                fpr.err(
                    'realistic returns would be: t = %s, rpm = %s, mpt = %s  for r = %s'
                    % (t, rpm, mpt, r))
                setReals(t_new, rpm, mpt)

    # for test
    waitin()