Chapter 7. Outside Connectivity

You cannot always control what goes on outside. But you can always control what goes on inside.

Wayne Dyer

In the previous chapters, we have covered a lot of important information that is essential to a working Asterisk system. However, we have yet to accomplish the one thing that is vital to any useful PBX: namely, connecting it to the outside world. In this chapter we will rectify that situation.

The architecture of Asterisk is significant, due in large part to the fact that it treats all channel types as equal. This is in contrast to a traditional PBX, where trunks (which connect to the outside world) and extensions (which connect to users and resources) are very different. The fact that the Asterisk dialplan treats all channels in a similar manner means that in an Asterisk system you can accomplish very easily things that are much more difficult (or impossible) to achieve on a traditional PBX.

This flexibility does come with a price, however. Since the system does not inherently know the difference between an internal resource (such as a telephone set) and an external resource (for example, a telco circuit), it is up to you to ensure that your dialplan handles each type of resource appropriately.

The Basics of Trunking

The purpose of trunking is to provide a shared connection between two entities. For example, a trunk road would be a highway that connects two towns together. Railroads used the term “trunk” extensively, to refer to a major line that connected feeder lines together.

Similarly, in telecom, trunking is used to connect two systems together. Carriers use telecom trunks to connect their networks together, and in a PBX, the circuits that connect the PBX to the outside world are commonly referred to as trunks (although the carriers themselves do not generally consider these to be trunks). From a technical perspective, the definition of a trunk is not as clear as it used to be (PBX trunks used totally different technology from station circuits), but as a concept, trunks are still very important. For example, with VoIP, everything is actually peer-to-peer (so from a technology perspective there isn’t really such a thing as a trunk anymore), but it is still useful to be able to differentiate between VoIP resources that connect to the outside world and VoIP resources that connect to user endpoints (such as SIP telephones).

It’s probably easiest to think of a trunk as a collection of circuits that service a route. So, in an Asterisk PBX, you might have trunks that go to your VoIP provider for long-distance calls, trunks for your PSTN circuits, and trunks that connect your various offices together. These trunks might actually run across the same network connection, but in your dialplan you could treat them quite differently.

While we believe that VoIP will eventually completely replace the PSTN, many of the concepts that are in use on VoIP circuits (such as a “phone number”) owe their existence more to history than any technical requirement, and thus we feel it will be helpful to discuss using traditional PSTN circuits with Asterisk before we get into VoIP.

If the system you are installing will use VoIP circuits only, that is not a problem. Go straight to the VoIP section of this chapter,[68] and we’ll take you through what you need to do. We do recommend reading the PSTN sections at your convenience, since there may be general knowledge in them that could be of use to you, but it is not strictly required in order to understand and use Asterisk.

Fundamental Dialplan for Outside Connectivity

In a traditional PBX, external lines are generally accessed by way of an access code that must be dialed before the number.[69] It is common to use the digit 9 for this purpose.

In Asterisk, it is similarly possible to assign 9 for routing of external calls, but since the Asterisk dialplan is so much more intelligent, it is not really necessary to force your users to dial 9 before placing a call. Typically, you will have an extension range for your system (say, 100–199), and a feature code range (*00 to *99). Anything outside those ranges that matches the dialing pattern for your country or region can be treated as an external call.

If you have one carrier providing all of your external routing, you can handle your external dialing through a few simple pattern matches. The example in this section is valid for the North American Numbering Plan (NANP). If your country is not within the NANP (which serves Canada, the US, and several Caribbean countries), you will need a different pattern match.

The [globals] section contains two variables, named LOCAL and TOLL.[70] The purpose of these variables is to simplify management of your dialplan should you ever need to change carriers. They allow you to make one change to the dialplan that will affect all places where the specified channel is referred to:

[globals]
LOCAL=DAHDI/G0           ; assuming you have a PSTN card in your system
TOLL=SIP/YourVoipCarrier ; as defined in sip.conf

The [external] section contains the actual dialplan code that will recognize the numbers dialed and pass them to the Dial() application[71]:

[external]
exten => _NXXNXXXXXX,1,Dial(${LOCAL}/${EXTEN})  ; 10-digit pattern match for NANP
exten => _NXXXXXX,1,Dial(${LOCAL}/${EXTEN})    ; 7-digit pattern match for NANP
exten => _1NXXNXXXXXX,1,Dial(${TOLL}/${EXTEN}) ; Long-distance pattern match for NANP
exten => _011.,1,Dial(${TOLL}/${EXTEN})        ; International pattern match for 
                                               ; calls made from NANP

; This section is functionally the same as the above section. 
; It is for people who like to dial '9' before their calls
exten => _9NXXNXXXXXX,1,Dial(${LOCAL}/${EXTEN:1})
exten => _9NXXXXXX,1,Dial(${LOCAL}/${EXTEN:1})
exten => _91NXXNXXXXXX,1,Dial(${TOLL}/${EXTEN:1})
exten => _9011.,1,Dial(${TOLL}/${EXTEN:1})

In any context that would be used by sets or user devices, you would use an include=> directive to allow access to the external context:

[LocalSets]
include => external

Warning

It is critically important that you do not include access to the external lines in any context that might process an incoming call. The risk here is that a phishing bot could eventually gain access to your outgoing trunks (you’d be surprised at how common these phishing bots are).

We cannot stress enough how important it is that you ensure that no external resource can access your toll lines.

PSTN Circuits

