Example #1
0
        /// <summary>
        ///  From RFC3261: Stateless Proxy Response Processing:
        ///
        /// When a response arrives at a stateless proxy, the proxy MUST inspect the sent-by value in the first
        /// (topmost) Via header field value.  If that address matches the proxy, (it equals a value this proxy has
        /// inserted into previous requests) the proxy MUST remove that header field value from the response and
        /// forward the result to the location indicated in the next Via header field value.  The proxy MUST NOT add
        /// to, modify, or remove the message body.  Unless specified otherwise, the proxy MUST NOT remove
        /// any other header field values.  If the address does not match the  proxy, the message MUST be silently discarded.
        /// </summary>
        private void GotResponse(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPResponse sipResponse)
        {
            try
            {
                // Used in the proxy monitor messages only, plays no part in response processing.
                string fromUser   = (sipResponse.Header.From != null) ? sipResponse.Header.From.FromURI.User : null;
                string toUser     = (sipResponse.Header.To != null) ? sipResponse.Header.To.ToURI.User : null;
                string summaryStr = "resp " + sipResponse.Header.CSeqMethod + " from=" + fromUser + ", to=" + toUser + ", " + remoteEndPoint.ToString();

                SIPViaHeader topVia    = sipResponse.Header.Vias.PopTopViaHeader();
                SIPEndPoint  outSocket = localSIPEndPoint;

                // If the second Via header on the response was also set by this proxy it means the request was originally received and forwarded
                // on different sockets. To get the response to travel the same path in reverse it must be forwarded from the proxy socket indicated
                // by the second top Via.
                if (sipResponse.Header.Vias.Length > 1)
                {
                    SIPViaHeader nextTopVia            = sipResponse.Header.Vias.TopViaHeader;
                    SIPEndPoint  nextTopViaSIPEndPoint = SIPEndPoint.ParseSIPEndPoint(nextTopVia.Transport + ":" + nextTopVia.ReceivedFromAddress);
                    //if (!(PublicIPAddress != null && nextTopVia.ReceivedFromIPAddress != null && nextTopVia.ReceivedFromIPAddress != PublicIPAddress.ToString())
                    //    &&
                    //    (m_sipTransport.IsLocalSIPEndPoint(nextTopViaSIPEndPoint) || (PublicIPAddress != null && nextTopVia.ReceivedFromIPAddress == PublicIPAddress.ToString())))
                    if (m_sipTransport.IsLocalSIPEndPoint(nextTopViaSIPEndPoint))
                    {
                        sipResponse.Header.Vias.PopTopViaHeader();
                        outSocket = nextTopViaSIPEndPoint;
                    }
                }

                bool isFromAppServer = (m_sipCallDispatcherFile != null) ?  m_sipCallDispatcherFile.IsAppServerEndPoint(remoteEndPoint) : false;

                lock (this)
                {
                    m_compiledScript.DefaultScope.RemoveVariable("sys");
                    m_compiledScript.DefaultScope.RemoveVariable("isreq");
                    m_compiledScript.DefaultScope.RemoveVariable("localEndPoint");
                    m_compiledScript.DefaultScope.RemoveVariable("outSocket");
                    m_compiledScript.DefaultScope.RemoveVariable("resp");
                    m_compiledScript.DefaultScope.RemoveVariable("remoteEndPoint");
                    m_compiledScript.DefaultScope.RemoveVariable("summary");
                    m_compiledScript.DefaultScope.RemoveVariable("sipMethod");
                    m_compiledScript.DefaultScope.RemoveVariable("topVia");
                    m_compiledScript.DefaultScope.RemoveVariable("IsFromAppServer");

                    m_compiledScript.DefaultScope.SetVariable("sys", m_proxyScriptFacade);
                    m_compiledScript.DefaultScope.SetVariable("isreq", false);
                    m_compiledScript.DefaultScope.SetVariable("localEndPoint", localSIPEndPoint);
                    m_compiledScript.DefaultScope.SetVariable("outSocket", outSocket);
                    m_compiledScript.DefaultScope.SetVariable("resp", sipResponse);
                    m_compiledScript.DefaultScope.SetVariable("remoteEndPoint", remoteEndPoint);
                    m_compiledScript.DefaultScope.SetVariable("summary", summaryStr);
                    m_compiledScript.DefaultScope.SetVariable("sipMethod", sipResponse.Header.CSeqMethod.ToString());
                    m_compiledScript.DefaultScope.SetVariable("topVia", topVia);
                    m_compiledScript.DefaultScope.SetVariable("IsFromAppServer", isFromAppServer);

                    m_compiledScript.Execute();
                }

                //if (responseStopwatch.ElapsedMilliseconds > 20)
                //{
                //    logger.Debug("GotResponse processing time=" + responseStopwatch.ElapsedMilliseconds + "ms, script time=" + scriptStopwatch.ElapsedMilliseconds + "ms.");
                //}
            }
            catch (Exception excp)
            {
                string respExcpError = "Exception SIPProxyCore GotResponse. " + excp.Message;
                logger.Error(respExcpError + "\n" + sipResponse.ToString());
                SIPMonitorEvent respExcpEvent = new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.SIPProxy, SIPMonitorEventTypesEnum.Error, respExcpError, localSIPEndPoint, remoteEndPoint, null);
                SendMonitorEvent(respExcpEvent);

                throw excp;
            }
        }
        public bool AuthenticateCall()
        {
            m_isAuthenticated = false;

            try
            {
                if (SIPAuthenticateRequest_External == null)
                {
                    // No point trying to authenticate if we haven't been given an authentication delegate.
                    Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null);
                }
                else if (GetSIPAccount_External == null)
                {
                    // No point trying to authenticate if we haven't been given a  delegate to load the SIP account.
                    Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null);
                }
                else
                {
                    m_sipAccount =
                        GetSIPAccount_External(s => s.SIPUsername == m_sipUsername && s.SIPDomain == m_sipDomain);

                    if (m_sipAccount == null)
                    {
                        Reject(SIPResponseStatusCodesEnum.Forbidden, null, null);
                    }
                    else
                    {
                        SIPRequest  sipRequest       = m_uasTransaction.TransactionRequest;
                        SIPEndPoint localSIPEndPoint = (!sipRequest.Header.ProxyReceivedOn.IsNullOrBlank())
                            ? SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxyReceivedOn)
                            : sipRequest.LocalSIPEndPoint;
                        SIPEndPoint remoteEndPoint = (!sipRequest.Header.ProxyReceivedFrom.IsNullOrBlank())
                            ? SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxyReceivedFrom)
                            : sipRequest.RemoteSIPEndPoint;

                        SIPRequestAuthenticationResult authenticationResult =
                            SIPAuthenticateRequest_External(localSIPEndPoint, remoteEndPoint, sipRequest, m_sipAccount);
                        if (authenticationResult.Authenticated)
                        {
                            if (authenticationResult.WasAuthenticatedByIP)
                            {
                            }
                            else
                            {
                            }

                            SetOwner(m_sipAccount.Owner, m_sipAccount.AdminMemberId);
                            m_isAuthenticated = true;
                        }
                        else
                        {
                            // Send authorisation failure or required response
                            SIPResponse authReqdResponse =
                                SIPTransport.GetResponse(sipRequest, authenticationResult.ErrorResponse, null);
                            authReqdResponse.Header.AuthenticationHeader =
                                authenticationResult.AuthenticationRequiredHeader;
                            m_uasTransaction.SendFinalResponse(authReqdResponse);
                        }
                    }
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPServerUserAgent AuthenticateCall. " + excp.Message);
                Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null);
            }

            return(m_isAuthenticated);
        }
        /// <summary>
        /// Authenticates a SIP request.
        /// </summary>
        public static SIPRequestAuthenticationResult AuthenticateSIPRequest(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPRequest sipRequest, SIPAccount sipAccount, SIPMonitorLogDelegate logSIPMonitorEvent)
        {
            try
            {
                if (sipAccount == null)
                {
                    return(new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.Forbidden, null));
                }
                else if (sipAccount.IsDisabled)
                {
                    logSIPMonitorEvent?.Invoke(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Authoriser, SIPMonitorEventTypesEnum.DialPlan, "SIP account " + sipAccount.SIPUsername + "@" + sipAccount.SIPDomain + " is disabled for " + sipRequest.Method + ".", sipAccount.Owner));
                    return(new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.Forbidden, null));
                }
                else
                {
                    SIPAuthenticationHeader reqAuthHeader = sipRequest.Header.AuthenticationHeader;
                    if (reqAuthHeader == null)
                    {
                        // Check for IP address authentication.
                        if (!sipAccount.IPAddressACL.IsNullOrBlank())
                        {
                            SIPEndPoint uaEndPoint = (!sipRequest.Header.ProxyReceivedFrom.IsNullOrBlank()) ? SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxyReceivedFrom) : remoteEndPoint;
                            if (Regex.Match(uaEndPoint.GetIPEndPoint().ToString(), sipAccount.IPAddressACL).Success)
                            {
                                // Successfully authenticated
                                return(new SIPRequestAuthenticationResult(true, true));
                            }
                        }

                        SIPAuthenticationHeader authHeader = new SIPAuthenticationHeader(SIPAuthorisationHeadersEnum.WWWAuthenticate, sipAccount.SIPDomain, GetNonce());
                        return(new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.Unauthorised, authHeader));
                    }
                    else
                    {
                        return(new SIPRequestAuthenticationResult(true, false));
                        //// Check for IP address authentication.
                        //if (!sipAccount.IPAddressACL.IsNullOrBlank())
                        //{
                        //    SIPEndPoint uaEndPoint = (!sipRequest.Header.ProxyReceivedFrom.IsNullOrBlank()) ? SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxyReceivedFrom) : remoteEndPoint;
                        //    if (Regex.Match(uaEndPoint.GetIPEndPoint().ToString(), sipAccount.IPAddressACL).Success)
                        //    {
                        //        // Successfully authenticated
                        //        return new SIPRequestAuthenticationResult(true, true);
                        //    }
                        //}

                        //string requestNonce = reqAuthHeader.SIPDigest.Nonce;
                        //string uri = reqAuthHeader.SIPDigest.URI;
                        //string response = reqAuthHeader.SIPDigest.Response;

                        //// Check for stale nonces.
                        //if (IsNonceStale(requestNonce))
                        //{
                        //    if (logSIPMonitorEvent != null)
                        //    {
                        //        logSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Authoriser, SIPMonitorEventTypesEnum.Warn, "Authentication failed stale nonce for realm=" + sipAccount.SIPDomain + ", username="******", uri=" + uri + ", nonce=" + requestNonce + ", method=" + sipRequest.Method + ".", null));
                        //    }
                        //    SIPAuthenticationHeader authHeader = new SIPAuthenticationHeader(SIPAuthorisationHeadersEnum.WWWAuthenticate, sipAccount.SIPDomain, GetNonce());
                        //    return new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.Unauthorised, authHeader);
                        //}
                        //else
                        //{
                        //    SIPAuthorisationDigest checkAuthReq = reqAuthHeader.SIPDigest;
                        //    checkAuthReq.SetCredentials(sipAccount.SIPUsername, sipAccount.SIPPassword, uri, sipRequest.Method.ToString());
                        //    string digest = checkAuthReq.Digest;

                        //    if (digest == response)
                        //    {
                        //        // Successfully authenticated
                        //        return new SIPRequestAuthenticationResult(true, false);
                        //    }
                        //    else
                        //    {
                        //        if (logSIPMonitorEvent != null)
                        //        {
                        //            logSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Authoriser, SIPMonitorEventTypesEnum.Warn, "Authentication token check failed for realm=" + sipAccount.SIPDomain + ", username="******", uri=" + uri + ", nonce=" + requestNonce + ", method=" + sipRequest.Method + ".", sipAccount.Owner));
                        //        }
                        //        SIPAuthenticationHeader authHeader = new SIPAuthenticationHeader(SIPAuthorisationHeadersEnum.WWWAuthenticate, sipAccount.SIPDomain, GetNonce());
                        //        return new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.Unauthorised, authHeader);
                        //    }
                        //}
                    }
                }
            }
            catch (Exception excp)
            {
                logSIPMonitorEvent?.Invoke(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Authoriser, SIPMonitorEventTypesEnum.Error, "Exception AuthoriseSIPRequest. " + excp.Message, null));
                return(new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.InternalServerError, null));
            }
        }
