syslog.syslog

Here are the examples of the python api syslog.syslog taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

106 Examples 7

Example 1

View license
        def run(self):
                syslog.syslog ('fail2ban-zmq-tools Monitor starting.')
                signal.signal(signal.SIGTERM, self.__sigTERMhandler)
                signal.signal(signal.SIGINT, self.__sigTERMhandler)
                self.monitor = Monitor(monitorconfig=monitorconfig)
                syslog.syslog ('fail2ban-zmq-tools Monitor running. Main process waiting for termination signal. Threads working.')
                self.monitor.start()
                signal.pause()
                syslog.syslog ('fail2ban-zmq-tools Monitor exiting.')

Example 2

Project: karaka
Source File: common.py
View license
def _log(level, mesg):
    try:
        if "\n" in mesg: mesgs = mesg.split("\n")
        else: mesgs = [mesg]

        pfx = ""
        for mesg in mesgs:
            while len(mesg) > 254:
                syslog.syslog(level, "%s%s" % (pfx, mesg[:254]))
                mesg = "%s" % mesg[254:]
                pfx = "||"
            syslog.syslog(level, "%s%s" % (pfx, mesg))
            pfx = "|"                      
    except UnicodeDecodeError, ude:
        syslog.syslog("XXX logging failed")
        syslog.syslog(fmt_stacktrace(ude))
    except Exception, ude:
        syslog.syslog("XXX logging failed")
        syslog.syslog(fmt_stacktrace(ude))

Example 3

View license
	def run(self):
		syslog.syslog("fail2ban-zmq-tools Subscriber starting")
		signal.signal(signal.SIGTERM,self.__sigTERMhandler)
		signal.signal(signal.SIGINT,self.__sigTERMhandler)
		self.subscriber = Subscriber(subscriberconfig=subscriberconfig)
		self.subscriber.start()
		syslog.syslog("fail2ban-zmq-tools Subscriber running. Main process waiting for termination signal. Threads working.")
		signal.pause()
		syslog.syslog("fail2ban-zmq-tools Subscriber exiting.")

Example 4

Project: nyx
Source File: palo_alto.py
View license
def add(indicator, settings, plist):
    """ adds indicator in the medium-confidence watch list in Palo Alto """
    if 'type' in indicator.keys() and indicator['type']=='Address - ipv4-addr':
        # adding an ip
        res=add_ip_to_panorama(indicator['ip'],get_sources(indicator),settings,settings[plist])
        bad_indicator=indicator['ip']
    elif 'type' in indicator.keys() and indicator['type']=='A':
        # adding the domain
        res=add_site_to_panorama(indicator['domain'],settings,settings[plist])
        bad_indicator=indicator['domain']
    else:
        syslog.syslog('nyx->PAN: I do not know how to handle the following type of observable: %s' % indicator['type'])
    
    if res and res.status_code == 200 and 'code="20"' in res.text:
        syslog.syslog(syslog.LOG_INFO,'nyx->PAN: successfully added %s to %s '% (bad_indicator, settings[plist]))
        return True
    else:
        syslog.syslog(syslog.LOG_ERR,'nyx->PAN: Palo Alto potential issues: %s' % res.text)
        return False

Example 5

View license
	def run(self):
		syslog.syslog("fail2ban-zmq-tools Publisher starting")
		signal.signal(signal.SIGTERM,self.__sigTERMhandler)
		signal.signal(signal.SIGINT,self.__sigTERMhandler)
		self.publisher = Publisher(publisherconfig=publisherconfig)
		self.publisher.start()
		syslog.syslog("fail2ban-zmq-tools Publisher running. Main process waiting for termination signal. Threads working.")
		signal.pause()
		syslog.syslog("fail2ban-zmq-tools Publisher exiting.")

Example 6

Project: karaka
Source File: common.py
View license
def _log(level, mesg):
    try:
        if "\n" in mesg: mesgs = mesg.split("\n")
        else: mesgs = [mesg]

        pfx = ""
        for mesg in mesgs:
            while len(mesg) > 254:
                syslog.syslog(level, "%s%s" % (pfx, mesg[:254]))
                mesg = "%s" % mesg[254:]
                pfx = "||"
            syslog.syslog(level, "%s%s" % (pfx, mesg))
            pfx = "|"                      
    except UnicodeDecodeError, ude:
        syslog.syslog("XXX logging failed")
        syslog.syslog(fmt_stacktrace(ude))
    except Exception, ude:
        syslog.syslog("XXX logging failed")
        syslog.syslog(fmt_stacktrace(ude))

Example 7

Project: DIRAC
Source File: SecurityLogClient.py
View license
  def addMessage( self, success, sourceIP, sourcePort, sourceIdentity,
                  destinationIP, destinationPort, destinationService,
                  action, timestamp = False ):
    if not timestamp:
      timestamp = Time.dateTime()
    msg = ( timestamp, success, sourceIP, sourcePort, sourceIdentity,
            destinationIP, destinationPort, destinationService, action )
    if gConfig.getValue( "/Registry/EnableSysLog", False ):
      strMsg = "Time=%s Accept=%s Source=%s:%s SourceID=%s Destination=%s:%s Service=%s Action=%s"
      syslog.syslog( strMsg % msg )
    while len( self.__messagesList ) > self.__maxMessagesWaiting:
      self.__messagesList.pop( 0 )
    if not self.__securityLogStore:
      self.__messagesList.append( msg )
    else:
      self.__securityLogStore[0].logAction( msg )

Example 8

Project: knockknock
Source File: PortOpener.py
View license
    def open(self, sourceIP, port):
        try:
            self.stream.write(sourceIP + "\n")
            self.stream.write(str(port) + "\n")
            self.stream.flush()
        except:
            syslog.syslog("knockknock:  Error, PortOpener process has died.  Terminating.")
            os._exit(4)

Example 9

Project: knockknock
Source File: KnockWatcher.py
View license
    def tailAndProcess(self):
        for line in self.logFile.tail():
            try:
                logEntry = LogEntry(line)
                profile  = self.profiles.getProfileForPort(logEntry.getDestinationPort())

                if (profile != None):
                    try:
                        ciphertext = logEntry.getEncryptedData()
                        port       = profile.decrypt(ciphertext, self.config.getWindow())
                        sourceIP   = logEntry.getSourceIP()
                    
                        self.portOpener.open(sourceIP, port)
                        syslog.syslog("Received authenticated port-knock for port " + str(port) + " from " + sourceIP)
                    except MacFailedException:
                        pass
            except:
#                print "Unexpected error:", sys.exc_info()
                syslog.syslog("knocknock skipping unrecognized line.")

Example 10

View license
    def send_email(self, title, message):
        if self.use_smtp:
            syslog.syslog("Sending email message")
            config = self.config['alerts']['smtp']
            server = smtplib.SMTP(config["smtphost"], config["smtpport"])
            if (config["smtp_tls"] == "True") :
                server.starttls()
            server.login(config["username"], config["password"])
            server.sendmail(config["username"], config["to_email"], message)
            server.close()

Example 11