The Public Switched Telephone Network (PSTN) has existed for over a century. It is the precursor to many of the technologies that shape our world today, from the Internet to MP3 players.

Traditional PSTN Trunks

There are two types of fundamental technology that phone carriers use to deliver telephone circuits: analog and digital.

Analog telephony

The first telephone networks were all analog. The audio signal that you generated with your voice was used to generate an electrical signal that was carried to the other end. The electrical signal had the same characteristics as the sound being produced.

Analog circuits have several characteristics that differentiate them from other circuits you might wish to connect to Asterisk:

  • No signaling channel exists—most signaling is electromechanical.

  • Disconnect supervision is usually delayed by several seconds, and is not completely reliable.

  • Far-end supervision is minimal (for example, answer supervision is lacking).

  • Differences in circuits means that audio characteristics will vary from circuit to circuit, and will require tuning.

Analog circuits that you wish to connect to your Asterisk system will need to connect to a Foreign eXchange Office (FXO) port. Since there is no such thing as an FXO port in any standard computer, an FXO card must be purchased and installed in the system in order to connect traditional analog lines.[72]

Analog ports are not generally used in medium to large systems. They are most commonly used in smaller offices (less than 10 lines; less than 30 phones). Your decision to use analog might be based on some of the following factors:

  • Availability of digital trunks in your area

  • Cost (analog is less expensive at smaller densities, but more expensive at higher densities)

  • Logistics (if you already have analog lines installed, you may wish to keep them)

From a technical perspective, you would normally want to have digital rather than analog circuits. Reality does not always accommodate, though, so analog will likely be around for a few more years yet.

Digital telephony

Digital telephony was developed in order to overcome many of the limitations of analog. Some of the benefits of digital circuits include:

  • No loss of amplitude over long distances

  • Reduced noise on circuits (especially long-distance circuits)

  • Ability to carry more than one call per circuit

  • Faster call setup and teardown

  • Richer signaling information (especially if using ISDN)

  • Lower cost for carriers

  • Lower cost for customers (at higher densities)

In an Asterisk system (or any PBX, for that matter), there are several types of digital circuits you might want to connect:

T1 (24 channels)

Used in Canada and the United States (mostly for ISDN-PRI)

E1 (32 channels)

Used in the rest of the world (ISDN-PRI or MFC/R2)

BRI (2 channels)

Used for ISDN-BRI circuits (Euro-ISDN)

Note that the physical circuit can be further defined by the protocol running on the circuit. For example, a T1 could be used for either ISDN-PRI, or CAS, and an E1 could be used for ISDN-PRI, CAS, or MFC/R2. We’ll discuss the different protocols in the next section.

Installing PSTN Trunks

Depending on the hardware you have installed, the process for installing your PSTN cards will vary. We will discuss installation in general terms, which will apply to all Digium PSTN cards. Other manufacturers tend to provide installation scripts with their hardware, which will automate much of this for you.

Downloading and installing DAHDI

The Digium Asterisk Hardware Device Interface, a.k.a. DAHDI (DAW-dee)[73] is the software framework required to enable communication between PSTN cards and Asterisk. Even if you do not have any PSTN hardware, we recommend installing DAHDI since it is a simple, reliable way to get a valid timing source.[74] Complete DAHDI installation instructions can be found in Chapter 3.

Configuring digital circuits

Digital telephony was developed by carriers as a way to reduce the cost of long-distance circuits, as well as improve transmission quality. The entire PSTN backbone has been fully digital for many years now. The essence of a digital circuit is the digitization of the audio, but digital trunks also allow for more complex and reliable signaling. Several standards have been developed and deployed, and for each standard there may be regional differences as well.

Tip

You can use dahdi_hardware and lsdahdi to help you determine what telephony hardware your system contains. You can also use dahdi_genconf modules to build an /etc/asterisk/modules file for you based on the found hardware.

PRI ISDN

Primary Rate Interface ISDN (commonly known as PRI) is a protocol designed to run primarily on a DS1 circuit (a T1 or E1, depending on where you are in the world) between a carrier and a customer. PRI uses one of the DS0 channels as a signaling channel (referred to as the D-channel). A typical PRI circuit is therefore broken down into a group of B-channels (the bearer channels that actually carry the calls), and a D-channel for signaling. Although it is most common to find a PRI circuit being carried across a single physical circuit (such as a T1 or E1), it is possible to have a PRI circuit span multiple DS1s, and even to have multiple D-channels.[75]

While there are many different ways to configure PRI circuits, we are hoping to avoid confusing you with all of the options (many of which are obsolete or at least no longer in common use), and instead provide examples of the more common configurations.

Note

When installing telephony hardware, be sure you update the /etc/dahdi/modules file to enable the appropriate modules for your hardware and then reload DAHDI with the init script (/etc/init.d/dahdi). You can use the dahdi_genconf modules command to generate the modules file for your system as well.

Most PRI circuits in North America will use a T1 with the following characteristics:

  • Line code: B8ZS (bipolar with 8-zeros substitution)

  • Framing: ESF (extended superframe)

You will need to configure two files. The /etc/dahdi/system.conf file should look something like this:

loadzone = us
defaultzone = us

span = 1,1,0,esf,b8zs
bchan = 1-23
echocanceller = mg2,1-23
hardhdlc = 24

And the /etc/asterisk/chan_dahdi.conf file should look like this:

[trunkgroups]

[channels]

