Inheritance: IDisposable
        private static bool AuthenticateUser()
        {
            // 32 byte random blob of data
            var sessionKey = CryptoHelper.GenerateRandomBlock(32);

            byte[] encryptedSessionKey = null;

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

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

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

                try
                {
                    result = userAuth.AuthenticateUser(
                        steamid: Steam.Instance.Client.SteamID.ConvertToUInt64(),
                        sessionkey: WebHelpers.UrlEncode(encryptedSessionKey),
                        encrypted_loginkey: WebHelpers.UrlEncode(encryptedLoginKey),
                        method: "POST",
                        secure: true
                    );
                }
                catch (WebException e)
                {
                    var response = (HttpWebResponse)e.Response;

                    if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
                    {
                        IsAuthorized = false;

                        if (Steam.Instance.Client.IsConnected)
                        {
                            Steam.Instance.User.RequestWebAPIUserNonce();
                        }
                    }

                    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;
        }
Exemple #2
0
        void OnLoginKey(SteamUser.LoginKeyCallback callback)
        {
            string SessionID = WebHelpers.EncodeBase64(callback.UniqueID.ToString());

            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 (var rsa = new RSACrypto(KeyDictionary.GetPublicKey(Client.ConnectedUniverse)))
                {
                    cryptedSessionKey = rsa.Encrypt(sessionKey);
                }

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

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

                KeyValue authResult = null;
                EResult  result     = EResult.OK;

                try
                {
                    authResult = userAuth.AuthenticateUser(
                        steamid: Client.SteamID.ConvertToUInt64(),
                        sessionkey: WebHelpers.UrlEncode(cryptedSessionKey),
                        encrypted_loginkey: WebHelpers.UrlEncode(cryptedLoginKey),
                        method: "POST"
                        );
                }
                catch (Exception)
                {
                    result = EResult.Fail;
                }

                Login.SessionId = SessionID;

                if (authResult != null)
                {
                    Login.Token = authResult["token"].AsString();
                }

                this.Client.PostCallback(new WebLoggedOnCallback()
                {
                    Result = result,
                    Login  = Login
                });
            }
        }
Exemple #3
0
        public bool Authenticate(string myUniqueId, SteamClient client, string myLoginKey)
        {
            mToken = mTokenSecure = "";
            mSessionId = Convert.ToBase64String(Encoding.UTF8.GetBytes(myUniqueId));
            mCookieContainer = 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 = 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)
                {
                    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;
            }
        }
Exemple #4
0
        /// <summary>
        /// Connects and authenticates to the specified content server.
        /// </summary>
        /// <param name="csServer">The content server to connect to.</param>
        /// <exception cref="System.ArgumentNullException">csServer was null.</exception>
        public void Connect(Server csServer)
        {
            DebugLog.Assert(steamClient.IsConnected, "CDNClient", "CMClient is not connected!");

            if (csServer == null)
            {
                throw new ArgumentNullException("csServer");
            }

            byte[] pubKey = KeyDictionary.GetPublicKey(steamClient.ConnectedUniverse);

            sessionKey = CryptoHelper.GenerateRandomBlock(32);

            byte[] cryptedSessKey = null;
            using (var rsa = new RSACrypto(pubKey))
            {
                cryptedSessKey = rsa.Encrypt(sessionKey);
            }

            string data;

            if (appTicket == null)
            {
                // no appticket, doing anonymous connection
                data = string.Format("sessionkey={0}&anonymoususer=1&steamid={1}", WebHelpers.UrlEncode(cryptedSessKey), steamClient.SteamID.ConvertToUInt64());
            }
            else
            {
                byte[] encryptedAppTicket = CryptoHelper.SymmetricEncrypt(appTicket, sessionKey);
                data = string.Format("sessionkey={0}&appticket={1}", WebHelpers.UrlEncode(cryptedSessKey), WebHelpers.UrlEncode(encryptedAppTicket));
            }

            KeyValue initKv = DoCommand(csServer, "initsession", data, WebRequestMethods.Http.Post);

            sessionId  = ( ulong )initKv["sessionid"].AsLong();
            reqCounter = initKv["req-counter"].AsLong();

            if (appTicket == null)
            {
                data = string.Format("depotid={0}", depotId);
            }
            else
            {
                byte[] encryptedAppTicket = CryptoHelper.SymmetricEncrypt(appTicket, sessionKey);
                data = string.Format("appticket={0}", WebHelpers.UrlEncode(encryptedAppTicket));
            }

            DoCommand(csServer, "authdepot", data, WebRequestMethods.Http.Post, true);

            connectedServer = csServer;
        }
        void OnLoginKey(SteamUser.LoginKeyCallback callback)
        {
            string SessionID = WebHelpers.EncodeBase64(callback.UniqueID.ToString());

            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 (var rsa = new RSACrypto(KeyDictionary.GetPublicKey(Client.ConnectedUniverse)))
                {
                    cryptedSessionKey = rsa.Encrypt(sessionKey);
                }

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

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

                KeyValue authResult = null;
                EResult result = EResult.OK;

                try
                {
                    authResult = userAuth.AuthenticateUser(
                        steamid: Client.SteamID.ConvertToUInt64(),
                        sessionkey: WebHelpers.UrlEncode(cryptedSessionKey),
                        encrypted_loginkey: WebHelpers.UrlEncode(cryptedLoginKey),
                        method: "POST"
                    );
                }
                catch (Exception)
                {
                    result = EResult.Fail;
                }

                Login.SessionId = SessionID;

                if (authResult != null)
                    Login.Token = authResult["token"].AsString();

                this.Client.PostCallback(new WebLoggedOnCallback()
                {
                    Result = result,
                    Login = Login
                });
            }
        }
Exemple #6
0
        /// <summary>
        /// Connects this instance to the server.
        /// </summary>
        /// <returns><c>true</c> if the connection was a success; otherwise, <c>false</c>.</returns>
        public bool Connect()
        {
            byte[] encryptedKey = null;

            // TODO: handle other universes?
            byte[] universeKey = KeyDictionary.GetPublicKey(EUniverse.Public);
            using (var rsa = new RSACrypto(universeKey))
            {
                encryptedKey = rsa.Encrypt(sessionKey);
            }

            byte[] encryptedTicket = CryptoHelper.SymmetricEncrypt(appTicket, sessionKey);

            string payload = String.Format("sessionkey={0}&appticket={1}", WebHelpers.UrlEncode(encryptedKey), WebHelpers.UrlEncode(encryptedTicket));

            webClient.Headers.Clear();
            webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            string response;

            try
            {
                response = webClient.UploadString(BuildCommand(endPoint, "initsession"), payload);
            }
            catch (WebException)
            {
                return(false);
            }

            var responsekv  = KeyValue.LoadFromString(response);
            var sessionidn  = responsekv.Children.Where(c => c.Name == "sessionid").First();
            var reqcountern = responsekv.Children.Where(c => c.Name == "req-counter").First();

            sessionID  = (ulong)(sessionidn.AsLong(0));
            reqcounter = reqcountern.AsLong(0);

            try
            {
                AuthDepot();
            }
            catch (WebException)
            {
                return(false);
            }

            return(true);
        }
Exemple #7
0
        /// <summary>
        /// Connects and initializes a session to the specified content server.
        /// </summary>
        /// <param name="csServer">The content server to connect to.</param>
        /// <exception cref="System.ArgumentNullException">csServer was null.</exception>
        /// <exception cref="HttpRequestException">An network error occurred when performing the request.</exception>
        /// <exception cref="SteamKitWebRequestException">A network error occurred when performing the request.</exception>
        public async Task ConnectAsync(Server csServer)
        {
            DebugLog.Assert(steamClient.IsConnected, "CDNClient", "CMClient is not connected!");

            if (csServer == null)
            {
                throw new ArgumentNullException(nameof(csServer));
            }

            // Nothing needs to be done to initialize a session to a CDN server
            if (csServer.Type == "CDN")
            {
                connectedServer = csServer;
                return;
            }

            byte[] pubKey = KeyDictionary.GetPublicKey(steamClient.Universe);

            sessionKey = CryptoHelper.GenerateRandomBlock(32);

            byte[] cryptedSessKey = null;
            using (var rsa = new RSACrypto(pubKey))
            {
                cryptedSessKey = rsa.Encrypt(sessionKey);
            }

            string data;

            if (appTicket == null)
            {
                // no appticket, doing anonymous connection
                data = string.Format("sessionkey={0}&anonymoususer=1&steamid={1}", WebHelpers.UrlEncode(cryptedSessKey), steamClient.SteamID.ConvertToUInt64());
            }
            else
            {
                byte[] encryptedAppTicket = CryptoHelper.SymmetricEncrypt(appTicket, sessionKey);
                data = string.Format("sessionkey={0}&appticket={1}", WebHelpers.UrlEncode(cryptedSessKey), WebHelpers.UrlEncode(encryptedAppTicket));
            }

            var initKv = await DoCommandAsync(csServer, HttpMethod.Post, "initsession", data).ConfigureAwait(false);

            sessionId       = initKv["sessionid"].AsUnsignedLong();
            reqCounter      = initKv["req-counter"].AsLong();
            connectedServer = csServer;
        }
