private SIPResponse GetAuthReqdResponse(SIPRequest sipRequest, string nonce, string realm)
        {
            try
            {
                SIPResponse authReqdResponse =
                    SIPTransport.GetResponse(sipRequest, SIPResponseStatusCodesEnum.Unauthorised, null);
                SIPAuthenticationHeader authHeader =
                    new SIPAuthenticationHeader(SIPAuthorisationHeadersEnum.WWWAuthenticate, realm, nonce);
                SIPHeader requestHeader = sipRequest.Header;
                SIPHeader unauthHeader  = new SIPHeader(requestHeader.Contact, requestHeader.From, requestHeader.To,
                                                        requestHeader.CSeq, requestHeader.CallId);

                if (unauthHeader.To.ToTag == null || unauthHeader.To.ToTag.Trim().Length == 0)
                {
                    unauthHeader.To.ToTag = CallProperties.CreateNewTag();
                }

                unauthHeader.CSeqMethod           = requestHeader.CSeqMethod;
                unauthHeader.Vias                 = requestHeader.Vias;
                unauthHeader.AuthenticationHeader = authHeader;
                //unauthHeader.Server = m_serverAgent;
                unauthHeader.UserAgent   = m_serverAgent;
                unauthHeader.MaxForwards = Int32.MinValue;

                authReqdResponse.Header = unauthHeader;

                return(authReqdResponse);
            }
            catch (Exception excp)
            {
                Logger.Logger.Error("Exception GetAuthReqdResponse. ->" + excp.Message);
                throw excp;
            }
        }
Ejemplo n.º 2
0
 public SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum errorResponse,
                                       SIPAuthenticationHeader authenticationRequiredHeader)
 {
     Authenticated = false;
     ErrorResponse = errorResponse;
     AuthenticationRequiredHeader = authenticationRequiredHeader;
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Cancels an in progress call. This method should be called prior to the remote user agent server answering the call.
        /// </summary>
        public void Cancel()
        {
            try
            {
                m_callCancelled = true;

                // Cancel server call.
                if (m_serverTransaction == null)
                {
                    logger.LogDebug("Cancelling forwarded call leg " + m_sipCallDescriptor.Uri + ", server transaction has not been created yet no CANCEL request required.");
                }
                else if (m_cancelTransaction != null)
                {
                    if (m_cancelTransaction.TransactionState != SIPTransactionStatesEnum.Completed)
                    {
                        logger.LogDebug("Call " + m_serverTransaction.TransactionRequest.URI.ToString() + " has already been cancelled once, trying again.");
                        m_cancelTransaction.SendRequest();
                    }
                    else
                    {
                        logger.LogDebug("Call " + m_serverTransaction.TransactionRequest.URI.ToString() + " has already responded to CANCEL, probably overlap in messages not re-sending.");
                    }
                }
                else //if (m_serverTransaction.TransactionState == SIPTransactionStatesEnum.Proceeding || m_serverTransaction.TransactionState == SIPTransactionStatesEnum.Trying)
                {
                    logger.LogDebug("Cancelling forwarded call leg, sending CANCEL to " + m_serverTransaction.TransactionRequest.URI.ToString() + ".");

                    // No response has been received from the server so no CANCEL request necessary, stop any retransmits of the INVITE.
                    m_serverTransaction.CancelCall();

                    SIPRequest cancelRequest = GetCancelRequest(m_serverTransaction.TransactionRequest);

                    // If auth header is included inside INVITE request, we re-include them inside CANCEL request
                    if (m_serverTransaction.TransactionRequest.Header.HasAuthenticationHeader)
                    {
                        string username = (m_sipCallDescriptor.AuthUsername == null || m_sipCallDescriptor.AuthUsername.Trim().Length <= 0 ? m_sipCallDescriptor.Username : m_sipCallDescriptor.AuthUsername);
                        SIPAuthorisationDigest authDigest = m_serverTransaction.TransactionRequest.Header.AuthenticationHeaders.First().SIPDigest;
                        authDigest.SetCredentials(username, m_sipCallDescriptor.Password, m_sipCallDescriptor.Uri, SIPMethodsEnum.CANCEL.ToString());

                        var authHeader = new SIPAuthenticationHeader(authDigest);
                        authHeader.SIPDigest.IncrementNonceCount();
                        authHeader.SIPDigest.Response = authDigest.GetDigest();

                        cancelRequest.Header.AuthenticationHeaders.Clear();
                        cancelRequest.Header.AuthenticationHeaders.Add(authHeader);
                    }

                    m_cancelTransaction = new SIPNonInviteTransaction(m_sipTransport, cancelRequest, m_outboundProxy);
                    m_cancelTransaction.SendRequest();
                }

                CallFailed?.Invoke(this, "Call cancelled by user.", null);
            }
            catch (Exception excp)
            {
                logger.LogError("Exception CancelServerCall. " + excp.Message);
            }
        }
Ejemplo n.º 4
0
        public void ParseAuthHeaderUnitTest()
        {
            Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);

            SIPAuthenticationHeader authHeader = SIPAuthenticationHeader.ParseSIPAuthenticationHeader(SIPAuthorisationHeadersEnum.ProxyAuthorization, "Digest realm=\"o-fone.com\",nonce=\"mv1keFTRX4yYVsHb/E+rviOflIurIw\",algorithm=MD5,qop=\"auth\",username=\"joe.bloggs\", response=\"1234\",uri=\"sip:o-fone.com\"");

            Console.WriteLine("SIP Auth Header=" + authHeader.ToString() + ".");

            Assert.AreEqual(authHeader.SIPDigest.Realm, "o-fone.com", "The SIP auth header realm was not parsed correctly.");
            Assert.AreEqual(authHeader.SIPDigest.Nonce, "mv1keFTRX4yYVsHb/E+rviOflIurIw", "The SIP auth header nonce was not parsed correctly.");
            Assert.AreEqual(authHeader.SIPDigest.URI, "sip:o-fone.com", "The SIP URI was not parsed correctly.");
            Assert.AreEqual(authHeader.SIPDigest.Username, "joe.bloggs", "The SIP username was not parsed correctly.");
            Assert.AreEqual(authHeader.SIPDigest.Response, "1234", "The SIP response was not parsed correctly.");
        }