usecallerid = yes
hidecallerid = no
callwaiting = yes
usecallingpres = yes
callwaitingcallerid = yes
threewaycalling = yes
transfer = yes
canpark = yes
cancallforward = yes
callreturn = yes
echocancel = yes
echocancelwhenbridged = yes
relaxdtmf = yes
rxgain = 0.0
txgain = 0.0
group = 1
callgroup = 1
pickupgroup = 1
immediate = no

switchtype = national ; commonly referred to as NI2
context = from-pstn
group = 0
echocancel = yes
signalling = pri_cpe
channel => 1-23

Some carriers will use Nortel’s DMS switch, which commonly uses the DMS100 protocol instead of National ISDN 2. In this case you would set the switchtype to DMS100:

switchtype = dms100

Outside of Canada and the US, PRI circuits will be carried on an E1 circuit.

In Europe, an E1 circuit used for PRI will normally have the following characteristics:

  • Line code: CCS

  • Framing: HDB3 (high-density bipolar)

The /etc/dahdi/system.conf file might look something like this:

span = 1,0,0,ccs,hdb3,crc4
bchan = 1-15,17-31
hardhdlc = 16

And the /etc/asterisk/chan_dahdi.conf file should look something like this:

[trunkgroups]

[channels]

usecallerid = yes
hidecallerid = no
callwaiting = yes
usecallingpres = yes
callwaitingcallerid = yes
threewaycalling = yes
transfer = yes
canpark = yes
cancallforward = yes
callreturn = yes
echocancel = yes
echocancelwhenbridged = yes
relaxdtmf = yes
rxgain = 0.0
txgain = 0.0
group = 1
callgroup = 1
pickupgroup = 1
immediate = no

switchtype = qsig
context = pri_incoming
group = 0
signalling = pri_cpe
channel => 1-15,17-31

BRI ISDN

Basic Rate Interface ISDN (commonly known as BRI, or sometimes even just ISDN) was intended to be the smaller sibling to PRI. BRI only provides two 64K B-channels and a 16K D-channel. The use of BRI has been somewhat limited in North America (we don’t recommend using it for any reason), but in some countries in Europe it is widely used and has almost completely replaced analog.

BRI support under Asterisk will be different depending on the BRI card you are installing. The manufacturer of your BRI card will provide specific installation instructions for its hardware.

Note

When installing telephony hardware, be sure you update the /etc/dahdi/modules file to enable the appropriate modules for your hardware and then reload DAHDI with the init script (/etc/init.d/dahdi). You can use the dahdi_genconf modules command to generate the modules file for your system as well.

MFC/R2

The MFC/R2 protocol could be thought of as a precursor to ISDN. It was at first used on analog circuits, but it is now mostly deployed on the same E1 circuits that also carry ISDN-PRI. This protocol is not typically found in Canada, the US, or Western Europe, but it is very popular in some parts of the world (especially Latin America and Asia), mostly because it tends to be a less expensive service offering from the carriers.

There are many different flavors of this protocol, each country having a different regional variant.

The OpenR2 project provides the libopenr2 library, which needs to be installed on your system in order for Asterisk to support your R2 circuits. Before installing libopenr2, however, you need to have DAHDI installed.

The compilation and installation order, therefore, is:

  1. DAHDI

  2. libopenr2

  3. Asterisk

Once OpenR2 has been installed, you can use the r2test application to see a list of variants that are supported:

$ r2test -l
Variant Code        Country                                 
AR                  Argentina                               
BR                  Brazil                                  
CN                  China                                   
CZ                  Czech Republic                          
CO                  Colombia                                
EC                  Ecuador                                 
ITU                 International Telecommunication Union   
MX                  Mexico                                  
PH                  Philippines                             
VE                  Venezuela

For additional information on configuring R2 support in Asterisk, see the configs/chan_dahdi.conf.sample file included in the Asterisk source tree (search for “mfcr2”). Additionally, OpenR2 contains some sample configuration files for connecting Asterisk to networks in various countries. To read information about some of the country variants, search the /doc/asterisk folder and refer to the documents inside the appropriate subdirectory:

$ ls doc/asterisk/
ar  br  ec  mx  ve

As an example, OpenR2 provides a sample configuration for connecting to Telmex or Axtel in Mexico. We’ll step you through this to give you an idea of the process. First, you must configure DAHDI by modifying /etc/dahdi/system.conf as shown here:

loadzone = us
defaultzone = us

span = 1,1,0,cas,hdb3
cas = 1-15:1101
cas = 17-31:1101

span = 2,1,0,cas,hdb3
cas = 32-46:1101
cas = 48-62:1101

Next, you must configure Asterisk by modifying /etc/asterisk/chan_dahdi.conf as follows:

signalling = mfcr2
mfcr2_variant = mx
mfcr2_get_ani_first = no
mfcr2_max_ani = 10
mfcr2_max_dnis = 4
mfcr2_category = national_subscriber
mfcr2_mfback_timeout = -1
mfcr2_metering_pulse_timeout = -1
; this is for debugging purposes
mfcr2_logdir = log
mfcr2_logging = all
; end debugging configuration
channel => 1-15
channel => 17-31

Configuring analog circuits

There are many companies producing PSTN cards for Asterisk. The card will need to have its drivers installed so that Linux can recognize it (DAHDI ships with these drivers for Digium cards). From that point, configuration is handled by the Asterisk module chan_dahdi.

Tip

You can use dahdi_hardware and lsdahdi to determine what telephony hardware your system contains.

