Ejemplo n.º 1
0
        private static ApiErrorItem ParseLdapException(LdapException ex)
        {
            // If the LDAP server returned an error, it will be formatted
            // similar to this:
            //    "0000052D: AtrErr: DSID-03191083, #1:\n\t0: 0000052D: DSID-03191083, problem 1005 (CONSTRAINT_ATT_TYPE), data 0, Att 9005a (unicodePwd)\n\0"
            //
            // The leading number before the ':' is the Win32 API Error Code in HEX
            if (ex.LdapErrorMessage == null)
            {
                return(new ApiErrorItem(ApiErrorCode.LdapProblem, "Unexpected null exception"));
            }

            var m = Regex.Match(ex.LdapErrorMessage, "([0-9a-fA-F]+):");

            if (!m.Success)
            {
                return(new ApiErrorItem(ApiErrorCode.LdapProblem, $"Unexpected error: {ex.LdapErrorMessage}"));
            }

            var errCodeString = m.Groups[1].Value;
            var errCode       = int.Parse(errCodeString, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
            var err           = Win32ErrorCode.ByCode(errCode);

            return(err == null
                ? new ApiErrorItem(ApiErrorCode.LdapProblem, $"Unexpected Win32 API error; error code: {errCodeString}")
                : new ApiErrorItem(ApiErrorCode.InvalidCredentials,
                                   $"Resolved Win32 API Error: code={err.Code} name={err.CodeName} desc={err.Description}"));
        }
Ejemplo n.º 2
0
 protected void NotifyExceptionListeners(LdapMessage sourceMessage, LdapException ldapException)
 {
     if (null != directory_exception_event)
     {
         directory_exception_event(this, new DirectoryExceptionEventArgs(sourceMessage, ldapException));
     }
 }
Ejemplo n.º 3
0
        public MonitorEventResponse(RfcLdapMessage message)
            : base(message)
        {
            sbyte[] returnedValue = Value;

            if (null == returnedValue)
            {
                throw new LdapException(LdapException.resultCodeToString(ResultCode),
                                        ResultCode,
                                        null);
            }

            LBERDecoder decoder = new LBERDecoder();

            Asn1Sequence sequence = (Asn1Sequence)decoder.decode(returnedValue);

            int     length      = ((Asn1Integer)sequence.get_Renamed(0)).intValue();
            Asn1Set sequenceSet = (Asn1Set)sequence.get_Renamed(1);

            specifier_list = new EdirEventSpecifier[length];

            for (int i = 0; i < length; i++)
            {
                Asn1Sequence eventspecifiersequence =
                    (Asn1Sequence)sequenceSet.get_Renamed(i);
                int classfication =
                    ((Asn1Integer)eventspecifiersequence.get_Renamed(0)).intValue();
                int enumtype =
                    ((Asn1Enumerated)eventspecifiersequence.get_Renamed(1)).intValue();
                specifier_list[i] =
                    new EdirEventSpecifier((EdirEventType)classfication, (EdirEventResultType)enumtype);
            }
        }
        public static string returnErrorMessage(LdapException lexc)
        {
            string error        = lexc.ServerErrorMessage;
            string errorcode    = error.Substring(77, 3);
            string errorMessage = ADAuthentication.ldapErrors[errorcode];

            return(errorMessage);
        }
Ejemplo n.º 5
0
        public BooleanResult AuthenticateUser(Shared.Types.SessionProperties properties)
        {
            // Get the LdapServer object from the session properties (created in BeginChain)
            LdapServer server = properties.GetTrackedSingle <LdapServer>();

            if (server == null)
            {
                return new BooleanResult()
                       {
                           Success = false, Message = "Internal error: LdapServer object not available"
                       }
            }
            ;

            try
            {
                m_logger.DebugFormat("AuthenticateUser({0})", properties.Id.ToString());

                Shared.Types.UserInformation userInfo = properties.GetTrackedSingle <Shared.Types.UserInformation>();
                m_logger.DebugFormat("Received username: {0}", userInfo.Username);

                // Authenticate the login
                m_logger.DebugFormat("Attempting authentication for {0}", userInfo.Username);

                // Se o login foi realizado com sucesso, vamos mapear o disco da rede.
                BooleanResult result = server.Authenticate(userInfo.Username, userInfo.Password);
                return(result);
            }
            catch (Exception e)
            {
                if (e is LdapException)
                {
                    LdapException ldapEx = (e as LdapException);

                    if (ldapEx.ErrorCode == 81)
                    {
                        // Server can't be contacted, set server object to null
                        m_logger.ErrorFormat("Server unavailable: {0}, {1}", ldapEx.ServerErrorMessage, e.Message);
                        server.Close();
                        properties.AddTrackedSingle <LdapServer>(null);
                        return(new BooleanResult {
                            Success = false, Message = "Failed to contact LDAP server."
                        });
                    }
                }

                // This is an unexpected error, so set LdapServer object to null, because
                // subsequent stages shouldn't use it, and this indicates to later stages
                // that this stage failed unexpectedly.
                server.Close();
                properties.AddTrackedSingle <LdapServer>(null);
                m_logger.ErrorFormat("Exception in LDAP authentication: {0}", e);
                throw;  // Allow pGina service to catch and handle exception
            }
        }
Ejemplo n.º 6
0
        public void Ctor_Default()
        {
            var exception = new LdapException();

            Assert.NotEmpty(exception.Message);
            Assert.Null(exception.InnerException);

            Assert.Equal(0, exception.ErrorCode);
            Assert.Null(exception.ServerErrorMessage);
            Assert.Empty(exception.PartialResults);
        }
Ejemplo n.º 7
0
        public void Ctor_ErrorCode_Message_ServerErrorMessage()
        {
            var exception = new LdapException(10, "message", "serverErrorMessage");

            Assert.Equal("message", exception.Message);
            Assert.Null(exception.InnerException);

            Assert.Equal(10, exception.ErrorCode);
            Assert.Equal("serverErrorMessage", exception.ServerErrorMessage);
            Assert.Empty(exception.PartialResults);
        }
        public void TestInvalidFilter()
        {
            using LdapConnection connection = GetConnection();

            LdapException ex = Assert.Throws <LdapException>(() =>
            {
                var searchRequest = new SearchRequest(LdapConfiguration.Configuration.SearchDn, "==invalid==", SearchScope.OneLevel);
                _ = (SearchResponse)connection.SendRequest(searchRequest);
            });

            Assert.Equal(/* LdapError.FilterError */ 0x57, ex.ErrorCode);
        }
Ejemplo n.º 9
0
        public void Ctor_Message_InnerException()
        {
            var innerException = new Exception();
            var exception      = new LdapException("message", innerException);

            Assert.Equal("message", exception.Message);
            Assert.Same(innerException, exception.InnerException);

            Assert.Equal(0, exception.ErrorCode);
            Assert.Null(exception.ServerErrorMessage);
            Assert.Empty(exception.PartialResults);
        }
Ejemplo n.º 10
0
 public static void Validate(int error)
 {
     if (error != (int)LdapStatus.LDAP_SUCCESS)
     {
         var errorPointer = LdapClientLibrary.ldap_err2string(error);
         var errorString  = Marshal.PtrToStringAnsi(errorPointer);
         var message      = string.Format("{0}-{1} (error code = {2})", "Exception thrown from LDAP", errorString, error);
         var exception    = new LdapException(message);
         exception.LdapError = (LdapStatus)Enum.Parse(typeof(LdapStatus), error.ToString(), false);
         throw exception;
     }
 }
Ejemplo n.º 11
0
 private static void AppendLdapException(this StringBuilder stringBuilder, LdapException exception)
 {
     stringBuilder.AppendMarkdownLine("LdapException specific:");
     stringBuilder.Append("   ").AppendMarkdownProperty("ServerErrorMessage", exception.ServerErrorMessage);
     stringBuilder.Append("   ").AppendMarkdownProperty("ErrorCode", exception.ErrorCode.ToString());
     foreach (var partialResult in exception.PartialResults)
     {
         if (partialResult != null)
         {
             stringBuilder.Append("   ").AppendMarkdownProperty("PartialResult", partialResult.ToString());
         }
     }
 }
Ejemplo n.º 12
0
        private static LdapPacket BuildError(LdapPacket request, LdapException ex)
        {
            BaseOperationDone operation = null;

            switch (request.ProtocolOperation.Tag.LdapCommand)
            {
            case LdapCommands.AddRequest:
                operation = new AddResponse();
                break;

            case LdapCommands.BindRequest:
                operation = new BindResponse();
                break;

            case LdapCommands.DelRequest:
                operation = new DelResponse();
                break;

            case LdapCommands.SearchRequest:
                operation = new SearchResultDone();
                break;

            case LdapCommands.ModifyRequest:
                operation = new ModifyResponse();
                break;
            }

            operation.Result = new LDAPResult
            {
                MatchedDN         = new DEROctetString(ex.Target),
                DiagnosticMessage = new DEROctetString(ex.Message),
                ResultCode        = new DEREnumerated <LDAPResultCodes>
                {
                    Value = ex.Code
                }
            };
            var ldapPacket = new LdapPacket
            {
                MessageId         = request.MessageId,
                ProtocolOperation = new DERProtocolOperation
                {
                    Operation = operation
                }
            };

            return(ldapPacket);
        }
        // Token: 0x06001979 RID: 6521 RVA: 0x0006BFA4 File Offset: 0x0006A1A4
        private PropertyValidationError CheckForDDLMisconfiguration(DirectoryException e)
        {
            DirectoryOperationException ex = e as DirectoryOperationException;

            if (ex != null)
            {
                if (ex.Response == null)
                {
                    return(null);
                }
                ResultCode resultCode = ex.Response.ResultCode;
                if (resultCode == ResultCode.OperationsError)
                {
                    return(new PropertyValidationError(DirectoryStrings.ErrorDDLOperationsError, ADDynamicGroupSchema.RecipientContainer, this.RecipientContainer));
                }
                switch (resultCode)
                {
                case ResultCode.ReferralV2:
                case ResultCode.Referral:
                    return(new PropertyValidationError(DirectoryStrings.ErrorDDLReferral, ADDynamicGroupSchema.RecipientContainer, this.RecipientContainer));

                default:
                    switch (resultCode)
                    {
                    case ResultCode.NoSuchObject:
                        return(new PropertyValidationError(DirectoryStrings.ErrorDDLNoSuchObject, ADDynamicGroupSchema.RecipientContainer, this.RecipientContainer));

                    case ResultCode.InvalidDNSyntax:
                        return(new PropertyValidationError(DirectoryStrings.ErrorDDLInvalidDNSyntax, ADDynamicGroupSchema.RecipientContainer, this.RecipientContainer));
                    }
                    return(null);
                }
            }
            else
            {
                LdapException ex2 = e as LdapException;
                if (ex2 != null && ex2.ErrorCode == 87)
                {
                    return(new PropertyValidationError(DirectoryStrings.ErrorDDLFilterError, ADDynamicGroupSchema.RecipientFilter, this.RecipientFilter));
                }
                return(null);
            }
        }
Ejemplo n.º 14
0
        private void HandleLdapException(LdapException x)
        {
            switch (x.ResultCode)
            {
            case LdapException.Ldap_TIMEOUT:
                throw new TimeoutException("Ldap lookup timed out", x);

            case LdapException.OPERATIONS_ERROR:
            case LdapException.INVALID_DN_SYNTAX:
                if (x.ResultCode == 1 && x.LdapErrorMessage.Contains("DSID-0C090627"))
                {
                    throw new DreamAbortException(DreamMessage.Forbidden(string.Format("Account '{0}' is disabled", this._username)));
                }

                throw new ArgumentException(string.Format("The search base '{0}' may have invalid format (Example: 'DC=sales,DC=acme,DC=com') or the account used for binding may be disabled. Error returned from LDAP: {1}", _config.LdapSearchBase, x.LdapErrorMessage), x);

            default:
                throw x;
            }
        }
Ejemplo n.º 15
0
        private ApiErrorItem ParseLdapException(LdapException ex)
        {
            // If the LDAP server returned an error, it will be formated
            // similar to this:
            //    "0000052D: AtrErr: DSID-03191083, #1:\n\t0: 0000052D: DSID-03191083, problem 1005 (CONSTRAINT_ATT_TYPE), data 0, Att 9005a (unicodePwd)\n\0"
            //
            // The leading number before the ':' is the Win32 API Error Code in HEX
            var m = Regex.Match(ex.LdapErrorMessage, "([0-9a-fA-F]+):");

            if (m.Success)
            {
                var errCodeString = m.Groups[1].Value;
                var errCode       = int.Parse(errCodeString, NumberStyles.HexNumber);
                var err           = Win32ErrorCode.ByCode(errCode);

                if (err != null)
                {
                    _logger.LogWarning("resolved Win32 API Error: code={0} name={1} desc={2}",
                                       err.Code, err.CodeName, err.Description);
                    return(new ApiErrorItem
                    {
                        ErrorCode = ApiErrorCode.InvalidCredentials,
                        FieldName = "currentPassword",
                        Message = $"0x{err.Code:X}:{err.CodeName}: {err.Description}",
                    });
                }

                return(new ApiErrorItem
                {
                    ErrorCode = ApiErrorCode.Generic,
                    Message = "unexpected Win32 API error; error code: " + errCodeString,
                });
            }
            return(new ApiErrorItem
            {
                ErrorCode = ApiErrorCode.Generic,
                Message = "unexpected error: " + ex.LdapErrorMessage,
            });
        }
Ejemplo n.º 16
0
        public bool Validate(string userName, string password, ContextOptions connectionMethod)
        {
            bool flag;

            if (userName == null || userName.Length != 0)
            {
                if (this.contextType == ContextType.Domain || this.contextType == ContextType.ApplicationDirectory)
                {
                    try
                    {
                        NetworkCredential networkCredential = new NetworkCredential(userName, password);
                        this.BindLdap(networkCredential, connectionMethod);
                        flag = true;
                    }
                    catch (LdapException ldapException1)
                    {
                        LdapException ldapException = ldapException1;
                        if ((long)ldapException.ErrorCode != (long)ExceptionHelper.ERROR_LOGON_FAILURE)
                        {
                            throw;
                        }
                        else
                        {
                            flag = false;
                        }
                    }
                    return(flag);
                }
                else
                {
                    return(this.BindSam(this.serverName, userName, password));
                }
            }
            else
            {
                return(false);
            }
        }
        public static TargetConnection Create(Server localHub, TargetServerConfig targetServerConfig, NetworkCredential credential, SyncTreeType type, EdgeSyncLogSession logSession)
        {
            TargetConnection result;

            try
            {
                result = new LdapTargetConnection(localHub.VersionNumber, targetServerConfig, credential, type, logSession);
            }
            catch (ExDirectoryException ex)
            {
                if (ex.InnerException is LdapException)
                {
                    LdapException ex2 = ex.InnerException as LdapException;
                    if (ex2.ErrorCode == 49)
                    {
                        string userName = credential.UserName;
                        string host     = targetServerConfig.Host;
                    }
                }
                throw;
            }
            return(result);
        }
Ejemplo n.º 18
0
        public BooleanResult AuthorizeUser(SessionProperties properties)
        {
            m_logger.Debug("LDAP Plugin Authorization");

            bool requireAuth = Settings.Store.AuthzRequireAuth;

            // Get the authz rules from registry
            List <GroupAuthzRule> rules = GroupRuleLoader.GetAuthzRules();

            if (rules.Count == 0)
            {
                throw new Exception("No authorizaition rules found.");
            }

            // Get the LDAP server object
            LdapServer serv = properties.GetTrackedSingle <LdapServer>();

            // If LDAP server object is not found, then something went wrong in authentication.
            // We allow or deny based on setting
            if (serv == null)
            {
                m_logger.ErrorFormat("AuthorizeUser: Internal error, LdapServer object not available.");

                // LdapServer is not available, allow or deny based on settings.
                return(new BooleanResult()
                {
                    Success = Settings.Store.AuthzAllowOnError,
                    Message = "LDAP server unavailable."
                });
            }

            // If we require authentication, and we failed to auth this user, then we
            // fail authorization.  Note that we do this AFTER checking the LDAP server object
            // because we may want to succeed if the authentication failed due to server
            // being unavailable.
            if (requireAuth)
            {
                PluginActivityInformation actInfo = properties.GetTrackedSingle <PluginActivityInformation>();
                try
                {
                    BooleanResult ldapResult = actInfo.GetAuthenticationResult(this.Uuid);
                    if (!ldapResult.Success)
                    {
                        m_logger.InfoFormat("Deny because LDAP auth failed, and configured to require LDAP auth.");
                        return(new BooleanResult()
                        {
                            Success = false,
                            Message = "Deny because LDAP authentication failed."
                        });
                    }
                }
                catch (KeyNotFoundException)
                {
                    // The plugin is not enabled for authentication
                    m_logger.ErrorFormat("LDAP is not enabled for authentication, and authz is configured to require authentication.");
                    return(new BooleanResult
                    {
                        Success = false,
                        Message = "Deny because LDAP auth did not execute, and configured to require LDAP auth."
                    });
                }
            }

            // Apply the authorization rules
            try
            {
                UserInformation userInfo = properties.GetTrackedSingle <UserInformation>();
                string          user     = userInfo.Username;

                // Bind for searching if we have rules to process.  If there's only one, it's the
                // default rule which doesn't require searching the LDAP tree.
                if (rules.Count > 1)
                {
                    serv.BindForSearch();
                }

                foreach (GroupAuthzRule rule in rules)
                {
                    bool inGroup = false;

                    // Don't need to check membership if the condition is "always."  This is the
                    // case for the default rule only. which is the last rule in the list.
                    if (rule.RuleCondition != GroupRule.Condition.ALWAYS)
                    {
                        inGroup = serv.MemberOfGroup(user, rule.Group);
                        m_logger.DebugFormat("User {0} {1} member of group {2}", user, inGroup ? "is" : "is not",
                                             rule.Group);
                    }

                    if (rule.RuleMatch(inGroup))
                    {
                        if (rule.AllowOnMatch)
                        {
                            return new BooleanResult()
                                   {
                                       Success = true,
                                       Message = string.Format("Allow via rule: \"{0}\"", rule.ToString())
                                   }
                        }
                        ;
                        else
                        {
                            return new BooleanResult()
                                   {
                                       Success = false,
                                       Message = string.Format("Deny via rule: \"{0}\"", rule.ToString())
                                   }
                        };
                    }
                }

                // We should never get this far because the last rule in the list should always be a match,
                // but if for some reason we do, return success.
                return(new BooleanResult()
                {
                    Success = true, Message = ""
                });
            }
            catch (Exception e)
            {
                if (e is LdapException)
                {
                    LdapException ldapEx = (e as LdapException);

                    if (ldapEx.ErrorCode == 81)
                    {
                        // Server can't be contacted, set server object to null
                        m_logger.ErrorFormat("Server unavailable: {0}, {1}", ldapEx.ServerErrorMessage, e.Message);
                        serv.Close();
                        properties.AddTrackedSingle <LdapServer>(null);
                        return(new BooleanResult
                        {
                            Success = Settings.Store.AuthzAllowOnError,
                            Message = "Failed to contact LDAP server."
                        });
                    }
                    else if (ldapEx.ErrorCode == 49)
                    {
                        // This is invalid credentials, return false, but server object should remain connected
                        m_logger.ErrorFormat("LDAP bind failed: invalid credentials.");
                        return(new BooleanResult
                        {
                            Success = false,
                            Message = "Authorization via LDAP failed. Invalid credentials."
                        });
                    }
                }

                // Unexpected error, let the PluginDriver catch
                m_logger.ErrorFormat("Error during authorization: {0}", e);
                throw;
            }
        }
        // Token: 0x060002A1 RID: 673 RVA: 0x0000ECEC File Offset: 0x0000CEEC
        public static Exception DirectoryTracerCallback(string exceptionType)
        {
            Exception result = null;

            if (!string.IsNullOrEmpty(exceptionType))
            {
                if (exceptionType.Contains("_") && !string.IsNullOrEmpty(exceptionType.Substring(exceptionType.IndexOf("_") + 1)))
                {
                    string strA      = exceptionType.Substring(0, exceptionType.IndexOf("_"));
                    int    errorCode = int.Parse(exceptionType.Substring(exceptionType.IndexOf("_") + 1));
                    if (string.Compare(strA, "LdapException", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        result = new LdapException(errorCode);
                    }
                }
                else
                {
                    if (exceptionType == "ADTransientException-ExceptionNativeErrorWhenLookingForServersInDomain")
                    {
                        throw new ADTransientException(DirectoryStrings.ExceptionNativeErrorWhenLookingForServersInDomain(-1, "Fault Injection domain", "Fault injection Error"));
                    }
                    if (exceptionType == "ThreadAbortException")
                    {
                        Thread.CurrentThread.Abort();
                    }
                    else
                    {
                        if (exceptionType == "MServTransientException")
                        {
                            throw new MServTransientException(DirectoryStrings.TransientMservError("Fault injection MSERV transient error"));
                        }
                        if (exceptionType == "MServPermanentException")
                        {
                            throw new MServPermanentException(DirectoryStrings.PermanentMservError("Fault injection MSERV permanent error"));
                        }
                        if (exceptionType == "GlsTransientException")
                        {
                            throw new EndpointNotFoundException("Fault injection GLS transient error");
                        }
                        if (exceptionType == "GlsPermanentException")
                        {
                            throw new QuotaExceededException("Fault injection GLS permanent error");
                        }
                        if (exceptionType == "GlsDelay")
                        {
                            Thread.Sleep(4000);
                            throw new TimeoutException("Test timeout exception");
                        }
                        if (exceptionType == "GlsAsyncTransientException")
                        {
                            throw new EndpointNotFoundException("Fault injection GLS Async transient error");
                        }
                        if (exceptionType == "GlsAsyncPermanentException")
                        {
                            throw new QuotaExceededException("Fault injection GLS Async permanent error");
                        }
                        if (exceptionType == "GlsAsyncDelay")
                        {
                            Thread.Sleep(4000);
                            throw new TimeoutException("Async test timeout exception");
                        }
                        if (exceptionType == "DirectoryExceptionNotification")
                        {
                            throw new LdapException(91);
                        }
                    }
                }
            }
            return(result);
        }
Ejemplo n.º 20
0
        internal void ReadServerConfig(string serverName, ref ServerProperties properties)
        {
            string[] strArrays = new string[5];
            strArrays[0] = "msDS-PortSSL";
            strArrays[1] = "msDS-PortLDAP";
            strArrays[2] = "domainControllerFunctionality";
            strArrays[3] = "dnsHostName";
            strArrays[4] = "supportedCapabilities";
            string[]       strArrays1     = strArrays;
            LdapConnection ldapConnection = null;

            using (ldapConnection)
            {
                bool flag = (this.options & ContextOptions.SecureSocketLayer) > 0;
                if (!flag || this.contextType != ContextType.Domain)
                {
                    ldapConnection = new LdapConnection(serverName);
                }
                else
                {
                    LdapDirectoryIdentifier ldapDirectoryIdentifier = new LdapDirectoryIdentifier(serverName, LdapConstants.LDAP_SSL_PORT);
                    ldapConnection = new LdapConnection(ldapDirectoryIdentifier);
                }
                ldapConnection.AutoBind = false;
                ldapConnection.SessionOptions.SecureSocketLayer = flag;
                string         str            = null;
                string         str1           = "(objectClass=*)";
                SearchResponse searchResponse = null;
                SearchRequest  searchRequest  = new SearchRequest(str, str1, SearchScope.Base, strArrays1);
                try
                {
                    searchResponse = (SearchResponse)ldapConnection.SendRequest(searchRequest);
                }
                catch (LdapException ldapException1)
                {
                    LdapException ldapException = ldapException1;
                    throw new PrincipalServerDownException(StringResources.ServerDown, ldapException);
                }
                properties.dnsHostName         = (string)searchResponse.Entries[0].Attributes["dnsHostName"][0];
                properties.SupportCapabilities = new string[searchResponse.Entries[0].Attributes["supportedCapabilities"].Count];
                for (int i = 0; i < searchResponse.Entries[0].Attributes["supportedCapabilities"].Count; i++)
                {
                    properties.SupportCapabilities[i] = (string)searchResponse.Entries[0].Attributes["supportedCapabilities"][i];
                }
                string[] supportCapabilities = properties.SupportCapabilities;
                for (int j = 0; j < (int)supportCapabilities.Length; j++)
                {
                    string str2 = supportCapabilities[j];
                    if ("1.2.840.113556.1.4.1851" != str2)
                    {
                        if ("1.2.840.113556.1.4.800" == str2)
                        {
                            properties.contextType = ContextType.Domain;
                        }
                    }
                    else
                    {
                        properties.contextType = ContextType.ApplicationDirectory;
                    }
                }
                if (!searchResponse.Entries[0].Attributes.Contains("domainControllerFunctionality"))
                {
                    properties.OsVersion = DomainControllerMode.Win2k;
                }
                else
                {
                    properties.OsVersion = (DomainControllerMode)Convert.ToInt32(searchResponse.Entries[0].Attributes["domainControllerFunctionality"][0], CultureInfo.InvariantCulture);
                }
                if (properties.contextType == ContextType.ApplicationDirectory)
                {
                    if (searchResponse.Entries[0].Attributes.Contains("msDS-PortSSL"))
                    {
                        properties.portSSL = Convert.ToInt32(searchResponse.Entries[0].Attributes["msDS-PortSSL"][0]);
                    }
                    if (searchResponse.Entries[0].Attributes.Contains("msDS-PortLDAP"))
                    {
                        properties.portLDAP = Convert.ToInt32(searchResponse.Entries[0].Attributes["msDS-PortLDAP"][0]);
                    }
                }
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Connects to LDAP Server according to user's credentials.
        /// (These credentials have been stored in the SessionProperties object
        /// during the Gateway stage.)
        /// Retrieves the name of the script file on the user's LDAP account.
        /// </summary>
        private void LdapPart(SessionChangeDescription changeDescription, SessionProperties properties)
        {
            // initializes and sets up a new Ldap connection
            LdapInitialization(properties);
            // Get the LdapServer object from the session properties (created in LdapInitialization)
            LdapServer server = properties.GetTrackedSingle <LdapServer>();

            if (server == null)
            {
                pluginImpl_logger.ErrorFormat("Internal error: LdapServer object not available.");
                return;
            }

            try
            {
                pluginImpl_logger.DebugFormat("AuthenticateUser({0})", properties.Id.ToString());

                // retrieving user's information stored during Gateway stage
                Shared.Types.UserInformation userInfo = properties.GetTrackedSingle <Shared.Types.UserInformation>();
                string userLogin    = properties.GetTracked <string>("UserLogin");
                string userPassword = properties.GetTracked <string>("UserPassword");
                pluginImpl_logger.DebugFormat("Received username: {0}", userLogin);

                // Authenticate the login
                pluginImpl_logger.DebugFormat("Attempting authentication for {0}", userLogin);
                BooleanResult authenticateBool = server.Authenticate(userLogin, userPassword);

                if (!authenticateBool.Success) // authentication and attribute value retrieving didn't work
                {
                    pluginImpl_logger.ErrorFormat("LDAP Authentication failed. {0}", authenticateBool.Message);
                    return;
                }

                // retrieves the script name from Ldap
                this.scriptName = server.GetScriptName();
                pluginImpl_logger.DebugFormat("Name of the script file:  {0}", this.scriptName);

                // cleans up any resources held by the plugin
                LdapEnd(properties);
            }
            catch (Exception e)
            {
                if (e is LdapException)
                {
                    LdapException ldapEx = (e as LdapException);

                    if (ldapEx.ErrorCode == 81)
                    {
                        // Server can't be contacted, set server object to null
                        pluginImpl_logger.ErrorFormat("Server unavailable: {0}, {1}", ldapEx.ServerErrorMessage, e.Message);
                        server.Close();
                        properties.AddTrackedSingle <LdapServer>(null);
                        return;
                    }
                }

                // This is an unexpected error, so set LdapServer object to null, because
                // subsequent stages shouldn't use it, and this indicates to later stages
                // that this stage failed unexpectedly.
                server.Close();
                properties.AddTrackedSingle <LdapServer>(null);
                pluginImpl_logger.ErrorFormat("Exception in LDAP authentication: {0}", e);
                throw;  // Allow pGina service to catch and handle exception
            }
        }
        public static string GetUnderlineLdapExceptionCode(this LdapException e)
        {
            var errorCode = new Regex(@"(?<=data\s)\S{3}", RegexOptions.IgnoreCase | RegexOptions.Multiline).Match(e.LdapErrorMessage).Value;

            return(errorMessages.ContainsKey(errorCode) ? errorMessages[errorCode] : "Bilinmeyen Bir Hata Oluştu. Lütfen Sistem Yöneticinize Başvurun.");
        }
Ejemplo n.º 23
0
 protected override void OnError(Guid clientId, LdapException exception)
 {
     Console.WriteLine($"{clientId} E {exception.Message} ({exception.ResultCode})");
     base.OnError(clientId, exception);
 }
 public DirectoryExceptionEventArgs(LdapMessage message, LdapException ldapException)
     : base(message)
 {
     ldap_exception_object = ldapException;
 }
Ejemplo n.º 25
0
        public bool Validate(string userName, string password)
        {
            bool flag;
            NetworkCredential networkCredential = new NetworkCredential(userName, password);

            if (userName == null || userName.Length != 0)
            {
                if (this.contextType == ContextType.Domain || this.contextType == ContextType.ApplicationDirectory)
                {
                    try
                    {
                        if (this.lastBindMethod != CredentialValidator.AuthMethod.Simple || !this.fastConcurrentSupported && this.contextType != ContextType.ApplicationDirectory)
                        {
                            try
                            {
                                this.BindLdap(networkCredential, ContextOptions.Negotiate | ContextOptions.Signing | ContextOptions.Sealing);
                                this.lastBindMethod = CredentialValidator.AuthMethod.Negotiate;
                                flag = true;
                                return(flag);
                            }
                            catch (LdapException ldapException)
                            {
                            }
                            this.BindLdap(networkCredential, ContextOptions.SimpleBind | ContextOptions.SecureSocketLayer);
                            this.lastBindMethod = CredentialValidator.AuthMethod.Simple;
                            flag = true;
                        }
                        else
                        {
                            try
                            {
                                this.BindLdap(networkCredential, ContextOptions.SimpleBind | ContextOptions.SecureSocketLayer);
                                this.lastBindMethod = CredentialValidator.AuthMethod.Simple;
                                flag = true;
                                return(flag);
                            }
                            catch (LdapException ldapException1)
                            {
                            }
                            this.BindLdap(networkCredential, ContextOptions.Negotiate | ContextOptions.Signing | ContextOptions.Sealing);
                            this.lastBindMethod = CredentialValidator.AuthMethod.Negotiate;
                            flag = true;
                        }
                    }
                    catch (LdapException ldapException3)
                    {
                        LdapException ldapException2 = ldapException3;
                        if ((long)ldapException2.ErrorCode != (long)ExceptionHelper.ERROR_LOGON_FAILURE)
                        {
                            throw;
                        }
                        else
                        {
                            flag = false;
                        }
                    }
                    return(flag);
                }
                else
                {
                    return(this.BindSam(this.serverName, userName, password));
                }
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 26
0
 public DirectoryExceptionEventArgs(LdapMessage message, LdapException ldapException)
     : base(message)
 {
     ldap_exception_object = ldapException;
 }
Ejemplo n.º 27
0
        public BooleanResult AuthorizeUser(SessionProperties properties)
        {
            ////m_logger.Debug("LDAP Plugin Authorization");

            bool requireAuth = Settings.Store.AuthzRequireAuth;

            // Get the authz rules from registry
            List <GroupAuthzRule> rules = GroupRuleLoader.GetAuthzRules();

            // Get the LDAP server object
            LdapServer serv = properties.GetTrackedSingle <LdapServer>();

            // If LDAP server object is not found, then something went wrong in authentication.
            // We allow or deny based on setting
            if (serv == null)
            {
                ////m_logger.ErrorFormat("AuthorizeUser: Internal error, LdapServer object not available.");

                // LdapServer is not available, allow or deny based on settings.
                return(new BooleanResult()
                {
                    Success = Settings.Store.AuthzAllowOnError,
                    Message = "LDAP server unavailable."
                });
            }

            // If we require authentication, and we failed to auth this user, then we
            // fail authorization.  Note that we do this AFTER checking the LDAP server object
            // because we may want to succeed if the authentication failed due to server
            // being unavailable.
            PluginActivityInformation actInfo = properties.GetTrackedSingle <PluginActivityInformation>();

            if (requireAuth && !WeAuthedThisUser(actInfo))
            {
                ////m_logger.InfoFormat("Deny because LDAP auth failed, and configured to require LDAP auth.");
                return(new BooleanResult()
                {
                    Success = false,
                    Message = "Deny because LDAP authentication failed, or did not execute."
                });
            }

            // Apply the authorization rules
            try
            {
                UserInformation userInfo = properties.GetTrackedSingle <UserInformation>();

                // Bind for searching if we have rules to process.  If there's only one, it's the
                // default rule which doesn't require searching the LDAP tree.
                if (rules.Count > 0)
                {
                    this.BindForAuthzOrGatewaySearch(serv);
                }

                foreach (GroupAuthzRule rule in rules)
                {
                    bool   inGroup = false;
                    string path    = rule.path.Replace("%u", userInfo.Username);
                    string filter  = rule.filter.Replace("%u", userInfo.Username);
                    inGroup = serv.GetUserAttribValue(path, filter, rule.SearchScope, new string[] { "dn" }).Count > 0;
                    ////m_logger.DebugFormat("User {0} {1} {2} {3}", userInfo.Username, inGroup ? "is" : "is not", filter, path);

                    if (rule.RuleMatch(inGroup))
                    {
                        if (rule.AllowOnMatch)
                        {
                            return new BooleanResult()
                                   {
                                       Success = true,
                                       Message = string.Format("Allow via rule: \"{0}\"", rule.ToString())
                                   }
                        }
                        ;
                        else
                        {
                            return new BooleanResult()
                                   {
                                       Success = false,
                                       Message = string.Format("Deny via rule: \"{0}\"", rule.ToString())
                                   }
                        };
                    }
                }

                // If there is no matching rule use default. allow or deny
                if ((bool)Settings.Store.AuthzDefault)
                {
                    return new BooleanResult()
                           {
                               Success = true, Message = ""
                           }
                }
                ;
                else
                {
                    return new BooleanResult()
                           {
                               Success = false, Message = String.Format("You are not allowed to login! No matching rule found! Default rule:{0}", (bool)Settings.Store.AuthzDefault ? "Allow" : "Deny")
                           }
                };
            }
            catch (Exception e)
            {
                if (e is LdapException)
                {
                    LdapException ldapEx = (e as LdapException);

                    if (ldapEx.ErrorCode == 81)
                    {
                        // Server can't be contacted, set server object to null
                        ////m_logger.ErrorFormat("Server unavailable: {0}, {1}", ldapEx.ServerErrorMessage, e.Message);
                        serv.Close();
                        properties.AddTrackedSingle <LdapServer>(null);
                        return(new BooleanResult
                        {
                            Success = Settings.Store.AuthzAllowOnError,
                            Message = "Failed to contact LDAP server."
                        });
                    }
                    else if (ldapEx.ErrorCode == 49)
                    {
                        // This is invalid credentials, return false, but server object should remain connected
                        ////m_logger.ErrorFormat("LDAP bind failed: invalid credentials.");
                        return(new BooleanResult
                        {
                            Success = false,
                            Message = "Authorization via LDAP failed. Invalid credentials."
                        });
                    }
                }

                // Unexpected error, let the PluginDriver catch
                ////m_logger.ErrorFormat("Error during authorization: {0}", e);
                throw;
            }
        }