示例#1
0
def run(name, config):
    """Start a milter loop.
    """
    Milter.factory = PGPMilter
    Milter.factory.config = config
    Milter.set_flags(Milter.ADDHDRS + Milter.CHGHDRS + Milter.CHGBODY)
    Milter.runmilter(name, config.socket, timeout=config.timeout)
def macromilterSUT(request):

    macromilter.LOG_DIR = 'test_output/'
    macromilter.MATCHED_FILE_LOG_DIR = 'test_output/matched_files/'
    macromilter.initialize_async_process_queues(20)
    macromilter.cleanup_queues()

    Milter.factory = macromilter.MacroMilter
    flags = Milter.CHGBODY + Milter.CHGHDRS + Milter.ADDHDRS
    flags += Milter.ADDRCPT
    flags += Milter.DELRCPT
    Milter.set_flags(flags)
    Milter.factory._ctx = TestBase()

    sut = macromilter.MacroMilter()
    sut.messageToParse = StringIO.StringIO()

    def tear_down():
        # clear queues
        macromilter.cleanup_queues()
        macromilter.WhiteList = ()

    request.addfinalizer(tear_down)

    return sut
示例#3
0
def main():
  # Run as a specific user
  if run_as_user != None:
    run_as_uid = getpwnam(run_as_user).pw_uid
    run_as_gid = getpwnam(run_as_user).pw_gid
    print "%s running as %s (uid=%s,gid=%s)" % (time.strftime('%Y%b%d %H:%M:%S'), run_as_user, run_as_uid, run_as_gid)
    # always set gid first, because once we've set uid, we can't set gid anymore
    os.setgid(run_as_gid)
    os.setuid(run_as_uid)

  # Log startup
  print "%s milter startup" % time.strftime('%Y%b%d %H:%M:%S')
  sys.stdout.flush()

  # Handle log printing in the background
  bt = Thread(target=background)
  bt.start()

  # Register to have the Milter factory create instances of your class:
  Milter.factory = MilterSysUser
  #Milter.set_flags(Milter.ADDHDRS) # we only need to add a header

  flags = Milter.CHGBODY + Milter.CHGHDRS + Milter.ADDHDRS
  flags += Milter.ADDRCPT
  flags += Milter.DELRCPT
  Milter.set_flags(flags)       # tell Sendmail which features we use

  Milter.runmilter("pythonfilter", socketname, timeout)

  # Wait for logger to complete
  logq.put(None)
  bt.join()
  print "%s milter shutdown" % time.strftime('%Y%b%d %H:%M:%S')
def main():
    """Start the milter."""
    socket = "/tmp/change-rcpt-milter.sock"
    timeout = 600
    Milter.factory = ChangeRecipientMilter
    logger.info("{} {} starting".format(MILTER_NAME, MILTER_VERSION))
    Milter.runmilter(MILTER_NAME, socket, timeout)
    logger.info("{} {} shutting down".format(MILTER_NAME, MILTER_VERSION))
示例#5
0
文件: milter.py 项目: cirrax/pydspam
 def run(self):
     utils.log_to_syslog()
     logger.info('DSPAM Milter startup (v{})'.format(VERSION))
     self.configure()
     utils.daemonize(self.pidfile)
     Milter.factory = DspamMilter
     Milter.runmilter('DspamMilter', self.socket, self.timeout)
     logger.info('DSPAM Milter shutdown (v{})'.format(VERSION))
     logging.shutdown()
示例#6
0
def main():
  bt = Thread()
  bt.start()
  timeout = 60
  # Register with Milter factory 
  Milter.factory = pgpMilter
  # we don't modify mails, so no flags
  Milter.set_flags(0)
  Milter.runmilter("pgpmilter",socket,timeout)
  bt.join()
示例#7
0
def main():
  socketname = "/var/run/nomixsock"
  timeout = 600
  # Register to have the Milter factory create instances of your class:
  Milter.factory = NoMixMilter
  print("%s milter startup" % time.strftime('%Y%b%d %H:%M:%S'))
  sys.stdout.flush()
  Milter.runmilter("nomixfilter",socketname,timeout)
  logq.put(None)
  bt.join()
  print("%s nomix milter shutdown" % time.strftime('%Y%b%d %H:%M:%S'))
示例#8
0
文件: wumi.py 项目: gonter/wumi
def main():

    sys.stdout.write("--------------- WUMI START ---------------\n")
    sys.stdout.flush()
    cfg.vars = cfg.Globals(configfile)
    syslog.openlog(cfg.vars["filtername"])
    Milter.factory = WUMilter
    Milter.set_flags(Milter.ADDHDRS | Milter.CHGHDRS)
    Milter.runmilter(cfg.vars["filtername"],
                     cfg.vars["socketname"],
                     timeout=1800)
    print '%s: runmilter returned - shutdown' % cfg.vars["filtername"]
def main():
    timeout = 600
    Milter.factory = LissMilter

    # Tell Sendmail which features we use
    flags = Milter.CHGHDRS
    Milter.set_flags(flags)

    print("%s milter startup" % time.strftime('%Y-%m-%d %H:%M:%S'))
    sys.stdout.flush()
    Milter.runmilter("lissmilter", connection_string, timeout)
    print("%s milter shutdown" % time.strftime('%Y-%m-%d %H:%M:%S'))
