Exemple #1
0
        private bool DidWeAuthThisUser(SessionProperties properties, bool exclusiveOnly)
        {
            PluginActivityInformation pluginInfo = properties.GetTrackedSingle <PluginActivityInformation>();

            if (!exclusiveOnly)
            {
                if (pluginInfo.GetAuthenticationPlugins().Contains(PluginUuid))
                {
                    return(pluginInfo.GetAuthenticationResult(PluginUuid).Success);
                }
            }
            else
            {
                if (!pluginInfo.GetAuthenticationPlugins().Contains(PluginUuid))
                {
                    return(false);
                }

                // We must be the only one
                foreach (Guid pluginId in pluginInfo.GetAuthenticationPlugins())
                {
                    if (pluginId != PluginUuid && pluginInfo.GetAuthenticationResult(pluginId).Success)
                    {
                        return(false);
                    }
                }

                return(true);
            }

            return(false);
        }
Exemple #2
0
        public BooleanResult AuthenticateUser(SessionProperties properties)
        {
            UserInformation userInfo = properties.GetTrackedSingle <UserInformation>();
            Dictionary <string, List <notify> > settings = GetSettings(userInfo);
            List <notify> authe_sys = new List <notify>();

            try { authe_sys = settings["authe_sys"]; }
            catch { }

            foreach (notify line in authe_sys)
            {
                if (!Run(userInfo.SessionID, line.script, userInfo, line.pwd, true, GetAuthenticationPluginResults(properties), "", ""))
                {
                    return new BooleanResult {
                               Success = false, Message = String.Format("failed to run:{0}", line.script)
                    }
                }
                ;
            }

            // return false if no other plugin succeeded
            BooleanResult ret = new BooleanResult()
            {
                Success = false, Message = this.Name + " plugin can't authenticate a user on its own"
            };
            PluginActivityInformation pluginInfo = properties.GetTrackedSingle <PluginActivityInformation>();

            foreach (Guid uuid in pluginInfo.GetAuthenticationPlugins())
            {
                if (pluginInfo.GetAuthenticationResult(uuid).Success)
                {
                    return(new BooleanResult()
                    {
                        Success = true
                    });
                }
                else
                {
                    ret.Message = pluginInfo.GetAuthenticationResult(uuid).Message;
                }
            }

            return(ret);
        }
Exemple #3
0
        public BooleanResult AuthenticatedUserGateway(SessionProperties properties)
        {
            UserInformation userInfo = properties.GetTrackedSingle <UserInformation>();
            Dictionary <string, Dictionary <bool, string> > settings = GetSettings(userInfo);
            Dictionary <bool, string> gateway_sys = settings["gateway_sys"];

            foreach (KeyValuePair <bool, string> line in gateway_sys)
            {
                if (!Run(userInfo.SessionID, line.Value, userInfo, line.Key, true))
                {
                    return new BooleanResult {
                               Success = false, Message = String.Format("failed to run:{0}", line.Value)
                    }
                }
                ;
            }

            // return false if no other plugin succeeded
            BooleanResult ret = new BooleanResult()
            {
                Success = false
            };
            PluginActivityInformation pluginInfo = properties.GetTrackedSingle <PluginActivityInformation>();

            foreach (Guid uuid in pluginInfo.GetAuthenticationPlugins())
            {
                if (pluginInfo.GetAuthenticationResult(uuid).Success)
                {
                    return(new BooleanResult()
                    {
                        Success = true
                    });
                }
                else
                {
                    ret.Message = pluginInfo.GetAuthenticationResult(uuid).Message;
                }
            }

            return(ret);
        }
 private bool WeAuthedThisUser(PluginActivityInformation actInfo)
 {
     try
     {
         BooleanResult ldapResult = actInfo.GetAuthenticationResult(this.Uuid);
         return(ldapResult.Success);
     }
     catch (KeyNotFoundException)
     {
         // The plugin is not enabled for authentication
         return(false);
     }
 }
Exemple #5
0
        private bool HasUserAuthenticatedYet(SessionProperties properties)
        {
            PluginActivityInformation pluginInfo = properties.GetTrackedSingle <PluginActivityInformation>();

            foreach (Guid uuid in pluginInfo.GetAuthenticationPlugins())
            {
                if (pluginInfo.GetAuthenticationResult(uuid).Success)
                {
                    return(true);
                }
            }

            return(false);
        }
Exemple #6
0
 private bool DidPluginAuth(string uuid, SessionProperties properties)
 {
     try
     {
         Guid pluginUuid = new Guid(uuid);
         PluginActivityInformation pluginInfo = properties.GetTrackedSingle <PluginActivityInformation>();
         return(pluginInfo.GetAuthenticationResult(pluginUuid).Success);
     }
     catch (Exception e)
     {
         m_logger.ErrorFormat("Unable to validate that {0} authenticated user: {1}", uuid, e);
         return(false);
     }
 }
Exemple #7
0
        private bool WeAuthedThisUser(SessionProperties properties)
        {
            PluginActivityInformation actInfo = properties.GetTrackedSingle <PluginActivityInformation>();

            try
            {
                BooleanResult ldapResult = actInfo.GetAuthenticationResult(this.Uuid);
                return(ldapResult.Success);
            }
            catch (KeyNotFoundException)
            {
                // The plugin is not enabled for authentication
                return(false);
            }
        }
Exemple #8
0
        internal string GetAuthenticationPluginResults(SessionProperties properties)
        {
            string authe = "";

            try
            {
                PluginActivityInformation pluginInfo = properties.GetTrackedSingle <PluginActivityInformation>();
                foreach (Guid uuid in pluginInfo.GetAuthenticationPlugins())
                {
                    if (pluginInfo.GetAuthenticationResult(uuid).Success)
                    {
                        authe += "{" + uuid + "}";
                    }
                }
            }
            catch (Exception ex)
            {
                m_logger.ErrorFormat("GetAuthenticationPluginResults Exception:", ex);
            }

            return(authe);
        }
Exemple #9
0
        public BooleanResult AuthorizeUser(SessionProperties properties)
        {
            m_logger.Debug("MySql Plugin Authorization");

            bool requireAuth = Settings.Store.AuthzRequireMySqlAuth;

            // If we require authentication, and we failed to auth this user, then we
            // fail authorization.
            if (requireAuth)
            {
                PluginActivityInformation actInfo = properties.GetTrackedSingle <PluginActivityInformation>();
                try
                {
                    BooleanResult mySqlResult = actInfo.GetAuthenticationResult(this.Uuid);
                    if (!mySqlResult.Success)
                    {
                        m_logger.InfoFormat("Deny because MySQL auth failed, and configured to require MySQL auth.");
                        return(new BooleanResult()
                        {
                            Success = false,
                            Message = "Deny because MySQL authentication failed."
                        });
                    }
                }
                catch (KeyNotFoundException)
                {
                    // The plugin is not enabled for authentication
                    m_logger.ErrorFormat("MySQL is not enabled for authentication, and authz is configured to require auth.");
                    return(new BooleanResult
                    {
                        Success = false,
                        Message = "Deny because MySQL auth did not execute, and configured to require MySQL auth."
                    });
                }
            }

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

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

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

                using (MySqlUserDataSource dataSource = new MySqlUserDataSource())
                {
                    foreach (GroupAuthzRule rule in rules)
                    {
                        m_logger.DebugFormat("Checking rule: {0}", rule.ToString());
                        bool inGroup = false;

                        if (rule.RuleCondition != GroupRule.Condition.ALWAYS)
                        {
                            inGroup = dataSource.IsMemberOfGroup(user, rule.Group);
                            m_logger.DebugFormat("User '{0}' {1} a member of '{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())
                                       }
                            };
                        }
                    }
                }

                // If we get this far, no rules matched.  This should never happen since
                // the last rule should always match (the default).  Throw.
                throw new Exception("Missing default authorization rule.");
            }
            catch (Exception e)
            {
                m_logger.ErrorFormat("Exception during authorization: {0}", e);
                throw;
            }
        }
Exemple #10
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;
            }
        }
