Skip to content
This repository has been archived by the owner on Jul 30, 2024. It is now read-only.

Commit

Permalink
Merge pull request #627 from scholtzm/404fix
Browse files Browse the repository at this point in the history
Fix for issue #404 + added support for steamLoginSecure
  • Loading branch information
BlueRaja committed Sep 28, 2014
2 parents 0dc82ce + 7465208 commit 8c63e89
Show file tree
Hide file tree
Showing 2 changed files with 116 additions and 25 deletions.
117 changes: 96 additions & 21 deletions SteamBot/Bot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,14 @@ public IEnumerable<SteamID> FriendsList
// The number, in milliseconds, between polls for the trade.
int TradePollingInterval;

public string MyLoginKey;
public string MyUserNonce;
public string MyUniqueId;

string sessionId;
string token;
string tokensecure;
bool CookiesAreInvalid = true;

This comment has been minimized.

Copy link
@waylaidwanderer

waylaidwanderer Sep 30, 2014

Contributor

The casing in this variable doesn't match the previous ones. public variables are capitalized per-word and non-public ones should be all lowercase camel case.

Actually, tokenSecure should be camel case to match sessionId...

This comment has been minimized.

Copy link
@BlueRaja

BlueRaja Sep 30, 2014

Author Collaborator

Agreed. After my open PR's get merged, remind me to come back through and clean up a few of the main files.

This comment has been minimized.

Copy link
@scholtzm

scholtzm Sep 30, 2014

Contributor

According to this article, almost everything should be in PascalCase. But frankly, you chose the worst time to point this out. 😄

This comment has been minimized.

Copy link
@BlueRaja

BlueRaja Sep 30, 2014

Author Collaborator

MS only set guidelines on public members. The community has quietly agreed that private methods should be PascalCased, private fields should be camelCase. Whether or not to start private fields with an _underscore isn't commonly agreed upon; I like to, if that matters.


bool isprocess;
public bool IsRunning = false;

