Пример #1
0
def authorize(p):
  value = rpairstodict(p)
  #print value
  for keys,values in value.items():
    print str(keys) + ':' + str(values)
  #print value['User-Name']
  #print '+++++++++++++++'
  #print settings_local.BILLSDB
  #print rauth.get_nas_info(1, 1)
  radiusd.radlog(radiusd.L_INFO, '*** radlog call in authorize ***')
  db = MySQLdb.connect(settings_local.RADHOST, settings_local.RADUSER, settings_local.RADPASSWD, settings_local.RADDB)
#  msql_ver_cur = db.cursor()
#  msql_ver_cur.execute("SELECT VERSION()")
#  mysql_version = msql_ver_cur.fetchone()[0]
#  print mysql_version
#  print '=========='
  cursor = db.cursor()
  cursor.execute('SELECT DECODE(password, "%s") FROM users WHERE id="%s"' % (settings_local.ENCRYPT_KEY, value['User-Name']))
  password = cursor.fetchone()[0]
#  cursor.close()
  db.close()
  reply = (('Acct-Interim-Interval', '300'), ('Framed-IP-Address', '192.168.3.1'), ('Framed-IP-Netmask', '255.255.255.255'))
  config = ( ('User-Name', '%s' % value['User-Name']), ('Cleartext-Password', password) )
#  print '--------------------------'
#  print rpairstodict(p)
#  print rauth.auth(rpairstodict(p))
#  print '--------------------------'
#  print
#  print radiusd.config
#  print
#  print "================"
#  print radiusd.RLM_MODULE_OK
#  print radiusd.RLM_MODULE_REJECT
#  return radiusd.RLM_MODULE_OK
  return (radiusd.RLM_MODULE_OK, reply, config)
Пример #2
0
def accounting(p):
  print "*** accounting ***"
  print "========================================================================================"
  radiusd.radlog(radiusd.L_INFO, '*** radlog call in accounting (0) ***')
  print
  print p
  return radiusd.RLM_MODULE_OK
Пример #3
0
def authorize(p):
    print "*** authorize ***"
    print
    radiusd.radlog(radiusd.L_INFO, '*** radlog call in authorize ***')
    print
    print p
    return radiusd.RLM_MODULE_OK
Пример #4
0
def authorize(p):
  log = Log("AUTHORIZE")
  log.log(p)
  print("*** authorize ***")
  print("")
  radiusd.radlog(radiusd.L_INFO, '*** radlog call in authorize ***')
  print("")
  print(p)
  print("")
  print(radiusd.config)
  print("")
  reply = ()
  conf = ()
  try:
    user_mac = _get_user_mac(p)
    user = user_mac[0]
    macs = user_mac[1]
    if user is not None:
      password = _get_pass(user)
      if password is not None:
        conf = ( ('Cleartext-Password', password), )
      if macs is not None:
        vlan = _get_vlan(user, macs)
        if vlan is not None:
          reply = ( ('Tunnel-Type', 'VLAN'),
                    ('Tunnel-Medium-Type', 'IEEE-802'),
                    ('Tunnel-Private-Group-Id', vlan), )
  except Exception as e:
    log.log("error")
    log.log(str(e))
  log.log(reply)
  log.log(conf)
  return (radiusd.RLM_MODULE_OK, reply, conf)
Пример #5
0
def authenticate(p):

	d_user_info = None
	char_to_strip = '\'\"'

	username = get_radius_attribute('User-Name', p).strip(char_to_strip).lower()
	password = get_radius_attribute('User-Password', p)
	password_strip = password.strip(char_to_strip)
	user_station = get_radius_attribute('Calling-Station-Id', p)
	nas_ip = get_radius_attribute('NAS-IP-Address', p)

	RedisPool = redis.ConnectionPool()
	RedisDB = redis.Redis(connection_pool=RedisPool)

	d_user_info = RedisDB.get('users_freeradius:{0}'.format(username))

	RedisPool.disconnect()

	if d_user_info:
		d_user_info = json.loads(d_user_info)

	print
	print p
	print

	if d_user_info['password'] == password_strip or d_user_info['password'] == password:
		radiusd.radlog(radiusd.L_AUTH, 'Authenticate User {0}@{1} on {2}'.format(username, user_station, nas_ip))
		return (radiusd.RLM_MODULE_OK)
	else:
		radiusd.radlog(radiusd.L_AUTH, 'Failed : Reject access for User {0}@{2} on {3}'.format(username, password, user_station, nas_ip))
		return (radiusd.RLM_MODULE_FAIL)