Ejemplo n.º 5
0
        /// <summary>
        /// MagicJack apply a custom algorithm when calculating their nonce seemingly in order to
        /// prevent other SIP UAs from being able to authenticate. This method attempts to apply the same
        /// algorithm to allow the authenticated requests from this stack.
        /// </summary>
        /// <remarks>
        /// MJ is modifying the nonce dynamically. They append an underscore, then 8 characters to the nonce before computing the MD5. The 8 characters come from the call id.
        /// Use the first 8 bytes of the nonce as an index into your call id.
        /// Assume your callid is:
        /// callid: 9876ABC56738DD43...
        /// index:  0123456789ABCDEF
        /// and your nonce is: 8765abc4_32190
        /// Take the first digit of your nonce (which in our example is 8 ), and find the value in the callid at index 8, which is 6.
        /// So, append that to the nonce. 8765abc4_32190_6
        /// Then move on to the second digit of the nonce, which is 7 in our example. Find the value at index 7 in the callid, which is 5, and append that:
        /// 8765abc4_32190_65 continue until you have done 8 digits. Your new nonce would be:
        /// 8765abc4_32190_65CB38DA Use this value when computing the MD5, but pass the original nonce to magicJack.
        /// </remarks>
        /// <param name="authReqdResponse"></param>
        /// <returns></returns>
        public static SIPAuthenticationHeader GetAuthenticationHeader(SIPResponse authReqdResponse)
        {
            try {
                SIPAuthenticationHeader mjAuthHeader = new SIPAuthenticationHeader(authReqdResponse.Header.AuthenticationHeader.SIPDigest);
                string origNonce = mjAuthHeader.SIPDigest.Nonce;
                string mjNonce   = GetNonce(origNonce, authReqdResponse.Header.CallId);
                mjAuthHeader.SIPDigest.Nonce    = mjNonce;
                mjAuthHeader.SIPDigest.Response = mjAuthHeader.SIPDigest.Digest;
                mjAuthHeader.SIPDigest.Nonce    = origNonce;

                return(mjAuthHeader);
            }
            catch (Exception excp) {
                logger.Error("Exception SIPProviderMagicJack GetAuthenticationHeader. " + excp.Message);
                throw;
            }
        }
