public KeyboardInputProcessor()
        {
            _previousKeyboardState = new KeyboardState();
            _currentKeyboardState = new KeyboardState();

            KeyDictionary = new KeyDictionary();
        }
示例#2
0
        public bool Remove(TKey key)
        {
            if (TryGetValue(key, out var value))
            {
                KeyDictionary.Remove(key);
                ValueDictionary.Remove(value);
                return(true);
            }

            return(false);
        }
示例#3
0
        public bool Authenticate(string myUniqueId, SteamClient client, string myLoginKey)
        {
            mToken           = mTokenSecure = "";
            mSessionId       = Convert.ToBase64String(Encoding.UTF8.GetBytes(myUniqueId));
            mCookieContainer = new CookieContainer();

            using (var userAuth = WebAPI.GetInterface("ISteamUserAuth"))
            {
                // generate an AES session key
                var sessionKey = CryptoHelper.GenerateRandomBlock(32);

                // rsa encrypt it with the public key for the universe we're on
                byte[] cryptedSessionKey = null;
                using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(client.Universe)))
                {
                    cryptedSessionKey = rsa.Encrypt(sessionKey);
                }

                byte[] loginKey = new byte[20];
                Array.Copy(Encoding.ASCII.GetBytes(myLoginKey), loginKey, myLoginKey.Length);

                // aes encrypt the loginkey with our session key
                byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey);

                KeyValue authResult;

                try
                {
                    var dict = new System.Collections.Generic.Dictionary <string, object>()
                    {
                        { "steamid", client.SteamID.ConvertToUInt64() },
                        { "sessionkey", cryptedSessionKey },
                        { "encrypted_loginkey", cryptedLoginKey },
                        { "secure", true }
                    };

                    authResult = userAuth.Call(System.Net.Http.HttpMethod.Post, "AuthenticateUser", 1, dict);
                }
                catch (Exception)
                {
                    mToken = mTokenSecure = null;
                    return(false);
                }

                mToken       = authResult["token"].AsString();
                mTokenSecure = authResult["tokensecure"].AsString();

                mCookieContainer.Add(new Cookie("sessionid", mSessionId, string.Empty, mSteamCommunityDomain));
                mCookieContainer.Add(new Cookie("steamLogin", mToken, string.Empty, mSteamCommunityDomain));
                mCookieContainer.Add(new Cookie("steamLoginSecure", mTokenSecure, string.Empty, mSteamCommunityDomain));

                return(true);
            }
        }
示例#4
0
        public bool Remove(TKey key, TValue value)
        {
            if (Contains(key, value))
            {
                KeyDictionary.Remove(key);
                ValueDictionary.Remove(value);
                return(true);
            }

            return(false);
        }
示例#5
0
 private static void AddAnyRu(KeyDictionary dictionary, Keys key, object any, string letter)
 {
     if (dictionary.ContainsKey(key))
     {
         throw new Exception("Duplicate key: " + key);
     }
     else
     {
         dictionary.Add(key, AnyRu(any, letter));
     }
 }
示例#6
0
        ///<summary>
        /// Authenticate using SteamKit2 and ISteamUserAuth.
        /// This does the same as SteamWeb.DoLogin(), but without contacting the Steam Website.
        /// </summary>
        /// <remarks>Should this one doesnt work anymore, use <see cref="SteamWeb.DoLogin"/></remarks>
        /// <param name="myUniqueId">Id what you get to login.</param>
        /// <param name="client">An instance of a SteamClient.</param>
        /// <param name="myLoginKey">Login Key of your account.</param>
        /// <returns>A bool, which is true if the login was successful.</returns>
        public bool Authenticate(string myUniqueId, SteamClient client, string myLoginKey)
        {
            Token     = TokenSecure = "";
            SessionId = Convert.ToBase64String(Encoding.UTF8.GetBytes(myUniqueId));
            _cookies  = new CookieContainer();

            using (dynamic userAuth = WebAPI.GetInterface("ISteamUserAuth"))
            {
                // Generate an AES session key.
                var sessionKey = CryptoHelper.GenerateRandomBlock(32);

                // rsa encrypt it with the public key for the universe we're on
                byte[] cryptedSessionKey;
                using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(client.Universe)))
                {
                    cryptedSessionKey = rsa.Encrypt(sessionKey);
                }

                byte[] loginKey = new byte[20];
                Array.Copy(Encoding.ASCII.GetBytes(myLoginKey), loginKey, myLoginKey.Length);

                // AES encrypt the loginkey with our session key.
                byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey);

                KeyValue authResult;

                // Get the Authentification Result.
                try
                {
                    authResult = userAuth.AuthenticateUser(
                        steamid: client.SteamID.ConvertToUInt64(),
                        sessionkey: HttpUtility.UrlEncode(cryptedSessionKey),
                        encrypted_loginkey: HttpUtility.UrlEncode(cryptedLoginKey),
                        method: "POST",
                        secure: true
                        );
                }
                catch (Exception)
                {
                    Token = TokenSecure = null;
                    return(false);
                }

                Token       = authResult["token"].AsString();
                TokenSecure = authResult["tokensecure"].AsString();

                // Adding cookies to the cookie container.
                _cookies.Add(new Cookie("sessionid", SessionId, string.Empty, SteamCommunityDomain));
                _cookies.Add(new Cookie("steamLogin", Token, string.Empty, SteamCommunityDomain));
                _cookies.Add(new Cookie("steamLoginSecure", TokenSecure, string.Empty, SteamCommunityDomain));

                return(true);
            }
        }
示例#7
0
        private KeyDictionary Add(string title, KeyLinstener test, KeyDictionary mappings)
        {
            Add((key, state) =>
            {
                if (!test(key, state))
                {
                    return(false);
                }
                Logger.Log("Test passed: " + title);
                return(KeysSender.Send(key, mappings, state.Layout));
            });

            return(mappings);
        }
示例#8
0
        /// <summary>
        /// Cast key to derived enum
        /// </summary>
        /// <param name="key">Key to cast</param>
        /// <returns>Derived enum matching key OR new enum if not exists</returns>
        protected new static TDerived From(int key)
        {
            if (KeyDictionary.ContainsKey(key))
            {
                return((TDerived)KeyDictionary[key]);
            }

            var result = new TDerived
            {
                Key = key
            };

            KeyDictionary.Add(key, result);
            return(result);
        }
示例#9
0
        ///<summary>
        /// Authenticate using SteamKit2 and ISteamUserAuth.
        /// This does the same as SteamWeb.DoLogin(), but without contacting the Steam Website.
        /// </summary>
        /// <remarks>Should this one doesnt work anymore, use <see cref="SteamWeb.DoLogin"/></remarks>
        public static bool Authenticate(string myUniqueId, SteamClient client, out string sessionId, out string token, out string tokensecure, string myLoginKey)
        {
            sessionId = Convert.ToBase64String(Encoding.UTF8.GetBytes(myUniqueId));

            using (dynamic userAuth = WebAPI.GetInterface("ISteamUserAuth"))
            {
                // generate an AES session key
                var sessionKey = CryptoHelper.GenerateRandomBlock(32);

                // rsa encrypt it with the public key for the universe we're on
                byte[] cryptedSessionKey = null;
                using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(client.ConnectedUniverse)))
                {
                    cryptedSessionKey = rsa.Encrypt(sessionKey);
                }


                byte[] loginKey = new byte[20];
                Array.Copy(Encoding.ASCII.GetBytes(myLoginKey), loginKey, myLoginKey.Length);

                // aes encrypt the loginkey with our session key
                byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey);

                KeyValue authResult;

                try
                {
                    authResult = userAuth.AuthenticateUser(
                        steamid: client.SteamID.ConvertToUInt64(),
                        sessionkey: HttpUtility.UrlEncode(cryptedSessionKey),
                        encrypted_loginkey: HttpUtility.UrlEncode(cryptedLoginKey),
                        method: "POST",
                        secure: true
                        );
                }
                catch (Exception)
                {
                    token       = null;
                    tokensecure = null;
                    return(false);
                }

                token       = authResult ["token"].AsString();
                tokensecure = authResult["tokensecure"].AsString();

                return(true);
            }
        }
示例#10
0
        public void VerifyTable()
        {
            var serializer = new ConfigurationContainer().Type <Key>()
                             .Register()
                             .Converter()
                             .Using(KeyConverter.Default)
                             .UseAutoFormatting()
                             .Create()
                             .ForTesting();

            var instance = new KeyDictionary <string> {
                { 6776, "Hello World!" }
            };

            serializer.Cycle(instance).Should().BeEquivalentTo(instance);
        }
示例#11
0
        public void Has_all_keys()
        {
            var keys = typeof (Key)
                .GetEnumValues()
                .Cast<Key>()
                .ToList();

            var keyDictionary = new KeyDictionary();

            foreach (var key in keys)
            {
                var key1 = key;
                Action act = () => { var b = keyDictionary[key1]; };

                act.ShouldNotThrow();
            }
        }
