This tutorial provides detailed instructions for setting up a SIP Server and managing communication between the server and the CGRateS instance.


The development and testing of the instructions in this tutorial has been done on a Debian 11 (Bullseye) virtual machine.

Scenario Overview

The tutorial comprises the following steps:

  1. SIP Server Setup: Select and install a SIP Server. The tutorial supports the following options:

  2. CGRateS Initialization: Launch a CGRateS instance with the corresponding agent configured. In this context, an “agent” refers to a component within CGRateS that manages communication between CGRateS and the SIP Servers.

  3. Account Configuration: Establish user accounts for different request types.

  4. Balance Addition: Allocate suitable balances to the user accounts.

  5. Call Simulation: Use Zoiper (or any other SIP UA of your choice) to register the user accounts and simulate calls between the configured accounts, and then verify the balance updates post-calls.

  6. Fraud Detection Setup: Implement a fraud detection mechanism to secure and maintain the integrity of the service.

As we progress through the tutorial, each step will be elaborated in detail. Let’s embark on this journey with the SIP Server Setup.

Software Installation

CGRateS already has a section within this documentation regarding installation. It can be found here.

Regarding the SIP Servers, click on the tab corresponding to the choice you made and follow the steps in order to set up:

For detailed information on installing FreeSWITCH on Debian, please refer to its official installation wiki.

Before installing FreeSWITCH, you need to authenticate by creating a SignalWire Personal Access Token. To generate your personal token, follow the instructions in the SignalWire official wiki on creating a personal token.

To install FreeSWITCH and configure it, we have chosen the simplest method using vanilla packages.

TOKEN=YOURSIGNALWIRETOKEN # Insert your SignalWire Personal Access Token here
sudo apt-get update && apt-get install -y gnupg2 wget lsb-release
wget --http-user=signalwire --http-password=$TOKEN -O /usr/share/keyrings/signalwire-freeswitch-repo.gpg https://freeswitch.signalwire.com/repo/deb/debian-release/signalwire-freeswitch-repo.gpg
echo "machine freeswitch.signalwire.com login signalwire password $TOKEN" > /etc/apt/auth.conf
chmod 600 /etc/apt/auth.conf
echo "deb [signed-by=/usr/share/keyrings/signalwire-freeswitch-repo.gpg] https://freeswitch.signalwire.com/repo/deb/debian-release/ `lsb_release -sc` main" > /etc/apt/sources.list.d/freeswitch.list
echo "deb-src [signed-by=/usr/share/keyrings/signalwire-freeswitch-repo.gpg] https://freeswitch.signalwire.com/repo/deb/debian-release/ `lsb_release -sc` main" >> /etc/apt/sources.list.d/freeswitch.list

# If /etc/freeswitch does not exist, the standard vanilla configuration is deployed
sudo apt-get update && apt-get install -y freeswitch-meta-all

Configuration and initialization

This section will be dedicated to configuring both the chosen SIP Server, as well as CGRateS and then get them running.

Regarding the SIP Servers, we have prepared custom configurations in advance, as well as an init scripts that can be used to start the services using said configurations. It can also be used to stop/restart/check on the status of the services. Another way to do that would be to copy the configuration in the default folder, where the Server will be searching for the configuration before starting, with it usually being /etc/<software name>.

The FreeSWITCH setup consists of:

  • vanilla configuration + “mod_json_cdr” for CDR generation;

  • configurations for the following users (found in etc/freeswitch/directory/default): 1001-prepaid, 1002-postpaid, 1003-pseudoprepaid, 1004-rated, 1006-prepaid, 1007-rated;

  • addition of CGRateS’ own extensions befoure routing towards users in the dialplan (found in etc/freeswitch/dialplan/default.xml).

To start FreeSWITCH with the prepared custom configuration, run:

sudo /usr/share/cgrates/tutorials/fs_evsock/freeswitch/etc/init.d/freeswitch start

To verify that FreeSWITCH is running, run the following command:

sudo fs_cli -x status

CGRateS will be configured with the following subsystems enabled:

  • SessionS: started as gateway between the SIP Server and rest of CGRateS subsystems;

  • ChargerS: used to decide the number of billing runs for customer/supplier charging;

  • AttributeS: used to populate extra data to requests (ie: prepaid/postpaid, passwords, paypal account, LCR profile);

  • RALs: used to calculate costs as well as account bundle management;

  • SupplierS: selection of suppliers for each session (in case of OpenSIPS, it will work in tandem with their DRouting module);

  • StatS: computing statistics in real-time regarding sessions and their charging;

  • ThresholdS: monitoring and reacting to events coming from above subsystems;

  • EEs: exporting rated CDRs from CGR StorDB (export path: /tmp).

Just as with the SIP Servers, we have also prepared configurations and init scripts for CGRateS. And just as well, you can manage the CGRateS service using systemctl if you prefer. You can even start it using the cgr-engine binary, like so:

cgr-engine -config_path=<path_to_config> -logger=*stdout


The logger flag from the command above is optional, it’s usually more convenient for us to check for logs in the terminal that cgrates was started in rather than checking the syslog.

sudo /usr/share/cgrates/tutorials/fs_evsock/cgrates/etc/init.d/cgrates start


If you have chosen OpenSIPS, CGRateS has to be started first since the dependency is reversed.

Loading CGRateS Tariff Plans