Project: karaka
Source File: api.py
View license
def _log(level, mesg):
    if "\n" in mesg: mesgs = mesg.split("\n")
    else: mesgs = [mesg]

    pfx = ""
    for mesg in mesgs:
        while len(mesg) > 254:
            syslog.syslog(level, "%s%s" % (pfx, mesg[:254].encode("utf-8"),))
            mesg = "%s" % mesg[254:]
            pfx = "||"
        syslog.syslog(level, "%s%s" % (pfx, mesg.encode("utf-8")))
        pfx = "|"                      

Example 12

Project: py3status
Source File: core.py
View license
    def log(self, msg, level='info'):
        """
        log this information to syslog or user provided logfile.
        """
        if not self.config['log_file']:
            # If level was given as a str then convert to actual level
            level = LOG_LEVELS.get(level, level)
            syslog(level, u'{}'.format(msg))
        else:
            # Binary mode so fs encoding setting is not an issue
            with open(self.config['log_file'], 'ab') as f:
                log_time = time.strftime("%Y-%m-%d %H:%M:%S")
                out = u'{} {} {}\n'.format(log_time, level.upper(), msg)
                try:
                    # Encode unicode strings to bytes
                    f.write(out.encode('utf-8'))
                except (AttributeError, UnicodeDecodeError):
                    # Write any byte strings straight to log
                    f.write(out)

Example 13

View license
    def update_openhab(self, item, state):
        syslog.syslog("Updating openhab")
        config = self.config['openhab']
        conn = httplib.HTTPConnection("%s:%s" % (config['server'], config['port']))
        conn.request("PUT", "/rest/items/%s/state" % item, state)
        conn.getresponse()

Example 14

Project: denyhosts
Source File: report.py
View license
    def add_section(self, message, iterable):
        self.report += "%s:\n\n" % message
        for i in iterable:
            # checks the item type (list or tuple)
            if isinstance(i, list) or isinstance(i, tuple):
                extra = ": %d\n" % i[1]
                i = i[0]
            else:
                extra = ""
            if self.hostname_lookup:
                hostname = self.get_hostname(i)
                debug("get_host: %s", hostname)
            else: hostname = i

            self.report += "%s%s\n" % (hostname, extra)

            if self.use_syslog:
                syslog.syslog("%s - %s%s" %(message, hostname, extra))
        self.report += "\n" + "-" * 70 + "\n"

Example 15

Project: acoustid-server
Source File: utils.py
View license
    def emit(self, record):
        try:
            msg = self.format(record)
            if isinstance(msg, unicode):
                msg = msg.encode('utf-8')
            priority = self.priority_map[record.levelname]
            for m in msg.splitlines():
                syslog.syslog(self.facility | priority, m)
        except StandardError:
            self.handleError(record)

Example 16

Project: tumgreyspf
Source File: tumgreyspfsupp.py
View license
   def __call__(self, etype, evalue, etb):
      import traceback, string
      tb = traceback.format_exception(*(etype, evalue, etb))
      tb = map(string.rstrip, tb)
      tb = string.join(tb, '\n')
      for line in string.split(tb, '\n'):
         if self.useSyslog:
            syslog.syslog(line)
         if self.useStderr:
            sys.stderr.write(line + '\n')

Example 17

Project: karaka
Source File: api.py
View license
def _log(level, mesg):
    if "\n" in mesg: mesgs = mesg.split("\n")
    else: mesgs = [mesg]

    pfx = ""
    for mesg in mesgs:
        while len(mesg) > 254:
            syslog.syslog(level, "%s%s" % (pfx, mesg[:254].encode("utf-8"),))
            mesg = "%s" % mesg[254:]
            pfx = "||"
        syslog.syslog(level, "%s%s" % (pfx, mesg.encode("utf-8")))
        pfx = "|"                      

Example 18

View license
    def toggle(self, doorId):
        for d in self.doors:
            if d.id == doorId:
                syslog.syslog('%s: toggled' % d.name)
                d.toggle_relay()
                return

Example 19

View license
    def send_email(self, title, message):
        if self.use_smtp:
            syslog.syslog("Sending email message")
            config = self.config['alerts']['smtp']
            server = smtplib.SMTP(config["smtphost"], config["smtpport"])
            if (config["smtp_tls"] == "True") :
                server.starttls()
            server.login(config["username"], config["password"])
            server.sendmail(config["username"], config["to_email"], message)
            server.close()

Example 20

View license
    def send_pushbullet(self, door, title, message):
        syslog.syslog("Sending pushbutton message")
        config = self.config['alerts']['pushbullet']

        if door.pb_iden != None:
            conn = httplib.HTTPSConnection("api.pushbullet.com:443")
            conn.request("DELETE", '/v2/pushes/' + door.pb_iden, "",
                         {'Authorization': 'Bearer ' + config['access_token'], 'Content-Type': 'application/json'})
            conn.getresponse()
            door.pb_iden = None
                        
        conn = httplib.HTTPSConnection("api.pushbullet.com:443")
        conn.request("POST", "/v2/pushes",
             json.dumps({
                 "type": "note",
                 "title": title,
                 "body": message,
             }), {'Authorization': 'Bearer ' + config['access_token'], 'Content-Type': 'application/json'})
        door.pb_iden = json.loads(conn.getresponse().read())['iden']

Example 21

View license
    def update_openhab(self, item, state):
        syslog.syslog("Updating openhab")
        config = self.config['openhab']
        conn = httplib.HTTPConnection("%s:%s" % (config['server'], config['port']))
        conn.request("PUT", "/rest/items/%s/state" % item, state)
        conn.getresponse()

Example 22

Project: autotest
Source File: crash_handler.py
View license
def write_cores(core_data, dir_list):
    """
    Write core files to all directories, optionally providing reports.

    :param core_data: Contents of the core file.
    :param dir_list: List of directories the cores have to be written.
    :param report: Whether reports are to be generated for those core files.
    """
    syslog.syslog("Writing core files to %s" % dir_list)
    for result_dir in dir_list:
        if not os.path.isdir(result_dir):
            os.makedirs(result_dir)
        core_path = os.path.join(result_dir, 'core')
        core_path = write_to_file(core_path, core_file, report=True)

Example 23

Project: tumgreyspf
Source File: tumgreyspfsupp.py
View license
def processConfigFile(filename = None, config = None, useSyslog = 1,
		useStderr = 0):
	'''Load the specified config file, exit and log errors if it fails,
	otherwise return a config dictionary.'''

	import tumgreyspfsupp
	if config == None: config = tumgreyspfsupp.defaultConfigData
	if filename == None: filename = tumgreyspfsupp.defaultConfigFilename

	try:
		loadConfigFile(filename, config)
	except Exception, e:
		if useSyslog:
			syslog.syslog(e.args[0])
		if useStderr:
			sys.stderr.write('%s\n' % e.args[0])
		sys.exit(1)

	return(config)

Example 24

Project: tumgreyspf
Source File: tumgreyspfsupp.py
View license
def processConfigFile(filename = None, config = None, useSyslog = 1,
		useStderr = 0):
	'''Load the specified config file, exit and log errors if it fails,
	otherwise return a config dictionary.'''

	import tumgreyspfsupp
	if config == None: config = tumgreyspfsupp.defaultConfigData
	if filename == None: filename = tumgreyspfsupp.defaultConfigFilename

	try:
		loadConfigFile(filename, config)
	except Exception, e:
		if useSyslog:
			syslog.syslog(e.args[0])
		if useStderr:
			sys.stderr.write('%s\n' % e.args[0])
		sys.exit(1)

	return(config)

