Beispiel #1
0
 def authorize(self, username, domain, macaddr, nasaddr, vlanid1, vlanid2, textinfo=None):
     """send radius auth request
     :param username: not contain @doamin
     :param domain:
     :param macaddr:
     :param nasaddr:
     :param vlanid1:
     :param vlanid2:
     :param textinfo:
     """
     try:
         nas = yield self.get_nas(nasaddr)
         nonce = str(time.time())
         sign = self.make_sign(nas.get("api_secret"), [username, domain, macaddr, nasaddr, vlanid1, vlanid2, textinfo, nonce])
         apiurl = nas and nas.get("api_auth_url") or None
         reqdata = json.dumps(dict(
             username=username,
             domain=safestr(domain),
             macaddr=safestr(macaddr),
             nasaddr=nasaddr,
             vlanid1=vlanid1,
             vlanid2=vlanid2,
             textinfo=safestr(textinfo),
             nonce=nonce,
             sign=sign
         ), ensure_ascii=False)
         resp = yield self.send(apiurl, reqdata, nas.get("api_secret"))
         defer.returnValue(resp)
     except Exception as err:
         self.log.msg(u"[HttpClient] ::::::: authorize failure,%s" % safestr(err.message))
         defer.returnValue(dict(code=1, msg=u"authorize error, please see log detail"))
Beispiel #2
0
    def logger(self, nasaddr=None, content=None, level='info'):
        """
        send logger to logserver
        :param nasaddr:
        :param content:
        """
        nas = yield self.redb.get_nas(nasaddr)
        apiurl = nas and nas.get("api_logger_url") or self.config.defaults.get("log_server")
        if apiurl:
            if self.config.defaults.debug:
                log.msg("[HttpClient] ::::::: Send log Request to {0}, {1}".format(safestr(apiurl), safestr(content)))

            content = safestr(content)
            nonce = str(time.time())
            _datetime = get_currtime()
            sign = self.make_sign([nasaddr, content, _datetime, nonce], nas.get("api_secret"))
            reqdata = json.dumps(dict(
                nasaddr=nasaddr,
                content=content,
                datetime=_datetime,
                nonce=nonce,
                sign=sign
            ), ensure_ascii=False)

            headers = {"Content-Type": ["text/plain;charset=utf-8"]}
            resp = yield requests.post(safestr(apiurl), data=reqdata, headers=headers)
            log.msg("[HttpClient] ::::::: Received Resp {0}, Send log done".format(resp.code))
        else:
            log.msg("[HttpClient] ::::::: Not send, {0}".format(safestr(content)))
Beispiel #3
0
 def make_sign(self, params=[]):
     _params = [utils.safestr(p) for p in params if p is not None]
     _params.sort()
     _params.insert(0, self.settings.api_secret)
     strs = utils.safestr(''.join(_params))
     mds = md5(strs).hexdigest()
     return mds.upper()
Beispiel #4
0
    def post(self):
        try:
            req_msg = json.loads(self.request.body)
            if not self.check_sign(self.settings.api_secret, req_msg):
                log.msg("[api debug] nas delete request sign error")
                self.render_json(code=1, msg="sign error")
                return
        except Exception as err:
            log.err("parse params error %s" % safestr(err))
            self.render_json(code=1, msg="parse params error")
            return

        ipaddr = req_msg.get("ipaddr")
        if not validate.is_ip.valid(ipaddr):
            self.render_json(code=1, msg="ipaddr {0} format error,{1}".format(ipaddr, validate.is_ip.msg))
            return

        try:
            yield self.redb.delete(self.redb.nas_pkey(ipaddr))
            result = dict(code=0, msg="success")
        except Exception as err:
            log.err("delete nasdata from database error  %s" % safestr(err))
            result = dict(code=1, msg="delete nasdata {0} from database error".format(ipaddr))

        self.render_json(**result)
Beispiel #5
0
    def post(self):
        try:
            req_msg = json.loads(self.request.body)
            if not self.check_sign(self.settings.api_secret, req_msg):
                log.msg("[api debug] nas delete request sign error")
                self.render_json(code=1, msg='sign error')
                return
        except Exception as err:
            log.err('parse params error %s' % safestr(err))
            self.render_json(code=1, msg='parse params error')
            return

        ipaddr = req_msg.get('ipaddr')
        if not validate.is_ip.valid(ipaddr):
            self.render_json(code=1,
                             msg="ipaddr {0} format error,{1}".format(
                                 ipaddr, validate.is_ip.msg))
            return

        try:
            yield self.redb.delete(self.redb.nas_pkey(ipaddr))
            result = dict(code=0, msg='success')
        except Exception as err:
            log.err('delete nasdata from database error  %s' % safestr(err))
            result = dict(
                code=1,
                msg='delete nasdata {0} from database error'.format(ipaddr))

        self.render_json(**result)