Пример #6
0
def authorize(p):
  print "*** authorize ***"
  print
  radiusd.radlog(radiusd.L_INFO, '*** radlog call in authorize ***')
  print
  print p
  return radiusd.RLM_MODULE_OK
Пример #7
0
    def __process_request(self, req_tuple):
        reply_list = []

        # Pega todas as variaveis usadas da tupla de requisicao  
        hostname = self.__get_tuple_item("DHCP-Hostname", req_tuple)
        raw_fqdn = self.__get_tuple_item("DHCP-Client-FQDN", req_tuple)
        mac = self.__get_tuple_item("Calling-Station-Id", req_tuple)
        # O identificador do Client é sempre o MAC, mas se for usado o Client-Identifier o TXT tem um prefixo diferente
        client_identifier = self.__get_tuple_item('DHCP-Client-Identifier', req_tuple) 
        # HW Type, vai ser sempre Ethernet, mas melhor preparar o código para expansão
        hw_type = self.__get_tuple_item('DHCP-Hardware-Type', req_tuple)
        client_ip = self.__get_tuple_item('DHCP-Client-IP-Address', req_tuple)
        gateway = self.__get_tuple_item('DHCP-Gateway-IP-Address', req_tuple)        

        # Hostname e fqdn não podem ser os dois nulos
        if hostname is None and raw_fqdn is None:
            reply_list.append(('DHCP-Client-FQDN', raw_fqdn))
            return None
        elif raw_fqdn is not None:            
            try:
                fqdn = FreeradiusFqdn(raw_fqdn)
            except Exception, e:
                # Em caso de exceção o FQDN enviado pelo cliente é mal formado
                radiusd.radlog(radiusd.L_INFO, "Bad FQDN %s" % (raw_fqdn))
                return None
Пример #8
0
def authorize(p):
    print("*** authorize ***")
    radiusd.radlog(radiusd.L_INFO, '*** radlog call in authorize ***')
    print()
    print(p)
    print()
    print(radiusd.config)
    return radiusd.RLM_MODULE_OK
Пример #9
0
def accounting(p):
  log = Log("ACCOUNTING")
  log.log(p)
  print("*** accounting ***")
  radiusd.radlog(radiusd.L_INFO, '*** radlog call in accounting (0) ***')
  print("")
  print(p)
  return radiusd.RLM_MODULE_OK
Пример #10
0
 def emit(self, record):
     """Process un message de log, en convertissant les niveaux"""
     if record.levelno >= logging.WARN:
         rad_sig = radiusd.L_ERR
     elif record.levelno >= logging.INFO:
         rad_sig = radiusd.L_INFO
     else:
         rad_sig = radiusd.L_DBG
     radiusd.radlog(rad_sig, record.msg.encode('utf-8'))
Пример #11
0
 def emit(self, record):
     """Log message processing, level are converted"""
     if record.levelno >= logging.WARN:
         rad_sig = radiusd.L_ERR
     elif record.levelno >= logging.INFO:
         rad_sig = radiusd.L_INFO
     else:
         rad_sig = radiusd.L_DBG
     radiusd.radlog(rad_sig, str(record.msg))
Пример #12
0
def authenticate(p):
  log = Log("AUTHENTICATE")
  log.log(p)
  radiusd.radlog(radiusd.L_INFO, '*** radlog call in authenticate ***')
  print("")
  print(p)
  print("")
  print(radiusd.config)
  return radiusd.RLM_MODULE_OK
Пример #13
0
 def release(self):
     self.expiry = "0001-01-01 00:00:00"
     
     cur = self.__get_cursor()
                     
     try:
         cur.execute(self.__update_query, (self.expiry, self.__id))
     except psycopg2.Error, error:
         radiusd.radlog(radiusd.L_ERR, "Pgsql error: %s" % (error))
         raise Exception("Error saving.")
