Posts Tagged ‘sip’

OpenSIPS: filter REGISTER requests based on username

Thursday, July 11th, 2019

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

loadmodule "permissions.so" # no deps

...

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

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

register.deny file:

ALL : ALL


register.allow file:

# this allows lexus, lexus2, lexus3 to register
"^sip:lexus[23]?@alexeyka.zantsev.com" : ALL

# regexp seems to be CORRECT, but for some reason lexus2 and lexus3 can not register
# "^sip:lexus[\d]?@alexeyka.zantsev.com" : 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 regex.so module from Pavel Eremin. The pros of this method is that it allows editing a txt file with usernames defined and reload regex.so 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
INVITE sip:123@dmn.co...
I mean starting with ‘INVITE’ word, following space and following ‘sip’ word.

Linphone: command line interface

Tuesday, November 24th, 2015

voip_nerd
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 listing below):

linphonec> proxy add
Adding new proxy setup. Hit ^D to abort.
Enter proxy sip address: 10.1.51.13
Your identity for this proxy: sip:1301@10.1.51.13
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: 
route: 
identity: sip:1301@10.1.51.13
register: yes
expires: 0
registered: no
--------------------------------------------
Accept the above proxy configuration (yes/no) ?: yes
Proxy added.
linphonec> 
Password for 1301 on "pbx.secretcompany.com": MeGaSeCuRePaSs

linphonec> Unregistration on sip:10.1.51.13 done.
linphonec>

Yes, the message ‘Unregistration on sip:10.1.51.13 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: 
route: 
identity: sip:1301@10.1.51.13
register: yes
expires: 0
registered: no
linphonec>

4. Let’s call via default proxy:

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

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@10.1.51.13          | OutgoingEarlyMedia | 

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

linphonec> calls
Call states
Id |            Destination              |      State      |    Flags   |
------------------------------------------------------------------------
2  | sip:79991234567@10.1.51.13          | 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

Вариантов много, подробности тут http://www.voip-info.org/wiki/view/Convert+WAV+audio+files+for+use+in+Asterisk

Я сначала конвертировал .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 тоже должен быть отредактирован.
В минимальной конфигурации этого будет вполне достаточно:


[general]

[default]
mode=files
directory=moh
random=yes

Asterisk, codecs, audio files

Wednesday, August 1st, 2012

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

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


disallow=all
allow=g729
allow=alaw
...
language=ru

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

http://downloads.asterisk.org/pub/telephony/sounds/asterisk-core-sounds-ru-g729-current.tar.gz

http://downloads.asterisk.org/pub/telephony/sounds/asterisk-core-sounds-ru-alaw-current.tar.gz

и распаковываем их в соответствующую директорию – /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 pgp.mit.edu --recv-keys 175E41DF
    Если будут проблемы с импортированием, можно попробовать вот так:wget http://packages.asterisk.org/keys/175E41DF.pub -O - | sudo apt-key add -
  4. Добавляем в /etc/apt/sources.list репозиторий:
    deb http://packages.asterisk.org/deb squeeze maindeb-src http://packages.asterisk.org/deb squeeze main
  5. Опциональнодобавляем репозиторий ветви Proposed:deb http://packages.asterisk.org/deb squeeze-proposed main
    deb http://packages.asterisk.org/deb squeeze-proposed main
  6. Устанавливаем:sudo apt-get update && sudo apt-get install asterisk-1.8

Чуть подробнее и по-английски – на официальном сайте: https://wiki.asterisk.org/wiki/display/AST/Asterisk+Packages