Beispiel #6
0
    def send(self,apiurl,reqdata,secret):
        """ send radius request
        :param apiurl: oss server api
        :param reqdata: json data
        """
        try:
            if self.config.defaults.debug:
                log.msg("[HttpClient] ::::::: Send http request to {0}, {1}".format(safestr(apiurl),safestr(reqdata)))

            headers = {"Content-Type": ["application/json;charset=utf-8"]}
            resp = yield requests.post(safestr(apiurl), data=reqdata, headers=headers)
            resp_json = yield resp.json()

            if self.config.defaults.debug:
                log.msg("[HttpClient] ::::::: Received http response from {0}, {1}".format(safestr(apiurl), safestr(resp_json)))

            if resp.code != 200:
                defer.returnValue(dict(code=1, msg=u'server return error http status code {0}'.format(resp.code)))
            else:
                result = resp_json
                if not self.check_sign(secret, result):
                    defer.returnValue(dict(code=1, msg=u"sign error"))
                else:
                    defer.returnValue(result)
        except Exception as err:
            import traceback
            traceback.print_exc()
            defer.returnValue(dict(code=1, msg=u'server error'))
Beispiel #7
0
 def make_sign(self, secret, params=[]):
     """ make sign
     :param secret:
     :param params: params list
     :return: :rtype:
     """
     _params = [safestr(p) for p in params if p is not None]
     _params.sort()
     _params.insert(0, secret)
     strs = safestr(''.join(_params))
     mds = md5(strs).hexdigest()
     return mds.upper()
Beispiel #8
0
 def make_sign(self, secret, params=[]):
     """ make sign
     :param params: params list
     :return: :rtype:
     """
     _params = [utils.safestr(p) for p in params if p is not None]
     _params.sort()
     _params.insert(0, secret)
     strs = ''.join(_params)
     # if self.settings.debug:
     #     log.msg("sign_src = %s" % strs, level=logging.DEBUG)
     mds = md5(utils.safestr(strs)).hexdigest()
     return mds.upper()
Beispiel #9
0
 def make_sign(self, secret, params=[]):
     """ make sign
     :param params: params list
     :return: :rtype:
     """
     _params = [utils.safestr(p) for p in params if p is not None]
     _params.sort()
     _params.insert(0, secret)
     strs = ''.join(_params)
     # if self.settings.debug:
     #     log.msg("sign_src = %s" % strs, level=logging.DEBUG)
     mds = md5(utils.safestr(strs)).hexdigest()
     return mds.upper()
Beispiel #10
0
 def make_sign(self, secret, params=[]):
     """ make sign
     :param secret:
     :param params: params list
     :return: :rtype:
     """
     _params = [safestr(p) for p in params if p is not None]
     _params.sort()
     _params.insert(0, secret)
     strs = safestr(''.join(_params))
     # if self.config.defaults.debug:
     #     self.log.info("[HttpClient] ::::::: sign_src = %s" % strs)
     mds = md5(strs).hexdigest()
     return mds.upper()
Beispiel #11
0
 def make_sign(self, secret, params=[]):
     """ make sign
     :param secret:
     :param params: params list
     :return: :rtype:
     """
     _params = [safestr(p) for p in params if p is not None]
     _params.sort()
     _params.insert(0, secret)
     strs = safestr(''.join(_params))
     # if self.config.defaults.debug:
     #     log.msg("[HttpClient] ::::::: sign_src = %s" % strs, level=logging.DEBUG)
     mds = md5(strs).hexdigest()
     return mds.upper()
Beispiel #12
0
    def processPacket(self, req, bas=None):
        """process radius packet
        :param req:
        :return: :rtype:
        :raise PacketError:
        """
        if req.code != packet.AccessRequest:
            raise PacketError(
                'non-AccessRequest packet on authentication socket')

        reply = req.CreateReply()
        reply.source = req.source

        aaa_resp = yield self.radapi.authorize(*req.get_authorize_msg())

        if aaa_resp['code'] > 0:
            reply['Reply-Message'] = aaa_resp['msg']
            reply.code = packet.AccessReject
            defer.returnValue(reply)

        if 'bypass' in aaa_resp and aaa_resp['bypass'] == 1:
            is_pwd_ok = True
        else:
            is_pwd_ok = req.is_valid_pwd(aaa_resp.get('passwd'))

        if not is_pwd_ok:
            reply['Reply-Message'] = "password not match"
            reply.code = packet.AccessReject
            defer.returnValue(reply)
        else:
            if "input_rate" in aaa_resp and 'output_rate' in aaa_resp:
                rate_process.process(reply,
                                     input_rate=aaa_resp['input_rate'],
                                     output_rate=aaa_resp['output_rate'])

            attrs = aaa_resp.get("attrs") or {}
            for attr_name in attrs:
                try:
                    # todo: May have a type matching problem
                    reply.AddAttribute(utils.safestr(attr_name),
                                       attrs[attr_name])
                except Exception as err:
                    errstr = "RadiusError:current radius cannot support attribute {0},{1}".format(
                        attr_name, utils.safestr(err.message))
                    self.log.error(errstr)

        reply['Reply-Message'] = 'success!'
        reply.code = packet.AccessAccept
        defer.returnValue(reply)
