18.06.2022

Auth SIP manual

How to md5 auth SIP client manually if you have access to DB with passwords:
in short words:

#       How to calculate manual response to send into Authorization header
#       HA1=MD5(username:realm:password)
#       HA2=MD5(method:digestURI)
#       response=MD5(HA1:nonce:HA2)


route[auth] {
            if (!is_present_hf("Authorization")) return;

# <         converts string with ',' to string with ';' 

            $var(raw_auth) = $hdr(Authorization);
            $var(reg_input)=$var(raw_auth);
            xlog("$var(reg_input) [$ci]");
            $var(reg) = "/,/;/g";
            $var(auth) = $(var(reg_input){re.subst,$var(reg)});
            $var(reg) = "/Digest //g";
            $var(auth) = $(var(auth){re.subst,$var(reg)});
            xlog("$var(auth) [$ci]");
# >

            $var(cl_user)     = $(var(auth){param.value,username});
            $var(cl_realm)    = $(var(auth){param.value,realm});
            $var(cl_uri)      = $(var(auth){param.value,uri});
            $var(cl_nonce)    = $(var(auth){param.value,nonce});
            $var(cl_response) = $(var(auth){param.value,response});

#ask asterisk DB for secret
            avp_db_query("SELECT secret FROM ars_sip  WHERE username='$fU'",
                        "$avp(secret)",1);

       if ($avp(secret) == NULL)
            exit;

#       xlog("CL_CREDENTIALS: $var(cl_user) , $var(cl_realm) , $avp(secret)  [$ci]");
        $var(ha1) = $var(cl_user) + ":"+$var(cl_realm)+":" + $avp(secret);

#       xlog("CL_CREDENTIALS: REGISTER:$var(cl_uri) [$ci]");
        $var(ha2) = "REGISTER:"+ $var(cl_uri) ;
        $var(response) = $(var(ha1){s.md5}) + ":" + $var(cl_nonce)+ ":" + $(var(ha2){s.md5});

        $var(response_md5) = $(var(response){s.md5});


        xlog("my $var(response_md5) client response is $var(cl_response)");
        if ($var(response_md5) != $var(cl_response)) 
               exit;

##############

}

24.05.2022

Update opensips 3.2.2 -> 3.2.6 centos 7

процедура такая получилась:
1. удаляем новую Libmicrohttpd
2. обновляем Opensips и ставим http и prometheus модули со старой либой
2.1 копируем модули от нового в tmp
3. Удаляем старую либу(она удаляется с модулями http и prometheus)
4. ставим новую либу Libmicrohttpd
5. копируем модули httpd и prometheus из tmp в папку с Opensips lib
6. делаем копию файла libmicrohttpd.12 -> libmicrohttpd.10
7. после этого можно перезапускать Opensips

command line script:

yum remove libmicrohttpd -y
yum update -y
yum install opensips-http-modules opensips-prometheus-module -y
#copy httpd.so, prometheus.so, mi_http.so > /tmp
yum remove libmicrohttpd -y
yum install libmicrohttpd-0.9.59
#copy all files from /tmp to /usr/lib64/opensips/modules
cp /usr/lib64/libmicrohttpd.so.12 /usr/lib64/libmicrohttpd.so.10
systemctl daemon-reload
setcap CAP_NET_BIND_SERVICE=+eip /usr/sbin/opensips
systemctl restart opensips

28.01.2022

Opensips. MI. Json. Zabbix.

Opensips 3.2 have beautiful statistics module. For example you may get Data about average count of incoming sip messages directly from MI interface. Also you can output it on Zabbix graph.

  1. Enable mi_http module, add into opensips.conf:
    loadmodule “httpd.so”
    loadmodule “mi_http.so”
    modparam(“mi_http”, “root”, “mi”)
  2. Load statistics module and define statistics profiles and add update_stat_series() functions to script, check for example here.

so, now you be able to ask system for stats though MI interface, for example:

opensips-cli -x mi get_statistics all

internally opensips-cli will ask opensips through http://127.0.0.1:8888/mi with POST request with json body:

#example 1 for statistics...
{ 
  "jsonrpc":"2.0",
  "id":1,
  "method":"get_statistics",
  "params":[
             ["avg_1m:",
              "shmem:",
         metri     "usrloc:"]
          ]
}
#example 2 for ratelimit data...
{
  "jsonrpc":"2.0",
  "id":1,
  "method":"rl_list",
  "params": []
}

You will get result in Json format too.
In our case i just counting how many INVITE,REGISTER and CANCELS initial requests caming to my opensips per 1 minute.

#in opensips.conf: 
....
modparam("statistics", "stat_series_profile", "avg_1m: algorithm=accumulate")
....
route { 
      route(custom_stat);
....
}
route[custom_stat] {
                    # Ignore indialog requests
                    if (has_totag())
                        return ;

                        update_stat_series("avg_1m", "$si", 1);
                        update_stat_series("avg_1m", "$rm", 1);
                        update_stat_series("avg_1m", "$socket_in(proto)|$rm|$si", 1);
}

ZABBIX

  1. Create item like HTTP agent
  2. Use (example 1) inside body of POST request, Set JSON type for request and “convert to JSON”
  3. Add preprocessing JSONPath and “$.body.result” see here for more greatfull examples of how to interpret json answers.
  4. next step will be getting exactly params you want to monitor: create another item, but set it as “Depended” on item you have created previously.
  5. Add preprocessing like this : JSON Path and “$.Pipes[?(@.id == “total_INVITE”)].counter” it will show counter value from example 4 Json answer.
{
    "Pipes": [
        {
            "id": "xxx.xxx.xxx.xxx",
            "algorithm": "TAILDROP",
            "limit": 30,
            "counter": 0
        },
        {
            "id": "total_INVITE",
            "algorithm": "TAILDROP",
            "limit": 150,
            "counter": 0
        }
    ],
    "drop_rate": 1150
}

17.01.2022

Opensips 3.2, Homer 7

Advantages of using Opensips + Homer is possibility to see webrtc\tls traffic

There is how to set simplest configuration on opensips side and Homer side. Homer 7 instruction for Debian 10.

OPENSIPS:

socket=hep_udp:ens5:9000 
socket=hep_tcp:ens5:9000
...
loadmodule "proto_hep.so"
loadmodule "tracer.so"

modparam("proto_hep", "hep_capture_id", 5002)
modparam("proto_hep", "hep_id",  "[hid]homer_ip:9060; transport=tcp; version=3")
modparam("tracer", "trace_id", "[tid]uri=hep:hid")

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

# main request routing logic

route{

        xlog("INCOME $rm TO: $tu [$ci]");
        trace("tid");
...

HOMER 7: CAUTION use only on vanilla debian due to it will replace pg_hba.conf (old one will ba saved)

apt install curl postgresql mc -y
curl -s https://packagecloud.io/install/repositories/qxip/sipcapture/script.deb.sh | sudo bash
apt install heplify-server homer-app -y
cp /etc/postgresql/11/main/pg_hba.conf /etc/postgresql/11/main/pg_hba.conf.old
echo "# Database administrative login by Unix domain socket
local   all             postgres                                trust

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     trust

# IPv4 local connections:
host    all             all             127.0.0.1/32            trust

# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            md5
host    replication     all             ::1/128                 md5
" > /etc/postgresql/11/main/pg_hba.conf

systemctl restart postgresql

homer-app -initialize_db
homer-app -create-table-db-config
homer-app -populate-table-db-config
homer-app -upgrade-table-db-config
homer-app -update-ui-user=admin -update-ui-password=mypassword

systemctl restart homer-app

# Set into /etc/heplify-server.toml
# HEPTCPAddr            = "0.0.0.0:9060"
# HEPTLSAddr            = "0.0.0.0:9061"
#

systemctl restart heplify-server

After this you may to connect to your external_ip:9080 port and use admin\mypassword

17.01.2022

Permission denied interface 80, 443

If you get permission denied for interface when start opensips. Like 44 interface for TLS, solution is here (https://superuser.com/questions/710253/allow-non-root-process-to-bind-to-port-80-and-443)
in short words:
setcap CAP_NET_BIND_SERVICE=+eip /usr/sbin/opensips

10.12.2021

Ansible Part II. Install opensips,opensips-cli,opensips control panel.

You can use this Ansible roles to install full Opensips + Control Panel with one command.

For some reason roles to install Opensips from ansible galaxy not working as expected.

I have modified some roles to make it works.

This will good only for Debian 10 and Centos 7. Most popular systems. 

Roles will install Mysql server with defaults, opensips-cli, opensips 3.2 and opensips control panel with opensips DB. Access to panel is login “admin” and password “opensips”.

Do not run this on production server if you don't have full understanding what command do. It may cause your system loose some important things like ssh keys.
  1. Make usr/local/bin inpath to run command from it.
    export PATH=$PATH:/usr/local/sbin
    echo “export PATH=$PATH:/usr/local/sbin” > /root/.bashrc
  2. Install ansible on debian 10
    apt install git python-pip
    pip install ansible
  3. Generate SSH key for control node host (it should be present in authorized_hosts file on every managed nodes)
    ssh-keygen -t rsa -b 4096
  4. Get repository with modified roles
    git clone https://bitbucket.org/yooxy/ansible-opensips.git
  5. Put roles into /root/.ansible repository.
    mkdir /root/.ansible
    mkdir /root/.ansible/roles
    cp -r ansible-opensips/roles /root/.ansible
  6. Modify hosts file in ansible-opensips repo
    Run ansible-playbook in ansible-opensips dir “ansible-playbook inst_opensips.yml -i hosts”

Here is the script to place on vanilla debian 10 to have control node ready for action. Just do step 6 after this script done.

#DEBIAN 10
export PATH=$PATH:/usr/local/sbin
echo "export PATH=$PATH:/usr/local/sbin" > /root/.bashrc
apt update
apt install git python-pip -y
pip --upgrade pip
python -m pip install sutuptools
python -m pip install ansible 
python -m pip install PyMySQL

ssh-keygen -t rsa -b 4096
git clone https://bitbucket.org/yooxy/ansible-opensips.git
mkdir /etc/ansible
mkdir /root/.ansible
mkdir /root/.ansible/roles
cp -r ansible-opensips/roles /root/.ansible
cd ansible-opensips
ansible-playbook inst_opensips.yml -i hosts




12.03.2021

183 ringback. OPensips + Rtpproxy.

Задача подменить КПВ идущее от провайдера на 10 секунд, далее прокидывать КПВ от провайдера. Задача решается при помощи opensips 3.1 + rtpproxy 2.1 и минимальной конфигурацией.

rtpproxy прекрасно компилируется на базу Ubuntu 20
opensips 3.1 устанавливается из репозиториев с конфигурацией по умолчанию
для проигрывания своего приветсвия необходимо сделать 2 вещи:

а) подключить rtpproxy и использовать rtpproxy_stream2uac функцию. Пример находится в репозитории.

б) для rtpproxy приветствия необходимо подготовить в нужном формате при помощи makeann (создается после компиляции).

