Hello
 I have been having issues with kamailio and asterisk realtime. I have used all the configurations posted, but it just has not worked for me. What I am trying to do is to use asterisk as PSTN & voicemail for kamailio. But I keep getting this 401 not authorized from asterisk like this:

========
--- (19 headers 19 lines) ---
Sending to 99.89.26.17:5060 (NAT)
Using INVITE request as basis request - LCklNT_HoIeTxCB_8cSIf9efRNvkcR
       > doing dnsmgr_lookup for '99.89.26.17'
    -- adding dns manager for '99.89.26.17'
Scheduling destruction of SIP dialog '3d67147a652fe8641c536eb92383ad74@99.89.26.17' in 32000 ms (Method: NOTIFY)
Reliably Transmitting (NAT) to 99.89.26.17:5060:
NOTIFY sip:1000@99.89.26.17 SIP/2.0
Via: SIP/2.0/UDP 99.89.26.18:5060;branch=z9hG4bK00545e8e;rport
Max-Forwards: 70
From: "asterisk" <sip:1000@99.89.26.17>;tag=as4d28adb7
To: <sip:1000@99.89.26.17>
Contact: <sip:1000@99.89.26.18:5060>
Call-ID: 3d67147a652fe8641c536eb92383ad74@99.89.26.17
CSeq: 102 NOTIFY
User-Agent: Asterisk PBX
Event: message-summary
Content-Type: application/simple-message-summary
Content-Length: 84

Messages-Waiting: no
Message-Account: sip:1@99.89.26.17
Voice-Message: 0/0 (0/0)

---
Found peer '1000' for '1000' from 99.89.26.17:5060

<--- Reliably Transmitting (NAT) to 99.89.26.17:5060 --->
SIP/2.0 401 Unauthorized
Via: SIP/2.0/UDP 99.89.26.17;branch=z9hG4bK354f.e07b39b2.0;received=99.89.26.17;rport=5060
Via: SIP/2.0/UDP 192.168.1.101:5060;branch=z9hG4bKj4sndhbgkh863bu8fpr61tb;rport=5060
From: <sip:1000@99.89.26.17>;tag=5tnt79v6phhc689kd5vh
To: <sip:+2348023098407@99.89.26.17;user=phone>;tag=as21d7a164
Call-ID: LCklNT_HoIeTxCB_8cSIf9efRNvkcR
CSeq: 1710 INVITE
Server: Asterisk PBX
Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO, PUBLISH
Supported: replaces, timer
WWW-Authenticate: Digest algorithm=MD5, realm="99.89.26.17", nonce="16c11ac7"
Content-Length: 0

========

asterisk and kamailio are on different server, and I have put the IP of asterisk in trusted table in kamailio db. My kamailio.cfg is:



#!KAMAILIO
#
# $Id$


#!define WITH_MYSQL
#!define WITH_AUTH
#!define WITH_USRLOCDB
#!define WITH_PRESENCE
#!define WITH_NAT
#!define WITH_PSTN
#!define WITH_ACCDB


####### Global Parameters #########

#!ifdef WITH_DEBUG
debug=4
log_stderror=yes
#!else
debug=3
log_stderror=no
#!endif

memdbg=3
memlog=3

log_facility=LOG_LOCAL0

fork=yes
children=4

/* uncomment the next line to disable TCP (default on) */
#disable_tcp=yes

/* uncomment the next line to disable the auto discovery of local aliases
   based on revers DNS on IPs (default on) */
#auto_aliases=no


/* uncomment and configure the following line if you want Kamailio to
   bind on a specific interface/port/proto (default bind on all available) */
listen=udp:99.89.26.17:5060
advertised_address=99.89.26.17
alias=udp:99.89.26.17:5060
port=5060



####### Modules Section ########

mpath="/usr/local/lib/kamailio/modules_k/:/usr/local/lib/kamailio/modules/"

#!ifdef WITH_MYSQL
loadmodule "db_mysql.so"
#!endif
loadmodule "mi_fifo.so"
loadmodule "kex.so"
loadmodule "tm.so"
loadmodule "tmx.so"
loadmodule "sl.so"
loadmodule "rr.so"
loadmodule "pv.so"
loadmodule "maxfwd.so"
loadmodule "usrloc.so"
loadmodule "registrar.so"
loadmodule "textops.so"
loadmodule "uri_db.so"
loadmodule "siputils.so"
loadmodule "xlog.so"
loadmodule "sanity.so"
loadmodule "ctl.so"
loadmodule "mi_rpc.so"
loadmodule "acc.so"
loadmodule "uac.so"

