Need help securing Asterisk


#1

I knew nothing about Asterisk and have stumbled my way through setting it up, so please use dummy terms in your answer.

I use Asterisk as an automated phone system. It is used ONLY for incoming calls. It is set up and working on a Ubuntu 10.04 server with Asterisk 1.6.2.5-0ubuntu1.

I used to get peppered with tons of intrusion attempts, which actually brought the asterisk server down. I set up Fail2Ban and tried to set up firewall rules so that only communication from my VoIP provider would be allowed. The problem is greatly reduced now, but my logs show that intrusion attempts are still reaching the server. As far as I can tell, they haven’t ever been successful (I haven’t seen any huge bills or anything), and Fail2Ban does block them after 6 failed attempts, but I’m not really comfortable with any of these attempts still getting to the server.

Here is my sip.conf file with comments removed (and auth info, of course):

;
; SIP Configuration example for Asterisk
;
; Syntax for specifying a SIP device in extensions.conf is
; SIP/devicename where devicename is defined in a section below.
;
; You may also use 
; SIP/username@domain to call any SIP user on the Internet
; (Don't forget to enable DNS SRV records if you want to use this)
; 
; If you define a SIP proxy as a peer below, you may call
; SIP/proxyhostname/user or SIP/user@proxyhostname 
; where the proxyhostname is defined in a section below 
; 
; Useful CLI commands to check peers/users:
;   sip show peers      Show all SIP peers (including friends)
;   sip show users      Show all SIP users (including friends)
;   sip show registry      Show status of hosts we register with
;
;   sip debug         Show all SIP messages
;
;   reload chan_sip.so      Reload configuration file
;            Active SIP peers will not be reconfigured
;

[general]
context=default         ; Default context for incoming calls
allowguest=no         ; Allow or reject guest calls (default is yes)
allowoverlap=no         ; Disable overlap dialing support. (Default is yes)
;allowtransfer=no      ; Disable all transfers (unless enabled in peers or users)
            ; Default is enabled
;realm=mydomain.tld      ; Realm for digest authentication
            ; defaults to "asterisk". If you set a system name in
            ; asterisk.conf, it defaults to that system name
            ; Realms MUST be globally unique according to RFC 3261
            ; Set this to your host name or domain name
bindport=5060         ; UDP Port to bind to (SIP standard port is 5060)
            ; bindport is the local UDP port that Asterisk will listen on
bindaddr=0.0.0.0      ; IP address to bind to (0.0.0.0 binds to all)
srvlookup=yes         ; Enable DNS SRV lookups on outbound calls
            ; Note: Asterisk only uses the first host 
            ; in SRV records
            ; Disabling DNS SRV lookups disables the 
            ; ability to place SIP calls based on domain 
            ; names to some other SIP users on the Internet
            
;domain=mydomain.tld      ; Set default domain for this host
            ; If configured, Asterisk will only allow
            ; INVITE and REFER to non-local domains
            ; Use "sip show domains" to list local domains
;pedantic=yes         ; Enable checking of tags in headers, 
            ; international character conversions in URIs
            ; and multiline formatted headers for strict
            ; SIP compatibility (defaults to "no")

; See doc/ip-tos.txt for a description of these parameters.
;tos_sip=cs3                    ; Sets TOS for SIP packets.
;tos_audio=ef                   ; Sets TOS for RTP audio packets.
;tos_video=af41                 ; Sets TOS for RTP video packets.

;maxexpiry=3600         ; Maximum allowed time of incoming registrations
            ; and subscriptions (seconds)
;minexpiry=60         ; Minimum length of registrations/subscriptions (default 60)
;defaultexpiry=120      ; Default length of incoming/outgoing registration
;t1min=100         ; Minimum roundtrip time for messages to monitored hosts
            ; Defaults to 100 ms
;notifymimetype=text/plain   ; Allow overriding of mime type in MWI NOTIFY
;checkmwi=10         ; Default time between mailbox checks for peers
;buggymwi=no         ; Cisco SIP firmware doesn't support the MWI RFC
            ; fully. Enable this option to not get error messages
            ; when sending MWI to phones with this bug.
;vmexten=voicemail      ; dialplan extension to reach mailbox sets the 
            ; Message-Account in the MWI notify message 
            ; defaults to "asterisk"
disallow=all         ; First disallow all codecs
allow=g726;         ; Allow codecs in order of preference
allow=ulaw;
allow=alaw;
allow=g726aal2;
allow=adpcm;
allow=slin;
allow=lpc10;
allow=speex;
allow=g726;



insecure = port,invite;
;
; This option specifies a preference for which music on hold class this channel
; should listen to when put on hold if the music class has not been set on the
; channel with Set(CHANNEL(musicclass)=whatever) in the dialplan, and the peer
; channel putting this one on hold did not suggest a music class.
;
; This option may be specified globally, or on a per-user or per-peer basis.
;
;mohinterpret=default
;
; This option specifies which music on hold class to suggest to the peer channel
; when this channel places the peer on hold. It may be specified globally or on
; a per-user or per-peer basis.
;
;mohsuggest=default
;
;language=en         ; Default language setting for all users/peers
            ; This may also be set for individual users/peers
;relaxdtmf=yes         ; Relax dtmf handling
;trustrpid = no         ; If Remote-Party-ID should be trusted
;sendrpid = yes         ; If Remote-Party-ID should be sent
;progressinband=never      ; If we should generate in-band ringing always
            ; use 'never' to never use in-band signalling, even in cases
            ; where some buggy devices might not render it
            ; Valid values: yes, no, never Default: never
;useragent=Asterisk PBX      ; Allows you to change the user agent string
;promiscredir = no         ; If yes, allows 302 or REDIR to non-local SIP address
                             ; Note that promiscredir when redirects are made to the
                             ; local system will cause loops since Asterisk is incapable
                             ; of performing a "hairpin" call.
;usereqphone = no      ; If yes, ";user=phone" is added to uri that contains
            ; a valid phone number
;dtmfmode = rfc2833      ; Set default dtmfmode for sending DTMF. Default: rfc2833
            ; Other options: 
            ; info : SIP INFO messages
            ; inband : Inband audio (requires 64 kbit codec -alaw, ulaw)
            ; auto : Use rfc2833 if offered, inband otherwise

;compactheaders = yes      ; send compact sip headers.
;
;videosupport=yes      ; Turn on support for SIP video. You need to turn this on
            ; in the this section to get any video support at all.
            ; You can turn it off on a per peer basis if the general
            ; video support is enabled, but you can't enable it for
            ; one peer only without enabling in the general section.
;maxcallbitrate=384      ; Maximum bitrate for video calls (default 384 kb/s)
            ; Videosupport and maxcallbitrate is settable
            ; for peers and users as well
;callevents=no         ; generate manager events when sip ua 
            ; performs events (e.g. hold)
alwaysauthreject = yes      ; When an incoming INVITE or REGISTER is to be rejected,
                ; for any reason, always reject with '401 Unauthorized'
            ; instead of letting the requester know whether there was
            ; a matching user or peer for their request

;g726nonstandard = yes      ; If the peer negotiates G726-32 audio, use AAL2 packing
            ; order instead of RFC3551 packing order (this is required
            ; for Sipura and Grandstream ATAs, among others). This is
            ; contrary to the RFC3551 specification, the peer _should_
            ; be negotiating AAL2-G726-32 instead :-(

;matchexterniplocally = yes     ; Only substitute the externip or externhost setting if it matches
                                ; your localnet setting. Unless you have some sort of strange network
                                ; setup you will not need to enable this.

;
; If regcontext is specified, Asterisk will dynamically create and destroy a
; NoOp priority 1 extension for a given peer who registers or unregisters with
; us and have a "regexten=" configuration item.  
; Multiple contexts may be specified by separating them with '&'. The 
; actual extension is the 'regexten' parameter of the registering peer or its
; name if 'regexten' is not provided.  If more than one context is provided,
; the context must be specified within regexten by appending the desired
; context after '@'.  More than one regexten may be supplied if they are 
; separated by '&'.  Patterns may be used in regexten.
;
;regcontext=sipregistrations
;
;--------------------------- RTP timers ----------------------------------------------------
; These timers are currently used for both audio and video streams. The RTP timeouts
; are only applied to the audio channel.
; The settings are settable in the global section as well as per device
;
;rtptimeout=60         ; Terminate call if 60 seconds of no RTP or RTCP activity
            ; on the audio channel
            ; when we're not on hold. This is to be able to hangup
            ; a call in the case of a phone disappearing from the net,
            ; like a powerloss or grandma tripping over a cable.
;rtpholdtimeout=300      ; Terminate call if 300 seconds of no RTP or RTCP activity
            ; on the audio channel
            ; when we're on hold (must be > rtptimeout)
;rtpkeepalive=<secs>      ; Send keepalives in the RTP stream to keep NAT open
            ; (default is off - zero)
;--------------------------- SIP DEBUGGING ---------------------------------------------------
;sipdebug = yes         ; Turn on SIP debugging by default, from
            ; the moment the channel loads this configuration
;recordhistory=yes      ; Record SIP history by default 
            ; (see sip history / sip no history)
;dumphistory=yes      ; Dump SIP history at end of SIP dialogue
            ; SIP history is output to the DEBUG logging channel


;--------------------------- STATUS NOTIFICATIONS (SUBSCRIPTIONS) ----------------------------
; You can subscribe to the status of extensions with a "hint" priority
; (See extensions.conf.sample for examples)
; chan_sip support two major formats for notifications: dialog-info and SIMPLE 
;
; You will get more detailed reports (busy etc) if you have a call limit set
; for a device. When the call limit is filled, we will indicate busy. Note that
; you need at least 2 in order to be able to do attended transfers.
;
; For queues, you will need this level of detail in status reporting, regardless
; if you use SIP subscriptions. Queues and manager use the same internal interface
; for reading status information.
;
; Note: Subscriptions does not work if you have a realtime dialplan and use the
; realtime switch.
;
;allowsubscribe=no      ; Disable support for subscriptions. (Default is yes)
;subscribecontext = default   ; Set a specific context for SUBSCRIBE requests
            ; Useful to limit subscriptions to local extensions
            ; Settable per peer/user also
;notifyringing = yes      ; Notify subscriptions on RINGING state (default: no)
;notifyhold = yes      ; Notify subscriptions on HOLD state (default: no)
            ; Turning on notifyringing and notifyhold will add a lot
            ; more database transactions if you are using realtime.
;limitonpeers = yes      ; Apply call limits on peers only. This will improve 
            ; status notification when you are using type=friend
            ; Inbound calls, that really apply to the user part
            ; of a friend will now be added to and compared with
            ; the peer limit instead of applying two call limits,
            ; one for the peer and one for the user.
            ; "sip show inuse" will only show active calls on 
            ; the peer side of a "type=friend" object if this
            ; setting is turned on.

;----------------------------------------- T.38 FAX PASSTHROUGH SUPPORT -----------------------
;
; This setting is available in the [general] section as well as in device configurations.
; Setting this to yes, enables T.38 fax (UDPTL) passthrough on SIP to SIP calls, provided
; both parties have T38 support enabled in their Asterisk configuration 
; This has to be enabled in the general section for all devices to work. You can then
; disable it on a per device basis. 
;
; T.38 faxing only works in SIP to SIP calls, with no local or agent channel being used.
;
; t38pt_udptl = yes            ; Default false
;
;----------------------------------------- OUTBOUND SIP REGISTRATIONS  ------------------------
; Asterisk can register as a SIP user agent to a SIP proxy (provider)
; Format for the register statement is:
;       register => user[:secret[]]@host[:port][/extension]
;
; If no extension is given, the 's' extension is used. The extension needs to
; be defined in extensions.conf to be able to accept calls from this SIP proxy
; (provider).
;
; host is either a host name defined in DNS or the name of a section defined
; below.
;
; Examples:
;
;register => 1234:password@mysipprovider.com   
;
;     This will pass incoming calls to the 's' extension
;
;
;register => 2345:password@sip_proxy/1234
;
;    Register 2345 at sip provider 'sip_proxy'.  Calls from this provider
;    connect to local extension 1234 in extensions.conf, default context,
;    unless you configure a [sip_proxy] section below, and configure a
;    context.
;    Tip 1: Avoid assigning hostname to a sip.conf section like [provider.com]
;    Tip 2: Use separate type=peer and type=user sections for SIP providers
;           (instead of type=friend) if you have calls in both directions
  
;registertimeout=20      ; retry registration calls every 20 seconds (default)
registerattempts=0      ; Number of registration attempts before we give up
            ; 0 = continue forever, hammering the other server
            ; until it accepts the registration
            ; Default is 0 tries, continue forever

register => MY_USERNAME:SECRET:MY_USERNAME@sip.inphonex.com:5060/700
[inphonex]
type=peer
username=MY_USERNAME
fromuser=MY_USERNAME
secret=SECRET ; password used to login their website (same as in register =>)
host=sip.inphonex.com
fromdomain=sip.inphonex.com
nat=yes ; my asterisk is behind nat
canreinvite=yes
qualify=yes
context=inbound-inphonex; context to be used in extensions.conf for inbound calls from inphonex 
disallow=all
allow=ulaw
allow=alaw
allow=gsm
insecure=port,invite

; the following lines should block everybody except Inphonex - TH
deny=0.0.0.0/0.0.0.0
permit=208.239.76.169/255.255.255.255
permit=208.239.76.177/255.255.255.255
permit=208.239.76.170/255.255.255.255
;----------------------------------------- NAT SUPPORT ------------------------
; The externip, externhost and localnet settings are used if you use Asterisk
; behind a NAT device to communicate with services on the outside.

;externip = 207.218.93.7   ; Address that we're going to put in outbound SIP
            ; messages if we're behind a NAT

            ; The externip and localnet is used
            ; when registering and communicating with other proxies
            ; that we're registered with
;externhost=foo.dyndns.net   ; Alternatively you can specify an 
            ; external host, and Asterisk will 
            ; perform DNS queries periodically.  Not
            ; recommended for production 
            ; environments!  Use externip instead
;externrefresh=10      ; How often to refresh externhost if 
            ; used
            ; You may add multiple local networks.  A reasonable 
            ; set of defaults are:
;localnet=192.168.0.0/255.255.0.0; All RFC 1918 addresses are local networks
;localnet=10.0.0.0/255.0.0.0   ; Also RFC1918
;localnet=172.16.0.0/12      ; Another RFC1918 with CIDR notation
;localnet=169.254.0.0/255.255.0.0 ;Zero conf local network

; The nat= setting is used when Asterisk is on a public IP, communicating with
; devices hidden behind a NAT device (broadband router).  If you have one-way
; audio problems, you usually have problems with your NAT configuration or your
; firewall's support of SIP+RTP ports.  You configure Asterisk choice of RTP
; ports for incoming audio in rtp.conf
;
;nat=no            ; Global NAT settings  (Affects all peers and users)
                                ; yes = Always ignore info and assume NAT
                                ; no = Use NAT mode only according to RFC3581 (;rport)
                                ; never = Never attempt NAT mode or RFC3581 support
            ; route = Assume NAT, don't send rport 
            ; (work around more UNIDEN bugs)

;----------------------------------- MEDIA HANDLING --------------------------------
; By default, Asterisk tries to re-invite the audio to an optimal path. If there's
; no reason for Asterisk to stay in the media path, the media will be redirected.
; This does not really work with in the case where Asterisk is outside and have
; clients on the inside of a NAT. In that case, you want to set canreinvite=nonat
;
;canreinvite=yes      ; Asterisk by default tries to redirect the
            ; RTP media stream (audio) to go directly from
            ; the caller to the callee.  Some devices do not
            ; support this (especially if one of them is behind a NAT).
            ; The default setting is YES. If you have all clients
            ; behind a NAT, or for some other reason wants Asterisk to
            ; stay in the audio path, you may want to turn this off.

            ; In Asterisk 1.4 this setting also affect direct RTP
            ; at call setup (a new feature in 1.4 - setting up the
            ; call directly between the endpoints instead of sending
            ; a re-INVITE).

;directrtpsetup=yes      ; Enable the new experimental direct RTP setup. This sets up
            ; the call directly with media peer-2-peer without re-invites.
            ; Will not work for video and cases where the callee sends 
            ; RTP payloads and fmtp headers in the 200 OK that does not match the
            ; callers INVITE. This will also fail if canreinvite is enabled when
            ; the device is actually behind NAT.

;canreinvite=nonat      ; An additional option is to allow media path redirection
            ; (reinvite) but only when the peer where the media is being
            ; sent is known to not be behind a NAT (as the RTP core can
            ; determine it based on the apparent IP address the media
            ; arrives from).

;canreinvite=update      ; Yet a third option... use UPDATE for media path redirection,
            ; instead of INVITE. This can be combined with 'nonat', as
            ; 'canreinvite=update,nonat'. It implies 'yes'.

;----------------------------------------- REALTIME SUPPORT ------------------------
; For additional information on ARA, the Asterisk Realtime Architecture,
; please read realtime.txt and extconfig.txt in the /doc directory of the
; source code.
;
;rtcachefriends=yes      ; Cache realtime friends by adding them to the internal list
            ; just like friends added from the config file only on a
            ; as-needed basis? (yes|no)

;rtsavesysname=yes      ; Save systemname in realtime database at registration
            ; Default= no

;rtupdate=yes         ; Send registry updates to database using realtime? (yes|no)
            ; If set to yes, when a SIP UA registers successfully, the ip address,
            ; the origination port, the registration period, and the username of
            ; the UA will be set to database via realtime. 
            ; If not present, defaults to 'yes'.
;rtautoclear=yes      ; Auto-Expire friends created on the fly on the same schedule
            ; as if it had just registered? (yes|no|<seconds>)
            ; If set to yes, when the registration expires, the friend will
            ; vanish from the configuration until requested again. If set
            ; to an integer, friends expire within this number of seconds
            ; instead of the registration interval.

;ignoreregexpire=yes      ; Enabling this setting has two functions:
            ;
            ; For non-realtime peers, when their registration expires, the
            ; information will _not_ be removed from memory or the Asterisk database
            ; if you attempt to place a call to the peer, the existing information
            ; will be used in spite of it having expired
            ;
            ; For realtime peers, when the peer is retrieved from realtime storage,
            ; the registration information will be used regardless of whether
            ; it has expired or not; if it expires while the realtime peer 
            ; is still in memory (due to caching or other reasons), the 
            ; information will not be removed from realtime storage

;----------------------------------------- SIP DOMAIN SUPPORT ------------------------
; Incoming INVITE and REFER messages can be matched against a list of 'allowed'
; domains, each of which can direct the call to a specific context if desired.
; By default, all domains are accepted and sent to the default context or the
; context associated with the user/peer placing the call.
; Domains can be specified using:
; domain=<domain>[,<context>]
; Examples:
; domain=myasterisk.dom
; domain=customer.com,customer-context
;
; In addition, all the 'default' domains associated with a server should be
; added if incoming request filtering is desired.
; autodomain=yes
;
; To disallow requests for domains not serviced by this server:
; allowexternaldomains=no

;domain=mydomain.tld,mydomain-incoming
            ; Add domain and configure incoming context
            ; for external calls to this domain
;domain=1.2.3.4         ; Add IP address as local domain
            ; You can have several "domain" settings
;allowexternaldomains=no   ; Disable INVITE and REFER to non-local domains
            ; Default is yes
;autodomain=yes         ; Turn this on to have Asterisk add local host
            ; name and local IP to domain list.

; fromdomain=mydomain.tld    ; When making outbound SIP INVITEs to
                             ; non-peers, use your primary domain "identity"
                             ; for From: headers instead of just your IP
                             ; address. This is to be polite and
                             ; it may be a mandatory requirement for some
                             ; destinations which do not have a prior
                             ; account relationship with your server. 

;------------------------------ JITTER BUFFER CONFIGURATION --------------------------
; jbenable = yes              ; Enables the use of a jitterbuffer on the receiving side of a
                              ; SIP channel. Defaults to "no". An enabled jitterbuffer will
                              ; be used only if the sending side can create and the receiving
                              ; side can not accept jitter. The SIP channel can accept jitter,
                              ; thus a jitterbuffer on the receive SIP side will be used only
                              ; if it is forced and enabled.

; jbforce = no                ; Forces the use of a jitterbuffer on the receive side of a SIP
                              ; channel. Defaults to "no".

; jbmaxsize = 200             ; Max length of the jitterbuffer in milliseconds.

; jbresyncthreshold = 1000    ; Jump in the frame timestamps over which the jitterbuffer is
                              ; resynchronized. Useful to improve the quality of the voice, with
                              ; big jumps in/broken timestamps, usually sent from exotic devices
                              ; and programs. Defaults to 1000.

; jbimpl = fixed              ; Jitterbuffer implementation, used on the receiving side of a SIP
                              ; channel. Two implementations are currently available - "fixed"
                              ; (with size always equals to jbmaxsize) and "adaptive" (with
                              ; variable size, actually the new jb of IAX2). Defaults to fixed.

; jblog = no                  ; Enables jitterbuffer frame logging. Defaults to "no".
;-----------------------------------------------------------------------------------

[authentication]
; Global credentials for outbound calls, i.e. when a proxy challenges your
; Asterisk server for authentication. These credentials override
; any credentials in peer/register definition if realm is matched.
;
; This way, Asterisk can authenticate for outbound calls to other
; realms. We match realm on the proxy challenge and pick an set of 
; credentials from this list
; Syntax:
;   auth = <user>:<secret>@<realm>
;   auth = <user>#<md5secret>@<realm>
; Example:
;auth=mark:topsecret@digium.com
; 
; You may also add auth= statements to [peer] definitions 
; Peer auth= override all other authentication settings if we match on realm

;------------------------------------------------------------------------------
; Users and peers have different settings available. Friends have all settings,
; since a friend is both a peer and a user
;
; User config options:        Peer configuration:
; --------------------        -------------------
; context                     context
; callingpres            callingpres
; permit                      permit
; deny                        deny
; secret                      secret
; md5secret                   md5secret
; dtmfmode                    dtmfmode
; canreinvite                 canreinvite
; nat                         nat
; callgroup                   callgroup
; pickupgroup                 pickupgroup
; language                    language
; allow                       allow
; disallow                    disallow
; insecure                    insecure
; trustrpid                   trustrpid
; progressinband              progressinband
; promiscredir                promiscredir
; useclientcode               useclientcode
; accountcode                 accountcode
; setvar                      setvar
; callerid            callerid
; amaflags            amaflags
; call-limit            call-limit
; allowoverlap            allowoverlap
; allowsubscribe         allowsubscribe
; allowtransfer                  allowtransfer
; subscribecontext         subscribecontext
; videosupport            videosupport
; maxcallbitrate         maxcallbitrate
; rfc2833compensate           mailbox
; t38pt_usertpsource          username
;                             template
;                             fromdomain
;                             regexten
;                             fromuser
;                             host
;                             port
;                             qualify
;                             defaultip
;                             rtptimeout
;                             rtpholdtimeout
;                             sendrpid
;                             outboundproxy
;                             rfc2833compensate
;                             t38pt_usertpsource

;[sip_proxy]
; For incoming calls only. Example: FWD (Free World Dialup)
; We match on IP address of the proxy for incoming calls 
; since we can not match on username (caller id)
;type=peer
;context=from-fwd
;host=fwd.pulver.com

;[sip_proxy-out]
;type=peer                   ; we only want to call out, not be called
;secret=guessit
;username=yourusername         ; Authentication user for outbound proxies
;fromuser=yourusername         ; Many SIP providers require this!
;fromdomain=provider.sip.domain   
;host=box.provider.com
;usereqphone=yes         ; This provider requires ";user=phone" on URI
;call-limit=5            ; permit only 5 simultaneous outgoing calls to this peer
;outboundproxy=proxy.provider.domain   ; send outbound signaling to this proxy, not directly to the peer
               ; Call-limits will not be enforced on real-time peers,
               ; since they are not stored in-memory
;port=80            ; The port number we want to connect to on the remote side
               ; Also used as "defaultport" in combination with "defaultip" settings

;------------------------------------------------------------------------------
; Definitions of locally connected SIP devices
;
; type = user   a device that authenticates to us by "from" field to place calls
; type = peer   a device we place calls to or that calls us and we match by host
; type = friend two configurations (peer+user) in one
;
; For device names, we recommend using only a-z, numerics (0-9) and underscore
; 
; For local phones, type=friend works most of the time
;
; If you have one-way audio, you probably have NAT problems. 
; If Asterisk is on a public IP, and the phone is inside of a NAT device
; you will need to configure nat option for those phones.
; Also, turn on qualify=yes to keep the nat session open

;[grandstream1]
;type=friend          
;context=from-sip      ; Where to start in the dialplan when this phone calls
;callerid=John Doe <1234>   ; Full caller ID, to override the phones config
            ; on incoming calls to Asterisk
;host=192.168.0.23      ; we have a static but private IP address
            ; No registration allowed
;nat=no            ; there is not NAT between phone and Asterisk
;canreinvite=yes      ; allow RTP voice traffic to bypass Asterisk
;dtmfmode=info         ; either RFC2833 or INFO for the BudgeTone
;call-limit=1         ; permit only 1 outgoing call and 1 incoming call at a time
            ; from the phone to asterisk
            ; 1 for the explicit peer, 1 for the explicit user,
            ; remember that a friend equals 1 peer and 1 user in
            ; memory
            ; This will affect your subscriptions as well.
            ; There is no combined call counter for a "friend"
            ; so there's currently no way in sip.conf to limit
            ; to one inbound or outbound call per phone. Use
            ; the group counters in the dial plan for that.
            ;
;mailbox=1234@default      ; mailbox 1234 in voicemail context "default"
;disallow=all         ; need to disallow=all before we can use allow=
;allow=ulaw         ; Note: In user sections the order of codecs
            ; listed with allow= does NOT matter!
;allow=alaw
;allow=g723.1         ; Asterisk only supports g723.1 pass-thru!
;allow=g729         ; Pass-thru only unless g729 license obtained
;callingpres=allowed_passed_screen   ; Set caller ID presentation
            ; See doc/callingpres.txt for more information


[xlite1]
; Turn off silence suppression in X-Lite ("Transmit Silence"=YES)!
; Note that Xlite sends NAT keep-alive packets, so qualify=yes is not needed
type=friend
regexten=1000         ; When they register, create extension 1234
callerid="Xlite" <1000>
context = phones
host=dynamic         ; This device needs to register
nat=yes         ; X-Lite is behind a NAT router

[xlite2]
; Turn off silence suppression in X-Lite ("Transmit Silence"=YES)!
; Note that Xlite sends NAT keep-alive packets, so qualify=yes is not needed
type=friend
regexten=1002         ; When they register, create extension 1234
callerid="Xlite2" <1002>
context = phones
host=dynamic         ; This device needs to register
nat=yes         ; X-Lite is behind a NAT router




;canreinvite=no         ; Typically set to NO if behind NAT
;disallow=all
;allow=gsm         ; GSM consumes far less bandwidth than ulaw
;allow=ulaw
;allow=alaw
;mailbox=1234@default,1233@default   ; Subscribe to status of multiple mailboxes


;[snom]
;type=friend         ; Friends place calls and receive calls
;context=from-sip      ; Context for incoming calls from this user
;secret=blah
;subscribecontext=localextensions   ; Only allow SUBSCRIBE for local extensions
;language=de         ; Use German prompts for this user 
;host=dynamic         ; This peer register with us
;dtmfmode=inband      ; Choices are inband, rfc2833, or info
;defaultip=192.168.0.59      ; IP used until peer registers
;mailbox=1234@context,2345      ; Mailbox(-es) for message waiting indicator
;subscribemwi=yes      ; Only send notifications if this phone 
            ; subscribes for mailbox notification
;vmexten=voicemail      ; dialplan extension to reach mailbox 
            ; sets the Message-Account in the MWI notify message
            ; defaults to global vmexten which defaults to "asterisk"
;disallow=all
;allow=ulaw         ; dtmfmode=inband only works with ulaw or alaw!


;[polycom]
;type=friend         ; Friends place calls and receive calls
;context=from-sip      ; Context for incoming calls from this user
;secret=blahpoly
;host=dynamic         ; This peer register with us
;dtmfmode=rfc2833      ; Choices are inband, rfc2833, or info
;username=polly         ; Username to use in INVITE until peer registers
            ; Normally you do NOT need to set this parameter
;disallow=all
;allow=ulaw                     ; dtmfmode=inband only works with ulaw or alaw!
;progressinband=no      ; Polycom phones don't work properly with "never"


;[pingtel]
;type=friend
;secret=blah
;host=dynamic
;insecure=port         ; Allow matching of peer by IP address without 
            ; matching port number
;insecure=invite      ; Do not require authentication of incoming INVITEs
;insecure=port,invite      ; (both)
;qualify=1000         ; Consider it down if it's 1 second to reply
            ; Helps with NAT session
            ; qualify=yes uses default value
;
; Call group and Pickup group should be in the range from 0 to 63
;
;callgroup=1,3-4      ; We are in caller groups 1,3,4
;pickupgroup=1,3-5      ; We can do call pick-p for call group 1,3,4,5
;defaultip=192.168.0.60      ; IP address to use if peer has not registered
;deny=0.0.0.0/0.0.0.0      ; ACL: Control access to this account based on IP address
;permit=192.168.0.60/255.255.255.0

;[cisco1]
;type=friend
;secret=blah
;qualify=200         ; Qualify peer is no more than 200ms away
;nat=yes         ; This phone may be natted
            ; Send SIP and RTP to the IP address that packet is 
            ; received from instead of trusting SIP headers 
;host=dynamic         ; This device registers with us
;canreinvite=no         ; Asterisk by default tries to redirect the
            ; RTP media stream (audio) to go directly from
            ; the caller to the callee.  Some devices do not
            ; support this (especially if one of them is 
            ; behind a NAT).
;defaultip=192.168.0.4      ; IP address to use until registration
;username=goran         ; Username to use when calling this device before registration
            ; Normally you do NOT need to set this parameter
;setvar=CUSTID=5678      ; Channel variable to be set for all calls from this device

;[pre14-asterisk]
;type=friend
;secret=digium
;host=dynamic
;rfc2833compensate=yes      ; Compensate for pre-1.4 DTMF transmission from another Asterisk machine.
            ; You must have this turned on or DTMF reception will work improperly.
;t38pt_usertpsource=yes         ; Use the source IP address of RTP as the destination IP address for UDPTL packets
                                ; if the nat option is enabled. If a single RTP packet is received Asterisk will know the
                                ; external IP address of the remote device. If port forwarding is done at the client side
                                ; then UDPTL will flow to the remote device.

Notice at line 291, I am attempting to block all except for the three IP addresses that my provider says that they use. I have similar rules set up in my firewall, but this still isn’t working 100%.

Here is a sample from my log files that shows these intrusion attempts (again, auth info removed):

[2011-11-20 12:41:45] NOTICE[5482] chan_sip.c: Registration from '"3448044435"<sip:3448044435@MY_IP>' failed for '64.27.24.109' - No matching peer found
[2011-11-20 12:54:13] NOTICE[5482] chan_sip.c:    -- Registration for 'MY_USERNAME@sip.inphonex.com' timed out, trying again (Attempt #1)
[2011-11-21 17:35:46] NOTICE[5482] chan_sip.c: Registration from '"745155724"<sip:745155724@MY_IP>' failed for '94.75.205.16' - No matching peer found
[2011-11-21 17:35:47] NOTICE[5482] chan_sip.c: Registration from '"3791632045"<sip:3791632045@MY_IP>' failed for '94.75.205.16' - No matching peer found
[2011-11-21 17:37:03] NOTICE[5482] chan_sip.c:    -- Registration for 'MY_USERNAME@sip.inphonex.com' timed out, trying again (Attempt #1)
[2011-11-21 18:58:23] NOTICE[5482] chan_sip.c: Registration from '"2777104542"<sip:2777104542@MY_IP>' failed for '64.69.40.213' - No matching peer found
[2011-11-21 19:38:52] NOTICE[5482] chan_sip.c:    -- Registration for 'MY_USERNAME@sip.inphonex.com' timed out, trying again (Attempt #1)
[2011-11-23 06:00:05] NOTICE[5482] chan_sip.c: Sending fake auth rejection for device "unknown" <sip:unknown@92.241.168.34>;tag=eWBFi1i77i
[2011-11-23 06:00:05] NOTICE[5482] chan_sip.c: Sending fake auth rejection for device "unknown" <sip:unknown@92.241.168.34>;tag=l3WlSA30Ga
[2011-11-23 06:00:06] NOTICE[5482] chan_sip.c: Sending fake auth rejection for device "unknown" <sip:unknown@92.241.168.34>;tag=Vue7rGCz58
[2011-11-23 06:00:07] NOTICE[5482] chan_sip.c: Sending fake auth rejection for device "unknown" <sip:unknown@92.241.168.34>;tag=fyNFJZU4AP
[2011-11-23 06:00:08] NOTICE[5482] chan_sip.c: Sending fake auth rejection for device "unknown" <sip:unknown@92.241.168.34>;tag=Gh6NMvqfzh
[2011-11-23 06:00:09] NOTICE[5482] chan_sip.c: Sending fake auth rejection for device "unknown" <sip:unknown@92.241.168.34>;tag=rM4XS89wDJ
[2011-11-23 06:00:10] NOTICE[5482] chan_sip.c: Sending fake auth rejection for device "unknown" <sip:unknown@92.241.168.34>;tag=OKbXgQextv
[2011-11-25 14:49:43] NOTICE[5482] chan_sip.c: Registration from '"3186928129"<sip:3186928129@MY_IP>' failed for '173.203.109.169' - No matching peer found
[2011-11-25 14:49:43] NOTICE[5482] chan_sip.c: Registration from '"1667791004"<sip:1667791004@MY_IP>' failed for '173.203.109.169' - No matching peer found
[2011-11-25 15:38:07] NOTICE[5482] chan_sip.c:    -- Registration for 'MY_USERNAME@sip.inphonex.com' timed out, trying again (Attempt #1)
[2011-11-25 22:25:56] NOTICE[5482] chan_sip.c: Sending fake auth rejection for device "VOIP" <sip:VOIP@76.74.253.98>;tag=PTwtTr3793
[2011-11-25 22:25:56] NOTICE[5482] chan_sip.c: Sending fake auth rejection for device "VOIP" <sip:VOIP@76.74.253.98>;tag=Tscll9Y6yt
[2011-11-25 22:25:57] NOTICE[5482] chan_sip.c: Sending fake auth rejection for device "VOIP" <sip:VOIP@76.74.253.98>;tag=tvgl4ofuHc
[2011-11-25 22:25:59] NOTICE[5482] chan_sip.c: Sending fake auth rejection for device "VOIP" <sip:VOIP@76.74.253.98>;tag=2RSDZHtlkb
[2011-11-25 22:26:01] NOTICE[5482] chan_sip.c: Sending fake auth rejection for device "VOIP" <sip:VOIP@76.74.253.98>;tag=6yiS1ke8yp
[2011-11-25 22:26:03] NOTICE[5482] chan_sip.c: Sending fake auth rejection for device "VOIP" <sip:VOIP@76.74.253.98>;tag=oVtWHo2fEA
[2011-11-25 22:26:05] NOTICE[5482] chan_sip.c: Sending fake auth rejection for device "VOIP" <sip:VOIP@76.74.253.98>;tag=PSYs8vuYkh
[2011-11-25 22:26:08] NOTICE[5482] chan_sip.c: Sending fake auth rejection for device "VOIP" <sip:VOIP@76.74.253.98>;tag=gtz84WWE8V
[2011-11-25 22:26:10] NOTICE[5482] chan_sip.c: Sending fake auth rejection for device "VOIP" <sip:VOIP@76.74.253.98>;tag=3EFNd6cDeV
[2011-11-26 09:10:32] NOTICE[5482] chan_sip.c: Registration from '"2524299004"<sip:2524299004@MY_IP>' failed for '184.72.45.109' - No matching peer found
[2011-11-26 16:44:26] NOTICE[5482] chan_sip.c: Peer 'inphonex' is now UNREACHABLE!  Last qualify: 35
[2011-11-26 16:44:36] NOTICE[5482] chan_sip.c: Peer 'inphonex' is now Reachable. (37ms / 2000ms)

Keeping in mind that I’m a total noob when it comes to Asterisk, is there a way for me to block everyone except my VoIP provider? Or is there a way to prevent anyone from trying to register with my server (since it’s only used for incoming calls)?

EDIT:

Here is my extensions.conf as well:

[code];!
;! Automatically generated configuration file
;! Filename: extensions.conf (/etc/asterisk/extensions.conf)
;! Generator: Manager
;! Creation Date: Mon Sep 8 16:04:23 2008
;!
[general]
static = yes
writeprotect = no
clearglobalvars = yes

[globals]
TRUNKMSD = 1 ; MSD digits to strip (usually 1 or 0)
timeinterval_all day = ||undefined|undefined
;
; Included Contexts
;
; One may include another context in the current one as well, optionally with a
; date and time. Included contexts are included in the order
; they are listed.
; The reason a context would include other contexts is for their
; extensions.
; The algorithm to find an extension is recursive, and works in this
; fashion:
; first, given a stack on which to store context references,
; push the context to find the extension onto the stack…
; a) Try to find a matching extension in the context at the top of
; the stack, and, if found, begin executing the priorities
; there in sequence.
; b) If not found, Search the switches, if any declared, in
; sequence.
; c) If still not found, for each include, push that context onto
; the top of the context stack, and recurse to a).
; d) If still not found, pop the entry from the top of the stack;
; if the stack is empty, the search has failed. If it’s not,
; continue with the next context in c).
; This is a depth-first traversal, and stops with the first context
; that provides a matching extension. As usual, if more than one
; pattern in a context will match, the ‘best’ match will win.
; Please note that that extensions found in an included context are
; treated as if they were in the context from which the search began.
; The PBX’s notion of the “current context” is not changed.
; Please note that in a context, it does not matter where an include
; directive occurs. Whether at the top, or near the bottom, the effect
; will be the same. The only thing that matters is that if there is
; more than one include directive, they will be searched for extensions
; in order, first to last.
; Also please note that pattern matches (like _9XX) are not treated
; any differently than exact matches (like 987). Also note that the
; order of extensions in a context have no affect on the outcome.
;
; Timing list for includes is
;
; |||
;
; Note that ranges may be specified to wrap around the ends. Also, minutes are
; fine-grained only down to the closest even minute.
;
;include => daytime|9:00-17:00|mon-fri||
;include => weekend||sat-sun||*
;include => weeknights|17:02-8:58|mon-fri||
;
; ignorepat can be used to instruct drivers to not cancel dialtone upon
; receipt of a particular pattern. The most commonly used example is
; of course ‘9’ like this:
;
;ignorepat => 9
;
; so that dialtone remains even after dialing a 9.
;
;
; Sample entries for extensions.conf
;
;
[local]
;
ignorepat => 9
include => default
include => parkedcalls
;
;
exten => 1234,1,Playback(transfer,skip) ; “Please hold while…”
; (but skip if channel is not up)
exten => 1234,n,Macro(stdexten,1234,${GLOBAL(CONSOLE)})
exten => 1235,1,Voicemail(1234,u) ; Right to voicemail
exten => 1236,1,Dial(Console/dsp) ; Ring forever
exten => 1236,n,Voicemail(1234,b) ; Unless busy
;
; # for when they’re done with the demo
;
exten => #,1,Playback(demo-thanks) ; "Thanks for trying the demo"
exten => #,n,Hangup ; Hang them up.
;
; A timeout and “invalid extension rule”
;
exten => t,1,Goto(#,1) ; If they take too long, give up
exten => i,1,Playback(invalid) ; “That’s not valid, try again”
;
; Create an extension, 500, for dialing the
; Asterisk demo.
;
exten => 500,1,Playback(demo-abouttotry) ; Let them know what’s going on
exten => 500,n,Dial(IAX2/guest@pbx.digium.com/s@default) ; Call the Asterisk demo
exten => 500,n,Playback(demo-nogo) ; Couldn’t connect to the demo site
exten => 500,n,Goto(s,6) ; Return to the start over message.
;
; Create an extension, 600, for evaluating echo latency.
;
exten => 600,1,Playback(demo-echotest) ; Let them know what’s going on
exten => 600,n,Echo ; Do the echo test
exten => 600,n,Playback(demo-echodone) ; Let them know it’s over
exten => 600,n,Goto(s,6) ; Start over
;
;
; Give voicemail at extension 8500
;
exten => 8500,1,VoicemailMain
exten => 8500,n,Goto(s,6)
;
;

[default]
(${CALLERID(num)}@default)

[incoming_calls]

[internal]
exten => 500,1,Verbose(1|Echo test application)
exten => 500,n,Echo()
exten => 500,n,Hangup()
exten => 7000,1,Goto(voicemenu-custom-1|s|1)
exten => 7001,1,Goto(voicemenu-custom-2|s|1)
exten => 1000,1,Verbose(1|Extension 1000)
exten => 1000,n,Dial(SIP/1000,30)
exten => 1000,n,Hangup()
exten => 1002,1,Verbose(1|Extension 1002)
exten => 1002,n,Dial(SIP/1002,30)
exten => 1002,n,Hangup()
exten => 700,1,Wait(1) ;Wait a second, and to get the CallerID information.
exten => 700,1,Goto(voicemenu-custom-1|s|1)

[phones]
include => internal

[conferences]

[ringgroups]

[queues]

[voicemenus]
exten => 7000,1,Goto(voicemenu-custom-1|s|1)
exten = 7000,1,Goto(voicemenu-custom-1|s|1)
exten = 7001,1,Goto(voicemenu-custom-2|s|1)

[inbound-inphonex]
exten => 700,1,Answer
exten => 700,2,AGI(basic.pl)
exten => 700,3,Hangup

[voicemailgroups]

[directory]

[asterisk_guitools]
exten = executecommand,1,System(${command})
exten = executecommand,n,Hangup()
exten = record_vmenu,1,Answer
exten = record_vmenu,n,Playback(vm-intro)
exten = record_vmenu,n,Record(${var1})
exten = record_vmenu,n,Playback(vm-saved)
exten = record_vmenu,n,Playback(vm-goodbye)
exten = record_vmenu,n,Hangup
exten = play_file,1,Answer
exten = play_file,n,Playback(${var1})
exten = play_file,n,Hangup

[CallingRule_default]
exten = _NXXXXXX,1,Goto(voicemenu-custom-1|s|1)

[voicemenu-custom-1]
exten = s,1,NoOp(IVRTest)
exten = s,2,Answer()
exten = s,3,Wait(1)
exten = s,4,Authenticate(12345)
exten = s,5,Playback(demo-congrats)

[DID_]
include = DID__default

[DID__default]

[DLPN_DialPlan1]
include = CallingRule_default
include = default
include = parkedcalls
include = conferences
include = ringgroups
include = voicemenus
include = queues
include = voicemailgroups
include = directory

[macro-trunkdial-failover-0.3]
; Macro by = Brandon Kruse bkruse@digium.com & Matthew O’Gorman mogorman@digium.com
exten = s,1,Set(CALLERID(num)=${IF($[${LEN(${CID_${CALLERID(num)}})} > 2]?${CID_${CALLERID(num)}}:)})
exten = s,n,GotoIf($[${LEN(${CALLERID(num)})} > 6]?1-dial,1)
exten = s,n,Set(CALLERID(all)=${IF($[${LEN(${CID_${ARG3}})} > 6]?${CID_${ARG3}}:${GLOBAL_OUTBOUNDCID})})
exten = s,n,Goto(1-dial,1)
exten = 1-dial,1,Dial(${ARG1})
exten = 1-dial,n,Gotoif(${LEN(${ARG2})} > 0 ?1-${DIALSTATUS},1:1-out,1)
exten = 1-CHANUNAVAIL,1,Dial(${ARG2})
exten = 1-CHANUNAVAIL,n,Hangup()
exten = 1-CONGESTION,1,Dial(${ARG2})
exten = 1-CONGESTION,n,Hangup()
exten = 1-out,1,Hangup()

[macro-stdexten]
exten = s,1,GotoIf($[${FOLLOWME_${ARG1}} = 1]?4:2)
exten = s,2,Dial(${ARG2},20)
exten = s,3,Goto(s-${DIALSTATUS},1)
exten = s,4,Macro(stdexten-followme,${ARG1},${ARG2})
exten = s-NOANSWER,1,Voicemail(${ARG1},u)
exten = s-NOANSWER,2,Goto(default,s,1)
exten = s-BUSY,1,Voicemail(${ARG1},b)
exten = s-BUSY,2,Goto(default,s,1)
exten = _s-.,1,Goto(s-NOANSWER,1)
exten = a,1,VoicemailMain(${ARG1})

[macro-stdexten-followme]
exten = s,1,Dial(${ARG2},20)
exten = s,2,Followme(${ARG1},a)
exten = s,3,Voicemail(${ARG1},b)
exten = s-NOANSWER,1,Voicemail(${ARG1},u)
exten = s-BUSY,1,Voicemail(${ARG1},b)
exten = s-BUSY,2,Goto(default,s,1)
exten = _s-.,1,Goto(s-NOANSWER,1)
exten = a,1,VoicemailMain(${ARG1})

[voicemenu-custom-2]
exten = s,1,NoOp(Keys)
exten = s,2,Answer()
exten => s,3,AGI(basic.pl)
exten => s,4, Hangup
[/code]


#2

Hi Travesty3!

Make sure that you know what you have in your [default] context in your dialplan <extensions.conf>.
It is not so good if anybody can make phone call out of your system in there!

You can have that context empty!

like this:

[code][default]
; Blank context.

[outgoing_context]
exten => s,1,DIAL( …

[next_context]


[/code]
If you are not connecting any phones from the outside, I don’t think
you need to have port 5060-5061 open on incoming.
So you can block that in you firewall.


#3

Thanks for the reply. I added my extensions.conf file to the original post. The only thing in the [default] context is: code[/code] Should I take that out, or is that ok?

I will try blocking 5060-5061 on my router and make sure I can still get incoming calls. I’ll post the result here.

EDIT:

The phone system does indeed still work with ports 5060-5061 blocked, so I will keep it that way. Hopefully this problem wil be solved. Thanks for the help!


#4
Doesn't handle that case.

[code]canreinvite=yes[/code]
Almost certainly won't work across a NAT and with a SIP provider.  They may be rejecting the re-invites, or you may be doing something incompatible.

[code]insecure=port,invite[/code]
Almost certainly should be insecure=invite

[code](${CALLERID(num)}@default)[/code]
is gibberish, probably from a bad edit.

I would worry about the AGI script.

Doesn’t handle that case.

Almost certainly won’t work across a NAT and with a SIP provider. They may be rejecting the re-invites, or you may be doing something incompatible.

Almost certainly should be insecure=invite

is gibberish, probably from a bad edit.

I would worry about the AGI script.


#5

Also, if you are concerned about security, you should not be using anything as old as 1.6.2.5. If you are locked into 1.6.2, you should be using 1.6.2.20, but noting that security fix support will end for 1.6.2.x some time next year.

Also note that canreinvite is being renamed as directmedia - I think that was in 1.6.2.


#6

[quote=“david55”]nat=yes ; my asterisk is behind nat
Doesn’t handle that case.

Almost certainly won’t work across a NAT and with a SIP provider. They may be rejecting the re-invites, or you may be doing something incompatible.

Almost certainly should be insecure=invite

is gibberish, probably from a bad edit.
[/quote]
Actually, my server really is not behind a NAT. IIRC, I changed that option when trying to set it up, and for some reason, it worked. It was most likely a different setting that was causing the problem, but since it worked, I didn’t touch it. I just changed it back, commented out the canreinvite=yes line, changed it to insecure=invite, and removed the stuff under the [default] context, and it all still works. Thanks for these suggestions.

[quote=“david55”]Also, if you are concerned about security, you should not be using anything as old as 1.6.2.5. If you are locked into 1.6.2, you should be using 1.6.2.20, but noting that security fix support will end for 1.6.2.x some time next year.

Also note that canreinvite is being renamed as directmedia - I think that was in 1.6.2.[/quote]
As a noob, I’m afraid to update for fear that it could cause it to stop working, forcing me to invest more time than I can afford on this. With the firewall rules blocking ports 5060 and 5061, and Fail2Ban as a backup, I’m hoping that this will be secure enough for us without updating for now.

What do you mean by this?


#7

This line is being run for your untrusted, incoming callers:

for all I know it could be allowing them to make outgoing calls.


#8

Here is basic.pl:

[code]#!/usr/bin/perl
use Asterisk::AGI;
use LWP::Simple;
use LWP::UserAgent;
use HTTP::Request;
use HTTP::Response;
use DBI;

$| = 1;

my $AGI = new Asterisk::AGI;
my %input = $AGI->ReadParse();
my $loop, $env, $version, $demoFlag, $user_id, $password, $type, $mac, $url, $mysql;
@types = ("", “u”, “s”);
@environments = (“prod”, “test”);

($seconds, $minutes, $hours, $day, $month, $year) = localtime();
$year += 1900;
$month += 1;
$date = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $year, $month, $day, $hours, $minutes, $seconds);
$AGI->verbose(“Call from “. $input{‘callerid’} .” Received ${date}”);

$lrepeat = 1;
$MAX_RETRIES = 3;
$currentRetries = 0;

temporary outage message while switching to cloud servers. remove the next two lines when upgrade is done.

#$AGI->stream_file(“UpgradingOutage”);
#$lrepeat = 0;

while ($lrepeat == 1)
{
$AGI->stream_file(“ThankYouForCalling”);

while($currentRetries < $MAX_RETRIES)
{
	$version = $AGI->get_data("Version", 10000, 1);
	
	if ($version == 1 || $version == 2)
	{
		if ($version == 2)
		{
			$version = 0;
		}
		last;
	}
	
	$AGI->stream_file("InvalidEntry");
	$currentRetries++;
}

if ($currentRetries == $MAX_RETRIES)
{
	$AGI->stream_file('HaveAGreatDay');
	$AGI->hangup();
	exit(0);
}
else
{
	$currentRetries = 0;
}

if ($version == 1)
{
	while($currentRetries < $MAX_RETRIES)
	{
		$demoFlag = $AGI->get_data("30DayUnlimitedLicense", 10000, 1);	# 1 = yes, 2 = no
		
		if ($demoFlag == 1 || $demoFlag == 2)
		{
			if ($demoFlag == 2)
			{
				$demoFlag = 0;
			}
			last;
		}
		
		$AGI->stream_file("InvalidEntry");
		$currentRetries++;
	}
}

if ($currentRetries == $MAX_RETRIES)
{
	$AGI->stream_file('HaveAGreatDay');
	$AGI->hangup();
	exit(0);
}
else
{
	$currentRetries = 0;
}

if ($demoFlag == 0 || $version == 0)
{
	while($currentRetries < $MAX_RETRIES)
	{
		$user_id = $AGI->get_data("UserID", 10000, 6);
		
		if (length($user_id) == 6)
		{
			last;
		}
		
		$AGI->stream_file("InvalidEntry");
		$currentRetries++;
	}

	if ($currentRetries == $MAX_RETRIES)
	{
		$AGI->stream_file('HaveAGreatDay');
		$AGI->hangup();
		exit(0);
	}
	else
	{
		$currentRetries = 0;
	}
	
	while($currentRetries < $MAX_RETRIES)
	{
		$password = $AGI->get_data("Password", 10000, 6);
		
		if (length($password) == 6)
		{
			last;
		}
		
		$AGI->stream_file("InvalidEntry");
		$currentRetries++;
	}

	if ($currentRetries == $MAX_RETRIES)
	{
		$AGI->stream_file('HaveAGreatDay');
		$AGI->hangup();
		exit(0);
	}
	else
	{
		$currentRetries = 0;
	}
}

if ($version == 1)
{
	while($currentRetries < $MAX_RETRIES)
	{
		$type = $AGI->get_data("IDType", 10000, 1);	# 1 = UNIQUE, 2 = SERIAL
		
		if ($type == 1 || $type == 2)
		{
			last;
		}
		
		$AGI->stream_file("InvalidEntry");
		$currentRetries++;
	}

	if ($currentRetries == $MAX_RETRIES)
	{
		$AGI->stream_file('HaveAGreatDay');
		$AGI->hangup();
		exit(0);
	}
	else
	{
		$currentRetries = 0;
	}
}
else
{
	$type = 1;
}

while($currentRetries < $MAX_RETRIES)
{
	my $file;
	
	if ($type == 1)
	{
		$mac = $AGI->get_data("UniqueID", 10000, 6);
	}
	else
	{
		$mac = $AGI->get_data("SerialNum", 10000, 8);
	}
		
	if ((length($mac) == 6 && $type == 1) || (length($mac) == 8 && $type == 2))
	{
		last;
	}
	
	$AGI->stream_file("InvalidEntry");
	$currentRetries++;
}

if ($currentRetries == $MAX_RETRIES)
{
	$AGI->stream_file('HaveAGreatDay');
	$AGI->hangup();
	exit(0);
}
else
{
	$currentRetries = 0;
}

$mysql = DBI->connect("CONNECTION_INFO_REMOVED") or die "Can't open database: $DBI::errstr";
my $query = $mysql->prepare("INSERT_QUERY_REMOVED") or die "Couldn't prepare statement: ". $dbh->errstr;
$query->execute($input{'callerid'}, $user_id, $mac);

$url = "URL_REMOVED";
$AGI->verbose("url = ${url}");
@result = `${url}`;
@code = split(/ /, $result[2]);
$AGI->verbose("result = ${result[2]}");

if (@code[0] eq "No")
{
	$ll = 0;
	foreach $inty(@code)
	{
		if ($inty eq "No")
		{
			$ll++;
			next;
		}
		
		if ($version == 1)
		{
			$base = 34;
		}
		else
		{
			$base = 36;
		}
		
		$base36 = "";
		
		for ($i=0; $i<7; $i++)
		{
			$digit = $inty % $base;
			
			if ($base == 34)
			{
				if ($digit == 0)
				{
					$digit += 35;
				}
				elsif ($digit == 24)
				{
					$digit += 10;
				}
			}
			
			if ($digit >= 10)
			{
				$digit += 87;
				$digit = pack("c", $digit); 
			}

			$base36 = $digit . $base36;
			$inty /= $base;
		}
		
		@code[$ll] = $base36;
		$ll++;
	}
	
	open(StatsFile, '>>/tmp/stats.txt');
	print StatsFile " $user_id \n";
	close (StatsFile);
	
	my $message = @code[1] ."-". @code[2];
	if (@code[3] > 0)
	{
		$message .= "-". @code[3] ."-". @code[4];
	}
	$AGI->verbose($message);
	
	do
	{
		$AGI->stream_file('UnlockCodeIs');
		$AGI->exec('SayPhonetic', @code[1]);
		$AGI->stream_file('Dash');
		$AGI->exec('SayPhonetic', @code[2]);
		
		if (@code[3] > 0)
		{
			$AGI->stream_file('Dash');
			$AGI->exec('SayPhonetic', @code[3]);
			$AGI->stream_file('Dash');
			$AGI->exec('SayPhonetic', @code[4]);
		}
		
		$again = $AGI->get_data("Again", 10000, 1);
	} while ($again);
	$lrepeat = 0;
}
elsif (@code[0] eq "Error:")
{
	if (@code[1] == 1 && @code[2] == 0)
	{
		$AGI->stream_file('UserIDPasswordDontMatch');
	}
	elsif (@code[1] == 2 && @code[2] == 0)
	{
		$AGI->stream_file('LicenseAlreadyActivated');
		$lrepeat = 0;
	}
	elsif (@code[1] == 3 && @code[2] == 0)
	{
		$AGI->stream_file('GenerationsDontMatch');
		$lrepeat = 0;
	}
	elsif (@code[1] == 4 && @code[2] == 0)
	{
		if ($type == 1)
		{
			$AGI->stream_file('30DayAlreadyActivatedUniqueID');
		}
		else
		{
			$AGI->stream_file('30DayAlreadyActivatedSerial');
		}
		$lrepeat = 0;
	}
	elsif (@code[1] == 5 && @code[2] == 0)
	{
		$AGI->stream_file('InvalidSerial');
		$lrepeat = 0;
	}
	else
	{
		$AGI->stream_file('ProblemCreatingKey');
		$lrepeat = 0;
	}
	
	$AGI->stream_file('ContactSupport');
}

}

$AGI->stream_file(‘HaveAGreatDay’);
$AGI->hangup();
exit(0);
[/code]

Your ongoing help is greatly appreciated. Thanks!