Example #1
0
    def ksr_route_auth(self, msg):

        if KSR.pv.get("$rm") != "REGISTER" :
            if KSR.permissions.allow_source_address(1)>0 :
                # source IP allowed
                return 1;

        if KSR.pv.get("$rm")=="REGISTER" or KSR.is_myself(KSR.pv.get("$fu")) :
            # authenticate requests
            if KSR.auth_db.auth_check(KSR.pv.get("$fd"), "subscriber", 1)<0 :
                KSR.auth.auth_challenge(KSR.pv.get("$fd"), 0);
                return -255;

            # user authenticated - remove auth header
            if not "REGISTER,PUBLISH".find(KSR.pv.get("$rm"))!=-1 :
                KSR.auth.consume_credentials();

        # if caller is not local subscriber, then check if it calls
        # a local destination, otherwise deny, not an open relay here
        if (not KSR.is_myself(KSR.pv.get("$fu"))
                and (not KSR.is_myself(KSR.pv.get("$ru")))) :
            KSR.sl.sl_send_reply(403,"Not relaying");
            return -255;

        return 1;
    def ksr_onreply_manage(self, msg):
        KSR.dbg("incoming reply\n");
        scode = KSR.pv.get("$rs");
        if scode>100 and scode<299 :
            self.ksr_route_natmanage(msg);

        return 1;
Example #3
0
 def __init__(self):
     try:
         self.pn = FirebasePushNotifications()
     except UndefinedEnvironmentVariable as e:
         KSR.error(e.message)
     except:
         KSR.info(traceback.format_exc())
    def ksr_route_auth(self, msg):

        if KSR.pv.get("$rm") != "REGISTER" :
            if KSR.permissions.allow_source_address(1)>0 :
                # source IP allowed
                return 1;

        if KSR.pv.get("$rm")=="REGISTER" or KSR.is_myself(KSR.pv.get("$fu")) :
            # authenticate requests
            if KSR.auth_db.auth_check(KSR.pv.get("$fd"), "subscriber", 1)<0 :
                KSR.auth.auth_challenge(KSR.pv.get("$fd"), 0);
                return -255;

            # user authenticated - remove auth header
            if not "REGISTER,PUBLISH".find(KSR.pv.get("$rm"))!=-1 :
                KSR.auth.consume_credentials();

        # if caller is not local subscriber, then check if it calls
        # a local destination, otherwise deny, not an open relay here
        if (not KSR.is_myself(KSR.pv.get("$fu"))
                and (not KSR.is_myself(KSR.pv.get("$ru")))) :
            KSR.sl.sl_send_reply(403,"Not relaying");
            return -255;

        return 1;
Example #5
0
    def ksr_onreply_manage(self, msg):
        KSR.dbg("incoming reply\n");
        scode = KSR.pv.get("$rs");
        if scode>100 and scode<299 :
            self.ksr_route_natmanage(msg);

        return 1;
Example #6
0
 def __init__(self):
     KSR.info('===== kamailio.__init__\n')
     # Re-import modules on reload
     for filename in ROUTES: # app_python3
         if filename in sys.modules:# app_python3
             KSR.info("Reload route:" + filename)# app_python3
             del sys.modules[filename] # app_python3
             exec("import " + filename) # app_python3
    def ksr_route_natdetect(self, msg):
        KSR.force_rport();
        if KSR.nathelper.nat_uac_test(19)>0 :
            if KSR.pv.get("$rm")=="REGISTER" :
                KSR.nathelper.fix_nated_register();
            elif KSR.siputils.is_first_hop()>0 :
                KSR.nathelper.set_contact_alias();

            KSR.setflag(FLT_NATS);

        return 1;
Example #8
0
    def ksr_route_natdetect(self, msg):
        KSR.force_rport();
        if KSR.nathelper.nat_uac_test(19)>0 :
            if KSR.pv.get("$rm")=="REGISTER" :
                KSR.nathelper.fix_nated_register();
            elif KSR.siputils.is_first_hop()>0 :
                KSR.nathelper.set_contact_alias();

            KSR.setflag(FLT_NATS);

        return 1;
Example #9
0
 def send_push_notification(self, msg):
     KSR.info(">>> Send push notification")
     try:
         self.pn.send_push_notification(KSR.pv.get("$tU"),
                                        call_id=KSR.pv.get("$ci"),
                                        sip_from=KSR.pv.get("$fU"),
                                        loc_key=KSR.pv.get("$mi"),
                                        loc_args=KSR.pv.get("$oU"))
     except:
         KSR.info(traceback.format_exc())
     return 1
    def ksr_route_natdetect(self, msg):
        KSR.force_rport()
        if KSR.nathelper.nat_uac_test(19) > 0:
            if KSR.is_REGISTER():
                KSR.nathelper.fix_nated_register()
            elif KSR.siputils.is_first_hop() > 0:
                KSR.nathelper.set_contact_alias()

            KSR.setflag(FLT_NATS)

        return 1