Example #4
0
            public void BlockIPAddressUnitTest()
            {
                Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);

                SIPMonitorFilter filter = new SIPMonitorFilter("ipaddress 127.0.0.1 and event full");

                Console.WriteLine(filter.GetFilterDescription());

                Assert.IsTrue(filter != null, "The filter was not correctly instantiated.");
                Assert.AreEqual(filter.IPAddress, "127.0.0.1", "The filter ip address was not correctly set.");

                SIPMonitorEvent monitorEvent    = new SIPMonitorControlClientEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.FullSIPTrace, "blah blah", String.Empty, SIPEndPoint.ParseSIPEndPoint("127.0.0.2"), null);
                bool            showEventResult = filter.ShowSIPMonitorEvent(monitorEvent);

                Assert.IsFalse(showEventResult, "The filter should not have shown this event.");
            }
        public bool AuthenticateCall()
        {
            m_isAuthenticated = false;

            try
            {
                if (SIPAuthenticateRequest_External == null)
                {
                    // No point trying to authenticate if we haven't been given an authentication delegate.
                    Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null);
                }
                else if (GetSIPAccount_External == null)
                {
                    // No point trying to authenticate if we haven't been given a  delegate to load the SIP account.
                    Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null);
                }
                else
                {
                    m_sipAccount = GetSIPAccount_External(m_sipUsername, m_sipDomain);

                    if (m_sipAccount == null)
                    {
                        Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer,
                                                                SIPMonitorEventTypesEnum.DialPlan,
                                                                "Rejecting authentication required call for " + m_sipUsername + "@" + m_sipDomain +
                                                                ", SIP account not found.", null));
                        Reject(SIPResponseStatusCodesEnum.Forbidden, null, null);
                    }
                    else
                    {
                        SIPRequest  sipRequest       = m_uasTransaction.TransactionRequest;
                        SIPEndPoint localSIPEndPoint = (!sipRequest.Header.ProxyReceivedOn.IsNullOrBlank())
                            ? SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxyReceivedOn)
                            : sipRequest.LocalSIPEndPoint;
                        SIPEndPoint remoteEndPoint = (!sipRequest.Header.ProxyReceivedFrom.IsNullOrBlank())
                            ? SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxyReceivedFrom)
                            : sipRequest.RemoteSIPEndPoint;

                        SIPRequestAuthenticationResult authenticationResult =
                            SIPAuthenticateRequest_External(localSIPEndPoint, remoteEndPoint, sipRequest, m_sipAccount,
                                                            Log_External);
                        if (authenticationResult.Authenticated)
                        {
                            if (authenticationResult.WasAuthenticatedByIP)
                            {
                                Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer,
                                                                        SIPMonitorEventTypesEnum.DialPlan,
                                                                        "New call from " + remoteEndPoint.ToString() +
                                                                        " successfully authenticated by IP address.", m_sipAccount.Owner));
                            }
                            else
                            {
                                Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer,
                                                                        SIPMonitorEventTypesEnum.DialPlan,
                                                                        "New call from " + remoteEndPoint.ToString() +
                                                                        " successfully authenticated by digest.", m_sipAccount.Owner));
                            }

                            SetOwner(m_sipAccount.Owner, m_sipAccount.AdminMemberId);
                            m_isAuthenticated = true;
                        }
                        else
                        {
                            // Send authorisation failure or required response
                            SIPResponse authReqdResponse =
                                SIPResponse.GetResponse(sipRequest, authenticationResult.ErrorResponse, null);
                            authReqdResponse.Header.AuthenticationHeader =
                                authenticationResult.AuthenticationRequiredHeader;
                            Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer,
                                                                    SIPMonitorEventTypesEnum.DialPlan,
                                                                    "Call not authenticated for " + m_sipUsername + "@" + m_sipDomain +
                                                                    ", responding with " + authenticationResult.ErrorResponse + ".", null));
                            m_uasTransaction.SendFinalResponse(authReqdResponse);
                        }
                    }
                }
            }
            catch (Exception excp)
            {
                Logger.Logger.Error("Exception SIPServerUserAgent AuthenticateCall. ->" + excp.Message);
                Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null);
            }

            return(m_isAuthenticated);
        }