Example 25

Project: libstoragemgmt
Source File: _common.py
View license
def post_msg(level, prg, msg):
    """
    If a message includes new lines we will create multiple syslog
    entries so that the message is readable.  Otherwise it isn't very readable.
    Hopefully we won't be logging much :-)
    """
    for l in msg.split('\n'):
        if len(l):
            syslog.syslog(level, prg + ": " + l)

Example 26

Project: fail2ban-zmq-tools
Source File: monitor.py
View license
	def notifier(self):
		sys.stdout.flush()
		flag='ok'
		while flag !='stop':
			try:
				flag,jail,action,attacker = self.dq.get()
			except:
				pass
			sys.stdout.flush()
			if flag == 'stop':
#				self.zmqRequester(flag,"BYEBYE","BYEBYE","BYEBYE")
				break
#			syslog.syslog('notifier got item: ',flag,jail,action,attacker)
			self.zmqRequester(flag,jail,action,attacker)
			self.dq.task_done()
		syslog.syslog("Notifier exiting loop")
		sys.stdout.flush()

Example 27

Project: minos
Source File: loggers.py
View license
    def emit(self, record):
        try:
            params = record.asdict()
            message = params['message']
            for line in message.rstrip('\n').split('\n'):
                params['message'] = line
                msg = self.fmt % params
                try:
                    syslog.syslog(msg)
                except UnicodeError:
                    syslog.syslog(msg.encode("UTF-8"))
        except:
            self.handleError(record)

Example 28

Project: python-pyhsm
Source File: validation_server.py
View license
def my_log_message(my_args, prio, msg):
    """
    Log msg to syslog, and possibly also output to stderr.
    """
    syslog.syslog(prio, msg)
    if my_args.debug or my_args.verbose or prio == syslog.LOG_ERR:
        sys.stderr.write("%s\n" % (msg))

Example 29

View license
    def toggle(self, doorId):
        for d in self.doors:
            if d.id == doorId:
                syslog.syslog('%s: toggled' % d.name)
                d.toggle_relay()
                return

Example 30

Project: hddfancontrol
Source File: __init__.py
View license
  def emit(self, record):
    """ See logging.Handler.emit. """
    msg = self.format(record)
    h = logging.handlers.SysLogHandler
    level = h.priority_names[h.priority_map[record.levelname]]
    syslog.syslog(level, msg)

Example 31

Project: knockknock
Source File: PortOpener.py
View license
    def waitForRequests(self):
        while True:
            sourceIP    = self.stream.readline().rstrip("\n")
            port        = self.stream.readline().rstrip("\n")

            if sourceIP == "" or port == "":
                syslog.syslog("knockknock.PortOpener: Parent process is closed.  Terminating.")
                os._exit(4)                    

            description = 'INPUT -m limit --limit 1/minute --limit-burst 1 -m state --state NEW -p tcp -s ' + sourceIP + ' --dport ' + str(port) + ' -j ACCEPT'
            command     = 'iptables -I ' + description
            command     = command.split()            

            subprocess.call(command, shell=False)

            RuleTimer(self.openDuration, description).start()

Example 32

Project: fail2ban-zmq-tools
Source File: publisher.py
View license
	def __init__(self,publisherconfig=None,num_worker_threads=1):
		threading.Thread.__init__(self)
		self._stopevent=threading.Event()
		self.publisherconfig=publisherconfig
		self.zmqBroadcasterBindUrl=self.publisherconfig['broadcasterbindurl']
		self.zmqReplyBindUrl=self.publisherconfig['replybindurl']
		self.authenticate=self.publisherconfig['auth']
		self.authtoken=self.publisherconfig['authtoken']

		syslog.syslog("fail2ban-zmq-tools Publisher: initialization complete")

Example 33

View license
    def send_pushbullet(self, door, title, message):
        syslog.syslog("Sending pushbutton message")
        config = self.config['alerts']['pushbullet']

        if door.pb_iden != None:
            conn = httplib.HTTPSConnection("api.pushbullet.com:443")
            conn.request("DELETE", '/v2/pushes/' + door.pb_iden, "",
                         {'Authorization': 'Bearer ' + config['access_token'], 'Content-Type': 'application/json'})
            conn.getresponse()
            door.pb_iden = None
                        
        conn = httplib.HTTPSConnection("api.pushbullet.com:443")
        conn.request("POST", "/v2/pushes",
             json.dumps({
                 "type": "note",
                 "title": title,
                 "body": message,
             }), {'Authorization': 'Bearer ' + config['access_token'], 'Content-Type': 'application/json'})
        door.pb_iden = json.loads(conn.getresponse().read())['iden']

Example 34

Project: tumgreyspf
Source File: tumgreyspfsupp.py
View license
   def __call__(self, etype, evalue, etb):
      import traceback, string
      tb = traceback.format_exception(*(etype, evalue, etb))
      tb = map(string.rstrip, tb)
      tb = string.join(tb, '\n')
      for line in string.split(tb, '\n'):
         if self.useSyslog:
            syslog.syslog(line)
         if self.useStderr:
            sys.stderr.write(line + '\n')

Example 35

Project: libstoragemgmt
Source File: _common.py
View license
def post_msg(level, prg, msg):
    """
    If a message includes new lines we will create multiple syslog
    entries so that the message is readable.  Otherwise it isn't very readable.
    Hopefully we won't be logging much :-)
    """
    for l in msg.split('\n'):
        if len(l):
            syslog.syslog(level, prg + ": " + l)

Example 36

Project: python-pyhsm
Source File: yubikey_ksm.py
View license
def my_log_message(verbose, prio, msg):
    """
    Log to syslog, and possibly also to stderr.
    """
    syslog.syslog(prio, msg)
    if verbose or prio == syslog.LOG_ERR:
        sys.stderr.write("%s\n" % (msg))

Example 37