#!ifdef WITH_AUTH
loadmodule "auth.so"
loadmodule "auth_db.so"
#!endif 

loadmodule "alias_db.so"
loadmodule "domain.so"

#!ifdef WITH_PRESENCE
loadmodule "presence.so"
loadmodule "presence_xml.so"
#!endif

#!ifdef WITH_NAT
loadmodule "nathelper.so"
#!endif

loadmodule "permissions.so"

# ----------------- setting module-specific parameters ---------------


# ----- mi_fifo params -----
modparam("mi_fifo", "fifo_name", "/tmp/kamailio_fifo")


# ----- rr params -----
modparam("rr", "enable_full_lr", 1)          # add value to ;lr param to cope with most of the UAs
modparam("rr", "append_fromtag", 1)


# ----- registrar params -----
modparam("registrar", "method_filtering", 1)
#modparam("registrar", "append_branches", 0)
#modparam("registrar", "max_contacts", 10)
# ----- uri_db params -----
modparam("uri_db", "use_uri_table", 0)
modparam("uri_db", "db_url", "mysql://openser:openserrw@localhost/openser")


# ----- acc params -----

  # Usage of flags is as follows:
  #   1 == should account(all to gateway),
  #   2 == should report on missed calls (transactions to kamailio users),
  #   3 == failed transactions
  #   4 == destination user wishes to use voicemail
  #   6 == nathelper  
  #

modparam("acc", "early_media", 1)
modparam("acc", "report_ack", 1)
modparam("acc", "report_cancels", 1)
modparam("acc", "detect_direction", 0)
modparam("acc", "failed_transaction_flag", 3)
modparam("acc", "log_flag", 1)
modparam("acc", "db_flag", 1)
modparam("acc", "log_missed_flag", 2)
modparam("acc", "db_missed_flag", 2)
modparam("acc", "log_extra", "src_user=$fU;src_domain=$fd;dst_ouser=$tU;dst_user=$rU;dst_domain=$rd")
modparam("acc", "db_url","mysql://openser:openserrw@localhost/openser")
modparam("acc", "db_extra","src_user=$fU;src_domain=$fd;dst_ouser=$tU;dst_user=$rU;dst_domain=$rd")
modparam("acc", "db_table_acc", "acc")
modparam("acc", "db_table_missed_calls", "missed_calls")
#!endif

# ----- usrloc params -----
/* enable DB persistency for location entries */
#!ifdef WITH_USRLOCDB
modparam("usrloc", "db_mode",   2)
modparam("usrloc", "db_url", "mysql://openser:openserrw@localhost/openser")
modparam("usrloc", "domain_column", "domain")
modparam("usrloc", "user_column", "username")
modparam("usrloc", "matching_mode", 0)
#!endif


# ----- auth_db params -----
/* enable the DB based authentication */
#!ifdef WITH_AUTH
modparam("auth_db", "calculate_ha1", yes)
modparam("auth_db", "password_column", "password")
modparam("auth_db", "db_url","mysql://openser:openserrw@localhost/openser")
modparam("auth_db", "load_credentials", "")
#!endif


# ----- alias_db params -----
/* uncomment the following lines if you want to enable the DB based
   aliases */
modparam("alias_db", "db_url",  "mysql://openser:openserrw@localhost/openser")


# ----- domain params -----
/* uncomment the following lines to enable multi-domain detection
   support */
modparam("domain", "db_url",    "mysql://openser:openserrw@localhost/openser")
modparam("domain", "db_mode", 0)   # do not use caching
modparam("domain", "domain_col", "domain")
modparam("domain", "domain_table", "domain")
  
  
# ----- multi-module params -----
/* uncomment the following line if you want to enable multi-domain support
   in the modules (dafault off) */
modparam("alias_db|auth_db|usrloc|uri_db", "use_domain", 1)


# ----- presence params -----
/* enable presence server support */
#!ifdef WITH_PRESENCE
modparam("presence|presence_xml", "db_url","mysql://openser:openserrw@localhost/openser")
modparam("presence_xml", "force_active", 1)
modparam("presence", "server_address", "sip:99.89.26.17:5060")
#!endif


# ----- nathelper -----
#!ifdef WITH_NAT
modparam("nathelper", "rtpproxy_sock", "udp:99.89.26.17:7722 udp:99.89.26.17:7723")
modparam("nathelper", "natping_interval", 30)
modparam("nathelper", "ping_nated_only", 1)
modparam("nathelper", "sipping_bflag", 7)
modparam("nathelper", "sipping_from", "sip:pinger@kamailio.org")
modparam("registrar|nathelper", "received_avp", "$avp(i:80)")
modparam("usrloc", "nat_bflag", 6)
#!endif


#------tm timeout for voicemail params--------
modparam("tm", "fr_timer", 10000)
modparam("tm", "fr_inv_timer", 20000)

#------permissions-------
modparam("permissions", "db_url","mysql://openser:openserrw@localhost/openser")
modparam("permissions", "db_mode", 0)     #do not allow caching
modparam("permissions", "trusted_table", "trusted")
modparam("permissions", "source_col", "src_ip")
modparam("permissions", "proto_col", "proto")
modparam("permissions", "from_col", "from_pattern")
modparam("permissions", "peer_tag_avp", "$avp(i:707)")
modparam("permissions", "tag_col", "tag")
#----------uac params -------------
modparam("uac", "credential", "kamailio:99.89.26.17:kamailio")
modparam("uac","from_restore_mode","auto")


####### Routing Logic ########

   
# main request routing logic