Now that we have CGRateS installed and started with one of the custom configurations, we can load the prepared data out of the shared folder, containing the following rules:

  • Create the necessary timings (always, asap, peak, offpeak).

  • Configure 3 destinations (1002, 1003 and 10 used as catch all rule).

  • As rating we configure the following:

  • Rate id: RT_10CNT with connect fee of 20cents, 10cents per minute for the first 60s in 60s increments followed by 5cents per minute in 1s increments.

  • Rate id: RT_20CNT with connect fee of 40cents, 20cents per minute for the first 60s in 60s increments, followed by 10 cents per minute charged in 1s increments.

  • Rate id: RT_40CNT with connect fee of 80cents, 40cents per minute for the first 60s in 60s increments, follwed by 20cents per minute charged in 10s increments.

  • Rate id: RT_1CNT having no connect fee and a rate of 1 cent per minute, chargeable in 1 minute increments.

  • Rate id: RT_1CNT_PER_SEC having no connect fee and a rate of 1 cent per second, chargeable in 1 second increments.

  • Accounting part will have following configured:

    • Create 3 accounts: 1001, 1002, 1003.

    • 1001, 1002 will receive 10units of *monetary balance.

cgr-loader -verbose -path=/usr/share/cgrates/tariffplans/tutorial

To verify that all actions successfully performed, we use following cgr-console commands:

  • Make sure all our balances were topped-up:

cgr-console 'accounts Tenant="cgrates.org" AccountIds=["1001"]'
cgr-console 'accounts Tenant="cgrates.org" AccountIds=["1002"]'
  • Query call costs so we can see our calls will have expected costs (final cost will result as sum of ConnectFee and Cost fields):

cgr-console 'cost Category="call" Tenant="cgrates.org" Subject="1001" Destination="1002" AnswerTime="2014-08-04T13:00:00Z" Usage="20s"'
cgr-console 'cost Category="call" Tenant="cgrates.org" Subject="1001" Destination="1002" AnswerTime="2014-08-04T13:00:00Z" Usage="1m25s"'
cgr-console 'cost Category="call" Tenant="cgrates.org" Subject="1001" Destination="1003" AnswerTime="2014-08-04T13:00:00Z" Usage="20s"'

Test calls

1001 -> 1002

Since the user 1001 is marked as prepaid inside the telecom switch, calling between 1001 and 1002 should generate pre-auth and prepaid debits which can be checked with accounts command integrated within cgr-console tool. Charging will be done based on time of day as described in the tariff plan definition above.


An important particularity to note here is the ability of CGRateS SessionManager to refund units booked in advance (eg: if debit occurs every 10s and rate increments are set to 1s, the SessionManager will be smart enough to refund pre-booked credits for calls stoped in the middle of debit interval).

Check that 1001 balance is properly deducted, during the call, and moreover considering that general balance has priority over the shared one debits for this call should take place at first out of general balance.

cgr-console 'accounts Tenant="cgrates.org" AccountIds=["1001"]'

1002 -> 1001

The user 1002 is marked as postpaid inside the telecom switch hence his calls will be debited at the end of the call instead of during a call and his balance will be able to go on negative without influencing his new calls (no pre-auth).

To check that we had debits we use again console command, this time not during the call but at the end of it:

cgr-console 'accounts Tenant="cgrates.org" AccountIds=["1002"]'

1001 -> 1003

The user 1001 call user 1003 and after 12 seconds the call will be disconnected.

CDR Processing

  • The SIP Server generates a CDR event at the end of each call (i.e., FreeSWITCH via HTTP Post and Kamailio via evapi)

  • The event is directed towards the port configured inside cgrates.json due to the automatic handler registration built into the SessionS subsystem.

  • The event reaches CGRateS through the SessionS subsystem in close to real-time.

  • Once inside CGRateS, the event is instantly rated and ready for export.

CDR Exporting

Once the CDRs are mediated, they are available to be exported. To export them, you first need to configure your EEs in configs (already done by the cgrates script from earlier). Important fields to populate are “id” (sample: tutorial_export), “type” (sample: *file_csv), “export_path” (sample: /tmp), and “fields” where you define all the data that you want to export. After that, you can use available RPC APIs or directly call export_cdrs from the console to export them:

cgr-console 'export_cdrs ExportArgs={"ExportFormat":"*file_csv", "ExportPath":"/tmp"}'

Your exported files will be appear on your defined “export_path” folder after the command is executed. In this case the folder is /tmp

Fraud detection

We have configured some action triggers for our tariffplans where more than 20 units of balance topped-up triggers a notification over syslog, and most importantly, an action trigger to monitor for 100 or more units topped-up which will also trigger an account disable together with killing it’s calls if prepaid debits are used.

To verify this mechanism simply add some random units into one account’s balance:

cgr-console 'balance_set Tenant="cgrates.org" Account="1003" Value=23 BalanceType="*monetary" Balance={"ID":"MonetaryBalance"}'
tail -f /var/log/syslog -n 20

cgr-console 'balance_set Tenant="cgrates.org" Account="1001" Value=101 BalanceType="*monetary" Balance={"ID":"MonetaryBalance"}'
tail -f /var/log/syslog -n 20

On the CDRs side we will be able to integrate CdrStats monitors as part of our Fraud Detection system (eg: the increase of average cost for 1001 and 1002 accounts will signal us abnormalities, hence we will be notified via syslog).