Ejemplo n.º 6
0
 public override void AddMessageResponse(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPResponse response)
 {
     if (response.Status == SIPResponseStatusCodesEnum.Unauthorised)
     {
         logger.Info("需要提供身份认证字段" + remoteEndPoint.ToHost());
         //安全身份认证
         SIPAuthorisationDigest digest = new SIPAuthorisationDigest(SIPAuthorisationHeadersEnum.Authorize);
         digest.Username = response.Header.AuthenticationHeader.SIPDigest.Username;
         digest.Password = "******";
         digest.Realm    = response.Header.AuthenticationHeader.SIPDigest.Realm;
         digest.Nonce    = response.Header.AuthenticationHeader.SIPDigest.Nonce;
         digest.Response = digest.Digest;
         string md5Pass = digest.ToString();
         SIPAuthenticationHeader auth = new SIPAuthenticationHeader(digest);
         _auth = auth;
         RegisterToPlatform();
     }
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Attempts to generate a SIP request authentication header from the most appropriate digest challenge.
        /// </summary>
        /// <param name="authenticationChallenges">The challenges to authenticate the request against. Typically the challenges come from a
        /// SIP response.</param>
        /// <param name="uri">The URI of the SIP request being authenticated.</param>
        /// <param name="method">The method of the SIP request being authenticated.</param>
        /// <param name="username">The username to authenticate with.</param>
        /// <param name="password">The password to authenticate with.</param>
        /// <param name="digestAlgorithm">The digest algorithm to use in the authentication header.</param>
        /// <returns>An authentication header that can be added to a SIP header.</returns>
        public static SIPAuthenticationHeader GetAuthenticationHeader(List <SIPAuthenticationHeader> authenticationChallenges,
                                                                      SIPURI uri,
                                                                      SIPMethodsEnum method,
                                                                      string username,
                                                                      string password,
                                                                      DigestAlgorithmsEnum digestAlgorithm = DigestAlgorithmsEnum.MD5)
        {
            var challenge = authenticationChallenges.First().SIPDigest.CopyOf();

            challenge.DigestAlgorithm = digestAlgorithm;
            challenge.SetCredentials(username, password, uri.ToString(), method.ToString());

            var authHeader = new SIPAuthenticationHeader(challenge);

            authHeader.SIPDigest.Response = challenge.GetDigest();

            return(authHeader);
        }
Ejemplo n.º 8
0
            public void MagicJackAuthUnitTest()
            {
                Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);

                string      nonce            = "8765abc4_32190";
                SIPResponse authReqdResponse = new SIPResponse(SIPResponseStatusCodesEnum.Unauthorised, null, null);

                authReqdResponse.Header.CallId = "9876ABC56738DD43";
                authReqdResponse.Header.AuthenticationHeader = SIPAuthenticationHeader.ParseSIPAuthenticationHeader(SIPAuthorisationHeadersEnum.WWWAuthenticate, "Digest nonce=\"" + nonce + "\",realm=\"stratus.com\",algorithm=MD5");
                authReqdResponse.Header.AuthenticationHeader.SIPDigest.SetCredentials("username", "password", "sip:[email protected]", SIPMethodsEnum.INVITE.ToString());

                Assert.IsTrue(SIPProviderMagicJack.IsMagicJackRequest(authReqdResponse), "The SIP Response was not correctly identified as being for a MagicJack request.");

                string mjNonce = GetNonce(authReqdResponse.Header.AuthenticationHeader.SIPDigest.Nonce, authReqdResponse.Header.CallId);
                SIPAuthenticationHeader mjAuthheader = SIPProviderMagicJack.GetAuthenticationHeader(authReqdResponse);

                Assert.IsTrue(mjNonce == "8765abc4_32190_65CB38DA", "The MagicJack nonce was not correctly generated.");
                Assert.IsTrue(authReqdResponse.Header.AuthenticationHeader.SIPDigest.Nonce == nonce, "The nonce set in the MagicJack response was not preserved correctly.");

                Console.WriteLine("-----------------------------------------");
            }