示例#12
0
        static DbExpressionOptimizer()
        {
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_String_Length);

            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Now);
            //_toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_UtcNow);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Today);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Date);

            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Year);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Month);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Day);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Hour);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Minute);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Second);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Millisecond);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_DayOfWeek);

            _toTranslateMembers = _toTranslateMembers.Clone();
        }
示例#13
0
        static EvaluableDbExpressionTransformer()
        {
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_String_Length);

            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Now);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_UtcNow);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Today);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Date);

            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Year);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Month);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Day);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Hour);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Minute);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Second);
            /* MySql is not supports MILLISECOND */
            //_toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Millisecond);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_DayOfWeek);

            _toTranslateMembers = _toTranslateMembers.Clone();
        }
示例#14
0
        //private void AddToDictionary(
        //    PoeNinjaDataService.ItemJsonResponse.Line line,
        //    string attribute,
        //    bool useNameForKeyGeneration = true,
        //    bool useBaseTypeForKeyGeneration = false)
        //{
        //    line.Name = line.Name.Trim();

        //    var keyNode = new KeyNode
        //    {
        //        Description = line.Name,
        //        Key = FormatStringToKey(line, useNameForKeyGeneration, useBaseTypeForKeyGeneration),
        //    };

        //    keyNode.Attributes.Add($"[Name(Name = \"{line.Name}\")]");

        //    if(line.Id != -1)
        //    {
        //        keyNode.Attributes.Add($"[{attribute}(PoeNinjaId = \"{line.Id}\")]");
        //        keyNode.Attributes.Add($"[PoeNinja]");
        //    }
        //    else
        //    {
        //        keyNode.Attributes.Add($"[{attribute}()]");
        //    }

        //    AddToDictionary(keyNode);
        //}

        private void AddToDictionary(KeyNode keyNode)
        {
            if(!KeyDictionary.ContainsKey(keyNode.Key))
            {
                KeyDictionary.Add(keyNode.Key, keyNode);

                return;
            }

            var existing = (KeyNode)KeyDictionary[keyNode.Key];

            foreach(var a in keyNode.Attributes)
            {
                if(existing.Attributes.Any(o => o.Equals(a, StringComparison.OrdinalIgnoreCase)))
                {
                    continue;
                }

                existing.Attributes.Add(a);
            }

        }
        static EvaluableDbExpressionTransformer()
        {
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_String_Length);

            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Now);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_UtcNow);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Today);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Date);

            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Year);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Month);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Day);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Hour);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Minute);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Second);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_Millisecond);
            _toTranslateMembers.Add(UtilConstants.PropertyInfo_DateTime_DayOfWeek);

            _toTranslateMembers.Add(OracleSemantics.PropertyInfo_ROWNUM);

            _toTranslateMembers = _toTranslateMembers.Clone();
        }
示例#16
0
        void HandleEncryptRequest(IPacketMsg packetMsg)
        {
            var encRequest = new Msg <MsgChannelEncryptRequest>(packetMsg);

            EUniverse eUniv        = encRequest.Body.Universe;
            uint      protoVersion = encRequest.Body.ProtocolVersion;

            DebugLog.WriteLine("CMClient", "Got encryption request. Universe: {0} Protocol ver: {1}", eUniv, protoVersion);
            DebugLog.Assert(protoVersion == 1, "CMClient", "Encryption handshake protocol version mismatch!");

            byte[] pubKey = KeyDictionary.GetPublicKey(eUniv);

            if (pubKey == null)
            {
                DebugLog.WriteLine("CMClient", "HandleEncryptionRequest got request for invalid universe! Universe: {0} Protocol ver: {1}", eUniv, protoVersion);
                return;
            }

            ConnectedUniverse = eUniv;

            var encResp = new Msg <MsgChannelEncryptResponse>();

            tempSessionKey = CryptoHelper.GenerateRandomBlock(32);
            byte[] cryptedSessKey = null;

            using (var rsa = new RSACrypto(pubKey))
            {
                cryptedSessKey = rsa.Encrypt(tempSessionKey);
            }

            byte[] keyCrc = CryptoHelper.CRCHash(cryptedSessKey);

            encResp.Write(cryptedSessKey);
            encResp.Write(keyCrc);
            encResp.Write(( uint )0);

            this.Send(encResp);
        }