Example #6
0
        public void Load(DataRow cdrRow)
        {
            m_sipCDR               = new SIPCDR();
            m_sipCDR.CDRId         = new Guid(cdrRow["id"] as string);
            m_sipCDR.Owner         = cdrRow["owner"] as string;
            m_sipCDR.AdminMemberId = cdrRow["adminmemberid"] as string;
            Inserted               = DateTimeOffset.Parse(cdrRow["inserted"] as string);
            m_sipCDR.CallDirection = (cdrRow["direction"] as string == SIPCallDirection.In.ToString())
                ? SIPCallDirection.In
                : SIPCallDirection.Out;
            Created = DateTimeOffset.Parse(cdrRow["created"] as string);
            m_sipCDR.Destination      = SIPURI.ParseSIPURI(cdrRow["dsturi"] as string);
            m_sipCDR.From             = SIPFromHeader.ParseFromHeader(cdrRow["fromheader"] as string);
            m_sipCDR.CallId           = cdrRow["callid"] as string;
            m_sipCDR.LocalSIPEndPoint = (!(cdrRow["localsocket"] as string).IsNullOrBlank())
                ? SIPEndPoint.ParseSIPEndPoint(cdrRow["localsocket"] as string)
                : null;
            m_sipCDR.RemoteEndPoint = (!(cdrRow["remotesocket"] as string).IsNullOrBlank())
                ? SIPEndPoint.ParseSIPEndPoint(cdrRow["remotesocket"] as string)
                : null;
            m_sipCDR.BridgeId = (!(cdrRow["bridgeid"] as string).IsNullOrBlank())
                ? new Guid(cdrRow["bridgeid"] as string)
                : Guid.Empty;
            if (cdrRow["inprogresstime"] != DBNull.Value && cdrRow["inprogresstime"] != null &&
                !(cdrRow["inprogresstime"] as string).IsNullOrBlank())
            {
                InProgressTime = DateTimeOffset.Parse(cdrRow["inprogresstime"] as string);
            }
            else
            {
                InProgressTime = null;
            }

            m_sipCDR.ProgressStatus = (cdrRow["inprogressstatus"] != null && cdrRow["inprogressstatus"] != DBNull.Value)
                ? Convert.ToInt32(cdrRow["inprogressstatus"])
                : 0;
            m_sipCDR.ProgressReasonPhrase = cdrRow["inprogressreason"] as string;
            if (cdrRow["answeredtime"] != DBNull.Value && cdrRow["answeredtime"] != null &&
                !(cdrRow["answeredtime"] as string).IsNullOrBlank())
            {
                AnsweredTime = DateTimeOffset.Parse(cdrRow["answeredtime"] as string);
            }
            else
            {
                AnsweredTime = null;
            }

            m_sipCDR.AnswerStatus = (cdrRow["answeredstatus"] != DBNull.Value && cdrRow["answeredstatus"] != null)
                ? Convert.ToInt32(cdrRow["answeredstatus"])
                : 0;
            m_sipCDR.AnswerReasonPhrase = cdrRow["answeredreason"] as string;
            if (cdrRow["hunguptime"] != DBNull.Value && cdrRow["hunguptime"] != null &&
                !(cdrRow["hunguptime"] as string).IsNullOrBlank())
            {
                HungupTime = DateTimeOffset.Parse(cdrRow["hunguptime"] as string);
            }
            else
            {
                HungupTime = null;
            }

            m_sipCDR.HangupReason = cdrRow["hungupreason"] as string;
            m_sipCDR.InProgress   = (m_sipCDR.ProgressTime != null);
            m_sipCDR.IsAnswered   = (m_sipCDR.AnswerTime != null);
            m_sipCDR.IsHungup     = (m_sipCDR.HangupTime != null);
            if (cdrRow["answeredat"] != DBNull.Value && cdrRow["answeredat"] != null)
            {
                AnsweredAt = (DateTime)cdrRow["answeredat"];
            }

            m_sipCDR.DialPlanContextID = (!(cdrRow["dialplancontextid"] as string).IsNullOrBlank())
                ? new Guid(cdrRow["dialplancontextid"] as string)
                : Guid.Empty;
        }