route{

        if (!mf_process_maxfwd_header("10")) {
                sl_send_reply("483","Too Many Hops");
                exit;
        }
   
        if(!sanity_check("1511", "7"))
        {
                xlog("Malformed SIP message from $si:$sp\n");
                exit;
        }

        # -----------------------------------------------------------------
        # Record Route Section
        # -----------------------------------------------------------------
        if ((method=="INVITE|SUBSCRIBE") && nat_uac_test("19")) {
                xlog("L_INFO","chuks-test: I am in invite-subscribe\n");
                remove_hf("Route");
                record_route_preset("99.89.26.17:5060");
        } else if (!is_method("REGISTER")) {
                record_route();
        };


        # -----------------------------------------------------------------
        # Call Tear Down Section
        # -----------------------------------------------------------------
        if (is_method("BYE") || is_method("CANCEL")) {
                xlog("L_INFO","chuks-test: I am in bye-cancel\n");
                unforce_rtp_proxy();
        };

        # -----------------------------------------------------------------
        # Loose Route Section
        # -----------------------------------------------------------------
        if (loose_route()) {

                xlog("L_INFO","chuks-test: I am in loose route\n");
                if (is_method("BYE")) {
                        xlog("L_INFO","chuks-test: method is BYE in loose route\n");
                        setflag(1); # do accounting ...
                        setflag(3); # ... even if the transaction fails
                }
              if ((method=="INVITE" || method=="REFER") && !has_totag()) {
                        xlog("L_INFO","chuks-test: method is $rm and no totag in loose route\n");
                        sl_send_reply("403", "Forbidden");
                        break;
                };

                if (is_method("INVITE") || is_method("NOTIFY")) {
                        if (!allow_trusted("$si", "$(proto{s.toupper})")) {
                                xlog("L_INFO","!allow_trusted. rs $rs si $si rm $rm ru $ru tu $tu fu $fu rr $rr\n");
                                if (!proxy_authorize("99.89.26.17","subscriber")) {
                                        proxy_challenge("99.89.26.17","0");
                                        break;
                                } else if (!check_from()) {
                                        sl_send_reply("403", "Forbidden Auth ID");
                                        break;
                                };
                                consume_credentials();
                        };
         
                        if (nat_uac_test("19")){
                                setflag(6);
                                force_rport();
                                fix_nated_contact();
                        }
        
                        force_rtp_proxy("l");
                };
                route(RELAY);
                break;
        };
        
                
          
        # -----------------------------------------------------------------
        # Call Type Processing Section
        # -----------------------------------------------------------------
        if (!is_uri_host_local()) {
                xlog("L_INFO","chuks-test: I am in !is_uri_host_local\n"); 
                append_hf("P-hint: outbound\r\n");
                if (is_from_local() || allow_trusted("$si", "$(proto{s.toupper})")) {
                        xlog("L_INFO","chuks-test: I am in is_from_local || allow_trusted in !is_uri_host_local method\n");
                        route(NAT);
                        route(RELAY);
                } else {
                        xlog("L_INFO","chuks-test: 403 Forbidden from is_uri_host_local\n");
                        sl_send_reply("403", "Forbidden");
                };
                break;
        };
                
        if (is_method("ACK")) {
                xlog("L_INFO","chuks-test: method is ack\n");
                 sl_send_reply("200", "Acknowledged");
                route(RELAY);
                break;
     } else if (is_method("CANCEL")) {
                xlog("L_INFO","chuks-test: method is cancel\n");
                route(RELAY);
                break;
        } else if (is_method("INVITE")) {
                xlog("L_INFO","chuks-test: method is invite\n");
                setflag(1); # do accounting
                route(INVITE);
                break;
        } else if (is_method("REGISTER")) {
                xlog("L_INFO","chuks-test: method is register\n");
                setflag(1); #do accounting
                route(REGISTER);
                break;
        } else if (is_method("NOTIFY")){
                sl_send_reply("200", "Understood");
                return;
        } else if (is_method("OPTIONS")){
                sl_send_reply("200", "Got it");
                return;
        } else if (is_method("BYE")){
                xlog("L_INFO","chuks-test: method is bye\n");
                sl_send_reply("200", "Bye for now");
                #route(RELAY);
                exit;
        }
                  
                
        lookup("aliases");
        if (!is_uri_host_local()) {
                route(NAT);
                route(RELAY);
                break;
         }
        
        if (!lookup("location")) {
                xlog("L_INFO","chuks-test: no user found in location table\n");
                sl_send_reply("404", "User Not Found"); 
                break;
        }
                        
        route(RELAY);
                        
}
                        
                        
# ---------------------------------------------------------------
# Relay route - default message Handler
# ---------------------------------------------------------------
route[RELAY] {  
        xlog("L_INFO","chuks-test: I am in relay route\n");
        t_on_reply("REPLY_ONE");
        t_on_failure("FAIL_ONE");
        if (!t_relay()) {
                if (is_method("INVITE") || is_method("ACK")) {
                       unforce_rtp_proxy();
                }
                sl_reply_error();
        }
}
                
                
# -----------------------------------------------------------------
# REGISTER Message Handler
# -----------------------------------------------------------------
route[REGISTER] {
        xlog("L_INFO","chuks-test: now in register route\n");
                
        if (!search("^Contact:[ ]*\*") && nat_uac_test("19")){
                setflag(6);
                fix_nated_register();
                force_rport();
        } 
                
        sl_send_reply("100", "Trying to register");
        
        if (!www_authorize("99.89.26.17","subscriber")) {
                xlog("L_INFO","chuks-test: now in register route - www_authorize is not true, challenge\n");
                www_challenge("99.89.26.17","0");
                break;
        }
                  
        if (!check_to()) {
                xlog("L_INFO","chuks-test: now in register route - check_to failed\n");
                sl_send_reply("401", "Unauthorized");
                break;
        }
                
        consume_credentials();
        
        if (!save("location")) {
                sl_reply_error();
        }
}
         
                        
#------------------------------------------------------------
# Invite method route   
#-----------------------------------------------------------
route[INVITE] {         
        xlog("L_INFO","chuks-test: I am in invite route\n");
        if (!allow_trusted("$si", "$(proto{s.toupper})")) {
                xlog("L_INFO","chuks-test: now in invite route, then we should challened bc we're not in trusted table\n");
                if (!proxy_authorize("99.89.26.17","subscriber")) {
                        proxy_challenge("99.89.26.17","0");
                        break;
                } else if (!check_from()) {
                        sl_send_reply("403", "Use From=ID");
                        break;
                }


              consume_credentials();
        }
        
        if (nat_uac_test("19")){
                setflag(6);
                force_rport();
                fix_nated_contact();
        }

        lookup("aliases");
        if (!is_uri_host_local()) {
                xlog("L_INFO","chuks-debug: why am I here?\n");
                route(NAT);
                route(RELAY);
                break;
        }
          
/*      if (uri=~"^sip:1[0-9]{10}@") {
                strip(1);
        }*/
        
                
        if (!lookup("location")) {
                if (uri=~"^sip:(\+|011)[0-9]*@") {   # International Format PSTN
                        xlog("L_INFO","chuks-debug: international\n");
                        route(NAT);
                        route(PSTN);
                        break;
                }
                
                if (uri=~"^sip:[0-9]{10}@") { # Domestic PSTN
                        xlog("L_INFO","chuks-debug: domestic\n");
                        route(NAT);
                        route(PSTN);
                        break;  
                }
        
                if (uri=~"sip:1@"){      # check voicemail
                        xlog("L_INFO","chuks-debug: *98 for voicemail reached\n");
                        route(NAT);
                        route(PSTN);
                        break;
                }

                sl_send_reply("404", "User Not Found");
                break;
        }
                
        route(NAT);
        route(RELAY);
}
                        

                        
                
