예제 #1
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.')
예제 #2
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.')
예제 #3
0
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
예제 #4
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')
예제 #5
0
파일: __init__.py 프로젝트: ulif/pgp-milter
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)
예제 #6
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')
예제 #7
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'))
예제 #8
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()
예제 #9
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'))
예제 #11
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()
예제 #12
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)
예제 #13
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)
예제 #14
0
def main():

	# Load the whitelist into memory
	WhiteListLoad()
	HashTableLoad()

	# create helper threads
	bt = Thread(target=background)
	perft = Thread(target=writeperformacedata)
	ha = Thread(target=writehashtofile)
	ex = Thread(target=writeExData)

	# start helper threads
	ex.start()
	perft.start()
	bt.start()
	ha.start()

	# 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)
	
	# wait for helper threads
	bt.join() # stop logging thread
	perft.join() # stop performance data thread
	ha.join() # stop hash data thread
	ex.join() # stop filename thread - obsolete - delete in next version

	# cleanup the queues
	logq.put(None)
	extension_data.put(None)
	hash_to_write.put(None)
	performace_data.put(None)

	print "%s Macro milter shutdown" % time.strftime('%d.%b.%Y %H:%M:%S')
예제 #15
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'))
예제 #16
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')
예제 #17
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')
예제 #18
0
def main():
    # TODO: log to file with rotation
    logging.basicConfig(format='%(levelname)8s: %(message)s', level=logging.DEBUG)

    logging.info('Starting MacroRaptorMilter - listening on %s' % SOCKET)
    logging.info('Press Ctrl+C to stop.')

    # 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("MacroRaptorMilter", SOCKET, TIMEOUT)
    logging.info('Stopping MacroRaptorMilter.')
예제 #19
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')
예제 #20
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)
예제 #21
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")
예제 #22
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'))
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'))
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')
예제 #25
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()
예제 #26
0
def main():
    if CLIParser() != 0:
        sys.stderr.write(
            "\nERROR:  An error has occurred and the program has been terminated!"
        )
        sys.exit(0)

    __log__.info("%s milter startup" % os.path.basename(sys.argv[0]))
    __logOutput__.clipLine()
    __logOutput__.itemLine(
        "milter version",
        str(Milter.getversion()[0]) + "." + str(Milter.getversion()[1]) + "." +
        str(Milter.getversion()[2]))
    __logOutput__.itemLine("milter listener", __listener__)
    __logOutput__.itemLine("milter port", __port__)
    __logOutput__.clipLine()
    # inet:[email protected]
    __socketName__ = "inet:" + str(__port__) + "@" + str(__listener__)
    Milter.factory = InfoMilter
    # Tell the milter, which feature we want to use.
    Milter.set_flags(__flags__)
    Milter.runmilter("pythonfilter", __socketName__, __timeout__)
    __logOutput__.clipLine()
    __log__.info("%s milter shutdown" % sys.argv[0])