Example #7
0
        public async Task IncomingCallNoSdpWithACKUnitTest()
        {
            logger.LogDebug("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
            logger.BeginScope(System.Reflection.MethodBase.GetCurrentMethod().Name);

            SIPTransport transport = new SIPTransport();

            transport.AddSIPChannel(new MockSIPChannel(new System.Net.IPEndPoint(IPAddress.Any, 0)));
            var dummySep = SIPEndPoint.ParseSIPEndPoint("udp:127.0.0.1:5060");

            SIPUserAgent userAgent = new SIPUserAgent(transport, null);

            string inviteReqStr = @"INVITE sip:[email protected] SIP/2.0
Via: SIP/2.0/UDP 127.0.0.1:51200;branch=z9hG4bKbeed9b0cde8d43cc8a2aae91526b6a1d;rport
To: <sip:[email protected]>
From: <sip:[email protected]>;tag=GCLNRILCDU
Call-ID: 7265e19f53a146a1bacdf4f4f8ea70b2
CSeq: 1 INVITE
Contact: <sip:127.0.0.1:51200>
Max-Forwards: 70
User-Agent: www.sipsorcery.com
Content-Length: 0
Content-Type: application/sdp" + m_CRLF + m_CRLF;

            SIPEndPoint      dummySipEndPoint = new SIPEndPoint(new IPEndPoint(IPAddress.Loopback, 0));
            SIPMessageBuffer sipMessageBuffer = SIPMessageBuffer.ParseSIPMessage(inviteReqStr, dummySipEndPoint, dummySipEndPoint);
            SIPRequest       inviteReq        = SIPRequest.ParseSIPRequest(sipMessageBuffer);

            var uas          = userAgent.AcceptCall(inviteReq);
            var mediaSession = CreateMediaSession();

            _ = Task.Run(() =>
            {
                Task.Delay(2000).Wait();

                string ackReqStr = @"ACK sip:127.0.0.1:5060 SIP/2.0
Via: SIP/2.0/UDP 127.0.0.1:51200;branch=z9hG4bK76dfb1480ea14f778bd24afed1c8ded0;rport
To: <sip:[email protected]>;tag=YWPNZPMLPB
From: <sip:[email protected]>;tag=GCLNRILCDU
Call-ID: 7265e19f53a146a1bacdf4f4f8ea70b2
CSeq: 1 ACK
Max-Forwards: 70
Content-Length: 160

v=0
o=- 67424 0 IN IP4 127.0.0.1
s=-
c=IN IP4 127.0.0.1
t=0 0
m=audio 16976 RTP/AVP 8 101
a=rtpmap:101 telephone-event/8000
a=fmtp:101 0-16
a=sendrecv" + m_CRLF + m_CRLF;


                uas.ClientTransaction.ACKReceived(dummySep, dummySep, SIPRequest.ParseSIPRequest(ackReqStr));
            });

            await userAgent.Answer(uas, mediaSession);

            Assert.True(userAgent.IsCallActive);
        }
        static void Main(string[] args)
        {
            bool isConsole = false;

            try
            {
                // Get DateTime.ToString() to use a format ot ToString("o") instead of ToString("G").
                CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
                culture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";
                culture.DateTimeFormat.LongTimePattern  = "THH:mm:ss.fffffffzzz";
                Thread.CurrentThread.CurrentCulture     = culture;

                m_serverStorageType    = (AppState.GetConfigSetting(m_storageTypeKey) != null) ? StorageTypesConverter.GetStorageType(AppState.GetConfigSetting(m_storageTypeKey)) : StorageTypes.Unknown;
                m_serverStorageConnStr = AppState.GetConfigSetting(m_connStrKey);
                bool monitorCalls = true;

                if (m_serverStorageType == StorageTypes.Unknown || m_serverStorageConnStr.IsNullOrBlank())
                {
                    throw new ApplicationException("The SIP Application Service cannot start with no persistence settings specified.");
                }

                // Need to force the System.Data.Entity assembly to load before a dialplan instantiation. The assembly will fail to load if
                // requested from the Dynamic Language Runtime which is what happens if the first time it's requested is in an IronRuby dialplan.
                using (SIPSorceryEntities appEntities = new SIPSorceryEntities())
                {
                    logger.Debug("Lookups count=" + (from lookup in appEntities.SIPDialplanLookups select lookup).Count() + ", forcing entity framework assemblies to load.");
                }

                //if (args != null && args.Length > 0)
                //{
                isConsole = true;
                Console.WriteLine("SIP App Server starting");
                logger.Debug("SIP App Server Console starting...");

                string sipSocket             = null;
                string callManagerSvcAddress = null;

                foreach (string arg in args)
                {
                    if (arg.StartsWith("-sip:"))
                    {
                        sipSocket = arg.Substring(5);
                    }
                    else if (arg.StartsWith("-cms:"))
                    {
                        callManagerSvcAddress = arg.Substring(5);
                    }
                    else if (arg.StartsWith("-hangupcalls:"))
                    {
                        monitorCalls = Convert.ToBoolean(arg.Substring(13));
                    }
                }

                SIPAppServerDaemon daemon = null;

                if (sipSocket.IsNullOrBlank() || callManagerSvcAddress.IsNullOrBlank())
                {
                    daemon = new SIPAppServerDaemon(m_serverStorageType, m_serverStorageConnStr);
                }
                else
                {
                    daemon = new SIPAppServerDaemon(m_serverStorageType, m_serverStorageConnStr, SIPEndPoint.ParseSIPEndPoint(sipSocket), callManagerSvcAddress, monitorCalls);
                }

                Thread daemonThread = new Thread(new ThreadStart(daemon.Start));
                daemonThread.Start();

                m_proxyUp.WaitOne();
                //}
                //else
                //{
                //    logger.Debug("SIP App Server Windows Service Starting...");
                //    System.ServiceProcess.ServiceBase[] ServicesToRun;
                //    SIPAppServerDaemon daemon = new SIPAppServerDaemon(m_serverStorageType, m_serverStorageConnStr);
                //    ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service(daemon) };
                //    System.ServiceProcess.ServiceBase.Run(ServicesToRun);
                //}
            }
            catch (Exception excp)
            {
                Console.WriteLine("Exception SIP App Server Main. " + excp.Message);

                if (isConsole)
                {
                    Console.WriteLine("press any key to exit...");
                    Console.ReadLine();
                }
            }
        }
        public bool AuthenticateCall()
        {
            m_isAuthenticated = false;

            try
            {
                if (m_sipAccount == null)
                {
                    logger.LogWarning($"Rejecting authentication required call for {m_uasTransaction.TransactionRequestFrom}, SIP account not found.");
                    Reject(SIPResponseStatusCodesEnum.Forbidden, null, null);
                }
                else
                {
                    SIPRequest  sipRequest       = m_uasTransaction.TransactionRequest;
                    SIPEndPoint localSIPEndPoint = (!sipRequest.Header.ProxyReceivedOn.IsNullOrBlank()) ? SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxyReceivedOn) : sipRequest.LocalSIPEndPoint;
                    SIPEndPoint remoteEndPoint   = (!sipRequest.Header.ProxyReceivedFrom.IsNullOrBlank()) ? SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxyReceivedFrom) : sipRequest.RemoteSIPEndPoint;

                    var authenticationResult = SIPRequestAuthenticator.AuthenticateSIPRequest(localSIPEndPoint, remoteEndPoint, sipRequest, m_sipAccount);
                    if (authenticationResult.Authenticated)
                    {
                        if (authenticationResult.WasAuthenticatedByIP)
                        {
                            logger.LogDebug("New call from " + remoteEndPoint.ToString() + " successfully authenticated by IP address.");
                        }
                        else
                        {
                            logger.LogDebug("New call from " + remoteEndPoint.ToString() + " successfully authenticated by digest.");
                        }

                        m_isAuthenticated = true;
                    }
                    else
                    {
                        // Send authorisation failure or required response
                        SIPResponse authReqdResponse = SIPResponse.GetResponse(sipRequest, authenticationResult.ErrorResponse, null);
                        authReqdResponse.Header.AuthenticationHeader = authenticationResult.AuthenticationRequiredHeader;
                        logger.LogWarning($"Call not authenticated for {m_sipAccount.SIPUsername}@{m_sipAccount.SIPDomain}, responding with {authenticationResult.ErrorResponse}.");
                        m_uasTransaction.SendFinalResponse(authReqdResponse);
                    }
                }
            }
            catch (Exception excp)
            {
                logger.LogError("Exception SIPServerUserAgent AuthenticateCall. " + excp.Message);
                Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null);
            }

            return(m_isAuthenticated);
        }