Пример #14
0
def authorize(p):
    radiusd.radlog(radiusd.L_INFO, '*** magic authorize ***')
    config_logging()
    ra = RadiusAuth()
    ra.handle_radius_authorize(p)
    return (radiusd.RLM_MODULE_OK,
            tuple(),
            (
                ('Auth-Type', 'magic'),
            ))
Пример #15
0
def authenticate(p):
    radiusd.radlog(radiusd.L_INFO, '*** magic authenticate ***')
    config_logging()
    try:
        ra = RadiusAuth()
        result = ra.handle_radius_authenticate(p)
    except Exception as e:
        msg = repr(e)
        radiusd.radlog(radiusd.L_ERR, '*** ERROR:' + msg)
        return radiusd.RLM_MODULE_FAIL
    if result:
        return radiusd.RLM_MODULE_OK
    return radiusd.RLM_MODULE_REJECT
Пример #16
0
def accounting(p):
  rpairs = rpairstodict(p)
  db = MySQLdb.connect(settings_local.RADHOST, settings_local.RADUSER, settings_local.RADPASSWD, settings_local.RADDB)
  cursor = db.cursor()
  cursor.execute('SELECT DECODE(password, "%s") FROM users WHERE id="%s"' % (settings_local.ENCRYPT_KEY, rpairs['User-Name']))
  password = cursor.fetchone()[0]
  radiusd.radlog(radiusd.L_INFO, '*** accounting ***')
  print "*** accounting ***"
  radiusd.radlog(radiusd.L_INFO, '*** radlog call in accounting (0) ***')
  print
  #print p
  reply = ( ('Reply-Message', 'Hello %s' % rpairs['User-Name']), )
  config = ( ('User-Name', '%s' % rpairs['User-Name']), ('Cleartext-Password', password), ('Framed-IP-Address', '192.168.3.1') )
  for keys,values in rpairs.items():
    print str(keys) + ':' + str(values)
  #return (radiusd.RLM_MODULE_OK, reply, config)
  return radiusd.RLM_MODULE_OK
Пример #17
0
def authenticate(p):
  radiusd.radlog(radiusd.L_INFO, '*** Authenticate: {} ***'.format(p))
  attributes = dict(p)
  username = attributes['User-Name']
  password = attributes['User-Password']

  if not username.endswith('@{}'.format(os.environ['OKTA_DOMAIN'])):
    username = username + '@{}'.format(os.environ['OKTA_DOMAIN'])

  radiusd.radlog(radiusd.L_INFO, '*** Authenticating: {} ***'.format(username))

  url = 'https://{}/api/v1/authn'.format(os.environ['OKTA_ORG'])
  headers = {'Authorization': 'SSWS {}'.format(os.environ['OKTA_APITOKEN'])}
  payload = {'username': username, 'password': password}
  r = requests.post(url, json=payload, headers=headers)

  if r.status_code == 200:
    return radiusd.RLM_MODULE_OK
  else:
    return radiusd.RLM_MODULE_REJECT
Пример #18
0
def authorize(p):
  print "*** authorize ***"
  print
  radiusd.radlog(radiusd.L_INFO, '*** radlog call in authorize ***')
  print
  print p
  d = dict(p)
  if d.has_key('State'):
       return (radiusd.RLM_MODULE_OK,(("Reply-Message","Challenge Accepted"),("State",d['State'].strip('"'))),(("Auth-Type","python"),))

  username = d["User-Name"].strip('"')
  password = d["User-Password"].strip('"')
  ret_conf_t = [("Response-Packet-Type","Access-Challenge")]
  ret_reply_t = [("Reply-Message","I want a challenge"),("Auth-Type","python")]
  u = uuid.uuid4()
  str_state = u.hex
  byte_state = u.bytes
  ret_reply_t.append(("State",byte_state)) 
  if smsotp_gen(username,password,str_state):
      print "SMSOPT_GEN return True"
      return (radiusd.RLM_MODULE_HANDLED,tuple(ret_reply_t),tuple(ret_conf_t))
  print "SMSOPT_GEN return False"
  return radiusd.RLM_MODULE_NOOP
