Posts Tagged ‘sip’

OpenSIPS: filter REGISTER requests based on username

Thursday, July 11th, 2019

Formerly we’ve learned how to restrict access with module based on source IP addresses. Today I’ll show how to restrict access to your OpenSIPS based on usernames, being registering.

loadmodule "" # no deps


if (is_method("REGISTER")) {
if(!allow_register("register")) {
sl_send_reply(403, "Forbidden by permissions");

“Deny all, but …” policy – we will allow registrations of explicitly defined usernames and drop anybody else.

register.deny file:


register.allow file:

# this allows lexus, lexus2, lexus3 to register
"^sip:lexus[23]?" : ALL

# regexp seems to be CORRECT, but for some reason lexus2 and lexus3 can not register
# "^sip:lexus[\d]?" : ALL

Have a look how it’s working! A good guy is being registered successfully:

good guy

While a bad guy had been kicked:

bad guy

Another solution using module from Pavel Eremin. The pros of this method is that it allows editing a txt file with usernames defined and reload module via MI interface (no restart needed).

And even one more from Răzvan Crainea.

SIP debugging: catch only certain types of messages

Thursday, May 18th, 2017

Let’s say you need to catch INVITEs only. In this case do:
ngrep -q -W byline -d eth0 INVITE\ sip

‘-W byline’ means to print each SIP packet in readable text mode, line by line
‘-q’ means to be quiet, not to print packet reception hash marks. Without this option your screen will fill up with ###### signs between captured types of packets.
‘-d eth0’ it’s clear
‘INVITE\ sip’ means show INVITEs only. Be careful: if you type ‘INVITE’ word only, you’ll catch nearly every SIP packet, as not only INVITE requests contain the word ‘INVITE’. For example a reply for OPTION request also contains this word among allowed mwthods described in the ‘Allow:’ header field.

And each INVITE request has a request-line like
I mean starting with ‘INVITE’ word, following space and following ‘sip’ word.

Linphone: command line interface

Tuesday, November 24th, 2015

Wanna be a real VoIP nerd? :-) Let’s use Linphone from a command line!

1. ‘linphonec’ – enter the CLI.
2. ‘help’ – list available commands. Now it’s time to create a profile and connect to PBX
3. ‘help proxy’ – show help.
3.1. ‘proxy add’ – and press Enter. Answer to the appeared questions (just look at kisting below):

linphonec> proxy add
Adding new proxy setup. Hit ^D to abort.
Enter proxy sip address:
Your identity for this proxy: sip:1301@
Do you want to register on this proxy (yes/no): yes
Specify register expiration time in seconds (default is 600): 
Expiration: 0 seconds
Specify route if needed: 
No route specified.
sip address: 
identity: sip:1301@
register: yes
expires: 0
registered: no
Accept the above proxy configuration (yes/no) ?: yes
Proxy added.
Password for 1301 on "": MeGaSeCuRePaSs

linphonec> Unregistration on sip: done.

Yes, the message ‘Unregistration on sip: done.’ seems strange, but tcpdump shows that everything is OK.

3.2. Now we may list our proxies:

linphonec> proxy list
****** Proxy 0 - this is the default one - *******
sip address: 
identity: sip:1301@
register: yes
expires: 0
registered: no

4. Let’s call via default proxy:

linphonec> call 79991234567
Establishing call id to <sip:79991234567@>, assigned id 1
Contacting <sip:79991234567@>
linphonec> Call 1 to <sip:79991234567@> in progress.
linphonec> Remote ringing.
linphonec> Early media.
linphonec> Call 1 with <sip:79991234567@> early media.
Call 1 with <sip:79991234567@> connected.
Call answered by <sip:79991234567@>.
linphonec> Media streams established with <sip:79991234567@> for call 1 (audio).</sip:79991234567@></sip:79991234567@></sip:79991234567@></sip:79991234567@></sip:79991234567@></sip:79991234567@></sip:79991234567@>

We may look active calls with ‘calls’ command.
This is how it looks like while ringing:

linphonec> calls
Call states
Id |            Destination              |      State      |    Flags   |
2  | sip:79991234567@          | OutgoingEarlyMedia | 

And this is how it looks like during an established call:

linphonec> calls
Call states
Id |            Destination              |      State      |    Flags   |
2  | sip:79991234567@          | StreamsRunning  | 

If you want to terminate a call, just type ‘terminate’ and press Enter.

If you have some troubles with sound and your PC is behind NAT, play with following parameters: ‘firewall’ and ‘nat’. Maybe you need ‘firewall none’ (it helped me at previous linphonec setup with one-way sound).

5. You may quit linphonec with ‘quit’ command. And these are history log, call log and configuration file in your home directory:

lexus@lexus:~$ ls -lh .linph*
-rw------- 1 lexus lexus  162 нояб. 24 15:10 .linphonec_history
-rw------- 1 lexus lexus 2,5K нояб. 24 15:10 .linphonerc

6. Read the documentation for more information.

Asterisk: конвертируем файлы для MOH

Monday, August 20th, 2012

Вариантов много, подробности тут

Я сначала конвертировал .mp3 в .wav, но Asterisk ругался, поэтому пришлось .wav конвертировать в .sln, он очень хорош для Asterisk’a.

mpg123 -w foo-out.wav foo-in.mp3
sox foo-in.wav -t raw -r 8000 -s -2 -c 1 foo-out.sln

По ссылке выше написано, что можно сразу из .mp3 в .sln, но у меня не получилось.

Asterisk: Provide Music on Hold to the calling party until the called channel answers

Friday, August 17th, 2012

В Интернете много пишут про MusicOnHold, т.е. музыка при удержании звонка. Но когда мы хотим слышать музыку, пока на том конце не успели поднять трубку, MusicOnHold – не совсем то, что нам нужно. Следует использовать параметр ‘m‘ для приложения Dial.

exten => _XXXX,1,Dial(SIP/${EXTEN},15,m)
exten => {EXTEN},n,Hangup()

Обратите внимание, что сначала указывается, как долго дозваниваться, прежде чем звонок будет завершен (15 секунд), а только потом параметр музыки (m). Если поменять местами, музыка играть не будет.

Файл musiconhold.conf тоже должен быть отредактирован.
В минимальной конфигурации этого будет вполне достаточно:



Asterisk, codecs, audio files

Wednesday, August 1st, 2012

В Asterisk разрешены кодеки alaw и g729. Также включена поддержка русского языка:

часть файла sip.conf:


Поэтому скачиваем два файла:

и распаковываем их в соответствующую директорию – /usr/share/asterisk/sounds/ (по крайней мере в Debian так), предварительно создав в ней директорию ru.


Теперь звуки будут проигрываться независимо от того, на какой кодек настроена наша SIP-аппаратура.

Asterisk-1.8 на Debian 6.0.5 Squeeze

Friday, July 27th, 2012
  1. Устанавливаем Debian
  2. Устанавливаем пакет python-software-properties:
    sudo apt-get install python-software-properties
  3. Импортируем public-key:
    sudo apt-key adv --keyserver --recv-keys 175E41DF
    Если будут проблемы с импортированием, можно попробовать вот так:wget -O - | sudo apt-key add -
  4. Добавляем в /etc/apt/sources.list репозиторий:
    deb squeeze maindeb-src squeeze main
  5. Опциональнодобавляем репозиторий ветви Proposed:deb squeeze-proposed main
    deb squeeze-proposed main
  6. Устанавливаем:sudo apt-get update && sudo apt-get install asterisk-1.8

Чуть подробнее и по-английски – на официальном сайте: