public AuthControllerTests()
        {
            string apiKey = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI1YTE1NDNjOC00YzhhLTQ1M2EtOThjNS1kYmE1MTk4NjFlYWYiLCJzdWIiOiJCT1NBcGlLZXkiLCJpYXQiOjE1NzA1NjYwMzcsImFjY291bnQiOiIzMGM3NjkxMC1hYzU5LTRjOWItYmUyZS1kNGQ3OGJmZTBjZDAiLCJwcm9qZWN0IjoiM2RhY2FhZDQtYzE1ZC00NmY3LTk5YjktM2I3NDQ2MjVmYTdiIiwidGVuYW50IjoiNGU1MGNmNDItMzE4MS00N2RmLTk0ZGQtNzE5NTVlNmVmOTY1In0.ebHQCuto1BL3U1_xh8tIJdKqcv9fGMj43icx1edQ0yc";

            HttpClient httpClientAuth = new HttpClient();

            httpClientAuth.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey);
            httpClientAuth.BaseAddress = new Uri("https://apis.dev.bosframework.com/auth/odata");
            AuthClient authClient = new AuthClient(httpClientAuth);

            HttpClient httpClientIA = new HttpClient();

            httpClientIA.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey);
            httpClientIA.BaseAddress = new Uri("https://apis.dev.bosframework.com/ia/odata");
            IAClient iaClient = new IAClient(httpClientIA);

            HttpClient httpClientEmail = new HttpClient();

            httpClientEmail.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey);
            httpClientEmail.BaseAddress = new Uri("https://apis.dev.bosframework.com/email/odata");
            EmailClient emailClient = new EmailClient(httpClientEmail);

            _bosAuthClient  = authClient;
            _bosIAClient    = iaClient;
            _bosEmailClient = emailClient;
            _configuration  = null;
        }
コード例 #2
0
        private static void AuthChallengeRequestCallback(IAuthClient client, Ban clientBan)
        {
            if (clientBan != null)
            {
                if (clientBan.IPMinimum != 0 && clientBan.IPMaximum != 0)
                {
                    if (clientBan.Expires <= DateTime.Now)
                    {
                        // remove the ban since it's expired
                        client.Server.EnqueueTask(QueryFactory.CreateNonResultQuery(clientBan.DeleteAndFlush));
                    }
                    else
                    {
                        OnLoginError(client, AccountStatus.Failure);
                        return;
                    }
                }
            }

            if (client.Server.IsAccountLoggedIn(client.CurrentUser))
            {
                OnLoginError(client, AccountStatus.AccountInUse);
            }
            else
            {
                var acctQuery = QueryFactory.CreateResultQuery(
                    () => AccountMgr.GetAccount(client.CurrentUser),
                    QueryAccountCallback,
                    client
                    );
                client.Server.EnqueueTask(acctQuery);
            }
        }
コード例 #3
0
 public LoginModel(SignInManager <IdentityUser> signInManager, ILogger <LoginModel> logger,
                   IAuthClient authClient)
 {
     _signInManager = signInManager;
     _logger        = logger;
     _authClient    = authClient;
 }
コード例 #4
0
 public IActionResult SetAuthClient()
 {
     try
     {
         var token = _contextAccessor.HttpContext.Session.GetString("ApplicationToken");
         if (token != null)
         {
             var tokenResult1 = JsonConvert.DeserializeObject <TokenResponse>(token);
             if (tokenResult1 != null)
             {
                 string bosServiceURL = _configuration["BOS:ServiceBaseURL"];
                 var    client        = new HttpClient();
                 client.BaseAddress = new Uri("" + bosServiceURL + _configuration["BOS:AuthRelativeURL"]);
                 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult1.data);
                 _bosAuthClient = new AuthClient(client);
                 return(null);
             }
             else
             {
                 return(RedirectToAction("SignOut", "Auth"));
             }
         }
         else
         {
             return(RedirectToAction("SignOut", "Auth"));
         }
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
コード例 #5
0
 public LoginModel(ILogger <LoginModel> logger,
                   IAuthClient authClient, IIAClient iaClient)
 {
     _logger     = logger;
     _authClient = authClient;
     _iaClient   = iaClient;
 }
コード例 #6
0
        /// <summary>
        /// Client passed login challenge and can be logged in
        /// </summary>
        /// <param name="client"></param>
        private static void LoginClient(IAuthClient client)
        {
            var acc = client.Account;

            if (acc == null)
            {
                //Resync accounts first
                AccountMgr.Instance.Resync();

                // Pass and username are identical so an Account can be auto-created
                // the corresponding check happened before
                s_log.Debug(resources.AutocreatingAccount, client.AccountName);

                if (AccountMgr.DoesAccountExist(client.AccountName))
                {
                    // account was already created
                    SendAuthProofErrorReply(client, AccountStatus.Failure);
                    return;
                }
                client.Account = acc = AutoCreateAccount(client);
            }

            var authInfo = new AuthenticationInfo
            {
                SessionKey        = client.Authenticator.SRP.SessionKey.GetBytes(40),
                Salt              = client.Authenticator.SRP.Salt.GetBytes(32),
                Verifier          = client.Authenticator.SRP.Verifier.GetBytes(),
                SystemInformation = ClientInformation.Serialize(client.Info)
            };

            client.Server.StoreAuthenticationInfo(client.AccountName, authInfo);

            acc.OnLogin(client);
            SendAuthProofSuccessReply(client);
        }
コード例 #7
0
        private static void QueryAccountCallback(IAuthClient client, Account acct)
        {
            if (!client.IsConnected)
            {
                return;
            }

            var accName = client.AccountName;

            if (acct == null)
            {
                // Account doesn't exist yet -> Check for auto creation
                if (AuthServerConfiguration.AutocreateAccounts)
                {
                    if (!AccountMgr.NameValidator(ref accName))
                    {
                        OnLoginError(client, AccountStatus.InvalidInformation);
                        return;
                    }

                    // Fill in this client's info with the username they gave.
                    // We have to go through the authentication phase, and if
                    // the password ends up matching the username, we know it's
                    // an autocreation attempt.

                    var passHash = SecureRemotePassword.GenerateCredentialsHash(accName, accName);

                    client.Authenticator = new Authenticator(new SecureRemotePassword(accName, passHash, true));
                    SendAuthChallengeSuccessReply(client);
                }
                else
                {
                    OnLoginError(client, AccountStatus.InvalidInformation);
                }
            }
            else
            {
                // check if Account may be used
                if (acct.CheckActive())
                {
                    client.Account       = acct;
                    client.Authenticator = new Authenticator(new SecureRemotePassword(accName, acct.Password, true));
                    SendAuthChallengeSuccessReply(client);
                }
                else
                {
                    // Account has been deactivated
                    if (client.Account.StatusUntil == null)
                    {
                        // temporarily suspended
                        OnLoginError(client, AccountStatus.AccountBanned);
                    }
                    else
                    {
                        // deactivated
                        OnLoginError(client, AccountStatus.AccountFrozen);
                    }
                }
            }
        }
コード例 #8
0
        /// <summary>
        /// Check for bans and already logged in Accounts, else continue the journey
        /// </summary>
        /// <param name="client"></param>
        private static void AuthChallengeRequestCallback(IAuthClient client)
        {
            if (!client.IsConnected)
            {
                // Client disconnected in the meantime
                return;
            }

            if (BanMgr.IsBanned(client.ClientAddress))
            {
                OnLoginError(client, AccountStatus.AccountBanned);
            }
            //else if (client.Server.IsAccountLoggedIn(client.AccountName))
            //{
            //    OnLoginError(client, AccountStatus.AccountInUse);
            //}
            else
            {
                var acctQuery = new Action(() =>
                {
                    var acc = AccountMgr.GetAccount(client.AccountName);
                    QueryAccountCallback(client, acc);
                });

                AuthenticationServer.IOQueue.AddMessage(acctQuery);
            }
        }
コード例 #9
0
 public AuthViewModel(IAuthClient authBaseAPI, IBaseTokenService baseTokenService, INavigateWindow navigateWindow, INotificationService notificationService)
 {
     this.navigateWindow      = navigateWindow;
     this.authBaseAPI         = authBaseAPI;
     this.baseTokenService    = baseTokenService;
     this.notificationService = notificationService;
 }
コード例 #10
0
        /// <summary>
        /// Called when the given client failed to login due to the given reason.
        /// Delays, fires the LoginFailed event and sends the reply.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="error"></param>
        public static void OnLoginError(IAuthClient client, AccountStatus error, bool silent)
        {
            if (!silent)
            {
                s_log.Debug("Client {0} failed to login: {1}", client, error);
            }

            LoginFailInfo failInfo;

            if (!failedLogins.TryGetValue(client.ClientAddress, out failInfo))
            {
                failedLogins.Add(client.ClientAddress, failInfo = new LoginFailInfo(DateTime.Now));
            }
            else
            {
                failInfo.LastAttempt = DateTime.Now;
                failInfo.Count++;
                // TODO: Ban, if trying too often?
            }

            // delay the reply
            ThreadPool.RegisterWaitForSingleObject(failInfo.Handle, (state, timedOut) =>
            {
                if (client.IsConnected)
                {
                    var evt = LoginFailed;
                    if (evt != null)
                    {
                        evt(client, error);
                    }

                    SendAuthProofErrorReply(client, error);
                }
            }, null, FailedLoginDelay, true);
        }
コード例 #11
0
        /// <summary>
        /// Called when the given client failed to login due to the given reason.
        /// Delays, fires the LoginFailed event and sends the reply.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="error"></param>
        private static void OnLoginError(IAuthClient client, AccountStatus error)
        {
            TimeoutWaitHandle delayHandle;

            if (!failedLogins.TryGetValue(client.ClientAddress, out delayHandle))
            {
                failedLogins.Add(client.ClientAddress, delayHandle = new TimeoutWaitHandle(DateTime.Now));
            }
            else
            {
                delayHandle.LastAttempt = DateTime.Now;
            }

            ThreadPool.RegisterWaitForSingleObject(delayHandle.Handle, (state, timedOut) => {
                if (client.IsConnected)
                {
                    var evt = LoginFailed;
                    if (evt != null)
                    {
                        evt(client, error);
                    }
                    SendAuthProofErrorReply(client, error);
                }
            }, null, LoginFailedDelay, true);
        }
コード例 #12
0
 public static void SendAuthReconnectChallenge(IAuthClient client)
 {
     using (var packet = new AuthPacketOut(AuthServerOpCode.AUTH_RECONNECT_CHALLENGE))
     {
         client.Authenticator.WriteReconnectChallenge(packet);
     }
 }
コード例 #13
0
        public OsmApiEnder(ILogger logger, string baseAddress, string userName, string password, TagsCollectionBase tags)
        {
            var factory = new ClientsFactory(logger, new HttpClient(), baseAddress);

            Client = factory.CreateBasicAuthClient(userName, password);
            Tags   = tags;
        }
コード例 #14
0
        private static void LoadRealmList(IAuthClient client)
        {
            var packet = new OutgoingAuthPacket(AuthenticationCmd.CMD_REALM_LIST);

            packet.Position += 2;
            packet.Write(0);       // unknown

            packet.Write((byte)1); // # realms, to be repalced with actual number

            packet.Write(0);
            packet.WriteByte(0x40);
            packet.WriteCString("Auuuuuub");
            packet.WriteCString("127.0.0.1:8085");
            packet.WriteFloat(2);
            packet.WriteByte(0x00);
            packet.WriteByte(0x01);
            packet.WriteByte(0x00);

            packet.Write((short)0x0002);

            packet.Position = 1;                         // set the stream offset to write packet size
            packet.Write((short)packet.TotalLength - 3); // write packet size

            client.Send(packet);
        }
コード例 #15
0
        public AuthControllerTests()
        {
            var    config    = new ConfigurationBuilder().AddJsonFile("appsettings.test.json").Build();
            var    bosAPIkey = config["BOS:APIkey"];
            string baseURL   = config["BOS:ServiceBaseURL"];

            HttpClient httpClientAuth = new HttpClient();

            httpClientAuth.BaseAddress = new Uri(baseURL + config["BOS:AuthRelativeURL"]);
            httpClientAuth.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", bosAPIkey);
            AuthClient authClient = new AuthClient(httpClientAuth);

            _bosAuthClient = authClient;

            HttpClient httpClientIA = new HttpClient();

            httpClientIA.BaseAddress = new Uri(baseURL + config["BOS:IARelativeURL"]);
            httpClientIA.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", bosAPIkey);
            IAClient iaClient = new IAClient(httpClientIA);

            _bosIAClient = iaClient;

            HttpClient httpClientEmail = new HttpClient();

            httpClientEmail.BaseAddress = new Uri(baseURL + config["BOS:EmailRelativeURL"]);
            httpClientEmail.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", bosAPIkey);
            EmailClient emailClient = new EmailClient(httpClientEmail);

            _bosEmailClient = emailClient;

            _configuration = null;
        }
コード例 #16
0
        private static void HandleLogonProof(IAuthClient client, IncomingAuthPacket packet)
        {
            client.Authenticator.SRP.PublicEphemeralValueA = packet.ReadBigInteger(32);
            BigInteger proof = packet.ReadBigInteger(20);

            SendLogonProofReply(client);
        }
コード例 #17
0
        public static void AuthChallengeRequest(IAuthClient client, AuthPacketIn packet)
        {
            packet.SkipBytes(6);             // Skip game name and packet size

            client.ClientInfo = ClientInformation.ReadFromPacket(packet);

            if (!WCellInfo.RequiredVersion.IsSupported(client.ClientInfo.Version))
            {
                OnLoginError(client, AccountStatus.WrongBuild);
            }
            else
            {
                string accName = packet.ReadPascalString();

                s_log.Debug(Resources.AccountChallenge, accName);

                client.CurrentUser = accName;

                var banQuery = QueryFactory.CreateResultQuery
                               (
                    () => Ban.GetBan(client.ClientAddress),
                    AuthChallengeRequestCallback,
                    client
                               );

                client.Server.EnqueueTask(banQuery);
            }
        }
コード例 #18
0
ファイル: Account.cs プロジェクト: remixod/netServer
		public virtual void OnLogin(IAuthClient client)
		{
			var addr = client.ClientAddress;
			if (addr == null)
			{
				// client disconnected
				return;
            }

            LastIP = addr.GetAddressBytes();
            LastLogin = DateTime.Now;
			Locale = client.Info.Locale;
			ClientVersion = client.Info.Version.ToString();
			//UpdateAndFlush(); TODO: I believe this saves the value to the database

			AuthCommandHandler.AutoExecute(this);

			var evt = LoggedIn;
			if (evt != null)
			{
				evt(this, client);
			}

			s_log.Info("Account \"{0}\" logged in from {1}.", Name, client.ClientAddress);
		}
コード例 #19
0
 public IdentityMvcService(IIdentityClient client, LocalStorage localStorage, ILogger <IdentityMvcService> logger, IAuthClient authClient)
 {
     _identityClient = client;
     _localStorage   = localStorage;
     _logger         = logger;
     _authClient     = authClient;
 }
コード例 #20
0
        internal void OnLogin(IAuthClient client)
        {
            var addr = client.ClientAddress;

            if (addr == null)
            {
                // client disconnected
                return;
            }

            LastIP        = addr.GetAddressBytes();
            LastLogin     = DateTime.Now;
            Locale        = client.Info.Locale;
            ClientVersion = client.Info.Version.ToString();
            UpdateAndFlush();

            AuthCommandHandler.AutoExecute(this);

            var evt = LoggedIn;

            if (evt != null)
            {
                evt(this, client);
            }

            s_log.Info("Account \"{0}\" logged in from {1}.", Name, client.ClientAddress);
        }
コード例 #21
0
 public Function1(
     IAuthClient auth,
     IWebApiRequest apiReq
     )
 {
     _auth   = auth;
     _apiReq = apiReq;
 }
コード例 #22
0
 public UsersController(IAuthClient authClient, IEmailClient bosEmailClient, IConfiguration configuration, IHttpContextAccessor contextAccessor)
 {
     _bosAuthClient   = authClient;
     _bosEmailClient  = bosEmailClient;
     _configuration   = configuration;
     _contextAccessor = contextAccessor;
     Logger           = new Logger();
 }
コード例 #23
0
 public static void SendAuthReconnectProof(IAuthClient client)
 {
     using (var packet = new AuthPacketOut(AuthServerOpCode.AUTH_RECONNECT_PROOF))
     {
         packet.Write((byte)0);                // error
         packet.Write((short)0);
     }
 }
コード例 #24
0
 public AuthController(IAuthClient authClient, IIAClient iaClient, IEmailClient emailClient, IConfiguration configuration)
 {
     _bosAuthClient  = authClient;
     _bosIAClient    = iaClient;
     _bosEmailClient = emailClient;
     _configuration  = configuration;
     Logger          = new Logger();
 }
コード例 #25
0
        public RocketClient(IAuthClient authClient, IConfiguration configuration, ILogger logger, IHttpHelperClient http)
        {
            this.authClient = authClient;
            this.logger     = logger;
            this.http       = http;

            rocketApiUrl = configuration["RocketApi:Url"];
        }
コード例 #26
0
        public UsersController(IAuthClient authClient, IEmailClient bosEmailClient, IConfiguration configuration)
        {
            _bosAuthClient  = authClient;
            _bosEmailClient = bosEmailClient;
            _configuration  = configuration;

            Logger = new Logger();
        }
コード例 #27
0
        public ExasClient(IConfiguration config, IAuthClient authClient)
        {
            ExasBaseUrl         = config["Exas:BaseUri"];
            ExasSubscriptionKey = config["Exas:SubscriptionKey"];

            DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", ExasSubscriptionKey);
            auth = authClient;
        }
コード例 #28
0
 public AuthController(IAuthClient authClient, IIAClient iaClient, IEmailClient emailClient, IConfiguration configuration, IHttpContextAccessor contextAccessor)
 {
     _bosAuthClient   = authClient;
     _bosIAClient     = iaClient;
     _bosEmailClient  = emailClient;
     _configuration   = configuration;
     _contextAccessor = contextAccessor;
     Logger           = new Logger();
 }
コード例 #29
0
 public RegisterModel(IConfiguration configuration,
                      ILogger <RegisterModel> logger,
                      IEmailSender emailSender, IAuthClient authClient)
 {
     _authClient  = authClient;
     _logger      = logger;
     _emailSender = emailSender;
     AccessToken  = configuration["BOSApiKey"];
 }
コード例 #30
0
        public static DelegatingHandler[] GetApiHandlers(IAuthClient auth)
        {
            var options = Options.Create(new BankClientOptions());

            return(new DelegatingHandler[]
            {
                new BankAuthHandler(null, options, new AzureServiceTokenProvider(), auth, new CachingService())
            });
        }
コード例 #31
0
 public BetfairFetchingService(ICompetitionsService compsService, IEventsService eventsService, IMarketsService marketsService, IMarketBooksService marketBooksService, IAuthClient authClient, IKeepAliveClient keepAliveClient)
 {
     _compsService       = compsService;
     _eventsService      = eventsService;
     _marketsService     = marketsService;
     _marketBooksService = marketBooksService;
     _authClient         = authClient;
     _keepAliveClient    = keepAliveClient;
 }
コード例 #32
0
		/// <summary>
		/// Sends an authentication challenge error to the client.
		/// </summary>
		/// <param name="client">the client</param>
		/// <param name="error">the authentication challenge error to send</param>
		public static void SendAuthChallengeErrorReply(IAuthClient client, AccountStatus error)
		{
			using (var packet = new AuthPacketOut(AuthServerOpCode.AUTH_LOGON_CHALLENGE))
			{
				packet.Write((byte)0x00);
				packet.Write((byte)error);

				client.Send(packet);
			}
		}
コード例 #33
0
		/// <summary>
		/// Sends an authentication challenge success reply to the client.
		/// </summary>
		/// <param name="client">the client</param>
		public static void SendAuthChallengeSuccessReply(IAuthClient client)
		{
			using (var packet = new AuthPacketOut(AuthServerOpCode.AUTH_LOGON_CHALLENGE))
			{
				packet.Write((byte)AccountStatus.Success);
				// Grunt command
				packet.Write((byte)0x00);

				client.Authenticator.WriteServerChallenge(packet);

                //var rand = new BigInteger(new Random(Environment.TickCount), 128);
                //packet.WriteBigInt(rand, 16);
                Random rand = new Random(Environment.TickCount);
                byte[] randbytes = new byte[16];              
                rand.NextBytes(randbytes);           
                packet.Write(randbytes);            
                
                const byte securityFlag = 0x0;
				packet.Write(securityFlag);

				// Require PIN input
                //if ((securityFlag & 0x1) == 0x1)
                //{
                //    packet.WriteInt(0);
                //    packet.Write(new byte[16]);
                //}

                // Matrix input
                //if ((securityFlag & 0x2) == 0x2)
                //{
                //    packet.Write((byte)0);
                //    packet.Write((byte)0);
                //    packet.Write((byte)0);
                //    packet.Write((byte)0);
                //    packet.Write(0UL);
                //}
				// Require Security Token input
                //if ((securityFlag & 0x4) == 0x4)
                //{
                //    packet.Write((byte)1);
                //}

				client.Send(packet);
			}
		}
コード例 #34
0
ファイル: Authentication.cs プロジェクト: KroneckerX/WCell
		public static void SendAuthReconnectChallenge(IAuthClient client)
		{
			using (var packet = new AuthPacketOut(AuthServerOpCode.AUTH_RECONNECT_CHALLENGE))
			{
				client.Authenticator.WriteReconnectChallenge(packet);
			}
		}
コード例 #35
0
		/// <summary>
		/// Called when the given client failed to login due to the given reason.
		/// Delays, fires the LoginFailed event and sends the reply.
		/// </summary>
		/// <param name="client"></param>
		/// <param name="error"></param>
		public static void OnLoginError(IAuthClient client, AccountStatus error)
		{
			OnLoginError(client, error, false);
		}
コード例 #36
0
		public static void SendAuthReconnectChallenge(IAuthClient client)
		{
			//using (var packet = new AuthPacketOut(AuthServerOpCode.AUTH_RECONNECT_CHALLENGE))
			//{
			//    //client.Authenticator.WriteReconnectChallenge(packet);
			//    client.Send(packet);
			//}

			// drop silently for now
			OnLoginError(client, AccountStatus.Failure, true);
		}
コード例 #37
0
		public static void AuthReconnectChallenge(IAuthClient client, AuthPacketIn packet)
		{
			SendAuthReconnectChallenge(client);
		}
コード例 #38
0
		/// <summary>
		/// Client passed login challenge and can be logged in
		/// </summary>
		/// <param name="client"></param>
		private static void LoginClient(IAuthClient client)
		{
			var acc = client.Account;

			if (acc == null)
			{
				// Pass and username are identical so an Account can be auto-created
				// the corresponding check happened before
				s_log.Debug(Resources.AutocreatingAccount, client.AccountName);

				if (AccountMgr.DoesAccountExist(client.AccountName))
				{
					// account was already created								
					SendAuthProofErrorReply(client, AccountStatus.Failure);
					return;
				}
				acc = AutoCreateAccount(client);
			}

			var authInfo = new AuthenticationInfo
			{
				SessionKey = client.Authenticator.SRP.SessionKey.GetBytes(40),
				Salt = client.Authenticator.SRP.Salt.GetBytes(32),
				Verifier = client.Authenticator.SRP.Verifier.GetBytes(),
				SystemInformation = ClientInformation.Serialize(client.Info)
			};
			client.Server.StoreAuthenticationInfo(client.AccountName, authInfo);

			acc.OnLogin(client);
			SendAuthProofSuccessReply(client);
		}
コード例 #39
0
		private static void QueryAccountCallback(IAuthClient client, Account acct)
		{
			if (!client.IsConnected)
			{
				return;
			}

			var accName = client.AccountName;

			if (acct == null)
			{
				// Account doesn't exist yet -> Check for auto creation
				if (AuthServerConfiguration.AutocreateAccounts)
				{
					if (!AccountMgr.NameValidator(ref accName))
					{
						OnLoginError(client, AccountStatus.InvalidInformation);
						return;
					}

					// Fill in this client's info with the username they gave.
					// We have to go through the authentication phase, and if 
					// the password ends up matching the username, we know it's
					// an autocreation attempt.

					var passHash = SecureRemotePassword.GenerateCredentialsHash(accName, accName);

					client.Authenticator = new Authenticator(new SecureRemotePassword(accName, passHash, true));
					SendAuthChallengeSuccessReply(client);
				}
				else
				{
					OnLoginError(client, AccountStatus.InvalidInformation);
				}
			}
			else
			{
				// check if Account may be used
				if (acct.CheckActive())
				{
					client.Account = acct;
					client.Authenticator = new Authenticator(new SecureRemotePassword(accName, acct.Password, true));
					SendAuthChallengeSuccessReply(client);
				}
				else
				{
 					// Account has been deactivated
					if (client.Account.StatusUntil == null)
					{
						// temporarily suspended
						OnLoginError(client, AccountStatus.AccountBanned);
					}
					else
					{
						// deactivated
						OnLoginError(client, AccountStatus.AccountFrozen);
					}
				}
			}
		}
コード例 #40
0
ファイル: RealmEntry.cs プロジェクト: NVN/WCell
        /// <summary>
        /// Writes the realm information to the specified packet.
        /// </summary>
        /// <param name="packet">the packet to write the realm info to</param>
        public void WriteRealm(IAuthClient client, AuthPacketOut packet)
        {
			var status = Status;
			var flags = Flags;
			var name = Name;
			if (!ClientVersion.IsSupported(client.Info.Version))
			{
				flags = RealmFlags.Offline;
				name += " [" + ClientVersion.BasicString + "]";
			}
            else if (Flags.HasFlag(RealmFlags.Offline) && Status == RealmStatus.Locked)
            {
            	var acc = client.Account;
                var role = acc.Role;
                if (role.IsStaff)
                {
                    status = RealmStatus.Open;
                	flags = RealmFlags.None;
                }
			}

            // TODO: Change char-count to amount of Characters of the querying account on this Realm
			packet.Write((byte)ServerType);
            packet.Write((byte)status);
            packet.Write((byte)flags);
            packet.WriteCString(name);
            packet.WriteCString(AddressString);
            packet.Write(Population);
            packet.Write(Chars);
            packet.Write((byte)Category);
            packet.Write((byte)0x00); // realm separator?
        }
コード例 #41
0
ファイル: Authentication.cs プロジェクト: KroneckerX/WCell
		private static void QueryAccountCallback(IAuthClient client, Account acct)
		{
			string accName = client.CurrentUser;

			if (acct == null)
			{
				if (AuthServerConfiguration.AutocreateAccounts)
				{
					// Fill in this client's info with the username they gave.
					// We have to go through the authentication phase, and if 
					// the password ends up matching the username, we know it's
					// an autocreation attempt.

					client.IsAutocreated = true;

					var passHash = new BigInteger(SecureRemotePassword.GenerateCredentialsHash(accName, accName));

					client.Authenticator = new Authenticator(new SecureRemotePassword(accName, passHash, true));
					SendAuthChallengeSuccessReply(client);
				}
				else
				{
					s_log.Debug(Resources.AccountNotFound, accName);

					OnLoginError(client, AccountStatus.InvalidInformation);
				}
			}
			else
			{
				// check if Account may be used
				if (acct.Status != AccountStatus.Success)
				{
					SendAuthChallengeErrorReply(client, acct.Status);
				}
				else
				{
					client.Authenticator = new Authenticator(new SecureRemotePassword(accName, acct.Password, true));
					acct.OnLogin(client);
				}
			}
		}
コード例 #42
0
ファイル: AuthPacketMessage.cs プロジェクト: KroneckerX/WCell
		public AuthPacketMessage(Action<IAuthClient, AuthPacketIn> handler, IAuthClient client, AuthPacketIn packet)
		{
			m_handler = handler;
			m_client = client;
			m_packet = packet;
		}
コード例 #43
0
ファイル: Authentication.cs プロジェクト: KroneckerX/WCell
		public static void AuthProofRequest(IAuthClient client, AuthPacketIn packet)
		{
			if (client.Authenticator == null)
			{
				client.Server.DisconnectClient(client);
			}
			else
			{
				if (client.Authenticator.IsClientProofValid(packet))
				{
					if (client.IsAutocreated)
					{
						// Their stuff matched, which means they gave us the same password
						// as their username, which is what must occur to autocreate. Create
						// the account for them before proceeding.

						s_log.Debug(Resources.AutocreatingAccount, client.CurrentUser);

						string role;
						if (IPAddress.IsLoopback(client.ClientAddress))
						{
							// local users get the highest role
							role = RoleGroupInfo.HighestRole.Name;
						}
						else
						{
							// remote users get default role
							role = AuthServerConfiguration.DefaultRole;
						}

						var acctCreateQuery = QueryFactory.CreateResultQuery(
							() => AccountMgr.Instance.CreateAccount(
							          client.CurrentUser,
							          client.Authenticator.SRP.Credentials.GetBytes(20),
							          null,
							          role,
							          ClientId.Wotlk
							          ),
							AutocreateAccountCallback,
							client
							);

						client.Server.EnqueueTask(acctCreateQuery);
					}
					else
					{
						// The following was sent twice
						var authInfo = new AuthenticationInfo {
							SessionKey = client.Authenticator.SRP.SessionKey.GetBytes(40),
							Salt = client.Authenticator.SRP.Salt.GetBytes(32),
							Verifier = client.Authenticator.SRP.Verifier.GetBytes(),
							SystemInformation = ClientInformation.Serialize(client.ClientInfo)
						};

						client.Server.StoreAuthenticationInfo(client.CurrentUser, authInfo);

						SendAuthProofSuccessReply(client);
					}
				}
				else
				{
					s_log.Debug(Resources.InvalidClientProof, client.CurrentUser);

					OnLoginError(client, AccountStatus.InvalidInformation);
				}
			}
		}
コード例 #44
0
ファイル: Authentication.cs プロジェクト: KroneckerX/WCell
		private static void AutocreateAccountCallback(IAuthClient client, Account acct)
		{
			if (acct == null)
			{
				OnLoginError(client, AccountStatus.InvalidInformation);

				return;
			}

			var authInfo = new AuthenticationInfo {
				SessionKey = client.Authenticator.SRP.SessionKey.GetBytes(40),
				Salt = client.Authenticator.SRP.Salt.GetBytes(32),
				Verifier = client.Authenticator.SRP.Verifier.GetBytes(),
				SystemInformation = ClientInformation.Serialize(client.ClientInfo)
			};

			client.Server.StoreAuthenticationInfo(client.CurrentUser, authInfo);

			SendAuthProofSuccessReply(client);
		}
コード例 #45
0
ファイル: Authentication.cs プロジェクト: KroneckerX/WCell
		public static void AuthReconnectProof(IAuthClient client, AuthPacketIn packet)
		{
			AuthenticationInfo authInfo;
			if (AuthenticationServer.Instance.GetAuthenticationInfo(client.CurrentUser, out authInfo))
			{
				if (client.Authenticator.IsReconnectProofValid(packet, authInfo))
				{
					SendAuthReconnectProof(client);
				}
			}

		}
コード例 #46
0
		public static void AuthChallengeRequest(IAuthClient client, AuthPacketIn packet)
		{
			packet.SkipBytes(6); // Skip game name and packet size

			client.Info = ClientInformation.ReadFromPacket(packet);

			// Account-names are always sent upper-case by the client (make sure, the tradition is kept alive)
			var accName = packet.ReadPascalString().ToUpper();

			s_log.Debug(Resources.AccountChallenge, accName);

			client.AccountName = accName;
			AuthenticationServer.Instance.AddMessage(new Message1<IAuthClient>(client, AuthChallengeRequestCallback));
		}
コード例 #47
0
		/// <summary>
		/// Check for bans and already logged in Accounts, else continue the journey
		/// </summary>
		/// <param name="client"></param>
		private static void AuthChallengeRequestCallback(IAuthClient client)
		{
			if (!client.IsConnected)
			{
				// Client disconnected in the meantime
				return;
			}

			if (BanMgr.IsBanned(client.ClientAddress))
			{
				OnLoginError(client, AccountStatus.AccountBanned);	
			}
			//else if (client.Server.IsAccountLoggedIn(client.AccountName))
			//{
			//    OnLoginError(client, AccountStatus.AccountInUse);
			//}
			else
			{
			    var acctQuery = new Action(() =>
			    {
			        var acc = AccountMgr.GetAccount(client.AccountName);
			        QueryAccountCallback(client, acc);
			    });

				AuthenticationServer.Instance.AddMessage(acctQuery);
			}
		}
コード例 #48
0
ファイル: RealmEntry.cs プロジェクト: remixod/netServer
 public static void RealmListRequest(IAuthClient client, PacketIn packet)
 {
     SendRealmList(client);
 }
コード例 #49
0
		public static void AuthProofRequest(IAuthClient client, AuthPacketIn packet)
		{
			if (client.Authenticator == null)
			{
				client.Server.DisconnectClient(client);
			}
			else if (client.IsConnected)
			{
                if (client.Authenticator.IsClientProofValid(packet))
                {
                    AuthenticationServer.Instance.AddMessage(() =>
                    {
                    	LoginClient(client);
                    });
                }
                else
                {
                    s_log.Debug(Resources.InvalidClientProof, client.AccountName);

                    OnLoginError(client, AccountStatus.InvalidInformation);
                }
			}
		}
コード例 #50
0
ファイル: RealmEntry.cs プロジェクト: remixod/netServer
        /// <summary>
        /// Sends the realm list to the client.
        /// </summary>
        /// <param name="client">the Session the incoming packet belongs to</param>
        public static void SendRealmList(IAuthClient client)
        {
			if (client.Account == null)
			{
				AuthenticationHandler.OnLoginError(client, AccountStatus.Failure);
				return;
			}
            using (var packet = new AuthPacketOut(AuthServerOpCode.REALM_LIST))
            {
            	packet.Position += 2;							// Packet length
                packet.Write(0);								// Unknown Value (0x0000)
            	//var cpos = packet.Position;
            	//packet.Position = cpos + 2;

            	packet.Write((short)AuthenticationServer.RealmCount);

            	//var count = 0;
                foreach (var realm in AuthenticationServer.Realms)
                {
                	// check for client version
                	//if (realm.ClientVersion.IsSupported(client.Info.Version))
                	realm.WriteRealm(client, packet);
                }

            	//packet.Write((byte)0x15);
                packet.Write((byte)0x10);
				packet.Write((byte)0x00);

				//packet.Position = cpos;
				//packet.WriteShort(count);

                packet.Position = 1;
                packet.Write((short)packet.TotalLength - 3);

                client.Send(packet);
            }
        }
コード例 #51
0
		/// <summary>
		/// Used to create accounts when using Auto-account creation
		/// </summary>
		/// <param name="client"></param>
		/// <returns></returns>
		private static Account AutoCreateAccount(IAuthClient client)
		{
			string role;
			if (IPAddress.IsLoopback(client.ClientAddress))
			{
				// local users get the highest role
				role = RoleGroupInfo.HighestRole.Name;
			}
			else
			{
				// remote users get default role
				role = AuthServerConfiguration.DefaultRole;
			}

			return AccountMgr.Instance.CreateAccount(
				client.AccountName,
				client.Authenticator.SRP.Credentials.GetBytes(20),
				null,
				role,
				ClientId.Wotlk
				);
		}
コード例 #52
0
ファイル: RealmEntry.cs プロジェクト: remixod/netServer
        /// <summary>
        /// Writes the realm information to the specified packet.
        /// </summary>
        /// <param name="packet">the packet to write the realm info to</param>
        public void WriteRealm(IAuthClient client, AuthPacketOut packet)
        {
			var status = Status;
			var flags = Flags;
			var name = Name;

			if (!ClientVersion.IsSupported(client.Info.Version))
			{
				// if client is not supported, flag realm as offline and append the required client version
				flags = RealmFlags.Offline;
				name += " [" + ClientVersion.BasicString + "]";
			}
            else if (Flags.HasFlag(RealmFlags.Offline) && Status == RealmStatus.Locked)
            {
				// let staff members join anyway
				if (client.Account.Role.IsStaff)
                {
                    status = RealmStatus.Open;
                	flags = RealmFlags.None;
                }
			}


			var addr = NetworkUtil.GetMatchingLocalIP(client.ClientAddress) ?? (object)Address;

			packet.Write((byte)ServerType);
            packet.Write((byte)status);
            packet.Write((byte)flags);
            packet.WriteCString(name);

			packet.WriteCString(GetAddress(addr.ToString()));

            packet.WriteFloat(Population);
			packet.Write(Chars); // TODO: Change to amount of Characters of the querying account on this Realm
			packet.Write((byte)Category);

			if (flags.HasFlag(RealmFlags.SpecifyBuild))
			{
				packet.Write(ClientVersion.Major);
				packet.Write(ClientVersion.Minor);
				packet.Write(ClientVersion.Revision);
				packet.Write(ClientVersion.Build);
			}

			packet.WriteByte(0x00);
        }
コード例 #53
0
		public static void AuthReconnectProof(IAuthClient client, AuthPacketIn packet)
		{
			var authInfo = AuthenticationServer.Instance.GetAuthenticationInfo(client.AccountName);
			if (authInfo != null)
			{
				if (client.Authenticator.IsReconnectProofValid(packet, authInfo))
				{
					SendAuthReconnectProof(client);
				}
			}

		}
コード例 #54
0
ファイル: Authentication.cs プロジェクト: KroneckerX/WCell
		private static void AuthChallengeRequestCallback(IAuthClient client, Ban clientBan)
		{
			if (clientBan != null)
			{
				if (clientBan.IPMinimum != 0 && clientBan.IPMaximum != 0)
				{
					if (clientBan.Expires <= DateTime.Now)
					{
						// remove the ban since it's expired
					    client.Server.EnqueueTask(QueryFactory.CreateNonResultQuery(clientBan.DeleteAndFlush));
					}
					else
					{
						OnLoginError(client, AccountStatus.Failure);
						return;
					}
				}
			}

			if (client.Server.IsAccountLoggedIn(client.CurrentUser))
			{
				OnLoginError(client, AccountStatus.AccountInUse);
			}
			else
			{
				var acctQuery = QueryFactory.CreateResultQuery(
				    () => AccountMgr.GetAccount(client.CurrentUser),
												QueryAccountCallback,
												client
											);
				client.Server.EnqueueTask(acctQuery);
			}
		}
コード例 #55
0
		public static void SendAuthReconnectProof(IAuthClient client)
		{
			using (var packet = new AuthPacketOut(AuthServerOpCode.AUTH_RECONNECT_PROOF))
			{
				packet.Write((byte)0);// error
				packet.Write((short)0);
                client.Send(packet);
			}
		}
コード例 #56
0
ファイル: Authentication.cs プロジェクト: KroneckerX/WCell
		public static void AuthChallengeRequest(IAuthClient client, AuthPacketIn packet)
		{
			packet.SkipBytes(6); // Skip game name and packet size

			client.ClientInfo = ClientInformation.ReadFromPacket(packet);

			if (!WCellInfo.RequiredVersion.IsSupported(client.ClientInfo.Version))
			{
				OnLoginError(client, AccountStatus.WrongBuild);
			}
			else
			{
				string accName = packet.ReadPascalString();

				s_log.Debug(Resources.AccountChallenge, accName);

				client.CurrentUser = accName;

				var banQuery = QueryFactory.CreateResultQuery
					(
				    () => Ban.GetBan(client.ClientAddress),
					AuthChallengeRequestCallback,
					client
					);

				client.Server.EnqueueTask(banQuery);
			}
		}
コード例 #57
0
		/// <summary>
		/// Called when the given client failed to login due to the given reason.
		/// Delays, fires the LoginFailed event and sends the reply.
		/// </summary>
		/// <param name="client"></param>
		/// <param name="error"></param>
		public static void OnLoginError(IAuthClient client, AccountStatus error, bool silent)
		{
			if (!silent)
			{
				s_log.Debug("Client {0} failed to login: {1}", client, error);
			}

			LoginFailInfo failInfo;
			if (!failedLogins.TryGetValue(client.ClientAddress, out failInfo))
			{
				failedLogins.Add(client.ClientAddress, failInfo = new LoginFailInfo(DateTime.Now));
			}
			else
			{
				failInfo.LastAttempt = DateTime.Now;
				failInfo.Count++;
				// TODO: Ban, if trying too often?
			}

			// delay the reply
			ThreadPool.RegisterWaitForSingleObject(failInfo.Handle, (state, timedOut) => {
				if (client.IsConnected)
				{
					var evt = LoginFailed;
					if (evt != null)
					{
						evt(client, error);
					}

					SendAuthProofErrorReply(client, error);
				}
			}, null, FailedLoginDelay, true);
		}
コード例 #58
0
ファイル: PmpSdk.cs プロジェクト: jokecamp/pmp.sdk.csharp
 public PmpSdk(string uri, IAuthClient authClient)
 {
     _uri = uri;
     _authClient = authClient;
 }
コード例 #59
0
		/// <summary>
		/// Sends an authentication proof success reply to the client.
		/// </summary>
		/// <param name="client">the client</param>
		public static void SendAuthProofSuccessReply(IAuthClient client)
		{
			using (var packet = new AuthPacketOut(AuthServerOpCode.AUTH_LOGON_PROOF))
			{
				packet.Write((byte)AccountStatus.Success);
				client.Authenticator.WriteServerProof(packet);

				packet.WriteInt(0);
				packet.WriteInt(0);
				packet.WriteShort(0);

				client.Send(packet);
			}
		}
コード例 #60
0
ファイル: Authentication.cs プロジェクト: KroneckerX/WCell
		/// <summary>
		/// Called when the given client failed to login due to the given reason.
		/// Delays, fires the LoginFailed event and sends the reply.
		/// </summary>
		/// <param name="client"></param>
		/// <param name="error"></param>
		private static void OnLoginError(IAuthClient client, AccountStatus error)
		{
			TimeoutWaitHandle delayHandle;
			if (!failedLogins.TryGetValue(client.ClientAddress, out delayHandle))
			{
				failedLogins.Add(client.ClientAddress, delayHandle = new TimeoutWaitHandle(DateTime.Now));
			}
			else
			{
				delayHandle.LastAttempt = DateTime.Now;
			}

			ThreadPool.RegisterWaitForSingleObject(delayHandle.Handle, (state, timedOut) => {
				if (client.IsConnected)
				{
					var evt = LoginFailed;
					if (evt != null)
					{
						evt(client, error);
					}
					SendAuthProofErrorReply(client, error);
				}
			}, null, LoginFailedDelay, true);
		}