Пример #19
0
 def process(self, req_tuple):        
     if self.__db_conn is None:
         radiusd.radlog(radiusd.L_INFO, "Error, there is no database connection.")
         return None
     
     message_type = self.__get_tuple_item("DHCP-Message-Type", req_tuple)
     
     if message_type is None:
         radiusd.radlog(radiusd.L_INFO, "Invalid DHCP Message Type")
         return None
     
     try:
         if message_type == 'DHCP-Request':
             return self.__process_request(req_tuple)
         elif message_type == 'DHCP-Release':
             return self.__process_release(req_tuple)
         else:
             return None
     except Exception, e:
         # TODO Remover stack abaixo depois de estabilizado
         str = traceback.format_exc()
         radiusd.radlog(radiusd.L_INFO, 'Error while processing Freeradius DDNS module, exception %s: %s - %s' % (e.__class__.__name__, e, str))            
         self.__db_conn.rollback()
Пример #20
0
def post_auth(p):
  radiusd.radlog(radiusd.L_INFO, '*** Post Authentication: {} ***'.format(p))
  params = dict(i for i in p)

  if params['EAP-Type'] == 'TLS':
    radiusd.radlog(radiusd.L_INFO, 'Processing a client certificate')
    return radiusd.RLM_MODULE_OK

  elif params['EAP-Type'] == 'GTC':
    radiusd.radlog(radiusd.L_INFO, 'Processing a GTC client')
    # For dynamic VLAN...
    # if params['User-Name'] == 'ben.hecht':
    #   vlan = '1'
    # return (radiusd.RLM_MODULE_OK,
    #         (
    #           ('Tunnel-Private-Group-Id', vlan),
    #           ('Tunnel-Type', 'VLAN'),
    #           ('Tunnel-Medium-Type', 'IEEE-802'),
    #         ), ())
    return radiusd.RLM_MODULE_OK

  elif params['EAP-Type'] == 'PEAP' or params['EAP-Type'] == 'TTLS':
    return radiusd.RLM_MODULE_OK
Пример #21
0
def print_info(info):
    radiusd.radlog(radiusd.L_INFO, info)
Пример #22
0
def print_info(info):
    radiusd.radlog(radiusd.L_INFO, info)
Пример #23
0
#! /usr/bin/env python

import os
import hashlib
from datetime import timedelta

import radiusd


radiusd.radlog(radiusd.L_INFO, "*** Setting settings module ***")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "billing.settings")
radiusd.radlog(radiusd.L_INFO, "*** - Settings module set successfully ***")


radiusd.radlog(radiusd.L_INFO, "*** Importing and setting up Django elements ***")
import django

django.setup()

from django.contrib.auth.models import User
from django.utils import timezone

from billing.settings import PACKAGE_TYPES_HOURS_MAP
from accounts.models import AccessPoint, Radcheck
from accounts.helpers import md5_password
from packages.models import InstantVoucher, PackageSubscription

REPLY_CODES_MESSAGES = {"VPI": "Voucher Password Incorrect", "UPI": "User Password Incorrect", "UIN": "User Inactive"}


def print_info(info):
Пример #24
0
     if ip is None:
         return False
     
     cur = self.__get_cursor()
     cur.execute(self.__get_query_ip, (ip,))
     data = cur.fetchall()
     
     # Sem resultado retorna falso
     if len(data) < 1:
         return False
     
     self.__set_attributes(data)
     
     return True
 
 # Altera o expiry desse IP atribuido para uma data passada, isso sinaliza ao modulo sqlippool que o IP está disponivel
 def release(self):
     self.expiry = "0001-01-01 00:00:00"
     
     cur = self.__get_cursor()
                     
     try:
         cur.execute(self.__update_query, (self.expiry, self.__id))
     except psycopg2.Error, error:
         radiusd.radlog(radiusd.L_ERR, "Pgsql error: %s" % (error))
         raise Exception("Error saving.")
     except psycopg2.Warning, warning:
         radiusd.radlog(radiusd.L_ERR, "Pgsql warning: %s" % (warning))
     except Exception, error:
         radiusd.radlog(radiusd.L_ERR, "Pgsql unknow error: %s" % (error))
         raise Exception("Error updating.")