Project: a5
Source File: control.py
View license
def runInVM(m,job,VMs,adbport,vmlock,adbl,results, fcnt):
	name = multiprocessing.current_process().name

 	formatter = logging.Formatter(fmt=LOGFORMAT,datefmt=LOGDATEFORMAT)
    	pathForFile = MALWAREJOBSBASE + "/" + job['jobuuid'] + "/" + job['sha256'] + "-run.log"
	print "HH%sHH" % pathForFile
    	handler = logging.FileHandler(pathForFile, mode='w')
    	handler.setFormatter(formatter)

    	vlogger = logger.getChild("worker" + name + ".vm")
    	vlogger.setLevel(logging.DEBUG)
    	vlogger.addHandler(handler)

	vlogger.info("logging started at " + pathForFile)


	rval = True
	if VMs[m].state in ["Reserved"] :
		with vmlock:
			VMlocal = VMs[m];
			VMlocal.state = "Starting"
			VMs[m] = VMlocal;
		#emulator doens't observe system hosts:  (must start emulator with -partition-size 128 (for example) to give room to write)
		#adb pull /etc/hosts
		#edit to 10.0.2.2 (your local machine)
		#adb remount
		#adb push hosts /etc/hosts
		t1 = time.time()
		

		#emulator -avd NAME -partition-size 128 -ports 5,2322 -no-window -tcpdump FILE -dns-server SERVER -http-proxy PROXY
		#TODO instead of wipe-data, would be best to re-create the VM
		EMUSTART = "%s/emulator -avd %s -partition-size %s -port %s -no-window -tcpdump %s -wipe-data"
		#./adb logcat
		#./adb install /storage/malware/RU.apk
		#./adb shell am broadcast -a android.intent.action.BOOT_COMPLETED

		#start (with specified ports)
		#emulator -ports X,Y @avd_X

		#wait for emulator to be fully started
		#./adb -s emulator-5584 wait-for-device
		EMUWAIT = "%s/adb -s %s wait-for-device"

		EMULOGCAT = "%s/adb -s %s logcat"

		#command
		#adb -s emualtor-X shell cmd

		EMUINSTALL = "%s/adb -s %s install %s"

		#<INTENT> specifications include these flags:
		#       [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]
		#       [-c <CATEGORY> [-c <CATEGORY>] ...]
		#       [-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]
		#       [--esn <EXTRA_KEY> ...]
		#       [--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]
		#       [-e|--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]
		#adb shell am broadcast -a android.intent.action.BOOT_COMPLETED -c android.intent.category.HOME -n net.fstab.checkit_android/.StartupReceiver
		#am broadcast -a android.intent.action.BOOT_COMPLETED
		EMUINTENT = "%s/adb -s %s shell am broadcast -a %s"
	
		#adb shell am start -n com.package.name/com.package.name.ActivityName
		#am start -a android.intent.action.MAIN -n com.iftitah.android.contact/com.iftitah.android.contact.Contact
		#am start -a <ACTION> -n <PACKAGE>/<PACKAGE><ACTIVITYCLASS>
		EMULAUNCH = "%s/adb -s %s shell am start -a %s -n %s/%s"

		#kill
		#could do adb shell stop
		#but why really?  just going to reset for next run anyway
		# (though a stop would preserve state)
		#adb -s emulator-X emu kill
		EMUKILL = "%s/adb -s %s emu kill"

		#monkey
		#$ adb shell monkey -v -p your.package.name 100 --ignore-security-exceptions -s SEED
		EMUMONKEY = "%s/adb -s %s shell monkey -v -p %s 100 --ignore-security-exceptions -s %s --throttle 250"

		#update database with start values
		permissions_filename = job['sha256'] + ".xml"
		image_used = VMs[m].name
		start_time = time.strftime("%Y-%m-%d-%H:%M:%S", time.gmtime())
		msdb.updateStartRun(job['jobuuid'],image_used,start_time,permissions_filename,MSVERSION)

		vlogger.info( name + ":" + "...starting VM " + VMs[m].name)
		#start it
		cmd = EMUSTART % ( SDKPATH, VMs[m].name, PSIZE, str(adbport), MALWAREJOBSBASE + "/" + job['jobuuid'] + "/" + job['sha256']+ "-orig.pcap")
		vlogger.info( name + ":" + cmd)
		pEmu = None
		try:
			args = shlex.split(cmd)
			pEmu = subprocess.Popen(args)
		except:
			vlogger.info( name + ":" + "emulator start error", sys.exc_info()[0])
			sys.exit(1)
		#check for start error conditions:
		#emulator: WARNING: ignoring locked SD Card image at /path/to/avd/ms-sdk003-003/sdcard.img
		#it seems too many emulator instances are running on this machine. Aborting


		#wait for it to start
		cmd = EMUWAIT % ( ADBPATH, "emulator-" + str(adbport))
		vlogger.info( name + ":" + cmd)
		try:
			ret = subprocess.check_call([cmd], shell=True)
			vlogger.info( name + ":" + "emulator wait returned: %d" % ret )
		except:
			vlogger.error( name + ":" + "emulator wait error: %s" % cmd )
			sys.exit(1)
		vlogger.info( name + ":" + "emulator-" + str(adbport) + " started")
		time.sleep(VM_POLL_REST * 3)
		with vmlock:
			VMlocal = VMs[m];
			VMlocal.state = "Running"
			VMs[m] = VMlocal;

		#start logcat
		#start it
		cmd = EMULOGCAT % ( SDKPATH, "emulator-" + str(adbport))
		vlogger.info( name + ":" + cmd)
		pLogCat = None
		fLogCat = None
		try:
			args = shlex.split(cmd)
			vlogger.info( args)
			fLogCat = open(MALWAREJOBSBASE + "/" + job['jobuuid'] + "/" + job['sha256'] + ".logcat","w")
			fNull = open("/dev/null")
#TODO			pLogCat = subprocess.Popen(args, stdin=fNull, stderr=fNull, stdout=fLogCat)
		except:
			vlogger.error( name + ": " + cmd )
			vlogger.error( formatExceptionInfo())
			vlogger.error( name + ":" + "emulator logcat error", sys.exc_info()[0])
			sys.exit(1)

		#install malicious app
		cmd = EMUINSTALL % ( ADBPATH, "emulator-" + str(adbport), "'" + job['fullpath'] + "'")
		vlogger.info( name + ":" + cmd)
	
		try:
			ret = subprocess.check_output([cmd], shell=True)
			vlogger.info( name + ":" + "emulator install returned: %s" % ret )
			install_attempts = ADBTRIES
			while "Success" not in ret and install_attempts > 0:
				kick_adb_maybe(adbl, fcnt)
				vlogger.info( name + ":" + "install failed emulator install returned: %s" % ret )
				time.sleep(VM_POLL_REST)

				#TODO FIXME, track down why this sometimes stalls forever, seem on SDKs 11 and 14...
				ret = subprocess.check_output([cmd], shell=True)
				install_attempts -= 1
				if install_attempts <= 0:
					syslog.syslog(VMs[m].name + ":" + "install failed emulator install returned: %s" % ret )
					vlogger.error(VMs[m].name + ":" + "install failed emulator install returned: %s" % ret )
				

		except:
			vlogger.error( name + ":" + "emulator install fatal error: %s" % cmd )
			vlogger.error( formatExceptionInfo())
			sys.exit(1)

		#possible errors:
		#Error: Could not access the Package Manager.  Is the system running?

		time.sleep(VM_POLL_REST * 3)

		#stimulate
		doc = etree.parse( MALWAREJOBSBASE + "/" + job['jobuuid'] + "/" + job['sha256'] + ".xml")
		package = doc.find('package')

		
		li = libIntent.libIntent("localhost",adbport)
	
		#for each rint
		for rint in doc.findall('rint'):
			vlogger.info( name + " handling " + str(rint.text))
			li.handleRIntent(str(rint.text))

		#for each permission (actions and rints _should_ catch all these....)
		for perm in doc.findall('permission'):
			vlogger.info( name + " handling " + str(perm.text))
			li.handlePermission(str(perm.text))

		#for each action
		for action in doc.findall('action'):
			vlogger.info( name + " handling " + str(action.text))
			li.handleAction(str(action.text))
			#BROADCASTS are done this way
			#cmd = EMUINTENT % ( ADBPATH, "emulator-" + str(adbport), "android.intent.action.BOOT_COMPLETED")
			cmd = EMUINTENT % ( ADBPATH, "emulator-" + str(adbport), str(action.text))
			vlogger.info( name + ":" + cmd)
			try:
				#TODO check for "Broadcast completed" in output, repeat if necessary
				ret = subprocess.check_call([cmd], shell=True)
			except:
				syslog.syslog("app %s error sending intent %s" % (job['sha256'],str(action.text)))
				vlogger.error( name + ":" + "emulator intent error: %s" % cmd )
				vlogger.error( name + ":" + "emulator intent error: %d" % ret )
				#TODO exit is a little too harsh here, but should probably requeue somehow
				#sys.exit(1)
				#sys.exit(1)

		#somethings just don't have nice rint or actions
		li.sendCall()
		time.sleep(VM_POLL_REST)
		li.endAllCalls()

		#open app


		# TODO this should not be a for/for loop, the actions shoudl be paired with activities
		for activity in doc.findall('activity'):
			for action in doc.findall('action'):
				vlogger.info( name + ": " + "################## launching activity " + str(activity.text))
				cmd = EMULAUNCH % ( ADBPATH, "emulator-" + str(adbport), str(action.text), str(package.text), str(activity.text))
				vlogger.info( name + ":" + cmd)
				try:
					ret = subprocess.check_call([cmd], shell=True)
				except:
					vlogger.error( name + ":" + "emulator launch error: %s" % cmd )
					vlogger.error( name + ":" + "emulator launch error: %d" % ret )
					#TODO exit is a little too harsh here, but should probably requeue somehow
					#sys.exit(1)

		time.sleep(VM_POLL_REST * 5)

		#monkey around
		cmd = EMUMONKEY % ( ADBPATH, "emulator-" + str(adbport), str(package.text), random.randint(1,100))
		vlogger.info( name + ":" + cmd)
	
		try:
			ret = subprocess.check_output([cmd], shell=True)
			vlogger.info( name + ":" + "emulator monkey returned: %s" % ret )