Beispiel #13
0
    def authorize(self,
                  username,
                  domain,
                  macaddr,
                  nasaddr,
                  vlanid1,
                  vlanid2,
                  textinfo=None):
        """send radius auth request
        :param username: not contain @doamin
        :param domain:
        :param macaddr:
        :param nasaddr:
        :param vlanid1:
        :param vlanid2:
        :param textinfo:
        """
        _start = time.clock()
        try:
            _reqdata = dict(username=username,
                            domain=safestr(domain),
                            macaddr=safestr(macaddr),
                            nasaddr=nasaddr,
                            vlanid1=vlanid1,
                            vlanid2=vlanid2,
                            textinfo=safestr(textinfo))
            reqdata = apiutils.make_request(self.config.api.api_secret,
                                            _reqdata)
            if self.protocol == 'http':
                resp = yield self.send_http(self.api_auth_url, reqdata)
                self.log.info("[http authorize cast:%.6f second]" %
                              (time.clock() - _start))
                defer.returnValue(resp)
            elif self.protocol == 'zmq':
                resp = yield self.send_zmq('authorize', reqdata)
                self.log.info("[zmq authorize cast:%.6f second]" %
                              (time.clock() - _start))
                defer.returnValue(resp)
            else:
                defer.returnValue(dict(code=1, msg=u"not support"))

        except Exception as err:
            import traceback
            traceback.print_exc()
            self.log.error(u"[ApiClient] :: authorize failure,%s" %
                           safestr(err.message))
            defer.returnValue(
                dict(code=1, msg=u"authorize error, please see log detail"))
Beispiel #14
0
    def get_nas(self, nasaddr, nas_identify=None):
        _start = time.clock()
        cache_key = "toughengine.get_nas.{0}".format(nasaddr)
        if cache_key in self.cache.cache:
            log.msg("[get_nas cast:%.6f second (hit cache)]" %
                    (time.clock() - _start))
            defer.returnValue(self.cache.get(cache_key))

        api_url = self.config.api.api_url
        if not api_url:
            raise ValueError("api_url is None")

        try:
            _reqdata = dict(
                nasaddr=nasaddr,
                nas_identify=nas_identify,
            )
            reqdata = apiutils.make_request(self.config.api.api_secret,
                                            _reqdata)
            resp = yield self.send_http("%s/nas/fetch" % api_url, reqdata)
            if resp['code'] == 0:
                self.cache.set(cache_key, resp, expire=120)
            self.log.info("[init_nas cast:%.6f second]" %
                          (time.clock() - _start))
            defer.returnValue(resp)
        except Exception as err:
            import traceback
            traceback.print_exc()
            self.log.error(u"[HttpClient] :: fetch nas failure,%s" %
                           safestr(err.message))
            defer.returnValue(
                dict(code=1, msg=u"fetch nas error, please see log detail"))
Beispiel #15
0
    def send_zmq(self, rtype, reqdata):
        """ send radius request
        :param rtype: radius msg type
        :param reqdata: json data
        """
        try:
            if self.config.defaults.debug:
                self.log.debug("[ZmqClient] :: Send zmq request {0}".format(
                    safestr(reqdata)))

            resp = None
            if rtype == 'authorize':
                resp = yield self.zauth_conn.sendMsg(reqdata, timeout=15.0)
            elif rtype == 'accounting':
                resp = yield self.zacct_conn.sendMsg(reqdata, timeout=15.0)
            else:
                defer.returnValue(
                    dict(code=1, msg=u"not support radius msg type"))

            if self.config.defaults.debug:
                self.log.debug(
                    "[ZmqClient] :: Received zmq response {0}".format(
                        safeunicode(resp)))

            result = json.loads(resp[0])
            if not apiutils.check_sign(self.config.api.api_secret, result):
                defer.returnValue(dict(code=1, msg=u"zmq msg sign error"))

            defer.returnValue(result)
        except Exception as err:
            import traceback
            traceback.print_exc()
            defer.returnValue(dict(code=1, msg=u'server error'))
Beispiel #16
0
    def post(self):
        """ authorize post
        :return: :rtype:
        """
        try:
            req_msg = self.parse_request()
        except Exception as err:
            self.render_json(msg=safestr(err.message))
            return

        result = dict(
            code=0,
            msg=u'success',
            username=req_msg['username'],
            passwd='123456',
            input_rate=4194304,
            output_rate=4194304,
            attrs={
                "Session-Timeout": 3600,
                "Acct-Interim-Interval": 300
            }
        )

        sign = self.make_sign(self.settings.api_secret,result.values())
        result['sign'] = sign
        self.render_json(**result)
Beispiel #17
0
    def accounting(self,req_type,username, session_id, session_time,session_timeout,macaddr,nasaddr,ipaddr,
                   input_octets,output_octets,input_pkts,output_pkts, textinfo=None):
        """send radius accounting request
        :param req_type: 1 Start 2 Stop 3 Alive
        :param username:
        :param session_id:
        :param session_time:
        :param session_timeout:
        :param macaddr:
        :param nasaddr:
        :param ipaddr:
        :param input_octets:
        :param output_octets:
        :param input_pkts:
        :param output_pkts:
        :param textinfo:
        """
        try:
            nas = yield self.get_nas(nasaddr)
            nonce = str(time.time())
            sign = self.make_sign(nas.get("api_secret"), [req_type, username, session_id, session_time, session_timeout, macaddr, nasaddr, ipaddr,
                                input_octets, output_octets, input_pkts, output_pkts,nonce])

            apiurl = nas and nas.get("api_acct_url") or None
            reqdata = json.dumps(dict(
                req_type=req_type,
                username=username,
                session_id=session_id,
                session_time=session_time,
                session_timeout=session_timeout,
                macaddr=macaddr,
                nasaddr=nasaddr,
                ipaddr=ipaddr,
                input_octets=input_octets,
                output_octets=output_octets,
                input_pkts=input_pkts,
                output_pkts=output_pkts,
                textinfo=safestr(textinfo),
                nonce=nonce,
                sign=sign
            ), ensure_ascii=False)
            resp = yield self.send(apiurl, reqdata, nas.get("api_secret"))
            defer.returnValue(resp)
        except Exception as err:
            self.log.msg(u"[HttpClient] ::::::: accounting failure,%s" % safestr(err.message))
            defer.returnValue(dict(code=1, msg=u"accounting error, please see log detail"))
