Пример #1
0
        private void StoreSettings()
        {
            Settings.Store.LdapHost       = Regex.Split(ldapHostTextBox.Text.Trim(), @"\s+");
            Settings.Store.LdapPort       = Convert.ToInt32(ldapPortTextBox.Text.Trim());
            Settings.Store.LdapTimeout    = Convert.ToInt32(timeoutTextBox.Text.Trim());
            Settings.Store.UseSsl         = (useSslCheckBox.CheckState == CheckState.Checked);
            Settings.Store.RequireCert    = (validateServerCertCheckBox.CheckState == CheckState.Checked);
            Settings.Store.ServerCertFile = sslCertFileTextBox.Text.Trim();
            Settings.Store.SearchDN       = searchDnTextBox.Text.Trim();
            Settings.Store.SetEncryptedSetting("SearchPW", searchPassTextBox.Text);
            Settings.Store.GroupDnPattern    = this.groupDNPattern.Text.Trim();
            Settings.Store.GroupMemberAttrib = this.groupMemberAttrTB.Text.Trim();
            Settings.Store.Dereference       = this.DereferenceComboBox.SelectedIndex;

            // Authentication
            Settings.Store.AllowEmptyPasswords = this.allowEmptyPwCB.Checked;
            Settings.Store.DnPattern           = dnPatternTextBox.Text.Trim();
            Settings.Store.DoSearch            = (searchForDnCheckBox.CheckState == CheckState.Checked);
            Settings.Store.SearchFilter        = searchFilterTextBox.Text.Trim();
            Settings.Store.SearchContexts      = Regex.Split(searchContextsTextBox.Text.Trim(), @"\s*\r?\n\s*");

            // Authorization
            Settings.Store.AuthzRequireAuth  = this.authzRequireAuthCB.Checked;
            Settings.Store.AuthzAllowOnError = this.authzAllowOnErrorCB.Checked;
            List <GroupAuthzRule> lst = new List <GroupAuthzRule>();

            foreach (Object item in this.authzRulesListBox.Items)
            {
                lst.Add(item as GroupAuthzRule);
                m_logger.DebugFormat("Saving rule: {0}", item);
            }
            // Add the default as the last rule in the list
            lst.Add(new GroupAuthzRule(this.authzDefaultAllowRB.Checked));

            GroupRuleLoader.SaveAuthzRules(lst);

            // Gateway
            List <GroupGatewayRule> gwList = new List <GroupGatewayRule>();

            foreach (Object item in this.gatewayRulesListBox.Items)
            {
                gwList.Add(item as GroupGatewayRule);
                m_logger.DebugFormat("Saving rule: {0}", item);
            }
            GroupRuleLoader.SaveGatewayRules(gwList);
        }
Пример #2
0
        public BooleanResult AuthenticatedUserGateway(SessionProperties properties)
        {
            m_logger.Debug("LDAP Plugin Gateway");
            List <string> addedGroups = new List <string>();

            LdapServer serv = properties.GetTrackedSingle <LdapServer>();

            // If the server is unavailable, we go ahead and succeed anyway.
            if (serv == null)
            {
                m_logger.ErrorFormat("AuthenticatedUserGateway: Internal error, LdapServer object not available.");
                return(new BooleanResult()
                {
                    Success = true,
                    Message = "LDAP server not available"
                });
            }

            try
            {
                UserInformation userInfo = properties.GetTrackedSingle <UserInformation>();
                string          user     = userInfo.Username;

                List <GroupGatewayRule> rules = GroupRuleLoader.GetGatewayRules();
                bool boundToServ = false;
                foreach (GroupGatewayRule rule in rules)
                {
                    bool inGroup = false;

                    // Don't need to check for group membership if the rule is to be always applied.
                    if (rule.RuleCondition != GroupRule.Condition.ALWAYS)
                    {
                        // If we haven't bound to server yet, do so.
                        if (!boundToServ)
                        {
                            serv.BindForSearch();

                            boundToServ = true;
                        }

                        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))
                    {
                        m_logger.InfoFormat("Adding user {0} to local group {1}, due to rule \"{2}\"",
                                            user, rule.LocalGroup, rule.ToString());
                        addedGroups.Add(rule.LocalGroup);
                        userInfo.AddGroup(new GroupInformation()
                        {
                            Name = rule.LocalGroup
                        });
                    }
                }
            }
            catch (Exception e)
            {
                m_logger.ErrorFormat("Error during gateway: {0}", e);

                // Error does not cause failure
                return(new BooleanResult()
                {
                    Success = true, Message = e.Message
                });
            }

            string message = "";

            if (addedGroups.Count > 0)
            {
                message = string.Format("Added to groups: {0}", string.Join(", ", addedGroups));
            }
            else
            {
                message = "No groups added.";
            }

            return(new BooleanResult()
            {
                Success = true, Message = message
            });
        }