Ejemplo n.º 9
0
        /// <summary>
        /// Authenticates a SIP request.
        /// </summary>
        public static SIPRequestAuthenticationResult AuthenticateSIPRequest(
            SIPEndPoint localSIPEndPoint,
            SIPEndPoint remoteEndPoint,
            SIPRequest sipRequest,
            ISIPAccount sipAccount)
        {
            try
            {
                if (sipAccount == null)
                {
                    return(new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.Forbidden, null));
                }
                else if (sipAccount.IsDisabled)
                {
                    logger.LogWarning($"SIP account {sipAccount.SIPUsername}@{sipAccount.SIPDomain} is disabled for {sipRequest.Method}.");

                    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
                    {
                        // 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))
                        {
                            logger.LogWarning($"Authentication failed stale nonce for realm={sipAccount.SIPDomain}, username={sipAccount.SIPUsername}, uri={uri}, nonce={requestNonce}, method={sipRequest.Method}.");

                            SIPAuthenticationHeader authHeader = new SIPAuthenticationHeader(SIPAuthorisationHeadersEnum.WWWAuthenticate, sipAccount.SIPDomain, GetNonce());
                            return(new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.Unauthorised, authHeader));
                        }
                        else
                        {
                            SIPAuthorisationDigest checkAuthReq = reqAuthHeader.SIPDigest;

                            if (sipAccount.SIPPassword != null)
                            {
                                checkAuthReq.SetCredentials(sipAccount.SIPUsername, sipAccount.SIPPassword, uri, sipRequest.Method.ToString());
                            }
                            else if (sipAccount.HA1Digest != null)
                            {
                                checkAuthReq.SetCredentials(sipAccount.HA1Digest, uri, sipRequest.Method.ToString());
                            }
                            else
                            {
                                throw new ApplicationException("SIP authentication cannot be attempted as neither a password or HA1 digest are available.");
                            }

                            string digest = checkAuthReq.Digest;

                            if (digest == response)
                            {
                                // Successfully authenticated
                                return(new SIPRequestAuthenticationResult(true, false));
                            }
                            else
                            {
                                logger.LogWarning("Authentication token check failed for realm=" + sipAccount.SIPDomain + ", username="******", uri=" + uri + ", nonce=" + requestNonce + ", method=" + sipRequest.Method + ".");

                                SIPAuthenticationHeader authHeader = new SIPAuthenticationHeader(SIPAuthorisationHeadersEnum.WWWAuthenticate, sipAccount.SIPDomain, GetNonce());
                                return(new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.Unauthorised, authHeader));
                            }
                        }
                    }
                }
            }
            catch (Exception excp)
            {
                logger.LogError(0, excp, "Exception AuthoriseSIPRequest. " + excp.Message);
                return(new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.InternalServerError, null));
            }
        }
        /// <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)
                {
                    if (logSIPMonitorEvent != null)
                    {
                        logSIPMonitorEvent(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
                    {
                        // 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)
            {
                if (logSIPMonitorEvent != null)
                {
                    logSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Authoriser, SIPMonitorEventTypesEnum.Error, "Exception AuthoriseSIPRequest. " + excp.Message, null));
                }
                return new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.InternalServerError, null);
            }
        }
Ejemplo n.º 11
0
        /// <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)
                {
                    if (logSIPMonitorEvent != null)
                    {
                        logSIPMonitorEvent(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
                    {
                        // 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)
            {
                if (logSIPMonitorEvent != null)
                {
                    logSIPMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.Authoriser, SIPMonitorEventTypesEnum.Error, "Exception AuthoriseSIPRequest. " + excp.Message, null));
                }
                return(new SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum.InternalServerError, null));
            }
        }