Note

When installing telephony hardware, be sure you update the /etc/dahdi/modules file to enable the appropriate modules for your hardware and then reload DAHDI with the init script (/etc/init.d/dahdi). You can use the dahdi_genconf modules command to generate the modules file for your system as well.

In order to configure an FXO card to work with Asterisk, two files are required.

The first is not an Asterisk configuration file, and is thus located in the /etc/dahdi folder on your system.[76] This file, system.conf allows you to define some basic parameters, as well as specify the channels that will be available to your system. Our example assumes a four-port FXO card, but many different combinations are possible, depending on your hardware.

loadzone = us       ; tonezone defines sounds the interface must produce
                    ; (dialtone, busy signal, ringback, etc.)
defaultzone = us    ; define a default tonezone
fxsks = 1-4         ; which channels on the card will have these parameters

Once your card and channels are known to the operating system, you must configure them for Asterisk by means of the file /etc/asterisk/chan_dahdi.conf:

[channels]

;
; To apply other options to these channels, put them before "channel".
;
signalling = fxs_ks  ; in Asterisk, FXO channels use FXS signaling 
                     ; (and yes, FXS channels use FXO signaling)
channel => 1-4       ; apply all the previously defined settings to this channel

In this example, we have told Asterisk that the first four DAHDI channels in the system are FXO ports.

The s extension

If you are connecting to the PSTN using analog channels, we need to explain extension s. When calls enter a context without a specific destination extension (for example, a ringing FXO line from the PSTN), they are passed to the s extension. (The s stands for “start,” as this is where a call will start if no extension information was passed with the call). This extension can also be useful for accepting calls that have been redirected from other parts of the dialplan. For example, if we had a list of DID numbers that were all going to the same place, we might want to point each DID to the s extension, rather than having to code duplicate dialplan logic for each DID.

Since this is exactly what we need for our dialplan, let’s begin to fill in the pieces. We will be performing three actions on the call (answer it, play a sound file, and hang it up), so our s extension will need three priorities. We’ll place the three priorities below [incoming], because we have decided that all incoming calls should start in this context[77]:

[incoming]
exten => s,1,Answer()
   same => n,Playback(tt-weasels)
   same => n,Hangup()

Obviously, you would not normally want to answer a call and then hang up. Typically, an incoming call will either be answered by an automated attendant, or ring directly to a phone (or group of phones).

VoIP

In the world of telecom, VoIP is still a relatively new concept. For the century or so prior to VoIP, the only way to connect your site to the PSTN was through the use of circuits provided for that purpose by your local telephone company. VoIP now allows for connections between endpoints without the PSTN having to be involved at all (although in most VoIP scenarios, there will still be a PSTN component at some point, especially if there is a traditional E.164 phone number involved).

PSTN Termination

Until VoIP totally replaces the PSTN, there will be a need to connect calls from VoIP networks to the public telephone network. This process is referred to as termination. What it means is that at some point a gateway connected to the PSTN needs to accept calls from the VoIP network and connect them to the PSTN network. From the perspective of the PSTN, the call will appear to have originated at the termination point.

Asterisk can be used as a PSTN termination point. In fact, given that Asterisk handles protocol conversion with ease, this can be an excellent use for an Asterisk system.

In order to provide termination, an Asterisk box will need to be able to handle all of the protocols you wish to connect to the PSTN. In general, this means that your Asterisk box will need a PRI circuit to handle the PSTN connection, and SIP channels to handle the calls coming from the VoIP network. The underlying principle is the same regardless of whether you’re running a small system providing PSTN trunks to an office full of VoIP telephones, or a complex network of gateway machines deployed in strategic locations, offering termination to thousands of subscribers.

Calls from the VoIP network will arrive in the dialplan in whatever context you assigned to the incoming SIP channels, and the dialplan will relay the calls out through the PSTN interface. At its very simplest, a portion of a dialplan that supports termination could look like this:

[from-voip-network]
exten => _X.,1,Verbose(2, Call from VoIP network to ${EXTEN})
   same => n,Dial(DAHDI/g0/${EXTEN})

In reality, though, you will often have to handle a more complex routing plan that takes into consideration things like geography, corporate policy, cost, available resources, and so forth.

Warning

Given that most PSTN circuits will allow you to dial any number, anywhere in the world, and given that you will be expected to pay for all incurred charges, we cannot stress enough the importance of security on any gateway machine that is providing PSTN termination. Criminals put a lot of effort into cracking phone systems (especially poorly secured Asterisk systems), and if you do not pay careful attention to all aspects of security, you will be the victim of toll fraud. It’s only a matter of time.

Do not allow any unsecured VoIP connections into any context that contains PSTN termination.

PSTN Origination

Obviously, if you want to pass calls from your VoIP network to the PSTN, you might also want to be able to accept calls from the PSTN into your VoIP network. The process of doing this is commonly referred to as origination. This simply means that the call originated in the PSTN.

In order to provide origination, a phone number is required. You will therefore need to obtain a circuit from your local phone company, which you will connect to your Asterisk system. Depending on where you are in the world, there are several different types of circuits that could provide this functionality, from a basic analog POTS line to a carrier-grade SS7 circuit.

Note

Phone numbers as used for the purpose of origination are commonly called direct inward dialing numbers (DIDs). This is not strictly the case in all situations (for example, the phone number on a traditional analog line would not be considered a DID), but the term is useful enough that it has caught on. Historically, a DID referred to a phone number associated with a trunk connected to customer premise equipment (CPE).

