MediaWiki on Linux: Domain Authentication

Enabling LDAP authentication on MediaWiki is fairly straightforward, but there are a couple tricks and gotchas to watch out for.

First, a couple packages are needed: php-ldap (through your packaged manager) and Extension:LDAP Authentication (download and install as instructed).

This assumes that you already have your Linux server working with your LDAP environment.

First, edit /etc/openldap/ldap.conf and add this line to the bottom:

TLS_REQCERT never

After all, we trust our own domain, right?

In your LocalSettings.php, add the following:

require_once ("$IP/extensions/LdapAuthentication/LdapAuthentication.php");

$wgAuth = new LdapAuthenticationPlugin();

$wgLDAPDomainNames = array(
'my.domain.com'
);

$wgLDAPServerNames = array(
'my.domain.com' => 'ldap.domain.com'
);

$wgLDAPSearchAttributes = array(
'my.domain.com' => 'sAMAccountName'
);

$wgLDAPBaseDNs = array(
'my.domain.com' => 'dc=my,dc=domain,dc=com'
);

$wgLDAPEncryptionType = array(
'my.domain.com' => 'ssl'
);

$wgMinimalPasswordLength = 1;

Just change my.domain.com to your FQDN.

After updating both files, on command line run:

/path/to/wiki/maintenance/php update.php

You should now be able to log in with your domain user. I also disabled anonymous editing in my configuration.

Asterisk 13: C*NET IAX Connection (ckts.info)

All of the instructions you see online are for much older versions of Asterisk. It makes sense, as a phone system is always highly customized and can get very complicated, very quick. It’s hard to upgrade an in-place system to a newer version, especially in Asterisk’s case where the newer stuff broke a lot of the old stuff. However, for a new setup, why not use the latest and greatest? More security fixes, more features, and hopefully less bugs. The downside? There isn’t much documentation out there for things on the newer systems yet. This means learning from scratch and adapting!

Thankfully, once I learned a little more about how to use extensions.conf and iax.conf, it appears trivial to get a C*Net connection going (although this is after 10+ hours of head abuse by scratching and banging, and elevated blood pressure).

So let’s get started!

C*NET Side:

You have to register and activate your office code first. When all is said and done, you will receive your e-mail from one of the great people over on that side with your activation information. If you haven’t received this e-mail yet, receiving calls won’t work. It’s part of a manual entry process on their Asterisk server to allow connection to yours (it maps your office code to your IP). The most important information from this e-mail is your username. Of course your country code, office code, and thousands block are also good things to know.

Networking Side:

You MUST have port 4569 UDP opened/forwarded to your Asterisk box. You can call out to C*Net without this port opened, but you cannot receive calls. It’s a fairly obscure port number, so security wise it probably won’t be subjected to much abuse, but make sure you have something like fail2ban in place to help with security.

Asterisk Side:

First, make sure the IAX2 module is loaded:

asterisk*CLI> module show like iax
Module                         Description                              Use Count  Status      Support Level
chan_iax2.so                   Inter Asterisk eXchange (Ver 2)          0          Running              core

If it’s not loaded, make sure you don’t have it as a noload line in modules.conf. If you are like me, you might have disabled it along with a host of others.

IAX.CONF:

Next, edit iax.conf to give IAX a route into your extensions.conf. The [username] context must be changed to the username you received in your e-mail.

[general]
bandwidth=medium
disallow=all
allow=ulaw
jitterbuffer=no
tos=0x12
calltokenoptional=0.0.0.0/0.0.0.0
requirecalltoken=no
autokill=yes

[username]
type=user
context=from-cnet
sendani=yes

Note: context can also be changed to whatever context you want in extensions.conf, however I would recommend using one specifically for C*Net, for reasons you will see next. Double check to make sure the names match.

 

EXTENSIONS.CONF:

On to the potatoes of the meat and potatoes.

In the [globals] context, add the following:

CNETANI=16361000
MYNAME=Big Bird

Change the CNETANI to be whatever yours is. country code + office code + thousands block. Also change MYNAME to your name.

Now, add a new context for the macro that will actually do the dialing out to C*Net. This macro is a heavily modified version of one from Los Angeles Telephone to work with the newer versions of Asterisk. It will not work in versions like 1.8.

[macro-dialcnet]
exten => s,1,Set(CALLERID(num)=${CNETANI})
exten => s,n,Set(result=${ENUMLOOKUP(+${ARG1},iax2,,1,std.ckts.info)})
exten => s,n,GotoIf($["${result}"!=""]?dialiax)
exten => s,n,Set(result=${ENUMLOOKUP(+${ARG1},sip,,1,std.ckts.info)})
exten => s,n,GotoIf($["${result}"!=""]?dialsip)
exten => s,n,Playback(enum-lookup-failed,noanswer)
exten => s,n,Congestion(10)
exten => s,n,MacroExit
exten => s,n(dialsip),Dial(SIP/${result},120)
exten => s,n,MacroExit
exten => s,n(dialiax),Dial(IAX2/${result},120)
exten => s,n,MacroExit

Basically, it uses something called ENUM lookup to get all the IAX (or SIP) information that Asterisk needs to complete the call to C*NET using the DNS name of std.ckts.info so you don’t have to keep track of IP addresses. This particular macro tries an IAX connection first, tries a SIP connection as a fallback, and then finally fails with a failed lookup message.

Now that we have the macro set up, receiving in and dialing out capabilities can be added. Dialing out uses this macro.

Receiving calls:

Earlier in iax.conf the context “from-cnet” was defined, so that is next to be added:

[from-cnet]
exten => _X.,1,NoOp(Incomming call from C*NET: ${CALLERID(all)})
exten => _X.,n,GoTo(from-internal,${EXTEN:-3},1)

A couple important notes with this section:

The first line is just for my debugging and flow following process. NoOp just simply spits out to console/log what you tell it to. You can completely remove the first line if you would like, just change the n to 1 on the second line if you do so.

The second line forwards the call to another context, which in my case is “from-internal”. Change this to whichever context you use for your extensions. This is useful so you don’t have to define them again. The -3 part of ${EXTEN:-3} tells it to forward the last 3 numbers of the call, since I use 3 number extensions. Change it to 2 to only forward the last 2, etc. For example, if you dial 1-636-1112, it goes to the from-internal context with the digits 112.

Sending calls:

Here we just need to add a few quick lines. These are in my “from-internal” context, but can be place in whichever context you have set up for dialing out definitions.

; Dial out to C*NET
exten => _7X.,1,NoOp(Dialing out from ${CALLERID(all)} to ${EXTEN:1} through C*Net)
exten => _7X.,n,Macro(dialcnet,${EXTEN:1})
exten => _7X.,n,Playtones(congestion)

A couple important notes:

The first line again is just for debugging/logging. The same modification can be made if desired.

Because I have a few different ways to make calls outbound of my Asterisk, I am now on “dial 7 to get an outside line” for C*Net. I can also dial 8 to dial out on my cell phone (via x-link Bluetooth), and dial 9 to dial out on my VOIP line (I know, getting out of control!).

Finally, save your extensions.conf, reload the IAX module and the dialplan:

asterisk*CLI> module reload chan_iax2.so

asterisk*CLI> dailplan reload

 

Troubleshooting:

“CAUSE: No such context/extension”

This is most likely an error in your extensions.conf. Even if you have a NoOp command as the very first line, it won’t spit anything out unless there is something correctly configured to do after. In my case, I had assumed I would at least see output from the NoOp command, and that was incorrect and caused hours of high blood pressure.

“CAUSE: No authority found.”

This is an error in the iax.conf configuration. In C*Net’s case, there must be a context with the correct username, and type must be equal to user (type=user).

Done!

That’s it! Enjoy C*Net and the great people that are part of it. Don’t forget to sign up for the mailing list. There are a lot of very smart people on it, and most with 20+ years of industry experience.

https://www.ckts.info/

Asterisk 13/DAHDI: Setting up an FXO Channel

With DAHDI, this turns out not to be so bad. Once you add the physical hardware, There is just a few DAHDI related commands to run, and a small section of extensions.conf to change.

Note: Throughout I use the parameter -vvvvv to indicate as much as verboseness as possible. I use all 5 v’s from habit because of Asterisk’s console command (more of a make sure it’s as verbose as possible by adding many v’s).

First (after installing the hardware), run dahdi_scan as root to make sure it’s detected. Your output should look similar to mine:

mikerm@asterisk:~$ sudo dahdi_scan -vvvvv
[1]
active=yes
alarms=OK
description=Wildcard TDM410P
name=WCTDM/0
manufacturer=Digium
devicetype=Wildcard TDM410P
location=PCI Bus 00 Slot 12
basechan=1
totchans=4
irq=0
type=analog
port=1,FXS
port=2,FXS
port=3,none
port=4,FXO
mikerm@asterisk:~$

Then, run dahdi_cfg as to configure DAHDI to accept the current hardware setup:

mikerm@asterisk:~$ sudo dahdi_cfg -vvvvv
DAHDI Tools Version - 2.10.0.1

DAHDI Version: 2.10.0.1
Echo Canceller(s): MG2
Configuration
======================


Channel map:

Channel 01: FXO Kewlstart (Default) (Echo Canceler: mg2) (Slaves: 01)
Channel 02: FXO Kewlstart (Default) (Echo Canceler: mg2) (Slaves: 02)
Channel 04: FXS Kewlstart (Default) (Echo Canceler: mg2) (Slaves: 04)