Пример #3
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;
            }
        }
Пример #4
0
        private void LoadSettings()
        {
            string[] ldapHosts = Settings.Store.LdapHost;
            string   hosts     = "";

            for (int i = 0; i < ldapHosts.Count(); i++)
            {
                string host = ldapHosts[i];
                if (i < ldapHosts.Count() - 1)
                {
                    hosts += host + " ";
                }
                else
                {
                    hosts += host;
                }
            }
            ldapHostTextBox.Text = hosts;

            int port = Settings.Store.LdapPort;

            ldapPortTextBox.Text = Convert.ToString(port);

            int timeout = Settings.Store.LdapTimeout;

            timeoutTextBox.Text = Convert.ToString(timeout);

            bool useSsl = Settings.Store.UseSsl;

            useSslCheckBox.CheckState = useSsl ? CheckState.Checked : CheckState.Unchecked;

            bool useTls = Settings.Store.UseTls;

            useTlsCheckBox.CheckState = useTls ? CheckState.Checked : CheckState.Unchecked;

            bool reqCert = Settings.Store.RequireCert;

            validateServerCertCheckBox.CheckState = reqCert ? CheckState.Checked : CheckState.Unchecked;

            string serverCertFile = Settings.Store.ServerCertFile;

            sslCertFileTextBox.Text = serverCertFile;

            string searchDn = Settings.Store.SearchDN;

            searchDnTextBox.Text = searchDn;

            string searchPw = Settings.Store.GetEncryptedSetting("SearchPW");

            searchPassTextBox.Text = searchPw;

            // Authentication tab
            bool allowEmpty = Settings.Store.AllowEmptyPasswords;

            this.allowEmptyPwCB.Checked = allowEmpty;

            string dnPattern = Settings.Store.DnPattern;

            dnPatternTextBox.Text = dnPattern;

            bool doSearch = Settings.Store.DoSearch;

            searchForDnCheckBox.CheckState = doSearch ? CheckState.Checked : CheckState.Unchecked;

            string filter = Settings.Store.SearchFilter;

            searchFilterTextBox.Text = filter;

            bool useAuth = Settings.Store.UseAuthBindForAuthzAndGateway;

            useAuthBindForAuthzAndGatewayCb.Checked = useAuth;

            string[] searchContexts = Settings.Store.SearchContexts;
            string   ctxs           = "";

            for (int i = 0; i < searchContexts.Count(); i++)
            {
                string ctx = searchContexts[i];
                if (i < searchContexts.Count() - 1)
                {
                    ctxs += ctx + "\r\n";
                }
                else
                {
                    ctxs += ctx;
                }
            }
            searchContextsTextBox.Text = ctxs;

            // AttribConverter Grid
            string[] AttribConv = Settings.Store.AttribConv;
            Column1.DataSource        = AttribConvert.Attribs.ToArray();
            dataGridView1.ColumnCount = 2;
            for (int x = 0; x < AttribConv.Count(); x++)
            {
                string[] split = AttribConv[x].Split('\t');
                if (split.Count() == 2)
                {
                    split[0] = split[0].Trim();
                    split[1] = split[1].Trim();
                    if (!String.IsNullOrEmpty(split[0]) && !String.IsNullOrEmpty(split[1]))
                    {
                        if (AttribConvert.Attribs.Contains(split[0]))
                        //if (Array.Exists(WinValues(), element => element == split[0]))
                        {
                            int index = AttribConvert.Attribs.IndexOf(split[0]);
                            //int index = Array.FindIndex(WinValues(), item => item == split[0]);

                            DataGridViewRow          row        = new DataGridViewRow();
                            DataGridViewComboBoxCell CellSample = new DataGridViewComboBoxCell();
                            CellSample.DataSource = AttribConvert.Attribs.ToArray(); // list of the string items that I want to insert in ComboBox.
                            CellSample.Value      = AttribConvert.Attribs[index];    // default value for the ComboBox
                            row.Cells.Add(CellSample);

                            row.Cells.Add(new DataGridViewTextBoxCell()
                            {
                                Value = split[1]
                            });
                            dataGridView1.Rows.Add(row);
                        }
                    }
                }
            }

            /////////////// Authorization tab /////////////////
            this.authzRuleMemberComboBox.SelectedIndex = 0;
            this.authzRuleActionComboBox.SelectedIndex = 0;
            this.authzRuleScope.SelectedIndex          = 0;
            this.authzDefaultAllowRB.Checked           = Settings.Store.AuthzDefault;
            this.authzDefaultDenyRB.Checked            = !(bool)Settings.Store.AuthzDefault;
            this.authzRequireAuthCB.Checked            = Settings.Store.AuthzRequireAuth;
            this.authzAllowOnErrorCB.Checked           = Settings.Store.AuthzAllowOnError;

            List <GroupAuthzRule> lst = GroupRuleLoader.GetAuthzRules();

            foreach (GroupAuthzRule rule in lst)
            {
                this.authzRulesListBox.Items.Add(rule);
            }

            ///////////////// Gateway tab /////////////////
            this.gatewayRuleGroupMemberCB.SelectedIndex = 0;
            this.gatewayRuleScope.SelectedIndex         = 0;

            List <GroupGatewayRule> gwLst = GroupRuleLoader.GetGatewayRules();

            foreach (GroupGatewayRule rule in gwLst)
            {
                this.gatewayRulesListBox.Items.Add(rule);
            }

            ////////////// Change Password tab ///////////////
            List <AttributeEntry> attribs = CPAttributeSettings.Load();

            foreach (AttributeEntry entry in attribs)
            {
                this.passwordAttributesDGV.Rows.Add(entry.Name, entry.Method);
            }
        }