Since phone numbers are controlled by the traditional telecom industry, you will need to obtain the number either from a carrier directly, or from one of the many companies that purchase numbers in bulk and resell them in smaller blocks. If you obtain a circuit such as a PRI circuit, you will normally be able to order DID numbers to be delivered with that circuit.

In order to accept a call from a circuit you are using for origination, you will normally need to handle the passing of the phone number that was called. This is because PSTN trunks can typically handle more than one phone number, and thus the carrier needs to identify which number was called so that your Asterisk system will know how to route the call. The number that was dialed is commonly referred to as the Dialed Number Identification Service (DNIS) number. The DNIS number and the DID do not have to match,[78] but typically they will. If you are ordering a circuit from the carrier, you will want to ask that they send the DNIS (if they don’t understand that, you may want to consider another carrier).

In the dialplan, you associate the incoming circuit with a context that will know how to handle the incoming digits. As an example, it could look something like this:

[from-pstn] 
; This is the context that would be listed in the config file
; for the circuit (i.e. chan_dahdi.conf)

exten => _X.,1,Verbose(2,Incoming call to ${EXTEN})
    same => n,Goto(number-mapping,${EXTEN},1)

[number-mapping] 
; This context is not strictly required, but will make it easier
; to keep track of your DIDs in a single location in your dialplan. 
; From here you can pass the call to another part of the dialplan
; where the actual dialplan work will take place.

exten => 4165551234,1,Dial(SIP/0000FFFF0001)
exten => 4165554321,1,Goto(autoattendant-context,start,1)
exten => 4165559876,1,VoiceMailMain() ; a handy back door for listening
                                      ; to voice messages

exten => i,1,Verbose(2,Incoming call to invalid number)

In the number-mapping context you explicitly list all of the DIDs that you expect to handle, plus an invalid handler for any DIDs that are not listed (you could send invalid numbers to reception, or to an automated attendant, or to some context that plays an invalid prompt).

VoIP to VoIP

Eventually, the need for the PSTN will likely vanish, and most voice communications will take place over network connections.

The original thinking behind the SIP protocol was that it was to be a peer-to-peer protocol. Technically, this is still the case. What has happened, however, is that things have gotten a bit more complicated. Issues such as security, privacy, corporate policies, integration, centralization, and so forth have made things a bit more involved than simply putting a URI into a SIP phone and having a SIP phone somewhere else ring in response.

The SIP protocol has become bloated and complex. Implementing SIP-based systems and networks has arguably become even more complicated than implementing traditional phone PBXs and networks.[79]

We are not going to get into the complexities of designing and implementing VoIP networks in this book, but we will discuss some of the ways you can configure Asterisk to support VoIP connectivity to other VoIP systems.

Configuring VoIP Trunks

In Asterisk, there is no need to explicitly install your VoIP modules (unless for some reason you did not compile Asterisk with the required modules). There are several VoIP protocols that you can choose to use with Asterisk, but we will focus on the two most popular: SIP and IAX.

Configuring SIP trunks between Asterisk systems

SIP is far and away the most popular of the VoIP protocols—so much so that many people would consider other VoIP protocols to be obsolete (they are not, but it cannot be denied that SIP has dominated VoIP for several years now).

The SIP protocol is peer-to-peer and does not really have a formal trunk specification. This means that whether you are connecting a single phone to your server or connecting two servers together, the SIP connections will be similar.

Connecting two Asterisk systems together with SIP

The need to be able to connect two Asterisk systems together to allow calls to be sent between them is a fairly common requirement. Perhaps you have a company with two physical locations and want to have a PBX at each location, or maybe you’re the administrator of the company PBX and you like Asterisk so much that you would also like to install it at home. This section provides a quick guide on configuring two Asterisk servers to be able to pass calls to each other over SIP. In our example, we will creatively refer to the two servers as serverA and serverB.

The first file that must be modified is /etc/asterisk/sip.conf. This is the main configuration file for setting up SIP accounts. First, this entry must be added to sip.conf on serverA. It defines a SIP peer for the other server:

[serverB]

;
; Specify the SIP account type as 'peer'.  This means that incoming
; calls will be matched on IP address and port number.  So, when Asterisk
; receives a call from 192.168.1.102 and the standard SIP port of 5060,
; it will match this entry in sip.conf.  It will then request authentication
; and expect the password to match the 'secret' specified here.
;
type = peer
;
; This is the IP address for the remote box (serverB). This option can also
; be provided a hostname.
;
host = 192.168.1.102
;
; When we send calls to this SIP peer and must provide authentication,
; we use 'serverA' as our username.
;
username = serverA
;
; This is the shared secret with serverB.  It will be used as the password
; when either receiving a call from serverB, or sending a call to serverB.
;
secret = apples
;
; When receiving a call from serverB, match it against extensions
; in the 'incoming' context of extensions.conf.
;
context = incoming
;
; Start by clearing out the list of allowed codecs.
;
disallow = all
;
; Only allow the ulaw codec.
;
allow = ulaw

Note

Be sure to change the host option to match the appropriate IP address for your own setup.

Now put the following entry in /etc/asterisk/sip.conf on serverB. It is nearly identical to the contents of the entry we put on serverA, but the name of the peer and the IP address were changed:

[serverA]

type = peer
host = 192.168.1.101
username = serverB
secret = apples
context = incoming
disallow = all
allow = ulaw