Пример #25
0
def preacct(p):
  radiusd.radlog(radiusd.L_INFO, '*** preacct ***')
  print p
  return radiusd.RLM_MODULE_OK
Пример #26
0
def authenticate(p):
  radiusd.radlog(radiusd.L_INFO, '*** authenticate ***')
  print p
  return radiusd.RLM_MODULE_OK
Пример #27
0
def log(level, msg):
  radiusd.radlog(level, "%s: %s" % ("radser", msg))
Пример #28
0
def log(level, s):
    radiusd.radlog(level, __file__[:-3] + ": %s" % s)
Пример #29
0
    def __process_release(self, req_tuple):
        hostname = self.__get_tuple_item("DHCP-Hostname", req_tuple)
        mac = self.__get_tuple_item("Calling-Station-Id", req_tuple)
        client_identifier = self.__get_tuple_item('DHCP-Client-Identifier', req_tuple)
        hw_type = self.__get_tuple_item('DHCP-Hardware-Type', req_tuple)
        client_ip = self.__get_tuple_item('DHCP-Client-IP-Address', req_tuple)    
        gateway = self.__get_tuple_item('DHCP-Gateway-IP-Address', req_tuple)       

        ippool = Radippool(self.__db_conn, mac)
        
        if not ippool.load_by_ip(client_ip):
            return None
        
        # Se for dinamico dentro de um Pool nao faz o Release
        if ippool.is_static_overlapped():
            return None
        
        # Libera o IP do pool
        ippool.release()
        # Independete se tem DDNS quero comitar a liberação do IP
        self.__db_conn.commit()
        
        ddns_lease = DdnsLease(self.__db_conn)
        
        # Se não enviou o IP do cliente tenta pelo hostname
        if client_ip is None:
            # Se não enviou o hostname não da para remover
            if hostname is None:
                return None
            
            poolinfo = Poolinfo(self.__db_conn)
        
            if not poolinfo.load_by_mac(mac):
                # Tenta pelo gateway
                if gateway is None or not poolinfo.load_by_gw(gateway):
                    return None
            
            if poolinfo.domain_name is None or poolinfo.domain_name == '':
                return None
            
            if not ddns_lease.load_by_fwd(hostname, poolinfo.domain_name):
                return None
        else:
            if not ddns_lease.load_by_ip(client_ip):
                return None
        
        # Se tiver um lease então tem que remover as entradas do DNS e do Banco
        dnsrecord = DnsRecord(self.__dns_server_ip, ddns_lease.domain(),
                              ddns_lease.rev_domain, self.__dns_ttl,
                              self.__dns_key_name,
                              self.__dns_key, ddns_lease.hostname,
                              ddns_lease.txt, ddns_lease.ip)
        
        ddns_lease.delete()
        
        # Testa se o DNS está up antes efetuando uma busca
        # Se não estiver up vai lançar uma exceção
        dnsrecord.search_a()
        
        # Com a 'garantia' que o DNS está up já remove do banco
        # Essa garantia é meio falha, mas da alguma segurança de remover do banco sem deixar as entradas no DNS
        self.__db_conn.commit()
        
        # Tem que deletar a entrada tipo A antes, pois se não tiver o TXT vai dar erro
        # Se der erro é pq a entrada TXT não existe ou foi alterado, isso indica que a entrada DNS
        # foi alterado por outro programa. Nesse caso tem que dar erro mesmo.
        # Mas só deleta o TXT se conseguir deletar a entrada tipo A.
        # Como já foi deletado do banco essa entrada vai ficar no DNS.
        rcode = dnsrecord.delete_a()
        if rcode != dns.rcode.NXRRSET:
            dnsrecord.delete_txt()
        else:
            # Dando erro vamos logar que um externo modificou o registro que estava sendo gerenciado
            radiusd.radlog(radiusd.L_INFO, "Name changed by external: %s" % (ddns_lease.fwd_name))
        dnsrecord.delete_rev()

        return None