示例#10
0
def main():
    bt = Thread( target = background )
    bt.start()
    socketname = "/var/spool/EARS/EARSmilter.sock"
    timeout = 600
    Milter.factory = EARS.milter
    flags = Milter.CHGBODY + Milter.CHGHDRS + Milter.ADDHDRS
    flags += Milter.ADDRCPT
    flags += Milter.DELRCPT
    Milter.set_flags( flags )     # tell Sendmail/Postfix which features we use
    Milter.runmilter( "EARSmilter", socketname, timeout )
    logq.put( None )
    bt.join()
示例#11
0
def main():
    bt = Thread(target=background)
    bt.start()
    socketname = "/var/run/pagure/paguresock"
    timeout = 600
    # Register to have the Milter factory create instances of your class:
    Milter.factory = PagureMilter
    print "%s pagure milter startup" % time.strftime('%Y%b%d %H:%M:%S')
    sys.stdout.flush()
    Milter.runmilter("paguremilter", socketname, timeout)
    logq.put(None)
    bt.join()
    print "%s pagure milter shutdown" % time.strftime('%Y%b%d %H:%M:%S')
def main():
    bt = Thread(target=background)
    bt.start()
    socketname = "/var/run/pagure/paguresock"
    timeout = 600
    # Register to have the Milter factory create instances of your class:
    Milter.factory = PagureMilter
    print "%s pagure milter startup" % time.strftime("%Y%b%d %H:%M:%S")
    sys.stdout.flush()
    Milter.runmilter("paguremilter", socketname, timeout)
    logq.put(None)
    bt.join()
    print "%s pagure milter shutdown" % time.strftime("%Y%b%d %H:%M:%S")
示例#13
0
def main():
  parser = OptionParser()
  parser.add_option('-s', '--socket', dest='socket', help='Socket to listen (e.g. inet:8890@localhost)')
  parser.add_option('-t', '--timeout', type='int', dest='timeout', default='10', help='MTA timeout (default is 10 sec)')
  (options, args) = parser.parse_args()
  if not options.socket:
    parser.print_help()
    sys.exit(0)
    
  Milter.factory = TuMilter
  print "%s TuMilter startup" % time.strftime('%Y %b %d %H:%M:%S')
  sys.stdout.flush()
  Milter.runmilter("tumilter",options.socket,options.timeout)
示例#14
0
def main():
    """Main entry point, run the milter and start the background logging daemon"""

    try:
        debug = configParser.getboolean('main', 'debug')

        # Exit if the main thread have been already created
        if os.path.exists(PID_FILE_PATH):
            print("pid file {} already exists, exiting".format(PID_FILE_PATH))
            os.exit(-1)

        lgThread = Thread(target=loggingThread)
        lgThread.start()
        timeout = 600

        # Register to have the Milter factory create new instances
        Milter.factory = MarkAddressBookMilter

        # For this milter, we only add headers
        flags = Milter.ADDHDRS
        Milter.set_flags(flags)

        # Get the parent process ID and remember it
        pid = os.getpid()
        with open(PID_FILE_PATH, "w") as pidFile:
            pidFile.write(str(pid))
            pidFile.close()

        print("Started RoundCube address book search and tag milter (pid={}, debug={})".format(pid, debug))
        sys.stdout.flush()

        # Start the background thread
        Milter.runmilter("milter-rc-abook", SOCKET_PATH, timeout)
        GlobalLogQueue.put(None)

        #  Wait until the logging thread terminates
        lgThread.join()

        # Log the end of process
        print("Stopped RoundCube address book search and tag milter (pid={})".format(pid))

    except Exception as error:
        print("Exception when running the milter: {}".format(error.message))

    # Make sure to remove the pid file even if an error occurs
    # And close the database connection if opened
    finally:
        if os.path.exists(PID_FILE_PATH):
            os.remove(PID_FILE_PATH)
示例#15
0
def main():
    os.umask(007)
    Milter.set_flags(  Milter.QUARANTINE
                     + Milter.CHGHDRS
                     + Milter.DELRCPT
                     + Milter.ADDRCPT
                     + Milter.CHGFROM)

    config = getConfig()

    def instantiate():
        return DMARCMilter(config)

    Milter.factory = instantiate
    Milter.runmilter("dmarc_milter", config.socket, config.timeout)
示例#16
0
 def __init__(self):
   self.tempname = None
   self.mailfrom = None
   self.fp = None
   self.bodysize = 0
   self.id = Milter.uniqueID()
   self.user = None