Beispiel #18
0
 def valid(self, value):
     if self.rexp:
         return bool(self.rexp.match(safestr(value)))
     if self.test:
         try:
             return self.test(value)
         except:
             return False
Beispiel #19
0
 def valid(self, value):
     if self.rexp:
         return bool(self.rexp.match(safestr(value)))
     if self.test:
         try:
             return self.test(value)
         except:
             return False
Beispiel #20
0
 def process_delay(self):
     while self.auth_delay.delay_len() > 0:
         try:
             reject = self.auth_delay.get_delay_reject(0)
             if (datetime.datetime.now() - reject.created).seconds < self.auth_delay.reject_delay:
                 return
             else:
                 self.reply(self.auth_delay.pop_delay_reject())
         except Exception as err:
             self.log.error('RadiusError:process_delay error,{0}'.format(utils.safestr(err)))
Beispiel #21
0
 def authorize(self,
               username,
               domain,
               macaddr,
               nasaddr,
               vlanid1,
               vlanid2,
               textinfo=None):
     """send radius auth request
     :param username: not contain @doamin
     :param domain:
     :param macaddr:
     :param nasaddr:
     :param vlanid1:
     :param vlanid2:
     :param textinfo:
     """
     try:
         nas = yield self.redb.get_nas(nasaddr)
         nonce = str(time.time()),
         sign = self.make_sign([
             username, domain, macaddr, nasaddr, vlanid1, vlanid2, textinfo,
             nonce
         ], nas.get("api_secret"))
         apiurl = nas and nas.get("api_auth_url") or None
         reqdata = json.dumps(dict(username=username,
                                   domain=safestr(domain),
                                   macaddr=safestr(macaddr),
                                   nasaddr=nasaddr,
                                   vlanid1=vlanid1,
                                   vlanid2=vlanid2,
                                   textinfo=safestr(textinfo),
                                   nonce=nonce,
                                   sign=sign),
                              ensure_ascii=False)
         resp = yield self.send(apiurl, reqdata, nas.get("api_secret"))
         defer.returnValue(resp)
     except Exception as err:
         log.msg(u"[HttpClient] ::::::: authorize failure,%s" %
                 safestr(err.message))
         defer.returnValue(
             dict(code=1, msg=u"authorize error, please see log detail"))
Beispiel #22
0
    def processPacket(self, req):
        """process radius packet
        :param req:
        :return: :rtype:
        :raise PacketError:
        """

        self.redb.stat_incr('auth_all')
        if req.code != packet.AccessRequest:
            self.redb.stat_incr('auth_drop')
            raise PacketError('non-AccessRequest packet on authentication socket')

        reply = req.CreateReply()
        reply.source = req.source

        aaa_resp = yield self.radapi.authorize(*req.get_authorize_msg())

        if aaa_resp['code'] > 0:
            self.send_reject(req, reply, aaa_resp['msg'])
            return

        if 'bypass' in aaa_resp and aaa_resp['bypass'] == 1:
            is_pwd_ok = True
        else:
            is_pwd_ok = req.is_valid_pwd(aaa_resp.get('passwd'))

        if not is_pwd_ok:
            self.send_reject(req, reply, aaa_resp['msg'])
        else:
            if "input_rate" in aaa_resp and 'output_rate' in aaa_resp:
                rate_process.process(reply, input_rate=aaa_resp['input_rate'], output_rate=aaa_resp['output_rate'])

            attrs = aaa_resp.get("attrs") or {}
            for attr_name in attrs:
                try:
                    reply.AddAttribute(utils.safestr(attr_name),attrs[attr_name])
                except Exception as err:
                    errstr = "RadiusError:current radius cannot support attribute {0},{1}".format(
                        attr_name,utils.safestr(err.message))
                    self.radapi.logger(nasaddr=req.source[0],content=errstr, level='error')

            self.send_accept(req, reply)
Beispiel #23
0
    def post(self):
        try:
            req_msg = self.parse_request()
        except Exception as err:
            self.render_json(msg=utils.safestr(err.message))
            return

        _data = self.test_nas.copy()
        _sign = self.make_sign(self.settings.api_secret,_data.values())
        _data['sign'] = _sign
        self.render_json(**_data)