репозиторий с примером конфига.

Схема решения:

client -> opensips -> carrier.

22.12.2020

opensips as SBC

Example of opensips SBC with 2 interfaces with full RTP proxy and g729 transcoding.

Software: opensips 3.1, rtpengine, bcg729.

example settings for rtpengine:

OPTIONS="-i external/172.18.254.50!EXTERNAL_IP -i internal/172.25.150.242 -n 127.0.0.1:2223 -m 35000 -M 65000 -L 4 --log-facility=local1 --table=0 --delete-delay=0 --timeout=60 --silent-timeout=600 --final-timeout=7200 –offer-timeout=60 --num-threads=4 --tos=184 –no-fallback"

example opensips config: git clone https://bitbucket.org/yooxy/opensips-sbc-local-external-transcode.git

1.10.2020

opensips 3.1 centos 7

Установка Opensips 3.1\opensips-cli\database на centos 7

устанавливаем репозиторий для centos 7:

yum install epel-release
yum install https://yum.opensips.org/3.1/releases/el/7/x86_64/opensips-yum-releases-3.1-6.el7.noarch.rpm

устанавливаем все пакеты в репозитории opensips (если нужно конечно все модули opensips поставить)
yum repo-pkgs opensips install

opensips-cli можно поставить из репозитория:

yum install opensips-cli -y

А можно из github:

yum install git -y
git clone https://github.com/OpenSIPS/opensips-cli.git
yum install python36 python36-pip python36-devel gcc mysql-devel python36-mysql python36-sqlalchemy python36-pyOpenSSL
cd opensips-cli
python3 setup.py install

Далее обновим и поставим mysql: mariadb и установим рутовый пароль:

cat > /etc/yum.repos.d/mariadb.repo <<EOF
# MariaDB 10.5 CentOS repository list - created 2020-10-09 07:01 UTC 
# http://downloads.mariadb.org/mariadb/repositories/ 
[mariadb] 
name = MariaDB 
baseurl = http://yum.mariadb.org/10.5/centos7-amd64 
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB 
gpgcheck=1
EOF

yum install mariadb-server -y
systemctl start mariadb
mysql_secure_installation

сделаем так чтобы всё запускалось при перезапуске:

systemctl enable opensips
systemctl enable mariadb
vi /etc/systemd/system/multi-user.target.wants/opensips.service

вместо mysqld.service в строчке After, запишем mariadb.service

systemctl daemon-reload

24.09.2020

TCP\TLS NAT Zoiper

Столкнулся с проблемой, когда через sip прокси (opensips) не проходили пакеты (OPTIONS, NOTIFY, INVITE) в сторону uac при использовании TCP и TLS протоколов. при TLS opensips ругался 477/Send Error, при использовании TCP – 408 timeout. И действительно пакеты с opensips уходили, но не доходили до UAC.

Причина была в использовании STUN, если его отключить на Zoiper то связь работает хорошо в обе стороны.