Exemple #1
0
        public bool AuthentificateUser(ulong steamID, byte[] sessionKey, byte[] loginKey, out KeyValue result)
        {
            result = null;

            try
            {
                using (dynamic steamUserAuth = WebAPI.GetAsyncInterface("ISteamUserAuth", _keyManager.SWAKey))
                {
                    result = steamUserAuth.AuthenticateUser(
                        steamid: steamID,
                        sessionkey: Encoding.ASCII.GetString(WebUtility.UrlEncodeToBytes(sessionKey, 0, sessionKey.Length)),
                        encrypted_loginkey: Encoding.ASCII.GetString(WebUtility.UrlEncodeToBytes(loginKey, 0, loginKey.Length)),
                        method: WebRequestMethods.Http.Post,
                        secure: true
                        );
                }
            }
            catch (Exception ex)
            {
                Log.Error("Could not authentificate with Steam Web API: {Error}", ex.Message);
                return(false);
            }

            return(result != null);
        }
Exemple #2
0
        public async Task <string> GetSteamLevel(string steamid)
        {
            using (dynamic playerService = WebAPI.GetAsyncInterface("IPlayerService", steamKey))
            {
                KeyValue kvLevel = await playerService.GetSteamLevel1(steamid : steamid);

                return(kvLevel["player_level"].AsString());
            }
        }
Exemple #3
0
        public static async Task <WebSession> AuthenticateWebSession(
            this SteamClient client,
            string userNonce
            )
        {
            // Generate random SessionId
            var sessionId = Guid.NewGuid().ToString("N");

            // Generate an AES SessionKey.
            var sessionKey = CryptoHelper.GenerateRandomBlock(32);

            // rsa encrypt it with the public key for the universe we're on
            byte[] encryptedSessionKey;

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

            // AES encrypt the loginkey with our session key.
            var encryptedLoginKey = CryptoHelper.SymmetricEncrypt(
                Encoding.ASCII.GetBytes(userNonce),
                sessionKey
                );

            try
            {
                using (var steamUserAuth = WebAPI.GetAsyncInterface("ISteamUserAuth"))
                {
                    var result = await steamUserAuth.CallAsync(
                        HttpMethod.Post,
                        "AuthenticateUser",
                        1,
                        new Dictionary <string, object>
                    {
                        { "steamid", client.SteamID.ConvertToUInt64().ToString() },
                        { "sessionkey", encryptedSessionKey },
                        { "encrypted_loginkey", encryptedLoginKey }
                    }
                        ).ConfigureAwait(false);

                    return(new WebSession(
                               client.SteamID.ConvertToUInt64(),
                               result["token"]?.Value?.ToUpper(),
                               result["tokensecure"]?.Value?.ToUpper(),
                               sessionId,
                               null,
                               null
                               ));
                }
            }
            catch
            {
                return(null);
            }
        }
Exemple #4
0
        public async Task <long> ResolveVanityURL(string vanityName)
        {
            using (dynamic steamUser = WebAPI.GetAsyncInterface("ISteamUser", steamKey))
            {
                KeyValue kvVanity = await steamUser.ResolveVanityURL(vanityurl : vanityName);

                if (kvVanity["success"].AsInteger() == 1)
                {
                    return(kvVanity["steamid"].AsLong());
                }
                else
                {
                    return(0);
                }
            }
        }
Exemple #5
0
        public async Task ThrowsHttpRequestExceptionIfRequestUnsuccessful()
        {
            var listener = new TcpListener(new IPEndPoint(IPAddress.Loopback, 28123));

            listener.Start();
            try
            {
                AcceptAndAutoReplyNextSocket(listener);

                var     baseUri = "http://localhost:28123";
                dynamic iface   = WebAPI.GetAsyncInterface(new Uri(baseUri), "IFooService");

                await Assert.ThrowsAsync(typeof(HttpRequestException), () => (Task)iface.PerformFooOperation());
            }
            finally
            {
                listener.Stop();
            }
        }
        public async Task <PlayerCountDetails> RequestPlayerCountWeb(uint appId)
        {
            using (dynamic api = WebAPI.GetAsyncInterface("ICommunityService", Settings.Current.WebAPIKey))
            {
                KeyValue resultKv;

                try
                {
                    resultKv = await api.GetPlayerCount(appIds : new[] { appId });
                }
                catch (WebException ex)
                {
                    Log.WriteError(nameof(PlayerCountHandler), "Unable to retreive player count from WebAPI: {0}", ex);

                    return(new PlayerCountDetails
                    {
                        AppID = appId,
                        Result = EResult.Fail,
                    });
                }

                KeyValue playerCount = resultKv["apps_played"].Children
                                       .FirstOrDefault(c => c["appid"].AsInteger() == appId);

                if (playerCount == null)
                {
                    return(new PlayerCountDetails
                    {
                        AppID = appId,
                        Result = EResult.NoMatch,
                    });
                }

                return(new PlayerCountDetails
                {
                    AppID = appId,
                    Result = EResult.OK,

                    Count = playerCount["players"].AsUnsignedInteger(),
                });
            }
        }