At this point you should be able to verify that the configuration has been successfully loaded into Asterisk using some CLI commands. The first command to try is sip show peers. As the name implies, it will show all SIP peers that have been configured:

*CLI> sip show peers
Name/username       Host             Dyn Forcerport ACL Port     Status     
serverB/serverA     192.168.1.101                       5060     Unmonitored 
1 sip peers [Monitored: 0 online, 0 offline Unmonitored: 1 online, 0 offline]

Note

You can also try sip show peer serverB. That command will show much more detail.

The last step in setting up SIP calls between two Asterisk servers is to modify the dialplan in /etc/asterisk/extensions.conf. For example, if you wanted any calls made on serverA to extensions 6000 through 6999 to be sent over to serverB, you would use this line in the dialplan:

exten => _6XXX,1,Dial(SIP/${EXTEN}@serverB)

Connecting an Asterisk system to a SIP provider

When you sign up for a SIP provider, you may have service for sending and/or receiving phone calls. The configuration will differ slightly depending on your usage of the SIP provider. Further, the configuration will differ between each provider. Ideally, the SIP provider that you sign up with will provide Asterisk configuration examples to help get you connected as quickly as possible. In case they do not, though, we will attempt to give you a common setup that will help you get started.

If you will be receiving calls from your service provider, the service provider will most likely require your server to register with one of its servers. To do so, you must add a registration line to the [general] section of /etc/asterisk/sip.conf:

[general]
...
register => username:password@your.provider.tld
...

Next, you will need to create a peer entry in sip.conf for your service provider. Here is a sample peer entry:

[myprovider]

type = peer
host = your.provider.tld
username = username
secret = password
; Most providers won't authenticate when they send calls to you,
; so you need this line to just accept their calls.
insecure = invite
dtmfmode = rfc2833
disallow = all
allow = ulaw

Now that the account has been defined, you must add some extensions in the dialplan to allow you to send calls to your service provider:

exten => _1NXXNXXXXXX,1,Dial(SIP/${EXTEN}@myprovider)

Encrypting SIP calls

Asterisk supports TLS for encryption of the SIP signaling and SRTP for encryption of the media streams of a phone call. In this section we will set up calls using SIP TLS and SRTP between two Asterisk severs. The first step is to ensure the proper dependencies have been installed. Ensure that you have both OpenSSL and LibSRTP installed. If either one of these was not installed, reinstall Asterisk after installing these dependencies to ensure that support for TLS and SRTP are included. Once complete, make sure that the res_srtp module was compiled and installed. To install OpenSSL, the package is openssl-devel on CentOS and libssl-dev on Ubuntu. To install LibSRTP, the package is libsrtp-devel on CentOS and libsrtp0-dev on Ubuntu.

Next we will configure SIP TLS. You must enable TLS using the global tlsenable option in the [general] section of /etc/asterisk/sip.conf on both servers. You can optionally specify an address to bind to if you would like to limit listening for TLS connections to a single IP address on the system. In this example, we have the IPv6 wildcard address specified to allow TLS connections on all IPv4 and IPv6 addresses on the system:

[general]

tlsenable = yes
tlsbindaddr = ::

The next step is to get certificates in place. For the purposes of demonstrating the configuration and functionality, we are going to generate self-signed certificates using a helper script distributed with Asterisk. If you were setting this up in a production environment, you might not want to use self-signed certificates. However, if you do, there are a number of applications out there that help make it easier to manage your own certificate authority (CA), such as TinyCA.

The script that we are going to use is ast_tls_cert, which is in the contrib/scripts/ directory of the Asterisk source tree. We need to generate a CA certificate and two server certificates. The first invocation of ast_tls_cert will generate the CA cert and the server cert for serverA. The second invocation of ast_tls_cert will generate the server cert for serverB:

$ cd contrib/scripts
$ mkdir certs
$ ./ast_tls_cert -d certs -C serverA -o serverA
$ ./ast_tls_cert -d certs -C serverB -o serverB -c certs/ca.crt -k certs/ca.key
$ ls certs
ca.cfg  ca.crt  ca.key  serverA.crt  serverA.csr  serverA.key  serverA.pem
serverB.crt  serverB.csr  serverB.key  serverB.pem  tmp.cfg

Now that the certificates have been created, they need to be moved to the appropriate locations on serverA and serverB. We will use the /var/lib/asterisk/keys/ directory to hold the certificates. Move the following files to serverA:

  • ca.crt

  • serverA.pem

And move these files to serverB:

  • ca.crt

  • serverB.pem

With the certificates in place, we can complete the Asterisk configuration. We need to point Asterisk to the server certificate that we just created. Since we’re using self-signed certificates, we also need to point to the CA certificate. In the [general] section of /etc/asterisk/sip.conf on serverA, add these options:

[general]

tlscertfile = /var/lib/asterisk/keys/serverA.pem
tlscafile = /var/lib/asterisk/keys/ca.crt

Make the same changes to sip.conf on serverB:

[general]

tlscertfile = /var/lib/asterisk/keys/serverB.pem
tlscafile = /var/lib/asterisk/keys/ca.crt

Warning

When you create the server certificates, the Common Name field must match the hostname of the server. If you use the ast_tls_cert script, this is the value given to the -C option. If there is a problem verifying the server certificate when you make a call, you may need to fix the Common Name field. Alternatively, for the sake of testing you can set the tlsdontverifyserver option to yes in the [general] section of /etc/asterisk/sip.conf, and Asterisk will allow the call to proceed even if it fails verification of the server certificate.