예제 #27
0
if (__name__ == "__main__"):
    os.umask(0o002)

    if (len(sys.argv) != 2):
        print('Usage: %s MODE' % sys.argv[0])
        print('Where MODE is smtpd or nonsmtpd')
        exit(1)

    if (sys.argv[1] not in ['smtpd', 'nonsmtpd']):
        print('%s is not a valid mode' % sys.argv[1])
        exit(1)

    mode = sys.argv[1]
    Milter.factory = SandboxMilter
    Milter.set_flags(Milter.ADDRCPT + Milter.DELRCPT)

    config = ConfigParser.SafeConfigParser()
    config.read('/etc/sandbox_milter/sandbox_milter.cfg')

    milter_section = mode + "_milter"
    socket = config.get(milter_section, 'socket')
    name = config.get(milter_section, 'socket')

    # Initialize logging
    logger = logging.getLogger('')
    if (config.getboolean('sandbox', 'log_debug')):
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)
예제 #28
0
def main():
    if LOGHANDLER == 'file':
        endstr = '**'
        # make sure the log directory exists:
        try:
            os.makedirs(LOGFILE_DIR, 0o0027)
        except:
            pass
    else:
        endstr = ''

    # Load the whitelist into memory
    global WhiteList, Hash_Whitelist
    global r
    global rsub
    global wfp
    global bg_redis_write
    global bg_submit_wf

    WhiteList, Hash_Whitelist= wildlib.whiteListLoad(CONFIG)

    # Register to have the Milter factory create instances of your class:
    Milter.factory = WildfireMilter
    flags = Milter.ADDHDRS
    Milter.set_flags(flags)  # tell Sendmail which features we use
    print("\n*************************************************************")
    print("*********** %s startup - Version %s ***********" % ('Wildfire Milter', __version__))
    print('*************  logging to %s' % LOGHANDLER, end='')
    if LOGSTDOUT:
        print(' and to stdout ', end=endstr)
    else:
        print(' **************', end=endstr)
    print("**************\n*************************************************************\n")
    log.info('* Starting %s v%s - listening on %s' % ('Wildfire Milter', __version__, SOCKET))
    log.debug('* Python version: %s' % str(sys.version).replace('\n', ' - '))
    log.debug('* Config file: %s' % CONFIG)
    print()
    sys.stdout.flush()

    # Initialize Wildfire API
    wfp = wildlib.wildfireConnect(WILDHOST, WILDKEY)

    # Initialize main Redis Cache
    r = wildlib.redisConnect(REDISHOST, REDISPORT, REDISDB, REDISAUTH)
    # Initialize Redis Cache for Wildfire submit
    if  'threading' in  sys.modules and submitq is not None:
        # This is done in another process/thread
        rsub = None
    else:
        rsub = wildlib.redisConnect(REDISHOST, REDISPORT, DBSUB, REDISAUTH)

    # 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)

    if TASK_TYPE != 'single':
        bg_redis_write = Thread(target=redis_background_write, args=(redisq,))
        bg_submit_wf   = Thread(target=submit_wildfire_background, args=(submitq,))
        bg_redis_write.start()
        bg_submit_wf.start()

    # Notify systemd that the milter is ready to serve and to protect
    if systemd.daemon.booted():
        systemd.daemon.notify('READY=1')
        systemd.daemon.notify('STATUS=Initialization of WildFire API and Redis completed. Ready to work.')
    # start the milter #################################
    Milter.runmilter('WildfireMilter', SOCKET, TIMEOUT)
    ####################################################

    if TASK_TYPE != 'single':
        # Terminate the running threads.
        redisq.put(None)
        submitq.put(None)
        bg_redis_write.join()
        bg_submit_wf.join()

    if systemd.daemon.booted():
        systemd.daemon.notify('STOPPING=1')
        systemd.daemon.notify('STATUS=Wildfire Milter ready to stop.')

    log.info('Wildfire Milter shutdown')
    print("\n*********** %s shutdown ***********\n" % 'WildfireMilter')
예제 #29
0
                        "ENV[MILTER_WHITELISTED_RCPTS]: invalid email address: "
                        + whitelisted_rcpt)
                    sys.exit(1)
                else:
                    logging.info("ENV[MILTER_WHITELISTED_RCPTS]: " +
                                 whitelisted_rcpt)
                    g_milter_whitelisted_rcpts[whitelisted_rcpt] = {}
        set_config_parameter("RESTARTABLE_SLEEPTIME", 2)
        set_config_parameter("RESTARTABLE_TRIES", 2)
        server = Server(g_ldap_server, get_info=NONE)
        g_ldap_conn = Connection(server,
                                 g_ldap_binddn,
                                 g_ldap_bindpw,
                                 auto_bind=True,
                                 raise_exceptions=True,
                                 client_strategy='RESTARTABLE')
        logging.info("Connected to LDAP-server: " + g_ldap_server)
        timeout = 600
        # Register to have the Milter factory create instances of your class:
        Milter.factory = LdapAclMilter
        # Tell the MTA which features we use
        flags = Milter.ADDHDRS
        Milter.set_flags(flags)
        logging.info("Startup " + g_milter_name + "@socket: " +
                     g_milter_socket + " in mode: " + g_milter_mode)
        Milter.runmilter(g_milter_name, g_milter_socket, timeout, True)
        logging.info("Shutdown " + g_milter_name)
    except:
        logging.error("MAIN-EXCEPTION: " + traceback.format_exc())
        sys.exit(1)
