public static RelayResponse ResetPassword(RelayMessage message)
        {
            var credential = Utils.ConvertDynamic <PasswordReset>(message.Data);

            var res = new RelayResponse
            {
                Operation          = SiteOperation.ResetPW,
                OriginConnectionId = message.OriginConnectionId,
                Identifier         = message.Identifier,
                OriginSiteId       = message.OriginSiteId,
                Data = credential.UserName
            };

            var user = GetUserPrincipal(credential.UserName);

            user.SetPassword(credential.NewPassword);
            user.Save();

            if (credential.Unlock)
            {
                user.UnlockAccount();
                user.Save();
            }

            if (credential.SetChangePasswordAtNextLogon)
            {
                user.ExpirePasswordNow();
            }

            return(res);
        }
        public static RelayResponse SetUserStatus(ADUser user)
        {
            var res = new RelayResponse
            {
                Operation = SiteOperation.SetUserStatus
            };

            try
            {
                UserPrincipal userPrincipal = GetUserPrincipal(user.OrgSamAccountName);
                userPrincipal.Enabled = user.Enabled;
                userPrincipal.AccountExpirationDate    = user.AccountExpirationDate;
                userPrincipal.PasswordNeverExpires     = user.PasswordNeverExpires;
                userPrincipal.SmartcardLogonRequired   = user.SmartcardLogonRequired;
                userPrincipal.UserCannotChangePassword = user.UserCannotChangePassword;
                if (user.OrgSamAccountName != user.SamAccountName)
                {
                    userPrincipal.SamAccountName = user.SamAccountName;
                }
                userPrincipal.Save();
                return(res);
            }
            catch (Exception ex)
            {
                res.Success      = false;
                res.ErrorMessage = ex.Message;
                return(res);
            }
        }
        public static RelayResponse GetUserStatus(string localGuid)
        {
            var res = new RelayResponse
            {
                Operation = SiteOperation.GetUserStatus
            };

            try
            {
                UserPrincipal p = GetUserPrincipal(localGuid);

                var usr = new ADUser
                {
                    AccountExpirationDate = p.AccountExpirationDate,
                    AccountLockoutTime    = p.AccountLockoutTime,
                    BadLogonCount         = p.BadLogonCount,
                    Enabled = p.Enabled,
                    LastBadPasswordAttempt = p.LastBadPasswordAttempt,
                    LastLogon                = p.LastLogon,
                    LastPasswordSet          = p.LastPasswordSet,
                    PasswordNeverExpires     = p.PasswordNeverExpires,
                    SamAccountName           = p.SamAccountName,
                    SmartcardLogonRequired   = p.SmartcardLogonRequired,
                    UserCannotChangePassword = p.UserCannotChangePassword
                };
                res.Data = usr;
                return(res);
            }
            catch (Exception ex)
            {
                res.Success      = false;
                res.ErrorMessage = ex.Message;
                return(res);
            }
        }
Exemplo n.º 4
0
        public static async Task <RelayResponse> GetUserStatus(StagedUser user)
        {
            try
            {
                var client = new SigRClient(Settings.AdminSiteUrl, Settings.STSApiKey, "SiteHub");

                var msg = new RelayMessage
                {
                    ApiKey     = Settings.AdminApiKey,
                    Data       = user.LocalGuid,
                    DestSiteId = user.SiteId,
                    Identifier = user.Upn,
                    Operation  = SiteOperation.GetUserStatus
                };

                await client.StartAsync();

                RelayResponse res = await client.ProcessRelayMessage(msg);

                return(res);
            }
            catch (Exception ex)
            {
                Utils.AddLogEntry("Error getting user status", EventLogEntryType.Error, 0, ex);
                return(new RelayResponse
                {
                    Success = false,
                    ErrorMessage = ex.Message
                });
            }
        }