def ksr_route_async_REGISTER(self, msg):
    if KSR.isflagset(self.FLAGS['FLT_NATS']):
        KSR.setbflag(self.FLAGS['FLB_NATB'])
        # do SIP NAT pinging
        KSR.setbflag(self.FLAGS['FLB_NATSIPPING'])
    if KSR.registrar.save("location", 0) < 0:
        KSR.xlog.xerr("Cant store AoR")
        KSR.sl.sl_reply_error()
    else:
        # Фильтруем УДАЧНЫЕ регистрации на предмет необходимости уведомлений
        self.check_registration_uri()
    return -255
    def ksr_route_registrar(self, msg):
        if KSR.pv.get("$rm") != "REGISTER" :
            return 1;
        if KSR.isflagset(FLT_NATS) :
            KSR.setbflag(FLB_NATB);
            # do SIP NAT pinging
            KSR.setbflag(FLB_NATSIPPING);

        if KSR.registrar.save("location", 0)<0 :
            KSR.sl.sl_reply_error();

        return -255;
Example #13
0
    def ksr_route_registrar(self, msg):
        if KSR.pv.get("$rm") != "REGISTER" :
            return 1;
        if KSR.isflagset(FLT_NATS) :
            KSR.setbflag(FLB_NATB);
            # do SIP NAT pinging
            KSR.setbflag(FLB_NATSIPPING);

        if KSR.registrar.save("location", 0)<0 :
            KSR.sl.sl_reply_error();

        return -255;
def ksr_route_natdetect(self):
    KSR.force_rport()
    if KSR.nathelper.nat_uac_test(19) > 0:
        KSR.xlog.xdbg("Client behind NAT.")
        if KSR.is_REGISTER():
            KSR.nathelper.fix_nated_register()
        elif KSR.siputils.is_first_hop() > 0:
            KSR.nathelper.set_contact_alias()

        KSR.setflag(self.FLAGS['FLT_NATS'])
    else:
        KSR.xlog.xdbg("NAT not detected.")

    return 1
    def ksr_route_reqinit(self, msg):
        if not KSR.is_myself(KSR.pv.get("$si")):
            if not KSR.pv.is_null("$sht(ipban=>$si)"):
                # ip is already blocked
                KSR.dbg("request from blocked IP - " + KSR.pv.get("$rm") +
                        " from " + KSR.pv.get("$fu") + " (IP:" +
                        KSR.pv.get("$si") + ":" + KSR.pv.get("$sp") + ")\n")
                return -255

            if KSR.pike.pike_check_req() < 0:
                KSR.err("ALERT: pike blocking " + KSR.pv.get("$rm") +
                        " from " + KSR.pv.get("$fu") + " (IP:" +
                        KSR.pv.get("$si") + ":" + KSR.pv.get("$sp") + ")\n")
                KSR.pv.seti("$sht(ipban=>$si)", 1)
                return -255

        if not KSR.pv.is_null("$ua"):
            if (KSR.pv.get("$ua").find("friendly-scanner") != -1
                    or KSR.pv.get("$ua").find("sipcli") != -1):
                KSR.sl.sl_send_reply(200, "Processed")
                return -255

        if KSR.maxfwd.process_maxfwd(10) < 0:
            KSR.sl.sl_send_reply(483, "Too Many Hops")
            return -255

        if (KSR.pv.get("$rm") == "OPTIONS" and KSR.is_myself(KSR.pv.get("$ru"))
                and KSR.pv.is_null("$rU")):
            KSR.sl.sl_send_reply(200, "Keepalive")
            return -255

        if KSR.sanity.sanity_check(1511, 7) < 0:
            KSR.err("Malformed SIP message from " + KSR.pv.get("$si") + ":" +
                    KSR.pv.get("$sp") + "\n")
            return -255