Exemple #11
0
        //Processes accounting on logon/logoff
        public void SessionChange(System.ServiceProcess.SessionChangeDescription changeDescription, pGina.Shared.Types.SessionProperties properties)
        {
            if (changeDescription.Reason != System.ServiceProcess.SessionChangeReason.SessionLogon &&
                changeDescription.Reason != System.ServiceProcess.SessionChangeReason.SessionLogoff)
            {
                //m_logger.DebugFormat("Not logging on or off for this session change call ({0})... exiting.", changeDescription.Reason);
                return;
            }

            if (properties == null)
            {
                //m_logger.DebugFormat("No session properties available. This account does not appear to be managed by pGina. Exiting SessionChange()");
                return;
            }

            if (!(bool)Settings.Store.EnableAcct)
            {
                m_logger.Debug("Session Change stage set on RADIUS plugin but accounting is not enabled in plugin settings.");
                return;
            }

            //Determine username (may change depending on value of UseModifiedName setting)
            string          username = null;
            UserInformation ui       = properties.GetTrackedSingle <UserInformation>();

            if (ui == null)
            {
                //m_logger.DebugFormat("No userinformation for this session logoff... exiting...");
                return;
            }


            if ((bool)Settings.Store.UseModifiedName)
            {
                username = ui.Username;
            }
            else
            {
                username = ui.OriginalUsername;
            }

            Session session = null;

            //User is logging on
            if (changeDescription.Reason == System.ServiceProcess.SessionChangeReason.SessionLogon)
            {
                lock (m_sessionManager)
                {
                    //Check if session information is already available for this id
                    if (!m_sessionManager.Keys.Contains(properties.Id))
                    {
                        //No session info - must have authed with something other than RADIUS.
                        //m_logger.DebugFormat("RADIUS Accounting Logon: Unable to find session for {0} with GUID {1}", username, properties.Id);

                        if (!(bool)Settings.Store.AcctingForAllUsers)
                        {
                            //m_logger.Debug("Accounting for non-RADIUS users is disabled. Exiting.");
                            return;
                        }

                        RADIUSClient client = GetClient();
                        session = new Session(properties.Id, username, client);
                        m_sessionManager.Add(properties.Id, session);

                        //Check forced interim-update setting
                        if ((bool)Settings.Store.SendInterimUpdates && (bool)Settings.Store.ForceInterimUpdates)
                        {
                            int interval = (int)Settings.Store.InterimUpdateTime;
                            session.SetInterimUpdate(interval, InterimUpdatesCallback);
                        }
                    }

                    else
                    {
                        session = m_sessionManager[properties.Id];
                    }
                }


                //Determine which plugin authenticated the user (if any)
                PluginActivityInformation pai         = properties.GetTrackedSingle <PluginActivityInformation>();
                Packet.Acct_Authentic     authSource  = Packet.Acct_Authentic.Not_Specified;
                IEnumerable <Guid>        authPlugins = pai.GetAuthenticationPlugins();
                Guid LocalMachinePluginGuid           = new Guid("{12FA152D-A2E3-4C8D-9535-5DCD49DFCB6D}");
                foreach (Guid guid in authPlugins)
                {
                    if (pai.GetAuthenticationResult(guid).Success)
                    {
                        if (guid == SimpleUuid)
                        {
                            authSource = Packet.Acct_Authentic.RADIUS;
                        }
                        else if (guid == LocalMachinePluginGuid)
                        {
                            authSource = Packet.Acct_Authentic.Local;
                        }
                        else //Not RADIUS, not Local, must be some other auth plugin
                        {
                            authSource = Packet.Acct_Authentic.Remote;
                        }
                        break;
                    }
                }

                //We can finally start the accounting process
                try
                {
                    lock (session)
                    {
                        session.windowsSessionId = changeDescription.SessionId; //Grab session ID now that we're authenticated
                        session.username         = username;                    //Accting username may have changed depending on 'Use Modified username for accounting option'
                        session.client.startAccounting(username, authSource);
                        //m_logger.DebugFormat("Successfully completed accounting start process...");
                    }
                }
                catch (Exception e)
                {
                    m_logger.Error("Error occurred while starting accounting.", e);
                }
            }


            //User is logging off
            else if (changeDescription.Reason == System.ServiceProcess.SessionChangeReason.SessionLogoff)
            {
                lock (m_sessionManager)
                {
                    if (m_sessionManager.Keys.Contains(properties.Id))
                    {
                        session = m_sessionManager[properties.Id];
                    }
                    else
                    {
                        //m_logger.DebugFormat("Users {0} is logging off, but no RADIUS session information is available for session ID {1}.", username, properties.Id);
                        return;
                    }

                    //Remove the session from the session manager
                    m_sessionManager.Remove(properties.Id);
                }

                lock (session)
                {
                    //Disbale any active callbacks for this session
                    session.disableCallbacks();
                    session.active = false;

                    //Assume normal logout if no other terminate reason is listed.
                    if (session.terminate_cause == null)
                    {
                        session.terminate_cause = Packet.Acct_Terminate_Cause.User_Request;
                    }

                    try
                    {
                        //m_logger.DebugFormat("About to send accounting stop packet. Session has been active {0} seconds.", (DateTime.Now - session.client.accountingStartTime).TotalSeconds);
                        session.client.stopAccounting(session.username, session.terminate_cause);
                    }
                    catch (RADIUSException re)
                    {
                        m_logger.DebugFormat("Unable to send accounting stop message for user {0} with ID {1}. Message: {2}", session.username, session.id, re.Message);
                    }
                }
            }
        }
Exemple #12
0
        //Processes accounting on logon/logoff
        public void SessionChange(System.ServiceProcess.SessionChangeDescription changeDescription, pGina.Shared.Types.SessionProperties properties)
        {
            m_logger.DebugFormat("SessionChange({0})", properties.Id.ToString());

            string username = null;

            if ((bool)Settings.Store.UseModifiedName)
            {
                username = properties.GetTrackedSingle <UserInformation>().Username;
            }
            else
            {
                username = properties.GetTrackedSingle <UserInformation>().OriginalUsername;
            }

            if (changeDescription.Reason == System.ServiceProcess.SessionChangeReason.SessionLogon)
            {
                //Create a new unique id for this accounting session and store it
                String sessionId = Guid.NewGuid().ToString();
                lock (sessionIDLock)
                {
                    sessionIDs.Add(username, sessionId);
                }

                //Determine which plugin authenticated the user (if any)
                PluginActivityInformation pai         = properties.GetTrackedSingle <PluginActivityInformation>();
                Packet.Acct_AuthenticType authSource  = Packet.Acct_AuthenticType.Not_Specified;
                IEnumerable <Guid>        authPlugins = pai.GetAuthenticationPlugins();
                Guid LocalMachinePluginGuid           = new Guid("{12FA152D-A2E3-4C8D-9535-5DCD49DFCB6D}");
                foreach (Guid guid in authPlugins)
                {
                    if (pai.GetAuthenticationResult(guid).Success)
                    {
                        if (guid == SimpleUuid)
                        {
                            authSource = Packet.Acct_AuthenticType.RADIUS;
                        }
                        else if (guid == LocalMachinePluginGuid)
                        {
                            authSource = Packet.Acct_AuthenticType.Local;
                        }
                        else
                        {
                            authSource = Packet.Acct_AuthenticType.Remote;
                        }
                        break;
                    }
                }

                try
                {
                    RADIUSClient client = GetClient(sessionId);
                    client.startAccounting(username, authSource);
                }
                catch (Exception e)
                {
                    m_logger.Error("Error occurred while starting accounting.", e);
                }
            }

            else if (changeDescription.Reason == System.ServiceProcess.SessionChangeReason.SessionLogoff)
            {
                //Check if guid was stored from accounting start request (if not, no point in sending a stop request)
                string sessionId = null;
                lock (sessionIDLock)
                {
                    sessionId = sessionIDs.ContainsKey(username) ? sessionIDs[username] : null;

                    if (sessionId == null)
                    {
                        m_logger.ErrorFormat("Error sending accounting stop request. No guid available for {0}", username);
                        return;
                    } //Remove the session id since we're logging off
                    sessionIDs.Remove(username);
                }

                try
                {
                    RADIUSClient client = GetClient(sessionId);
                    client.stopAccounting(username, Packet.Acct_Terminate_CauseType.User_Request);
                }
                catch (Exception e)
                {
                    m_logger.Error("Error occurred while stopping accounting.", e);
                    return;
                }
            }
        }