Exemplo n.º 5
0
        public static async Task <RelayResponse> ResetPassword(PasswordReset credential, StagedUser stagedUser)
        {
            try
            {
                var client = new SigRClient(Settings.AdminSiteUrl, Settings.STSApiKey, "SiteHub");
                var data   = JsonConvert.SerializeObject(credential);

                var msg = new RelayMessage
                {
                    ApiKey     = Settings.AdminApiKey,
                    Data       = data,
                    DestSiteId = stagedUser.SiteId,
                    Identifier = stagedUser.Id,
                    Operation  = SiteOperation.ResetPW
                };

                await client.StartAsync();

                RelayResponse res = await client.ProcessRelayMessage(msg);

                return(res);
            }
            catch (Exception ex)
            {
                Utils.AddLogEntry("Error setting user status", EventLogEntryType.Error, 0, ex);
                return(new RelayResponse
                {
                    Success = false,
                    ErrorMessage = ex.Message
                });
            }
        }
        /// <summary>
        /// Executed when response for a request is sent back.
        /// </summary>
        /// <param name="requestId">Unique request Id.</param>
        /// <param name="relayResponse">The response being sent back.</param>
        /// <returns>Task tracking operation.</returns>
        public Task ResponseSentAsync(string requestId, RelayResponse relayResponse)
        {
            this.Dispatcher.Invoke(() =>
            {
                this.logger.LogTrace("Updating request with Id '{0}'", requestId);

                if (this.requestMap.ContainsKey(requestId))
                {
                    try
                    {
                        RequestDetails requestDetails  = this.requestMap[requestId];
                        requestDetails.ResponseData    = this.GetUIFriendlyString(relayResponse.OutputStream, relayResponse.Headers[HttpResponseHeader.ContentType], relayResponse.Headers[HttpResponseHeader.ContentEncoding]);
                        requestDetails.ResponseHeaders = relayResponse.Headers.GetHeaderMap();
                        requestDetails.StatusCode      = relayResponse.HttpStatusCode.ToString();
                        requestDetails.Duration        = (relayResponse.RequestEndDateTime.DateTime - requestDetails.RequestReceiveTime).TotalMilliseconds + " ms";

                        // For a Change event to fire we need to completely replace the object so we are cloning the object and replacing it.
                        this.requestMap[requestId] = JObject.FromObject(requestDetails).ToObject <RequestDetails>();
                    }
                    catch (Exception ex)
                    {
                        this.logger.LogWarning(ex, "Hit exception while updating request with Id '{0}'.", requestId);
                    }
                }
            });

            return(Task.CompletedTask);
        }
Exemplo n.º 7
0
        private Nethereum.Signer.Transaction ConvertToTx(RelayResponse response)
        {
            var tx = new Nethereum.Signer.Transaction(
                response.To,
                response.Value.Value,
                response.Nonce.Value,
                response.GasPrice.Value,
                response.Gas.Value,
                response.Input);

            tx.SetSignature(new EthECDSASignature(
                                new Org.BouncyCastle.Math.BigInteger(response.R.RemoveHexPrefix(), 16),
                                new Org.BouncyCastle.Math.BigInteger(response.S.RemoveHexPrefix(), 16),
                                response.V.HexToByteArray()));

            return(tx);
        }
Exemplo n.º 8
0
        public static Transaction ToTransaction(this RelayResponse response)
        {
            var tx = new Transaction(
                response.To,
                response.Value.Value,
                response.Nonce.Value,
                response.GasPrice.Value,
                response.Gas.Value,
                response.Input);

            tx.SetSignature(new EthECDSASignature(
                                new Org.BouncyCastle.Math.BigInteger(response.R.RemoveHexPrefix(), 16),
                                new Org.BouncyCastle.Math.BigInteger(response.S.RemoveHexPrefix(), 16),
                                response.V.HexToByteArray()));

            return(tx);
        }
        public static RelayResponse EnableDisableUser(string username, bool enabled)
        {
            var res = new RelayResponse();

            try
            {
                UserPrincipal userPrincipal = GetUserPrincipal(username);
                userPrincipal.Enabled = enabled;
                userPrincipal.Save();
                return(res);
            }
            catch (Exception ex)
            {
                res.Success      = false;
                res.ErrorMessage = ex.Message;
                return(res);
            }
        }
