示例#1
0
        public override string ToString()
        {
            var sb = new StringBuilder();

            sb.Append("Message Type (op): ").AppendLine(MessageType.ToString());
            sb.Append("Hardware Address Type (htype): ").AppendLine(HardwareAddressType.ToString());
            sb.Append("Hardware Address Length (hlen): ").AppendLine(HardwareAddressLength.ToString());
            sb.Append("Gateway Hops (hops): ").AppendLine(GatewayHops.ToString());
            sb.Append("Transaction Id (xid): ").AppendLine(TransactionId.ToString());
            sb.Append("Seconds Elapsed (secs): ").AppendLine(SecondsElapsed.ToString());
            sb.Append("Flags (flags): ").AppendLine(Convert.ToString((int)Flags, 2));
            foreach (DhcpServerPacketFlags flag in Enum.GetValues(typeof(DhcpServerPacketFlags)))
            {
                sb.Append("    ");
                var mask = Convert.ToString((short)flag, 2).Replace('0', '.');
                if (Flags.HasFlag(flag))
                {
                    sb.Append(mask).Append(": ").AppendLine(flag.ToString());
                }
                else
                {
                    sb.Append(mask.Replace('1', '0')).Append(": No ").AppendLine(flag.ToString());
                }
            }
            sb.Append("Client IP Address (ciaddr): ").AppendLine(ClientIpAddress.ToString());
            sb.Append("Your IP Address (yiaddr): ").AppendLine(YourIpAddress.ToString());
            sb.Append("Next Server IP Address (siaddr): ").AppendLine(NextServerIpAddress.ToString());
            sb.Append("Relay Agent IP Address (giaddr): ").AppendLine(RelayAgentIpAddress.ToString());
            sb.Append("Client Hardware Address (chaddr): ").AppendLine(ClientHardwareAddress.ToString());
            sb.Append("Server Host Name (sname): ").AppendLine(ServerHostName);
            sb.Append("File Name (file): ").AppendLine(FileName);
            sb.Append("Options Magic Cookie: ").AppendLine(OptionsMagicCookie.ToString());

            var options = Options.ToList();

            if (options.Count == 0)
            {
                sb.Append("Options: None");
            }
            else
            {
                sb.Append("Options:");
                foreach (var option in options)
                {
                    sb.AppendLine();
                    sb.Append("    ");
                    sb.Append(((byte)option.Id).ToString("000"));
                    sb.Append(" ");
                    sb.Append(option.Id.ToString());
                    sb.Append(" [");
                    sb.Append(option.Type.ToString());
                    sb.AppendLine("]");
                    sb.Append("        ");
                    option.DataAsFormatted(sb);
                }
            }

            return(sb.ToString());
        }
示例#2
0
 public override int GetHashCode()
 {
     unchecked {
         int hashCode = UserAgent?.GetHashCode() ?? 0;
         hashCode = (hashCode * 397) ^ (HttpMethod?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ IsSecure.GetHashCode();
         hashCode = (hashCode * 397) ^ (Host?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ Port;
         hashCode = (hashCode * 397) ^ (Path?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Referrer?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (ClientIpAddress?.GetHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Cookies?.GetCollectionHashCode(_cookieHashCodeExclusions) ?? 0);
         hashCode = (hashCode * 397) ^ (QueryString?.GetCollectionHashCode() ?? 0);
         hashCode = (hashCode * 397) ^ (Data?.GetCollectionHashCode() ?? 0);
         return(hashCode);
     }
 }
示例#3
0
 public override int GetHashCode()
 {
     unchecked {
         var hashCode = UserAgent == null ? 0 : UserAgent.GetHashCode();
         hashCode = (hashCode * 397) ^ (HttpMethod == null ? 0 : HttpMethod.GetHashCode());
         hashCode = (hashCode * 397) ^ IsSecure.GetHashCode();
         hashCode = (hashCode * 397) ^ (Host == null ? 0 : Host.GetHashCode());
         hashCode = (hashCode * 397) ^ Port;
         hashCode = (hashCode * 397) ^ (Path == null ? 0 : Path.GetHashCode());
         hashCode = (hashCode * 397) ^ (Referrer == null ? 0 : Referrer.GetHashCode());
         hashCode = (hashCode * 397) ^ (ClientIpAddress == null ? 0 : ClientIpAddress.GetHashCode());
         hashCode = (hashCode * 397) ^ (Cookies == null ? 0 : Cookies.GetCollectionHashCode(_cookieHashCodeExclusions));
         hashCode = (hashCode * 397) ^ (QueryString == null ? 0 : QueryString.GetCollectionHashCode());
         hashCode = (hashCode * 397) ^ (Data == null ? 0 : Data.GetCollectionHashCode());
         return(hashCode);
     }
 }
示例#4
0
        public ActionResult ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (_authRepository.AlreadyExists(model.Email))
                {
                    var token     = AuthEncryption.RandomSalt(6);
                    var result    = _authRepository.SetPasswordResetToken(model.Email, token);
                    var userIp    = ClientIpAddress.GetIPAddress(Request);
                    var secureUrl = Url.Action("TryResetPassword", "Account", new { e = model.Email, c = token }, "https");
                    //var linkUrl = Url.AbsoluteAction("TryResetPassword", "Account", new { e = model.Email, c = token });
                    string mailBody = MailCommonStrings.PasswordResetBody(userIp, secureUrl);
                    Mailer.SendEmail_NoWait(model.Email, MailCommonStrings.ResetPasswordSubject, mailBody);
                    _logger.Debug(string.Format("{0} has requested to reset their password from {1}", model.Email, ClientIpAddress.GetIPAddress(Request)));
                }
                MvcCaptcha.ResetCaptcha("ResetPasswordCaptcha");
                return(RedirectToAction("PasswordResetSent"));
            }

            return(View());
        }
示例#5
0
        public ActionResult Reverify(ReverifyViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (_authRepository.AlreadyExists(model.Email))
                {
                    var token     = AuthEncryption.RandomSalt(6);
                    var result    = _authRepository.SetEmailConfirmationToken(model.Email, token);
                    var secureUrl = Url.Action("ConfirmEmail", "Account", new { e = model.Email, c = token }, "https");
                    //var linkUrl = Url.AbsoluteAction("ConfirmEmail", "Account", new { e = model.Email, c = token });
                    string mailBody = MailCommonStrings.RegisteredBody(secureUrl);
                    Mailer.SendEmail_NoWait(model.Email, MailCommonStrings.RegisteredSubject, mailBody);
                    _logger.Debug(string.Format("{0} has requested another verification email from {1}", model.Email, ClientIpAddress.GetIPAddress(Request)));
                }
                MvcCaptcha.ResetCaptcha("ReverifyCaptcha");
                return(RedirectToAction("ReverificationSent"));
            }

            return(View());
        }
