class Rador(object): """Класс для пересылки сообщений из Syslog-ng в Radius.""" def __init__(self, radius_settings_tuple, logging): """Инициализация объекта из файла ibitial.conf.""" self.packet_send = 0 self.logging = logging radius_ip = radius_settings_tuple[0] radius_secret = radius_settings_tuple[1] radius_dict_path = radius_settings_tuple[2] self.srv = Client( server=radius_ip, secret=radius_secret.encode(), dict=Dictionary(radius_dict_path), ) def send_message(self, attributes_dict): """Send radius packet.""" self.attributes_dict = attributes_dict self.req = self.srv.CreateAcctPacket() # Создаем запрос по всем атрибутам и их значениям for key in self.attributes_dict: self.req[key] = self.attributes_dict[key] # Отправляем запрос reply = self.srv.SendPacket(self.req) # В случае успеха (ответный код 5), отправляем в лог if reply.code == pyrad.packet.AccountingResponse: self.packet_send += 1 self.logging.error('Successfully sent Acct packet to server.') else: # Иначе пишем в лог ошибку self.logging.error('Error with sending packet.')
def Hangup(server, port, session, user_name): server = Server.objects.get(id=server) print server.get_hash_password client = Client(server=server.ip, secret=server.get_hash_password, acctport=3799, dict=Dictionary("dictionary")) if 'mx80' in server.server_type: req = client.CreateAcctPacket(code=pyrad.packet.DisconnectRequest) req["Acct-Session-Id"] = session reply = client.SendPacket(req) return reply if 'mpd5' in server.server_type: req = client.CreateAcctPacket(code=pyrad.packet.DisconnectRequest) req["User-Name"] = user_name reply = client.SendPacket(req) return reply
def sendAcct(ns, user, ip, action): server = "172.16.3.1" srv = Client(server=server, secret="sandvine", dict=Dictionary("/etc/ppp/aaa-dictionary")) import types def setRetryTimeout(self, r, t): self.retries = r self.timeout = t srv.setRetryTimeout = types.MethodType(setRetryTimeout, srv) srv.setRetryTimeout(1, 0) req = srv.CreateAcctPacket(User_Name=user) # req["NAS-IP-Address"]="192.168.1.10" # req["NAS-Port"]=0 # req["NAS-Identifier"]="trillian" # req["Called-Station-Id"]="00-04-5F-00-0F-D1" # req["Calling-Station-Id"]="00-01-24-80-B3-9C" req["Framed-IP-Address"] = ip req["User-Name"] = user req["3GPP-IMSI"] = user req["Calling-Station-Id"] = user req["Acct-Status-Type"] = action req["Acct-Session-Id"] = "1" req["3GPP-SGSN-Address"] = server req["3GPP-GGSN-Address"] = server req["Event-Timestamp"] = int(time.time()) pid = os.fork() if (pid == 0): try: x = find_ns.NS(ns) try: srv.SendPacket(req) except: # We expect this error, since we get an ICMP port unreach # back since no one is listening. But that's ok, we just # tee the AAA anyway pass x.__del__() except: # Hmm, namespace is gone pass sys.exit(0) os.waitpid(pid, 0)
class OtherTests(unittest.TestCase): def setUp(self): self.server = object() self.client = Client(self.server, secret=six.b('zeer geheim')) def testCreateAuthPacket(self): packet = self.client.CreateAuthPacket(id=15) self.failUnless(isinstance(packet, AuthPacket)) self.failUnless(packet.dict is self.client.dict) self.assertEqual(packet.id, 15) self.assertEqual(packet.secret, six.b('zeer geheim')) def testCreateAcctPacket(self): packet = self.client.CreateAcctPacket(id=15) self.failUnless(isinstance(packet, AcctPacket)) self.failUnless(packet.dict is self.client.dict) self.assertEqual(packet.id, 15) self.assertEqual(packet.secret, six.b('zeer geheim'))
class Rasta: def __init__(self): self.cfg = None def load_config(self, config_file): fnm = config_file try: f = open(fnm, 'r') self.cfg = json.load(f) except IOError as e: print("Failed to open config file: %s" % (str(e), )) sys.exit(-1) return True def create_client(self, dictfile): self.server = Client(server=str(self.cfg["settings"]["acct"]['host']), secret=str( self.cfg["settings"]["acct"]["secret"]), dict=Dictionary(dictfile)) def expand_var(self, s): return s def create_packets(self, username, packet_type): reqs = [] if username in self.cfg["users"].keys(): # print("user " + username + " in database") req = self.server.CreateAcctPacket(User_Name=str(username)) req[r"Acct-Status-Type"] = str(packet_type) for att in self.cfg["users"][username]["Acct"][packet_type].keys(): val = self.cfg["users"][username]["Acct"][packet_type][att] if type(val) == type(u"some string"): req[str(att)] = self.expand_var(str(val)) else: req[str(att)] = self.expand_var(val) reqs.append(req) else: pass # print("user " + username + " NOT in database") return reqs def send_one(self, req): try: print("Sending accounting start packet") self.server.SendPacket(req) except pyrad.client.Timeout: print("RADIUS server does not reply") return False except socket.error, error: print("Network error: " + error[1]) return False return True
#!/usr/bin/python from __future__ import print_function from pyrad.client import Client from pyrad import dictionary from pyrad import packet ADDRESS = "127.0.0.1" SECRET = b"Kah3choteereethiejeimaeziecumi" ATTRIBUTES = {"Acct-Session-Id": "1337"} CODE = packet.CoARequest # 43 # CODE = packet.DisconnectRequest # 40 # create coa client client = Client(server=ADDRESS, secret=SECRET, authport=3799, acctport=3799, dict=dictionary.Dictionary("dictionary")) # set coa timeout client.timeout = 30 # create coa request packet attributes = {k.replace("-", "_"): attributes[k] for k in attributes} request = client.CreateAcctPacket(code=CODE, **attributes) # send coa request result = client.SendPacket(request) print(result)
except pyrad.client.Timeout: print("RADIUS server does not reply") sys.exit(1) except socket.error as error: print("Network error: " + error[1]) sys.exit(1) # For more Acct-Status-Type action, check Radius Dictionary dict = StringIO("ATTRIBUTE User-Name 1 string\n" + "ATTRIBUTE Framed-IP-Address 8 ipaddr\n" + "ATTRIBUTE Class 25 string\n" + "ATTRIBUTE Calling-Station-Id 31 string\n" + "ATTRIBUTE Acct-Status-Type 40 integer\n" + "ATTRIBUTE Acct-Session-Id 44 string\n" + "VALUE Acct-Status-Type Start 1\n" + "VALUE Acct-Status-Type Stop 2") srv = Client(server=FGT_IP, secret=FGT_RAD_SECRET, dict=Dictionary(dict)) req = srv.CreateAcctPacket(User_Name="teste2") req["Calling-Station-Id"] = "00-0c-29-44-BE-B8" req["Acct-Session-Id"] = "0211a4ef" req["Class"] = "group1" req["Acct-Status-Type"] = "Start" for ip in ipaddress.IPv4Network(NET_SIZE): req["Framed-IP-Address"] = "%s" % ip print("Sending accounting start packet") SendPacket(srv, req)
def SendPacket(srv, req): try: srv.SendPacket(req) except pyrad.client.Timeout: print("RADIUS server does not reply") sys.exit(1) except socket.error as error: print("Network error: " + error[1]) sys.exit(1) else: print("Account Request has been processed by server successfully!") srv = Client(server="127.0.0.1", secret=b"56rmkuri92d8a0wvi9divyxvn1nku3", dict=Dictionary(path_to_dictionary)) req = srv.CreateAcctPacket( User_Name="VZJ9VTB662KI7F1ZHFF8YBW8PNV1ECEQD3FZAMSY2") req["NAS-IP-Address"] = "192.168.1.10" req["NAS-Port"] = 0 req["NAS-Identifier"] = "azae0j07sbjzcyc2hg66_ac86745dbe40" req["Called-Station-Id"] = "00-04-5F-00-0F-D1" req["Calling-Station-Id"] = "00-01-24-80-B3-9C" req["Framed-IP-Address"] = "10.0.0.100" req["Acct-Session-Id"] = '80200028' req["Acct-Status-Type"] = "Start" SendPacket(srv, req)
#!/usr/bin/python import os, socket import pyrad.packet from pyrad.client import Client from pyrad.dictionary import Dictionary server = "your_server_ip" secret = "your_server_secret" dict_path = "/path/to/dictionary" srv = Client(server=server, secret=secret, dict=Dictionary(dict_path)) req = srv.CreateAcctPacket() req["User-Name"] = os.getenv("USERNAME") req["NAS-IP-Address"] = socket.gethostbyname(socket.gethostname()) req["NAS-Port"] = 0 req["Calling-Station-Id"] = os.getenv("IP_REAL") req["Framed-IP-Address"] = os.getenv("IP_REMOTE") req["Service-Type"] = "Framed-User" req["Framed-Protocol"] = "AnyConnect" req["Acct-Session-Id"] = os.getenv("ID") if os.getenv("REASON") == "connect": req["Acct-Status-Type"] = "Start" else: req["Acct-Status-Type"] = "Stop" req["Acct-Input-Octets"] = long(os.getenv("STATS_BYTES_IN")) req["Acct-Output-Octets"] = long(os.getenv("STATS_BYTES_OUT")) req["Acct-Session-Time"] = long(os.getenv("STATS_DURATION")) req["Acct-Terminate-Cause"] = "User-Request" try:
def SendPacket(srv, req): try: srv.SendPacket(req) except pyrad.client.Timeout: print "RADIUS server does not reply" sys.exit(1) except socket.error, error: print "Network error: " + error[1] sys.exit(1) srv = Client(server="localhost", secret="Kah3choteereethiejeimaeziecumi", dict=Dictionary("dictionary")) req = srv.CreateAcctPacket(User_Name="wichert") req["NAS-IP-Address"] = "192.168.1.10" req["NAS-Port"] = 0 req["NAS-Identifier"] = "trillian" req["Called-Station-Id"] = "00-04-5F-00-0F-D1" req["Calling-Station-Id"] = "00-01-24-80-B3-9C" req["Framed-IP-Address"] = "10.0.0.100" print "Sending accounting start packet" req["Acct-Status-Type"] = "Start" SendPacket(srv, req) print "Sending accounting stop packet" req["Acct-Status-Type"] = "Stop" req["Acct-Input-Octets"] = random.randrange(2**10, 2**30)
import pyrad.packet import socket radius = "192.168.1.11" seckey = "cisco" msoc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) msoc.connect((radius, 1812)) myip = msoc.getsockname()[0] srv = Client(server=radius, secret=seckey, dict=Dictionary("dictionary")) db = TinyDB('1vm2radius.db') dbq = Query() srec = db.search(dbq.iclass != "") for recs in srec: req2 = srv.CreateAcctPacket(User_Name=recs['vname']) req2["Calling-Station-Id"] = str(recs['vmac']) req2["Framed-IP-Address"] = str(recs['vipadd']) req2["Service-Type"] = 2 req2["NAS-Port-Type"] = 0 req2["NAS-IP-Address"] = myip req2["Acct-Status-Type"] = "Stop" req2["Class"] = str(recs['iclass']) req2["Acct-Session-Id"] = str(recs['asess']) req2["Cisco-AVPair"] = "audit-session-id=" + str(recs['isess']) req2['Acct-Terminate-Cause'] = 2 req2['Acct-Delay-Time'] = 2 acct = srv.SendPacket(req2) db.purge() db.close()
store_data[i] = reply[i][0] elif reply.code == pyrad.packet.AccessReject: auth_message = " User Access Reject ", reply.code auth_response = ACCOUNT_STATUS_VALIDATION_FAILED store_data["auth"] = False else: auth_message = " An error occurred during the validation process ", reply.code auth_response = ACCOUNT_STATUS_ERROR store_data["auth"] = False store_data.save() if stage == "counters": # COUNTERS store_data = store.store_key(token) maxoctets = abs(int(outgoing) + int(incoming)) req = srv.CreateAcctPacket(User_Name=store_data["username"]) req["Acct-Status-Type"] = "Interim-Update" req["Acct-Session-Id"] = token req["Acct-Input-Octets"] = int(incoming) req["Acct-Output-Octets"] = int(outgoing) req["Acct-Delay-Time"] = 0 req["NAS-IP-Address"] = gw_address req["NAS-Port"] = config.custom_nas_port req["NAS-Port-Type"] = config.custom_nas_port_type # MAC OF WIFIDOG "00-10-A4-23-19-C0" req["NAS-Identifier"] = config.node_mac # MAC OF WIFIDOG"00-10-A4-23-19-C0" req["Called-Station-Id"] = config.node_mac # MAC OF USER OR IP "00-00-B4-23-19-C0"
def main(): """ Sample Python program for monitoring property changes to objects of one or more types to stdout """ args = get_args() if args.password: password = args.password else: password = getpass.getpass(prompt='Enter password for host %s and ' 'user %s: ' % (args.host, args.user)) msoc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) msoc.connect((args.radius, 1812)) myip = msoc.getsockname()[0] #Clean up DB on start. Send accounting STOP for stale entries srv = Client(server=args.radius, secret=args.secret, dict=Dictionary("dictionary")) db = TinyDB('1vm2radius.db') dbq = Query() srec = db.search(dbq.iclass != "") for recs in srec: req2 = srv.CreateAcctPacket(User_Name=recs['vname']) req2["Calling-Station-Id"] = str(recs['vmac']) req2["Framed-IP-Address"] = str(recs['vipadd']) req2["Service-Type"] = 2 req2["NAS-Port-Type"] = 0 req2["NAS-IP-Address"] = myip req2["Acct-Status-Type"] = "Stop" req2["Class"] = str(recs['iclass']) req2["Acct-Session-Id"] = str(recs['asess']) req2["Cisco-AVPair"] = "audit-session-id=" + str(recs['isess']) req2['Acct-Terminate-Cause'] = 2 req2['Acct-Delay-Time'] = 2 acct = srv.SendPacket(req2) db.purge() db.close() try: #if args.disable_ssl_warnings: # from requests.packages import urllib3 # urllib3.disable_warnings() if (not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None)): ssl._create_default_https_context = ssl._create_unverified_context si = SmartConnect(host=args.host, user=args.user, pwd=password, port=int(args.port)) if not si: print >> sys.stderr, "Could not connect to the specified host ' \ 'using specified username and password" raise atexit.register(Disconnect, si) spec = [ 'VirtualMachine:name,runtime.powerState,runtime.host,guest.ipAddress,guest.net' ] propspec = parse_propspec(spec) ite = None print "Starting VM2RADIUS. Press ^C to exit" monitor_property_changes(si, propspec, args.radius, args.secret, myip, ite) except vmodl.MethodFault, e: print >> sys.stderr, "Caught vmodl fault :\n%s" % str(e) raise
def monitor_property_changes(si, propspec, radius, seckey, myip, iterations=None): """ :type si: pyVmomi.VmomiSupport.vim.ServiceInstance :type propspec: collections.Sequence :type iterations: int or None """ pc = si.content.propertyCollector make_property_collector(pc, si.content.rootFolder, propspec) waitopts = make_wait_options(30) version = '' while True: if iterations is not None: if iterations <= 0: print('Iteration limit reached, monitoring stopped') break result = pc.WaitForUpdatesEx(version, waitopts) # timeout, call again if result is None: continue # process results for filterSet in result.filterSet: for objectSet in filterSet.objectSet: moref = getattr(objectSet, 'obj', None) assert moref is not None, 'object moref should always be ' \ 'present in objectSet' moref = str(moref).strip('\'') kind = getattr(objectSet, 'kind', None) assert (kind is not None and kind in ( 'enter', 'modify', 'leave', )), 'objectSet kind must be valid' #When the script starts, Vmware will return all VMs and kind will be set to enter. if kind == 'enter': changeSet = getattr(objectSet, 'changeSet', None) assert (changeSet is not None and isinstance( changeSet, collections.Sequence ) and len(changeSet) > 0), \ 'enter or modify objectSet should have non-empty' \ ' changeSet' changes = [] changes.append(( 'vmid', moref, )) srv = Client(server=radius, secret=seckey, dict=Dictionary("dictionary")) for change in changeSet: name = getattr(change, 'name', None) assert (name is not None), \ 'changeset should contain property name' val = getattr(change, 'val', None) if name == "name": vname = str(val) changes.append(( 'VM-Name', vname, )) elif name == "runtime.powerState": vpower = str(val) changes.append(( 'Power', vpower, )) elif name == "guest.net" and val != None: for netinfo in val: vnet = getattr(netinfo, "network", None) vmac = getattr(netinfo, "macAddress", None) changes.append(( 'network', str(vnet), )) changes.append(( 'macAddress', str(vmac), )) elif name == "runtime.host": vhost = str(val).split(':')[-1].split("'")[0] changes.append(( 'host', vhost, )) elif name == "guest.ipAddress" and val != None: vipadd = str(val) if "127.0.0.1" in vipadd: vipadd = None changes.append(( "VM IP", vipadd, )) elif name == "guest.ipAddress" and val == None: vipadd = None changes.append(( "VM IP", vipadd, )) else: changes.append(( name, str(val), )) #Send RADIUS Request for VMs that have IP clss = "" sess = "" asid = "" if vipadd != None: req = srv.CreateAuthPacket( code=pyrad.packet.AccessRequest, User_Name=vname) req["User-Password"] = req.PwCrypt("randompass") req["Calling-Station-Id"] = vmac req["Framed-IP-Address"] = vipadd req["Service-Type"] = 2 req["NAS-Port-Type"] = 0 req["NAS-IP-Address"] = myip if vhost != None and vnet != None: req["Called-Station-Id"] = vhost + ":" + vnet try: reply = srv.SendPacket(req) except pyrad.client.Timeout: sys.exit(1) except socket.error as error: sys.exit(1) if reply.code == pyrad.packet.AccessAccept: for i in reply.keys(): if i == "Class": clss = reply[i][0] m = re.search(":(.+?):", clss) if m: sess = m.group(1) #Send Accounting Start packet matching the above request req2 = srv.CreateAcctPacket(User_Name=vname) req2["Calling-Station-Id"] = vmac req2["Framed-IP-Address"] = vipadd req2["Service-Type"] = 2 req2["NAS-Port-Type"] = 0 req2["NAS-IP-Address"] = myip req2["Acct-Status-Type"] = "Start" req2["Class"] = clss if vhost != None and vnet != None: req2["Called-Station-Id"] = vhost + ":" + vnet asid = str(random.randint(1, 5000)) req2["Acct-Session-Id"] = asid req2["Cisco-AVPair"] = "audit-session-id=" + sess req2["Acct-Delay-Time"] = 0 acct = srv.SendPacket(req2) else: print "Authentication Failed for VM - " + vname + " Configure ISE to CONTINUE on auth failure" #Write to DB db = TinyDB('1vm2radius.db') db.insert({ 'vmid': moref, 'vname': vname, 'vipadd': vipadd, 'vhost': vhost, 'vnet': vnet, 'vpower': vpower, 'vmac': vmac, 'iclass': clss, 'isess': sess, 'asess': asid }) db.close() #print "== %s ==" % moref #print '\n'.join(['%s: %s' % (n, v,) for n, v in changes]) #print '\n' #When there is a change in VM, the value of kind will be modify elif kind == 'modify': changeSet = getattr(objectSet, 'changeSet', None) assert (changeSet is not None and isinstance( changeSet, collections.Sequence ) and len(changeSet) > 0), \ 'enter or modify objectSet should have non-empty' \ ' changeSet' #On receiving an update send an Accounting Stop first #and clean the DB srv = Client(server=radius, secret=seckey, dict=Dictionary("dictionary")) db = TinyDB('1vm2radius.db') detail = Query() records = db.search(detail.vmid == moref) for recs in records: if recs['vipadd'] != None: req2 = srv.CreateAcctPacket( User_Name=recs['vname']) req2["Calling-Station-Id"] = str(recs['vmac']) req2["Framed-IP-Address"] = str(recs['vipadd']) req2["Service-Type"] = 2 req2["NAS-Port-Type"] = 0 req2["NAS-IP-Address"] = myip req2["Acct-Status-Type"] = "Stop" req2["Class"] = str(recs['iclass']) req2["Acct-Session-Id"] = str(recs['asess']) req2["Cisco-AVPair"] = "audit-session-id=" + str( recs['isess']) req2['Acct-Terminate-Cause'] = 2 req2['Acct-Delay-Time'] = 2 acct = srv.SendPacket(req2) vname = recs['vname'] db.update({'vipadd': None}, detail.vmid == moref) db.update({'iclass': ""}, detail.vmid == moref) db.update({'asess': ""}, detail.vmid == moref) db.update({'isess': ""}, detail.vmid == moref) db.update({'vnet': ""}, detail.vmid == moref) changes = [] for change in changeSet: name = getattr(change, 'name', None) assert (name is not None), \ 'changeset should contain property name' val = getattr(change, 'val', None) if name == "runtime.powerState": #Update in DB db.update({'vpower': str(val)}, detail.vmid == moref) elif name == "guest.net" and val != None: for netinfo in val: vnet = getattr(netinfo, "network", None) vmac = getattr(netinfo, "macAddress", None) db.update({'vnet': vnet}, detail.vmid == moref) db.update({'vmac': vmac}, detail.vmid == moref) elif name == "guest.ipAddress" and val != None: vipadd = str(val) if "127.0.0.1" in vipadd: vipadd = None db.update({'vipadd': vipadd}, detail.vmid == moref) elif name == "guest.ipAddress" and val == None: vipadd = None db.update({'vipadd': vipadd}, detail.vmid == moref) changes.append(( name, val, )) if vipadd != None: req = srv.CreateAuthPacket( code=pyrad.packet.AccessRequest, User_Name=vname) req["User-Password"] = req.PwCrypt("randompass") req["Calling-Station-Id"] = vmac req["Framed-IP-Address"] = vipadd req["Service-Type"] = 2 req["NAS-Port-Type"] = 0 req["NAS-IP-Address"] = myip if vhost != None and vnet != None: req["Called-Station-Id"] = vhost + ":" + vnet try: reply = srv.SendPacket(req) except pyrad.client.Timeout: sys.exit(1) except socket.error as error: sys.exit(1) if reply.code == pyrad.packet.AccessAccept: for i in reply.keys(): if i == "Class": clss = reply[i][0] m = re.search(":(.+?):", clss) if m: sess = m.group(1) #Send Accounting Start packet matching the above request req2 = srv.CreateAcctPacket(User_Name=vname) req2["Calling-Station-Id"] = vmac req2["Framed-IP-Address"] = vipadd req2["Service-Type"] = 2 req2["NAS-Port-Type"] = 0 req2["NAS-IP-Address"] = myip req2["Acct-Status-Type"] = "Start" req2["Class"] = clss if vhost != None and vnet != None: req2["Called-Station-Id"] = vhost + ":" + vnet asid = str(random.randint(1, 5000)) req2["Acct-Session-Id"] = asid req2["Cisco-AVPair"] = "audit-session-id=" + sess acct = srv.SendPacket(req2) db.update({'iclass': clss}, detail.vmid == moref) db.update({'asess': asid}, detail.vmid == moref) db.update({'isess': sess}, detail.vmid == moref) else: print "Authentication Failed for VM - " + vname + " Configure ISE to CONTINUE on auth failure" db.close() #print "== %s ==" % moref #print '\n'.join(['%s: %s' % (n, v,) for n, v in changes]) #print '\n' #else: #print "== %s ==" % moref #print '(removed)\n' version = result.version if iterations is not None: iterations -= 1