#			monkey_attempts = ADBTRIES
#			while "Success" not in ret and monkey_attempts > 0:
#				kick_adb_maybe(adbl, fcnt)
#				vlogger.info( name + ":" + "monkey failed emulator monkey returned: %s" % ret )
#				time.sleep(VM_POLL_REST)
#
#				ret = subprocess.check_output([cmd], shell=True)
#				monkey_attempts -= 1
#				if monkey_attempts <= 0:
#					syslog.syslog(VMs[m].name + ":" + "monkey failed emulator monkey returned: %s" % ret )
				

		except:
			vlogger.error( name + ":" + "emulator monkey fatal error: %s" % cmd )
			syslog.syslog(VMs[m].name + ":" + "monkey failed emulator monkey error: %s" % cmd )
			vlogger.error( formatExceptionInfo())
			sys.exit(1)

		#kill
		cmd = EMUKILL % ( ADBPATH, "emulator-" + str(adbport))
		vlogger.info( name + ":" + cmd)
		try:
			ret = subprocess.check_call([cmd], shell=True)
		except:
			vlogger.error( name + ":" + "emulator kill error")
			sys.exit(1)

		#cleanup
		if pEmu.poll() is not None:
			vlogger.info( name + ": " + "poll is " + str(pEmu.poll()))
			try:	
				pEmu.terminate()
			except:
				vlogger.error( name + ": " + "pEmu term failed")
#TODO		if pLogCat.poll() is not None:
#TODO			pLogCat.terminate()
		fLogCat.flush()
		fLogCat.close()
		fNull.close()
		
		time.sleep(VM_POLL_REST)
		vlogger.info( name + ":" + "...stopping VM " + VMs[m].name)
		with vmlock:	
			VMlocal = VMs[m];
			VMlocal.state = "Off"
			VMs[m] = VMlocal;
	
		t2 = time.time()	

		complete_time = time.strftime("%Y-%m-%d-%H:%M:%S", time.gmtime())
		results_file = job['sha256'] + ".pcap"
		msdb.updateFinishRun(job['jobuuid'],complete_time,results_file)

		#post process pcap, pretty crude for now, adb uses it's port and port+1; so two prunes
		#...and it seems that adb uses 5555 regardless of which even port is specified
		originalpcap = MALWAREJOBSBASE + "/" + job['jobuuid'] + "/" + job['sha256'] + "-orig.pcap"
		tmppcap = MALWAREJOBSBASE + "/" + job['jobuuid'] + "/" + job['sha256'] + "-temp.pcap"
		finalpcap = MALWAREJOBSBASE + "/" + job['jobuuid'] + "/" + job['sha256'] + ".pcap"

		#cmd = "prune_pcap.sh %s %s %s" % (os.path.dirname(job['fullpath']) + "/" + job['sha256']+ "-orig.pcap",os.path.dirname(job['fullpath']) + "/" + job['sha256']+ ".pcap", str(adbport))
		cmd = "prune_pcap.sh %s %s %s" % (originalpcap,tmppcap, str(adbport))
		vlogger.info( name + ":" + cmd)
		try:
			ret = subprocess.check_call([cmd], shell=True)
		except:
			vlogger.error( name + ":" + "pcap prune error")
			sys.exit(1)

		#cmd = "prune_pcap.sh %s %s %s" % (os.path.dirname(job['fullpath']) + "/" + job['sha256']+ "-orig.pcap",os.path.dirname(job['fullpath']) + "/" + job['sha256']+ ".pcap", str(int(adbport)+1))
		cmd = "prune_pcap.sh %s %s %s" % (tmppcap,finalpcap, str(int(adbport)+1))
		vlogger.info( name + ":" + cmd)
		try:
			ret = subprocess.check_call([cmd], shell=True)
		except:
			vlogger.error( name + ":" + "pcap prune error")
			sys.exit(1)

		#cmd = "prune_pcap.sh %s %s %s" % (os.path.dirname(job['fullpath']) + "/" + job['sha256']+ "-orig.pcap",os.path.dirname(job['fullpath']) + "/" + job['sha256']+ ".pcap", str(5555))
#		cmd = "prune_pcap.sh %s %s %s" % (originalpcap,finalpcap, str(adbport))
#		vlogger.info( name + ":" + cmd)
#		try:
#			ret = subprocess.check_call([cmd], shell=True)
#		except:
#			vlogger.error( name + ":" + "pcap prune error")
#			sys.exit(1)

		#TODO unique ip addresses
		#tshark -r <input.pcap> -T fields -e ip.dst ip.src | sort | uniq


		vlogger.info( name + ":" + "sample took %s seconds process" % str(t2 - t1))
		results.put(t2-t1)

	elif VMs[m].state in ["Off"]:
		vlogger.info( name + ":" + VMs[m].name + "run error: found in state OFF!")
		rval = False
	elif VMs[m].state in ["Ready"]:
		vlogger.info( name + ":" + VMs[m].name + "run error: is running and not available for new malware")
		rval = False
		#if m.name in assignments:
		#	if assignments[m.name]['timeout'] <= time.time():
		#		#do anything you want to wrap up
		#		job_post_process(m)
		#		job_cleanup(m)
		#		vm_poweroff(m)
		#else: # if the machine is running but there is no job assigned to it then kill it
		#	pcap_terminate(m)
		#	vm_poweroff(m)