In Connecting two Asterisk systems together with SIP, we created the configuration necessary to pass calls between serverA and serverB. We are now going to modify that configuration so that Asterisk knows that the calls between the two servers should be encrypted. The only change required is to add the transport = tls option to the peer entry for the other server.

On serverA:

[serverB]

type = peer
host = 192.168.1.102
username = serverA
secret = apples
context = incoming                                                           
disallow = all                    
allow = ulaw
transport = tls                   

On serverB:

[serverA]

type = peer
host = 192.168.1.101
username = serverB
secret = apples
context = incoming                                                           
disallow = all                    
allow = ulaw
transport = tls   

Now when you make a call using Dial(SIP/serverA) or Dial(SIP/serverB), the SIP signaling will be encrypted. You can modify the dialplan to force outgoing calls to have encrypted signaling by setting the CHANNEL(secure_bridge_signaling) function to 1:

[default]

exten => 1234,1,Set(CHANNEL(secure_bridge_signaling)=1)
    same => n,Dial(SIP/1234@serverB)

On the side receiving the call, you can check whether the signaling on an incoming call is encrypted using the CHANNEL(secure_signaling) dialplan function. Consider the following example dialplan:

[incoming]

exten => _X.,1,Answer()
    same => n,GotoIf($["${CHANNEL(secure_signaling)}" = "1"]?secure:insecure)
    same => n(secure),NoOp(Signaling is encrypted.)
    same => n,Hangup()
    same => n(insecure),NoOp(Signaling is not encrypted.)
    same => n,Hangup()

When a call is sent from serverA to serverB using this configuration, you can see from the output on the Asterisk console that the dialplan determines that the signaling of the incoming call is encrypted:

    -- Executing [1234@incoming:1] Answer("SIP/serverA-00000000", "") in new stack
    -- Executing [1234@incoming:2] GotoIf("SIP/serverA-00000000", 
       "1?secure:insecure") in new stack
    -- Goto (incoming,1234,3)
    -- Executing [1234@incoming:3] NoOp("SIP/serverA-00000000", 
       "Signaling is encrypted.") in new stack
    -- Executing [1234@incoming:4] Hangup("SIP/serverA-00000000", "") in new stack

Now that SIP TLS has been set up for calls between serverA and serverB, we will set up SRTP so that the media streams associated with the call are encrypted as well. Luckily, it is quite easy to configure, compared to what was required to get SIP TLS working. First, make sure that you have the res_srtp module loaded in Asterisk:

*CLI> module show like res_srtp.so 
Module                         Description                              Use Count 
res_srtp.so                    Secure RTP (SRTP)                        0         
1 modules loaded

To enable SRTP, set the CHANNEL(secure_bridge_media) function to 1:

[default]

exten => 1234,1,Set(CHANNEL(secure_bridge_signaling)=1)
    same => n,Set(CHANNEL(secure_bridge_media)=1)
    same => n,Dial(SIP/1234@serverB)

This indicates that encrypted media is required for an outbound call. When the call is sent out via SIP, Asterisk will require that SRTP be used, or the call will fail.

With all of these tools in place, you can ensure that calls between two Asterisk servers are fully encrypted. The same techniques should be applied for encrypting calls between Asterisk and a SIP phone.

The dialplan functions provide a mechanism for verifying the encryption status of an incoming call and forcing encryption on an outgoing call. However, keep in mind that these tools only provide the means for controlling encryption for one hop of the call path. If the call goes through multiple servers, these tools do not guarantee that the call is encrypted through the entire call path. It is important to carefully consider what your requirements are for secure calls and take all of the necessary steps to ensure that those requirements are respected throughout the entire call path. Security is complicated, hard work.

Configuring IAX trunks between Asterisk systems

The Inter-Asterisk eXchange protocol, version 2 (most commonly known as IAX[80]) is Asterisk’s own VoIP protocol. It is different from SIP in that the signaling and media are carried in the same connection. This difference is one of the advantages of the IAX protocol, as it makes getting IAX to work across NAT connections much simpler.

IAX trunking

One of the more unique features of the IAX protocol is IAX trunking. Trunking an IAX connection could be useful on any network link that will often be carrying multiple simultaneous VoIP calls between two systems. By encapsulating multiple audio streams in one packet, IAX trunking cuts down on the overhead on the data connection, which can save bandwidth on a heavily used network link.

IAX encryption

The principal advantage of IAX encryption is that it requires one simple change to the /etc/asterisk/iax.conf file:

[general]
encryption = yes

For extra protection, you can set the following option to ensure that no IAX connection can happen without encryption:

forceencryption = yes

Both of these options can be specified in the [general] section, as well as in peer/user/friend sections in iax.conf.

Emergency Dialing

In North America, people are used to being able to dial 911 in order to reach emergency services. Outside of North America, well-known emergency numbers are 112 and 999. If you make your Asterisk system available to people, you are obligated (in many cases regulated) to ensure that calls can be made to emergency services from any telephone connected to the system (even those phones that otherwise are restricted from making calls).

One of the essential pieces of information the emergency response organization needs to know is where the emergency is (i.e., where to send the fire trucks). In a traditional PSTN trunk this information is already known by the carrier and is subsequently passed along to the Public Safety Answering Point (PSAP). With VoIP circuits things can get a bit more complicated, by virtue of the fact that VoIP circuits are not physically tied to any geographical location.