Exemplo n.º 10
0
        private void ValidateTx(
            RelayResponse returnedTx,
            TransactionInput transaction,
            BigInteger txFee,
            BigInteger gasPrice,
            BigInteger gasLimit,
            BigInteger nonce,
            string relayHubAddress,
            string relayAddress)
        {
            var tx     = returnedTx.ToTransaction();
            var signer = tx.Key.GetPublicAddress();

            var functionEncodingService = new FunctionMessageEncodingService <RelayCallFunction>();
            var relayCall = functionEncodingService.DecodeInput(new RelayCallFunction(), returnedTx.Input);

            var returnedTxHash = GetTransactionHash(
                relayCall.From,
                relayCall.To,
                relayCall.EncodedFunction.ToHex(),
                relayCall.TransactionFee,
                relayCall.GasPriceParam,
                relayCall.GasLimit,
                relayCall.NonceParam,
                returnedTx.To,
                signer);

            var hash = GetTransactionHash(
                transaction.From,
                transaction.To,
                transaction.Data,
                txFee,
                transaction.GasPrice.Value,
                transaction.Gas.Value,
                nonce,
                relayHubAddress,
                relayAddress);

            if (returnedTxHash.EnsureHexPrefix().ToLower() != hash.EnsureHexPrefix().ToLower() ||
                signer.EnsureHexPrefix().ToLower() != relayAddress.EnsureHexPrefix().ToLower())
            {
                throw new GSNRelayInvalidResponseException();
            }
        }
        public static RelayResponse GetScriptVersion(RelayMessage message)
        {
            var res = new RelayResponse();

            try
            {
                var dir  = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                var path = Path.GetFullPath(string.Format("{0}\\Scripts\\ScriptVersion.txt", dir));
                res.Data    = File.ReadAllText(path);
                res.Success = true;
                return(res);
            }
            catch (Exception ex)
            {
                res.Success      = false;
                res.ErrorMessage = ex.Message;
                return(res);
            }
        }
        /// <summary>
        /// Processes an event when response is sent.
        /// </summary>
        /// <param name="requestId">Unique Id of the request.</param>
        /// <param name="relayResponse">Relay response.</param>
        /// <returns>Task tracking operation.</returns>
        public Task ResponseSentAsync(string requestId, RelayResponse relayResponse)
        {
            lock (this.lockObject)
            {
                RequestConsoleDetails requestConsoleDetails = this.requestConsoleDetailsMap[requestId];
                this.requestConsoleDetailsMap.Remove(requestId);

                Console.SetCursorPosition(
                    0,
                    requestConsoleDetails.RequestConsoleTopCursor + 1);

                Console.Write(string.Format(
                                  CultureInfo.InvariantCulture,
                                  " -----> {0} - {1}",
                                  relayResponse.HttpStatusCode.ToString(),
                                  (DateTime.Now - requestConsoleDetails.RequestStartTime).TotalMilliseconds));
                Console.WriteLine();
            }

            return(Task.CompletedTask);
        }
        /// <summary>
        /// Site will reset the ADUser password from the admin portal
        /// </summary>
        /// <param name="credential"></param>
        private static void LogPWReset(RelayResponse response)
        {
            SyncLogEntry log;

            if (response.Success)
            {
                log = new SyncLogEntry(
                    EventLogEntryType.SuccessAudit,
                    string.Format("Password was reset for {0}", response.Data),
                    "SiteAgent.SiteOp.ResetPW",
                    response.Identifier);
            }
            else
            {
                log = new SyncLogEntry(
                    EventLogEntryType.FailureAudit,
                    string.Format("Password reset failed for {0} (error: {1})", response.Data, response.ErrorMessage),
                    "SiteAgent.SiteOp.ResetPW",
                    response.Identifier);
            }
            OrgApiCalls.AddSyncLog(log);
        }
        public static RelayResponse UpdateUser(StagedUser user)
        {
            var res = new RelayResponse
            {
                Operation = SiteOperation.UpdateUser
            };

            try
            {
                var principal = GetUserPrincipal(user.Upn);
                principal.GivenName            = user.GivenName;
                principal.Surname              = user.Surname;
                principal.DisplayName          = user.DisplayName;
                principal.Name                 = user.Name;
                principal.EmailAddress         = user.Mail;
                principal.VoiceTelephoneNumber = user.TelephoneNumber;

                var de = (DirectoryEntry)principal.GetUnderlyingObject();
                de.Properties["title"].Value         = user.Title;
                de.Properties["streetAddress"].Value = user.StreetAddress;
                de.Properties["st"].Value            = user.State;
                de.Properties["postalCode"].Value    = user.PostalCode;
                de.Properties["mobile"].Value        = user.Mobile;
                de.Properties["homePhone"].Value     = user.HomePhone;
                de.Properties["department"].Value    = user.Department;
                de.Properties["c"].Value             = user.Country;
                de.Properties["l"].Value             = user.City;
                de.CommitChanges();
                principal.Save();
                return(res);
            }
            catch (Exception ex)
            {
                res.Success      = false;
                res.ErrorMessage = ex.Message;
                return(res);
            }
        }
 /// <summary>
 /// Called by the responding site to send relay response back to the hub for forwarding to the requester
 /// </summary>
 /// <param name="res"></param>
 private void ForwardRelayResponse(RelayResponse response)
 {
     SendStatus("Calling forward relay response for {0} from {1}...", response.Operation.ToString(), response.OriginSiteId);
     _siteHubProxy.Invoke <RelayResponse>("ForwardRelayResponse", response);
 }
Exemplo n.º 16
0
 /// <summary>
 /// When a relay response is returned from a site, this method forwards the response back to the STS (which is also a relay client)
 /// </summary>
 /// <param name="response"></param>
 public void ForwardRelayResponse(RelayResponse response)
 {
     Clients.Client(response.OriginConnectionId).ProcessRelayResponse(response);
 }
Exemplo n.º 17
0
        private async Task <string> SendViaRelay(
            string relayUrl,
            TransactionInput transaction,
            BigInteger txFee,
            BigInteger gasPrice,
            BigInteger gasLimit,
            BigInteger nonce,
            string relayHubAddress,
            string relayAddress,
            string signature,
            string approvalData,
            BigInteger relayMaxNonce)
        {
            var requestData = new RelayRequest
            {
                EncodedFunction = transaction.Data,
                Signature       = signature.HexToByteArray(),
                ApprovalData    = approvalData.HexToByteArray(),
                From            = transaction.From,
                To              = transaction.To,
                GasPrice        = gasPrice,
                GasLimit        = gasLimit,
                RelayFee        = txFee,
                RecipientNonce  = nonce,
                RelayMaxNonce   = relayMaxNonce,
                RelayHubAddress = relayHubAddress,
                UserAgent       = _options.UserAgent
            };

            RelayResponse relayResponse = await _relayClient.RelayAsync(new Uri(relayUrl), requestData)
                                          .ConfigureAwait(false);

            if (!string.IsNullOrEmpty(relayResponse.Error))
            {
                throw new Exception(relayResponse.Error);
            }

            if (relayResponse.Nonce.Value.IsZero)
            {
                throw new Exception("Empty body received from server, or neither 'error' nor 'nonce' fields present.");
            }

            ValidateTx(
                relayResponse,
                transaction,
                txFee,
                gasPrice,
                gasLimit,
                nonce,
                relayHubAddress,
                relayAddress);

            var    tx   = relayResponse.ToTransaction();
            string hash = string.Empty;
            var    ethSendTransaction = new EthSendRawTransaction(_client);

            try
            {
                hash = await ethSendTransaction.SendRequestAsync(tx.GetRLPEncoded().ToHex().EnsureHexPrefix())
                       .ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                if (!ex.Message.Contains("the tx doesn't have the correct nonce") &&
                    !ex.Message.Contains("known transaction") &&
                    !ex.Message.Contains("nonce too low"))
                {
                    throw ex;
                }
            }

            var txHash = relayResponse.Hash;

            if (!string.IsNullOrEmpty(hash) &&
                relayResponse.Hash.EnsureHexPrefix().ToLower() != hash.EnsureHexPrefix().ToLower())
            {
                txHash = hash;
            }

            return(txHash);
        }