#	else: #not sure this is relevant...may need to remove it
#		vm_poweroff(m) #I need to get a list of states that I want to poweroff by default
	return rval

Example 38

Project: fail2ban-zmq-tools
Source File: subscriber.py
View license
	def run(self):
		self.zmqSubscriberContext=zmq.Context()
		self.zmqSubscriberSock=self.zmqSubscriberContext.socket(zmq.SUB)
# TODO: fix prefix handling
#		self.zmqSubscriberSock.setsockopt_string(zmq.SUBSCRIBE,self.subscriberconfig['zmqprefixfilter'].strip('"'))
		self.zmqSubscriberSock.setsockopt_string(zmq.SUBSCRIBE,"")
		self.zmqSubscriberSock.connect(self.zmqPublisher)
		# Wait for messages, when one is received, process it
		while not self._stopevent.isSet():
			message = self.zmqSubscriberSock.recv_string()
			# TODO: INPUT CHECK HERE - apply regex and such against message parts (jail, ip, etc)
			# TODO: act according to publisheraction [see fail2ban-cluster.conf]
			msg=message.split('|')
			Hostname=msg[0]
			Jail=msg[1]
			Action=msg[2]
			Attacker=msg[3]
			# Run a series of tests on incoming messages
			if not f2bcUtils.is_valid_hostname(Hostname):
				syslog.syslog("fail2ban-zmq-tools Subscriber: Invalid hostname in incoming message.")
				continue
			# If hostname matches our hostname, output warning, using different syntax to avoid
			# triggering the fail2bancluster jail filter.
			if Hostname==self.hostname:
				syslog.syslog("fail2ban-zmq-tools Subscriber: Got equal hostname broadcast. Our hostname is %s" % self.hostname)
				continue
			# Only accepted ban or unban actions
			if not f2bcUtils.is_valid_action(Action):
				syslog.syslog("fail2ban-zmq-tools Subscriber: Unknown action received in broadcasted message.")
				continue
			# Only accept valid IPv4 IP addresses for attacker
			if not f2bcUtils.valid_ipv4(Attacker):
				syslog.syslog("fail2ban-zmq-tools Subscriber: Invalid attacker IP received in broadcasted message.")
				continue
			# Jailnames must only contain chars a-z,A-Z,-_
			# TODO: verify fail2ban jailname constraints
			if not f2bcUtils.valid_jailname(Jail):
				syslog.syslog("fail2ban-zmq-tools Subscriber: Invalid jail name received in broadcasted message.")
				continue
			# TODO add debug level output for an invalid message
			syslog.syslog("fail2ban-zmq-tools Subscriber: Got broadcast message: %s" % message)
		syslog.syslog("fail2ban-zmq-tools Subscriber: thread exiting...")

Example 39

View license
    def __init__(self, config):
        gpio.setwarnings(False)
        gpio.cleanup()
        gpio.setmode(gpio.BCM)
        self.config = config
        self.doors = [Door(n,c) for (n,c) in config['doors'].items()]
        self.updateHandler = UpdateHandler(self)
        for door in self.doors:
            door.last_state = 'unknown'
            door.last_state_time = time.time()

        self.use_alerts = config['config']['use_alerts']
        self.alert_type = config['alerts']['alert_type']
        self.ttw = config['alerts']['time_to_wait']
        if self.alert_type == 'smtp':
            self.use_smtp = False
            smtp_params = ("smtphost", "smtpport", "smtp_tls", "username",
                       "password", "to_email", "time_to_wait")
            self.use_smtp = ('smtp' in config['alerts']) and set(smtp_params) == set(config['alerts']['smtp'])
            syslog.syslog("we are using SMTP")
        elif self.alert_type == 'pushbullet':
            self.pushbullet_access_token = config['alerts']['pushbullet']['access_token']
            syslog.syslog("we are using Pushbullet")
        else:
            self.alert_type = None
            syslog.syslog("No alerts configured")

Example 40

View license
    def __init__(self, config):
        gpio.setwarnings(False)
        gpio.cleanup()
        gpio.setmode(gpio.BCM)
        self.config = config
        self.doors = [Door(n,c) for (n,c) in config['doors'].items()]
        self.updateHandler = UpdateHandler(self)
        for door in self.doors:
            door.last_state = 'unknown'
            door.last_state_time = time.time()

        self.use_alerts = config['config']['use_alerts']
        self.alert_type = config['alerts']['alert_type']
        self.ttw = config['alerts']['time_to_wait']
        if self.alert_type == 'smtp':
            self.use_smtp = False
            smtp_params = ("smtphost", "smtpport", "smtp_tls", "username",
                       "password", "to_email", "time_to_wait")
            self.use_smtp = ('smtp' in config['alerts']) and set(smtp_params) == set(config['alerts']['smtp'])
            syslog.syslog("we are using SMTP")
        elif self.alert_type == 'pushbullet':
            self.pushbullet_access_token = config['alerts']['pushbullet']['access_token']
            syslog.syslog("we are using Pushbullet")
        else:
            self.alert_type = None
            syslog.syslog("No alerts configured")

Example 41

Project: thus
Source File: misc.py
View license
def find_in_os_prober(device, with_version=False):
    """Look for the device name in the output of os-prober.

    Return the friendly name of the device, or the empty string on error.
    """
    try:
        oslist, osvers = os_prober()
        if device in oslist:
            ret = oslist[device]
        elif is_swap(device):
            ret = 'swap'
        else:
            syslog.syslog('Device {0} not found in os-prober output'.format(device))
            ret = ''
        ret = utf8(ret, errors='replace')
        ver = utf8(osvers.get(device, ''), errors='replace')
        if with_version:
            return ret, ver
        else:
            return ret
    except (KeyboardInterrupt, SystemExit):
        pass
    except Exception:
        import traceback

        syslog.syslog(syslog.LOG_ERR, "Error in find_in_os_prober:")
        for line in traceback.format_exc().split('\n'):
            syslog.syslog(syslog.LOG_ERR, line)
    return ''

Example 42

Project: a5
Source File: control.py
View license
def main():
	global flagTerminate
        global beanstalk
	global logger

	logger = setupLogger()

 	# define a Handler which writes INFO messages or higher to the sys.stderr
	console = logging.StreamHandler()
	console.setLevel(logging.INFO)
	# set a format which is simpler for console use
	formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
	# tell the handler to use this format
	console.setFormatter(formatter)
	# add the handler to the root logger
	logging.getLogger().addHandler(console)

	random.seed()

	pool = ActivePool()
	assignments = pool.mgr.dict()
	count = pool.mgr.Value('i', 0)
	ADBFAILCOUNT = pool.mgr.Value('i', 0)

	VMs = pool.mgr.dict()

	s = multiprocessing.Semaphore(NUMACTIVEWORKERS)
	q = multiprocessing.Queue()
	r = multiprocessing.Queue()
	results = []
	al = multiprocessing.RLock()
	vml = multiprocessing.RLock()
	cl = multiprocessing.RLock()

	get_VMs(VMs)
	list_VMs(VMs)
	#make sure any pcaps are killed and we are starting with a clean filesystem

	for i in range(30):
		#q.put("item " + str(i) + " content")
		q.put("live" + str(i))
		

	#adb ports are 5554 - 5584, only even	
	port = ADBPORT
	jobs = [
		multiprocessing.Process(target=worker, name=str(i), args=(s, pool, q, "hi", VMs, vml, str(port+(i*2)), count, al, r, ADBFAILCOUNT))
		for i in range(NUMWORKERS)
		]

	for j in jobs:
		logger.info( "starting worker %s" % j.name)
		j.start()