示例#17
0
文件: rabf.py 项目: hax404/rabf
  def envrcpt(self, to, *str):
    rcptinfo = to,Milter.dictfromlist(str)
    self.R.append(rcptinfo)
    self.log("to: ", parse_addr(to)[0])

    a = 23
    b = 42
    addr = parse_addr(to)[0]
    euser = addr[0:2]
    ecsum = addr[2:4]
    eitext = addr[4:]
    edomain = parse_addr(to)[1]
    genitext = ''.join((euser, eitext, edomain))
    gencsum = hashlib.sha512(genitext.encode('utf-8')).hexdigest()
    posa = int(a)-1
    posb = int(b)-1
    csuma = gencsum[posa:(posa+1)]
    csumb = gencsum[posb:(posb+1)]

    self.log(addr, euser, ecsum, eitext, edomain, genitext, gencsum, posa, posb, csuma, csumb)

    if(ecsum != "".join((csuma,csumb))):
      self.log("Computer sagt nein.")
      return Milter.REJECT

    self.log("Computer sagt ja.")
    return Milter.CONTINUE
示例#18
0
 def envfrom(self, fromAddress, *extra):
     self.mailFrom = '@'.join(parse_addr(fromAddress))
     self.recipients = []
     self.fromparms = Milter.dictfromlist(extra) # ESMTP parms
     self.user = self.getsymval('{auth_authen}') # authenticated user
     self.fp = StringIO.StringIO()
     return Milter.CONTINUE
示例#19
0
 def __init__(self):
     self.tempname = None
     self.mailfrom = None
     self.fp = None
     self.bodysize = 0
     self.id = Milter.uniqueID()
     self.user = None
示例#20
0
	def __init__(self):  # A new instance with each new connection.
		self.id = Milter.uniqueID()  # Integer incremented with each call.
		self.messageToParse = None
		self.level = 0
		self.headercount = 0
		self.attachment_contains_macro = False
		self.size = 0
 def __init__(self):  # A new instance with each new connection.
     self.id = Milter.uniqueID()  # Integer incremented with each call.
     # You can initialize more stuff here
     self.subjectHeader = ''
     self.fromContentType = ''
     self.MIMEVersionHeader = ''
     self.ListProcessed = 'false'
     self.recip = []
示例#22
0
def main():
  bt = Thread(target=background)
  bt.start()
  socketname = "/home/stuart/pythonsock"
  timeout = 600
 
  Milter.factory = myMilter
  flags = Milter.CHGBODY + Milter.CHGHDRS + Milter.ADDHDRS
  flags += Milter.ADDRCPT
  flags += Milter.DELRCPT
  Milter.set_flags(flags)      
  print "%s milter startup" % time.strftime('%Y%b%d %H:%M:%S')
  sys.stdout.flush()
  Milter.runmilter("pythonfilter",socketname,timeout)
  logq.put(None)
  bt.join()
  print "%s bms milter shutdown" % time.strftime('%Y%b%d %H:%M:%S')
示例#23
0
def main():
  bt = Thread(target=background)
  bt.start()
  socketname = "/home/stuart/pythonsock"
  timeout = 600
  # Register to have the Milter factory create instances of your class:
  Milter.factory = myMilter
  flags = Milter.CHGBODY + Milter.CHGHDRS + Milter.ADDHDRS
  flags += Milter.ADDRCPT
  flags += Milter.DELRCPT
  Milter.set_flags(flags)       # tell Sendmail which features we use
  print "%s milter startup" % time.strftime('%Y%b%d %H:%M:%S')
  sys.stdout.flush()
  Milter.runmilter("pythonfilter",socketname,timeout)
  logq.put(None)
  bt.join()
  print "%s bms milter shutdown" % time.strftime('%Y%b%d %H:%M:%S')
示例#24
0
 def __init__(self, conf=None):  # A new instance with each new connection.
     self.id = Milter.uniqueID()
     if conf is not None:
         assert isinstance(conf, config.Config)
         self.conf = conf
     else:
         self.conf = config.Config()
     self.gpgm_gpg = gnupg.GPG(gnupghome=self.conf.gnupghome)
示例#25
0
def main():
  bt = Thread(target=background)
  bt.start()
  socketname = "/home/stuart/pythonsock"
  timeout = 600
  # Register to have the Milter factory create instances of your class:
  Milter.factory = myMilter
  flags = Milter.CHGBODY + Milter.CHGHDRS + Milter.ADDHDRS
  flags += Milter.ADDRCPT
  flags += Milter.DELRCPT
  Milter.set_flags(flags)       # tell Sendmail which features we use
  print("%s milter startup" % time.strftime('%Y%b%d %H:%M:%S'))
  sys.stdout.flush()
  Milter.runmilter("pythonfilter",socketname,timeout)
  logq.put(None)
  bt.join()
  print("%s bms milter shutdown" % time.strftime('%Y%b%d %H:%M:%S'))
示例#26
0
 def envfrom(self, mailfrom, *str):
     self.fromparms = Milter.param2dict(str)  # ESMTP parms
     self.user = self.getsymval('{auth_authen}')  # authenticated user
     self.canon_from = '@'.join(parse_addr(mailfrom))
     self.R = []
     self.fp = BytesIO()
     self.fp.write(b"From %s %s\n" % (codecs.encode(self.canon_from, 'utf-8'), codecs.encode(time.ctime(), 'utf-8')))
     return Milter.CONTINUE
示例#27
0
文件: milter.py 项目: cirrax/pydspam
    def __init__(self):
        """
        Create a new milter instance.

        """
        self.id = Milter.uniqueID()
        self.message = ''
        self.recipients = []
        self.dspam = None