Expand Down Expand Up @@ -218,7 +223,7 @@ public void StopBot()
/// </returns>
public bool OpenTrade(SteamID other)
{
if (CurrentTrade != null)
if (CurrentTrade != null || CheckCookies() == false)
return false;

SteamTrade.Trade(other);
Expand Down Expand Up @@ -351,7 +356,7 @@ void HandleSteamMessage(CallbackMsg msg)
if (callback.Result == EResult.OK)
{
MyLoginKey = callback.WebAPIUserNonce;
MyUserNonce = callback.WebAPIUserNonce;
}
else
{
Expand Down Expand Up @@ -380,25 +385,9 @@ void HandleSteamMessage(CallbackMsg msg)

msg.Handle<SteamUser.LoginKeyCallback>(callback =>
{
while (true)
{
bool authd = SteamWeb.Authenticate(callback, SteamClient, out sessionId, out token, MyLoginKey);
MyUniqueId = callback.UniqueID.ToString();
if (authd)
{
log.Success("User Authenticated!");
tradeManager = new TradeManager(apiKey, sessionId, token);
tradeManager.SetTradeTimeLimits(MaximumTradeTime, MaximiumActionGap, TradePollingInterval);
tradeManager.OnTimeout += OnTradeTimeout;
break;
}
else
{
log.Warn("Authentication failed, retrying in 2s...");
Thread.Sleep(2000);
}
}
UserWebLogOn();
if (Trade.CurrentSchema == null)
{
Expand All @@ -417,6 +406,22 @@ void HandleSteamMessage(CallbackMsg msg)
GetUserHandler(SteamClient.SteamID).OnLoginCompleted();
});

msg.Handle<SteamClient.JobCallback<SteamUser.WebAPIUserNonceCallback>>(jobCallback =>
{
log.Debug("Received new WebAPIUserNonce.");
if (jobCallback.Callback.Result == EResult.OK)
{
MyUserNonce = jobCallback.Callback.Nonce;
UserWebLogOn();
}
else
{
log.Error("WebAPIUserNonce Error: " + jobCallback.Callback.Result);
}
});

// handle a special JobCallback differently than the others
if (msg.IsType<SteamClient.JobCallback<SteamUser.UpdateMachineAuthCallback>>())
{
Expand Down Expand Up @@ -515,6 +520,12 @@ void HandleSteamMessage(CallbackMsg msg)

msg.Handle<SteamTrading.TradeProposedCallback>(callback =>
{
if (CheckCookies() == false)
{
SteamTrade.RespondToTrade(callback.TradeID, false);
return;
}
try
{
tradeManager.InitializeTrade(SteamUser.SteamID, callback.OtherClient);
Expand Down Expand Up @@ -604,6 +615,70 @@ void UserLogOn()
SteamUser.LogOn(logOnDetails);
}

void UserWebLogOn()
{
while (true)
{
bool authd = SteamWeb.Authenticate(MyUniqueId, SteamClient, out sessionId, out token, out tokensecure, MyUserNonce);

if (authd)
{
log.Success("User Authenticated!");

tradeManager = new TradeManager(apiKey, sessionId, token);
tradeManager.SetTradeTimeLimits(MaximumTradeTime, MaximiumActionGap, TradePollingInterval);
tradeManager.OnTimeout += OnTradeTimeout;

CookiesAreInvalid = false;
break;
}
else
{
log.Warn("Authentication failed, retrying in 2s...");
Thread.Sleep(2000);
}
}
}

/// <summary>
/// Checks if sessionId and token cookies are still valid.
/// Sets cookie flag if they are invalid.
/// </summary>
/// <returns>true if cookies are valid; otherwise false</returns>
bool CheckCookies()
{
// We still haven't re-authenticated
if (CookiesAreInvalid)
return false;

// Construct cookie container
CookieContainer cookies = new CookieContainer();
cookies.Add(new Cookie("sessionid", sessionId, String.Empty, "steamcommunity.com"));
cookies.Add(new Cookie("steamLogin", token, String.Empty, "steamcommunity.com"));

try
{
if (!SteamWeb.VerifyCookies(cookies))
{
// Cookies are no longer valid
log.Warn("Cookies are invalid. Need to re-authenticate.");
CookiesAreInvalid = true;
SteamUser.RequestWebAPIUserNonce();
return false;
}
else
{
return true;
}
}
catch
{
// Even if exception is caught, we should still continue.
log.Warn("Cookie check failed. http://steamcommunity.com is possibly down.");
return true;
}
}

UserHandler GetUserHandler(SteamID sid)
{
if (!userHandlers.ContainsKey(sid))
Expand Down
24 changes: 20 additions & 4 deletions SteamTrade/SteamWeb.cs
Original file line number Diff line number Diff line change
Expand Up @@ -179,9 +179,9 @@ public static CookieCollection DoLogin (string username, string password)
/// 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(SteamUser.LoginKeyCallback callback, SteamClient client, out string sessionId, out string token, string MyLoginKey)
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 (callback.UniqueID.ToString ()));
sessionId = Convert.ToBase64String (Encoding.UTF8.GetBytes (myUniqueId));

using (dynamic userAuth = WebAPI.GetInterface ("ISteamUserAuth"))
{
Expand All @@ -197,7 +197,7 @@ public static bool Authenticate(SteamUser.LoginKeyCallback callback, SteamClient


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

// aes encrypt the loginkey with our session key
byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt (loginKey, sessionKey);
Expand All @@ -210,21 +210,37 @@ public static bool Authenticate(SteamUser.LoginKeyCallback callback, SteamClient
steamid: client.SteamID.ConvertToUInt64 (),
sessionkey: HttpUtility.UrlEncode (cryptedSessionKey),
encrypted_loginkey: HttpUtility.UrlEncode (cryptedLoginKey),
method: "POST"
method: "POST",
secure: true
);
}
catch (Exception)
{
token = null;
tokensecure = null;
return false;
}

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

return true;
}
}

/// <summary>
/// Helper method to verify our precious cookies.
/// </summary>
/// <param name="cookies">CookieContainer with our cookies.</param>
/// <returns>true if cookies are correct; false otherwise</returns>
public static bool VerifyCookies(CookieContainer cookies)
{
using (HttpWebResponse response = Request("http://steamcommunity.com/", "HEAD", null, cookies))
{
return !(response.Cookies["steamLogin"] != null && response.Cookies["steamLogin"].Value.Equals("deleted"));
}
}

static void SubmitCookies (CookieContainer cookies)
{
HttpWebRequest w = WebRequest.Create ("https://steamcommunity.com/") as HttpWebRequest;
Expand Down

0 comments on commit 8c63e89

Please sign in to comment.