Пример #5
0
        private void StoreSettings()
        {
            Settings.Store.LdapHost       = Regex.Split(ldapHostTextBox.Text.Trim(), @"\s+");
            Settings.Store.LdapPort       = Convert.ToInt32(ldapPortTextBox.Text.Trim());
            Settings.Store.LdapTimeout    = Convert.ToInt32(timeoutTextBox.Text.Trim());
            Settings.Store.UseSsl         = (useSslCheckBox.CheckState == CheckState.Checked);
            Settings.Store.UseTls         = (useTlsCheckBox.CheckState == CheckState.Checked);
            Settings.Store.RequireCert    = (validateServerCertCheckBox.CheckState == CheckState.Checked);
            Settings.Store.ServerCertFile = sslCertFileTextBox.Text.Trim();
            Settings.Store.UseAuthBindForAuthzAndGateway = (useAuthBindForAuthzAndGatewayCb.CheckState == CheckState.Checked);
            Settings.Store.SearchDN = searchDnTextBox.Text.Trim();
            Settings.Store.SetEncryptedSetting("SearchPW", searchPassTextBox.Text);

            // Authentication
            Settings.Store.AllowEmptyPasswords = this.allowEmptyPwCB.Checked;
            Settings.Store.DnPattern           = dnPatternTextBox.Text.Trim();
            Settings.Store.DoSearch            = (searchForDnCheckBox.CheckState == CheckState.Checked);
            Settings.Store.SearchFilter        = searchFilterTextBox.Text.Trim();
            Settings.Store.SearchContexts      = Regex.Split(searchContextsTextBox.Text.Trim(), @"\s*\r?\n\s*");
            Settings.Store.AuthzDefault        = this.authzDefaultAllowRB.Checked;

            List <string> AttribConv = new List <string>();

            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (row.Cells[0].Value != null && row.Cells[1].Value != null)
                {
                    AttribConv.Add(row.Cells[0].Value.ToString() + "\t" + row.Cells[1].Value.ToString().Trim());
                }
            }
            if (AttribConv.Count > 0)
            {
                Settings.Store.AttribConv = AttribConv.ToArray();
            }
            else
            {
                Settings.Store.AttribConv = new string[] { }
            };

            // Authorization
            Settings.Store.AuthzRequireAuth  = this.authzRequireAuthCB.Checked;
            Settings.Store.AuthzAllowOnError = this.authzAllowOnErrorCB.Checked;
            Settings.Store.AuthzDefault      = this.authzDefaultAllowRB.Checked;
            List <GroupAuthzRule> lst = new List <GroupAuthzRule>();

            foreach (Object item in this.authzRulesListBox.Items)
            {
                lst.Add(item as GroupAuthzRule);
                m_logger.DebugFormat("Saving rule: {0}", item);
            }
            string SaveAuthzRules_ret = GroupRuleLoader.SaveAuthzRules(lst);

            if (!string.IsNullOrEmpty(SaveAuthzRules_ret))
            {
                MessageBox.Show("There was an error in saving your authorization rules.\n" + SaveAuthzRules_ret);
            }

            // Gateway
            List <GroupGatewayRule> gwList = new List <GroupGatewayRule>();

            foreach (Object item in this.gatewayRulesListBox.Items)
            {
                gwList.Add(item as GroupGatewayRule);
                m_logger.DebugFormat("Saving rule: {0}", item);
            }
            string SaveGatewayRules_ret = GroupRuleLoader.SaveGatewayRules(gwList);

            if (!string.IsNullOrEmpty(SaveGatewayRules_ret))
            {
                MessageBox.Show("There was an error in saving your gateway rules.\n" + SaveGatewayRules_ret);
            }

            // Change Password
            List <AttributeEntry> entries = new List <AttributeEntry>();

            foreach (DataGridViewRow row in this.passwordAttributesDGV.Rows)
            {
                if (row.Cells[0].Value != null && row.Cells[1].Value != null)
                {
                    string attribName = row.Cells[0].Value.ToString();
                    if (!string.IsNullOrEmpty(attribName))
                    {
                        AttributeEntry entry = new AttributeEntry
                        {
                            Name   = attribName,
                            Method = (Methods)(row.Cells[1].Value)
                        };
                        entries.Add(entry);
                    }
                }
            }
            CPAttributeSettings.Save(entries);
        }