示例#28
0
def main():
    # fully qualified name for the socket, postfix will only see /var/run/zf/sock
    socketname = "/var/spool/postfix/var/run/zf/sock"
    timeout = 600
    # Register to have the Milter factory create instances of your class:
    Milter.factory = zfMilter
    # these flags allow us to change the body, recipients and headers
    flags = Milter.CHGBODY + Milter.CHGHDRS + Milter.ADDHDRS
    flags += Milter.ADDRCPT
    flags += Milter.DELRCPT
    Milter.set_flags(flags)  # tell Sendmail which features we use
    syslog.syslog(
        syslog.LOG_INFO,
        json.dumps(
            {"msg": "%s milter startup" % time.strftime('%Y%b%d %H:%M:%S')}))
    sys.stdout.flush()
    Milter.runmilter("zfmilter", socketname, timeout)
    print "%s zf milter shutdown" % time.strftime('%Y%b%d %H:%M:%S')
示例#29
0
 def envfrom(self, mailfrom, *str):
     self.F = mailfrom
     self.R = []  # list of recipients
     self.fromparms = Milter.dictfromlist(str)  # ESMTP parms
     self.user = self.getsymval('{auth_authen}')  # authenticated user
     self.fp = StringIO.StringIO()
     self.canon_from = '@'.join(parse_addr(mailfrom))
     #self.fp.write('From %s %s\n' % (self.canon_from,time.ctime()))
     return Milter.CONTINUE
示例#30
0
 def envfrom(self, mailfrom, *str):
     self.F = mailfrom
     self.R = []
     self.fromparms = Milter.dictfromlist(str)
     self.user = self.getsymval('{auth_authen}')
     self.fp = StringIO()
     self.canon_from = '@'.join(parse_addr(mailfrom))
     self.fp.write('From %s %s\n' % (self.canon_from, time.ctime()))
     return Milter.CONTINUE
示例#31
0
 def __init__(self):  # Each connection calls new S3Milter
     MimeBodyProcessor.__init__(self)
     self.id = Milter.uniqueID()  # Integer incremented with each call.
     self.body_file = StringIO.StringIO()
     self.log_queue = None
     self.postgre_queue = None
     self.start_time = timestamp_start()
     self.log('debug', log_status(module_name=__name__, function_name='__init__',
                                  msg='Launched Milter ID={}'.format(self.id)))
示例#32
0
    def __init__(self):
        self._id = Milter.uniqueID()
        self._ip = None
        self._ip_name = None
        self._port = None

        self.fp = None
        self.headers_seen = []
        self.rcpts = []
示例#33
0
def main():
    # Ugh, but there's no easy way around this.
    global milterconfig
    global privateRSA
    global privateEd25519
    global publicSuffixList
    privateRSA = False
    privateEd25519 = False
    configFile = '/usr/local/etc/senderauth-milter.conf'
    pslFile = '/usr/local/etc/public_suffix_list.dat'
    if len(sys.argv) > 1:
        if sys.argv[1] in ('-?', '--help', '-h'):
            print('usage: dkimpy-milter [<configfilename>]')
            sys.exit(1)
        configFile = sys.argv[1]

    milterconfig = config._processConfigFile(filename=configFile)
    if milterconfig.get('Syslog'):
        facility = eval("syslog.LOG_{0}".format(
            milterconfig.get('SyslogFacility').upper()))
        syslog.openlog(os.path.basename(sys.argv[0]), syslog.LOG_PID, facility)
        setExceptHook()
    #
    pid = write_pid(milterconfig)
    if milterconfig.get('KeyFile'):
        privateRSA = read_keyfile(milterconfig, 'RSA')
    if milterconfig.get('KeyFileEd25519'):
        privateEd25519 = read_keyfile(milterconfig, 'Ed25519')
    Milter.factory = dkimMilter
    Milter.set_flags(Milter.CHGHDRS + Milter.ADDHDRS)
    miltername = 'samilter'
    socketname = milterconfig.get('Socket')
    if milterconfig.get('Syslog'):
        syslog.syslog('samilter started:{0} user:{1}'.format(
            pid, milterconfig.get('UserID')))
    publicSuffixList = dmarc.PublicSuffixList(pslFile)
    if not publicSuffixList:
        if milterconfig.get('Syslog'):
            syslog.syslog('Could not open PSL file:{}'.format(pslFile))
        sys.exit(1)
    sys.stdout.flush()
    Milter.runmilter(miltername, socketname, 240)
    own_socketfile(milterconfig)
    drop_privileges(milterconfig)
示例#34
0
 def envfrom(self, mailfrom, *str):
     self.log("mail from: %s  -  %s" % (mailfrom, str))
     self.fromparms = Milter.dictfromlist(str)
     # NOTE: self.fp is only an *internal* copy of message data.  You
     # must use addheader, chgheader, replacebody to change the message
     # on the MTA.
     self.fp = StringIO.StringIO()
     self.canon_from = '@'.join(parse_addr(mailfrom))
     self.fp.write('From %s %s\n' % (self.canon_from, time.ctime()))
     return Milter.CONTINUE