Beispiel #24
0
    def parse_request(self):
        try:
            msg_src = self.request.body
            req_msg = json.loads(msg_src)
        except Exception as err:
            self.log.error('parse params error %s' % utils.safestr(err))
            raise ValueError("parse params error")

        if not self.check_sign(req_msg):
            raise ValueError("message sign error")

        return req_msg
Beispiel #25
0
    def parse_request(self):
        try:
            msg_src = self.request.body
            req_msg = json.loads(msg_src)
        except Exception as err:
            self.log.error('parse params error %s' % utils.safestr(err))
            raise ValueError("parse params error")

        if not self.check_sign(self.settings.config.radiusd.key, req_msg):
            raise ValueError("message sign error")

        return req_msg
Beispiel #26
0
    def post(self):
        try:
            req_msg = json.loads(self.request.body)
            if not self.check_sign(self.settings.api_secret, req_msg):
                log.msg("[api debug] nas list request sign error")
                self.render_json(code=1, msg="sign error")
                return
        except Exception as err:
            log.err("parse params error %s" % safestr(err))
            self.render_json(code=1, msg="parse params error")
            return

        nas_list = yield self.redb.list_nas()
        self.render_json(code=0, msg="success", nas_list=nas_list)
Beispiel #27
0
    def parse_request(self):
        try:
            msg_src = self.request.body
            # if self.settings.debug:
            #     self.log.msg("[api debug] :::::::: (%s) request body : %s" % (self.request.path, utils.safestr(msg_src)))
            req_msg = json.loads(msg_src)
        except Exception as err:
            self.log.error('parse params error %s' % utils.safestr(err))
            raise ValueError("parse params error")

        if not self.check_sign(self.settings.api_secret, req_msg):
            raise ValueError("message sign error")

        return req_msg
Beispiel #28
0
    def post(self):
        try:
            req_msg = json.loads(self.request.body)
            if not self.check_sign(self.settings.api_secret, req_msg):
                log.msg("[api debug] nas list request sign error")
                self.render_json(code=1, msg='sign error')
                return
        except Exception as err:
            log.err('parse params error %s' % safestr(err))
            self.render_json(code=1, msg='parse params error')
            return

        nas_list = yield self.redb.list_nas()
        self.render_json(code=0, msg='success', nas_list=nas_list)
Beispiel #29
0
    def send_http(self, apiurl, reqdata):
        """ send radius request
        :param apiurl: oss server api
        :param reqdata: json data
        """
        try:
            if self.config.defaults.debug:
                self.log.debug(
                    "[HttpClient] :: Send http request to {0}, {1}".format(
                        safestr(apiurl), safeunicode(reqdata)))

            headers = {"Content-Type": ["application/json;charset=utf-8"]}
            resp = yield requests.post(safestr(apiurl),
                                       data=reqdata,
                                       headers=headers)

            if resp.code != 200:
                defer.returnValue(
                    dict(
                        code=1,
                        msg=u'server return error http status code {0}'.format(
                            resp.code)))
            else:
                result = yield resp.json()
                if self.config.defaults.debug:
                    self.log.debug(
                        "[HttpClient] :: Received http response from {0}, {1}".
                        format(safestr(apiurl), safeunicode(result)))
                if result.get('code') == 0 and not apiutils.check_sign(
                        self.config.api.api_secret, result):
                    defer.returnValue(dict(code=1, msg=u"sign error"))
                else:
                    defer.returnValue(result)
        except Exception as err:
            import traceback
            traceback.print_exc()
            defer.returnValue(dict(code=1, msg=u'server error'))
Beispiel #30
0
    def logger(self, nasaddr=None, content=None, level='info'):
        """
        send logger to logserver
        :param nasaddr:
        :param content:
        """
        nas = yield self.redb.get_nas(nasaddr)
        apiurl = nas and nas.get("api_logger_url") or self.config.defaults.get(
            "log_server")
        if apiurl:
            if self.config.defaults.debug:
                log.msg(
                    "[HttpClient] ::::::: Send log Request to {0}, {1}".format(
                        safestr(apiurl), safestr(content)))

            content = safestr(content)
            nonce = str(time.time())
            _datetime = get_currtime()
            sign = self.make_sign([nasaddr, content, _datetime, nonce],
                                  nas.get("api_secret"))
            reqdata = json.dumps(dict(nasaddr=nasaddr,
                                      content=content,
                                      datetime=_datetime,
                                      nonce=nonce,
                                      sign=sign),
                                 ensure_ascii=False)

            headers = {"Content-Type": ["text/plain;charset=utf-8"]}
            resp = yield requests.post(safestr(apiurl),
                                       data=reqdata,
                                       headers=headers)
            log.msg(
                "[HttpClient] ::::::: Received Resp {0}, Send log done".format(
                    resp.code))
        else:
            log.msg("[HttpClient] ::::::: Not send, {0}".format(
                safestr(content)))