#	for j in jobs:
#		j.join()
#		logger.info( 'Now running: %s' % str(pool))

	#make the connection after the child spawning, each child makes thier own connections
	rebeanstalk()

	while True:

		logger.info( "==============================")
		logger.info( "processed %d samples so far" % count.value)
		try:
			#not great, but the parent is the only consumer of r items
			thing = r.get(block=False)
			results.append(thing)
		except:
			logger.warning( "results queue exception")
		
		if len(results) > 0:
			logger.info( "average sample time: %s" % str(sum(results) / float(len(results))))
		try:
			if BSMSBOXQ not in beanstalk.tubes():
					logger.info( "there are no samples in the beanstalk")
			else:
				if beanstalk.peek_ready() is not None:
					logger.info( str(beanstalk.stats_tube(BSMSBOXQ)['current-jobs-ready']) + " samples ready to process")
				else:
					logger.info( "0 samples ready to process")
				if beanstalk.peek_reserved() is not None:
					logger.info( str(beanstalk.stats_tube(BSMSBOXQ)['current-jobs-reserved']) + " samples are processing")
				else:
					logger.info( "0 samples are processing")
				if beanstalk.peek_delayed() is not None:
					logger.info( str(beanstalk.stats_tube(BSMSBOXQ)['current-jobs-delayed']) + " samples are delayed")
				else:
					logger.info( "0 samples are delayed")
		except KeyError:
			logger.warning( "beanstalk keyerror")
		except:
			logger.warning( "beanstalk general error")
		logger.info( "about " + str(q.qsize()) + " current q items")
		logger.info( "adb has failed " + str(ADBFAILCOUNT.value) + " times since last kick")
		logger.debug( "should be " + str(NUMWORKERS) + " processes:")
		walive = 0
		wdead = 0
		for j in jobs:
			if j.is_alive():
				logger.debug( "   " + str(j.pid))
				walive += 1
			else: 
				logger.debug( "   dead")
				wdead += 1
				#this will kill the controller, leaving the children pipes wanting more (you will get sigpipe errors)
				#this is pretty harsh and shouldn't probably be done in production
				#TODO
				#sys.exit(1)
		logger.info( "%s alive; %s dead" % (walive, wdead))
		updateStatus(NUMWORKERS,walive,wdead)

		list_VMs(VMs)
		time.sleep(VM_POLL_REST + 10)

		#blocks until all items in q are processed
		#safe to exit
		#should check for sigint
		#if q.qsize() == 0:
		#	for i in jobs:
		#		q.put("die")
		#	q.close()

	sys.exit(0)


	signal.signal(signal.SIGINT, sigint_handler)
	syslog.syslog('Startup - Entering main polling loop...')
	while True:

		get_VMs(VMs)
		list_VMs(VMs)
		#make sure any pcaps are killed and we are starting with a clean filesystem
		#pcap_terminate(m)
		#job_cleanup(m)

		#check for a job in the beanstalk Q
		if not beanstalk:
			error_log('Re-establishing connection to beanstalkd')
			beanstalk = beanstalkc.Connection(host=BSHOST, port=BSPORT)
			beanstalk.watch(BSMSBOXQ)
			beanstalk.use(BSMSBOXQ)
			beanstalk.ignore('default')

		#we want to reserve, not peak_ready because if we can't process, we want to release with a delay later
		beanstalkjob = beanstalk.reserve()

		#if there was a job and we got it then queue up analysis
		if beanstalkjob:
			try:
				job = eval(beanstalkjob.body)
			except:
				error_log('ERROR: could not eval job - invalid job')
				beanstalkjob.delete()
				return False

			#is there a VM compatible with this sample that is ready to be used?
			m = findCompatibleVM(job,VMs,vml)
			if m is not None:
				logger.info( "yay using VM " + str(m))
				#process sample

				sys.exit(0)

				#delete from queue if successfull
				#beanstalkjob.delete()
			else:
				#no VM found, put it back in the queue (nobody will process for 60 seconds
				beanstalkjob.release(delay=60)
				logger.info( "requeuing job requiring a target version " + job['target'])


#		
#		#break ot of the loop and exit if the assignments are clear and the terminate flag is set
		if flagTerminate and len(assignments)==0:
			syslog.syslog('All assigned jobs are completed (EXITING)...')
			break
		#put a pause in the polling cycle...set to 0 for no pause
		time.sleep(VM_POLL_REST)
		sys.exit(0)
	syslog.syslog('Shutdown - Leaving main polling loop...')
	return 0

Example 43

Project: thus
Source File: misc.py
View license
def find_in_os_prober(device, with_version=False):
    """Look for the device name in the output of os-prober.

    Return the friendly name of the device, or the empty string on error.
    """
    try:
        oslist, osvers = os_prober()
        if device in oslist:
            ret = oslist[device]
        elif is_swap(device):
            ret = 'swap'
        else:
            syslog.syslog('Device {0} not found in os-prober output'.format(device))
            ret = ''
        ret = utf8(ret, errors='replace')
        ver = utf8(osvers.get(device, ''), errors='replace')
        if with_version:
            return ret, ver
        else:
            return ret
    except (KeyboardInterrupt, SystemExit):
        pass
    except Exception:
        import traceback

        syslog.syslog(syslog.LOG_ERR, "Error in find_in_os_prober:")
        for line in traceback.format_exc().split('\n'):
            syslog.syslog(syslog.LOG_ERR, line)
    return ''

Example 44

Project: tumgreyspf
Source File: tumgreyspfsupp.py
View license
def readConfigFile(path, configData = None, configGlobal = {}):
	'''Reads a configuration file from the specified path, merging it
	with the configuration data specified in configData.  Returns a
	dictionary of name/value pairs based on configData and the values
	read from path.'''

	debugLevel = configGlobal.get('debugLevel', 0)
	if debugLevel >= 3: syslog.syslog('readConfigFile: Loading "%s"' % path)
	if configData == None: configData = {}
	nameConversion = {
			'SPFSEEDONLY' : int,
			'GREYLISTTIME' : int,
			'CHECKERS' : str,
			'OTHERCONFIGS' : str,
			'GREYLISTEXPIREDAYS' : float,
			}

	#  check to see if it's a file
	try:
		mode = os.stat(path)[0]
	except OSError, e:
		syslog.syslog('ERROR stating "%s": %s' % ( path, e.strerror ))
		return(configData)
	if not stat.S_ISREG(mode):
		syslog.syslog('ERROR: is not a file: "%s", mode=%s' % ( path, oct(mode) ))
		return(configData)

	#  load file
	fp = open(path, 'r')
	while 1:
		line = fp.readline()
		if not line: break

		#  parse line
		line = string.strip(string.split(line, '#', 1)[0])
		if not line: continue
		data = map(string.strip, string.split(line, '=', 1))
		if len(data) != 2:
			syslog.syslog('ERROR parsing line "%s" from file "%s"'
					% ( line, path ))
			continue
		name, value = data

		#  check validity of name
		conversion = nameConversion.get(name)
		if conversion == None:
			syslog.syslog('ERROR: Unknown name "%s" in file "%s"' % ( name, path ))
			continue

		if debugLevel >= 4: syslog.syslog('readConfigFile: Found entry "%s=%s"'
				% ( name, value ))
		configData[name] = conversion(value)
	fp.close()
	
	return(configData)