예제 #30
0
def main():
    global spool_dir
    global ctx
    parser = \
        argparse.ArgumentParser(description='OPENPGPKEY milter application'
                                , epilog='For bugs. see [email protected]')
    parser.add_argument('--anchor', '-a', action='store', default='',
                        help='location of the unbound DNSSEC trust anchor file (default /var/lib/unbound/root.anchor')
    parser.add_argument('--port', '-p', action='store', default='8890',
                        help='port on localhost to use (default 8890)')
    parser.add_argument('--pid', '-P', action='store', default='',
                        help='pidfile to create (default no pid file is created')
    parser.add_argument('--rrtype', '-r', action='store',
                        default='65280',
                        help='RRtype allocation (default private use 65280)')
    parser.add_argument('--spool', '-s', action='store',
                        default='/var/spool/openpgpkey-milter',
                        help='spool dir for tmp files (default /var/spool/openpgpkey-milter)')
    parser.add_argument('--timeout', '-t', action='store', default=600,
                        help='timeout (default 600)')
    parser.add_argument('--version', action='store_true',
                        help='show version and exit')
    args = parser.parse_args()
    if args.version:
        print 'openpgpkey-milter version %s by Paul Wouters <*****@*****.**>' % VERSION
        print '     options: --rrtype %s --spool %s  --port %s  --timeout %s --pid <pidfile>' % (args.rrtype, args.spool, args.port, args.timeout)
        sys.exit()

    if args.anchor:
        if not os.path.isfile(args.anchor):
           sys.exit("anchor file '%s' does not exist"%args.anchor)
        ctx.add_ta_file(args.anchor)

    socketname = 'inet:%[email protected]' % args.port
    spool_dir = args.spool

    bt = Thread(target=background)
    bt.start()

    # 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)

    mypid = str(os.getpid())
    if args.pid:
       try:
            fp = open(args.pid,"w")
            fp.write(mypid)
            fp.close()
       except:
              sys.exit("Failed to write pid, aborted")

    syslog('starting daemon [%s] version %s on port %s at %s with timeout %s'
            % (mypid, VERSION, args.port, args.spool, args.timeout))
    sys.stdout.flush()
    Milter.runmilter('pythonfilter', socketname, args.timeout)
    logq.put(None)
    bt.join()
    syslog('shutting down daemon')

    if os.path.isfile(args.pid) and not os.path.islink(args.pid):
       os.unlink(args.pid)
예제 #31
0
if (__name__ == "__main__"):
    os.umask(0o002)

    if (len(sys.argv) != 2):
        print('Usage: %s MODE' % sys.argv[0])
        print('Where MODE is smtpd or nonsmtpd')
        exit(1)

    if (sys.argv[1] not in ['smtpd', 'nonsmtpd']):
        print('%s is not a valid mode' % sys.argv[1])
        exit(1)

    mode = sys.argv[1]
    Milter.factory = SandboxMilter
    Milter.set_flags(Milter.ADDRCPT + Milter.DELRCPT)

    config = ConfigParser.SafeConfigParser()
    config.read('/etc/sandbox_milter/sandbox_milter.cfg')

    milter_section = mode + "_milter"
    socket = config.get(milter_section, 'socket')
    name = config.get(milter_section, 'socket')

    # Initialize logging
    logger = logging.getLogger('')
    if (config.getboolean('sandbox', 'log_debug')):
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)
예제 #32
0
파일: srsmilter.py 프로젝트: pckizer/pysrs
        if self.conf.miltersrs and self.srsrcpt:
            newaddr = self.make_srs(self.canon_from)
            if newaddr != self.canon_from:
                self.log("srs mail from:", newaddr)
                self.chgfrom(newaddr)
        return Milter.CONTINUE


if __name__ == "__main__":
    global config
    config = Config(['pysrs.cfg', '/etc/mail/pysrs.cfg'])
    # FIXME: print helpful error if receiver missing from sendmail config
    Milter.factory = srsMilter
    if config.miltersrs:
        flags = Milter.CHGFROM + Milter.DELRCPT
    else:
        flags = Milter.DELRCPT
    Milter.set_flags(Milter.CHGFROM + Milter.DELRCPT)
    miltername = config.miltername
    socketname = config.socketname
    print("""To use this with sendmail, add the following to sendmail.cf:

O InputMailFilters=%s
X%s,        S=local:%s

See the sendmail README for libmilter.
sample srsmilter startup""" % (miltername, miltername, socketname))
    sys.stdout.flush()
    Milter.runmilter(miltername, socketname, 240)
    print("srsmilter shutdown")
예제 #33
0
    return Milter.TEMPFAIL

  def close(self):
    sys.stdout.flush()		# make log messages visible
    if self.tempname:
      os.remove(self.tempname)	# remove in case session aborted
    if self.fp:
      self.fp.close()
    return Milter.CONTINUE

  def abort(self):
    self.log("abort after %d body chars" % self.bodysize)
    return Milter.CONTINUE