You need to ensure that your system will properly handle 911 calls from any phone connected to it, and you need to communicate what is available to your users. As an example, if you allow users to register to the system from softphones on their laptops, what happens if they are in a hotel room in another country, and they dial 911?[81]

The dialplan for handling emergency calls does not need to be complicated. In fact, it’s far better to keep it simple. People are often tempted to implement all sorts of fancy functionality in the emergency services portions of their dialplans, but if a bug in one of your fancy features causes an emergency call to fail, lives could be at risk. This is no place for playing around. The [emergency-services] section of your dialplan might look something like this:

[emergency-services]
exten => 911,1,Goto(dialpsap,1)
exten => 9911,1,Goto(dialpsap,1) ; some people will dial '9' because 
                               ; they're used to doing that from the PBX
exten => 999,1,Goto(dialpsap,1)
exten => 112,1,Goto(dialpsap,1)

exten => dialpsap,1,Verbose(1,Call initiated to PSAP!)
    same => n,Dial(${LOCAL}/911) ; REPLACE 911 HERE WITH WHATEVER 
                                 ; IS APPROPRIATE TO YOUR AREA

[internal]
include => emergency-services   ; you have to have this in any context 
                                ; that has users in it

In contexts where you know the users are not on-site (for example, remote users with their laptops), something like this might be best instead:

[no-emergency-services]
exten => 911,1,Goto(nopsap,1)
exten => 9911,1,Goto(nopsap,1) ; for people who dial '9' before external calls
exten => 999,1,Goto(nopsap,1)
exten => 112,1,Goto(nopsap,1)

exten => nopsap,1,Verbose(1,Call initiated to PSAP!) 
    same => n,Playback(no-emerg-service) ; you'll need to record this prompt

[remote-users]
include => no-emergency-services

In North America, regulations have obligated many VoIP carriers to offer what is popularly known as E911.[82] When you sign up for their services, they will require address information for each DID that you wish to associate with outgoing calls. This address information will then be sent to the PSAP appropriate to that address, and your emergency calls should be handled the same as they would be if they were dialed on a traditional PSTN circuit.

Handling emergency calls does not have to be complicated (in fact, it is best to keep this as simple as possible). The bottom line is that you need to make sure that the phone system you create allows emergency calls.

Conclusion

Eventually, we believe that the PSTN will disappear entirely. Before that happens, however, a distributed mechanism that is widely used and trusted will be needed to allow organizations and individuals to publish addressing information so that they can be found. We’ll explore some of the ways this is already possible in Chapter 12.



[68] But do not collect $200.

[69] In a key system, each line has a corresponding button on each telephone, and lines are accessed by pressing the desired line key.

[70] You can name these anything you wish. The words “local” and “toll” do not have any built-in meaning to the Asterisk dialplan.

[71] For more information on pattern matches, see Chapter 6.

[72] You would use the exact same card if you wanted to connect a traditional home telephone line to your Asterisk system.

[73] Don’t ask.

[74] There are other ways of getting a timing source, and if you want a really tight system it is possible to run Asterisk without DAHDI, but it’s not something we’re going to cover here.

[75] Sometimes circuits are referenced by the number of B- and D-channels they contain, so a single T1 running the PRI protocol in North America might be referred to as 23B+D, and a dual T1 circuit with a backup D-channel would be a 46B+2D. We’ve even seen PRI referenced as nB+nD, although this can get a little bit pedantic.

[76] In theory, these cards could be used for any software that supports DAHDI; therefore, the basic card configuration is not a part of Asterisk.

[77] There is nothing special about any context name. We could have named this context [stuff_that_comes_in], and as long as that was the context assigned in the channel definition in sip.conf, iax.conf, chan_dahdi.conf, et al., the channel would enter the dialplan in that context. Having said that, it is strongly recommended that you give your contexts names that help you to understand their purpose. Some good context names might include [incoming], [local_calls], [long_distance], [sip_telephones], [user_services], [experimental], [remote_locations], and so forth. Always remember that a context determines how a channel enters the dialplan, so name accordingly.

[78] In traditional PBXs, the purpose of DIDs was to allow connection directly to an extension in the office. Many PBXs could not support concepts such as number translation or flexible digit lengths, and thus the carrier had to pass the extension number as the DID digits, rather than the number that was dialed (the DNIS number). For example, the phone number 416-555-1234 might have been mapped to extension 100, and thus the carrier would have sent the digits 100 to the PBX instead of the DNIS of 4165551234. If you ever replace an old PBX with an Asterisk system, you may find this translation in place, and you’ll need to obtain a list of mappings between the numbers that the caller dials and the numbers that are sent to the PBX. It is also common to see the carrier only pass the last four digits of the DNIS number, which the PBX then translates into an internal number.

[79] There are many proprietary PBX systems in the market that have a basic configuration that will work right out of the box. Asterisk deployments are far more flexible, but seldom as simple.

[80] Pronounced “eeks.”

[81] Don’t assume this can’t happen. When somebody calls 911 it’s because they have an emergency, and it’s not safe to assume that they’re going to be in a rational state of mind.

[82] It’s not actually the carrier that’s offering this; rather it’s a capability of the PSAP. E911 is also used on PSTN trunks, but since that happens without any involvement on your part (the PSTN carriers handle the paperwork for you), you are generally not aware that you have E911 on your local lines.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset