#!/usr/bin/python # # netinfo.py - Netinfo client classes # # (c) 2016,2017 Todd Shadburn # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # import os import sys import socket import time import struct from OpenSSL import SSL #NETINFO_EVENT_PACKET_SIZE = 404 NETINFO_EVENT_PACKET_SIZE = 408 # with pad1(uint32_t) class NetinfoEvent(object): def __init__(self,*args, **kwargs): self.flags = 0 self.rc = 0 self.timestamp = int(time.time()) self.datalen = 0 self.hostname = socket.gethostname() self.objectname = '' self.data = '' if 'flags' in kwargs: self.flags = int(kwargs['flags']) if 'rc' in kwargs: self.rc = int(kwargs['rc']) if 'hostname' in kwargs: self.hostname = kwargs['hostname'][:64] if 'object' in kwargs: self.objectname = kwargs['object'][:64] if 'data' in kwargs: self.data = kwargs['data'][:256] self.datalen = len(self.data) return def serialize(self): serdata = bytearray(NETINFO_EVENT_PACKET_SIZE) struct.pack_into('>L L Q L 64s 64s 256s L', serdata, 0, self.flags, self.rc, self.timestamp, self.datalen, self.__bytes(self.hostname, 'utf-8'), self.__bytes(self.objectname, 'utf-8'), self.__bytes(self.data, 'utf-8'), 0) #return buffer(serdata) return serdata def __bytes(self, data, dtype): """ Python 2.x vs 3.x: Why did they screw this up? """ if sys.version_info[0] < 3: return data return bytes(data, dtype) class NetinfoClient(object): def __init__(self, *args, **kwargs): # Initialize context #self.ctx = SSL.Context(SSL.SSLv23_METHOD) self.host = None self.port = 5011 self.cert = None self.key = None self.cacert = None if 'host' in kwargs: self.host = kwargs['host'] if 'port' in kwargs: self.port = int(kwargs['port']) if 'cert' in kwargs: self.cert = kwargs['cert'] if 'key' in kwargs: self.key = kwargs['key'] if 'cacert' in kwargs: self.cacert = kwargs['cacert'] self.ctx = SSL.Context(SSL.TLSv1_METHOD) self.ctx.use_privatekey_file (self.key) self.ctx.use_certificate_file(self.cert) if self.cacert: self.ctx.set_verify(SSL.VERIFY_PEER, verify_cb) # Demand a certificate self.ctx.load_verify_locations(self.cacert) # Set up client self.sock = SSL.Connection(self.ctx, socket.socket(socket.AF_INET, socket.SOCK_STREAM)) self.sock.connect((self.host, self.port)) return def close(self): self.sock.shutdown() self.sock.close() return def send_event(self, event=None): self.sock.send(event.serialize()) return