Example #10
0
        /// <summary>
        /// This constructor is used by client user agents or SIP elements acting in a client user agent role. When
        /// acting as a client user agent the local fields are contained in the From header and the remote fields are
        /// in the To header.
        /// </summary>
        public SIPDialogue(
            UACInviteTransaction uacInviteTransaction,
            string owner,
            string adminMemberId)
        {
            Id = Guid.NewGuid();

            CallId          = uacInviteTransaction.TransactionRequest.Header.CallId;
            RouteSet        = (uacInviteTransaction.TransactionFinalResponse != null && uacInviteTransaction.TransactionFinalResponse.Header.RecordRoutes != null) ? uacInviteTransaction.TransactionFinalResponse.Header.RecordRoutes.Reversed() : null;
            LocalUserField  = uacInviteTransaction.TransactionFinalResponse.Header.From.FromUserField;
            LocalTag        = uacInviteTransaction.TransactionFinalResponse.Header.From.FromTag;
            RemoteUserField = uacInviteTransaction.TransactionFinalResponse.Header.To.ToUserField;
            RemoteTag       = uacInviteTransaction.TransactionFinalResponse.Header.To.ToTag;
            CSeq            = uacInviteTransaction.TransactionRequest.Header.CSeq;
            CDRId           = uacInviteTransaction.CDR.CDRId;
            Owner           = owner;
            AdminMemberId   = adminMemberId;
            ContentType     = uacInviteTransaction.TransactionRequest.Header.ContentType;
            SDP             = uacInviteTransaction.TransactionRequest.Body;
            RemoteSDP       = uacInviteTransaction.TransactionFinalResponse.Body;
            Inserted        = DateTimeOffset.UtcNow;
            Direction       = SIPCallDirection.Out;

            // Set the dialogue remote target and take care of mangling if an upstream proxy has indicated it's required.
            RemoteTarget  = new SIPURI(uacInviteTransaction.TransactionRequest.URI.Scheme, SIPEndPoint.ParseSIPEndPoint(uacInviteTransaction.RemoteEndPoint.ToString()));
            ProxySendFrom = uacInviteTransaction.TransactionFinalResponse.Header.ProxyReceivedOn;
            if (uacInviteTransaction.TransactionFinalResponse.Header.Contact != null && uacInviteTransaction.TransactionFinalResponse.Header.Contact.Count > 0)
            {
                RemoteTarget = uacInviteTransaction.TransactionFinalResponse.Header.Contact[0].ContactURI.CopyOf();
                if (!uacInviteTransaction.TransactionFinalResponse.Header.ProxyReceivedFrom.IsNullOrBlank())
                {
                    // Setting the Proxy-ReceivedOn header is how an upstream proxy will let an agent know it should mangle the contact.
                    // Don't mangle private contacts if there is a Record-Route header. If a proxy is putting private IP's in a Record-Route header that's its problem.
                    if (RouteSet == null && IPSocket.IsPrivateAddress(RemoteTarget.Host))
                    {
                        SIPEndPoint remoteUASSIPEndPoint = SIPEndPoint.ParseSIPEndPoint(uacInviteTransaction.TransactionFinalResponse.Header.ProxyReceivedFrom);
                        RemoteTarget.Host = remoteUASSIPEndPoint.GetIPEndPoint().ToString();
                    }
                }
            }
        }