示例#6
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (!_authRepository.AlreadyExists(model.Email))
                {
                    // Try and send the confirmation email first. If that works, and the email is valid, then add it here.

                    var result = _authRepository.Register(model.Email, model.Password);
                    if (result.Success)
                    {
                        // Generate an email confirmation token for this account
                        var token = AuthEncryption.RandomSalt(6);
                        result = _authRepository.SetEmailConfirmationToken(model.Email, token);
                        var secureUrl = Url.Action("ConfirmEmail", "Account", new { e = model.Email, c = token }, "https");

                        string mailBody = MailCommonStrings.RegisteredBody(secureUrl);
                        Mailer.SendEmail_NoWait(model.Email, MailCommonStrings.RegisteredSubject, mailBody);
                        _logger.Debug($"{model.Email} has successfully registered an account from {ClientIpAddress.GetIPAddress(Request)}");

                        MvcCaptcha.ResetCaptcha("regoCaptcha");
                        return(RedirectToAction("ConfirmationRequired"));
                    }

                    ModelState.AddModelError("", result.Message);
                }
                else
                {
                    ModelState.AddModelError("", "An account with this email address already exists!");
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
示例#7
0
        public async Task <ActionResult> Login(LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // SYNCHRONOUS
            //var user = _authRepository.GetUserAccount(model.Email);
            // ASYNCHRONOUS
            var user = await _authRepository.GetUserAccountAsync(model.Email);

            if (user == null)
            {
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(model));
            }

            if (user.LockoutEndDate != null && user.LockoutEndDate > DateTime.UtcNow)
            {
                ModelState.AddModelError("", "Your account is currently locked due to too many incorrect password attempts. Try again in 5 minutes.");
                return(View(model));
            }

            if (!user.EmailConfirmed)
            {
                ModelState.AddModelError("", "You must verify your email address before you can login");
                return(View(model));
            }

            // SYNCHRONOUS
            //if (_authRepository.Validate(model.Email, model.Password))
            // ASYNCHRONOUS
            if (await _authRepository.ValidateAsync(model.Email, model.Password))
            {
                var claims = new List <Claim>();

                // For now, ignore the model.PostLoginUser property as well. If we need it, implement this code again.

                // Add the basic claims that all users need
                claims.Add(new Claim(ClaimTypes.NameIdentifier, model.Email));
                claims.Add(new Claim(ClaimTypes.Name, model.Email));
                claims.Add(new Claim(ClaimTypes.Email, model.Email));
                // Application Sid
                claims.Add(new Claim(ClaimTypes.Sid, ApplicationSid.Sid));
                // User Id so we don't have to query it again
                claims.Add(new Claim(ClaimTypes.PrimarySid, user.Id.ToString()));

                // Add any group-based claims
                var groupMembership = await _authRepository.GetUserGroupMembership(model.Email);

                if (groupMembership.Any())
                {
                    foreach (var group in groupMembership)
                    {
                        claims.Add(new Claim(ClaimTypes.Role, group));
                    }
                }

                var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

                HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties()
                {
                    IsPersistent = model.RememberMe
                }, identity);

                var userIp       = ClientIpAddress.GetIPAddress(Request);
                var loginSuccess = _authRepository.UpdateLastLoginInfo(model.Email, DateTime.UtcNow, userIp);

                _logger.Debug(string.Format("{0} has successfully logged in from {1}", model.Email, userIp));

                return(RedirectToLocal(model.ReturnUrl));
            }
            else
            {
                // Authentication failed but the email address exists. If we haven't explicitly disabled the lockout mechanism, increment or lock here
                if (user.LockoutEnabled)
                {
                    _logger.Debug(string.Format("{0} has failed to login, and their fail count is now {1}.", user.Email, user.AccessFailedCount + 1));

                    if (user.AccessFailedCount == 4)
                    {
                        // Lock the account for 5 minutes
                        _logger.Debug(string.Format("Locking {0} out for 5 minutes (too many incorrect password attempts)", user.Email));
                        _authRepository.LockAccount(user.Email);
                        ModelState.AddModelError("", "Your account has been locked out for 5 minutes due to too many incorrect password attempts.");
                        return(View(model));
                    }
                    else
                    {
                        // Increment the failed attempt count
                        _authRepository.FailedPasswordAttempt(user.Email, user.AccessFailedCount + 1);
                    }
                }
            }

            ModelState.AddModelError("", "Invalid login attempt.");
            return(View(model));
        }