def ksr_route_reqinit(self):
    if KSR.is_INVITE():
        KSR.xlog.xinfo("REQINIT. Check request $ru from $fu:$si")

    if KSR.is_method("PUBLISH|SUBSCRIBE"):
        # Drop unsupported methods
        KSR.sl.sl_send_reply(404, "Pool is closed due to aids.")
        return -255

    if KSR.is_OPTIONS() and re.match("friendly-scanner|sipcli|VaxSIPUserAgent", KSR.pv.getw("$ua")):
        # silent drop for scanners - uncomment next line if want to reply
        # KSR.sl.sl_send_reply(200, "OK")
        KSR.sl.sl_send_reply(503, "There is no money, but you hang in there. Best wishes! Cheers!")
        return -255

    if KSR.maxfwd.process_maxfwd(10) < 0:
        KSR.sl.sl_send_reply(483, "Too Many Hops")
        return -255

    if KSR.is_OPTIONS():
        KSR.sl.sl_send_reply(200, "Keepalive")
        return -255
    
    if (int(KSR.siputils.is_request()) > 0) and (int(KSR.textops.has_body()) < 0) and (int(KSR.hdr.is_present("Content-Length")) < 0):
        KSR.xlog.xwarn("Malformed SIP message from $si:$sp - unpresent Body and no Content-Length header. User agent:$ua - Append hdr")
        KSR.hdr.append("Content-Length: 0\r\n")
        KSR.textopsx.msg_apply_changes()
        
    if "null" in KSR.pv.getw("$ct"):
        KSR.xlog.xalert("Null in contact:{} Patch it".format(KSR.pv.getw("$ct")))
        KSR.hdr.remove("Contact")
        KSR.hdr.append("Contact: sip:{}@{}:{}\r\n".format(KSR.pv.getw("$fU"), KSR.pv.getw("$si"), KSR.pv.getw("$sp")))
        KSR.textopsx.msg_apply_changes()
        KSR.xlog.xalert("Contact now:{}".format(KSR.pv.getw("$ct")))

    if KSR.sanity.sanity_check(1511, 7) < 0:
        KSR.xlog.xerr("Malformed SIP message from $si:$sp")
        return -255

    if not KSR.pv.is_null("$au") and re.match("(\=)|(\-\-)|(')|(\#)|(\%27)|(\%24)", KSR.pv.getw("$au")):
        KSR.xlog.xalert("SQL Injection in authorization username from IP:$si:$sp - $au")
        KSR.sl.sl_send_reply(503, "There is no money, but you hang in there. Best wishes! Cheers!")
        return -255

    if KSR.is_INVITE() and re.match("(\=)|(\-\-)|(')|(\#)|(\%27)|(\%24)", KSR.pv.getw("$ru")):
        KSR.xlog.xalert("SQL Injection in RURI in INVITE from IP:$si:$sp - $ru")
        KSR.sl.sl_send_reply(503, "There is no money, but you hang in there. Best wishes! Cheers!")
        return -255
    return 1
    def ksr_route_sipout(self, msg):
        if KSR.is_myself(KSR.pv.get("$ru")) :
            return 1;

        KSR.hdr.append("P-Hint: outbound\r\n");
        self.ksr_route_relay(msg);
        return -255;
Example #18
0
    def ksr_route_sipout(self, msg):
        if KSR.is_myself(KSR.pv.get("$ru")) :
            return 1;

        KSR.hdr.append("P-Hint: outbound\r\n");
        self.ksr_route_relay(msg);
        return -255;
    def ksr_route_sipout(self, msg):
        if KSR.is_myself_ruri():
            return 1

        KSR.hdr.append("P-Hint: outbound\r\n")
        self.ksr_route_relay(msg)
        return -255
    def ksr_route_location(self, msg):
        rc = KSR.registrar.lookup("location")
        if rc < 0:
            KSR.tm.t_newtran()
            if rc == -1 or rc == -3:
                KSR.sl.send_reply(404, "Not Found")
                return -255
            elif rc == -2:
                KSR.sl.send_reply(405, "Method Not Allowed")
                return -255

        # when routing via usrloc, log the missed calls also
        if KSR.is_INVITE():
            KSR.setflag(FLT_ACCMISSED)

        self.ksr_route_relay(msg)
        return -255
Example #21
0
 def extract_contact(self, msg):
     KSR.info(">>> Extract contact")
     try:
         result = self.parse_contact(KSR.pv.get("$ct"))
         if result is None:
             return 1
         contact = ";".join([result["prefix"], result["suffix"]])
         self.update_contact_header(contact)
         self.pn.update_pn_contact(
             result["username"],
             app_id=result["app_id"],
             pn_type=result["pn_type"],
             pn_token=result["pn_token"],
         )
     except:
         KSR.info(traceback.format_exc())
     return 1