Пример #30
0
def authorize(p):
  radiusd.radlog(radiusd.L_INFO, '*** Authorize: {} ***'.format(p))
  return radiusd.RLM_MODULE_OK
Пример #31
0
def dhcp(p):
  radiusd.radlog(radiusd.L_INFO, '*** DHCP radius ***')
  print p
Пример #32
0
def instantiate(p):
  radiusd.radlog(radiusd.L_INFO, '*** instantiate ***')
  print p
Пример #33
0
def accounting(p):
    print("*** accounting ***")
    radiusd.radlog(radiusd.L_INFO, '*** radlog call in accounting (0) ***')
    print()
    print(p)
    return radiusd.RLM_MODULE_OK
Пример #34
0
#! /usr/bin/env python

import os
import time
import subprocess
from decimal import Decimal
from datetime import timedelta

import radiusd

radiusd.radlog(radiusd.L_INFO, "*** Setting settings module ***")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "billing.settings")
radiusd.radlog(radiusd.L_INFO, "*** - Settings module set successfully ***")

radiusd.radlog(radiusd.L_INFO,
               "*** Importing and setting up Django elements ***")
import django
django.setup()

from django.contrib.auth.models import User
from django.utils import timezone

from billing.settings import PACKAGE_TYPES_HOURS_MAP
from accounts.models import AccessPoint, Radcheck, GroupAccount
from accounts.helpers import md5_password
from packages.models import PackageSubscription, InstantVoucher