示例#35
0
	def envfrom( self, mailfrom, *ESMTP_params ):
		self.Message.SMTP.MAIL_FROM = mailfrom.strip( '<>' );
		self.Message.SMTP.MAIL_FROM_PARAMS = Milter.dictfromlist( ESMTP_params );    # ESMTP params
		self.Message.SMTP.AUTH_USER = self.getsymval( '{auth_authen}' );    # Authenticated User
# 		self.canon_from = '@'.join( parse_addr( mailfrom ) )
# 		self.Message.Raw.write( 'From %s %s\n' % ( self.canon_from, time.ctime() ) )

		self.log.smtp( "mail from:", self.Message.SMTP.MAIL_FROM, *ESMTP_params )

		return self.ProcessRuleSet();
示例#36
0
def main(args=None):
	import argparse
	parser = argparse.ArgumentParser(
		description='Ad-hoc dspam milter that does --deliver=summary'
			' and only adds result as header, never rejecting or dropping messages.' )
	parser.add_argument('socket',
		nargs='?', default='local:/tmp/dspam_milter.sock',
		help='libmilter-format socket spec to listen on (default: %(default)s).'
			' Examples: local:/tmp/dspam_milter.sock, inet:1234@localhost, inet6:1234@localhost')
	parser.add_argument('-u', '--user',
		metavar='name', default='dspam',
		help='--user parameter to pass argument to dspam client (default: %(default)s).'
			' dspam-recognized group names can be passed here as well.'
			' Affects spam classification groups and permissions. Empty - dont pass.')
	parser.add_argument('-t', '--timeout',
		type=float, default=600, metavar='seconds',
		help='Number of seconds the MTA should wait'
			' for a response before considering this milter dead (default: %(default)s).')
	parser.add_argument('--dspam-fail-pass', action='store_true',
		help='Accept mails instead of returning TEMPFAIL'
			' if dspamc returns any kind of errors instead of filtering results.')
	parser.add_argument('--dspam-opts', action='append', metavar='options',
		help='Extra options to pass to dspamc command.'
			' Will be split on spaces, unless option is used multiple times.')
	parser.add_argument('--debug', action='store_true', help='Verbose operation mode.')
	opts = parser.parse_args(sys.argv[1:] if args is None else args)

	logging.basicConfig(
		level=logging.DEBUG if opts.debug else logging.WARNING,
		format='%(levelname)s :: %(message)s')
	log = logging.getLogger('dspam_milter.main')

	# pymilter uses stdout for spam, no logging should go there anyway
	sys.stdout = open(os.devnull, 'w')

	dspamc_opts = opts.dspam_opts or list()
	if len(dspamc_opts) == 1: dspamc_opts = dspamc_opts[0].strip().split()

	Milter.factory = ft.partial( MilterDspam, opts.user,
		fail_pass=opts.dspam_fail_pass, dspamc_opts=dspamc_opts )
	log.debug('Starting libmilter loop...')
	Milter.runmilter('DspamMilter', opts.socket, opts.timeout)
	log.debug('libmilter loop stopped')
示例#37
0
def main():

    #TODO parse command line

    # read configuration
    cfgfile = "/etc/gnupg-milter.conf"
    conf = gpgmilter.config.Config(cfgfile)
    conf.init_config(cfgfile)

    # Register to have the Milter factory create instances of your class:
    Milter.factory = gpgmilter.GnupgMilter.gpgm_get_factory(conf=conf)
    flags = Milter.CHGBODY + Milter.CHGHDRS + Milter.ADDHDRS
    flags += Milter.ADDRCPT
    flags += Milter.DELRCPT
    Milter.set_flags(flags)
    print("%s gnupg-milter startup" % time.strftime('%Y-%m-%d %H:%M:%S'))
    sys.stdout.flush()
    Milter.runmilter("gnupg-milter", config.socket, config.timeout)
    print("%s gnupg-milter shutdown" % time.strftime('%Y-%m-%d %H:%M:%S'))
示例#38
0
文件: wumi.py 项目: gonter/wumi
 def __init__(self):
     self.v_id = Milter.uniqueID()
     self.v_remotehostname = ''
     self.v_remotehostip = ''
     self.o_lastplugin = Plugin(
         self
     )  # even if no eom plugins are configured, the ok() method is necessary
     self.v_keepfile = False
     self.v_rblinfo = False  # Do we have the info about rbl appearance of v_remotehostip
     self.reset()