Example #11
0
 public void Load(DataRow row)
 {
     try
     {
         Id                     = new Guid(row["id"] as string);
         SIPAccountId           = new Guid(row["sipaccountid"] as string);
         SIPAccountName         = row["sipaccountname"] as string;
         Owner                  = row["owner"] as string;
         AdminMemberId          = row["adminmemberid"] as string;
         UserAgent              = row["useragent"] as string;
         m_contactURI           = SIPURI.ParseSIPURI(row["contacturi"] as string);
         m_mangledContactURI    = (!(row["mangledcontacturi"] as string).IsNullOrBlank()) ? SIPURI.ParseSIPURI(row["mangledcontacturi"] as string) : null;
         Expiry                 = Convert.ToInt32(row["expiry"]);
         RemoteSIPEndPoint      = (!(row["remotesipsocket"] as string).IsNullOrBlank()) ? SIPEndPoint.ParseSIPEndPoint(row["remotesipsocket"] as string) : null;
         m_proxySIPEndPoint     = (!(row["proxysipsocket"] as string).IsNullOrBlank()) ? SIPEndPoint.ParseSIPEndPoint(row["proxysipsocket"] as string) : null;
         m_registrarSIPEndPoint = (!(row["registrarsipsocket"] as string).IsNullOrBlank()) ? SIPEndPoint.ParseSIPEndPoint(row["registrarsipsocket"] as string) : null;
         LastUpdate             = DateTimeOffset.Parse(row["lastupdate"] as string);
     }
     catch (Exception excp)
     {
         logger.Error("Exception SIPRegistrarBinding Load. " + excp.Message);
         throw;
     }
 }