Exemple #8
0
        void HandleEncryptRequest(IPacketMsg packetMsg)
        {
            var encRequest = new Msg <MsgChannelEncryptRequest>(packetMsg);

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

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

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

            if (pubKey == null)
            {
                DebugLog.WriteLine("UFSClient", "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);
        }
Exemple #9
0
        void HandleEncryptRequest( IPacketMsg packetMsg )
        {
            var encRequest = new Msg<MsgChannelEncryptRequest>( packetMsg );

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

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

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

            if ( pubKey == null )
            {
                DebugLog.WriteLine( "UFSClient", "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 );
        }
Exemple #10
0
        /// <summary>
        /// Connects and authenticates to the specified content server.
        /// </summary>
        /// <param name="csServer">The content server to connect to.</param>
        /// <exception cref="System.ArgumentNullException">csServer was null.</exception>
        public void Connect( Server csServer )
        {
            DebugLog.Assert( steamClient.IsConnected, "CDNClient", "CMClient is not connected!" );

            if ( csServer == null )
                throw new ArgumentNullException( "csServer" );

            byte[] pubKey = KeyDictionary.GetPublicKey( steamClient.ConnectedUniverse );

            sessionKey = CryptoHelper.GenerateRandomBlock( 32 );

            byte[] cryptedSessKey = null;
            using ( var rsa = new RSACrypto( pubKey ) )
            {
                cryptedSessKey = rsa.Encrypt( sessionKey );
            }

            string data;

            if ( appTicket == null )
            {
                // no appticket, doing anonymous connection
                data = string.Format( "sessionkey={0}&anonymoususer=1&steamid={1}", WebHelpers.UrlEncode( cryptedSessKey ), steamClient.SteamID.ConvertToUInt64() );
            }
            else
            {
                byte[] encryptedAppTicket = CryptoHelper.SymmetricEncrypt( appTicket, sessionKey );
                data = string.Format( "sessionkey={0}&appticket={1}", WebHelpers.UrlEncode( cryptedSessKey ), WebHelpers.UrlEncode( encryptedAppTicket ) );
            }

            KeyValue initKv = DoCommand( csServer, "initsession", data, WebRequestMethods.Http.Post );

            sessionId = ( ulong )initKv[ "sessionid" ].AsLong();
            reqCounter = initKv[ "req-counter" ].AsLong();

            if ( appTicket == null )
            {
                data = string.Format( "depotid={0}", depotId );
            }
            else
            {
                byte[] encryptedAppTicket = CryptoHelper.SymmetricEncrypt( appTicket, sessionKey );
                data = string.Format( "appticket={0}", WebHelpers.UrlEncode( encryptedAppTicket ) );
            }

            DoCommand( csServer, "authdepot", data, WebRequestMethods.Http.Post, true );

            connectedServer = csServer;
        }
Exemple #11
0
        void HandleEncryptRequest( IPacketMsg packetMsg )
        {
            var encRequest = new Msg<MsgChannelEncryptRequest>( packetMsg );

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

            DebugLog.WriteLine( "UFSClient", "Got encryption request. Universe: {0} Protocol ver: {1}", eUniv, protoVersion );
            DebugLog.Assert( protoVersion == 1, "UFSClient", "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( "UFSClient", "HandleEncryptionRequest got request for invalid universe! Universe: {0} Protocol ver: {1}", eUniv, protoVersion );
                return;
            }

            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 );
        }
Exemple #12
0
        void HandleEncryptRequest(IPacketMsg packetMsg)
        {
            var encRequest = new Msg <MsgChannelEncryptRequest>(packetMsg);

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

            DebugLog.WriteLine("UFSClient", "Got encryption request. Universe: {0} Protocol ver: {1}", eUniv, protoVersion);
            DebugLog.Assert(protoVersion == 1, "UFSClient", "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("UFSClient", "HandleEncryptionRequest got request for invalid universe! Universe: {0} Protocol ver: {1}", eUniv, protoVersion);
                return;
            }

            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);
        }
		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)) {
				Bot.ArchiLogger.LogNullError(nameof(steamID) + " || " + nameof(universe) + " || " + nameof(webAPIUserNonce) + " || " + nameof(parentalPin));
				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
			Bot.ArchiLogger.LogGenericInfo("Logging in to ISteamUserAuth...");

			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) {
					Bot.ArchiLogger.LogGenericException(e);
					return false;
				}
			}

			if (authResult == null) {
				Bot.ArchiLogger.LogNullError(nameof(authResult));
				return false;
			}

			string steamLogin = authResult["token"].Value;
			if (string.IsNullOrEmpty(steamLogin)) {
				Bot.ArchiLogger.LogNullError(nameof(steamLogin));
				return false;
			}

			string steamLoginSecure = authResult["tokensecure"].Value;
			if (string.IsNullOrEmpty(steamLoginSecure)) {
				Bot.ArchiLogger.LogNullError(nameof(steamLoginSecure));
				return false;
			}

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

			WebBrowser.CookieContainer.Add(new Cookie("steamLogin", steamLogin, "/", "." + SteamCommunityHost));
			WebBrowser.CookieContainer.Add(new Cookie("steamLogin", steamLogin, "/", "." + SteamStoreHost));

			WebBrowser.CookieContainer.Add(new Cookie("steamLoginSecure", steamLoginSecure, "/", "." + SteamCommunityHost));
			WebBrowser.CookieContainer.Add(new Cookie("steamLoginSecure", steamLoginSecure, "/", "." + SteamStoreHost));

			Bot.ArchiLogger.LogGenericInfo("Success!");

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

			Ready = true;
			LastSessionRefreshCheck = DateTime.Now;
			return true;
		}
		internal async Task Init(SteamClient steamClient, string webAPIUserNonce, string vanityURL, string parentalPin) {
			if (steamClient == null || steamClient.SteamID == null || string.IsNullOrEmpty(webAPIUserNonce)) {
				return;
			}

			SteamID = steamClient.SteamID;
			VanityURL = vanityURL;

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

			// 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 = null;
			using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(steamClient.ConnectedUniverse))) {
				cryptedSessionKey = rsa.Encrypt(sessionKey);
			}

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

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

			// Send the magic
			KeyValue authResult;
			Logging.LogGenericInfo(Bot.BotName, "Logging in to ISteamUserAuth...");
			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: true
					);
				} catch (Exception e) {
					Logging.LogGenericException(Bot.BotName, e);
					steamClient.Disconnect(); // We may get 403 if we use the same webAPIUserNonce twice
					return;
				}
			}

			if (authResult == null) {
				steamClient.Disconnect(); // Try again
				return;
			}

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

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

			SteamCookieDictionary.Clear();
			SteamCookieDictionary.Add("sessionid", sessionID);
			SteamCookieDictionary.Add("steamLogin", steamLogin);
			SteamCookieDictionary.Add("steamLoginSecure", steamLoginSecure);
			SteamCookieDictionary.Add("birthtime", "-473356799"); // ( ͡° ͜ʖ ͡°)

			if (!string.IsNullOrEmpty(parentalPin) && !parentalPin.Equals("0")) {
				Logging.LogGenericInfo(Bot.BotName, "Unlocking parental account...");
				Dictionary<string, string> postData = new Dictionary<string, string>() {
					{"pin", parentalPin}
				};

				HttpResponseMessage response = await Utilities.UrlPostRequestWithResponse("https://steamcommunity.com/parental/ajaxunlock", postData, SteamCookieDictionary, "https://steamcommunity.com/").ConfigureAwait(false);
				if (response != null && response.IsSuccessStatusCode) {
					Logging.LogGenericInfo(Bot.BotName, "Success!");

					var setCookieValues = response.Headers.GetValues("Set-Cookie");
					foreach (string setCookieValue in setCookieValues) {
						if (setCookieValue.Contains("steamparental=")) {
							string setCookie = setCookieValue.Substring(setCookieValue.IndexOf("steamparental=") + 14);
							setCookie = setCookie.Substring(0, setCookie.IndexOf(';'));
							SteamCookieDictionary.Add("steamparental", setCookie);
							break;
						}
					}
				} else {
					Logging.LogGenericInfo(Bot.BotName, "Failed!");
				}
			}

			Bot.Trading.CheckTrades();
		}
Exemple #15
0
        void HandleEncryptRequest( IPacketMsg packetMsg )
        {
            var request = new Msg<MsgChannelEncryptRequest>( packetMsg );

            var connectedUniverse = request.Body.Universe;
            var protoVersion = request.Body.ProtocolVersion;

            log.LogDebug( nameof(EnvelopeEncryptedConnection), "Got encryption request. Universe: {0} Protocol ver: {1}", connectedUniverse, protoVersion );
            DebugLog.Assert( protoVersion == 1, nameof(EnvelopeEncryptedConnection), "Encryption handshake protocol version mismatch!" );
            DebugLog.Assert( connectedUniverse == universe, nameof(EnvelopeEncryptedConnection), FormattableString.Invariant( $"Expected universe {universe} but server reported universe {connectedUniverse}" ) );

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

            var publicKey = KeyDictionary.GetPublicKey( connectedUniverse );

            if ( publicKey == null )
            {
                log.LogDebug( nameof(EnvelopeEncryptedConnection), "HandleEncryptRequest got request for invalid universe! Universe: {0} Protocol ver: {1}", connectedUniverse, protoVersion );

                Disconnect( userInitiated: false );
                return;
            }

            var response = new Msg<MsgChannelEncryptResponse>();
            
            var tempSessionKey = CryptoHelper.GenerateRandomBlock( 32 );
            byte[] encryptedHandshakeBlob;
            
            using ( var rsa = new RSACrypto( publicKey ) )
            {
                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 );

            response.Write( encryptedHandshakeBlob );
            response.Write( keyCrc );
            response.Write( ( uint )0 );
            
            if (randomChallenge != null)
            {
                encryption = new NetFilterEncryptionWithHMAC( tempSessionKey, log );
            }
            else
            {
                encryption = new NetFilterEncryption( tempSessionKey, log );
            }

            var serialized = response.Serialize();

            try
            {
                debugNetworkListener?.OnOutgoingNetworkMessage( response.MsgType, serialized );
            }
            catch ( Exception e )
            {
                log.LogDebug( nameof( EnvelopeEncryptedConnection ), "DebugNetworkListener threw an exception: {0}", e );
            }

            state = EncryptionState.Challenged;
            Send( serialized );
        }
		internal async Task<bool> Init(SteamClient steamClient, string webAPIUserNonce, string vanityURL, string parentalPin) {
			if (steamClient == null || steamClient.SteamID == null || string.IsNullOrEmpty(webAPIUserNonce)) {
				return false;
			}

			SteamID = steamClient.SteamID;
			VanityURL = vanityURL;

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

			// 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 = null;
			using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(steamClient.ConnectedUniverse))) {
				cryptedSessionKey = rsa.Encrypt(sessionKey);
			}

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

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

			// Send the magic
			KeyValue authResult;
			Logging.LogGenericInfo(Bot.BotName, "Logging in to ISteamUserAuth...");
			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: true
					);
				} catch (Exception e) {
					Logging.LogGenericException(Bot.BotName, e);
					return false;
				}
			}

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

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

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

			Cookie["sessionid"] = sessionID;
			Cookie["steamLogin"] = steamLogin;
			Cookie["steamLoginSecure"] = steamLoginSecure;
			Cookie["birthtime"] = "-473356799";

			await UnlockParentalAccount(parentalPin).ConfigureAwait(false);
			return true;
		}
Exemple #17
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(SteamUser.LoginKeyCallback callback, SteamClient client, out string sessionId, out string token)
        {
            sessionId = Convert.ToBase64String (Encoding.UTF8.GetBytes (callback.UniqueID.ToString ()));

            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 (callback.LoginKey), loginKey, callback.LoginKey.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"
                        );
                }
                catch (Exception)
                {
                    token = null;
                    return false;
                }

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

                return true;
            }
        }
Exemple #18
0
		// Authenticate. This does the same as SteamWeb.DoLogin(),
		// but without contacting the Steam Website.
		// Should this one doesnt work anymore, use SteamWeb.DoLogin().
		bool Authenticate(SteamUser.LoginKeyCallback callback) {
			sessionId = WebHelpers.EncodeBase64(callback.UniqueID.ToString());

			Util.printConsole("Got login key, performing web auth...", this, ConsoleColor.Magenta, true);

			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 (var rsa = new RSACrypto(KeyDictionary.GetPublicKey(SteamClient.ConnectedUniverse))) {
					cryptedSessionKey = rsa.Encrypt(sessionKey);
				}

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

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

				KeyValue authResult;

				try {
					authResult = userAuth.AuthenticateUser(
						steamid:SteamClient.SteamID.ConvertToUInt64(),
						sessionkey:WebHelpers.UrlEncode(cryptedSessionKey),
						encrypted_loginkey:WebHelpers.UrlEncode(cryptedLoginKey),
						method:"POST"
					);
				} catch (Exception) {
					return false;
				}

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

				return true;
			}
		}