if __name__ == "__main__":
  #tempfile.tempdir = "/var/log/milter"
  #socketname = "/var/log/milter/pythonsock"
  socketname = os.getenv("HOME") + "/pythonsock"
  Milter.factory = sampleMilter
  Milter.set_flags(Milter.CHGBODY + Milter.CHGHDRS + Milter.ADDHDRS)
  print("""To use this with sendmail, add the following to sendmail.cf:

O InputMailFilters=pythonfilter
Xpythonfilter,        S=local:%s

See the sendmail README for libmilter.
sample  milter startup""" % socketname)
  sys.stdout.flush()
  Milter.runmilter("pythonfilter",socketname,240)
  print("sample milter shutdown")
예제 #34
0
            try:
                self.db["cursor"].execute(
                    "SELECT DISTINCT spamuser FROM find_user_address(%s) LIMIT 1",
                    (self.to, ))
                if self.db["cursor"].rowcount > 0:
                    user = self.db["cursor"].fetchall()[0][0]
                return user
            except:
                if self.db["connection"].closed > 0:
                    try:
                        self.db["connection"] = psycopg2.connect(
                            **self.db["config"])
                        self.db["connection"].autocommit = True
                        self.db["cursor"] = self.db["connection"].cursor()
                    except:
                        break
        return user


if __name__ == "__main__":
    os.umask(0007)
    socketname = "/var/spool/postfix/run/spammilter.sock"
    timeout = 600
    SpamdMilter.db["config"] = db_config
    SpamdMilter.db["connection"] = psycopg2.connect(**SpamdMilter.db["config"])
    SpamdMilter.db["connection"].autocommit = True
    SpamdMilter.db["cursor"] = SpamdMilter.db["connection"].cursor()
    Milter.factory = SpamdMilter
    Milter.set_flags(Milter.ADDHDRS)
    Milter.runmilter("SpamdMilter", socketname, timeout)
예제 #35
0
파일: sample.py 프로젝트: yuhei159/pymilter
    def close(self):
        sys.stdout.flush()  # make log messages visible
        if self.tempname:
            os.remove(self.tempname)  # remove in case session aborted
        if self.fp:
            self.fp.close()
        return Milter.CONTINUE

    def abort(self):
        self.log("abort after %d body chars" % self.bodysize)
        return Milter.CONTINUE


if __name__ == "__main__":
    #tempfile.tempdir = "/var/log/milter"
    #socketname = "/var/log/milter/pythonsock"
    socketname = os.getenv("HOME") + "/pythonsock"
    Milter.factory = sampleMilter
    Milter.set_flags(Milter.CHGBODY + Milter.CHGHDRS + Milter.ADDHDRS)
    print("""To use this with sendmail, add the following to sendmail.cf:

O InputMailFilters=pythonfilter
Xpythonfilter,        S=local:%s

See the sendmail README for libmilter.
sample  milter startup""" % socketname)
    sys.stdout.flush()
    Milter.runmilter("pythonfilter", socketname, 240)
    print("sample milter shutdown")
예제 #36
0
    def lookup_user(self):
        user = "******"
        for _ in range(2):
            try:
                self.db["cursor"].execute("SELECT DISTINCT spamuser FROM find_user_address(%s) LIMIT 1", (self.to,))
                if self.db["cursor"].rowcount > 0:
                    user = self.db["cursor"].fetchall()[0][0]
                return user
            except:
                if self.db["connection"].closed > 0:
                    try:
                        self.db["connection"] = psycopg2.connect(**self.db["config"])
                        self.db["connection"].autocommit = True
                        self.db["cursor"] = self.db["connection"].cursor()
                    except:
                        break
        return user


if __name__ == "__main__":
    os.umask(0007)
    socketname = "/var/spool/postfix/run/spammilter.sock"
    timeout = 600
    SpamdMilter.db["config"] = db_config
    SpamdMilter.db["connection"] = psycopg2.connect(**SpamdMilter.db["config"])
    SpamdMilter.db["connection"].autocommit = True
    SpamdMilter.db["cursor"] = SpamdMilter.db["connection"].cursor()
    Milter.factory = SpamdMilter
    Milter.set_flags(Milter.ADDHDRS)
    Milter.runmilter("SpamdMilter",socketname,timeout)