3 channels to configure.

Setting echocan for channel 1 to mg2
Setting echocan for channel 2 to mg2
Setting echocan for channel 4 to mg2
mikerm@asterisk:~$

Now, run dahdi_genconf as root to re-generate the other configuration files to set up signalling:

mikerm@asterisk:~$ sudo dahdi_genconf -vvvvv
Default parameters from /etc/dahdi/genconf_parameters
Generating /etc/dahdi/assigned-spans.conf
Generating /etc/dahdi/system.conf
Generating /etc/asterisk/dahdi-channels.conf
mikerm@asterisk:~$

If you have a Digium TDM400P/800P/2400P card, also see: fxotune

If this is the first time configuring DAHDI, make sure “#include /etc/asterisk/dahdi-channels.conf” is under the “channels” context in chan_dahdi.conf:

[channels]
#include /etc/asterisk/dahdi-channels.conf
----- snip -----

 

Now we get to play in extensions.conf. If you check out /etc/asterisk/dahdi-channels.conf, you should see an entry similar to this:

;;; line="4 WCTDM/0/3 FXSKS  (EC: MG2 - INACTIVE)"
signalling=fxs_ks
callerid=asreceived
group=0
context=from-pstn
channel => 4
callerid=
group=
context=default

By default, we now have a context “from-pstn” that we need to either add, or modify in extensions.conf. Here is a part of mine as an example.