Пример #6
0
        public BooleanResult AuthenticatedUserGateway(SessionProperties properties)
        {
            ////m_logger.Debug("LDAP Plugin Gateway");
            List <string> addedGroups = new List <string>();

            LdapServer serv = properties.GetTrackedSingle <LdapServer>();

            // If the server is unavailable, we go ahead and succeed anyway.
            if (serv == null)
            {
                ////m_logger.ErrorFormat("AuthenticatedUserGateway: Internal error, LdapServer object not available.");
                return(new BooleanResult()
                {
                    Success = true,
                    Message = "LDAP server not available"
                });
            }

            try
            {
                UserInformation userInfo = properties.GetTrackedSingle <UserInformation>();

                List <GroupGatewayRule> rules = GroupRuleLoader.GetGatewayRules();
                bool boundToServ = false;
                foreach (GroupGatewayRule rule in rules)
                {
                    bool inGroup = false;

                    // If we haven't bound to server yet, do so.
                    if (!boundToServ)
                    {
                        this.BindForAuthzOrGatewaySearch(serv);
                        boundToServ = true;
                    }

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

                    if (rule.RuleMatch(inGroup))
                    {
                        ////m_logger.InfoFormat("Adding user {0} to local group {1}, due to rule \"{2}\"", userInfo.Username, rule.LocalGroup, rule.ToString());
                        addedGroups.Add(rule.LocalGroup);
                        userInfo.AddGroup(new GroupInformation()
                        {
                            Name = rule.LocalGroup
                        });
                    }
                }
            }
            catch (Exception e)
            {
                ////m_logger.ErrorFormat("Error during gateway: {0}", e);

                // Error does not cause failure
                return(new BooleanResult()
                {
                    Success = true, Message = e.Message
                });
            }

            string message = "";

            if (addedGroups.Count > 0)
            {
                message = string.Format("Added to groups: {0}", string.Join(", ", addedGroups));
            }
            else
            {
                message = "No groups added.";
            }

            return(new BooleanResult()
            {
                Success = true, Message = message
            });
        }
Пример #7
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;
            }
        }