Beispiel #31
0
    def accounting(self, req_type, username, session_id, session_time,
                   session_timeout, macaddr, nasaddr, ipaddr, input_octets,
                   output_octets, input_pkts, output_pkts):
        """send radius accounting request
        :param req_type: 1 Start 2 Stop 3 Alive
        :param username:
        :param session_id:
        :param session_time:
        :param session_timeout:
        :param macaddr:
        :param nasaddr:
        :param ipaddr:
        :param input_octets:
        :param output_octets:
        :param input_pkts:
        :param output_pkts:
        """
        try:
            nas = yield self.redb.get_nas(nasaddr)
            nonce = str(time.time()),
            sign = self.make_sign([
                username, session_id, session_time, session_timeout, macaddr,
                nasaddr, ipaddr, input_octets, output_octets, input_pkts,
                output_pkts, nonce
            ], nas.get("api_secret"))

            apiurl = nas and nas.get("api_acct_url") or None
            reqdata = json.dumps(dict(req_type=req_type,
                                      username=username,
                                      session_id=session_id,
                                      session_time=session_time,
                                      session_timeout=session_timeout,
                                      macaddr=macaddr,
                                      nasaddr=nasaddr,
                                      ipaddr=ipaddr,
                                      input_octets=input_octets,
                                      output_octets=output_octets,
                                      input_pkts=input_pkts,
                                      output_pkts=output_pkts,
                                      nonce=nonce,
                                      sign=sign),
                                 ensure_ascii=False)
            resp = yield self.send(apiurl, reqdata, nas.get("api_secret"))
            defer.returnValue(resp)
        except Exception as err:
            log.msg(u"[HttpClient] ::::::: accounting failure,%s" %
                    safestr(err.message))
            defer.returnValue(
                dict(code=1, msg=u"accounting error, please see log detail"))
Beispiel #32
0
    def post(self):
        try:
            req_msg = json.loads(self.request.body)
            if not self.check_sign(self.settings.api_secret, req_msg):
                log.msg("[api debug] nas query request sign error")
                self.render_json(code=1, msg="sign error")
                return
        except Exception as err:
            log.err("parse params error %s" % safestr(err))
            self.render_json(code=1, msg="parse params error")
            return

        ipaddr = req_msg.get("ipaddr")
        if not validate.is_ip.valid(ipaddr):
            self.render_json(code=1, msg="ipaddr {0} format error,{1}".format(ipaddr, validate.is_ip.msg))
            return

        nas = yield self.redb.get_nas(ipaddr)
        self.render_json(code=0, msg="success", **nas)
Beispiel #33
0
    def post(self):
        """ accounting post
        :return: :rtype:
        """
        try:
            req_msg = self.parse_request()
        except Exception as err:
            self.render_json(msg=safestr(err.message))
            return

        result = dict(
            code=0,
            msg=u'success',
            username=req_msg['username']
        )

        sign = self.make_sign(self.settings.api_secret,result.values())
        result['sign'] = sign
        self.render_json(**result)
Beispiel #34
0
    def post(self):
        try:
            req_msg = json.loads(self.request.body)
            if not self.check_sign(self.settings.api_secret, req_msg):
                log.msg("[api debug] nas query request sign error")
                self.render_json(code=1, msg='sign error')
                return
        except Exception as err:
            log.err('parse params error %s' % safestr(err))
            self.render_json(code=1, msg='parse params error')
            return

        ipaddr = req_msg.get('ipaddr')
        if not validate.is_ip.valid(ipaddr):
            self.render_json(code=1,
                             msg="ipaddr {0} format error,{1}".format(
                                 ipaddr, validate.is_ip.msg))
            return

        nas = yield self.redb.get_nas(ipaddr)
        self.render_json(code=0, msg='success', **nas)
Beispiel #35
0
    def get_nas(self, nasaddr):
        nas_fetch_url = "%s/nas/fetch" % self.config.api.apiurl
        nas_fetch_secret = self.config.api.apikey
        if not nas_fetch_url:
            raise ValueError("nas_fetch_url is None")

        try:
            nonce = str(time.time())
            sign = self.make_sign(nas_fetch_secret,params=[nasaddr, nonce])
            reqdata = json.dumps(dict(
                nasaddr=nasaddr,
                nonce=nonce,
                sign=sign
            ), ensure_ascii=False)
            resp = yield self.send(nas_fetch_url, reqdata, nas_fetch_secret)
            self.log.info("query nas data %s" % repr(resp))
            defer.returnValue(resp)
        except Exception as err:
            import traceback
            traceback.print_exc()
            self.log.error(u"[HttpClient] ::::::: fetch nas failure,%s" % safestr(err.message))
            defer.returnValue(dict(code=1, msg=u"fetch nas error, please see log detail"))
Beispiel #36
0
 def on_exception(self, err):
     self.radapi.logger(content=u'RadiusError:Packet process error,{0}'.format(utils.safestr(err)), level='error')
Beispiel #37
0
 def on_exception(self, err):
     self.log.error('RadiusError:Packet process error,{0}'.format(utils.safestr(err)))
Beispiel #38
0
 def preProcessPacket(bas):
     if not bas:
         self.log.info('[Radiusd] ::::::: Dropping packet from unknown host ' + host)
     secret, vendor_id = bas['secret'], bas['vendor_id']
     try:
         _packet = self.createPacket(packet=datagram, dict=self.dict, secret=six.b(str(secret)),
                                     vendor_id=vendor_id)
         _packet.deferred.addCallbacks(self.reply, self.on_exception)
         _packet.source = (host, port)
         self.log.info("[Radiusd] ::::::: Received radius request: %s" % (str(_packet)))
         if self.config.defaults.debug:
             self.log.info(_packet.format_str())
         proc_deferd = self.processPacket(_packet)
         proc_deferd.addCallbacks(self.on_process_done, self.on_exception)
     except packet.PacketError as err:
         errstr = 'RadiusError:Dropping invalid packet from {0} {1},{2}'.format(host, port, utils.safestr(err))
         self.log.error(errstr)