Example #22
0
    def ksr_route_location(self, msg):
        rc = KSR.registrar.lookup("location");
        if rc<0 :
            KSR.tm.t_newtran();
            if rc==-1 or rc==-3 :
                KSR.sl.send_reply(404, "Not Found");
                return -255;
            elif rc==-2 :
                KSR.sl.send_reply(405, "Method Not Allowed");
                return -255;

        # when routing via usrloc, log the missed calls also
        if KSR.pv.get("$rm")=="INVITE" :
            KSR.setflag(FLT_ACCMISSED);

        self.ksr_route_relay(msg);
        return -255;
    def ksr_route_location(self, msg):
        rc = KSR.registrar.lookup("location");
        if rc<0 :
            KSR.tm.t_newtran();
            if rc==-1 or rc==-3 :
                KSR.sl.send_reply(404, "Not Found");
                return -255;
            elif rc==-2 :
                KSR.sl.send_reply(405, "Method Not Allowed");
                return -255;

        # when routing via usrloc, log the missed calls also
        if KSR.pv.get("$rm")=="INVITE" :
            KSR.setflag(FLT_ACCMISSED);

        self.ksr_route_relay(msg);
        return -255;
Example #24
0
 def ksr_reply_route(self, msg):
     if KSR.is_method_in("IBR"):
         # (I)NVITE, (B)YE, (R)EGITER
         KSR.xlog.xinfo("Get reply $rs:$rr")
         self.append_uuid(KSR.pv.getw("$ci"))
     scode = KSR.pv.getw("$rs")
     if 100 <= scode or scode <= 299:
         self.ksr_route_natmanage()
     return 1
    def ksr_route_relay(self, msg):
        # enable additional event routes for forwarded requests
        # - serial forking, RTP relaying handling, a.s.o.
        if KSR.is_method_in("IBSU"):
            if KSR.tm.t_is_set("branch_route") < 0:
                KSR.tm.t_on_branch("ksr_branch_manage")

        if KSR.is_method_in("ISU"):
            if KSR.tm.t_is_set("onreply_route") < 0:
                KSR.tm.t_on_reply("ksr_onreply_manage")

        if KSR.is_INVITE():
            if KSR.tm.t_is_set("failure_route") < 0:
                KSR.tm.t_on_failure("ksr_failure_manage")

        if KSR.tm.t_relay() < 0:
            KSR.sl.sl_reply_error()

        return -255
    def ksr_route_relay(self, msg):
        # enable additional event routes for forwarded requests
        # - serial forking, RTP relaying handling, a.s.o.
        if KSR.is_method_in("IBSU") :
            if KSR.tm.t_is_set("branch_route")<0 :
                KSR.tm.t_on_branch("ksr_branch_manage");

        if KSR.is_method_in("ISU") :
            if KSR.tm.t_is_set("onreply_route")<0 :
                KSR.tm.t_on_reply("ksr_onreply_manage");

        if KSR.is_INVITE() :
            if KSR.tm.t_is_set("failure_route")<0 :
                KSR.tm.t_on_failure("ksr_failure_manage");

        if KSR.tm.t_relay()<0 :
            KSR.sl.sl_reply_error();

        return -255;
Example #27
0
    def ksr_route_natmanage(self, msg):
        if KSR.siputils.is_request()>0 :
            if KSR.siputils.has_totag()>0 :
                if KSR.rr.check_route_param("nat=yes")>0 :
                    KSR.setbflag(FLB_NATB);

        if (not (KSR.isflagset(FLT_NATS) or KSR.isbflagset(FLB_NATB))) :
            return 1;

        KSR.rtpproxy.rtpproxy_manage("co");

        if KSR.siputils.is_request()>0 :
            if not KSR.siputils.has_totag() :
                if KSR.tmx.t_is_branch_route()>0 :
                    KSR.rr.add_rr_param(";nat=yes");

        if KSR.siputils.is_reply()>0 :
            if KSR.isbflagset(FLB_NATB) :
                KSR.nathelper.set_contact_alias();

        return 1;
    def ksr_route_natmanage(self, msg):
        if KSR.siputils.is_request()>0 :
            if KSR.siputils.has_totag()>0 :
                if KSR.rr.check_route_param("nat=yes")>0 :
                    KSR.setbflag(FLB_NATB);

        if (not (KSR.isflagset(FLT_NATS) or KSR.isbflagset(FLB_NATB))) :
            return 1;

        KSR.rtpproxy.rtpproxy_manage("co");

        if KSR.siputils.is_request()>0 :
            if not KSR.siputils.has_totag() :
                if KSR.tmx.t_is_branch_route()>0 :
                    KSR.rr.add_rr_param(";nat=yes");

        if KSR.siputils.is_reply()>0 :
            if KSR.isbflagset(FLB_NATB) :
                KSR.nathelper.set_contact_alias();

        return 1;