Exemple #7
0
        public async Task <SteamUserInfo> GetSteamUser(string id)
        {
            bool isVanity = !long.TryParse(id, out long steamid);

            if (isVanity)
            {
                steamid = await ResolveVanityURL(id);
            }

            using (dynamic steamUser = WebAPI.GetAsyncInterface("ISteamUser", steamKey))
            {
                KeyValue kvUser = await steamUser.GetPlayerSummaries2(steamids : steamid);

                if (kvUser["players"].Children.Count > 0)
                {
                    return(new SteamUserInfo(kvUser["players"].Children[0]));
                }
                return(null);
            }
        }
        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);
        }
Exemple #9
0
        public void WebAPIAsyncHasDefaultTimeout()
        {
            var iface = WebAPI.GetAsyncInterface(new Uri("https://whatever/"), "ISteamWhatever");

            Assert.Equal(iface.Timeout, TimeSpan.FromSeconds(100));
        }
Exemple #10
0
        private async Task SearchWorkshop(CommandContext ctx, string SearchQuery, int gameid)
        {
            await ctx.RespondAsync("Querying workshop... (This might take a minute)");

            using (dynamic SteamWorkshopQuery = WebAPI.GetAsyncInterface("IPublishedFileService", SettingsFile.steamwebapikey))
            {
                SteamWorkshopQuery.Timeout = TimeSpan.FromSeconds(5);

                var    searchResultIDList = new List <string>();
                int    totalSearchResults = 0;
                string next_cursor        = "";

                KeyValue kvResults = await SteamWorkshopQuery.QueryFiles(
                    query_type : 0,
                    cursor : "*",
                    appid : gameid,
                    search_text : SearchQuery,
                    method : HttpMethod.Get
                    );

                // Get the total search results
                foreach (var child in kvResults.Children)
                {
                    if (child.Name == "total")
                    {
                        totalSearchResults = Int32.Parse(child.Value);
                        break;
                    }
                }

                // Clamp results
                if (totalSearchResults > 5)
                {
                    totalSearchResults = 5;
                }

                while (searchResultIDList.Count < totalSearchResults)
                {
                    foreach (var child in kvResults.Children)
                    {
                        if (child.Name == "publishedfiledetails")
                        {
                            foreach (var child2 in child.Children)
                            {
                                foreach (var child3 in child2.Children)
                                {
                                    if (child3.Name == "publishedfileid")
                                    {
                                        if (!searchResultIDList.Contains(child3.Value))
                                        {
                                            searchResultIDList.Add(child3.Value);
                                        }
                                    }
                                }
                            }
                        }
                        if (child.Name == "next_cursor")
                        {
                            next_cursor = child.Value;
                        }
                    }
                    kvResults = await SteamWorkshopQuery.QueryFiles(
                        query_type : 0,
                        appid : gameid,
                        cursor : next_cursor,
                        search_text : SearchQuery,
                        method : HttpMethod.Get
                        );
                }


                var listresults = await SteamWorkshopModule.GetPublishedFileDetails(searchResultIDList);

                var embed = new DiscordEmbedBuilder
                {
                    Title = $"`{SearchQuery}` search results",
                    Color = new DiscordColor(0x171A21)
                };

                foreach (var workshopitem in listresults)
                {
                    if (gameid == 730 && workshopitem.FileURL == null)
                    {
                        continue;
                    }
                    embed.AddField($"{workshopitem.Title}", $"https://steamcommunity.com/sharedfiles/filedetails/?id={workshopitem.PublishedFileID}");
                }

                await ctx.RespondAsync(embed : embed);
            }
        }
        static public async Task <List <WorkshopReturnInformation> > GetPublishedFileDetails(List <string> itemids)
        {
            var kvlist = new List <KeyValue>();

            using (dynamic SteamPublishedFileDetails = WebAPI.GetAsyncInterface("ISteamRemoteStorage"))
            {
                var basedict = new Dictionary <string, object>
                {
                    ["itemcount"]           = 1,
                    ["method"]              = HttpMethod.Post,
                    ["publishedfileids[0]"] = ""
                };
                foreach (var itemid in itemids)
                {
                    basedict["publishedfileids[0]"] = itemid;
                    try
                    {
                        KeyValue kvResults = await SteamPublishedFileDetails.GetPublishedFileDetails(basedict);

                        kvlist.Add(kvResults);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        return(null);
                    }
                }
            }
            // Parse out the information we want
            var returninfo = new List <WorkshopReturnInformation>();

            foreach (var kvitem in kvlist)
            {
                foreach (var child in kvitem.Children)
                {
                    foreach (var child2 in child.Children)
                    {
                        if (child2.Name == "0")
                        {
                            var thisreturninfo = new WorkshopReturnInformation();

                            foreach (var child3 in child2.Children)
                            {
                                switch (child3.Name)
                                {
                                case "publishedfileid":
                                    thisreturninfo.PublishedFileID = child3.Value;
                                    break;

                                case "creator":
                                    thisreturninfo.CreatorID = child3.Value;
                                    break;

                                case "file_url":
                                    thisreturninfo.FileURL = child3.Value;
                                    break;

                                case "preview_url":
                                    thisreturninfo.PreviewURL = child3.Value;
                                    break;

                                case "title":
                                    thisreturninfo.Title = child3.Value;
                                    break;

                                case "description":
                                    thisreturninfo.Description = child3.Value;
                                    break;

                                case "time_created":
                                    thisreturninfo.TimeCreated = Int64.Parse(child3.Value);
                                    break;

                                case "time_updated":
                                    thisreturninfo.TimeCreated = Int64.Parse(child3.Value);
                                    break;

                                case "filename":
                                    thisreturninfo.Filename = child3.Value;
                                    break;

                                default:
                                    break;
                                }
                            }
                            returninfo.Add(thisreturninfo);
                        }
                    }
                }
            }


            return(returninfo);
        }
