def dkim_signature(body, d={}): try: import dkim dsig = dkim.sign( body, d.get('selector', ''), d.get('domain', ''), d.get('privkey', ''), d.get('identity', None), dkim_canontest(d.get('canonicalize', 'relaxed/simple')), #d.get('canonicalize','relaxed/simple'), include_headers=d.get('include_headers', ['from', 'to', 'subject']), length=d.get('length', False), #debuglog=None, ) #dbginfo('debug', dsig) #smtp['h_DKIM-Signature'] = dsig[len("DKIM-Signature: "):] return dsig[len("DKIM-Signature: "):] except ImportError: print dbginfo('warrning', 'Warrning: Missing module: dkimpy. Use: pip install dkimpy') print except Exception, e: print fpr.err('Err: ' + str(e)) print
def get_rrtxt(mfrom): RE_SPF = re.compile(br'^v=spf1$|^v=spf1 ', re.IGNORECASE) fpr('MFROM identity: %s' % mfrom) try: local_part, domain = spf.split_email(s=mfrom, h='') fpr('Domain: %s' % domain) print _dns = spf.DNSLookup(domain, 'TXT', strict=True, timeout=20) if _dns: #dbginfo('debug','DNS: %s ' % dns) # for k, v in DNSLookup(name, qtype, self.strict, timeout): for k, v in _dns: #k = (k[0].lower(), k[1]) if k[1] == 'TXT': m = re.match(RE_SPF, v[0]) if m: fpr('DNS RR: %s' % k[1]) print #for i in v: # fpr.green('%s' % i ) fpr.green('%s' % "".join(v)) #print else: fpr('No TXT RR was found') print except spf.TempError, e: fpr.err('Error: %s' % e) print
def auth_spfplflow(dd, spfid): # info('info','SPF Validation process tests SPF record if it is syntactically correct \n' \ # 'according to RFC 7208 compliant library pyspf. To present the whole path \n' \ # 'this test additionally follow all "include" mechanisms using DNS query to \n' \ # 'retrieve all external SPF policies.' \ # , adj='l') # print fpr('SPF identity type : %s' % spfid) fpr('SPF identity value : %s' % dd['id'].get(spfid)) if spfid == 'mfrom': local_part, domain = spf.split_email(s=dd['id'].get('mfrom'), h=dd['id'].get('helo')) if spfid == 'helo': local_part, domain = spf.split_email(s='', h=dd['id'].get('helo')) fpr('Domain: %s' % domain) print try: q = spf.query(i=dd.get('ip'), s=dd['id'].get('mfrom'), h=dd['id'].get('helo'), timeout=20, verbose=False, querytime=0) except Exception, e: fpr.err('Err: %s' % e) waitin() return
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 main(): try: signal.signal(signal.SIGINT, sig_handler) iworkspace() ishell() # except Ctrl+C, Ctrl+D # except (KeyboardInterrupt, EOFError): except EOFError: print print fpr.err('Interrupted by user! Session lost!') try: sys.exit(0) except SystemExit: os._exit(0) except Exception, error: print fpr.warn('> Unpredictable Exception has been catched') fpr.err('>>> %s' % str(error)) fpr('> Need help regarding the error, please send me a copy. Thank you.' ) fpr.warn( '> Restarting main() to keep the session.\n> Please save the session and restart me..' ) waitin() main()
def spfdns(domain, q): #local_part,domain = spf.split_email(s=dd['id'].get('mfrom'),h='') txt = q.dns_spf(domain) if txt: fpr.green('TXT: %s\n\n' % txt) else: fpr.err('SPF record not found or more than one record found')
def runDHAThreads(): viewDHAThreadsSummary() print if smtp['addrlist']['r_reject'].keys() or smtp['addrlist']['r_valid'].keys(): fpr('Flushing currently found results (valid/refused recipients) ..') del smtp['dha']['threads']['ok'][:] del smtp['dha']['threads']['fail'][:] smtp['addrlist']['r_reject'].clear() smtp['addrlist']['r_valid'].clear() from pprint import pprint if smtp['dha'].get('cmd') != 'RCPT TO': #chek if sysem support EXPN/VRFY command before threading print if get_yesno_input(' Would you like to test an SMTP server for %s method before threading [y/N]: ' % smtp['dha'].get('cmd')): sc = enumSMTPcmd(v=False,dhost=smtp['connect']['hosts'][0]) # enumSMTPcmd(v=True,dhost=smtp['connect']['hosts'][0]): #pprint(sc) #if smtp['connect']['hosts'][0]['tls_mode'] == 'TLS': #print smtp['dha'].get('cmd') if smtp['dha'].get('cmd') in sc['method']: fpr.ok('Method %s is supported' % smtp['dha'].get('cmd')) else: fpr.fail('Method %s is unsupported' % smtp['dha'].get('cmd')) print fpr('Consider to change an SMTP method!') print t = srThread() t.daemon = True t.delay = smtp['dha']['threads'].get('delay',1) t.threads = smtp['dha']['threads']['reals'].get( 'not',smtp['dha']['threads'].get('not',1) ) t.cpt = smtp['dha']['threads']['reals'].get( 'cpt',smtp['dha']['threads'].get('cpt',get_rcpts('NoR')) ) t.method = smtp['dha'].get('cmd') t.rcpts = smtp['addrlist']['rcpts'] #print get_rcpts('NoR') if get_rcpts('NoR'): if raw_input(' Confirm threading [y/N]:> ') in ['y','Y']: # enable logging from core.msg.sender import Logger logger = Logger() t.run() logger.close() else: print fpr.err('Threading were Cancaled!') else: print fpr.err('Err. No recipients defined!')
def runThreads(): # ----------------------------------------------------------- # del smtp['replay']['threads']['ok'][:] del smtp['replay']['threads']['fail'][:] if smtp['addrlist']['r_reject'].keys() or smtp['addrlist']['r_valid'].keys( ): fpr('Flushing currently found results (valid/refused recipients) ..') smtp['addrlist']['r_reject'].clear() smtp['addrlist']['r_valid'].clear() viewThreadsSummary() t = srThread() t.daemon = True t.delay = smtp['replay']['threads'].get('delay', 1) #viewThreadsSummary() #print #FIXME: after flushing all values are None t.threads = smtp['replay']['threads']['reals'].get( 'not', smtp['replay']['threads'].get('not', 1)) t.rpm = smtp['replay']['threads']['reals'].get( 'rpm', smtp['replay']['threads'].get('rpm', 1)) t.mpt = smtp['replay']['threads']['reals'].get( 'mpt', smtp['replay']['threads'].get('mpt', 1)) t.rate = smtp['replay']['threads'].get('rate', '1') t.th_interval = smtp['replay']['threads'].get('th_interval', 0) #t.msg = message t.msg = msg_builder() #t.rcpts = [smtp['addrlist']['rcpt_to']]+smtp['addrlist']['rcpts'] t.rcpts = smtp['addrlist']['rcpts'] dbginfo('debug', str(t.rcpts)) #t.msg = msg_builder().as_string(unixfrom=False) # ----------------------------------------------------------- # #print t.msg if t.msg: if raw_input(' Confirm threading [y/N]:> ') in ['y', 'Y']: # enable logging from core.msg.sender import Logger logger = Logger() t.run() logger.close() else: print fpr.err('Threading were Cancaled!') else: print fpr.err('Message can not be processed or not loaded !')
def loadSession(): print if not get_yesno_input(' Would you like to load saved session: [y/N]> '): return print fpr('Session files are stored under the session subdirectory by default.\n' \ 'Please provide a full path if you would like to load a session file from different location.') # get the latest file as default: print latest = max(glob.iglob(os.path.join(cfgs['sess_path'], '*.session')), key=os.path.getctime) if latest: fpr('Latest saved session is %s' % os.path.basename(latest)) print sf = raw_input(' [%s]> ' % os.path.basename(latest)) or latest print # if filename does not include path than search file in session dir if not os.path.dirname(sf): sf = cfgs['sess_path'] + '/' + sf if os.path.exists(sf): # import json try: f = open(sf, 'r') # json loads tmp = json.load(f) #from pprint import pprint #pprint(tmp) #TODO: test tmpe dict x = 0 for k in tmp.keys(): if k in [ 'connection', 'signatures', 'replay', 'content', 'headers' ]: x += 1 if x: fpr.ok('Session file seems to be proper') else: fpr.fail('Session file is not proper') return # overwrite main SMTP dict print '=====' #smtp = {k:v for k,v in tmp.items()} for k, v in inSMTPdict(tmp).items(): print k, v smtp[k] = v print '=====' fpr.ok('Session load successful') except IOError as e: fpr.err('Loding session failed: %s' % e) else: fpr.err('Session file does not exist')
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
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 !')
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))
def dumpSession(): info('info','Saved session allows to save current connection and message setting to be \n' \ 'useful with further tests, as a proof of successful test or used as template\n\n'\ 'Note: Session file can store sensitive data like SMTP authentication\n' \ ' credential or private keys and certificate.',adj='l') print if not get_yesno_input( ' Would you like to save your current session: [y/N]> '): return print fpr('Session files are stored under the session subdirectory by default.\n' \ 'Please provide a full path if you would like to store you session somehere else.') sessfile = 'minja-' + datetime.now().strftime('%Y%m%d%H%M%S') + '.session' print sf = raw_input(' [%s]> ' % sessfile) or sessfile print if sf == sessfile or not os.path.dirname(sf): sf = cfgs['sess_path'] + '/' + sf if os.path.exists(sf): fpr('Session file already exist') else: if os.access(os.path.dirname(sf), os.W_OK): #the file does not exists but write privileges are given fpr('Saving under %s\n' % sf) #import json dd = outSMTPdict(smtp) try: #f = codecs.open(sf, 'w', encoding='utf-8') f = open(sf, 'w') json.dump(dd, f, indent=3) fpr.ok('Session saving') except IOError as e: fpr.err('Saving file failed: %s' % e) else: fpr.fail('Missing write permission')
def parse_spfHeaders(h): if h: print h try: q = spf.query('0.0.0.0', '', '') q.mechanism = 'unknown' p = q.parse_header(h) ph = q.get_header(q.result, **p) print print p['identity'] fpr.blue(str(p)) fpr.warn(str(ph)) except Exception, e: fpr.err("Error: %s" % e)
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)
def get_file_content(fn,mode='rb'): if not os.path.isfile(fn): fpr.err('Err: File does not exist !') return None try: fp = open(fn, mode) inputs = fp.read() fp.close() if inputs: return inputs else: dbginfo('error','Err: File has no content. Please verify file size !\n[ %s ]' % fn) return None except: fpr.err("Err: Could not open a file !")
def get_rate(): # from core.data import smtp,fpr,tc,tr # import re rate = smtp['replay']['threads'].get('rate', '') fpr('Allowed values are N, N/Ms, N/Mm, N/Mh') fpr('where:') fpr(' N - number of Recipients/Messages \ \n M - value of s-seconds, m-minutes or h-hours\n') print r = raw_input(' [%s]> ' % (rate or '')) if r: m = re.match(r'^(\d+)(\/)*(\d+[smh])*$', r) if not m: # print fpr.err('Err: Incorrect syntax') return False else: #print type(m.group()) #if m.group(1): # print m.group(1) #if m.group(2): # print m.group(2) #if m.group(3): # print m.group(3) if m.group(1) and not m.group(2): fpr.ok('%s' % m.group()) smtp['replay']['threads']['rate'] = m.group() return m.group() if m.group(3): fpr.ok('%s' % m.group()) smtp['replay']['threads']['rate'] = m.group() return m.group() else: return (rate or '')
def logs_save(logs, thread_name, logpfx): from core.data import cfgs, smtp, fpr, tc, DEBUG from core.func import dbginfo from datetime import datetime logfile = logpfx + datetime.now().strftime('%Y%m%d%H%M%S') import os, errno import logging logger = logging.getLogger('threadslogs') fn = cfgs['log_path'] + '/' + logfile try: print with open(fn, "w") as text_file: text_file.write("{0}".format(logs)) fpr.ok('Saving logs in %s' % logfile) logger.info('[%s]: Successful saving logs in file: %s' % (thread_name, logfile)) except IOError as ioex: fpr.fail('Saving logs in %s' % logfile) #fpr.fail('Err: Logs not saved with %s' % logfile ) print fpr.err('Errno: %s' % ioex.errno) fpr.err('Err code: %s' % errno.errorcode[ioex.errno]) fpr.err('Err message: %s' % os.strerror(ioex.errno)) logger.info('[%s]: Saving logs in file: %s failed: %s: %s' % (thread_name, logfile, errno.errorcode[ioex.errno], os.strerror(ioex.errno)))
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
def save_content_asfile(content, fn, mode='w'): # if os.path.isfile(fn): # if not get_yesno_input (' File already exist. Overwrite it [y/N]: '): # return False try: with open(fn, mode) as fo: fo.write(content) fpr.ok('Saving content in %s' % fn) except IOError as ioex: fpr.fail('Saving content in %s' % fn ) #fpr.fail('Err: Logs not saved with %s' % logfile ) print fpr.err('Errno: %s' % ioex.errno) fpr.err('Err code: %s' % errno.errorcode[ioex.errno]) fpr.err('Err message: %s' % os.strerror(ioex.errno) )
def body_parser(dparts, bpart, x=0): # fpr('Message MIME structure') # print # fpr('_'*(tc-4)) # from email.iterators import _structure # fpr.blue('%s' % _structure(bpart) ) # #fpr.warn(_structure(bpart)) # fpr('_'*(tc-4)) print if bpart.is_multipart(): fpr.warn('~' * (tc - 4)) for part in bpart.walk(): print part.get_boundary() print part.get_content_type() print '== multipart ==' for payload in bpart.get_payload(): # if payload.is_multipart(): ... ptype = payload.get_content_type() print '--> ptype: ', ptype if ptype == 'multipart/alternative': #dparts[x] for subpart in payload.get_payload(): print '> subpart: ', subpart.get_content_type() x += 1 body_parser(dparts, subpart, x) elif ptype == 'multipart/related': print "---- m/realated ----" pprint(bpart) print dir(bpart) print bpart.get_params() print bpart.get_param('start', None) print bpart.get_param('type', None) for i, subpart in enumerate(bpart.get_payload()): print(i, subpart) print '> subpart: ', subpart.get_content_type() x += 1 body_parser(dparts, subpart, x) return #if (not start and i==0) or (start and start==subpart.get('Content-Id')): # _search_message_bodies(bodies, subpart) # return elif ptype == 'multipart/report': fpr.err('multipart/report is not supported') return elif ptype == 'multipart/signed': fpr.err('multipart/signed is not supported') retunr elif ptype == 'message/rfc822': # if ptype == fpr.err('message/rfc822 trying to parse') for subpart in payload.get_payload(): print '> m/rfc822 subpart: ', subpart.get_content_type() x += 1 body_parser(dparts, subpart, x) else: print '--else ptype=:', ptype, x x += 1 dparts[x] = dict() dparts[x]['mheaders'] = payload.items() dparts[x]['type'] = payload.get_content_type() dparts[x]['payload'] = payload.get_payload() dparts[x]['filename'] = payload.get_filename() else: print '--else no multipart' print bpart.get_content_type() print 'x=', x dparts[x] = dict() dparts[x]['mheaders'] = bpart.items() dparts[x]['type'] = bpart.get_content_type() dparts[x]['payload'] = bpart.get_payload() dparts[x]['filename'] = bpart.get_filename() #pprint(dparts[x]) #x +=1 #fpr('-- Non MIME Multipart Part --') """
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
def mpart_saver(part, op): if op == 1: #save as it is, no decoding #pprint(part) part['encext'] = None for (h, hv) in part['mheaders']: #fpr('%s: %s' % (h,hv)) if h.lower() == 'content-transfer-encoding': part['encext'] = '.' + hv.lower() print if not get_yesno_input(' Would you like to save this part: [y/N]> '): return print if part['filename']: fn = part['filename'] + part['encext'] else: fn = 'minja-' + part['type'].replace( '/', '_') + '-' + datetime.now().strftime( '%Y%m%d%H%M%S') + part['encext'] print fn = raw_input(' [%s]> ' % fn) or fn print #if sf == sessfile or not os.path.dirname(sf): # sf = cfgs['sess_path']+'/'+sf if not os.path.dirname(fn): fn = cfgs['mparts_path'] + '/' + fn if os.path.exists(fn): fpr('File already exist') else: if os.access(os.path.dirname(fn), os.W_OK): #the file does not exists but write privileges are given fpr('Saving under %s\n' % fn) try: #f = codecs.open(fn, 'w', encoding='utf-8') f = open(fn, 'w') f.write(part['payload']) f.close() fpr.ok('Session saving') except IOError as e: fpr.err('Saving file failed: %s' % e) else: fpr.fail('Missing write permission') if op == 2: #decode base64 first print if not get_yesno_input(' Would you like to save this part: [y/N]> '): return print if part['filename']: fn = part['filename'] else: fn = 'minja-' + part['type'].replace( '/', '_') + '-' + datetime.now().strftime('%Y%m%d%H%M%S') print fn = raw_input(' [%s]> ' % fn) or fn print #if sf == sessfile or not os.path.dirname(sf): # sf = cfgs['sess_path']+'/'+sf if not os.path.dirname(fn): fn = cfgs['mparts_path'] + '/' + fn if os.path.exists(fn): fpr('File already exist') else: if os.access(os.path.dirname(fn), os.W_OK): #the file does not exists but write privileges are given fpr('Saving under %s\n' % fn) try: #f = codecs.open(fn, 'w', encoding='utf-8') f = open(fn, 'wb') d = decode_attch(part['payload']) #pprint(d) f.write(d['raw']) f.close() fpr.ok('Session saving') except IOError as e: fpr.err('Saving file failed: %s' % e) else: fpr.fail('Missing write permission')
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))
def att_zip_plain_sample(mbody, smtype, sn): #mbody = smtp['content']['att'] #sn = '1' #from core.data import smpls,fpr,tc,tr #from core.func import waitin,get_zipfile,dbginfo while True: #print smpls['zip'].get(smtype,'dupa') if smpls['zip-smpls'].get( smtype) and smpls['zip-smpls'][smtype]['astat'] != 0: fpr('It seems you have already attached this zip %s sample' % smtype) if not raw_input(' Do you want to append another one [y/N]:') in [ 'y', 'Y' ]: break else: smpls['zip-smpls'].setdefault(smtype, {})['astat'] = 0 #print get_zipfile(smpls['spam']['val']) # for VOF test a name of file in archive is important !! if smpls[smtype][sn].get('filename', ''): inputs = get_zipfile(smpls[smtype][sn], fn=smpls[smtype][sn]['filename']) else: inputs = get_zipfile(smpls[smtype][sn]) #print type(inputs) if inputs: n = 1 if mbody.keys(): n = max(mbody.keys()) n += 1 #print max(mbody.keys()) print fpr('Attaching zipped %s' % smpls[smtype][sn]['descr']) print mbody.setdefault(n, {})['raw'] = inputs #mbody['0']['b64'] = inputs 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' % (smtype+'_'+smpls['zip-smpls']['filename'])) \ or 'attachments; filename=%s' % (smtype+'_'+smpls['zip-smpls']['filename']) 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 '' smpls['zip-smpls']['astat'] += 1 smpls['zip-smpls'].setdefault(smtype, {})['astat'] += 1 print fpr('Zipped %s attached (x%d)' % (smpls[smtype][sn]['descr'], smpls['zip-smpls'][smtype]['astat'])) else: fpr.err('Err: This should not happened ! ') waitin() break
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() """
def smtp_dha(cpt=1, rate=None, rcpts=[], method='RCPT TO',relays={} ,name='DHA-T-Single',v=False): dhar = dict() from pprint import pprint from core.data import cfgs,smtp,fpr,tc,DEBUG from core.func import dbginfo from core.msg.viewers import viewSmtpConv from core.msg.threads import get_tid dbginfo('DEBUG','name=%s, cpt=%s, method=%s, rate=%s, rcpts=%s' % (name,cpt,method,rate,rcpts) ) #verbnose dhost=smtp['connect']['hosts'][0] try: import sys import smtplib # # log debuglevel output from smtplib # # redirect stderr from smtplib to string # # # # - from smtplib import stderr # if cfgs['conv_logs'] and cl: # ostderr = smtplib.stderr # smtplib.stderr = StderrLogger() # run smtp session if v: fpr.white('Establishing the session ..') s = smtplib.SMTP(dhost['host'],dhost['port']) # if cfgs['conv_logs'] and cl: # s.set_debuglevel('debug') # HELO - introduce yourself if v: fpr.cyan('>>> %s %s' % ('EHLO',dhost['helo'])) (c,m) = s.ehlo(dhost['helo']) #r = s.helo(smtp['connect']['hosts'][0]['helo']) if v: #print (c,m) if 200 <= c <= 299: fpr.green('<<< %s %s' %(c,m)) if s.does_esmtp: fpr.white('ESMTP supported and have extn:') #print s.does_esmtp #print s.esmtp_features for (scmd,sarg) in s.esmtp_features.items(): fpr.white(' * %s %s' % (scmd,sarg)) elif 500 <= c <= 599: fpr.err('<<< %s %s' %(c,m)) # STAARTTLS if 'starttls' in s.esmtp_features.keys(): if dhost['tls_mode'] == 'TLS': if v: fpr.white('TLS supported and requested') fpr.white('Establishing TLS session ..') fpr.cyan('>>> %s' % ('STARTTLS')) (c,m) = s.starttls() if 200 <= c <= 299: fpr.green('<<< %s %s' %(c,m)) # HELO - introducing yourself on encrypted session should be done as well if v: fpr.cyan('>>> %s %s' % ('EHLO',dhost['helo'])) (c,m) = s.ehlo(dhost['helo']) if v: #print (c,m) if 200 <= c <= 299: fpr.green('<<< %s %s' %(c,m)) if s.does_esmtp: fpr.white('ESMTP supported and have extn:') #print s.does_esmtp #print s.esmtp_features for (scmd,sarg) in s.esmtp_features.items(): fpr.white(' * %s %s' % (scmd,sarg)) elif 500 <= c <= 599: fpr.err('<<< %s %s' %(c,m)) elif 500 <= c <= 599: fpr.err('<<< %s %s' %(c,m)) else: if v: fpr.white('TLS supported but not requested') fpr.white('Unencrypted session established') # SMTP AUTH if 'auth' in s.esmtp_features.keys(): if dhost['smtp_auth_user'] != '': if v: fpr.cyan('>>> %s %s' % ('AUTH PLAIN','*********')) (c,m) = s.login(dhost['smtp_auth_user'],dhost['smtp_auth_pass']) if v: if 200 <= c <= 299: fpr.green('<<< %s %s' %(c,m)) elif 500 <= c <= 599: fpr.err('<<< %s %s' %(c,m)) elif dhost['smtp_auth_user'] != '': if v: fpr.white('Authentication SET but not available (AUTH not supported)') fpr.white('Trying without AUTH') if method.lower() == 'rcpt to': # MAIL FROM sender = smtp['addrlist']['mail_from'] #rcpt = smtp['addrlist']['rcpt_to'] if v: fpr.cyan('>>> %s %s' % ('MAIL FROM:',sender)) (c,m) = s.docmd('MAIL FROM:',sender) if v: if 200 <= c <= 299: fpr.green('<<< %s %s' %(c,m)) elif 500 <= c <= 599: fpr.err('<<< %s %s' %(c,m)) # number of recipients to test # rpt - rcpt/thread # cpt - command/thread if cpt == None: cpt = 1 rpt = len(rcpts) cpt = rpt if v: fpr.white('Enumerating recipients ..') fpr.white(' * %s recipients to test with this thread' % len(rcpts)) fpr.white(' * method in use: %s' % method.lower()) #print rcpts for r in rcpts: if method.lower() == 'rcpt to': if v: fpr.cyan('>>> %s: <%s>' % (method,r)) (c,m) = s.docmd('%s:' % method,'<%s>' % r) else: # treat results returned from vrfy and expn similar # expn should have a separate condition as it could return # a list of recipients in case of mailing list but # in modern networks you should be really lucky to find such an SMTP server # supporting - good luck with that # - it should be implemented just as proof of concept rather than for real use if v: fpr.cyan('>>> %s <%s>' % (method,r)) (c,m) = s.docmd('%s' % method,'<%s>' % r) if 200 <= c <= 299: if v: fpr.green('<<< %s %s' %(c,m)) dhar.setdefault(r, { 'valid': True, 'code': c, 'msg': m, 'method': method.lower(), 'host': dhost['host'], 'thread': name } ) elif 500 <= c <= 599: if v: fpr.err('<<< %s %s' %(c,m)) dhar.setdefault(r, { 'valid': False, 'code': c, 'msg': m, 'method': method.lower(), 'host': dhost['host'], 'thread': name } ) else: if v: fpr.err('<<< %s %s' %(c,m)) dhar.setdefault(r, { 'valid': False, 'code': c, 'msg': m, 'method': method.lower(), 'host': dhost['host'], 'thread': name } ) # query timeout - wait before next command #sleep(1) # pprint(dhar) # quit smtp session if v: fpr.cyan('>>> %s' % ('QUIT:')) (c,m) = s.quit() if v: if 200 <= c <= 299: fpr.green('<<< %s %s' %(c,m)) fpr.white('Session closed successfully') elif 500 <= c <= 599: fpr.err('<<< %s %s' %(c,m)) if v: print fpr('To check valid recipients back to the main submenu') #pprint(dhar) # the exception is triggered only when all recipoient failed :( except smtplib.SMTPRecipientsRefused, e: fpr.fail('Error: unable to sent message. All recipients refused.') smtp['replay']['threads']['fail'].append(name) #print 'exception smtplib.SMTPRecipientsRefused',a fpr.warn(str(e)) smtp['addrlist']['r_reject'].update(e.recipients)
def enumSMTPcmd(v=None,dhost=smtp['connect']['hosts'][0]): #TODO: if no EHLO , use HELO from pprint import pprint # secure extn - list of extn received after successfull STARTTLS commands scmds = { 'extn' : [], 'secure_extn': [], 'cmds': '', 'method': [], } #pprint(dhost) #pprint(scmds) print try: import sys import smtplib # run smtp session if v: fpr.white('Establishing the session with %s on port %s' % (dhost['host'],dhost['port'])) s = smtplib.SMTP(dhost['host'],dhost['port']) if v: fpr.cyan('>>> %s' % 'HELP') r = s.help() scmds['scmds'] = r if v: fpr.green('<<< %s' % r) # if cfgs['conv_logs'] and cl: # s.set_debuglevel('debug') # HELO - introduce yourself if v: fpr.cyan('>>> %s %s' % ('EHLO',dhost['helo'])) (c,m) = s.ehlo(dhost['helo']) #r = s.helo(smtp['connect']['hosts'][0]['helo']) #print (c,m) if 200 <= c <= 299: if v: fpr.green('<<< %s %s' %(c,m)) if s.does_esmtp: if v: fpr.white('ESMTP supported and have extn:') #print s.does_esmtp #print s.esmtp_features for (scmd,sarg) in s.esmtp_features.items(): if v: fpr.white(' * %s %s' % (scmd,sarg)) scmds['extn'].append((scmd,sarg)) elif 500 <= c <= 599: fpr.err('<<< %s %s' %(c,m)) # STAARTTLS if 'starttls' in s.esmtp_features.keys(): if dhost['tls_mode'] == 'TLS': if v: fpr.white('TLS supported and requested') fpr.white('Establishing TLS session ..') fpr.cyan('>>> %s' % ('STARTTLS')) (c,m) = s.starttls() if 200 <= c <= 299: fpr.green('<<< %s %s' %(c,m)) # HELO - introducing yourself on encrypted session should be done as well if v: fpr.cyan('>>> %s %s' % ('EHLO',dhost['helo'])) (c,m) = s.ehlo(dhost['helo']) if v: #print (c,m) if 200 <= c <= 299: fpr.green('<<< %s %s' %(c,m)) if s.does_esmtp: fpr.white('ESMTP supported and have extn:') #print s.does_esmtp #print s.esmtp_features for (scmd,sarg) in s.esmtp_features.items(): fpr.white(' * %s %s' % (scmd,sarg)) scmds['secure_extn'].append((scmd,sarg)) elif 500 <= c <= 599: fpr.err('<<< %s %s' %(c,m)) elif 500 <= c <= 599: fpr.err('<<< %s %s' %(c,m)) else: if v: fpr.white('TLS supported but not requested') fpr.white('Unencrypted session established') # # SMTP AUTH # if 'auth' in s.esmtp_features.keys(): # if smtp['connect']['hosts'][0]['smtp_auth_user'] != '': # if v: # fpr.cyan('>>> %s %s' % ('AUTH PLAIN','*********')) # (c,m) = s.login(smtp['connect']['hosts'][0]['smtp_auth_user'],smtp['connect']['hosts'][0]['smtp_auth_pass']) # if v: # if 200 <= c <= 299: # fpr.green('<<< %s %s' %(c,m)) # elif 500 <= c <= 599: # fpr.err('<<< %s %s' %(c,m)) # else: # if smtp['connect']['hosts'][0]['smtp_auth_user'] != '': # if v: # fpr.white('Authentication SET but not available (AUTH not supported)') # fpr.white('Trying without AUTH') # else: # if v: # fpr.white('Authentication not available (AUTH not supported)') # fpr.white('Trying without AUTH') #print rcpts r = 'postmaster' for sm in ['EXPN','VRFY']: if v: fpr.cyan('>>> %s <%s>' % (sm,r)) (c,m) = s.docmd('%s' % sm,'<%s>' % r) if 200 <= c <= 299: if v: fpr.green('<<< %s %s' %(c,m)) scmds['method'].append(sm) elif 500 <= c <= 599: if v: fpr.err('<<< %s %s' %(c,m)) else: if v: fpr.err('<<< %s %s' %(c,m)) if 'rcpt' in scmds['scmds'].lower(): scmds['method'].append('RCPT') # pprint(dhar) # quit smtp session if v: fpr.cyan('>>> %s' % ('QUIT:')) (c,m) = s.quit() if v: if 200 <= c <= 299: fpr.green('<<< %s %s' %(c,m)) fpr.white('Session closed successfully') elif 500 <= c <= 599: fpr.err('<<< %s %s' %(c,m)) #pprint(scmds) return scmds # the exception is triggered only when all recipoient failed :( except smtplib.SMTPRecipientsRefused, e: fpr.fail('Error: unable to sent message. All recipients refused.') fpr.warn(str(e))
fpr.green('<<< %s %s' %(c,m)) fpr.white('Session closed successfully') elif 500 <= c <= 599: fpr.err('<<< %s %s' %(c,m)) #pprint(scmds) return scmds # the exception is triggered only when all recipoient failed :( except smtplib.SMTPRecipientsRefused, e: fpr.fail('Error: unable to sent message. All recipients refused.') fpr.warn(str(e)) except smtplib.SMTPResponseException, e: fpr.fail('Error: unable to sent message') fpr.err('%s %s',(e.smtp_code,e.smtp_error)) except smtplib.SMTPException: fpr.fail('Error: unable to sent message') # for all other errors like socket, io, rtc errors except Exception,error: fpr.err('%s' % str(error) ) # --------------------------------------------------------------------------- # # # --------------------------------------------------------------------------- # def smtp_dha(cpt=1, rate=None, rcpts=[], method='RCPT TO',relays={} ,name='DHA-T-Single',v=False):
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.')