Example #29
0
def ksr_route_relay(self):
    KSR.nathelper.handle_ruri_alias()
    # enable additional event routes for forwarded requests
    # - serial forking, RTP relaying handling, a.s.o.
    if KSR.is_method("INVITE|BYE|SUBSCRIBE|UPDATE") and (KSR.tm.t_is_set("branch_route") < 0):
        KSR.tm.t_on_branch("ksr_branch_manage")

    #if KSR.is_method("INVITE|BYE|SUBSCRIBE|UPDATE") and (KSR.tm.t_is_set("onreply_route") < 0):
    #    KSR.tm.t_on_reply("ksr_onreply_manage")

    if KSR.is_INVITE() and (KSR.tm.t_is_set("failure_route") < 0):
        KSR.tm.t_on_failure("ksr_failure_manage")

    if KSR.isflagset(self.FLAGS['FLT_FROM_ASTERISK']):
        KSR.textops.remove_hf_re("^X-")

    if KSR.tm.t_relay() < 0:
        KSR.xlog.xerr("Cant relay request. Send error.")
        KSR.sl.sl_reply_error()
        return -255
    else:
        return 1
Example #30
0
    def ksr_route_withindlg(self, msg):
        if KSR.siputils.has_totag()<0 :
            return 1;

        # sequential request withing a dialog should
        # take the path determined by record-routing
        if KSR.rr.loose_route()>0 :
            if self.ksr_route_dlguri(msg)==-255 :
                return -255;
            if KSR.pv.get("$rm")=="BYE" :
                # do accounting ...
                KSR.setflag(FLT_ACC);
                # ... even if the transaction fails
                KSR.setflag(FLT_ACCFAILED);
            elif KSR.pv.get("$rm")=="ACK" :
                # ACK is forwarded statelessly
                if self.ksr_route_natmanage(msg)==-255 :
                    return -255;
            elif KSR.pv.get("$rm")=="NOTIFY" :
                # Add Record-Route for in-dialog NOTIFY as per RFC 6665.
                KSR.rr.record_route();

            self.ksr_route_relay(msg);
            return -255;

        if KSR.pv.get("$rm")=="ACK" :
            if KSR.tm.t_check_trans() >0 :
                # no loose-route, but stateful ACK;
                # must be an ACK after a 487
                # or e.g. 404 from upstream server
                self.ksr_route_relay(msg);
                return -255;
            else:
                # ACK without matching transaction ... ignore and discard
                return -255;

        KSR.sl.sl_send_reply(404, "Not here");
        return -255;
    def ksr_route_withindlg(self, msg):
        if KSR.siputils.has_totag()<0 :
            return 1;

        # sequential request withing a dialog should
        # take the path determined by record-routing
        if KSR.rr.loose_route()>0 :
            if self.ksr_route_dlguri(msg)==-255 :
                return -255;
            if KSR.pv.get("$rm")=="BYE" :
                # do accounting ...
                KSR.setflag(FLT_ACC);
                # ... even if the transaction fails
                KSR.setflag(FLT_ACCFAILED);
            elif KSR.pv.get("$rm")=="ACK" :
                # ACK is forwarded statelessy
                if self.ksr_route_natmanage(msg)==-255 :
                    return -255;
            elif KSR.pv.get("$rm")=="NOTIFY" :
                # Add Record-Route for in-dialog NOTIFY as per RFC 6665.
                KSR.rr.record_route();

            self.ksr_route_relay(msg);
            return -255;

        if KSR.pv.get("$rm")=="ACK" :
            if KSR.tm.t_check_trans() >0 :
                # no loose-route, but stateful ACK;
                # must be an ACK after a 487
                # or e.g. 404 from upstream server
                self.ksr_route_relay(msg);
                return -255;
            else:
                # ACK without matching transaction ... ignore and discard
                return -255;

        KSR.sl.sl_send_reply(404, "Not here");
        return -255;
def ksr_route_withindlg(self):
    if KSR.siputils.has_totag() < 0:
        return 1

    # sequential request withing a dialog should
    # take the path determined by record-routing
    if KSR.rr.loose_route() > 0:
        if not KSR.isdsturiset():
            KSR.nathelper.handle_ruri_alias()
        if KSR.is_ACK():
            # ACK is forwarded statelessly
            if self.ksr_route_natmanage() == -255:
                return -255
        elif KSR.is_NOTIFY():
            # Add Record-Route for in-dialog NOTIFY as per RFC 6665.
            KSR.rr.record_route()
        elif KSR.is_INVITE():
            KSR.xlog.xinfo("Hande reINVITE")
            KSR.rr.record_route()

        self.ksr_route_relay()
        return -255

    if KSR.is_ACK():
        if KSR.tm.t_check_trans() > 0:
            # no loose-route, but stateful ACK
            # must be an ACK after a 487
            # or e.g. 404 from upstream server
            self.ksr_route_relay()
            return -255
        else:
            # ACK without matching transaction ... ignore and discard
            return -255

    KSR.sl.sl_send_reply(404, "Not here")
    return -255