Example 45

Project: tumgreyspf
Source File: tumgreyspfsupp.py
View license
def readConfigFile(path, configData = None, configGlobal = {}):
	'''Reads a configuration file from the specified path, merging it
	with the configuration data specified in configData.  Returns a
	dictionary of name/value pairs based on configData and the values
	read from path.'''

	debugLevel = configGlobal.get('debugLevel', 0)
	if debugLevel >= 3: syslog.syslog('readConfigFile: Loading "%s"' % path)
	if configData == None: configData = {}
	nameConversion = {
			'SPFSEEDONLY' : int,
			'GREYLISTTIME' : int,
			'CHECKERS' : str,
			'OTHERCONFIGS' : str,
			'GREYLISTEXPIREDAYS' : float,
			}

	#  check to see if it's a file
	try:
		mode = os.stat(path)[0]
	except OSError, e:
		syslog.syslog('ERROR stating "%s": %s' % ( path, e.strerror ))
		return(configData)
	if not stat.S_ISREG(mode):
		syslog.syslog('ERROR: is not a file: "%s", mode=%s' % ( path, oct(mode) ))
		return(configData)

	#  load file
	fp = open(path, 'r')
	while 1:
		line = fp.readline()
		if not line: break

		#  parse line
		line = string.strip(string.split(line, '#', 1)[0])
		if not line: continue
		data = map(string.strip, string.split(line, '=', 1))
		if len(data) != 2:
			syslog.syslog('ERROR parsing line "%s" from file "%s"'
					% ( line, path ))
			continue
		name, value = data

		#  check validity of name
		conversion = nameConversion.get(name)
		if conversion == None:
			syslog.syslog('ERROR: Unknown name "%s" in file "%s"' % ( name, path ))
			continue

		if debugLevel >= 4: syslog.syslog('readConfigFile: Found entry "%s=%s"'
				% ( name, value ))
		configData[name] = conversion(value)
	fp.close()
	
	return(configData)

Example 46

Project: fail2ban-zmq-tools
Source File: publisher.py
View license
	def run(self):
		self.zmqPublisherContext=zmq.Context()
		self.zmqPublisherSock=self.zmqPublisherContext.socket(zmq.PUB)
		self.zmqPublisherSock.bind(self.zmqBroadcasterBindUrl)
		
		self.zmqReplyContext=zmq.Context()
		self.zmqReplySock=self.zmqReplyContext.socket(zmq.REP)
		self.zmqReplySock.bind(self.zmqReplyBindUrl)

		self.zmqReplySock.setsockopt(zmq.MAXMSGSIZE,64) #http://api.zeromq.org/3-2:zmq-setsockopt
		self.zmqReplySock.setsockopt(zmq.RCVTIMEO,1000) # 1s timeout for recv()
		# Wait for messages, when one is received, process it
		while not self._stopevent.isSet():
			message=None
			try:
				message = self.zmqReplySock.recv_string() # NOBLOCK per setsockopt()
			except zmq.error.ZMQError as e:
#				pprint(e)
				if e==errno.EAGAIN: pass #Nothing to see, move along
			if not message: continue

			# Send it back to Requester (monitor instance), but first run some tests.
			# Failed tests trigger a NAK response, and then a while().continue
			
			# Check if splitted message has less than 4 or more than 5 slices
			if len(message.split('|')) < 4 or len(message.split('|')) > 5:
				self.zmqReplySock.send_string("NAK")
				syslog.syslog("fail2ban-zmq-tools Publisher: invalid message. Replying NAK.")
				continue
			# and if incoming token matches our defined token
			if self.authenticate=="true" and message.split('|')[0]!=self.authtoken:
				self.zmqReplySock.send_string("NAK")
				syslog.syslog("fail2ban-zmq-tools Publisher: invalid token. Replying NAK.")
				continue
				
			#remove authentication data from to-be-propagated message
			if self.authenticate=="true":
				newmsg=message.split('|')
				message='|'.join(newmsg[1:])

			# Now test hostname,jail,action and attacker
			newmsg=message.split('|')
			Hostname=newmsg[0]
			Jail=newmsg[1]
			Action=newmsg[2]
			Attacker=newmsg[3]
			
			if not f2bcUtils.is_valid_hostname(Hostname):
				self.zmqReplySock.send_string("NAK")
				syslog.syslog("fail2ban-zmq-tools Publisher: invalid hostname in incoming message. Replying NAK.")
				continue
			if not f2bcUtils.is_valid_action(Action):
				self.zmqReplySock.send_string("NAK")
				syslog.syslog("fail2ban-zmq-tools Publisher: Unknown action received in message. Replying NAK.")
				continue
			if not f2bcUtils.valid_ipv4(Attacker):
				self.zmqReplySock.send_string("NAK")
				syslog.syslog("fail2ban-zmq-tools Publisher: Invalid attacker IP received in message. Replying NAK.")
				continue
			if not f2bcUtils.valid_jailname(Jail):
				self.zmqReplySock.send_string("NAK")
				syslog.syslog("fail2ban-zmq-tools Publisher: Invalid jailname received in message.Replying NAK.")
				continue
				
			# If we got here, all tests were positive. we can make an OK reply
			# and then we can propagate the message, which now lacks authentication information
			self.zmqReplySock.send_string(message)
			syslog.syslog("fail2ban-zmq-tools Publisher: Propagating %s for %s/%s from %s" % (Action,Attacker,Jail,Hostname))
			self.zmqPublisherSock.send_string(message)
#TODO: add loglevels
		syslog.syslog("fail2ban-zmq-tools Publisher: thread exiting...")
		sys.stdout.flush()

Example 47

Project: douban-sqlstore
Source File: __init__.py
View license
    def _flush_get_cursor_log(self, cursor):
        if len(cursor.queries) > 1:
            syslog.syslog('get_cursor: %s' % '|'.join(cursor.queries))
        cursor.queries = []

Example 48

View license
        def __sigTERMhandler(self, signum, frame):
                syslog.syslog ("Caught signal %d. Initiating shutdown..." % signum)
                self.quit()

Example 49

Project: duo_openvpn
Source File: duo_openvpn.py
View license
def log(msg):
    msg = 'Duo OpenVPN: %s' % msg
    syslog.syslog(msg)

Example 50

Project: pyserial
Source File: port_publisher.py
View license
                def flush(self):
                    syslog.syslog(self.buffer)
                    self.buffer = ''