Exemple #19
0
        /// <summary>
        /// Connects this instance to the server.
        /// </summary>
        /// <returns><c>true</c> if the connection was a success; otherwise, <c>false</c>.</returns>
        public bool Connect()
        {

            byte[] encryptedKey = null;

            // TODO: handle other universes?
            byte[] universeKey = KeyDictionary.GetPublicKey( EUniverse.Public );
            using ( var rsa = new RSACrypto( universeKey ) )
            {
                encryptedKey = rsa.Encrypt( sessionKey );
            }

            byte[] encryptedTicket = CryptoHelper.SymmetricEncrypt(appTicket, sessionKey);

            string payload = String.Format("sessionkey={0}&appticket={1}", WebHelpers.UrlEncode(encryptedKey), WebHelpers.UrlEncode(encryptedTicket));

            webClient.Headers.Clear();
            webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            string response;
            try
            {
                response = webClient.UploadString(BuildCommand(endPoint, "initsession"), payload);
            }
            catch (WebException)
            {
                return false;
            }

            var responsekv = KeyValue.LoadFromString(response);
            var sessionidn = responsekv.Children.Where(c => c.Name == "sessionid").First();
            var reqcountern = responsekv.Children.Where(c => c.Name == "req-counter").First();

            sessionID = (ulong)(sessionidn.AsLong(0));
            reqcounter = reqcountern.AsLong(0);

            try
            {
                AuthDepot();
            }
            catch (WebException)
            {
                return false;
            }

            return true;
        }
		internal bool Init(SteamClient steamClient, string webAPIUserNonce, string parentalPin) {
			if (steamClient == null || steamClient.SteamID == null || string.IsNullOrEmpty(webAPIUserNonce)) {
				return false;
			}

			ulong 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);

			WebBrowser.CookieContainer.Add(new Cookie("sessionid", sessionID, "/", "." + SteamCommunity));

			string steamLogin = authResult["token"].Value;
			WebBrowser.CookieContainer.Add(new Cookie("steamLogin", steamLogin, "/", "." + SteamCommunity));

			string steamLoginSecure = authResult["tokensecure"].Value;
			WebBrowser.CookieContainer.Add(new Cookie("steamLoginSecure", steamLoginSecure, "/", "." + SteamCommunity));

			if (!UnlockParentalAccount(parentalPin).Result) {
				return false;
			}

			LastSessionRefreshCheck = DateTime.Now;
			return true;
		}