Example #33
0
    def ksr_reply_route(self, msg):
        KSR.dbg("response handling - python script\n")

        if KSR.sanity.sanity_check(17604, 6)<0 :
            KSR.err("Malformed SIP response from "
                    + KSR.pv.get("$si") + ":" + str(KSR.pv.get("$sp")) +"\n")
            KSR.set_drop()
            return -255

        return 1
    def ksr_route_registrar(self, msg):
        if not KSR.is_REGISTER():
            return 1
        if KSR.isflagset(FLT_NATS):
            KSR.setbflag(FLB_NATB)
            # do SIP NAT pinging
            KSR.setbflag(FLB_NATSIPPING)

        if KSR.registrar.save("location", 0) < 0:
            KSR.sl.sl_reply_error()

        return -255
    def ksr_route_reqinit(self, msg):
        if not KSR.is_myself(KSR.pv.get("$si")) :
            if not KSR.pv.is_null("$sht(ipban=>$si)") :
                # ip is already blocked
                KSR.dbg("request from blocked IP - " + KSR.pv.get("$rm")
                        + " from " + KSR.pv.get("$fu") + " (IP:"
                        + KSR.pv.get("$si") + ":" + str(KSR.pv.get("$sp")) + ")\n");
                return -255;

            if KSR.pike.pike_check_req()<0 :
                KSR.err("ALERT: pike blocking " + KSR.pv.get("$rm")
                        + " from " + KSR.pv.get("$fu") + " (IP:"
                        + KSR.pv.get("$si") + ":" + str(KSR.pv.get("$sp")) + ")\n");
                KSR.pv.seti("$sht(ipban=>$si)", 1);
                return -255;

        if KSR.corex.has_user_agent() > 0 :
            ua = KSR.pv.gete("$ua")
            if (ua.find("friendly-scanner")!=-1
                    or ua.find("sipcli")!=-1) :
                KSR.sl.sl_send_reply(200, "Processed");
                return -255;

        if KSR.maxfwd.process_maxfwd(10) < 0 :
            KSR.sl.sl_send_reply(483,"Too Many Hops");
            return -255;

        if (KSR.is_OPTIONS()
                and KSR.is_myself_ruri()
                and KSR.corex.has_ruri_user() < 0) :
            KSR.sl.sl_send_reply(200,"Keepalive");
            return -255;

        if KSR.sanity.sanity_check(1511, 7)<0 :
            KSR.err("Malformed SIP message from "
                    + KSR.pv.get("$si") + ":" + str(KSR.pv.get("$sp")) +"\n");
            return -255;
Example #36
0
    def ksr_route_reqinit(self, msg):
        if not KSR.is_myself(KSR.pv.get("$si")) :
            if not KSR.pv.is_null("$sht(ipban=>$si)") :
                # ip is already blocked
                KSR.dbg("request from blocked IP - " + KSR.pv.get("$rm")
                        + " from " + KSR.pv.get("$fu") + " (IP:"
                        + KSR.pv.get("$si") + ":" + str(KSR.pv.get("$sp")) + ")\n")
                return -255

            if KSR.pike.pike_check_req()<0 :
                KSR.err("ALERT: pike blocking " + KSR.pv.get("$rm")
                        + " from " + KSR.pv.get("$fu") + " (IP:"
                        + KSR.pv.get("$si") + ":" + str(KSR.pv.get("$sp")) + ")\n")
                KSR.pv.seti("$sht(ipban=>$si)", 1)
                return -255

        if KSR.corex.has_user_agent() > 0 :
            ua = KSR.pv.gete("$ua")
            if (ua.find("friendly")!=-1 or ua.find("scanner")!=-1
                    or ua.find("sipcli")!=-1 or ua.find("sipvicious")!=-1) :
                KSR.sl.sl_send_reply(200, "Processed")
                return -255

        if KSR.maxfwd.process_maxfwd(10) < 0 :
            KSR.sl.sl_send_reply(483,"Too Many Hops")
            return -255

        if (KSR.is_OPTIONS()
                and KSR.is_myself_ruri()
                and KSR.corex.has_ruri_user() < 0) :
            KSR.sl.sl_send_reply(200,"Keepalive")
            return -255

        if KSR.sanity.sanity_check(17895, 7)<0 :
            KSR.err("Malformed SIP message from "
                    + KSR.pv.get("$si") + ":" + str(KSR.pv.get("$sp")) +"\n")
            return -255