Exemple #12
0
        /// <summary>
        ///     重新获取新 Cookies,如果是第一次调用本方法,会同时启用定时检测计时器
        /// </summary>
        public async Task Refresh()
        {
            if (!_checkTimer.Enabled)
            {
                _logger.Info($"#{BotSequenceNumber} Cookies check timer started.");
                _checkTimer.Start();
            }

            if (string.IsNullOrWhiteSpace(WebApiUserNonce))
            {
                return;
            }

            // generate an AES session key
            var sessionKey = CryptoHelper.GenerateRandomBlock(32);

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

            var loginKey = new byte[20];

            Array.Copy(Encoding.ASCII.GetBytes(WebApiUserNonce), loginKey, WebApiUserNonce.Length);

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

            try
            {
                await _retryPolicy.ExecuteAsync(async() =>
                {
                    using (dynamic userAuth = WebAPI.GetAsyncInterface("ISteamUserAuth"))
                    {
                        KeyValue authResult =
                            await userAuth.AuthenticateUser(steamid: SteamId.ConvertToUInt64(),
                                                            sessionkey: HttpUtility.UrlEncode(encryptedSessionKey),
                                                            encrypted_loginkey: HttpUtility.UrlEncode(encryptedLoginKey),
                                                            method: "POST",
                                                            secure: true);

                        _cookieContainer.Add(new Cookie("sessionid",
                                                        Convert.ToBase64String(Encoding.UTF8.GetBytes(LoginKeyUniqueId.ToString())),
                                                        string.Empty,
                                                        "steamcommunity.com"));

                        _cookieContainer.Add(new Cookie("steamLogin", authResult["token"].AsString(),
                                                        string.Empty,
                                                        "steamcommunity.com"));

                        _cookieContainer.Add(new Cookie("steamLoginSecure", authResult["tokensecure"].AsString(),
                                                        string.Empty,
                                                        "steamcommunity.com"));

                        _logger.Info($"#{BotSequenceNumber} Cookies refreshed.");
                    }
                });
            }
            catch (Exception e)
            {
                _logger.Warn($"#{BotSequenceNumber} Cookies refresh failed.", e);
            }
        }