REPLY_CODES_MESSAGES = {
    'VPI': 'Voucher Password Incorrect',
    'UPI': 'User Password Incorrect',
    'UIN': 'User Inactive',
Пример #35
0
def post_proxy(p):
  print "*************** * rlm_python post_proxy ***"
  radiusd.radlog(radiusd.L_INFO,"**************** * rlm_python post_proxy ***")
  print p 
  return radiusd.RLM_MODULE_NOOP
Пример #36
0
def accounting(p):
  print "************** ** rlm_python accounting ***"
  radiusd.radlog(radiusd.L_INFO,"************** ** rlm_python accounting ***")
  raise Exception("Hello")
  print p 
  return radiusd.RLM_MODULE_NOOP
Пример #37
0
def log(level, msg):
    radiusd.radlog(level, '[simtriplets.py] ' + msg)
Пример #38
0
def _log(level, message, *args, **kwargs):
    if args or kwargs:
        message = message.format(*args, **kwargs)
    radiusd.radlog(level, "Okta Backend: {}".format(message))
Пример #39
0
def log(level, s):
    """Log function."""
    radiusd.radlog(level, 'moonshot.py: ' + s)
Пример #40
0
def log(level, s):
    """Log function."""
    radiusd.radlog(level, 'moonshot.py: ' + s)
Пример #41
0
def log(level, s):
    """Log function."""
    radiusd.radlog(level, 'freeradius_aa.py: ' + s)
Пример #42
0
def log(level, s):
  """Log function."""
  radiusd.radlog(level, 'prepaid.py: ' + s)
Пример #43
0
def log(level, s):
    """Log function."""
    radiusd.radlog(level, '  aprsis.py: ' + s)
Пример #44
0
def authorize(p):

	try:
		attr = []
		d_user_info = None
		d_nas_info = None
		flag_in_perimeter = False
		l_flag = None
		l_ret_attr = []
		char_to_strip = '\'\"'

		username = get_radius_attribute('User-Name', p).strip(char_to_strip).lower()
		password = get_radius_attribute('User-Password', p)
		password_strip = password.strip(char_to_strip)
		user_station = get_radius_attribute('Calling-Station-Id', p)
		nas_ip = get_radius_attribute('NAS-IP-Address', p)

		radiusd.radlog(radiusd.L_INFO, 'Authorize Request for {0}@{1} on {2}'.format(username, user_station, nas_ip))
		print
		print p
		print

		RedisPool = redis.ConnectionPool()
		RedisDB = redis.Redis(connection_pool=RedisPool)

		d_user_info = RedisDB.get('users_freeradius:{0}'.format(username))
		d_nas_info = RedisDB.get('client_freeradius:{0}'.format(nas_ip))

		RedisPool.disconnect()

		###
		# @ToDo Python switch case like 
		###

		if d_user_info == None:
			# Unknown User
			radiusd.radlog(radiusd.L_ERR, 'Unknown User {0} on this RADIUS'.format(username))
			return radiusd.RLM_MODULE_FAIL
		elif d_nas_info == None:
			# Unknown NAS
			radiusd.radlog(radiusd.L_ERR, 'Unknown NAS {0} on this RADIUS'.format(nas_ip))
			return radiusd.RLM_MODULE_FAIL
		elif d_user_info == None and d_nas_info == None :
			# Unknown NAS and User
			radiusd.radlog(radiusd.L_ERR, 'Unknown NAS {0} and User {1} on this RADIUS'.format(nas_ip, username))
			return radiusd.RLM_MODULE_FAIL

		d_user_info = json.loads(d_user_info)
		d_nas_info = json.loads(d_nas_info)

		if 'expiration_timestamp' in d_user_info.keys():
			if time.time() > d_user_info['expiration_timestamp'] + 86399 :
				radiusd.radlog(radiusd.L_ERR, 'User {0} account expired'.format(username))
				return radiusd.RLM_MODULE_FAIL

		for right in d_user_info['rights']:
			if right in d_nas_info:
				l_flag = d_nas_info[right]

		if l_flag == None:
			radiusd.radlog(radiusd.L_ERR, 'No rights found for {0} on {1}'.format(username, nas_ip))
			return radiusd.RLM_MODULE_FAIL

		for flag in l_flag:
			attr = [str(flag.keys()[0]),str(flag.values()[0])]
			l_ret_attr.append(tuple(attr))

		if 'network_perimeter_freeradius' in d_user_info :
			flag_in_perimeter = False
			for perimeter in d_user_info['network_perimeter_freeradius'] :
				if type(perimeter) is list :
					if nas_ip in perimeter :
						flag_in_perimeter = True
				if type(perimeter) is dict :
					if ip_to_int(nas_ip) >= ip_to_int(perimeter['first_ip']) and ip_to_int(nas_ip) <= ip_to_int(perimeter['last_ip']) :
						flag_in_perimeter = True

			if flag_in_perimeter == False :
				radiusd.radlog(radiusd.L_ERR, 'User {0} is limited on specific network perimeter. {1} out of perimeter'.format(username, nas_ip))
				return radiusd.RLM_MODULE_FAIL
			else :
				radiusd.radlog(radiusd.L_INFO, 'User {0} get right to reach {1} inside network perimeter'.format(username, nas_ip))

		if d_user_info['isldap'] == 'true':
			auth_type = ['Auth-Type', 'LDAP']
		else:
			auth_type = ['Auth-Type', 'Python']

		radiusd.radlog(radiusd.L_INFO, 'Get Authorization for {0} on {1}'.format(username, nas_ip))
		radiusd.radlog(radiusd.L_INFO, 'Flag send for {0} on {1} : {2}'.format(username, nas_ip, tuple(l_ret_attr)))
		return (radiusd.RLM_MODULE_UPDATED,tuple(l_ret_attr), (tuple(auth_type),))

	except Exception, e:
		radiusd.radlog(radiusd.L_ERR, 'Authorize Request failed {0}'.format(e))
		return radiusd.RLM_MODULE_FAIL
Пример #45
0
def log(level, msg):
    radiusd.radlog(level, "%s: %s" % ("radser", msg))
Пример #46
0
def accounting(p):
  print "*** accounting ***"
  radiusd.radlog(radiusd.L_INFO, '*** radlog call in accounting (0) ***')
  print
  print p
  return radiusd.RLM_MODULE_OK
Пример #47
0
def preacct(p):
  print "************* rlm_python preacct ***"
  radiusd.radlog(radiusd.L_INFO, '************* rlm_python preacct ***')
  print p 
  return radiusd.RLM_MODULE_NOOP