Example #37
0
    def ksr_request_route(self, msg):

        KSR.dbg("method " + KSR.pv.get("$rm") + " r-uri " + KSR.pv.get("$ru"))

        if KSR.is_method("REGISTER"):
            KSR.sl.send_reply(200, "OK")

        elif KSR.is_method("INVITE"):
            #Lookup our public IP address
            try:
                ip = requests.get('https://api.ipify.org').text
            except:
                ip = "Failed to resolve"

            #Add that as a header
            KSR.hdr.append("X-KEMI: I came from KEMI at " + str(ip) + "\r\n")

            #Set host IP to 10.1.1.1
            KSR.sethost("10.1.1.1")

            #Forward the request on
            KSR.forward()
        else:
            KSR.sl.send_reply(500, "Got no idea...")
    def ksr_route_auth(self, msg):

        if not KSR.is_REGISTER():
            if KSR.permissions.allow_source_address(1) > 0:
                # source IP allowed
                return 1

        if KSR.is_REGISTER() or KSR.is_myself_furi():
            # authenticate requests
            if KSR.auth_db.auth_check(KSR.pv.get("$fd"), "subscriber", 1) < 0:
                KSR.auth.auth_challenge(KSR.pv.get("$fd"), 0)
                return -255

            # user authenticated - remove auth header
            if not KSR.is_method_in("RP"):
                KSR.auth.consume_credentials()

        # if caller is not local subscriber, then check if it calls
        # a local destination, otherwise deny, not an open relay here
        if (not KSR.is_myself_furi()) and (not KSR.is_myself_ruri()):
            KSR.sl.sl_send_reply(403, "Not relaying")
            return -255

        return 1
Example #39
0
    def ksr_request_route(self, msg):
        # KSR.info("===== request - from kamailio python script\n");
        # KSR.info("===== method [%s] r-uri [%s]\n" % (KSR.pv.get("$rm"),KSR.pv.get("$ru")));

        # per request initial checks
        if self.ksr_route_reqinit(msg)==-255 :
            return 1;

        # NAT detection
        if self.ksr_route_natdetect(msg)==-255 :
            return 1;

        # CANCEL processing
        if KSR.pv.get("$rm") == "CANCEL" :
            if KSR.tm.t_check_trans()>0 :
                self.ksr_route_relay(msg);
            return 1;

        # handle requests within SIP dialogs
        if self.ksr_route_withindlg(msg)==-255 :
            return 1;

        # -- only initial requests (no To tag)

        # handle retransmissions
        if KSR.tmx.t_precheck_trans()>0 :
            KSR.tm.t_check_trans();
            return 1;

        if KSR.tm.t_check_trans()==0 :
            return 1;

        # authentication
        if self.ksr_route_auth(msg)==-255 :
            return 1

        # record routing for dialog forming requests (in case they are routed)
        # - remove preloaded route headers
        KSR.hdr.remove("Route");
        if "INVITE|SUBSCRIBE".find(KSR.pv.get("$rm"))!=-1 :
            KSR.rr.record_route();


        # account only INVITEs
        if KSR.pv.get("$rm")=="INVITE" :
            KSR.setflag(FLT_ACC); # do accounting


        # dispatch requests to foreign domains
        if self.ksr_route_sipout(msg)==-255 :
            return 1;

        # # requests for my local domains

        # handle registrations
        if self.ksr_route_registrar(msg)==-255 :
            return 1;

        if KSR.pv.is_null("$rU") :
            # request with no Username in RURI
            KSR.sl.sl_send_reply(484,"Address Incomplete");
            return 1;


        # user location service
        self.ksr_route_location(msg);

        return 1;
Example #40
0
 def child_init(self, rank):
     KSR.info('===== kamailio.child_init(%d)\n' % rank);
     return 0;
Example #41
0
 def ksr_reply_route(self, msg):
     KSR.info("===== response - from kamailio python script\n");
     return 1;
Example #42
0
 def __init__(self):
     KSR.info('===== kamailio.__init__\n');
Example #43
0
 def ksr_branch_manage(self, msg):
     KSR.dbg("new branch ["+ str(KSR.pv.get("$T_branch_idx"))
                 + "] to "+ KSR.pv.get("$ru") + "\n");
     self.ksr_route_natmanage(msg);
     return 1;