[from-pstn]
exten => s,1,NoOp(Incomming call from PSTN: ${CALLERID(all)})
exten => s,n,JabberSend(asterisk,${mikerm},Incomming call from: ${CALLERID(all)}

Note: Don’t assume that only having NoOp in a context will at least spit out a message if it’s called. It actually doesn’t do anything unless there is something else below it that works correctly.

Ubuntu 14.04+ and Asterisk 13: Rotating Logs

After a while, Asterisk can spit out a lot of logging, which eventually will take up a large amount of room. Thankfully Ubuntu already has a program installed by default to help get a handle on logs called “logrotate.” This makes it really simple to add more logs to be rotated. Simply create the file below and add in the logs you want to rotate:

/etc/logrotate.d/asterisk

/var/log/asterisk/messages /var/log/asterisk/debug /var/log/asterisk/queue_log {
        missingok
        rotate 7
        notifempty
        daily
        postrotate
        /usr/sbin/asterisk -rx 'logger reload' > /dev/null 2>&1
        endscript
}

Done! By default, logrotate is scripted to run daily (as seen under /etc/cron.daily).

To take a quick look, this is what the script does:

1st line consists of one or more log paths. The options will apply to all of the logs specified.
missingok – If the log file is missing, go on to the next one without issuing an error message.
rotate 7 – Log files are rotated times before being removed.
notifempty – Do not rotate the log if it is empty.
daily – Logs are rotated daily.
The lines between postrotate and endscript (both of which must appear on lines by themselves) are executed after the log file is rotated. The command in the middle tells Asterisk to reload the logger module which re-creates the files.

Ubuntu 14.04/Asterisk 13: CDR Reporting to MySQL

On Linux, I am familiar with MySQL, and for me it’s the easiest to get going. Asterisk used to include support for MySQL directly (and the config is still there, but not compiled into Asterisk by default anymore), but has since moved to a ODBC structure which offloads the database handling, making it database server agnostic. This is good in the way that it makes writing reports a lot more flexible, but also bad because you have to learn how to configure ODBC also. It’s not as simple as configuring the single ini anymore.

For a few reasons, it is suggested to install/use a MySQL server on another machine. It is safer and more space could be available if there isn’t enough on your Asterisk box. I don’t have that luxury, so I will have the SQL server sit on the server itself for now.

First, install MySQL:

sudo apt-get install mysql-server libmyodbc

During the install it will ask you for a root user password. Please enter a strong password, but one you will remember, as you will need it later.

Now we will need to use MySQL’s CLI client to set up our databases and tables. We will be calling the database “asterisk”, and the standard for CDR reports is a table called “cdr”. Of course, you can create the table in a separate database if you want.

Make a new file to copy all of the lines we need to make the table that CDR will use.

Now, copy and paste the following into a new file, I called it cdr.sql:

cd /tmp
vi cdr.sql

Putting it in /tmp will make the file disappear automatically on reboot. It can really be put anywhere, but this guide assumes that location, so change the path to suit your needs.

Copy and paste the following into the new file:

CREATE TABLE cdr ( 
        calldate datetime NOT NULL default '0000-00-00 00:00:00', 
        clid varchar(80) NOT NULL default '', 
        src varchar(80) NOT NULL default '', 
        dst varchar(80) NOT NULL default '', 
        dcontext varchar(80) NOT NULL default '', 
        channel varchar(80) NOT NULL default '', 
        dstchannel varchar(80) NOT NULL default '', 
        lastapp varchar(80) NOT NULL default '', 
        lastdata varchar(80) NOT NULL default '', 
        duration int(11) NOT NULL default '0', 
        billsec int(11) NOT NULL default '0', 
        disposition varchar(45) NOT NULL default '', 
        amaflags int(11) NOT NULL default '0', 
        accountcode varchar(20) NOT NULL default '', 
        uniqueid varchar(32) NOT NULL default '', 
        userfield varchar(255) NOT NULL default '' 
);

ALTER TABLE `cdr` ADD INDEX ( `calldate` );
ALTER TABLE `cdr` ADD INDEX ( `dst` );
ALTER TABLE `cdr` ADD INDEX ( `accountcode` );

Now, save and exit. Don’t forget the semicolon on the last line.

Log in to MySQL:

mysql -u root -p

Create a new database:

CREATE DATABASE asterisk;

If you are new to MySQL, every command that completes correctly responds with something similar to:

Query OK, 1 row affected (0.00 sec)

If not, it will tell you the error. 99% of the time it’s a syntax error, so check for spelling, etc. Also, every command must end with a semicolon.

Now, let’s go into the database and create the table:

USE asterisk;

It should now say “Database changed.” We can now create the CDR table. This can be done a few ways. You might be able to copy everything below in directly, or you can copy and paste it into a file on your asterisk box in your home directory (or wherever else that’s convenient, like your home directory).

Next, import the table structure we saved to a file earlier:

SOURCE /tmp/cdr.sql

If there are no errors, then it might say “0 rows affected” even though it actually imported.

Double check and make sure it’s all there:

DESCRIBE cdr;

It should show you 16 rows (it will say how many on the bottom).

Now, let’s create a user for CDR (and CEL):

CREATE USER 'asterisk'@'localhost' IDENTIFIED BY 'yourpasswordhere';

I used a random password generator site to generate a very long random password. I highly recommend using the longest, hardest, and strongest password you can bear to use to keep your system secure. These passwords will be stored in plain text in the configuration file, so DO NOT use your “normal” passwords. I immediately wrote the password down in a secure password file I have. Don’t lose this password! It will be needed in a few steps.

Now that all that is done, give this user permissions. For security the user will only be able to add or remove data, not tables or the entire database.

Add permissions:

GRANT SELECT, INSERT, UPDATE, DELETE ON asterisk.* TO 'asterisk'@'localhost';

To double check, you can execute the following command and you should see the permissions listed:

mysql> SHOW GRANTS FOR 'asterisk'@'localhost';
+-----------------------------------------------------------------------------------------------------------------+
| Grants for asterisk@localhost                                                                                   |
+-----------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'asterisk'@'localhost' IDENTIFIED BY PASSWORD '*CCC9275DB00A1C4GH9B756752F9896DBF5EBE395' |
| GRANT SELECT, INSERT, UPDATE, DELETE ON `asterisk`.* TO 'asterisk'@'localhost'                                  |
+-----------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

Now we are done with the MySQL side. type “exit” to leave the console.

Next we will need to configure unixODBC to connect to MySQL. This will vary slightly based on your installation. The file we are looking for is “libmyodbc.so”. Once we know where the file is, we can edit the odbc.ini file to set up a MySQL connection.

First, find and make a note of where libmyodbc.so file is located:

sudo updatedb
locate libmyodbc.so

This usually should return one line. If there is more, look for a path that’s similar to mine:

/usr/lib/i386-linux-gnu/odbc/libmyodbc.so

Do the same for libodbcmyS.so, but without the updatedb command as it’s not needed. Make sure to note both paths.

Edit the /etc/odbcinst.ini to reflect the MySQL setup correctly:

[Default]
Driver          = /path/to/libmyodbc.so

[MySQL]
Description     = MySQL driver
Driver          = /path/to/libmyodbc.so
Setup           = /path/to/libodbcmyS.so

Note: Make sure the [Default] section exists and specifies a driver, otherwise the res_odbc module in Asterisk will bark.

Now, edit the /etc/odbc.ini file (which might be blank) and add the following:

[MySQL-asterisk]
Driver          = MySQL
Description     = MySQL Connector for Asterisk
Server          = localhost
Port            = 3306
Database        = asterisk
username        = asterisk
password        = asteriskpasswordhere
Option          = 3
Socket          = /var/run/mysqld/mysqld.sock

Edit /etc/asterisk/res_odbc.conf to say the following:

[asterisk]
enabled=yes
dsn=MySQL-asterisk
username=asterisk
password=yourasteriskpasswordhere
pooling=no
limit=1
pre-connect=yes
share_connections=yes
sanitysql=select 1
isolation=repeatable_read

Edit /etc/asterisk/cdr_odbc.conf to say the following:

[global]
dsn=asterisk
loguniqueid=yes
table=cdr
dispositionstring=yes
usegmtime=no
hrtime=yes

Note: The dsn in cdr_odbc.conf is the dsn specified in res_odbc.conf, not the dsn specified in odbc.ini.

Edit cdr_manager.conf to say the following:

[general]
enabled = yes

Finally, edit /etc/ cdr_adaptive_odbc.conf to say the following:

[asteriskcdr]
connection=asterisk
table=cdr
alias start=calldate

NOTE: If you use the sample configs that come with Asterisk, then there is already a couple sections that are similar to this one. I personally backed up the default one, and then emptied it out to only say the above lines. This way, there are no problems. However, if you already have database connection definitions here, make sure to not delete those of course.

Save and exit, and then reload Asterisk:

sudo service asterisk restart

Now you can make a test call where the other end answers, and then hang up. There should be no CDR errors.

You can do a quick check to make sure the data made it after the call:

mysql -u asterisk -p yourasteriskpassword
use asterisk;
select * from cdr;

If there are no records, double check for configuration errors. “dsn” names are case sensitive, and must match exactly.

Whew! That’s it!

Troubleshooting:

There are some commands that can be used to troubleshoot any issues you might have:

In the asterisk console, using “cdr show status” should get you something similar:

asterisk*CLI> cdr show status

Call Detail Record (CDR) settings
----------------------------------
  Logging:                    Enabled
  Mode:                       Simple
  Log unanswered calls:       No
  Log congestion:             No

* Registered Backends
  -------------------
    Adaptive ODBC
    cdr_manager
    ODBC

If not, there are some configuration errors somewhere. Your registered backends section might be different, as I have pared mine down to the minimum, but the there should be at least those 3 listed.

In the asterisk console, the command “odbc show all” should look almost exactly like this:

asterisk*CLI> odbc show all

ODBC DSN Settings
-----------------

  Name:   asterisk
  DSN:    MySQL-asterisk
    Last connection attempt: 1969-12-31 17:00:00
  Pooled: No
  Connected: Yes

If not, then there is a database connection issue. Check your odbc.ini and odbcinst.ini files to make sure they are correct, that the user/password is correct, and that the user has proper access to the correct database.

Ubuntu 14.04+/Asterisk 13: Securing Asterisk

A default Asterisk install works, but is pretty insecure, leaving it up to the administrator to decided how to secure it that works for them. Below are some suggestions (and things I have done) to secure Asterisk.

Fail2Ban:

This is a pretty simple implementation, and can be done quickly. I have already setup an email relay on my Asterisk box to email me, so you may need to do that before hand or modify the settings slightly. I really enjoy being able to know by email what bad things are happening.

First, modify Asterisk to spit out errors in a separate log file:

Edit /etc/asterisk/logger.conf and:

– Un-comment the first dateformat line under [general]:

dateformat=%F %T   ; ISO 8601 date format

– Then, modify the messages line near the bottom and add security:

messages => security,notice,warning,error

Restart the Asterisk logger module to make the changes take effect:

sudo asterisk -rx "logger reload"

Now, install fail2ban:

sudo apt-get -y install fail2ban

Add the folowing to the end of /etc/fail2ban/jail.conf:

[asterisk-iptables]
# if more than 4 attempts are made within 6 hours, ban for 24 hours
enabled  = true
filter   = asterisk
action   = iptables-allports[name=ASTERISK, protocol=all]
              sendmail[name=ASTERISK, dest=dest@email.here, sender=fail2ban@address.here]
logpath  = /var/log/asterisk/security
maxretry = 4
findtime = 21600
bantime = 86400

Then, move the existing asterisk.conf in filter.d to a backup in the directory below (or wherever else you would like):

cd /etc/fail2ban/filter.d
sudo mv asterisk.conf ../asterisk.conf.orig

Create a new asterisk.conf in filter.d and add the following:

# Fail2Ban configuration file
#
#
# $Revision: 251 $
#

[INCLUDES]

# Read common prefixes. If any customizations available -- read them from
# common.local
before = common.conf


[Definition]

#_daemon = asterisk

# Option:  failregex
# Notes.:  regex to match the password failures messages in the logfile. The
#          host must be matched by a group named "host". The tag "<HOST>" can
#          be used for standard IP/hostname matching and is only an alias for
#          (?:::f{4,6}:)?(?P<host>\S+)
# Values:  TEXT
#
# Asterisk 1.8 uses Host:Port format which is reflected here

failregex = NOTICE.* .*: Registration from '.*' failed for '<HOST>:.*' - Wrong password
            NOTICE.* .*: Registration from '.*' failed for '<HOST>:.*' - No matching peer found
            NOTICE.* .*: Registration from '.*' failed for '<HOST>:.*' - No matching peer found
            NOTICE.* .*: Registration from '.*' failed for '<HOST>:.*' - Username/auth name mismatch
            NOTICE.* .*: Registration from '.*' failed for '<HOST>:.*' - Device does not match ACL
            NOTICE.* .*: Registration from '.*' failed for '<HOST>:.*' - Peer is not supposed to register
            NOTICE.* .*: Registration from '.*' failed for '<HOST>:.*' - ACL error (permit/deny)
            NOTICE.* .*: Registration from '.*' failed for '<HOST>:.*' - Device does not match ACL
            NOTICE.* .*: Registration from '\".*\".*' failed for '<HOST>:.*' - No matching peer found
            NOTICE.* .*: Registration from '\".*\".*' failed for '<HOST>:.*' - Wrong password
            NOTICE.* <HOST> failed to authenticate as '.*'$
            NOTICE.* .*: No registration for peer '.*' \(from <HOST>\)
            NOTICE.* .*: Host <HOST> failed MD5 authentication for '.*' (.*)
            NOTICE.* .*: Failed to authenticate user .*@<HOST>.*
            NOTICE.* .*: <HOST> failed to authenticate as '.*'
            NOTICE.* .*: <HOST> tried  to authenticate with nonexistent user '.*'
            VERBOSE.*SIP/<HOST>-.*Received incoming SIP connection from unknown peer
   
# Option:  ignoreregex
# Notes.:  regex to ignore. If this regex matches, the line is ignored.
# Values:  TEXT
#
ignoreregex =

Restart fail2ban:

sudo service fail2ban restart

 

SIP On Asterisk:

Edit sip.conf and add the following under [general]:

allowguest=no
alwaysauthreject=yes

Also, change the context line to either an empty context in extensions.conf, or also edit the default extensions.conf and comment out “include => demo” under [public].

Another configuration tip is to not set the extension number as the SIP username.

Ubuntu 14.04+: Set up Postfix to Send to Local Network Relay

I have an internal SMTP mail relay set up on one server, and I have other servers send emails to that relay. I have a pretty simple setup as there is no security to send emails to the relay from inside. This makes the setup on other servers easier (although it’s not as good as it could be security wise).

To set up your server to send to your local SMTP relay, install postfix (and mailutils for the mail command):

sudo apt-get install -y postfix mailutils

Choose “Internet Site” and accept the defaults.

Edit the main.cf config to specify the relay host:

# See /usr/share/postfix/main.cf.dist for a commented, more complete version
.........
relayhost = your.internal.ip.here
.........

Restart postfix:

sudo service postfix restart

Now you can test by sending a quick email to a valid email address:

echo "test" | mail -s "test" -r myserver@somemadeupdomain.com yourreal@email.address

Done!

Asterisk 13: Set Up Local SIP Channels

First, we will create the user/phone account in sip.conf:

[phone1]
type=friend
context=from-internal
defaultusername=phone1
secret=password1111 ;; *change this!*
host=dynamic
qualify=yes ;; keep NAT open
canreinvite=no
mailbox=20 ;; voicemail boxl

This creates a SIP phone called “phone1”, with the username “phone1”, using the password “password1111”. This also links it to the from-internal context in extensions.conf where I have the rest of my extensions. If you want it to go to a different part of the configuration, change that line here.

Now, edit voicemail.conf and add the new mailbox (The default context is quite a ways down):

[default]
; Note: The rest of the system must reference mailboxes defined here as mailbox@default.

20 => 20,User1,user1@asterisk.com

In the Asterisk console, reload:

reload

In the SIP client, the SIP address is now phone1@asterisk.ip.address. The password is what was set in sip.conf. You should now be able to dial other extensions! In some SIP clients, you may need to turn off/disable sRTP Encryption.

Now, the next thing we could do is make the SIP phone an extension in Asterisk. Edit extensions.conf and add the following to [from-internal] context (or whatever your normal extensions context is):

exten => 300,1,Dial(SIP/phone1,20)

In the Asterisk console, reload the dialplan:

dialplan reload

Your SIP phone is now extension 300!

There are a TON of different options for SIP phones, so this is just the beginning.

 

Ubuntu 14.04+ and Asterisk 13: Setting Up DAHDI

If you have added new hardware to your Asterisk box like FXO/FXS cards, there are a few configuration steps.

Note: If you didn’t compile Asterisk with DAHDI, you will need to do those first. SeeĀ Ubuntu 14.04 Server: Install Asterisk 13 (opens in new tab/window) for Installing Asterisk, and just do the steps for compiling DAHDI and compiling Asterisk, but leave outĀ  “&& make samples” so you don’t overwrite your configs. Warning, back up your configs.

I would recommend running sudo -i to switch to root for the following, otherwise, add sudo to the beginning of each command.

At this point I would also recommend opening up 2 SSH sessions to your Asterisk box. One to sit on the Asterisk console, and one to edit different files.

First, make sure DAHDI sees the card:

dahdi_scan -vvvvv

If you do not see any output, run dahdi_hardware and make sure it at least sees the card. If it does see the card, but no modules, then you may need to modify your system to load the correct kernel modules on boot. For example, I had to force my system to load the wctdm24xxp module on boot. If it does not see the card, make sure it is seated in the slot correctly and is known to be good.

If you have a hardware echo cancellation module, add a line in /etc/dahdi/genconf_parameters to enable use of it:

echo_can                hwec

Note: You can add this line anywhere, but I added it where the rest of the echo_can lines were. This is done here so you can continue to use the two tools below to automatically create updated configs with your custom settings.

Then, generate the new configuration files:

dahdi_genconf -vvvvvv

Then, configure the kernel for the installed modules:

dahdi_cfg -vvvvvv

You should see your modules show up in the channel map, and a configuration for the mg2/hwec echo canceller.

Restart DAHDI:

service dahdi restart

Point file chan_dahdi.conf to /etc/asterisk/dahdi-channels.conf:

  # open chan_dahdi.conf and include it under the section [channels]
  #
  # NOTE: You can edit and configure /etc/asterisk/dahdi-channels.conf at any time 
  # to set up your specific options there.
  ...
  [channels]
  ...
  #include /etc/asterisk/dahdi-channels.conf
  ...

Restart Asterisk:

service asterisk restart

Verify everything is working:

asterisk -rvvvvv

dahdi show status
dahdi show channels

If everything goes ok, and you have an FXS channel, you should now get dialtones!

Well that was easy, let’s set up a basic dialplan and a physical extension. I happen to have 2 FXS modules in my machine, so here is an easy example of how to get started with the new hardware:

vi /etc/asterisk/extensions.conf

Scroll all the way down to the bottom and put the following:

[from-internal]
exten => 100,1,Dial(DAHDI/1)
exten => 101,1,Dial(DAHDI/2)

Save and exit. Then, reload the dialplan in the Asterisk console:

dialplan reload

“But how did you know to use the [from-internal] context??” you may scream at me over the internet. The answer is the dahdi-channels.conf which told me on line 30.

context=from-internal

Now you should be able to call extension 100 or 101 and hear the sweet ring of success.

 

 

 

Ubuntu 14.04+ Server: Install Asterisk 13

Updated: 2017/08/20 – Fixed a few typos, changed apt-get instructions to apt, re-did the recommendations section, and removed Google Voice prerequisite section (since it’s been broken a lot lately, it will be a new separate post when I get it to work).

These instructions are a modification of my earlier FreePBX instructions. I ended up not liking FreePBX installed mostly because it makes Asterisk configuration non-standard, and for module compatibility, makes it produce a lot of errors. These errors could be ignored, but my OCD won’t let me personally ignore them. The huge advantage to FreePBX however is the GUI, which makes configuring things a lot easier. The downside to that though is that troubleshooting is a lot harder. Basically it boils down to forcing myself to learn Asterisk the correct way, through the various configuration files.

This assumes you are starting from a clean empty box and you are installing Ubuntu fresh from CD/USB. This is strongly recommended so that there are no other issues. The instructions install a very basic Asterisk install, but gets it ready for databases and other additions.

Note: These instructions are meant to be followed top down. Skipping non-optional sections will have dire consequences.

Recommendations

Run as root

I recommend following the instructions below “as root”, otherwise you will have to put sudo in front of each command.

sudo -i

Keep sources

Keep the sources you download. If you have to make a change, such as add a DAHDI card or update Asterisk, you can recompile/reinstall Asterisk easily from source after making low level changes. Same if you need to change DAHDI itself at that level. The sources don’t take that much room anyway. Keep in mind though, when re-compiling don’t run the commands that generate example configuration files that will overwrite yours.

BACK UP YOUR CONFIGS!

Always back up your configuration files, and off machine. There are a LOT of options out there for Linux to back up file/machines to other machines. It’s worth it to spend some time making always up to date backups that are off your machine so you don’t lose the configs you spent hours and hours on when the drive dies or something else happens to the machine. I speak from personal experience here where I lost my extensions.conf that I spent several full days on to get just right because I was too lazy to make backups. I said “oh I will get around to it”. Don’t “get around to it”, do it NOW. My favorite is a short shell script that tarballs the /etc directory and scp every day, or week depending.

 

Install Ubuntu Server

Install:

You can install 14.04 or 16.04. However, as of this update of the article the mysql driver for CDR reports is broken in 16.04.

During the installation process, select the OpenSSH server option during Software Selection. The rest of the needed packages will be installed later. Otherwise, run the setup as normal.

Setting up the new installation:
At this point, I strongly recommend setting up a static IP address for your Asterisk, but this is optional:
See: Ubuntu 14.04+: Changing to Static IP (Opens in new tab)

Make sure DNS works (and you can resolve names outside of your network):

ping www.google.com

If not, then troubleshoot your network connectivity before continuing.

Update using apt, upgrade the system, and install dependencies then reboot (Make sure to scroll over to get the whole command):

apt update; apt dist-upgrade -y; apt install -y build-essential git-core pkg-config subversion libjansson-dev sqlite autoconf automake libtool libxml2-dev libncurses5-dev unixodbc unixodbc-dev libasound2-dev libogg-dev libvorbis-dev libneon27-dev libsrtp0-dev libspandsp-dev uuid uuid-dev sqlite3 libsqlite3-dev libgnutls-dev libtool-bin python-dev texinfo; reboot

Optional Asterisk Prerequisites

 

DAHDI (if you have/will have physical hardware):

cd /usr/src
wget http://downloads.asterisk.org/pub/telephony/dahdi-linux-complete/dahdi-linux-complete-current.tar.gz
tar xvfz dahdi-linux-complete-current.tar.gz
cd dahdi-linux-complete-*
make all && make install && make config
cd tools
make install-config
dahdi_genconf modules

Note: You will see a bunch of messages like “Can’t read private key”. These can be ignored and are non-critical.

Reboot and re-run “sudo -i”.

 

LIBPRI (if you have/will have physical E1/T1/J1/ISDN cards):

cd /usr/src
wget http://downloads.asterisk.org/pub/telephony/libpri/libpri-1.4-current.tar.gz
tar xvfz libpri-1.4-current.tar.gz
cd libpri-*
make && make install

 

pjproject (if you need PJSIP, which you probably don’t):

cd /usr/src
git clone https://github.com/asterisk/pjproject.git
cd pjproject
./configure --enable-shared --disable-sound --disable-resample --disable-video --disable-opencore-amr
make dep && make && make install

 

Install Asterisk

Compile and install Asterisk:

cd /usr/src
wget http://downloads.asterisk.org/pub/telephony/asterisk/asterisk-13-current.tar.gz
tar xvfz asterisk-13-current.tar.gz
cd asterisk-*
./configure
./contrib/scripts/get_mp3_source.sh #If you want mp3 support
make menuselect

You will be prompted at the point to pick which modules to build. Most of them will be enabled, but if you want to have MP3 support, you need to manually turn on ‘format_mp3’ on the first page. Also, select app_meetme if the MeetMe conference bridge is desired. I also recommend selecting a package from “Extras Sound Packages” for some more cool sounds to play with.

Selecting ‘Save & Exit’ to continue.

make && make install && make config && make samples
ldconfig

Optional: Install Asterisk-Extra-Sounds:
Note that this installs the (8khz) ‘wav’ sound files. If you’re planning on running G722 (High Definition ‘Wideband’) audio, you also want to download the 722 codec pack, which is the second part. If you’re not planning on using Wideband, you can skip that part.

cd /var/lib/asterisk/sounds
wget http://downloads.asterisk.org/pub/telephony/sounds/asterisk-extra-sounds-en-wav-current.tar.gz
tar xvfz asterisk-extra-sounds-en-wav-current.tar.gz
rm -f asterisk-extra-sounds-en-wav-current.tar.gz
# Wideband Audio download (Optional)
wget http://downloads.asterisk.org/pub/telephony/sounds/asterisk-extra-sounds-en-g722-current.tar.gz
tar xfz asterisk-extra-sounds-en-g722-current.tar.gz
rm -f asterisk-extra-sounds-en-g722-current.tar.gz

Start Asterisk and enjoy!

asterisk

Check out the console:

asrterisk -r

Console with a lot of feedback (very useful for troubleshooting):

asterisk -rvvvvvv

Note: If you don’t plan on connecting Asterisk up to LDAP (or don’t know what LDAP is), you can unload that module now and remove some non-critical startup errors:

In /etc/asterisl/modules.conf, add the following to the bottom:

noload => res_config_ldap.so

This module is loaded by default, and can be re-loaded when needed by removing or commenting this line.

 

Have a physical card? Check my article to configure DAHDI next: Setting Up DAHDI

I also recommend checking out my article on securing Asterisk: Securing Asterisk 13