Files
server/src/Core/Services/Implementations/LicensingService.cs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

267 lines
9.6 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.IO;
2017-08-17 00:12:11 -04:00
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using Bit.Core.Models.Business;
using Bit.Core.Models.Table;
2017-08-16 23:15:09 -04:00
using Bit.Core.Repositories;
using Bit.Core.Settings;
using Bit.Core.Utilities;
using Microsoft.AspNetCore.Hosting;
2020-01-10 08:33:13 -05:00
using Microsoft.Azure.Storage;
2020-01-10 08:47:58 -05:00
using Microsoft.Extensions.Hosting;
2017-08-17 17:10:34 -04:00
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace Bit.Core.Services
{
2017-08-22 15:27:29 -04:00
public class LicensingService : ILicensingService
{
private readonly X509Certificate2 _certificate;
private readonly GlobalSettings _globalSettings;
2017-08-16 23:15:09 -04:00
private readonly IUserRepository _userRepository;
2017-08-17 00:12:11 -04:00
private readonly IOrganizationRepository _organizationRepository;
2017-08-22 15:27:29 -04:00
private readonly IOrganizationUserRepository _organizationUserRepository;
private readonly IMailService _mailService;
2017-08-22 15:27:29 -04:00
private readonly ILogger<LicensingService> _logger;
2017-08-17 00:12:11 -04:00
private IDictionary<Guid, DateTime> _userCheckCache = new Dictionary<Guid, DateTime>();
2017-08-22 15:27:29 -04:00
public LicensingService(
2017-08-16 23:15:09 -04:00
IUserRepository userRepository,
2017-08-17 00:12:11 -04:00
IOrganizationRepository organizationRepository,
2017-08-22 15:27:29 -04:00
IOrganizationUserRepository organizationUserRepository,
IMailService mailService,
2020-01-10 08:47:58 -05:00
IWebHostEnvironment environment,
2017-08-22 15:27:29 -04:00
ILogger<LicensingService> logger,
GlobalSettings globalSettings)
{
2017-08-16 23:15:09 -04:00
_userRepository = userRepository;
2017-08-17 00:12:11 -04:00
_organizationRepository = organizationRepository;
2017-08-22 15:27:29 -04:00
_organizationUserRepository = organizationUserRepository;
_mailService = mailService;
2017-08-17 17:10:34 -04:00
_logger = logger;
2019-07-10 20:05:07 -04:00
_globalSettings = globalSettings;
var certThumbprint = environment.IsDevelopment() && !_globalSettings.SelfHosted ?
"207E64A231E8AA32AAF68A61037C075EBEBD553F" :
2018-07-19 00:02:21 -04:00
"B34876439FCDA2846505B2EFBBA6C4A951313EBE";
if (_globalSettings.SelfHosted)
2019-07-10 20:05:07 -04:00
{
2020-01-13 15:35:50 -05:00
_certificate = CoreHelpers.GetEmbeddedCertificateAsync("licensing.cer", null)
.GetAwaiter().GetResult();
2019-07-10 20:05:07 -04:00
}
else if (CoreHelpers.SettingHasValue(_globalSettings.Storage?.ConnectionString) &&
2019-07-10 20:05:07 -04:00
CoreHelpers.SettingHasValue(_globalSettings.LicenseCertificatePassword))
{
var storageAccount = CloudStorageAccount.Parse(globalSettings.Storage.ConnectionString);
_certificate = CoreHelpers.GetBlobCertificateAsync(storageAccount, "certificates",
"licensing.pfx", _globalSettings.LicenseCertificatePassword)
.GetAwaiter().GetResult();
}
else
{
_certificate = CoreHelpers.GetCertificate(certThumbprint);
}
if (_certificate == null || !_certificate.Thumbprint.Equals(CoreHelpers.CleanCertificateThumbprint(certThumbprint),
2017-08-11 22:55:25 -04:00
StringComparison.InvariantCultureIgnoreCase))
{
throw new Exception("Invalid licensing certificate.");
}
if (_globalSettings.SelfHosted && !CoreHelpers.SettingHasValue(_globalSettings.LicenseDirectory))
{
throw new InvalidOperationException("No license directory.");
}
}
2017-08-17 00:12:11 -04:00
public async Task ValidateOrganizationsAsync()
{
if (!_globalSettings.SelfHosted)
2017-08-11 22:55:25 -04:00
{
2017-08-17 00:12:11 -04:00
return;
2017-08-11 22:55:25 -04:00
}
var enabledOrgs = await _organizationRepository.GetManyByEnabledAsync();
_logger.LogInformation(Constants.BypassFiltersEventId, null,
"Validating licenses for {0} organizations.", enabledOrgs.Count);
2017-08-17 17:10:34 -04:00
foreach (var org in enabledOrgs)
2017-08-17 00:12:11 -04:00
{
2018-10-18 10:41:49 -05:00
var license = ReadOrganizationLicense(org);
if (license == null)
2017-08-17 00:12:11 -04:00
{
2018-04-13 09:25:54 -04:00
await DisableOrganizationAsync(org, null, "No license file.");
continue;
}
2017-08-17 17:10:34 -04:00
var totalLicensedOrgs = enabledOrgs.Count(o => o.LicenseKey.Equals(license.LicenseKey));
if (totalLicensedOrgs > 1)
{
2018-04-13 09:25:54 -04:00
await DisableOrganizationAsync(org, license, "Multiple organizations.");
2019-02-13 21:03:22 -05:00
continue;
2018-04-13 09:25:54 -04:00
}
if (!license.VerifyData(org, _globalSettings))
2018-04-13 09:25:54 -04:00
{
await DisableOrganizationAsync(org, license, "Invalid data.");
2019-02-13 21:03:22 -05:00
continue;
2018-04-13 09:25:54 -04:00
}
if (!license.VerifySignature(_certificate))
2018-04-13 09:25:54 -04:00
{
await DisableOrganizationAsync(org, license, "Invalid signature.");
2019-02-13 21:03:22 -05:00
continue;
2017-08-17 00:12:11 -04:00
}
}
}
2018-04-13 09:25:54 -04:00
private async Task DisableOrganizationAsync(Organization org, ILicense license, string reason)
{
_logger.LogInformation(Constants.BypassFiltersEventId, null,
"Organization {0} ({1}) has an invalid license and is being disabled. Reason: {2}",
2018-04-13 09:25:54 -04:00
org.Id, org.Name, reason);
org.Enabled = false;
org.ExpirationDate = license?.Expires ?? DateTime.UtcNow;
org.RevisionDate = DateTime.UtcNow;
await _organizationRepository.ReplaceAsync(org);
await _mailService.SendLicenseExpiredAsync(new List<string> { org.BillingEmail }, org.Name);
}
2017-08-22 15:27:29 -04:00
public async Task ValidateUsersAsync()
{
if (!_globalSettings.SelfHosted)
2017-08-22 15:27:29 -04:00
{
return;
}
var premiumUsers = await _userRepository.GetManyByPremiumAsync(true);
_logger.LogInformation(Constants.BypassFiltersEventId, null,
"Validating premium for {0} users.", premiumUsers.Count);
2017-08-22 15:27:29 -04:00
foreach (var user in premiumUsers)
2017-08-22 15:27:29 -04:00
{
await ProcessUserValidationAsync(user);
}
}
2017-08-17 00:12:11 -04:00
public async Task<bool> ValidateUserPremiumAsync(User user)
{
if (!_globalSettings.SelfHosted)
2017-08-11 22:55:25 -04:00
{
return user.Premium;
}
if (!user.Premium)
{
return false;
}
// Only check once per day
var now = DateTime.UtcNow;
if (_userCheckCache.ContainsKey(user.Id))
{
var lastCheck = _userCheckCache[user.Id];
if (lastCheck < now && now - lastCheck < TimeSpan.FromDays(1))
{
return user.Premium;
}
else
{
_userCheckCache[user.Id] = now;
}
}
else
{
_userCheckCache.Add(user.Id, now);
}
_logger.LogInformation(Constants.BypassFiltersEventId, null,
"Validating premium license for user {0}({1}).", user.Id, user.Email);
2017-08-22 15:27:29 -04:00
return await ProcessUserValidationAsync(user);
}
2017-08-17 17:10:34 -04:00
2017-08-22 15:27:29 -04:00
private async Task<bool> ProcessUserValidationAsync(User user)
{
var license = ReadUserLicense(user);
if (license == null)
{
await DisablePremiumAsync(user, null, "No license file.");
return false;
}
2017-08-17 17:10:34 -04:00
if (!license.VerifyData(user))
{
await DisablePremiumAsync(user, license, "Invalid data.");
return false;
}
if (!license.VerifySignature(_certificate))
{
await DisablePremiumAsync(user, license, "Invalid signature.");
return false;
}
return true;
}
private async Task DisablePremiumAsync(User user, ILicense license, string reason)
{
_logger.LogInformation(Constants.BypassFiltersEventId, null,
"User {0}({1}) has an invalid license and premium is being disabled. Reason: {2}",
user.Id, user.Email, reason);
user.Premium = false;
user.PremiumExpirationDate = license?.Expires ?? DateTime.UtcNow;
user.RevisionDate = DateTime.UtcNow;
await _userRepository.ReplaceAsync(user);
await _mailService.SendLicenseExpiredAsync(new List<string> { user.Email });
}
2017-08-11 17:06:31 -04:00
public bool VerifyLicense(ILicense license)
{
return license.VerifySignature(_certificate);
}
2017-08-11 22:55:25 -04:00
public byte[] SignLicense(ILicense license)
{
if (_globalSettings.SelfHosted || !_certificate.HasPrivateKey)
2017-08-11 22:55:25 -04:00
{
throw new InvalidOperationException("Cannot sign licenses.");
}
return license.Sign(_certificate);
}
private UserLicense ReadUserLicense(User user)
{
2017-08-11 22:55:25 -04:00
var filePath = $"{_globalSettings.LicenseDirectory}/user/{user.Id}.json";
if (!File.Exists(filePath))
{
return null;
}
var data = File.ReadAllText(filePath, Encoding.UTF8);
return JsonConvert.DeserializeObject<UserLicense>(data);
}
2018-10-18 10:41:49 -05:00
private OrganizationLicense ReadOrganizationLicense(Organization organization)
{
2017-08-11 22:55:25 -04:00
var filePath = $"{_globalSettings.LicenseDirectory}/organization/{organization.Id}.json";
if (!File.Exists(filePath))
{
return null;
}
var data = File.ReadAllText(filePath, Encoding.UTF8);
return JsonConvert.DeserializeObject<OrganizationLicense>(data);
}
}
}