Example #44
0
    def ksr_route_dlguri(self, msg):
        if not KSR.isdsturiset() :
            KSR.nathelper.handle_ruri_alias();

        return 1;
    def ksr_request_route(self, msg):
        # KSR.info("===== request - from kamailio python script\n");
        # KSR.info("===== method [%s] r-uri [%s]\n" % (KSR.pv.get("$rm"),KSR.pv.get("$ru")));

        # per request initial checks
        if self.ksr_route_reqinit(msg)==-255 :
            return 1;

        # NAT detection
        if self.ksr_route_natdetect(msg)==-255 :
            return 1;

        # CANCEL processing
        if KSR.pv.get("$rm") == "CANCEL" :
            if KSR.tm.t_check_trans()>0 :
                self.ksr_route_relay();
            return 1;

        # handle requests within SIP dialogs
        if self.ksr_route_withindlg(msg)==-255 :
            return 1;

        # -- only initial requests (no To tag)

        # handle retransmissions
        if KSR.tmx.t_precheck_trans()>0 :
            KSR.tm.t_check_trans();
            return 1;

        if KSR.tm.t_check_trans()==0 :
            return 1;

        # authentication
        if self.ksr_route_auth(msg)==-255 :
            return 1

        # record routing for dialog forming requests (in case they are routed)
        # - remove preloaded route headers
        KSR.hdr.remove("Route");
        if "INVITE|SUBSCRIBE".find(KSR.pv.get("$rm"))!=-1 :
            KSR.rr.record_route();


        # account only INVITEs
        if KSR.pv.get("$rm")=="INVITE" :
            KSR.setflag(FLT_ACC); # do accounting


        # dispatch requests to foreign domains
        if self.ksr_route_sipout(msg)==-255 :
            return 1;

        # # requests for my local domains

        # handle registrations
        if self.ksr_route_registrar(msg)==-255 :
            return 1;

        if KSR.pv.is_null("$rU") :
            # request with no Username in RURI
            KSR.sl.sl_send_reply(484,"Address Incomplete");
            return 1;


        # user location service
        self.ksr_route_location(msg);

        return 1;
Example #46
0
def mod_init():
    KSR.info("===== from Python mod init\n");
    # dumpObj(KSR);
    return kamailio();
def ksr_special_routing(self, r_user):
    if r_user == "SOS":
        KSR.dispatcher.ds_select_dst(self.DSIDS['MEDIASERVERS'], 4)
        KSR.setbflag(self.FLAGS['FLB_NATB'])
        KSR.xlog.xwarn(
            "Pressed SOS button. Redirect to asterisk for recording. DURI set to:$du"
        )
        return True
    elif r_user == "7298886":
        KSR.xlog.xwarn("Zhilservice")
        KSR.seturi("sip:[email protected]")
        # Просто так From нельзя менять.
        KSR.uac.uac_replace_from_uri("sip:[email protected]")
        KSR.setbflag(self.FLAGS['FLB_NATB'])
        return True
    elif r_user == "VR":
        KSR.hdr.append("X-Route-to: VoiceRecognition\r\n")
        KSR.dispatcher.ds_select_dst(self.DSIDS['MEDIASERVERS'], 4)
        KSR.setbflag(self.FLAGS['FLB_NATB'])
        KSR.xlog.xinfo(
            "Call for voice recognition redirected to Asterisk. DURI set to:$du"
        )
        return True
    elif re.search("^instruction", r_user):
        KSR.dispatcher.ds_select_dst(self.DSIDS['MEDIASERVERS'], 4)
        KSR.setbflag(self.FLAGS['FLB_NATB'])
        KSR.xlog.xinfo(
            "Call redirected to mediaserver. DURI set to:$du RURI:$ru")
        return True
    elif re.search("^STP_", r_user):
        KSR.seturi("sip:{}@interphone.is74.ru:5060".format(r_user))
        KSR.hdr.append("X-Route-to: STP\r\n")
        KSR.setbflag(self.FLAGS['FLB_NATB'])
        KSR.xlog.xinfo("Call redirected to Interphone. RURI set to:$ru")
        return True
    elif KSR.pv.getw("$fU").lower() in test_domofones:
        direct_call = False  # Тестовый звонок напрямую на пользователя
        KSR.setbflag(self.FLAGS['FLB_NATB'])
        if direct_call:
            KSR.setuser("id206670")  # Подставить выбранного пользователя
            if self.ksr_x_route_location() == -255:
                exit()
        else:
            KSR.setdsturi(test_asterisk
                          )  # Маршрутизируем в какой либо сервер принудительно
        KSR.setbflag(self.FLAGS['FLB_NATB'])
        KSR.xlog.xinfo(
            "Test call from $fU to $rU apartment. RURI: $ru DURI: $du")
        return True
    elif re.search("^(.+)\.vd\.is74\.ru$", r_user):
        handset = r_user.split('.')
        uri = 'sip:' + handset.pop(0) + '@' + '.'.join(handset)
        KSR.xlog.xinfo(
            "STP call from $fU to $rU, setting RURI to {}".format(uri))
        KSR.seturi(uri)
        # Просто так From нельзя менять.
        KSR.uac.uac_replace_to_uri(uri)
        KSR.setbflag(self.FLAGS['FLB_NATB'])
        return True
    return False