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

178 lines
6.9 KiB
C#
Raw Normal View History

2022-03-15 18:00:53 +00:00
// (c) Copyright Ascensio System SIA 2010-2022
//
// This program is a free software product.
// You can redistribute it and/or modify it under the terms
// of the GNU Affero General Public License (AGPL) version 3 as published by the Free Software
// Foundation. In accordance with Section 7(a) of the GNU AGPL 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 details, see
// the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
//
// You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, EU, LV-1021.
//
// The interactive user interfaces in modified source and object code versions of the Program must
// display Appropriate Legal Notices, as required under Section 5 of the GNU AGPL version 3.
//
// Pursuant to Section 7(b) of the License you must retain the original Product logo when
// distributing the program. Pursuant to Section 7(e) we decline to grant you any rights under
// trademark law for use of our trademarks.
//
// All the Product's GUI elements, including illustrations and icon sets, as well as technical writing
// content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0
// International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
2022-02-15 11:52:43 +00:00
namespace ASC.Security.Cryptography;
[Scope]
public class EmailValidationKeyProvider
2020-10-19 15:53:15 +00:00
{
2022-02-15 11:52:43 +00:00
public enum ValidationResult
{
Ok,
Invalid,
Expired
}
public TimeSpan ValidEmailKeyInterval { get; }
public TimeSpan ValidAuthKeyInterval { get; }
public TimeSpan ValidVisitLinkInterval { get; }
2022-02-15 11:52:43 +00:00
private readonly ILog _logger;
private static readonly DateTime _from = new DateTime(2010, 01, 01, 0, 0, 0, DateTimeKind.Utc);
private readonly MachinePseudoKeys _machinePseudoKeys;
private readonly TenantManager _tenantManager;
2022-04-14 19:42:15 +00:00
public EmailValidationKeyProvider(MachinePseudoKeys machinePseudoKeys, TenantManager tenantManager, IConfiguration configuration, ILog logger)
2022-02-15 11:52:43 +00:00
{
_machinePseudoKeys = machinePseudoKeys;
_tenantManager = tenantManager;
if (!TimeSpan.TryParse(configuration["email:validinterval"], out var validInterval))
{
2022-02-15 11:52:43 +00:00
validInterval = TimeSpan.FromDays(7);
}
if (!TimeSpan.TryParse(configuration["auth:validinterval"], out var authValidInterval))
{
authValidInterval = TimeSpan.FromHours(1);
}
2022-05-16 17:18:25 +00:00
if (!TimeSpan.TryParse(configuration["visit:validinterval"], out var validVisitLinkInterval))
{
ValidVisitLinkInterval = TimeSpan.FromMinutes(15);
}
2022-05-05 12:31:04 +00:00
ValidEmailKeyInterval = validInterval;
ValidAuthKeyInterval = authValidInterval;
2022-03-17 10:13:52 +00:00
_logger = logger;
2022-02-15 11:52:43 +00:00
}
2022-02-15 11:52:43 +00:00
public string GetEmailKey(string email)
{
return GetEmailKey(_tenantManager.GetCurrentTenant().Id, email);
}
2022-02-15 11:52:43 +00:00
public string GetEmailKey(int tenantId, string email)
{
2022-03-09 17:15:51 +00:00
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(email);
2022-02-15 11:52:43 +00:00
email = FormatEmail(tenantId, email);
2022-02-15 11:52:43 +00:00
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));
2020-10-07 10:45:53 +00:00
}
2022-02-15 11:52:43 +00:00
private string FormatEmail(int tenantId, string email)
2020-10-07 10:45:53 +00:00
{
2022-03-09 17:15:51 +00:00
ArgumentNullException.ThrowIfNull(email);
2020-07-02 14:11:59 +00:00
2022-02-15 11:52:43 +00:00
try
2020-10-07 10:45:53 +00:00
{
2022-02-15 11:52:43 +00:00
return string.Format("{0}|{1}|{2}", email.ToLowerInvariant(), tenantId, Encoding.UTF8.GetString(_machinePseudoKeys.GetMachineConstant()));
2020-07-02 14:11:59 +00:00
}
2022-02-15 11:52:43 +00:00
catch (Exception e)
{
_logger.Fatal("Failed to format tenant specific email", e);
2022-02-15 11:52:43 +00:00
return email.ToLowerInvariant();
}
}
2020-07-02 14:11:59 +00:00
2022-02-15 11:52:43 +00:00
public ValidationResult ValidateEmailKey(string email, string key)
{
return ValidateEmailKey(email, key, TimeSpan.MaxValue);
}
2020-07-02 14:11:59 +00:00
2022-02-15 11:52:43 +00:00
public ValidationResult ValidateEmailKey(string email, string key, TimeSpan validInterval)
{
var result = ValidateEmailKeyInternal(email, key, validInterval);
_logger.DebugFormat("validation result: {0}, source: {1} with key: {2} interval: {3} tenant: {4}", result, email, key, validInterval, _tenantManager.GetCurrentTenant().Id);
return result;
}
2019-11-06 15:03:09 +00:00
2022-02-15 11:52:43 +00:00
private ValidationResult ValidateEmailKeyInternal(string email, string key, TimeSpan validInterval)
{
2022-03-09 17:15:51 +00:00
ArgumentNullOrEmptyException.ThrowIfNullOrEmpty(email);
ArgumentNullException.ThrowIfNull(key);
2019-11-06 15:03:09 +00:00
2022-02-15 11:52:43 +00:00
email = FormatEmail(_tenantManager.GetCurrentTenant().Id, email);
var parts = key.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != 2)
{
return ValidationResult.Invalid;
}
2020-07-02 14:11:59 +00:00
2022-02-15 11:52:43 +00:00
if (!long.TryParse(parts[0], out var ms))
{
return ValidationResult.Invalid;
}
2020-07-02 14:11:59 +00:00
2022-02-15 11:52:43 +00:00
var hash = GetMashineHashedData(BitConverter.GetBytes(ms), Encoding.ASCII.GetBytes(email));
var key2 = DoStringFromBytes(hash);
var key2_good = string.Equals(parts[1], key2, StringComparison.OrdinalIgnoreCase);
if (!key2_good)
{
return ValidationResult.Invalid;
}
var ms_current = (long)(DateTime.UtcNow - _from).TotalMilliseconds;
return validInterval >= TimeSpan.FromMilliseconds(ms_current - ms) ? ValidationResult.Ok : ValidationResult.Expired;
}
2020-07-02 14:11:59 +00:00
2022-02-15 11:52:43 +00:00
internal static string DoStringFromBytes(byte[] data)
{
var str = Convert.ToBase64String(data);
str = str.Replace("=", "").Replace("+", "").Replace("/", "").Replace("\\", "");
return str.ToUpperInvariant();
}
2020-07-02 14:11:59 +00:00
2022-02-15 11:52:43 +00:00
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
2022-02-15 11:52:43 +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; }
2022-05-15 20:19:03 +00:00
public int? RoomAccess { get; set; }
2022-05-05 12:31:04 +00:00
public string RoomId { get; set; }
2022-02-15 11:52:43 +00:00
public void Deconstruct(out string key, out EmployeeType? emplType, out string email, out Guid? uiD, out ConfirmType? type, out int? fileShare, out string roomId)
2022-02-15 11:52:43 +00:00
{
2022-05-15 20:19:03 +00:00
(key, emplType, email, uiD, type, fileShare, roomId) = (Key, EmplType, Email, UiD, Type, RoomAccess, RoomId);
2022-02-15 11:52:43 +00:00
}
}