Пример #8
0
        private void StoreSettings()
        {
            Settings.Store.LdapHost         = Regex.Split(ldapHostTextBox.Text.Trim(), @"\s+");
            Settings.Store.LdapPort         = Convert.ToInt32(ldapPortTextBox.Text.Trim());
            Settings.Store.LdapTimeout      = Convert.ToInt32(timeoutTextBox.Text.Trim());
            Settings.Store.EncryptionMethod = (int)(GetEncryptionMethodSelection());
            Settings.Store.RequireCert      = (validateServerCertCheckBox.CheckState == CheckState.Checked);
            Settings.Store.ServerCertFile   = sslCertFileTextBox.Text.Trim();
            Settings.Store.SearchDN         = searchDnTextBox.Text.Trim();
            Settings.Store.SetEncryptedSetting("SearchPW", searchPassTextBox.Text);
            Settings.Store.GroupDnPattern                = this.groupDNPattern.Text.Trim();
            Settings.Store.GroupMemberAttrib             = this.groupMemberAttrTB.Text.Trim();
            Settings.Store.GroupGidAttrib                = this.groupGidAttr.Text.Trim();
            Settings.Store.GroupGidAttribIU              = this.groupGidAttrIU.Text.Trim();
            Settings.Store.Dereference                   = this.DereferenceComboBox.SelectedIndex;
            Settings.Store.UseAuthBindForAuthzAndGateway = this.m_useAuthBindForAuthzAndGatewayCb.Checked;

            // Authentication
            Settings.Store.AllowEmptyPasswords = this.allowEmptyPwCB.Checked;
            Settings.Store.DnPattern           = dnPatternTextBox.Text.Trim();
            Settings.Store.DoSearch            = (searchForDnCheckBox.CheckState == CheckState.Checked);
            Settings.Store.SearchFilter        = searchFilterTextBox.Text.Trim();
            Settings.Store.SearchContexts      = Regex.Split(searchContextsTextBox.Text.Trim(), @"\s*\r?\n\s*");

            // Authorization
            Settings.Store.AuthzRequireAuth     = this.authzRequireAuthCB.Checked;
            Settings.Store.AuthzAllowOnError    = this.authzAllowOnErrorCB.Checked;
            Settings.Store.AuthzApplyToAllUsers = this.authzApplyToAllUsersCB.Checked;
            List <GroupAuthzRule> lst = new List <GroupAuthzRule>();

            foreach (Object item in this.authzRulesListBox.Items)
            {
                lst.Add(item as GroupAuthzRule);
                m_logger.DebugFormat("Saving rule: {0}", item);
            }
            // Add the default as the last rule in the list
            lst.Add(new GroupAuthzRule(this.authzDefaultAllowRB.Checked));

            GroupRuleLoader.SaveAuthzRules(lst);

            // Gateway
            List <GroupGatewayRule> gwList = new List <GroupGatewayRule>();

            foreach (Object item in this.gatewayRulesListBox.Items)
            {
                gwList.Add(item as GroupGatewayRule);
                m_logger.DebugFormat("Saving rule: {0}", item);
            }
            GroupRuleLoader.SaveGatewayRules(gwList);

            // Change Password
            List <PasswordAttributeEntry> entries = new List <PasswordAttributeEntry>();

            foreach (DataGridViewRow row in this.passwordAttributesDGV.Rows)
            {
                if (row.Cells[0].Value != null && row.Cells[1].Value != null)
                {
                    string attribName = row.Cells[0].Value.ToString();
                    if (!string.IsNullOrEmpty(attribName))
                    {
                        PasswordAttributeEntry entry = new PasswordAttributeEntry
                        {
                            Name   = attribName,
                            Method = (HashMethod)(row.Cells[1].Value)
                        };
                        entries.Add(entry);
                    }
                }
            }
            CPAttributeSettings.Save(entries);

            // Login Script SFTP
            Settings.Store.SFTPServerURL     = txt_script_serverurl.Text;
            Settings.Store.SFTPUser          = txt_script_user.Text;
            Settings.Store.SFTPPassword      = txt_script_password.Text;
            Settings.Store.SFTPFingerprint   = txt_script_fingerprint.Text;
            Settings.Store.SFTPScriptPath    = txt_script_path.Text;
            Settings.Store.SFTPScriptPath2   = txt_script_path_2.Text;
            Settings.Store.SFTPGroupListPath = txt_script_group_list_path.Text;
            Settings.Store.CMDLoginScript    = txt_script_cmd_login.Text;
            Settings.Store.CMDLogoffScript   = txt_script_cmd_logoff.Text;
        }
Пример #9
0
        private void LoadSettings()
        {
            string[] ldapHosts = Settings.Store.LdapHost;
            string   hosts     = "";

            for (int i = 0; i < ldapHosts.Count(); i++)
            {
                string host = ldapHosts[i];
                if (i < ldapHosts.Count() - 1)
                {
                    hosts += host + " ";
                }
                else
                {
                    hosts += host;
                }
            }
            ldapHostTextBox.Text = hosts;

            int port = Settings.Store.LdapPort;

            ldapPortTextBox.Text = Convert.ToString(port);

            int timeout = Settings.Store.LdapTimeout;

            timeoutTextBox.Text = Convert.ToString(timeout);

            int encryptionMethod = Settings.Store.EncryptionMethod;

            m_encryptionMethodCb.SelectedIndex = encryptionMethod;

            bool reqCert = Settings.Store.RequireCert;

            validateServerCertCheckBox.CheckState = reqCert ? CheckState.Checked : CheckState.Unchecked;

            string serverCertFile = Settings.Store.ServerCertFile;

            sslCertFileTextBox.Text = serverCertFile;

            string searchDn = Settings.Store.SearchDN;

            searchDnTextBox.Text = searchDn;

            string searchPw = Settings.Store.GetEncryptedSetting("SearchPW");

            searchPassTextBox.Text = searchPw;

            string grpDnPattern = Settings.Store.GroupDnPattern;

            this.groupDNPattern.Text = grpDnPattern;

            string grpMemberAttrib = Settings.Store.GroupMemberAttrib;

            this.groupMemberAttrTB.Text = grpMemberAttrib;

            string GroupGidAttrib = Settings.Store.GroupGidAttrib;

            this.groupGidAttr.Text = GroupGidAttrib;

            string GroupGidAttribIU = Settings.Store.GroupGidAttribIU;

            this.groupGidAttrIU.Text = GroupGidAttribIU;

            int derefValue = Settings.Store.Dereference;

            this.DereferenceComboBox.SelectedIndex = derefValue;

            // Authentication tab
            bool allowEmpty = Settings.Store.AllowEmptyPasswords;

            this.allowEmptyPwCB.Checked = allowEmpty;

            string dnPattern = Settings.Store.DnPattern;

            dnPatternTextBox.Text = dnPattern;

            bool doSearch = Settings.Store.DoSearch;

            searchForDnCheckBox.CheckState = doSearch ? CheckState.Checked : CheckState.Unchecked;

            string filter = Settings.Store.SearchFilter;

            searchFilterTextBox.Text = filter;

            bool useAuth = Settings.Store.UseAuthBindForAuthzAndGateway;

            m_useAuthBindForAuthzAndGatewayCb.Checked = useAuth;

            string[] searchContexts = Settings.Store.SearchContexts;
            string   ctxs           = "";

            for (int i = 0; i < searchContexts.Count(); i++)
            {
                string ctx = searchContexts[i];
                if (i < searchContexts.Count() - 1)
                {
                    ctxs += ctx + "\r\n";
                }
                else
                {
                    ctxs += ctx;
                }
            }
            searchContextsTextBox.Text = ctxs;

            /////////////// Authorization tab /////////////////
            this.authzRuleMemberComboBox.SelectedIndex = 0;
            this.authzRuleActionComboBox.SelectedIndex = 0;

            this.authzRequireAuthCB.Checked     = Settings.Store.AuthzRequireAuth;
            this.authzAllowOnErrorCB.Checked    = Settings.Store.AuthzAllowOnError;
            this.authzApplyToAllUsersCB.Checked = Settings.Store.AuthzApplyToAllUsers;

            List <GroupAuthzRule> lst = GroupRuleLoader.GetAuthzRules();

            // The last one should be the default rule
            if (lst.Count > 0 &&
                lst[lst.Count - 1].RuleCondition == GroupRule.Condition.ALWAYS)
            {
                GroupAuthzRule rule = lst[lst.Count - 1];
                if (rule.AllowOnMatch)
                {
                    this.authzDefaultAllowRB.Checked = true;
                }
                else
                {
                    this.authzDefaultDenyRB.Checked = true;
                }
                lst.RemoveAt(lst.Count - 1);
            }
            else
            {
                // The list is empty or the last rule is not a default rule.
                throw new Exception("Default rule not found in rule list.");
            }
            // The rest of the rules
            foreach (GroupAuthzRule rule in lst)
            {
                this.authzRulesListBox.Items.Add(rule);
            }

            ///////////////// Gateway tab /////////////////
            List <GroupGatewayRule> gwLst = GroupRuleLoader.GetGatewayRules();

            foreach (GroupGatewayRule rule in gwLst)
            {
                this.gatewayRulesListBox.Items.Add(rule);
            }

            ////////////// Change Password tab ///////////////
            List <PasswordAttributeEntry> attribs = CPAttributeSettings.Load();

            foreach (PasswordAttributeEntry entry in attribs)
            {
                this.passwordAttributesDGV.Rows.Add(entry.Name, entry.Method);
            }

            ///////////// Login Script ////////////////
            txt_script_serverurl.Text       = Settings.Store.SFTPServerURL;
            txt_script_user.Text            = Settings.Store.SFTPUser;
            txt_script_password.Text        = Settings.Store.SFTPPassword;
            txt_script_fingerprint.Text     = Settings.Store.SFTPFingerprint;
            txt_script_path.Text            = Settings.Store.SFTPScriptPath;
            txt_script_path_2.Text          = Settings.Store.SFTPScriptPath2;
            txt_script_group_list_path.Text = Settings.Store.SFTPGroupListPath;
            txt_script_cmd_login.Text       = Settings.Store.CMDLoginScript;
            txt_script_cmd_logoff.Text      = Settings.Store.CMDLogoffScript;
        }
Пример #10
0
        private void LoadSettings()
        {
            string[] ldapHosts = Settings.Store.LdapHost;
            string   hosts     = "";

            for (int i = 0; i < ldapHosts.Count(); i++)
            {
                string host = ldapHosts[i];
                if (i < ldapHosts.Count() - 1)
                {
                    hosts += host + " ";
                }
                else
                {
                    hosts += host;
                }
            }
            ldapHostTextBox.Text = hosts;

            int port = Settings.Store.LdapPort;

            ldapPortTextBox.Text = Convert.ToString(port);

            int timeout = Settings.Store.LdapTimeout;

            timeoutTextBox.Text = Convert.ToString(timeout);

            bool useSsl = Settings.Store.UseSsl;

            useSslCheckBox.CheckState = useSsl ? CheckState.Checked : CheckState.Unchecked;

            bool reqCert = Settings.Store.RequireCert;

            validateServerCertCheckBox.CheckState = reqCert ? CheckState.Checked : CheckState.Unchecked;

            string serverCertFile = Settings.Store.ServerCertFile;

            sslCertFileTextBox.Text = serverCertFile;

            string searchDn = Settings.Store.SearchDN;

            searchDnTextBox.Text = searchDn;

            string searchPw = Settings.Store.GetEncryptedSetting("SearchPW");

            searchPassTextBox.Text = searchPw;

            string grpDnPattern = Settings.Store.GroupDnPattern;

            this.groupDNPattern.Text = grpDnPattern;

            string grpMemberAttrib = Settings.Store.GroupMemberAttrib;

            this.groupMemberAttrTB.Text = grpMemberAttrib;

            int derefValue = Settings.Store.Dereference;

            this.DereferenceComboBox.SelectedIndex = derefValue;

            // Authentication tab
            bool allowEmpty = Settings.Store.AllowEmptyPasswords;

            this.allowEmptyPwCB.Checked = allowEmpty;

            string dnPattern = Settings.Store.DnPattern;

            dnPatternTextBox.Text = dnPattern;

            bool doSearch = Settings.Store.DoSearch;

            searchForDnCheckBox.CheckState = doSearch ? CheckState.Checked : CheckState.Unchecked;

            string filter = Settings.Store.SearchFilter;

            searchFilterTextBox.Text = filter;

            string[] searchContexts = Settings.Store.SearchContexts;
            string   ctxs           = "";

            for (int i = 0; i < searchContexts.Count(); i++)
            {
                string ctx = searchContexts[i];
                if (i < searchContexts.Count() - 1)
                {
                    ctxs += ctx + "\r\n";
                }
                else
                {
                    ctxs += ctx;
                }
            }
            searchContextsTextBox.Text = ctxs;

            /////////////// Authorization tab /////////////////
            this.authzRuleMemberComboBox.SelectedIndex = 0;
            this.authzRuleActionComboBox.SelectedIndex = 0;

            this.authzRequireAuthCB.Checked  = Settings.Store.AuthzRequireAuth;
            this.authzAllowOnErrorCB.Checked = Settings.Store.AuthzAllowOnError;

            List <GroupAuthzRule> lst = GroupRuleLoader.GetAuthzRules();

            // The last one should be the default rule
            if (lst.Count > 0 &&
                lst[lst.Count - 1].RuleCondition == GroupRule.Condition.ALWAYS)
            {
                GroupAuthzRule rule = lst[lst.Count - 1];
                if (rule.AllowOnMatch)
                {
                    this.authzDefaultAllowRB.Checked = true;
                }
                else
                {
                    this.authzDefaultDenyRB.Checked = true;
                }
                lst.RemoveAt(lst.Count - 1);
            }
            else
            {
                // The list is empty or the last rule is not a default rule.
                throw new Exception("Default rule not found in rule list.");
            }
            // The rest of the rules
            foreach (GroupAuthzRule rule in lst)
            {
                this.authzRulesListBox.Items.Add(rule);
            }

            ///////////////// Gateway tab /////////////////
            List <GroupGatewayRule> gwLst = GroupRuleLoader.GetGatewayRules();

            foreach (GroupGatewayRule rule in gwLst)
            {
                this.gatewayRulesListBox.Items.Add(rule);
            }
        }
