DocSpace-buildtools/common/ASC.Core.Common/Security/EmailValidationKeyProvider.cs

277 lines
11 KiB
C#
Raw Normal View History

2019-05-15 14:56:09 +00:00
/*
*
* (c) Copyright Ascensio System Limited 2010-2018
*
* This program is freeware. You can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html).
* In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that
* Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights.
*
* THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html
*
* You can contact Ascensio System SIA by email at sales@onlyoffice.com
*
* The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display
* Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3.
*
* Pursuant to Section 7 § 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains
* relevant author attributions when distributing the software. If the display of the logo in its graphic
* form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE"
* in every copy of the program you distribute.
* Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks.
*
*/
using System;
2020-02-17 08:58:14 +00:00
using System.Text;
2020-02-17 08:58:14 +00:00
using ASC.Common;
2019-11-06 15:03:09 +00:00
using ASC.Common.Logging;
2019-08-15 12:04:42 +00:00
using ASC.Core;
using ASC.Core.Users;
2020-02-17 08:58:14 +00:00
using ASC.Web.Studio.Utility;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.WebUtilities;
2019-11-06 15:03:09 +00:00
using Microsoft.Extensions.Configuration;
2020-02-17 08:58:14 +00:00
using Microsoft.Extensions.Options;
2019-11-06 15:03:09 +00:00
using static ASC.Security.Cryptography.EmailValidationKeyProvider;
2019-05-15 14:56:09 +00:00
namespace ASC.Security.Cryptography
2020-10-19 15:53:15 +00:00
{
[Scope]
2019-05-15 14:56:09 +00:00
public class EmailValidationKeyProvider
{
public enum ValidationResult
{
Ok,
Invalid,
Expired
}
2019-10-17 15:55:35 +00:00
private readonly ILog log;
2019-11-06 15:03:09 +00:00
private static readonly DateTime _from = new DateTime(2010, 01, 01, 0, 0, 0, DateTimeKind.Utc);
internal readonly TimeSpan ValidInterval;
private MachinePseudoKeys MachinePseudoKeys { get; }
2020-08-12 09:58:08 +00:00
private TenantManager TenantManager { get; }
public EmailValidationKeyProvider(MachinePseudoKeys machinePseudoKeys, TenantManager tenantManager, IConfiguration configuration, IOptionsMonitor<ILog> options)
{
MachinePseudoKeys = machinePseudoKeys;
2019-11-06 15:03:09 +00:00
TenantManager = tenantManager;
if (!TimeSpan.TryParse(configuration["email:validinterval"], out var validInterval))
{
validInterval = TimeSpan.FromDays(7);
}
2019-11-06 15:03:09 +00:00
ValidInterval = validInterval;
log = options.CurrentValue;
}
2019-09-17 12:42:32 +00:00
public string GetEmailKey(string email)
2019-05-15 14:56:09 +00:00
{
2019-09-17 12:42:32 +00:00
return GetEmailKey(TenantManager.GetCurrentTenant().TenantId, email);
2019-05-15 14:56:09 +00:00
}
2019-09-23 12:20:08 +00:00
public string GetEmailKey(int tenantId, string email)
2019-05-15 14:56:09 +00:00
{
if (string.IsNullOrEmpty(email)) throw new ArgumentNullException("email");
email = FormatEmail(tenantId, email);
var ms = (long)(DateTime.UtcNow - _from).TotalMilliseconds;
var hash = GetMashineHashedData(BitConverter.GetBytes(ms), Encoding.ASCII.GetBytes(email));
return string.Format("{0}.{1}", ms, DoStringFromBytes(hash));
}
2019-09-23 12:20:08 +00:00
private string FormatEmail(int tenantId, string email)
2019-05-15 14:56:09 +00:00
{
if (email == null) throw new ArgumentNullException("email");
try
{
return string.Format("{0}|{1}|{2}", email.ToLowerInvariant(), tenantId, Encoding.UTF8.GetString(MachinePseudoKeys.GetMachineConstant()));
2019-05-15 14:56:09 +00:00
}
catch (Exception e)
{
log.Fatal("Failed to format tenant specific email", e);
return email.ToLowerInvariant();
}
}
2019-09-17 12:42:32 +00:00
public ValidationResult ValidateEmailKey(string email, string key)
2019-05-15 14:56:09 +00:00
{
return ValidateEmailKey(email, key, TimeSpan.MaxValue);
}
2019-09-17 12:42:32 +00:00
public ValidationResult ValidateEmailKey(string email, string key, TimeSpan validInterval)
2019-05-15 14:56:09 +00:00
{
var result = ValidateEmailKeyInternal(email, key, validInterval);
2019-09-17 12:42:32 +00:00
log.DebugFormat("validation result: {0}, source: {1} with key: {2} interval: {3} tenant: {4}", result, email, key, validInterval, TenantManager.GetCurrentTenant().TenantId);
2019-05-15 14:56:09 +00:00
return result;
}
2019-09-17 12:42:32 +00:00
private ValidationResult ValidateEmailKeyInternal(string email, string key, TimeSpan validInterval)
2019-05-15 14:56:09 +00:00
{
if (string.IsNullOrEmpty(email)) throw new ArgumentNullException("email");
if (key == null) throw new ArgumentNullException("key");
2019-09-17 12:42:32 +00:00
email = FormatEmail(TenantManager.GetCurrentTenant().TenantId, email);
2019-05-15 14:56:09 +00:00
var parts = key.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != 2) return ValidationResult.Invalid;
2019-08-15 13:16:39 +00:00
if (!long.TryParse(parts[0], out var ms)) return ValidationResult.Invalid;
2019-05-15 14:56:09 +00:00
var hash = GetMashineHashedData(BitConverter.GetBytes(ms), Encoding.ASCII.GetBytes(email));
var key2 = DoStringFromBytes(hash);
2019-08-15 13:16:39 +00:00
var key2_good = string.Compare(parts[1], key2, StringComparison.InvariantCultureIgnoreCase) == 0;
2019-05-15 14:56:09 +00:00
if (!key2_good) return ValidationResult.Invalid;
var ms_current = (long)(DateTime.UtcNow - _from).TotalMilliseconds;
2019-08-15 12:04:42 +00:00
return validInterval >= TimeSpan.FromMilliseconds(ms_current - ms) ? ValidationResult.Ok : ValidationResult.Expired;
2019-05-15 14:56:09 +00:00
}
internal static string DoStringFromBytes(byte[] data)
{
2019-08-15 13:03:57 +00:00
var str = Convert.ToBase64String(data);
2019-05-15 14:56:09 +00:00
str = str.Replace("=", "").Replace("+", "").Replace("/", "").Replace("\\", "");
return str.ToUpperInvariant();
}
internal static byte[] GetMashineHashedData(byte[] salt, byte[] data)
{
var alldata = new byte[salt.Length + data.Length];
Array.Copy(data, alldata, data.Length);
Array.Copy(salt, 0, alldata, data.Length, salt.Length);
return Hasher.Hash(alldata, HashAlg.SHA256);
}
}
2019-11-06 15:03:09 +00:00
public class EmailValidationKeyModel
{
public string Key { get; set; }
public EmployeeType? EmplType { get; set; }
public string Email { get; set; }
public Guid? UiD { get; set; }
public ConfirmType? Type { get; set; }
2020-07-02 14:11:59 +00:00
public int? P { get; set; }
2020-10-10 10:01:09 +00:00
public void Deconstruct(out string key, out EmployeeType? emplType, out string email, out Guid? uiD, out ConfirmType? type, out int? p)
{
(key, emplType, email, uiD, type, p) = (Key, EmplType, Email, UiD, Type, P);
}
2020-10-07 10:45:53 +00:00
}
2020-10-19 15:53:15 +00:00
[Transient]
2020-10-07 10:45:53 +00:00
public class EmailValidationKeyModelHelper
{
private IHttpContextAccessor HttpContextAccessor { get; }
private EmailValidationKeyProvider Provider { get; }
private AuthContext AuthContext { get; }
private UserManager UserManager { get; }
private AuthManager Authentication { get; }
public EmailValidationKeyModelHelper(
2020-07-02 14:11:59 +00:00
IHttpContextAccessor httpContextAccessor,
EmailValidationKeyProvider provider,
AuthContext authContext,
UserManager userManager,
AuthManager authentication)
{
2020-10-07 10:45:53 +00:00
HttpContextAccessor = httpContextAccessor;
2020-07-02 14:11:59 +00:00
Provider = provider;
AuthContext = authContext;
UserManager = userManager;
Authentication = authentication;
2020-10-07 10:45:53 +00:00
}
2020-07-02 14:11:59 +00:00
2020-10-07 10:45:53 +00:00
public EmailValidationKeyModel GetModel()
{
var request = QueryHelpers.ParseQuery(HttpContextAccessor.HttpContext.Request.Headers["confirm"]);
2020-07-02 14:11:59 +00:00
2020-10-12 19:39:23 +00:00
request.TryGetValue("type", out var type);
2020-07-02 14:11:59 +00:00
ConfirmType? cType = null;
if (Enum.TryParse<ConfirmType>(type, out var confirmType))
{
cType = confirmType;
}
2019-11-06 15:03:09 +00:00
2020-10-12 19:39:23 +00:00
request.TryGetValue("key", out var key);
2019-11-06 15:03:09 +00:00
2020-10-12 19:39:23 +00:00
request.TryGetValue("p", out var pkey);
int.TryParse(pkey, out var p);
2020-07-02 14:11:59 +00:00
2020-10-12 19:39:23 +00:00
request.TryGetValue("emplType", out var emplType);
Enum.TryParse<EmployeeType>(emplType, out var employeeType);
2020-07-02 14:11:59 +00:00
2020-10-12 19:39:23 +00:00
request.TryGetValue("email", out var _email);
request.TryGetValue("uid", out var userIdKey);
Guid.TryParse(userIdKey, out var userId);
2020-07-02 14:11:59 +00:00
2020-10-07 10:45:53 +00:00
return new EmailValidationKeyModel
{
Email = _email,
EmplType = employeeType,
Key = key,
P = p,
Type = cType,
UiD = userId
};
2020-07-02 14:11:59 +00:00
}
2020-10-07 10:45:53 +00:00
public ValidationResult Validate(EmailValidationKeyModel model)
2019-11-06 15:03:09 +00:00
{
2020-10-07 10:45:53 +00:00
var (key, emplType, email, uiD, type, p) = model;
2020-07-02 14:11:59 +00:00
2019-11-06 15:03:09 +00:00
ValidationResult checkKeyResult;
2020-10-07 10:45:53 +00:00
switch (type)
2019-11-06 15:03:09 +00:00
{
case ConfirmType.EmpInvite:
2020-10-07 10:45:53 +00:00
checkKeyResult = Provider.ValidateEmailKey(email + type + (int)emplType, key, Provider.ValidInterval);
2019-11-06 15:03:09 +00:00
break;
case ConfirmType.LinkInvite:
2020-10-07 10:45:53 +00:00
checkKeyResult = Provider.ValidateEmailKey(type.ToString() + (int)emplType, key, Provider.ValidInterval);
2019-11-06 15:03:09 +00:00
break;
2020-02-17 08:58:14 +00:00
case ConfirmType.PortalOwnerChange:
2020-10-07 10:45:53 +00:00
checkKeyResult = Provider.ValidateEmailKey(email + type + uiD.HasValue, key, Provider.ValidInterval);
break;
2019-11-06 15:03:09 +00:00
case ConfirmType.EmailChange:
2020-10-07 10:45:53 +00:00
checkKeyResult = Provider.ValidateEmailKey(email + type + AuthContext.CurrentAccount.ID, key, Provider.ValidInterval);
2019-11-06 15:03:09 +00:00
break;
case ConfirmType.PasswordChange:
2020-10-07 10:45:53 +00:00
var hash = Authentication.GetUserPasswordStamp(UserManager.GetUserByEmail(email).ID).ToString("s");
2020-10-07 10:45:53 +00:00
checkKeyResult = Provider.ValidateEmailKey(email + type + hash, key, Provider.ValidInterval);
2019-11-06 15:03:09 +00:00
break;
case ConfirmType.Activation:
2020-10-07 10:45:53 +00:00
checkKeyResult = Provider.ValidateEmailKey(email + type + uiD, key, Provider.ValidInterval);
2019-11-06 15:03:09 +00:00
break;
case ConfirmType.ProfileRemove:
// validate UiD
2020-10-07 10:45:53 +00:00
if (p == 1)
2019-11-06 15:03:09 +00:00
{
2020-10-07 10:45:53 +00:00
var user = UserManager.GetUsers(uiD.GetValueOrDefault());
if (user == null || user.Status == EmployeeStatus.Terminated || AuthContext.IsAuthenticated && AuthContext.CurrentAccount.ID != uiD)
2019-11-06 15:03:09 +00:00
return ValidationResult.Invalid;
}
2020-10-07 10:45:53 +00:00
checkKeyResult = Provider.ValidateEmailKey(email + type + uiD, key, Provider.ValidInterval);
2020-07-02 14:11:59 +00:00
break;
case ConfirmType.Wizard:
2020-10-07 10:45:53 +00:00
checkKeyResult = Provider.ValidateEmailKey("" + type, key, Provider.ValidInterval);
2019-11-06 15:03:09 +00:00
break;
default:
2020-10-07 10:45:53 +00:00
checkKeyResult = Provider.ValidateEmailKey(email + type, key, Provider.ValidInterval);
2019-11-06 15:03:09 +00:00
break;
}
return checkKeyResult;
2020-09-30 14:47:42 +00:00
}
2019-11-06 15:03:09 +00:00
}
2019-05-15 14:56:09 +00:00
}