示例#39
0
def main():
    args = arg_config()
    (server_ip, server_port) = args.server.split(":")
    socketspec = "inet:" + server_port + ":" + server_ip
    syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_MAIL)

    syslog.syslog(syslog.LOG_INFO,
                  "Start loading rules at {}".format(datetime.datetime.now()))
    load_rules(args.config)
    syslog.syslog(syslog.LOG_INFO,
                  "Finish loading rules at {}".format(datetime.datetime.now()))

    Milter.factory = MailAcl
    Milter.set_flags(Milter.ADDHDRS)
    syslog.syslog(syslog.LOG_DEBUG, "running milter")
    Milter.runmilter("mail_acl", socketspec, 60)

    # Finished
    syslog.syslog(syslog.LOG_INFO, "shutdown")
 def envfrom(self, mailfrom, *str):
     self.log("mail from: %s  -  %s" % (mailfrom, str))
     self.fromparms = Milter.dictfromlist(str)
     # NOTE: self.fp is only an *internal* copy of message data.  You
     # must use addheader, chgheader, replacebody to change the message
     # on the MTA.
     self.fp = StringIO.StringIO()
     self.canon_from = "@".join(parse_addr(mailfrom))
     self.fp.write("From %s %s\n" % (self.canon_from, time.ctime()))
     return Milter.CONTINUE
示例#41
0
 def envfrom(self, mailfrom, *str):
     self.log("mail from: %s  -  %s" % (mailfrom, str))
     self.fromparms = Milter.dictfromlist(str)
     # NOTE: self.fp is only an *internal* copy of message data.  You
     # must use addheader, chgheader, replacebody to change the message
     # on the MTA.
     self.fp = BytesIO()
     self.canon_from = "@".join(parse_addr(mailfrom))
     from_txt = "From %s %s\n" % (self.canon_from, time.ctime())
     self.fp.write(from_txt.encode("utf-8"))
     return Milter.CONTINUE
示例#42
0
    def envfrom(self, mailfrom, *str):
        self.F = mailfrom
        self.R = []  
        self.fromparms = Milter.dictfromlist(str)  
        self.user = self.getsymval('{auth_authen}')  
       

        self.fp = StringIO.StringIO()
        self.canon_from = '@'.join(parse_addr(mailfrom))
        self.fp.write('From %s %s\n' % (self.canon_from, time.ctime()))
        return Milter.CONTINUE
def main():
    bt = Thread(target=background)
    bt.start()
    # This is NOT a good socket location for production, it is for
    # playing around.  I suggest /var/run/milter/myappnamesock for production.
    #  socketname = os.path.expanduser('~/pythonsock')
    socketname = "inet:8800"
    timeout = 600
    # Register to have the Milter factory create instances of your class:
    Milter.factory = myMilter
    flags = Milter.CHGBODY + Milter.CHGHDRS + Milter.ADDHDRS
    flags += Milter.ADDRCPT
    flags += Milter.DELRCPT
    Milter.set_flags(flags)  # tell Sendmail which features we use
    print("%s milter startup" % time.strftime('%Y%b%d %H:%M:%S'))
    sys.stdout.flush()
    Milter.runmilter("pythonfilter", socketname, timeout)
    logq.put(None)
    bt.join()
    print("%s bms milter shutdown" % time.strftime('%Y%b%d %H:%M:%S'))
示例#44
0
 def __init__(self):
     # A new instance with each new connection.
     # each connection runs in its own thread and has its own myMilter
     # instance.  Python code must be thread safe.  This is trivial if only stuff
     # in myMilter instances is referenced.
     self.id = Milter.uniqueID()  # Integer incremented with each call.
     self.message = None
     self.IP = None
     self.port = None
     self.flow = None
     self.scope = None
     self.IPname = None  # Name from a reverse IP lookup
示例#45
0
 def __init__(self):
     # A new instance with each new connection.
     # each connection runs in its own thread and has its own myMilter
     # instance.  Python code must be thread safe.  This is trivial if only stuff
     # in myMilter instances is referenced.
     self.id = Milter.uniqueID()  # Integer incremented with each call.
     self.message = None
     self.IP = None
     self.port = None
     self.flow = None
     self.scope = None
     self.IPname = None  # Name from a reverse IP lookup
def main():
  syslog('Starting daemon')

  try:
    args = parseArgs()
      
    with PidFile(args.pidfile) as pidfile:
      def createMilter():
        return EncryptionMilter(args.keyring)
      
      Milter.factory = createMilter
      flags = Milter.CHGBODY
      Milter.set_flags(flags)

      Milter.runmilter('encryption-milter', args.socket, 600)

  except Exception as e:
    syslog('An error occured')
    syslog(str(e))

  syslog('Shutting down daemon')
示例#47
0
def main():
    # banner
    print('mraptor_milter v%s - http://decalage.info/python/oletools' % __version__)
    print('logging to file %s' % LOGFILE_PATH)
    print('Press Ctrl+C to stop.')

    # make sure the log directory exists:
    try:
        os.makedirs(LOGFILE_DIR)
    except:
        pass
    # Add the log message handler to the logger
    # log to files rotating once a day:
    handler = logging.handlers.TimedRotatingFileHandler(LOGFILE_PATH, when='D', encoding='utf8')
    # create formatter and add it to the handlers
    formatter = logging.Formatter('%(asctime)s - %(levelname)8s: %(message)s')
    handler.setFormatter(formatter)
    log.addHandler(handler)
    # enable logging:
    log.setLevel(logging.DEBUG)

    log.info('Starting mraptor_milter v%s - listening on %s' % (__version__, SOCKET))
    log.debug('Python version: %s' % sys.version)

    # Register to have the Milter factory create instances of the class:
    Milter.factory = MacroRaptorMilter
    flags = Milter.CHGBODY + Milter.CHGHDRS + Milter.ADDHDRS
    flags += Milter.ADDRCPT
    flags += Milter.DELRCPT
    Milter.set_flags(flags)  # tell Sendmail which features we use
    # set the "last" fall back to ACCEPT if exception occur
    Milter.set_exception_policy(Milter.ACCEPT)
    # start the milter
    Milter.runmilter("mraptor_milter", SOCKET, TIMEOUT)
    log.info('Stopping mraptor_milter.')