# ------------------------------------------------------------
# Presence server route
# ------------------------------------------------------------
route[PRESENCE]
{
#!ifdef WITH_PRESENCE
        xlog("L_INFO","chuks-test: I am in presense route\n");
        if (!t_newtran())
        {
                sl_reply_error();
                exit;
        };
                
        if(is_method("PUBLISH"))
        {
                handle_publish();
                t_release();
        }
        else
        if( is_method("SUBSCRIBE"))
        {  
                handle_subscribe();
                t_release();
        }
        exit;
#!endif
                        
        # if presence enabled, this part will not be executed
        if (is_method("PUBLISH") || $rU==$null)
        {
                sl_send_reply("404", "Not here");
                exit;
        }
        return;
}
                        
                
        
# ------------------------------------------------------------
# Caller NAT detection route
# ------------------------------------------------------------
route[NAT]{
        xlog("L_INFO","chuks-test: I am in NAT route\n");
        if (isbflagset(6)){
                force_rport();
                fix_nated_contact();
                force_rtp_proxy();
        }
}              
        
        
 
# -----------------------------------------------------------
# PSTN GW routing      
# -----------------------------------------------------------


route[PSTN] {
        xlog("L_INFO","chuks-test: now in PSTN route\n");
        /*rewritehostport("99.89.26.18:5060");
        route(RELAY);*/
 
        t_on_failure("FAIL_ONE");
        # reset flag to mark no authentication yet performed  
        #resetflag(7);  
        # forward to PSTN
        t_relay_to_udp("99.89.26.18","5060");
        exit;
          
}              
        
        
#-----------------------------------------------------------
# On-reply route
#-----------------------------------------------------------
onreply_route[REPLY_ONE] {
        xlog("L_INFO","chuks-test: I am in reply route\n");
        if (isbflagset(6) && status=~"(180)|(183)|2[0-9][0-9]"){
                if (!search("^Content-Length:[ ]*0")){
                        force_rtp_proxy();
                }
        }

        if (nat_uac_test("19")){
                fix_nated_contact();
        }
}
                
                
# -------------------------------------------------------------
# Sample failure route
# --------------------------------------------------------------
failure_route[FAIL_ONE] {
        xlog("L_INFO","chuks-test: I am in failure route\n");
        
        if (is_method("INVITE") && isbflagset("6") ) {
                unforce_rtp_proxy();
        }

        if(t_check_status("401|407")) {
                if (uac_auth()){
                        #setflag(7);                            # mark that auth was performed
                        t_on_failure("FAIL_ONE");               # trigger again the failure route
                        append_branch();                        # repeat the request with auth response this time
                        t_relay();
                }
        }
        
 
        if (t_check_status("3[0-9][0-9]")) {
                t_reply("404","Not found");
                exit;
        }
        
        
        /*
        if (t_is_canceled()) {
                exit;
        }else{
                xlog("L_INFO", "INFO: CALL TO VOICEMAIL");
                #revert_uri();
                rewritehostport("99.89.26.18:5060");
                append_branch();
                setflag(2);
                t_relay();
        }*/
}        


===========================