Beispiel #39
0
def post(url, data=None, **kwargs):
    return treq.post(url,
                     data=safestr(data),
                     pool=pool,
                     data_to_body_producer=StringProducer,
                     **kwargs)
Beispiel #40
0
def post(url,data=None,**kwargs):
    return treq.post(url, data=safestr(data), pool=pool,data_to_body_producer=StringProducer,**kwargs)
Beispiel #41
0
    def post(self):
        try:
            req_msg = json.loads(self.request.body)
            if not self.check_sign(self.settings.api_secret, req_msg):
                log.msg("[api debug] nas add request sign error")
                self.render_json(code=1, msg='sign error')
                return
        except Exception as err:
            log.err('parse params error %s' % safestr(err))
            self.render_json(code=1, msg='parse params error')
            return

        try:
            ipaddr = req_msg['ipaddr']
            secret = req_msg['secret']
            vendor_id = int(req_msg['vendor_id'])
            coa_port = int(req_msg.get("coa_port", 3799))
            api_secret = req_msg["api_secret"]
            api_auth_url = req_msg["api_auth_url"]
            api_acct_url = req_msg["api_acct_url"]
            api_logger_url = req_msg["api_logger_url "]

            if not validate.is_ip.valid(ipaddr):
                raise ValueError("ipaddr {0} format error,{1}".format(
                    ipaddr, validate.is_ip.msg))

            if not validate.not_null.valid(secret):
                raise ValueError("secret {0} format error,{1}".format(
                    secret, validate.not_null.msg))

            if not validate.not_null.valid(vendor_id):
                raise ValueError("vendor_id {0} format error,{1}".format(
                    vendor_id, validate.not_null.msg))

            if not validate.is_number.valid(coa_port):
                raise ValueError("cao_port {0} format error,{1}".format(
                    coa_port, validate.is_number.msg))

            if not validate.not_null.valid(api_secret):
                raise ValueError("api_secret {0} format error,{1}".format(
                    api_secret, validate.not_null.msg))

            if not validate.is_url.valid(api_auth_url):
                raise ValueError("api_auth_url {0} format error,{1}".format(
                    api_auth_url, validate.is_url.msg))

            if not validate.is_url.valid(api_acct_url):
                raise ValueError("api_acct_url {0} format error,{1}".format(
                    api_acct_url, validate.is_url.msg))

            if api_logger_url and not validate.is_url.valid(api_logger_url):
                raise ValueError("api_logger_url {0} format error,{1}".format(
                    api_logger_url, validate.is_url.msg))

        except Exception as err:
            log.err('verify params error %s' % safestr(err))
            self.render_json(code=1, msg='verify params error')
            return

        nasdata = dict(ipaddr=ipaddr,
                       secret=secret,
                       vendor_id=vendor_id,
                       coa_port=coa_port,
                       api_secret=api_secret,
                       api_auth_url=api_auth_url,
                       api_acct_url=api_acct_url,
                       api_logger_url=api_logger_url)

        try:
            yield self.redb.set_nas(ipaddr, nasdata)
            result = dict(code=0, msg='success')
        except Exception as err:
            log.err('insert nasdata to database error  %s' % safestr(err))
            result = dict(code=1, msg='insert nasdata to database error')

        self.render_json(**result)
Beispiel #42
0
 def accounting(self,
                req_type,
                username,
                session_id,
                session_time,
                session_timeout,
                macaddr,
                nasaddr,
                ipaddr,
                input_octets,
                output_octets,
                input_pkts,
                output_pkts,
                nas_port,
                event_timestamp,
                nas_port_type,
                nas_port_id,
                textinfo=None):
     """send radius accounting request
     :param req_type: 1 Start 2 Stop 3 Alive
     :param username:
     :param session_id:
     :param session_time:
     :param session_timeout:
     :param macaddr:
     :param nasaddr:
     :param ipaddr:
     :param input_octets:
     :param output_octets:
     :param input_pkts:
     :param output_pkts:
     :param textinfo:
     """
     _start = time.clock()
     try:
         _reqdata = dict(req_type=req_type,
                         username=username,
                         session_id=session_id,
                         session_time=session_time,
                         session_timeout=session_timeout,
                         macaddr=macaddr,
                         nasaddr=nasaddr,
                         ipaddr=ipaddr,
                         input_octets=input_octets,
                         output_octets=output_octets,
                         input_pkts=input_pkts,
                         output_pkts=output_pkts,
                         nas_port=nas_port,
                         event_timestamp=event_timestamp,
                         nas_port_type=nas_port_type,
                         nas_port_id=nas_port_id,
                         textinfo=safestr(textinfo))
         reqdata = apiutils.make_request(self.config.api.api_secret,
                                         _reqdata)
         if self.protocol == 'http':
             resp = yield self.send_http(self.api_acct_url, reqdata)
             self.log.info("[http accounting cast:%.6f second]" %
                           (time.clock() - _start))
             defer.returnValue(resp)
         elif self.protocol == 'zmq':
             resp = yield self.send_zmq('accounting', reqdata)
             self.log.info("[zmq accounting cast:%.6f second]" %
                           (time.clock() - _start))
             defer.returnValue(resp)
         else:
             defer.returnValue(dict(code=1, msg=u"not support"))
     except Exception as err:
         self.log.error(u"[HttpClient] :: accounting failure,%s" %
                        safestr(err.message))
         defer.returnValue(
             dict(code=1, msg=u"accounting error, please see log detail"))