示例#17
0
        public ResultElement(ScopeParameterDictionary scopeParameters, KeyDictionary <string> scopeTables)
        {
            this.Orderings     = new List <DbOrdering>();
            this.GroupSegments = new List <DbExpression>();

            if (scopeTables == null)
            {
                this.ScopeTables = new KeyDictionary <string>();
            }
            else
            {
                this.ScopeTables = scopeTables.Clone();
            }

            if (scopeParameters == null)
            {
                this.ScopeParameters = new ScopeParameterDictionary();
            }
            else
            {
                this.ScopeParameters = scopeParameters.Clone();
            }
        }
示例#18
0
        public virtual JoinQueryResult ToJoinQueryResult(JoinType joinType, LambdaExpression conditionExpression, ScopeParameterDictionary scopeParameters, KeyDictionary <string> scopeTables, string tableAlias)
        {
            DbSqlQueryExpression sqlQuery = this.CreateSqlQuery();
            DbSubQueryExpression subQuery = new DbSubQueryExpression(sqlQuery);

            string         alias    = tableAlias;
            DbTableSegment tableSeg = new DbTableSegment(subQuery, alias, LockType.Unspecified);

            DbTable table = new DbTable(tableSeg.Alias);
            IMappingObjectExpression newMoe = this.Result.MappingObjectExpression.ToNewObjectExpression(sqlQuery, table);

            scopeParameters[conditionExpression.Parameters[conditionExpression.Parameters.Count - 1]] = newMoe;

            DbExpression condition = GeneralExpressionVisitor.ParseLambda(conditionExpression, scopeParameters, scopeTables);

            DbJoinTableExpression joinTable = new DbJoinTableExpression(joinType.AsDbJoinType(), tableSeg, condition);

            JoinQueryResult result = new JoinQueryResult();

            result.MappingObjectExpression = newMoe;
            result.JoinTable = joinTable;
            return(result);
        }
示例#19
0
        public static async Task <bool> AuthenticateUser()
        {
            SteamUser.WebAPIUserNonceCallback nonce;

            try
            {
                nonce = await Steam.Instance.User.RequestWebAPIUserNonce();
            }
            catch (Exception e)
            {
                IsAuthorized = false;

                Log.WriteWarn("WebAuth", "Failed to get nonce: {0}", e.Message);

                return(false);
            }

            // 32 byte random blob of data
            var sessionKey = CryptoHelper.GenerateRandomBlock(32);

            byte[] encryptedSessionKey;

            // ... which is then encrypted with RSA using the Steam system's public key
            using (var rsa = new RSACrypto(KeyDictionary.GetPublicKey(Steam.Instance.Client.Universe)))
            {
                encryptedSessionKey = rsa.Encrypt(sessionKey);
            }

            // users hashed loginkey, AES encrypted with the sessionkey
            var encryptedLoginKey = CryptoHelper.SymmetricEncrypt(Encoding.ASCII.GetBytes(nonce.Nonce), sessionKey);

            using (dynamic userAuth = WebAPI.GetAsyncInterface("ISteamUserAuth"))
            {
                KeyValue result;

                try
                {
                    result = await userAuth.AuthenticateUser(
                        steamid : Steam.Instance.Client.SteamID.ConvertToUInt64(),
                        sessionkey : WebHelpers.UrlEncode(encryptedSessionKey),
                        encrypted_loginkey : WebHelpers.UrlEncode(encryptedLoginKey),
                        method : "POST",
                        secure : true
                        );
                }
                catch (HttpRequestException e)
                {
                    IsAuthorized = false;

                    Log.WriteWarn("WebAuth", "Failed to authenticate: {0}", e.Message);

                    return(false);
                }

                File.WriteAllText(Path.Combine(Application.Path, "files", ".support", "cookie.txt"), $"steamLogin={result["token"].AsString()}; steamLoginSecure={result["tokensecure"].AsString()}");

                Cookies = new CookieContainer();
                Cookies.Add(new Cookie("steamLogin", result["token"].AsString(), "/", "store.steampowered.com"));
                Cookies.Add(new Cookie("steamLoginSecure", result["tokensecure"].AsString(), "/", "store.steampowered.com"));
            }

            IsAuthorized = true;

            Log.WriteInfo("WebAuth", "Authenticated");

            if (!Settings.IsFullRun)
            {
                await AccountInfo.RefreshAppsToIdle();
            }

            return(true);
        }
示例#20
0
        public static async Task <bool> AuthenticateUser()
        {
            SteamUser.WebAPIUserNonceCallback nonce;
            ulong steamid;

            try
            {
                nonce = await Steam.Instance.User.RequestWebAPIUserNonce();

                steamid = Steam.Instance.Client.SteamID.ConvertToUInt64();
            }
            catch (Exception e)
            {
                IsAuthorized = false;

                Log.WriteWarn("WebAuth", "Failed to get nonce: {0}", e.Message);

                return(false);
            }

            // 32 byte random blob of data
            var sessionKey = CryptoHelper.GenerateRandomBlock(32);

            byte[] encryptedSessionKey;

            // ... which is then encrypted with RSA using the Steam system's public key
            using (var rsa = new RSACrypto(KeyDictionary.GetPublicKey(Steam.Instance.Client.Universe) !))
            {
                encryptedSessionKey = rsa.Encrypt(sessionKey);
            }

            // users hashed loginkey, AES encrypted with the sessionkey
            var encryptedLoginKey = CryptoHelper.SymmetricEncrypt(Encoding.ASCII.GetBytes(nonce.Nonce), sessionKey);

            using (var userAuth = Steam.Configuration.GetAsyncWebAPIInterface("ISteamUserAuth"))
            {
                KeyValue result;

                try
                {
                    result = await userAuth.CallAsync(HttpMethod.Post, "AuthenticateUser", 1,
                                                      new Dictionary <string, object>
                    {
                        { "steamid", steamid },
                        { "sessionkey", encryptedSessionKey },
                        { "encrypted_loginkey", encryptedLoginKey },
                    }
                                                      );
                }
                catch (HttpRequestException e)
                {
                    IsAuthorized = false;

                    Log.WriteWarn("WebAuth", "Failed to authenticate: {0}", e.Message);

                    return(false);
                }

                Cookies = new CookieContainer();
                Cookies.Add(new Cookie("steamLogin", result["token"].AsString(), "/", "store.steampowered.com"));
                Cookies.Add(new Cookie("steamLoginSecure", result["tokensecure"].AsString(), "/", "store.steampowered.com"));
            }

            IsAuthorized = true;

            Log.WriteInfo("WebAuth", "Authenticated");

            return(true);
        }
示例#21
0
 /// <summary>
 /// Check if enum contains key
 /// </summary>
 /// <param name="key">Key to check</param>
 /// <returns>True if the enum key exists</returns>
 public static bool Contains(TKey key)
 {
     return(KeyDictionary.ContainsKey(key));
 }
示例#22
0
        public static IQueryState VisitQueryExpression(QueryExpression queryExpression, ScopeParameterDictionary scopeParameters, KeyDictionary <string> scopeTables)
        {
            QueryExpressionVisitor reducer = new QueryExpressionVisitor(scopeParameters, scopeTables);

            return(queryExpression.Accept(reducer));
        }
示例#23
0
        public static DbExpression ParseLambda(LambdaExpression lambda, ScopeParameterDictionary scopeParameters, KeyDictionary <string> scopeTables)
        {
            GeneralExpressionVisitor visitor = new GeneralExpressionVisitor(scopeParameters, scopeTables);

            return(visitor.Visit(lambda));
        }
示例#24
0
        bool HandleEncryptRequest(IPacketMsg packetMsg)
        {
            var encRequest = new Msg <MsgChannelEncryptRequest>(packetMsg);

            EUniverse eUniv        = encRequest.Body.Universe;
            uint      protoVersion = encRequest.Body.ProtocolVersion;

            DebugLog.WriteLine("CMClient", "Got encryption request. Universe: {0} Protocol ver: {1}", eUniv, protoVersion);
            DebugLog.Assert(protoVersion == 1, "CMClient", "Encryption handshake protocol version mismatch!");

            byte[] randomChallenge;
            if (encRequest.Payload.Length >= 16)
            {
                randomChallenge = encRequest.Payload.ToArray();
            }
            else
            {
                randomChallenge = null;
            }

            byte[] pubKey = KeyDictionary.GetPublicKey(eUniv);

            if (pubKey == null)
            {
                connection.Disconnect();

                DebugLog.WriteLine("CMClient", "HandleEncryptionRequest got request for invalid universe! Universe: {0} Protocol ver: {1}", eUniv, protoVersion);
                return(false);
            }

            ConnectedUniverse = eUniv;

            var encResp = new Msg <MsgChannelEncryptResponse>();

            var tempSessionKey = CryptoHelper.GenerateRandomBlock(32);

            byte[] encryptedHandshakeBlob = null;

            using (var rsa = new RSACrypto(pubKey))
            {
                if (randomChallenge != null)
                {
                    var blobToEncrypt = new byte[tempSessionKey.Length + randomChallenge.Length];
                    Array.Copy(tempSessionKey, blobToEncrypt, tempSessionKey.Length);
                    Array.Copy(randomChallenge, 0, blobToEncrypt, tempSessionKey.Length, randomChallenge.Length);

                    encryptedHandshakeBlob = rsa.Encrypt(blobToEncrypt);
                }
                else
                {
                    encryptedHandshakeBlob = rsa.Encrypt(tempSessionKey);
                }
            }

            var keyCrc = CryptoHelper.CRCHash(encryptedHandshakeBlob);

            encResp.Write(encryptedHandshakeBlob);
            encResp.Write(keyCrc);
            encResp.Write(( uint )0);

            if (randomChallenge != null)
            {
                pendingNetFilterEncryption = new NetFilterEncryptionWithHMAC(tempSessionKey);
            }
            else
            {
                pendingNetFilterEncryption = new NetFilterEncryption(tempSessionKey);
            }

            this.Send(encResp);
            return(true);
        }
示例#25
0
        internal async Task <bool> Init(SteamClient steamClient, string webAPIUserNonce, string parentalPin)
        {
            if (steamClient == null || steamClient.SteamID == null || string.IsNullOrEmpty(webAPIUserNonce))
            {
                return(false);
            }

            SteamID = steamClient.SteamID;

            string sessionID = Convert.ToBase64String(Encoding.UTF8.GetBytes(SteamID.ToString()));

            // Generate an AES session key
            byte[] sessionKey = CryptoHelper.GenerateRandomBlock(32);

            // RSA encrypt it with the public key for the universe we're on
            byte[] cryptedSessionKey;
            using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(steamClient.ConnectedUniverse))) {
                cryptedSessionKey = rsa.Encrypt(sessionKey);
            }

            // Copy our login key
            byte[] loginKey = new byte[webAPIUserNonce.Length];
            Array.Copy(Encoding.ASCII.GetBytes(webAPIUserNonce), loginKey, webAPIUserNonce.Length);

            // AES encrypt the loginkey with our session key
            byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey);

            // Do the magic
            Logging.LogGenericInfo("Logging in to ISteamUserAuth...", Bot.BotName);

            KeyValue authResult;

            using (dynamic iSteamUserAuth = WebAPI.GetInterface("ISteamUserAuth")) {
                iSteamUserAuth.Timeout = Timeout;

                try {
                    authResult = iSteamUserAuth.AuthenticateUser(
                        steamid: SteamID,
                        sessionkey: Encoding.ASCII.GetString(WebUtility.UrlEncodeToBytes(cryptedSessionKey, 0, cryptedSessionKey.Length)),
                        encrypted_loginkey: Encoding.ASCII.GetString(WebUtility.UrlEncodeToBytes(cryptedLoginKey, 0, cryptedLoginKey.Length)),
                        method: WebRequestMethods.Http.Post,
                        secure: !Program.GlobalConfig.ForceHttp
                        );
                } catch (Exception e) {
                    Logging.LogGenericException(e, Bot.BotName);
                    return(false);
                }
            }

            if (authResult == null)
            {
                return(false);
            }

            Logging.LogGenericInfo("Success!", Bot.BotName);

            string steamLogin       = authResult["token"].AsString();
            string steamLoginSecure = authResult["tokensecure"].AsString();

            Cookie["sessionid"]        = sessionID;
            Cookie["steamLogin"]       = steamLogin;
            Cookie["steamLoginSecure"] = steamLoginSecure;

            // The below is used for display purposes only
            Cookie["webTradeEligibility"] = "{\"allowed\":0,\"reason\":0,\"allowed_at_time\":0,\"steamguard_required_days\":0,\"sales_this_year\":0,\"max_sales_per_year\":0,\"forms_requested\":0}";

            await UnlockParentalAccount(parentalPin).ConfigureAwait(false);

            return(true);
        }
示例#26
0
        public static IMappingObjectExpression Resolve(LambdaExpression selector, ScopeParameterDictionary scopeParameters, KeyDictionary <string> scopeTables)
        {
            SelectorResolver resolver = new SelectorResolver(scopeParameters, scopeTables);

            return(resolver.Visit(selector));
        }
        internal async Task <bool> Init(ulong steamID, EUniverse universe, string webAPIUserNonce, string parentalPin)
        {
            if ((steamID == 0) || (universe == EUniverse.Invalid) || string.IsNullOrEmpty(webAPIUserNonce) || string.IsNullOrEmpty(parentalPin))
            {
                Logging.LogNullError(nameof(steamID) + " || " + nameof(universe) + " || " + nameof(webAPIUserNonce) + " || " + nameof(parentalPin), Bot.BotName);
                return(false);
            }

            SteamID = steamID;

            string sessionID = Convert.ToBase64String(Encoding.UTF8.GetBytes(steamID.ToString()));

            // Generate an AES session key
            byte[] sessionKey = SteamKit2.CryptoHelper.GenerateRandomBlock(32);

            // RSA encrypt it with the public key for the universe we're on
            byte[] cryptedSessionKey;
            using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(universe))) {
                cryptedSessionKey = rsa.Encrypt(sessionKey);
            }

            // Copy our login key
            byte[] loginKey = new byte[webAPIUserNonce.Length];
            Array.Copy(Encoding.ASCII.GetBytes(webAPIUserNonce), loginKey, webAPIUserNonce.Length);

            // AES encrypt the loginkey with our session key
            byte[] cryptedLoginKey = SteamKit2.CryptoHelper.SymmetricEncrypt(loginKey, sessionKey);

            // Do the magic
            Logging.LogGenericInfo("Logging in to ISteamUserAuth...", Bot.BotName);

            KeyValue authResult;

            using (dynamic iSteamUserAuth = WebAPI.GetInterface("ISteamUserAuth")) {
                iSteamUserAuth.Timeout = Timeout;

                try {
                    authResult = iSteamUserAuth.AuthenticateUser(
                        steamid: steamID,
                        sessionkey: Encoding.ASCII.GetString(WebUtility.UrlEncodeToBytes(cryptedSessionKey, 0, cryptedSessionKey.Length)),
                        encrypted_loginkey: Encoding.ASCII.GetString(WebUtility.UrlEncodeToBytes(cryptedLoginKey, 0, cryptedLoginKey.Length)),
                        method: WebRequestMethods.Http.Post,
                        secure: !Program.GlobalConfig.ForceHttp
                        );
                } catch (Exception e) {
                    Logging.LogGenericException(e, Bot.BotName);
                    return(false);
                }
            }

            if (authResult == null)
            {
                Logging.LogNullError(nameof(authResult), Bot.BotName);
                return(false);
            }

            string steamLogin = authResult["token"].Value;

            if (string.IsNullOrEmpty(steamLogin))
            {
                Logging.LogNullError(nameof(steamLogin), Bot.BotName);
                return(false);
            }

            string steamLoginSecure = authResult["tokensecure"].Value;

            if (string.IsNullOrEmpty(steamLoginSecure))
            {
                Logging.LogNullError(nameof(steamLoginSecure), Bot.BotName);
                return(false);
            }

            WebBrowser.CookieContainer.Add(new Cookie("sessionid", sessionID, "/", "." + SteamCommunityHost));
            WebBrowser.CookieContainer.Add(new Cookie("steamLogin", steamLogin, "/", "." + SteamCommunityHost));
            WebBrowser.CookieContainer.Add(new Cookie("steamLoginSecure", steamLoginSecure, "/", "." + SteamCommunityHost));

            Logging.LogGenericInfo("Success!", Bot.BotName);

            // Unlock Steam Parental if needed
            if (!parentalPin.Equals("0"))
            {
                if (!await UnlockParentalAccount(parentalPin).ConfigureAwait(false))
                {
                    return(false);
                }
            }

            Ready = true;
            LastSessionRefreshCheck = DateTime.Now;
            return(true);
        }