Example #12
0
        public bool AuthenticateCall()
        {
            m_isAuthenticated = false;

            try
            {
                if (m_sipAccount == null)
                {
                    // If no SIP account specified then the assumption is authentication is not required.
                    m_isAuthenticated = true;
                }
                else
                {
                    SIPRequest  sipRequest       = m_transaction.TransactionRequest;
                    SIPEndPoint localSIPEndPoint = (!sipRequest.Header.ProxyReceivedOn.IsNullOrBlank()) ? SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxyReceivedOn) : sipRequest.LocalSIPEndPoint;
                    SIPEndPoint remoteEndPoint   = (!sipRequest.Header.ProxyReceivedFrom.IsNullOrBlank()) ? SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxyReceivedFrom) : sipRequest.RemoteSIPEndPoint;

                    SIPRequestAuthenticationResult authenticationResult = SIPRequestAuthenticator.AuthenticateSIPRequest(localSIPEndPoint, remoteEndPoint, sipRequest, m_sipAccount);
                    if (authenticationResult.Authenticated)
                    {
                        if (authenticationResult.WasAuthenticatedByIP)
                        {
                            logger.LogDebug(m_transaction.TransactionRequest.Method + " request from " + remoteEndPoint.ToString() + " successfully authenticated by IP address.");
                        }
                        else
                        {
                            logger.LogDebug(m_transaction.TransactionRequest.Method + " request from " + remoteEndPoint.ToString() + " successfully authenticated by digest.");
                        }

                        m_isAuthenticated = true;
                    }
                    else
                    {
                        // Send authorisation failure or required response
                        SIPResponse authReqdResponse = SIPResponse.GetResponse(sipRequest, authenticationResult.ErrorResponse, null);
                        authReqdResponse.Header.AuthenticationHeader = authenticationResult.AuthenticationRequiredHeader;
                        logger.LogDebug(m_transaction.TransactionRequest.Method + " request not authenticated for " + m_sipUsername + "@" + m_sipDomain + ", responding with " + authenticationResult.ErrorResponse + ".");
                        m_transaction.SendResponse(authReqdResponse);
                    }
                }
            }
            catch (Exception excp)
            {
                logger.LogError("Exception SIPNonInviteUserAgent AuthenticateCall. " + excp.Message);
                Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null);
            }

            return(m_isAuthenticated);
        }