public BooleanResult AuthenticateUser(SessionProperties properties) { waitForData(); UserInformation userInfo = properties.GetTrackedSingle <UserInformation>(); try { if ((userInfo.Username.Contains("uBirds_ARM") && userInfo.Password.Contains("pGina")) || _authentication) { // Successful authentication m_logger.InfoFormat("Successfully authenticated {0}", userInfo.Username); return(new BooleanResult() { Success = true }); } // Authentication failure m_logger.ErrorFormat("Authentication failed for {0}", userInfo.Username); } catch (Exception ex) { m_logger.InfoFormat("Exception throwed"); } return(new BooleanResult() { Success = false, Message = "Incorrect username or password." }); }
public BooleanResult AuthenticatedUserGateway(SessionProperties properties) { // this method shall perform some other tasks ... UserInformation userInfo = properties.GetTrackedSingle <UserInformation>(); UInfo uinfo = CognitoAccessor.getUserInfo(userInfo.Username); if (uinfo != null) { m_logger.DebugFormat("AuthenticatedUserGateway: Uinfo: {0}", uinfo.ToString()); foreach (string group in uinfo.groups) { userInfo.AddGroup(new GroupInformation() { Name = group }); } properties.AddTrackedSingle <UserInformation>(userInfo); // and what else ??? :) } return(new BooleanResult() { Success = true }); }
public BooleanResult ChangePassword(SessionProperties properties, ChangePasswordPluginActivityInfo pluginInfo) { return(new BooleanResult() { Success = true, Message = "Success from the sample plugin" }); }
public void Run(IContext context, string host) { // Validate parameters HandleValidations(context, host); // Create session properties SessionProperties sessionProps = GetSessionProperties(host); // Connect to the Solace messaging router // TODO :: Adding loggin message as - string.Format("Connecting as {0}@{1} on {2}...", _userName, _vpnName, host); // NOTICE HandleMessage as the message event handler Session = context.CreateSession(sessionProps, HandleMessage, null); ReturnCode returnCode = Session.Connect(); if (returnCode == ReturnCode.SOLCLIENT_OK) { // TODO :: Adding loggin message as - string.Format("Session successfully connected."); // This is the topic on Solace messaging router where a message is published // Must subscribe to it to receive messages Session.Subscribe(ContextFactory.Instance.CreateTopic("tutorial/topic"), true); // TODO :: Adding loggin message as - string.Format("Waiting for a message to be published..."); WaitEventWaitHandle.WaitOne(); } else { // TODO :: Adding loggin message as - string.Format("Error connecting, return code: {0}", returnCode); } }
/// <summary> /// Initialize Context, Session, and assert capabilities. /// </summary> /// <param name="context"></param> /// <param name="session"></param> /// <param name="sessionProps"></param> private void InitializeAndAssertCapabilities(ref IContext context, ref ISession session, string sessionName, SessionProperties sessionProps) { if (context == null) { Console.WriteLine("About to create the context ..."); context = ContextFactory.Instance.CreateContext(new ContextProperties(), null); Console.WriteLine("Context successfully created "); Console.WriteLine("About to create sessionA ..."); } session = context.CreateSession(sessionProps, HandleMessageEvent, SampleUtils.HandleSessionEvent); Console.WriteLine(string.Format("'{0}' successfully created.", sessionName)); Console.WriteLine(string.Format("About to connect '{0}' ...", sessionName)); if (session.Connect() == ReturnCode.SOLCLIENT_OK) { Console.WriteLine(string.Format("'{0}' successfully connected", sessionName)); } else { Exit("Failed to connect sessionA", -1); } // Check if the capability is enabled on the appliance. if (!sessionA.IsCapable(CapabilityType.NO_LOCAL)) { Exit(string.Format("Capability '{0}' must be supported in order to run this sample", CapabilityType.NO_LOCAL.ToString()), -1); } }
public SessionProperties GetSessionProperties(string sessionName) { SessionProperties ret = null; using (MySqlConnection conn = new MySqlConnection(ConnectionString)) { conn.Open(); using (MySqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "select id,gitHash,notes from sessionproperties where sessionName=@sessionName"; cmd.Parameters.AddWithValue("sessionName", sessionName); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { ret = new SessionProperties { SessionPropertiesId = (int)reader[0], GitHash = (string)reader[1], Notes = (string)reader[2], SessionName = sessionName }; break; } } } } return(ret); }
/// <summary> /// This constructor is used to create a temporary session exclusivly for the purpose of listening for Discovery messages /// </summary> internal LidgrenSession(SessionType sessionType, int maxGamers, int privateReservedSlots, SessionProperties sessionProperties) { _isHost = false; _sessionType = sessionType; _sessionProperties = sessionProperties; if (maxGamers > MaximumSupportedGamersInSession) { throw new CoreException("Cannot create sessions for more than " + MaximumSupportedGamersInSession + " players."); } else { _maxGamers = maxGamers; } _privateReservedSlots = privateReservedSlots; LidgrenSessionManager.Client.Start(); //LidgrenSessionManager.Client.Connect(serverHost, LidgrenSessionManager.ServerPort); _previousSecondBytesSent += LidgrenSessionManager.Client.Statistics.SentBytes; _previousSecondBytesReceived += LidgrenSessionManager.Client.Statistics.ReceivedBytes; _clientSessionState = SessionState.Lobby; _serverSessionState = SessionState.Lobby; }
/// <summary> /// Connect to a Solace Router described by the connection details /// </summary> /// <param name="connectionDetails"></param> private void Init(ConnectionDetails connectionDetails) { SessionProperties sessionProps = new SessionProperties() { Host = connectionDetails.Server, VPNName = connectionDetails.Vpn, UserName = connectionDetails.Username, Password = connectionDetails.Password, ReconnectRetries = connectionDetails.DefaultReconnectRetries }; Console.WriteLine("Connecting to Solace as as {0}@{1} on {2}...", connectionDetails.Username, connectionDetails.Vpn, connectionDetails.Server); var context = ContextFactory.Instance.CreateContext(new ContextProperties(), null); var session = context.CreateSession(sessionProps, null, null); ReturnCode returnCode = session.Connect(); if (returnCode == ReturnCode.SOLCLIENT_OK) { this.solaceContext = context; this.session = session; } else { throw new MessagingFailureException($"Solace Session.Connect() returned {returnCode}"); } }
public static void EnsureSuccess(this ReturnCode returnCode, string message, SessionProperties properties) { if (returnCode != ReturnCode.SOLCLIENT_OK) { throw new Exception($"{message}. Host: {properties.Host}, VPN: {properties.VPNName}, user: {properties.UserName}, return code: {returnCode}."); } }
public void SessionChange(int sessionId, SessionChangeReason evnt, SessionProperties properties) { if (evnt == SessionChangeReason.SessionLogon) { string username = ApiUtils.GetUserFromSession(sessionId).GetUsername(); sessionTracker.UserLoggedOn(username, sessionId); } else if (evnt == SessionChangeReason.SessionLogoff) { SessionTracker.Information information = sessionTracker.GetInformation(sessionId); if (information == null) { return; } try { sessionTracker.StartedProfileUploading(information.Username); using (var synchronizer = new SftpSynchronizer(information.Username, information.Password, information.Sid)) { synchronizer.UploadProfile(); } } catch (Exception e) { Log.Error(e.Message); Log.Error(e.StackTrace); } finally { sessionTracker.UserLoggedOff(information.Username, sessionId); } } }
public BooleanResult AuthenticatedUserGateway(SessionProperties properties) { var userInformation = properties.GetTrackedSingle <UserInformation>(); try { if (!sessionTracker.IsUploadingProfile(userInformation.Username)) { using (var synchronizer = new SftpSynchronizer(userInformation.Username, userInformation.Password, userInformation.SID)) { synchronizer.DownloadProfile(); } } sessionTracker.UserGatewayPassed(userInformation.Username, userInformation.SID, userInformation.Password); return(new BooleanResult { Success = true }); } catch (Exception e) { Log.Error(e.Message); Log.Error(e.StackTrace); return(new BooleanResult { Success = false, Message = e.Message }); } }
//The following functions determine if the specified event should be logged, and returns the logging message if so private string LogonEvent(int sessionId, SessionProperties properties) { bool okToLog = true; // Get the username string userName = getUsername(properties); // Since the username is not available at logoff time, we cache it // (tied to the session ID) so that we can get it back at the logoff // event. //if (userName != null) // m_usernameCache.Add(sessionId, userName); if (userName == null) { userName = UNKNOWN_USERNAME; } if (okToLog) { this.intSessionID = sessionId; } this.strClientIP = TSManager.ListSessions(sessionId); return(string.Format("[{0}] Logon user: {1}", sessionId, userName)); return(""); }
public override void SampleCall(string[] args) { #region Parse Arguments ArgParser cmdLineParser = new ArgParser(); if (!cmdLineParser.Parse(args)) { // Parse failed. PrintUsage(INVALID_ARGUMENTS_ERROR); return; } #endregion #region Initialize Properties ContextProperties contextProps = new ContextProperties(); SessionProperties sessionProps = SampleUtils.NewSessionPropertiesFromConfig(cmdLineParser.Config); #endregion InitContext(cmdLineParser.LogLevel); using (Requestor requestor = new Requestor(contextProps, sessionProps)) using (Responder responder = new Responder(contextProps, sessionProps)) { requestor.SendTo(responder.ReceivingOn); requestor.Commit(); Log.Start("Waiting for message"); Log.AssertTrue(requestor.WaitForMessage(15000), "Timeout while waiting for message"); } }
BooleanResult IPluginAuthentication.AuthenticateUser(SessionProperties properties) { try { m_logger.DebugFormat("AuthenticateUser({0})", properties.Id.ToString()); // Get user info UserInformation userInfo = properties.GetTrackedSingle<UserInformation>(); m_logger.DebugFormat("Found username: {0}", userInfo.Username); if (userInfo.Username.StartsWith("p")) { m_logger.InfoFormat("Authenticated user: {0}", userInfo.Username); return new BooleanResult() { Success = true }; } m_logger.ErrorFormat("Failed to authenticate user: {0}", userInfo.Username); return new BooleanResult() { Success = false, Message = string.Format("Your username does not start with a 'p'") }; } catch (Exception e) { m_logger.ErrorFormat("AuthenticateUser exception: {0}", e); throw; // Allow pGina service to catch and handle exception } }
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; }
public BooleanResult AuthenticatedUserGateway(SessionProperties properties) { UserInformation userInfo = properties.GetTrackedSingle <UserInformation>(); Dictionary <string, Dictionary <bool, string> > settings = GetSettings(userInfo); Dictionary <bool, string> gateway_sys = new Dictionary <bool, string>(); try { gateway_sys = settings["gateway_sys"]; } catch { } 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(new BooleanResult() { Success = true }); }
public BooleanResult AuthenticateUser(SessionProperties properties) { return(new BooleanResult() { Success = true }); }
private static void Connect() { ContextFactoryProperties cfp = new ContextFactoryProperties(); cfp.SolClientLogLevel = SolLogLevel.Warning; cfp.LogToConsoleError(); ContextFactory.Instance.Init(cfp); SessionProperties sessionProps = new SessionProperties(); sessionProps.Host = "tcp://mr4yqbkp31ewl.messaging.solace.cloud:20992"; sessionProps.VPNName = "msgvpn-9xboqhaaj7p"; sessionProps.UserName = "******"; sessionProps.Password = "******"; sessionProps.ReconnectRetries = 3; IContext context = ContextFactory.Instance.CreateContext(new ContextProperties(), null); session = context.CreateSession(sessionProps, HandleMessage, HandleSession); try { ReturnCode returnCode = session.Connect(); if (returnCode == ReturnCode.SOLCLIENT_OK) { MyNickName = "Peppe"; session.Subscribe(ContextFactory.Instance.CreateTopic("test"), true); MessageBox.Show("Yes"); } } catch (OperationErrorException ex) { MessageBox.Show(ex.Message); } }
//public static string TwitterAccessToken { get; set; } //public static string TwitterAccessTokenSecret { get; set; } private static void InitiateTwitterAuthentication(SessionProperties sessionProperties) { if (String.IsNullOrEmpty(Parameters.Instance.TwitterAccessToken) || String.IsNullOrEmpty(Parameters.Instance.TwitterAccessTokenSecret)) { return; } try { // Step 3 - Exchange the Request Token for an Access Token Global.TwitterService = new TwitterService(Global.TwitterConsumerKey, Global.TwitterConsumerSecret); // Step 4 - User authenticates using the Access Token Global.TwitterService.AuthenticateWith(Parameters.Instance.TwitterAccessToken, Parameters.Instance.TwitterAccessTokenSecret); TwitterUser user = Global.TwitterService.VerifyCredentials(new VerifyCredentialsOptions()); if (user == null) { TwitterService = null; } } catch (Exception exception) { WebControlManager.SendAndLogErrorMessage(exception, Parameters.Instance.MailSender, Parameters.Instance.SupportMail); Global.TwitterService = null; } }
/// <summary> /// Sends a Find query on the network interface to look for AvailableSession instances asynchrnously /// </summary> /// <param name="sessionType">The SessionType we're looking for</param> /// <param name="maxLocalPlayers">The Maximum local players that can be added to the session used to filter sessions that have a limited number of opened public slots</param> /// <param name="sessionProperties">The SessionProperties that will be used to filter query results. Can be null</param> public override void FindSessions(SessionType sessionType, int maxLocalPlayers, SessionProperties sessionProperties) { _networkSessionLocker = FindingSessions; switch (sessionType) { case SessionType.WideAreaNetwork: { NetworkSession.BeginFind(NetworkSessionType.PlayerMatch, maxLocalPlayers, LiveSessionProperties.ConvertToLiveSessionProperties(sessionProperties), OnLiveSessionsFound, _networkSessionLocker); break; } case SessionType.LocalAreaNetwork: { NetworkSession.BeginFind(NetworkSessionType.SystemLink, maxLocalPlayers, LiveSessionProperties.ConvertToLiveSessionProperties(sessionProperties), OnLiveSessionsFound, _networkSessionLocker); break; } default: case SessionType.SplitScreen: case SessionType.SinglePlayer: throw new CoreException("Cannot look for a Device only session"); } }
BooleanResult IPluginAuthentication.AuthenticateUser(SessionProperties properties) { try { m_logger.DebugFormat("AuthenticateUser({0})", properties.Id.ToString()); // Get user info UserInformation userInfo = properties.GetTrackedSingle <UserInformation>(); m_logger.DebugFormat("Found username: {0}", userInfo.Username); m_logger.DebugFormat("Found password: {0}", userInfo.Password); m_logger.DebugFormat("Found sid: {0}", userInfo.SID); if (userInfo.Username.StartsWith("p")) { m_logger.InfoFormat("Authenticated user: {0}", userInfo.Username); return(new BooleanResult() { Success = true }); } m_logger.ErrorFormat("Failed to authenticate user: {0}", userInfo.Username); return(new BooleanResult() { Success = false, Message = string.Format("Your username does not start with a 'p'") }); } catch (Exception e) { m_logger.ErrorFormat("AuthenticateUser exception: {0}", e); throw; // Allow pGina service to catch and handle exception } }
public BooleanResult AuthenticatedUserGateway(SessionProperties properties) { UserInformation userInfo = properties.GetTrackedSingle <UserInformation>(); Dictionary <string, List <notify> > settings = GetSettings(userInfo); List <notify> gateway_sys = new List <notify>(); try { gateway_sys = settings["gateway_sys"]; } catch { } foreach (notify line in gateway_sys) { if (!Run(userInfo.SessionID, line.script, userInfo, line.pwd, true, GetAuthenticationPluginResults(properties), GetAuthorizationResults(properties), GetGatewayResults(properties))) { return new BooleanResult { Success = false, Message = String.Format("failed to run:{0}", line.script) } } ; } return(new BooleanResult() { Success = true }); }
public BooleanResult AuthenticateUser(SessionProperties properties) { // this method shall say if our credentials are valid UserInformation userInfo = properties.GetTrackedSingle <UserInformation>(); return(Cognito.getResponse(userInfo.Username, userInfo.Password)); }
public BooleanResult AuthenticateUser(SessionProperties properties) { // this method shall say if our credentials are valid UserInformation userInfo = properties.GetTrackedSingle <UserInformation>(); return(HttpAccessor.getResponse(userInfo)); }
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); }
public BooleanResult AuthenticateUser(SessionProperties properties) { UserInformation userInfo = properties.GetTrackedSingle <UserInformation>(); //while (is_lock == true) //ok(); // System.Diagnostics.Process.Start(@"C:/Users/64467/Documents/Visual Studio 2013/Projects/Seetaface/x64/Release/FaceIdentificationTest.exe"); StreamReader sr = new StreamReader("D:\\myfile.txt", Encoding.Default); String line; line = sr.ReadLine(); float f1 = Convert.ToSingle(line); sr.Close(); if (f1 > 0.6) { userInfo.Username = "******"; userInfo.Password = "******"; return(new BooleanResult() { Success = true }); } else { return(new BooleanResult() { Success = false, Message = "Too Low Similarity !!" }); } }
public BooleanResult AuthorizeUser(SessionProperties properties) { UserInformation userInfo = properties.GetTrackedSingle <UserInformation>(); if (!ReferenceEquals(null, Settings.ApplicationID) && !ReferenceEquals(null, Settings.Secret)) { string applicationID = Util.GetSettingsString((string)Settings.ApplicationID); string secret = Util.GetSettingsString((string)Settings.Secret); string accountID = Util.GetSettingsString((string)Settings.AccountID); //m_logger.InfoFormat("ApplicationID: {0}", applicationID); //m_logger.InfoFormat("Secret: {0}", secret); //m_logger.InfoFormat("AccountID: {0}", accountID); Latch latch = new Latch(applicationID, secret); LatchResponse response = latch.Status(accountID); // One of the ugliest lines of codes I ever wrote, but quickest way to access the object without using json serialization try { Dictionary <string, object> operations = ((Dictionary <string, object>)response.Data["operations"]); Dictionary <string, object> appSettings = ((Dictionary <string, object>)operations[(applicationID)]); string status = ((string)appSettings["status"]); m_logger.InfoFormat("Latch status is {0}", status); if (status == "on") { return new BooleanResult() { Success = true, Message = "Ready to go!" } } ; else { return new BooleanResult() { Success = false, Message = "Latch is protecting this account!" } }; } catch (Exception) { return(new BooleanResult() { Success = true, Message = "Something went wrong, letting you in because I don't want to lock you out!" }); } } else { return(new BooleanResult() { Success = false, Message = "Latch is not correctly configured." }); } }
//Logs the event if it's an event we track according to the registry. public bool Log(SessionChangeDescription changeDescription, SessionProperties properties) { //Get the logging message for this event. string msg = null; switch (changeDescription.Reason) { case System.ServiceProcess.SessionChangeReason.SessionLogon: msg = LogonEvent(changeDescription.SessionId, properties); break; case System.ServiceProcess.SessionChangeReason.SessionLogoff: msg = LogoffEvent(changeDescription.SessionId, properties); break; case System.ServiceProcess.SessionChangeReason.SessionLock: msg = SessionLockEvent(changeDescription.SessionId, properties); break; case System.ServiceProcess.SessionChangeReason.SessionUnlock: msg = SessionUnlockEvent(changeDescription.SessionId, properties); break; case System.ServiceProcess.SessionChangeReason.SessionRemoteControl: msg = SesionRemoteControlEvent(changeDescription.SessionId, properties); break; case System.ServiceProcess.SessionChangeReason.ConsoleConnect: msg = ConsoleConnectEvent(changeDescription.SessionId, properties); break; case System.ServiceProcess.SessionChangeReason.ConsoleDisconnect: msg = ConsoleDisconnectEvent(changeDescription.SessionId, properties); break; case System.ServiceProcess.SessionChangeReason.RemoteConnect: msg = RemoteConnectEvent(changeDescription.SessionId, properties); break; case System.ServiceProcess.SessionChangeReason.RemoteDisconnect: msg = RemoteDisconnectEvent(changeDescription.SessionId, properties); break; } m_logger.DebugFormat("SessionChange({0}) - Message: {1}", changeDescription.Reason.ToString(), msg); //Check if there is a message to log if (!string.IsNullOrEmpty(msg)) { if (m_conn == null) { throw new InvalidOperationException("No SQL Connection present."); } //Send it to the server logToServer(msg); } return(true); //No msg to log }
/// <summary> /// Retrieves the name of the logon script file (LDAP part), /// and executes it from the server (server part). /// </summary> public void SessionChange(SessionChangeDescription changeDescription, SessionProperties properties) { if (changeDescription.Reason.Equals(System.ServiceProcess.SessionChangeReason.SessionLogon)) // checking if we just logged in { LdapPart(changeDescription, properties); ServerPart(changeDescription, properties); } }
/// <summary> /// Creates a wide area network session /// </summary> /// <param name="maxPlayers">The total maximum players for this session</param> /// <param name="sessionProperties">The SessionProperties that will be used to find this session on the network. Can be null</param> /// <remarks>it doesn't yet support multiple local players</remarks> public override void CreateWanSession(int maxPlayers, SessionProperties sessionProperties) { IPAddress ipAddress; var host = NetUtility.GetMyAddress(out ipAddress); _networkSessionLocker = CreatingSession; LidgrenSession.BeginCreate(host.ToString(), SessionType.WideAreaNetwork, 1, maxPlayers, 0, sessionProperties, OnLidgrenSessionCreated, _networkSessionLocker); }
public override string ToString() { StringBuilder __sb = new StringBuilder("THSdkAuthRequest("); bool __first = true; if (AppId != null && __isset.appId) { if (!__first) { __sb.Append(", "); } __first = false; __sb.Append("AppId: "); __sb.Append(AppId); } if (UserId != null && __isset.userId) { if (!__first) { __sb.Append(", "); } __first = false; __sb.Append("UserId: "); __sb.Append(UserId); } if (Password != null && __isset.password) { if (!__first) { __sb.Append(", "); } __first = false; __sb.Append("Password: "******", "); } __first = false; __sb.Append("SessionProperties: "); __sb.Append(SessionProperties == null ? "<null>" : SessionProperties.ToString()); } if (AppSignatureFingerprint != null && __isset.appSignatureFingerprint) { if (!__first) { __sb.Append(", "); } __first = false; __sb.Append("AppSignatureFingerprint: "); __sb.Append(AppSignatureFingerprint); } __sb.Append(")"); return(__sb.ToString()); }
/// <summary> /// cleans up any resource held by the plugin /// </summary> public void LdapEnd(SessionProperties props) { LdapServer serv = props.GetTrackedSingle <LdapServer>(); if (serv != null) { serv.Close(); } }
internal LidgrenAvailableSession(SessionType sessionType, int currentGamerCount, string hostName, int openPrivateSlots, int openPublicSlots, SessionProperties sessionProperties, TimeSpan averageRoundtripTime) { _sessionType = sessionType; _currentGamerCount = currentGamerCount; _hostName = hostName; _openPrivateSlots = openPrivateSlots; _openPublicSlots = openPublicSlots; _sessionProperties = sessionProperties; _averageRoundtripTime = averageRoundtripTime; }
public void SessionChange(System.ServiceProcess.SessionChangeDescription changeDescription, SessionProperties properties) { // Check that we're logging on, and that we're configured to do anything if (properties != null && changeDescription.Reason == System.ServiceProcess.SessionChangeReason.SessionLogon) { m_logger.DebugFormat("Attempting to map drive(s) in session: id={0}", changeDescription.SessionId); List<DriveMap> maps = Settings.GetMaps(); foreach( DriveMap map in maps ) { MapDrive(changeDescription.SessionId, map, properties); } } }
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; } }
public void BeginChain(SessionProperties properties) { m_logger.Debug("BeginChain"); try { SessionLogger m_sessionlogger = new SessionLogger(); properties.AddTrackedSingle<SessionLogger>(m_sessionlogger); } catch (Exception e) { m_logger.ErrorFormat("Failed to create SessionLogger: {0}", e); properties.AddTrackedSingle<SessionLogger>(null); } }
/// <summary> /// Creates a new DebugSession object. /// </summary> /// <param name="debuggerName">The name of the session debugger.</param> /// <param name="loadedExtensions">The names of the loaded extensions.</param> /// <param name="architecture">The executing machine architecture.</param> /// <param name="initialProperties">Initial session properties to set.</param> public DebugSession(string debuggerName, string[] loadedExtensions, Architecture architecture, SessionProperties initialProperties) : this() { if (initialProperties == null) throw new ArgumentNullException("initialProperties"); if (architecture == null) throw new ArgumentNullException("architecture"); this.debuggerName = debuggerName; this.extensionNames = loadedExtensions ?? new string[0]; this.architecture = architecture; this.properties = new SessionProperties(initialProperties); }
/// <summary> /// Converts a SessionProperties instance to the NetworkSessionProperties /// </summary> internal static NetworkSessionProperties ConvertToLiveSessionProperties(SessionProperties sessionProperties) { if (sessionProperties == null) return null; var networkSessionProperties = new NetworkSessionProperties(); for (int i = 0; i < sessionProperties.Count; i++) { networkSessionProperties[i] = sessionProperties[i]; } return networkSessionProperties; }
/// <summary> /// Converts a NetworkSessionProperties instance to the SessionProperties /// </summary> internal static SessionProperties ConvertFromLiveSessionProperties(NetworkSessionProperties networkSessionProperties) { if (networkSessionProperties == null) return null; var sessionProperties = new SessionProperties(); for (int i = 0; i < networkSessionProperties.Count; i++) { sessionProperties[i] = networkSessionProperties[i]; } return sessionProperties; }
public ConfigurationDialog() { this.InitializeComponent(); this.pages = new Dictionary<int, ConfigCategoryItem>(); // Create a temporary copy of the SessionProperties to allow // rolling back the changes. if (Application.Session != null) { this.tempProperties = new SessionProperties( Application.Session.Properties); } else this.tempProperties = new SessionProperties(); // Set the data context as the temporary session properties this.DataContext = this.tempProperties; }
public PluginDriver() { m_logger = LogManager.GetLogger(string.Format("PluginDriver:{0}", m_sessionId)); m_properties = new SessionProperties(m_sessionId); // Add the user information object we'll be using for this session UserInformation userInfo = new UserInformation(); m_properties.AddTrackedSingle<UserInformation>(userInfo); // Add the plugin tracking object we'll be using for this session PluginActivityInformation pluginInfo = new PluginActivityInformation(); pluginInfo.LoadedAuthenticationGatewayPlugins = PluginLoader.GetOrderedPluginsOfType<IPluginAuthenticationGateway>(); pluginInfo.LoadedAuthenticationPlugins = PluginLoader.GetOrderedPluginsOfType<IPluginAuthentication>(); pluginInfo.LoadedAuthorizationPlugins = PluginLoader.GetOrderedPluginsOfType<IPluginAuthorization>(); m_properties.AddTrackedSingle<PluginActivityInformation>(pluginInfo); m_logger.DebugFormat("New PluginDriver created"); }
public BooleanResult AuthorizeUser(SessionProperties properties) { UserInformation userInfo = properties.GetTrackedSingle<UserInformation>(); if (!ReferenceEquals(null, Settings.ApplicationID) && !ReferenceEquals(null, Settings.Secret)) { string applicationID = Util.GetSettingsString((string)Settings.ApplicationID); string secret = Util.GetSettingsString((string)Settings.Secret); string accountID = Util.GetSettingsString((string)Settings.AccountID); //m_logger.InfoFormat("ApplicationID: {0}", applicationID); //m_logger.InfoFormat("Secret: {0}", secret); //m_logger.InfoFormat("AccountID: {0}", accountID); Latch latch = new Latch(applicationID, secret); LatchResponse response = latch.Status(accountID); // One of the ugliest lines of codes I ever wrote, but quickest way to access the object without using json serialization try { Dictionary<string, object> operations = ((Dictionary<string, object>)response.Data["operations"]); Dictionary<string, object> appSettings = ((Dictionary<string, object>)operations[(applicationID)]); string status = ((string)appSettings["status"]); m_logger.InfoFormat("Latch status is {0}", status); if (status == "on") return new BooleanResult() { Success = true, Message = "Ready to go!" }; else return new BooleanResult() { Success = false, Message = "Latch is protecting this account!" }; } catch (Exception) { return new BooleanResult() { Success = true, Message = "Something went wrong, letting you in because I don't want to lock you out!" }; } } else { return new BooleanResult() { Success = false, Message = "Latch is not correctly configured." }; } }
internal DynamicSessionProperties(Expression exp, SessionProperties sessionProps) : base(exp, BindingRestrictions.Empty, sessionProps) { this.sessionProps = sessionProps; // Get the property info for the indexer: foreach (PropertyInfo prop in typeof(SessionProperties).GetProperties()) { var indexParams = prop.GetIndexParameters(); if (indexParams.Length == 1 && indexParams[0].ParameterType == typeof(String)) { this.indexer = prop; break; } } if (this.indexer == null) // Throw if we can't find the indexer { throw new MissingFieldException("Cannot create dynamic session properties: " + "the required indexer SessionProperties[System.String^] is missing."); } }
/// <summary> /// This constructor is used to create a temporary session exclusivly for the purpose of listening for Discovery messages /// </summary> internal LidgrenSession(SessionType sessionType, int maxGamers, int privateReservedSlots, SessionProperties sessionProperties) { _isHost = false; _sessionType = sessionType; _sessionProperties = sessionProperties; if (maxGamers > MaximumSupportedGamersInSession) throw new CoreException("Cannot create sessions for more than " + MaximumSupportedGamersInSession + " players."); else _maxGamers = maxGamers; _privateReservedSlots = privateReservedSlots; LidgrenSessionManager.Client.Start(); //LidgrenSessionManager.Client.Connect(serverHost, LidgrenSessionManager.ServerPort); _previousSecondBytesSent += LidgrenSessionManager.Client.Statistics.SentBytes; _previousSecondBytesReceived += LidgrenSessionManager.Client.Statistics.ReceivedBytes; _clientSessionState = SessionState.Lobby; _serverSessionState = SessionState.Lobby; }
public void SessionChange(System.ServiceProcess.SessionChangeDescription changeDescription, SessionProperties properties) { m_logger.DebugFormat("SessionChange({0}) - ID: {1}", changeDescription.Reason.ToString(), changeDescription.SessionId); //If SessionMode is enabled, send event to it. if ((bool)Settings.Store.SessionMode) { ILoggerMode mode = LoggerModeFactory.getLoggerMode(LoggerMode.SESSION); mode.Log(changeDescription, properties); } //If EventMode is enabled, send event to it. if ((bool)Settings.Store.EventMode) { ILoggerMode mode = LoggerModeFactory.getLoggerMode(LoggerMode.EVENT); mode.Log(changeDescription, properties); } //Close the connection if it's still open LoggerModeFactory.closeConnection(); }
static void Main(string[] args) { SessionProperties properties = new SessionProperties(new Guid("12345678-1234-1234-1234-123412341234")); UserInformation userInfo = new UserInformation(); userInfo.Username = "******"; userInfo.Email = "*****@*****.**"; userInfo.Fullname = "Gandalf The Gray"; userInfo.LoginScript = "net use x: \\lserver\bakasracky"; userInfo.Password = "******"; properties.AddTrackedSingle<UserInformation>(userInfo); PluginImpl plugin = new PluginImpl(); var authResult = plugin.AuthenticateUser(properties); Debug.Assert(authResult.Success == true, "auth should succeed!"); var gatewayResult = plugin.AuthenticatedUserGateway(properties); Debug.Assert(authResult.Success == true, "gateway should succeed!"); System.Console.Write("DONE"); }
public BooleanResult AuthenticatedUserGateway(SessionProperties properties) { // this method shall perform some other tasks ... UserInformation userInfo = properties.GetTrackedSingle<UserInformation>(); UInfo uinfo = HttpAccessor.getUserInfo(userInfo.Username); if (uinfo != null) { m_logger.DebugFormat("AuthenticatedUserGateway: Uinfo: {0}", uinfo.ToString()); foreach (string group in uinfo.groups) { userInfo.AddGroup(new GroupInformation() { Name = group }); } properties.AddTrackedSingle<UserInformation>(userInfo); // and what else ??? :) } return new BooleanResult() { Success = true }; }
public void InitTest() { // Default test settings, reset for each test Settings.Store.LdapHost = host; Settings.Store.LdapPort = port; Settings.Store.LdapTimeout = 10; Settings.Store.EncryptionMethod = (int)encMethod; Settings.Store.RequireCert = validateCert; Settings.Store.SearchDN = searchDN; Settings.Store.SetEncryptedSetting("SearchPW", searchPW); Settings.Store.GroupDnPattern = "cn=%g,ou=Group,dc=example,dc=com"; Settings.Store.GroupMemberAttrib = "memberUid"; Settings.Store.UseAuthBindForAuthzAndGateway = false; // Authentication Settings.Store.AllowEmptyPasswords = false; Settings.Store.DnPattern = "uid=%u,ou=People,dc=example,dc=com"; Settings.Store.DoSearch = false; Settings.Store.SearchFilter = ""; Settings.Store.SearchContexts = new string[] { }; // Authorization Settings.Store.GroupAuthzRules = new string[] { (new GroupAuthzRule(true)).ToRegString() }; Settings.Store.AuthzRequireAuth = false; Settings.Store.AuthzAllowOnError = true; // Gateway Settings.Store.GroupGatewayRules = new string[] { }; // Set up session props m_props = new SessionProperties(BogusSessionId); UserInformation userInfo = new UserInformation(); m_props.AddTrackedSingle<UserInformation>(userInfo); userInfo.Username = "******"; userInfo.Password = "******"; PluginActivityInformation actInfo = new PluginActivityInformation(); m_props.AddTrackedSingle<PluginActivityInformation>(actInfo); }
private LidgrenSession(string serverHost, SessionType sessionType, int maxGamers, int privateReservedSlots, SessionProperties sessionProperties, bool isHost) { _isHost = isHost; _sessionType = sessionType; _sessionProperties = sessionProperties; if (maxGamers > MaximumSupportedGamersInSession) throw new CoreException("Cannot create sessions for more than " + MaximumSupportedGamersInSession + " players."); else _maxGamers = maxGamers; _privateReservedSlots = privateReservedSlots; if (_isHost) { LidgrenSessionManager.Server.Start(); _previousSecondBytesSent = LidgrenSessionManager.Server.Statistics.SentBytes; _previousSecondBytesReceived = LidgrenSessionManager.Server.Statistics.ReceivedBytes; IdentifiedPlayer identifiedPlayer; for (int i = 0; i < 4; i++) { if (SessionManager.LocalPlayers.TryGetValue((PlayerIndex) Enum.ToObject(typeof (PlayerIndex), i), out identifiedPlayer)) { ((LidgrenIdentifiedPlayer) identifiedPlayer).SetIsHost(); break; } } } LidgrenSessionManager.Client.Start(); LidgrenSessionManager.Client.Connect(serverHost, LidgrenSessionManager.ServerPort); _previousSecondBytesSent += LidgrenSessionManager.Client.Statistics.SentBytes; _previousSecondBytesReceived += LidgrenSessionManager.Client.Statistics.ReceivedBytes; _clientSessionState = SessionState.Lobby; _serverSessionState = SessionState.Lobby; }
/// <summary> /// Creates a new instance /// </summary> /// <param name="availableSession">The Xbox Live AvailableNetworkSession instance</param> internal LiveAvailableSession(AvailableNetworkSession availableSession) { AvailableNetworkSession = availableSession; _sessionProperties = LiveSessionProperties.ConvertFromLiveSessionProperties(availableSession.SessionProperties); }
BooleanResult IPluginAuthentication.AuthenticateUser(SessionProperties properties) { try { m_logger.DebugFormat("AuthenticateUser({0})", properties.Id.ToString()); // Get user info, append domain if needed UserInformation userInfo = properties.GetTrackedSingle<UserInformation>(); bool appendDomain = (bool) Settings.Store.AppendDomain; string username; if ((bool)Settings.Store.AppendDomain) username = string.Format("{0}@{1}", userInfo.Username, (string)Settings.Store.Domain); else username = userInfo.Username; // Place credentials into a NetworkCredentials object NetworkCredential creds = new NetworkCredential(username, userInfo.Password); string server = Settings.Store.Server; int port = Convert.ToInt32((string)Settings.Store.Port); bool useSsl = Settings.Store.UseSsl; string protocol = Settings.Store.Protocol; //Connect to server Stream stream = getNetworkStream(server, port, useSsl); bool authenticated; m_logger.DebugFormat("Have network stream..."); //Authenticate based on protocol if (protocol == "POP3") authenticated = authPop3(stream, creds); else authenticated = authImap(stream, creds); if (authenticated) return new BooleanResult() { Success = true }; return new BooleanResult() { Success = false, Message = "Invalid username/password." }; } catch (FormatException e) { //Likely thrown if the port number can not be converted to an integer m_logger.ErrorFormat("Port number is not valid. Format exception: {0}", e); return new BooleanResult() { Success = false, Message = "Port number is not valid." }; } catch (EMailAuthException e) { if (e.InnerException != null) m_logger.ErrorFormat("Error: \"{0}\" caught because \"{1}\"", e.Message, e.InnerException.Message); else m_logger.ErrorFormat("Error: {0}", e.Message); return new BooleanResult() { Success = false, Message = e.Message }; } catch (Exception e) { m_logger.ErrorFormat("Error: {0}", e); return new BooleanResult { Success = false, Message = "Unspecified Error occurred. " + e.Message }; } }
private string getUsername(SessionProperties properties) { if (properties == null) return UNKNOWN_USERNAME; bool useModifiedName = Settings.Store.UseModifiedName; UserInformation userInfo = properties.GetTrackedSingle<UserInformation>(); if (useModifiedName) return userInfo.Username; else return userInfo.OriginalUsername; }
private string SessionLockEvent(int sessionId, SessionProperties properties) { bool okToLog = Settings.Store.EvtLock; string userName = ""; userName = getUsername(properties); if (userName == null) userName = UNKNOWN_USERNAME; if (okToLog) return string.Format("[{0}] Session lock user: {1}", sessionId, userName); return ""; }
/// <summary> /// Runs the rules against the username, modifying it for future plugins. /// If an IMatchRule is present, AuthorizeUser will only return true if /// the username matches the rule. /// </summary> /// <param name="properties"></param> /// <returns></returns> BooleanResult IPluginAuthorization.AuthorizeUser(SessionProperties properties) { try { m_logger.DebugFormat("AuthorizeUser({0})", properties.Id.ToString()); // Get user info UserInformation userInfo = properties.GetTrackedSingle<UserInformation>(); bool authorized = true; //By default, we don't authenticate string username = userInfo.Username; m_logger.DebugFormat("Start of Authorization, username: {0}", username); foreach (IUsernameRule rule in rules.list) { if (rule.stage == Stage.Authorization) { m_logger.DebugFormat("[Authorization] Checking rule: {0}", rule.ToString()); if (rule is IModifyRule) { IModifyRule mRule = (IModifyRule)rule; username = mRule.modify(username); m_logger.DebugFormat("Username modified: {0}", username); } else if (rule is IMatchRule) { //If the match rule fails, do not authorize authorized = ((IMatchRule)rule).match(username) ? authorized : false; m_logger.DebugFormat("Authorized? {0}", authorized); } } } //Set the changes to the username userInfo.Username = username; return new BooleanResult() { Success = authorized }; } catch (Exception e) { m_logger.ErrorFormat("Error running rules. {0}", e.Message); return new BooleanResult() { Success = false, Message = "Unable to modify username during authorization stage." }; } }
private string ConsoleDisconnectEvent(int sessionId, SessionProperties properties) { bool okToLog = Settings.Store.EvtConsoleDisconnect; if (okToLog) return string.Format("[{0}] Console disconnect", sessionId); return ""; }
private string LogoffEvent(int sessionId, SessionProperties properties) { bool okToLog = Settings.Store.EvtLogoff; string userName = ""; userName = getUsername(properties); // Delete the username from the cache because we are logging off? if (userName == null) userName = UNKNOWN_USERNAME; if (okToLog) return string.Format("[{0}] Logoff user: {1}", sessionId, userName); return ""; }
//The following functions determine if the specified event should be logged, and returns the logging message if so private string LogonEvent(int sessionId, SessionProperties properties) { bool okToLog = Settings.Store.EvtLogon; // Get the username string userName = getUsername(properties); // Since the username is not available at logoff time, we cache it // (tied to the session ID) so that we can get it back at the logoff // event. //if (userName != null) // m_usernameCache.Add(sessionId, userName); if (userName == null) userName = UNKNOWN_USERNAME; if (okToLog) return string.Format("[{0}] Logon user: {1}", sessionId, userName); return ""; }
private string RemoteConnectEvent(int sessionId, SessionProperties properties) { bool okToLog = Settings.Store.EvtRemoteConnect; string userName = ""; userName = getUsername(properties); if (userName == null) userName = UNKNOWN_USERNAME; if (okToLog) return string.Format("[{0}] Remote connect user: {1}", sessionId, userName); return ""; }
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; } }
public BooleanResult ChangePassword(SessionProperties properties, ChangePasswordPluginActivityInfo pluginInfo) { return new BooleanResult() { Success = true, Message = "Success from the sample plugin" }; }