示例#48
0
def main():
	# Load the whitelist into memory
	WhiteListLoad()
	HashTableLoad()

	thread_pool = create_and_start_worker_threads()

	# Register to have the Milter factory create instances of the class:
	Milter.factory = MacroMilter
	flags = Milter.CHGBODY + Milter.CHGHDRS + Milter.ADDHDRS
	flags += Milter.ADDRCPT
	flags += Milter.DELRCPT
	Milter.set_flags(flags)  # tell Sendmail which features we use
	# start milter processing
	print "%s Macro milter startup - Version %s" % (time.strftime('%d.%b.%Y %H:%M:%S'), __version__)
	sys.stdout.flush()
	# set the "last" fall back to ACCEPT if exception occur
	Milter.set_exception_policy(Milter.ACCEPT)

	# start the milter
	Milter.runmilter("MacroMilter", SOCKET, TIMEOUT)

	shutdown_worker_threads(thread_pool)
	cleanup_queues()

	print "%s Macro milter shutdown" % time.strftime('%d.%b.%Y %H:%M:%S')
示例#49
0
def main():
    # banner
    print('mraptor_milter v%s - http://decalage.info/python/oletools' % __version__)
    print('logging to file %s' % LOGFILE_PATH)
    print('Press Ctrl+C to stop.')

    # make sure the log directory exists:
    try:
        os.makedirs(LOGFILE_DIR)
    except:
        pass
    # Add the log message handler to the logger
    # log to files rotating once a day:
    handler = logging.handlers.TimedRotatingFileHandler(LOGFILE_PATH, when='D', encoding='utf8')
    # create formatter and add it to the handlers
    formatter = logging.Formatter('%(asctime)s - %(levelname)8s: %(message)s')
    handler.setFormatter(formatter)
    log.addHandler(handler)
    # enable logging:
    log.setLevel(logging.DEBUG)

    log.info('Starting mraptor_milter v%s - listening on %s' % (__version__, SOCKET))
    log.debug('Python version: %s' % sys.version)

    # Register to have the Milter factory create instances of the class:
    Milter.factory = MacroRaptorMilter
    flags = Milter.CHGBODY + Milter.CHGHDRS + Milter.ADDHDRS
    flags += Milter.ADDRCPT
    flags += Milter.DELRCPT
    Milter.set_flags(flags)  # tell Sendmail which features we use
    # set the "last" fall back to ACCEPT if exception occur
    Milter.set_exception_policy(Milter.ACCEPT)
    # start the milter
    Milter.runmilter("mraptor_milter", SOCKET, TIMEOUT)
    log.info('Stopping mraptor_milter.')
示例#50
0
 def __init__(self):
     self.mailfrom = None
     self.mailfromdom = None
     self.fdomain = None
     self.helodomain = None
     self.id = Milter.uniqueID()
     # we don't want config used to change during a connection
     self.conf = milterconfig
     self.privatersa = privateRSA
     self.privateed25519 = privateEd25519
     self.fp = None
     self.dkimdomain = None
     self.dkimresult = 'none'
示例#51
0
def execute():
    log_manager = LogManager(log_queue)
    log_manager.start()
    postgre_manager = PostgreManager(postgresql_creds, postgre_queue, log_queue)
    postgre_manager.start()
    Milter.factory = QueuedS3Milter
    Milter.set_flags(Milter.MODBODY)
    log_queue.put({
        'type': 'info',
        'message': log_config.log_success(module_name=__name__, function_name='execute',
                                          msg='S3 Milter service launched.')
    })
    Milter.runmilter('S3Milter', milter_params['socket_name'], milter_params['timeout'])
    log_queue.put({
        'type': 'info',
        'message': log_config.log_success(module_name=__name__, function_name='execute',
                                          msg='S3 Milter service shutdown.')
    })
    postgre_queue.put(None)
    postgre_manager.join()
    log_queue.put(None)
    log_manager.join()
示例#52
0
    def __init__(self, config):
        self.is_internal_host = None
        self.envlp_from       = EmailAddress(logger=config.logger)
        self.envlp_to         = EmailAddress(logger=config.logger)
        self.hdr_from         = EmailAddress(logger=config.logger)
        self.hdr_to           = EmailAddress(logger=config.logger)

        self.x_mail_domain    = None
        self.x_action_uuid    = None
        self.id               = Milter.uniqueID()
        self.config           = config

        self.config.logger.debug('__init__')