Beispiel #43
0
 def preProcessPacket(bas):
     if not bas:
         log.msg('[Radiusd] ::::::: Dropping packet from unknown host ' + host, level=logging.DEBUG)
         return
     secret, vendor_id = bas['secret'], bas['vendor_id']
     try:
         _packet = self.createPacket(packet=datagram, dict=self.dict, secret=six.b(str(secret)),
                                     vendor_id=vendor_id)
         _packet.deferred.addCallbacks(self.reply, self.on_exception)
         _packet.source = (host, port)
         log.msg("[Radiusd] ::::::: Received radius request: %s" % (str(_packet)), level=logging.INFO)
         self.radapi.logger(nasaddr=host, content=_packet.format_log(), level='info')
         if self.config.defaults.debug:
             log.msg(_packet.format_str(), level=logging.DEBUG)
         proc_deferd = self.processPacket(_packet)
         proc_deferd.addCallbacks(self.on_process_done, self.on_exception)
     except packet.PacketError as err:
         errstr = 'RadiusError:Dropping invalid packet from {0} {1},{2}'.format(host, port, utils.safestr(err))
         self.radapi.logger(nasaddr=host, content=errstr, level='error')
Beispiel #44
0
 def process_delay(self):
     while self.auth_delay.delay_len() > 0:
         try:
             reject = self.auth_delay.get_delay_reject(0)
             if (datetime.datetime.now() - reject.created).seconds < self.auth_delay.reject_delay:
                 return
             else:
                 self.reply(self.auth_delay.pop_delay_reject())
         except Exception as err:
             self.radapi.logger(content=u'RadiusError:process_delay error,{0}'.format(utils.safestr(err)),
                                level='error')
Beispiel #45
0
    def post(self):
        try:
            req_msg = json.loads(self.request.body)
            if not self.check_sign(self.settings.api_secret, req_msg):
                log.msg("[api debug] nas add request sign error")
                self.render_json(code=1, msg="sign error")
                return
        except Exception as err:
            log.err("parse params error %s" % safestr(err))
            self.render_json(code=1, msg="parse params error")
            return

        try:
            ipaddr = req_msg["ipaddr"]
            secret = req_msg["secret"]
            vendor_id = int(req_msg["vendor_id"])
            coa_port = int(req_msg.get("coa_port", 3799))
            api_secret = req_msg["api_secret"]
            api_auth_url = req_msg["api_auth_url"]
            api_acct_url = req_msg["api_acct_url"]
            api_logger_url = req_msg["api_logger_url "]

            if not validate.is_ip.valid(ipaddr):
                raise ValueError("ipaddr {0} format error,{1}".format(ipaddr, validate.is_ip.msg))

            if not validate.not_null.valid(secret):
                raise ValueError("secret {0} format error,{1}".format(secret, validate.not_null.msg))

            if not validate.not_null.valid(vendor_id):
                raise ValueError("vendor_id {0} format error,{1}".format(vendor_id, validate.not_null.msg))

            if not validate.is_number.valid(coa_port):
                raise ValueError("cao_port {0} format error,{1}".format(coa_port, validate.is_number.msg))

            if not validate.not_null.valid(api_secret):
                raise ValueError("api_secret {0} format error,{1}".format(api_secret, validate.not_null.msg))

            if not validate.is_url.valid(api_auth_url):
                raise ValueError("api_auth_url {0} format error,{1}".format(api_auth_url, validate.is_url.msg))

            if not validate.is_url.valid(api_acct_url):
                raise ValueError("api_acct_url {0} format error,{1}".format(api_acct_url, validate.is_url.msg))

            if api_logger_url and not validate.is_url.valid(api_logger_url):
                raise ValueError("api_logger_url {0} format error,{1}".format(api_logger_url, validate.is_url.msg))

        except Exception as err:
            log.err("verify params error %s" % safestr(err))
            self.render_json(code=1, msg="verify params error")
            return

        nasdata = dict(
            ipaddr=ipaddr,
            secret=secret,
            vendor_id=vendor_id,
            coa_port=coa_port,
            api_secret=api_secret,
            api_auth_url=api_auth_url,
            api_acct_url=api_acct_url,
            api_logger_url=api_logger_url,
        )

        try:
            yield self.redb.set_nas(ipaddr, nasdata)
            result = dict(code=0, msg="success")
        except Exception as err:
            log.err("insert nasdata to database error  %s" % safestr(err))
            result = dict(code=1, msg="insert nasdata to database error")

        self.render_json(**result)