示例#8
0
        public Boolean TryWriteTo(Byte[] buffer)
        {
            try
            {
                buffer[0] = (Byte)Operation;
                buffer[1] = (Byte)HardwareAddressType;
                buffer[2] = HardwareLength;
                buffer[3] = Hops;
                BitConverter.TryWriteBytes(new Span <Byte>(buffer, 4, 4), SessionId);
                BitConverter.TryWriteBytes(new Span <Byte>(buffer, 8, 2), Seconds);
                BitConverter.TryWriteBytes(new Span <Byte>(buffer, 10, 2), Flags);
                ClientIpAddress.TryWriteBytes(new Span <Byte>(buffer, 12, 4), out _);
                YourIpAddress.TryWriteBytes(new Span <Byte>(buffer, 16, 4), out _);
                ServerIdentifierAddress.TryWriteBytes(new Span <Byte>(buffer, 20, 4), out _);
                GatewayOrRelayAddress.TryWriteBytes(new Span <Byte>(buffer, 24, 4), out _);
                ClientHardwareAddress.GetAddressBytes().CopyTo(new Span <Byte>(buffer, 28, 16));
                Encoding.UTF8.GetBytes(ServerHostName).CopyTo(new Span <Byte>(buffer, 44, 64));
                Encoding.UTF8.GetBytes(BootFileName).CopyTo(new Span <Byte>(buffer, 108, 128));
                BitConverter.TryWriteBytes(new Span <Byte>(buffer, 236, 4), MagicCookie);
                var index = 240;
                foreach (var option in Options)
                {
                    buffer[index] = (Byte)option.Key;
                    Byte dataLength = 0;
                    switch (option.Value)
                    {
                    case IPAddress iPAddress:
                        buffer[index + 1] = dataLength = 4;
                        iPAddress.TryWriteBytes(new Span <Byte>(buffer, index + 2, dataLength), out _);
                        break;

                    case IPAddress[] iPAddresses:
                        buffer[index + 1] = dataLength = (Byte)(4 * iPAddresses.Length);
                        var offset = 0;
                        foreach (var iPAddress in iPAddresses)
                        {
                            iPAddress.TryWriteBytes(new Span <Byte>(buffer, index + 2 + offset, dataLength), out _);
                            offset += 4;
                        }
                        break;

                    case Byte[] bytes:
                        buffer[index + 1] = dataLength = (Byte)bytes.Length;
                        bytes.CopyTo(new Span <Byte>(buffer, index + 2, dataLength));
                        break;

                    case Byte b:
                        buffer[index + 1] = dataLength = 1;
                        buffer[index + 2] = b;
                        break;

                    case MessageType messageType:
                        buffer[index + 1] = dataLength = 1;
                        buffer[index + 2] = (Byte)messageType;
                        break;

                    case UInt32 uintVal:
                        buffer[index + 1] = dataLength = 4;
                        BitConverter.TryWriteBytes(new Span <Byte>(buffer, index + 2, dataLength), uintVal);
                        break;

                    default:
                        throw new NotSupportedException();
                    }
                    index += dataLength + 2;
                }
            }
            catch { return(false); }
            return(true);
        }