示例#28
0
        internal async Task Init(string webAPIUserNonce)
        {
            steamID = _bot.steamClient.SteamID;

            sessionID = Convert.ToBase64String(Encoding.UTF8.GetBytes(steamID.ToString()));

            // Generate an AES session key
            byte[] sessionKey = CryptoHelper.GenerateRandomBlock(32);

            // RSA encrypt it with the public key for the universe we're on
            byte[] cryptedSessionKey;
            using (var crypto = new RSACrypto(KeyDictionary.GetPublicKey(_bot.steamClient.ConnectedUniverse)))
            {
                cryptedSessionKey = crypto.Encrypt(sessionKey);
            }
            // Copy our login key
            byte[] loginKey = new byte[webAPIUserNonce.Length];
            Array.Copy(Encoding.ASCII.GetBytes(webAPIUserNonce), loginKey, webAPIUserNonce.Length);

            // AES encrypt the loginkey with our session key
            byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey);

            _bot.Log("Logging in to ISteamUserAuth", LogType.Info);

            KeyValue autResult;

            using (dynamic iSteamUserAuth = WebAPI.GetInterface("ISteamUserAuth"))
            {
                iSteamUserAuth.Timeout = 60000;
                try
                {
                    autResult = iSteamUserAuth.AuthenticateUser(
                        steamid: steamID.ConvertToUInt64(),
                        sessionkey:
                        Encoding.ASCII.GetString(WebUtility.UrlEncodeToBytes(cryptedSessionKey, 0,
                                                                             cryptedSessionKey.Length)),
                        encrypted_loginkey:
                        Encoding.ASCII.GetString(WebUtility.UrlEncodeToBytes(cryptedLoginKey, 0,
                                                                             cryptedLoginKey.Length)),
                        method: WebRequestMethods.Http.Post,
                        secure: true);
                }
                catch (Exception e)
                {
                    _bot.Log("Cant AuthenticateUser " + e.Message, LogType.Error);
                    return;
                }
            }
            if (autResult == null)
            {
                return;
            }
            _bot.Log("Success", LogType.Info);

            string steamLogin       = autResult["token"].Value;
            string steamLoginSecure = autResult["tokensecure"].Value;

            webClient.cookieContainer.Add(new Cookie("sessionid", sessionID, "/", "." + SteamCommunityHOST));
            webClient.cookieContainer.Add(new Cookie("steamLogin", steamLogin, "/", "." + SteamCommunityHOST));
            webClient.cookieContainer.Add(new Cookie("steamLoginSecure", steamLoginSecure, "/", "." + SteamCommunityHOST));

            gameminerBot = new GameminerBot(webClient, _bot.BotConfig);

            Initialized = true;
            //GiveawayBotInit().Forget();
        }
示例#29
0
 QueryExpressionVisitor(ScopeParameterDictionary scopeParameters, KeyDictionary <string> scopeTables)
 {
     this._scopeParameters = scopeParameters;
     this._scopeTables     = scopeTables;
 }
示例#30
0
        ////////////////////////////////////////////////////
        // STEAM WEB INTERFACE
        ////////////////////////////////////////////////////

        // Copied this shit straight from ArchisSteamFarm, credit to him
        public override async void LoginWebInterface(ulong steamID)
        {
            if (!IsAuthenticated)
            {
                SteamUser.WebAPIUserNonceCallback callback;

                try
                {
                    callback = await _steamUser.RequestWebAPIUserNonce();
                }
                catch (Exception ex)
                {
                    _log.Error(ex, "Unable to request Web API Nonce. Titan won't be able to execute Web API actions.");
                    return;
                }

                if (string.IsNullOrWhiteSpace(callback?.Nonce))
                {
                    _log.Error("Received empty Web API Nonce. Titan won't be able to execute Web API actions.");
                    return;
                }

                var    sessionID  = Convert.ToBase64String(Encoding.UTF8.GetBytes(steamID.ToString()));
                var    sessionKey = CryptoHelper.GenerateRandomBlock(32);
                byte[] cryptedSessionKey;

                using (var rsa = new RSACrypto(KeyDictionary.GetPublicKey(_steamClient.Universe)))
                {
                    cryptedSessionKey = rsa.Encrypt(sessionKey);
                }

                var loginKey = new byte[callback.Nonce.Length];
                Array.Copy(Encoding.ASCII.GetBytes(callback.Nonce), loginKey, callback.Nonce.Length);

                // AES encrypt the login key with our session key
                var cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey);

                if (!Titan.Instance.WebHandle.AuthentificateUser(
                        steamID, cryptedLoginKey, cryptedSessionKey, out var result
                        ))
                {
                    _log.Error("Failed to authentificate with Web API Nonce. " +
                               "Titan won't be able to execute Web API actions.");
                    return;
                }

                var token       = result["token"].Value;
                var secureToken = result["tokensecure"].Value;

                if (string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(secureToken))
                {
                    _log.Error("Failed to authentificate with Web API Nonce. " +
                               "Titan won't be able to execute Web API actions.");
                    return;
                }

                Cookies.Add("sessionid", sessionID);
                Cookies.Add("steamLogin", token);
                Cookies.Add("steamLoginSecure", secureToken);

                if (!Titan.Instance.Options.Secure)
                {
                    _log.Debug("Authorized with Steam Web API. Session ID: {id}", sessionID);
                }

                _log.Information("Successfully authorized with Steam Web API.");

                IsAuthenticated = true;
            }
        }
示例#31
0
 SelectorResolver(ScopeParameterDictionary scopeParameters, KeyDictionary <string> scopeTables)
 {
     this._scopeParameters = scopeParameters;
     this._scopeTables     = scopeTables;
 }