示例#53
0
 def envfrom(self, mailfrom, *str):
     self.F = mailfrom
     self.R = []  # list of recipients
     self.fromparms = Milter.dictfromlist(str)  # ESMTP parms
     self.user = self.getsymval('{auth_authen}')  # authenticated user
     self.log("mail from:", mailfrom, *str)
     # NOTE: self.fp is only an *internal* copy of message data.  You
     # must use addheader, chgheader, replacebody to change the message
     # on the MTA.
     self.fp = BytesIO()
     self.canon_from = '@'.join(parse_addr(mailfrom))
     #self.fp.write('From %s %s\n' % (self.canon_from,time.ctime()))
     return Milter.CONTINUE
示例#54
0
 def envfrom(self, mailfrom, *str):
   self.F = mailfrom
   self.R = []  # list of recipients
   self.fromparms = Milter.dictfromlist(str)	# ESMTP parms
   self.user = self.getsymval('{auth_authen}')	# authenticated user
   self.log("mail from:", mailfrom, *str)
   # NOTE: self.fp is only an *internal* copy of message data.  You
   # must use addheader, chgheader, replacebody to change the message
   # on the MTA.
   self.fp = StringIO()
   self.canon_from = '@'.join(parse_addr(mailfrom))
   self.fp.write('From %s %s\n' % (self.canon_from,time.ctime()))
   return Milter.CONTINUE
示例#55
0
def main():

    # make sure the log directory exists:
    try:
        os.makedirs(LOGFILE_DIR, 0o0027)
    except:
        pass

    # Load the whitelist into memory
    WhiteListLoad()
    HashTableLoad()
    # Add the log message handler to the logger
    # rotation handeld by logrotatd
    oldumask = os.umask(0o0026)
    handler = logging.handlers.WatchedFileHandler(LOGFILE_PATH,
                                                  encoding='utf8')
    # create formatter and add it to the handlers
    formatter = logging.Formatter('%(asctime)s - %(levelname)8s: %(message)s')
    handler.setFormatter(formatter)
    log.addHandler(handler)
    os.umask(oldumask)

    # Loglevels are: 1 = Debug, 2 = Info, 3 = Error

    if LOGLEVEL == 2:
        log.setLevel(logging.INFO)
    elif LOGLEVEL == 3:
        log.setLevel(logging.WARNING)
    else:
        log.setLevel(logging.DEBUG)

    # Register to have the Milter factory create instances of the class:
    Milter.factory = MacroMilter
    flags = Milter.CHGBODY + Milter.CHGHDRS + Milter.ADDHDRS
    flags += Milter.ADDRCPT
    flags += Milter.DELRCPT
    Milter.set_flags(flags)  # tell Sendmail which features we use

    # start milter processing
    print("%s MacroMilter startup - Version %s" %
          (time.strftime('%Y-%m-%d %H:%M:%S'), __version__))
    print('logging to file %s' % LOGFILE_PATH)

    log.info('Starting MarcoMilter v%s - listening on %s' %
             (__version__, SOCKET))
    log.debug('Python version: %s' % sys.version)
    sys.stdout.flush()

    # ensure desired permissions on unix socket
    os.umask(UMASK)

    # set the "last" fall back to ACCEPT if exception occur
    Milter.set_exception_policy(Milter.ACCEPT)

    # start the milter
    Milter.runmilter("MacroMilter", SOCKET, TIMEOUT)

    print("%s MacroMilter shutdown" % time.strftime('%Y-%m-%d %H:%M:%S'))
示例#56
0
 def _negotiate(self):
   self._body = None
   self._bodyreplaced = False
   self._priv = None
   self._opts = TestCtx.default_opts
   self._stage = -1
   rc = Milter.negotiate_callback(self,self._opts)
   if rc == Milter.ALL_OPTS:
     self._opts = TestCtx.default_opts
   elif rc != Milter.CONTINUE:
     self._abort()
     self._close()
   self._protocol = self._opts[1]
   return rc
示例#57
0
 def _negotiate(self):
     self._body = None
     self._bodyreplaced = False
     self._priv = None
     self._opts = TestCtx.default_opts
     self._stage = -1
     rc = Milter.negotiate_callback(self, self._opts)
     if rc == Milter.ALL_OPTS:
         self._opts = TestCtx.default_opts
     elif rc != Milter.CONTINUE:
         self._abort()
         self._close()
     self._protocol = self._opts[1]
     return rc
示例#58
0
    def __init__(self):
        """
        Create a new milter instance.

        """
        self.id = Milter.uniqueID()
        self.message = ''
        self.recipients = []
        self.dspam = None
        self.remove_headers = []
        if self.recipient_delimiter:
            self.recipient_delimiter_re = re.compile('[{}][^@]*'.format(
                re.escape(self.recipient_delimiter)))
        else:
            self.recipient_delimiter_re = None
示例#59
0
 def __init__(self):  # A new instance with each new connection.
     self.flow = None
     self.scope = None
     self.IP = None
     self.port = None
     self.fromparms = None
     self.user = None
     self.canon_from = None
     self.IPname = None  # Name from a reverse IP lookup
     self.H = None
     self.fp = None
     self.R = []  # list of recipients
     self.nexthop = [] # list of nexthop
     self.queueid = None
     self.id = Milter.uniqueID()  # Integer incremented with each call.