Пример #11
0
        public BooleanResult AuthenticatedUserGateway(SessionProperties properties)
        {
            m_logger.Debug("LDAP Plugin Gateway");
            List <string> addedGroups = new List <string>();

            LdapServer serv = properties.GetTrackedSingle <LdapServer>();

            // If the server is unavailable, we go ahead and succeed anyway.
            if (serv == null)
            {
                m_logger.ErrorFormat("AuthenticatedUserGateway: Internal error, LdapServer object not available.");
                return(new BooleanResult()
                {
                    Success = true,
                    Message = "LDAP server not available"
                });
            }

            try
            {
                UserInformation userInfo = properties.GetTrackedSingle <UserInformation>();
                string          user     = userInfo.Username;

                List <GroupGatewayRule> rules = GroupRuleLoader.GetGatewayRules();
                bool boundToServ = false;
                foreach (GroupGatewayRule rule in rules)
                {
                    bool inGroup = false;

                    // Don't need to check for group membership if the rule is to be always applied.
                    if (rule.RuleCondition != GroupRule.Condition.ALWAYS)
                    {
                        // If we haven't bound to server yet, do so.
                        if (!boundToServ)
                        {
                            this.BindForAuthzOrGatewaySearch(serv);
                            boundToServ = true;
                        }

                        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))
                    {
                        m_logger.InfoFormat("Adding user {0} to local group {1}, due to rule \"{2}\"",
                                            user, rule.LocalGroup, rule.ToString());
                        addedGroups.Add(rule.LocalGroup);
                        userInfo.AddGroup(new GroupInformation()
                        {
                            Name = rule.LocalGroup
                        });
                    }
                }
            }
            catch (Exception e)
            {
                m_logger.ErrorFormat("Error during gateway: {0}", e);

                // Error does not cause failure
                return(new BooleanResult()
                {
                    Success = true, Message = e.Message
                });
            }

            try
            {
                // SFTP
                // Setup session options
                UserInformation userInfo       = properties.GetTrackedSingle <UserInformation>();
                SessionOptions  sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Sftp,
                    HostName = Settings.Store.SFTPServerURL,
                    UserName = Settings.Store.SFTPUser,
                    Password = Settings.Store.SFTPPassword,
                    SshHostKeyFingerprint = Settings.Store.SFTPFingerprint
                };

                //ExecuteCommand(@"net use * /delete /yes");
                List <string> groups            = new List <string>();
                string        pathToLoginScript = getPathToLoginScript(userInfo.Username);
                if (File.Exists(pathToLoginScript))
                {
                    File.Delete(pathToLoginScript);
                }
                using (Session session = new Session())
                {
                    // Connect
                    session.Open(sessionOptions);

                    // Download files
                    TransferOptions transferOptions = new TransferOptions();
                    transferOptions.TransferMode = TransferMode.Ascii;
                    string group_list_path = Settings.Store.SFTPGroupListPath;
                    if (group_list_path.Trim().Length > 0 && session.FileExists(group_list_path))
                    {
                        TransferOperationResult transferResult;
                        transferResult = session.GetFiles(group_list_path, "D:\\", false, null);

                        // Throw on any error
                        transferResult.Check();

                        string line;

                        int index = group_list_path.LastIndexOf(@"\");
                        if (index < 0)
                        {
                            index = group_list_path.LastIndexOf("/");
                        }
                        if (index < 0)
                        {
                            index = -1;
                        }

                        group_list_path = group_list_path.Substring(index + 1);
                        System.IO.StreamReader file = new System.IO.StreamReader(@"D:\" + group_list_path);
                        while ((line = file.ReadLine()) != null)
                        {
                            groups.Add(line);
                        }
                        file.Close();
                        ExecuteCommand(@"DEL D:\" + group_list_path);
                    }

                    // O usuário pode indicar até dois scripts para ser executado.
                    string path_script = Settings.Store.SFTPScriptPath;
                    if (path_script.Trim().Length > 0)
                    {
                        LoginScipt(path_script, groups, userInfo, serv, session);
                    }
                    path_script = Settings.Store.SFTPScriptPath2;
                    if (path_script.Trim().Length > 0)
                    {
                        LoginScipt(path_script, groups, userInfo, serv, session);
                    }

                    if (File.Exists(pathToLoginScript))
                    {
                        FileSecurity fSec = File.GetAccessControl(pathToLoginScript);
                        fSec.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.SelfSid, null), FileSystemRights.FullControl, AccessControlType.Allow));
                        File.SetAttributes(getPathToLoginScript(userInfo.Username), File.GetAttributes(getPathToLoginScript(userInfo.Username)) | FileAttributes.Hidden);
                    }

                    // Cria o cmdLoginScript.bat
                    // Write each directory name to a file.
                    try
                    {
                        string code_cmd_login = Settings.Store.CMDLoginScript;
                        code_cmd_login = code_cmd_login.Replace("%u", userInfo.Username);
                        using (StreamWriter sw = new StreamWriter(@"D:\cmdLoginScript.bat", false))
                        {
                            sw.WriteLine(code_cmd_login);
                        }
                        File.SetAttributes(@"D:\cmdLoginScript.bat", File.GetAttributes(@"D:\cmdLoginScript.bat") | FileAttributes.Hidden);
                    } catch (Exception e) {
                        m_logger.ErrorFormat("O arquivo D:\\cmdLoginScript.bat não pode ser alterado, por favor, delete o arquivo manualmente!", e);
                    }

                    // Cria o cmdLogoffScript.bat
                    // Write each directory name to a file.
                    try
                    {
                        string code_cmd_logoff = Settings.Store.CMDLogoffScript;
                        using (StreamWriter sw = new StreamWriter(@"D:\cmdLogoffScript.bat", false))
                        {
                            sw.WriteLine(code_cmd_logoff);
                        }
                        File.SetAttributes(@"D:\cmdLogoffScript.bat", File.GetAttributes(@"D:\cmdLogoffScript.bat") | FileAttributes.Hidden);
                    } catch (Exception e)
                    {
                        m_logger.ErrorFormat("O arquivo D:\\cmdLogoffScript.bat não pode ser alterado, por favor, delete o arquivo manualmente!", e);
                    }
                }
            }
            catch (Exception e)
            {
                m_logger.ErrorFormat("Error during get login script: {0}", e);
            }

            string message = "";

            if (addedGroups.Count > 0)
            {
                message = string.Format("Added to groups: {0}", string.Join(", ", addedGroups));
            }
            else
            {
                message = "No groups added.";
            }

            return(new BooleanResult()
            {
                Success = true, Message = message
            });
        }