WIP Clean Architecture

Windows 8.1 App Uses keepasslib v2.44 (temporarily)
This commit is contained in:
Geoffroy BONNEVILLE
2020-03-24 13:01:14 +01:00
parent 34cd4ca3d8
commit 7e44d47065
290 changed files with 4084 additions and 36416 deletions

View File

@@ -0,0 +1,76 @@
using System;
using System.Linq;
using AutoMapper;
using ModernKeePass.Domain.Entities;
using ModernKeePassLib;
using ModernKeePassLib.Security;
namespace ModernKeePass.Infrastructure.KeePass
{
public class EntryMappingProfile: Profile
{
public EntryMappingProfile()
{
FromModelToDto();
FromDtoToModel();
}
private void FromDtoToModel()
{
CreateMap<PwEntry, EntryEntity>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Uuid.ToHexString()))
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => GetEntryValue(src, PwDefs.TitleField)))
.ForMember(dest => dest.UserName, opt => opt.MapFrom(src => GetEntryValue(src, PwDefs.UserNameField)))
.ForMember(dest => dest.Password, opt => opt.MapFrom(src => GetEntryValue(src, PwDefs.PasswordField)))
.ForMember(dest => dest.Url, opt =>
{
opt.PreCondition(src => Uri.TryCreate(GetEntryValue(src, PwDefs.UrlField), UriKind.Absolute, out _));
opt.MapFrom(src => new Uri(GetEntryValue(src, PwDefs.UrlField)));
})
.ForMember(dest => dest.Notes, opt => opt.MapFrom(src => GetEntryValue(src, PwDefs.NotesField)))
.ForMember(dest => dest.ForegroundColor, opt => opt.MapFrom(src => src.ForegroundColor))
.ForMember(dest => dest.BackgroundColor, opt => opt.MapFrom(src => src.BackgroundColor))
.ForMember(dest => dest.ExpirationDate, opt => opt.MapFrom(src => new DateTimeOffset(src.ExpiryTime)))
.ForMember(dest => dest.HasExpirationDate, opt => opt.MapFrom(src => src.Expires))
.ForMember(dest => dest.Icon, opt => opt.MapFrom(src => IconMapper.MapPwIconToIcon(src.IconId)))
.ForMember(dest => dest.AdditionalFields, opt => opt.MapFrom(src =>
src.Strings.Where(s => !PwDefs.GetStandardFields().Contains(s.Key)).ToDictionary(s => s.Key, s => GetEntryValue(src, s.Key))))
.ForMember(dest => dest.LastModificationDate, opt => opt.MapFrom(src => new DateTimeOffset(src.LastModificationTime)));
}
private void FromModelToDto()
{
CreateMap<EntryEntity, PwEntry>().ConvertUsing<EntryToPwEntryDictionaryConverter>();
}
private string GetEntryValue(PwEntry entry, string key) => entry.Strings.GetSafe(key).ReadString();
}
public class EntryToPwEntryDictionaryConverter : ITypeConverter<EntryEntity, PwEntry>
{
public PwEntry Convert(EntryEntity source, PwEntry destination, ResolutionContext context)
{
//destination.Uuid = new PwUuid(System.Convert.FromBase64String(source.Id));
destination.ExpiryTime = source.ExpirationDate.DateTime;
destination.Expires = source.HasExpirationDate;
destination.LastModificationTime = source.LastModificationDate.DateTime;
destination.BackgroundColor = source.BackgroundColor;
destination.ForegroundColor = source.ForegroundColor;
destination.IconId = IconMapper.MapIconToPwIcon(source.Icon);
SetEntryValue(destination, PwDefs.TitleField, source.Name);
SetEntryValue(destination, PwDefs.UserNameField, source.UserName);
SetEntryValue(destination, PwDefs.PasswordField, source.Password);
SetEntryValue(destination, PwDefs.UrlField, source.Url?.ToString());
SetEntryValue(destination, PwDefs.NotesField, source.Notes);
foreach (var additionalField in source.AdditionalFields)
{
SetEntryValue(destination, additionalField.Key, additionalField.Value);
}
return destination;
}
private void SetEntryValue(PwEntry entry, string key, string newValue)
{
if (newValue != null) entry.Strings.Set(key, new ProtectedString(true, newValue));
}
}
}

View File

@@ -0,0 +1,126 @@
using ModernKeePass.Domain.Enums;
using ModernKeePassLib;
namespace ModernKeePass.Infrastructure.KeePass
{
public static class IconMapper
{
public static Icon MapPwIconToIcon(PwIcon value)
{
switch (value)
{
case PwIcon.Key: return Icon.Permissions;
case PwIcon.WorldSocket:
case PwIcon.World: return Icon.World;
case PwIcon.Warning: return Icon.Important;
case PwIcon.WorldComputer:
case PwIcon.Drive:
case PwIcon.DriveWindows:
case PwIcon.NetworkServer: return Icon.MapDrive;
case PwIcon.MarkedDirectory: return Icon.Map;
case PwIcon.UserCommunication: return Icon.ContactInfo;
case PwIcon.Parts: return Icon.ViewAll;
case PwIcon.Notepad: return Icon.Document;
case PwIcon.Identity: return Icon.Contact;
case PwIcon.PaperReady: return Icon.SyncFolder;
case PwIcon.Digicam: return Icon.Camera;
case PwIcon.IRCommunication: return Icon.View;
case PwIcon.Energy: return Icon.ZeroBars;
case PwIcon.Scanner: return Icon.Scan;
case PwIcon.CDRom: return Icon.Rotate;
case PwIcon.Monitor: return Icon.Caption;
case PwIcon.EMailBox:
case PwIcon.EMail: return Icon.Mail;
case PwIcon.Configuration: return Icon.Setting;
case PwIcon.ClipboardReady: return Icon.Paste;
case PwIcon.PaperNew: return Icon.Page;
case PwIcon.Screen: return Icon.GoToStart;
case PwIcon.EnergyCareful: return Icon.FourBars;
case PwIcon.Disk: return Icon.Save;
case PwIcon.Console: return Icon.SlideShow;
case PwIcon.Printer: return Icon.Scan;
case PwIcon.ProgramIcons: return Icon.GoToStart;
case PwIcon.Settings:
case PwIcon.Tool: return Icon.Repair;
case PwIcon.Archive: return Icon.Crop;
case PwIcon.Count: return Icon.Calculator;
case PwIcon.Clock: return Icon.Clock;
case PwIcon.EMailSearch: return Icon.Find;
case PwIcon.PaperFlag: return Icon.Flag;
case PwIcon.TrashBin: return Icon.Delete;
case PwIcon.Expired: return Icon.ReportHacked;
case PwIcon.Info: return Icon.Help;
case PwIcon.Folder:
case PwIcon.FolderOpen:
case PwIcon.FolderPackage: return Icon.Folder;
case PwIcon.PaperLocked: return Icon.ProtectedDocument;
case PwIcon.Checked: return Icon.Accept;
case PwIcon.Pen: return Icon.Edit;
case PwIcon.Thumbnail: return Icon.BrowsePhotos;
case PwIcon.Book: return Icon.Library;
case PwIcon.List: return Icon.List;
case PwIcon.UserKey: return Icon.ContactPresence;
case PwIcon.Home: return Icon.Home;
case PwIcon.Star: return Icon.OutlineStar;
case PwIcon.Money: return Icon.Shop;
case PwIcon.Certificate: return Icon.PreviewLink;
case PwIcon.BlackBerry: return Icon.CellPhone;
default: return Icon.Stop;
}
}
public static PwIcon MapIconToPwIcon(Icon value)
{
switch (value)
{
case Icon.Delete: return PwIcon.TrashBin;
case Icon.Edit: return PwIcon.Pen;
case Icon.Save: return PwIcon.Disk;
case Icon.Cancel: return PwIcon.Expired;
case Icon.Accept: return PwIcon.Checked;
case Icon.Home: return PwIcon.Home;
case Icon.Camera: return PwIcon.Digicam;
case Icon.Setting: return PwIcon.Configuration;
case Icon.Mail: return PwIcon.EMail;
case Icon.Find: return PwIcon.EMailSearch;
case Icon.Help: return PwIcon.Info;
case Icon.Clock: return PwIcon.Clock;
case Icon.Crop: return PwIcon.Archive;
case Icon.World: return PwIcon.World;
case Icon.Flag: return PwIcon.PaperFlag;
case Icon.PreviewLink: return PwIcon.Certificate;
case Icon.Document: return PwIcon.Notepad;
case Icon.ProtectedDocument: return PwIcon.PaperLocked;
case Icon.ContactInfo: return PwIcon.UserCommunication;
case Icon.ViewAll: return PwIcon.Parts;
case Icon.Rotate: return PwIcon.CDRom;
case Icon.List: return PwIcon.List;
case Icon.Shop: return PwIcon.Money;
case Icon.BrowsePhotos: return PwIcon.Thumbnail;
case Icon.Caption: return PwIcon.Monitor;
case Icon.Repair: return PwIcon.Tool;
case Icon.Page: return PwIcon.PaperNew;
case Icon.Paste: return PwIcon.ClipboardReady;
case Icon.Important: return PwIcon.Warning;
case Icon.SlideShow: return PwIcon.Console;
case Icon.MapDrive: return PwIcon.NetworkServer;
case Icon.ContactPresence: return PwIcon.UserKey;
case Icon.Contact: return PwIcon.Identity;
case Icon.Folder: return PwIcon.Folder;
case Icon.View: return PwIcon.IRCommunication;
case Icon.Permissions: return PwIcon.Key;
case Icon.Map: return PwIcon.MarkedDirectory;
case Icon.CellPhone: return PwIcon.BlackBerry;
case Icon.OutlineStar: return PwIcon.Star;
case Icon.Calculator: return PwIcon.Count;
case Icon.Library: return PwIcon.Book;
case Icon.SyncFolder: return PwIcon.PaperReady;
case Icon.GoToStart: return PwIcon.Screen;
case Icon.ZeroBars: return PwIcon.Energy;
case Icon.FourBars: return PwIcon.EnergyCareful;
case Icon.Scan: return PwIcon.Scanner;
default: return PwIcon.Key;
}
}
}
}

View File

@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using ModernKeePass.Application.Common.Interfaces;
using ModernKeePass.Domain.Entities;
using ModernKeePassLib;
using ModernKeePassLib.Cryptography.Cipher;
using ModernKeePassLib.Cryptography.KeyDerivation;
namespace ModernKeePass.Infrastructure.KeePass
{
public class KeePassCryptographyClient: ICryptographyClient
{
public IEnumerable<BaseEntity> Ciphers
{
get
{
for (var inx = 0; inx < CipherPool.GlobalPool.EngineCount; inx++)
{
var cipher = CipherPool.GlobalPool[inx];
yield return new BaseEntity
{
Id = cipher.CipherUuid.ToHexString(),
Name = cipher.DisplayName
};
}
}
}
public IEnumerable<BaseEntity> KeyDerivations => KdfPool.Engines.Select(e => new BaseEntity
{
Id = e.Uuid.ToHexString(),
Name = e.Name
});
public IEnumerable<string> CompressionAlgorithms => Enum.GetNames(typeof(PwCompressionAlgorithm)).Take((int) PwCompressionAlgorithm.Count);
}
}

View File

@@ -0,0 +1,266 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using ModernKeePass.Application.Common.Interfaces;
using ModernKeePass.Domain.Dtos;
using ModernKeePass.Domain.Entities;
using ModernKeePass.Domain.Exceptions;
using ModernKeePassLib;
using ModernKeePassLib.Cryptography.Cipher;
using ModernKeePassLib.Cryptography.KeyDerivation;
using ModernKeePassLib.Interfaces;
using ModernKeePassLib.Keys;
using ModernKeePassLib.Serialization;
using ModernKeePassLib.Utility;
namespace ModernKeePass.Infrastructure.KeePass
{
public class KeePassDatabaseClient: IDatabaseProxy
{
private readonly ISettingsProxy _settings;
private readonly IFileProxy _fileService;
private readonly IMapper _mapper;
private readonly PwDatabase _pwDatabase = new PwDatabase();
private string _fileAccessToken;
private CompositeKey _compositeKey;
public bool IsOpen => (_pwDatabase?.IsOpen).GetValueOrDefault();
public GroupEntity RecycleBin { get; set; }
public BaseEntity Cipher
{
get
{
var cipher = CipherPool.GlobalPool.GetCipher(_pwDatabase.DataCipherUuid);
return new BaseEntity
{
Id = cipher.CipherUuid.ToHexString(),
Name = cipher.DisplayName
};
}
set => _pwDatabase.DataCipherUuid = BuildIdFromString(value.Id);
}
public BaseEntity KeyDerivation
{
get
{
var keyDerivation = KdfPool.Engines.First(e => e.Uuid.Equals(_pwDatabase.KdfParameters.KdfUuid));
return new BaseEntity
{
Id = keyDerivation.Uuid.ToHexString(),
Name = keyDerivation.Name
};
}
set => _pwDatabase.KdfParameters = KdfPool.Engines
.FirstOrDefault(e => e.Uuid.Equals(BuildIdFromString(value.Name)))?.GetDefaultParameters();
}
public string Compression
{
get => _pwDatabase.Compression.ToString("G");
set => _pwDatabase.Compression = (PwCompressionAlgorithm)Enum.Parse(typeof(PwCompressionAlgorithm), value);
}
public KeePassDatabaseClient(ISettingsProxy settings, IFileProxy fileService, IMapper mapper)
{
_settings = settings;
_fileService = fileService;
_mapper = mapper;
}
public async Task<DatabaseEntity> Open(FileInfo fileInfo, Credentials credentials)
{
try
{
_compositeKey = await CreateCompositeKey(credentials);
var ioConnection = await BuildConnectionInfo(fileInfo);
_pwDatabase.Open(ioConnection, _compositeKey, new NullStatusLogger());
_fileAccessToken = fileInfo.Path;
return new DatabaseEntity
{
RootGroupEntity = BuildHierarchy(_pwDatabase.RootGroup)
};
}
catch (InvalidCompositeKeyException ex)
{
throw new ArgumentException(ex.Message, ex);
}
}
public async Task<DatabaseEntity> Create(FileInfo fileInfo, Credentials credentials)
{
_compositeKey = await CreateCompositeKey(credentials);
var ioConnection = await BuildConnectionInfo(fileInfo);
_pwDatabase.New(ioConnection, _compositeKey);
var fileFormat = _settings.GetSetting<string>("DefaultFileFormat");
switch (fileFormat)
{
case "4":
_pwDatabase.KdfParameters = KdfPool.Get("Argon2").GetDefaultParameters();
break;
}
_fileAccessToken = fileInfo.Path;
// TODO: create sample data depending on settings
return new DatabaseEntity
{
RootGroupEntity = BuildHierarchy(_pwDatabase.RootGroup)
};
}
public async Task SaveDatabase()
{
if (!_pwDatabase.IsOpen) return;
try
{
_pwDatabase.Save(new NullStatusLogger());
await _fileService.WriteBinaryContentsToFile(_fileAccessToken, _pwDatabase.IOConnectionInfo.Bytes);
}
catch (Exception e)
{
throw new SaveException(e);
}
}
public async Task SaveDatabase(FileInfo fileInfo)
{
try
{
var newFileContents = await _fileService.OpenBinaryFile(fileInfo.Path);
_pwDatabase.SaveAs(IOConnectionInfo.FromByteArray(newFileContents), true, new NullStatusLogger());
await _fileService.WriteBinaryContentsToFile(fileInfo.Path, _pwDatabase.IOConnectionInfo.Bytes);
_fileService.ReleaseFile(_fileAccessToken);
_fileAccessToken = fileInfo.Path;
}
catch (Exception e)
{
throw new SaveException(e);
}
}
public void CloseDatabase()
{
_pwDatabase?.Close();
_fileService.ReleaseFile(_fileAccessToken);
}
public async Task AddEntry(GroupEntity parentGroupEntity, EntryEntity entry)
{
await Task.Run(() =>
{
var parentPwGroup = _pwDatabase.RootGroup.FindGroup(BuildIdFromString(parentGroupEntity.Id), true);
var pwEntry = new PwEntry(true, true);
_mapper.Map(entry, pwEntry);
parentPwGroup.AddEntry(pwEntry, true);
entry.Id = pwEntry.Uuid.ToHexString();
});
}
public async Task AddGroup(GroupEntity parentGroupEntity, GroupEntity group)
{
await Task.Run(() =>
{
var parentPwGroup = _pwDatabase.RootGroup.FindGroup(BuildIdFromString(parentGroupEntity.Id), true);
var pwGroup = new PwGroup(true, true)
{
Name = group.Name
};
parentPwGroup.AddGroup(pwGroup, true);
group.Id = pwGroup.Uuid.ToHexString();
});
}
public Task UpdateEntry(EntryEntity entry)
{
throw new NotImplementedException();
}
public Task UpdateGroup(GroupEntity group)
{
throw new NotImplementedException();
}
public async Task DeleteEntry(EntryEntity entry)
{
await Task.Run(() =>
{
var pwEntry = _pwDatabase.RootGroup.FindEntry(BuildIdFromString(entry.Id), true);
var id = pwEntry.Uuid;
pwEntry.ParentGroup.Entries.Remove(pwEntry);
if (_pwDatabase.RecycleBinEnabled)
{
_pwDatabase.DeletedObjects.Add(new PwDeletedObject(id, DateTime.UtcNow));
}
});
}
public async Task DeleteGroup(GroupEntity group)
{
await Task.Run(() =>
{
var pwGroup = _pwDatabase.RootGroup.FindGroup(BuildIdFromString(group.Id), true);
var id = pwGroup.Uuid;
pwGroup.ParentGroup.Groups.Remove(pwGroup);
if (_pwDatabase.RecycleBinEnabled)
{
_pwDatabase.DeletedObjects.Add(new PwDeletedObject(id, DateTime.UtcNow));
}
});
}
public async Task UpdateCredentials(Credentials credentials)
{
_pwDatabase.MasterKey = await CreateCompositeKey(credentials);
}
private async Task<CompositeKey> CreateCompositeKey(Credentials credentials)
{
var compositeKey = new CompositeKey();
if (!string.IsNullOrEmpty(credentials.Password)) compositeKey.AddUserKey(new KcpPassword(credentials.Password));
if (!string.IsNullOrEmpty(credentials.KeyFilePath))
{
var kcpFileContents = await _fileService.OpenBinaryFile(credentials.KeyFilePath);
compositeKey.AddUserKey(new KcpKeyFile(IOConnectionInfo.FromByteArray(kcpFileContents)));
}
return compositeKey;
}
private async Task<IOConnectionInfo> BuildConnectionInfo(FileInfo fileInfo)
{
var fileContents = await _fileService.OpenBinaryFile(fileInfo.Path);
return IOConnectionInfo.FromByteArray(fileContents);
}
private GroupEntity BuildHierarchy(PwGroup pwGroup)
{
// TODO: build entity hierarchy in an iterative way or implement lazy loading
var group = new GroupEntity
{
Id = pwGroup.Uuid.ToHexString(),
Name = pwGroup.Name,
Icon = IconMapper.MapPwIconToIcon(pwGroup.IconId),
Entries = pwGroup.Entries.Select(e => _mapper.Map<EntryEntity>(e)).ToList(),
SubGroups = pwGroup.Groups.Select(BuildHierarchy).ToList()
};
return group;
}
private PwUuid BuildIdFromString(string id)
{
return new PwUuid(MemUtil.HexStringToByteArray(id));
}
}
}

View File

@@ -0,0 +1,46 @@
using ModernKeePass.Application.Common.Interfaces;
using ModernKeePass.Domain.Dtos;
using ModernKeePassLib.Cryptography;
using ModernKeePassLib.Cryptography.PasswordGenerator;
using ModernKeePassLib.Keys;
namespace ModernKeePass.Infrastructure.KeePass
{
public class KeePassPasswordClient: IPasswordProxy
{
public string GeneratePassword(PasswordGenerationOptions options)
{
var pwProfile = new PwProfile
{
GeneratorType = PasswordGeneratorType.CharSet,
Length = (uint)options.PasswordLength,
CharSet = new PwCharSet()
};
if (options.UpperCasePatternSelected) pwProfile.CharSet.Add(PwCharSet.UpperCase);
if (options.LowerCasePatternSelected) pwProfile.CharSet.Add(PwCharSet.LowerCase);
if (options.DigitsPatternSelected) pwProfile.CharSet.Add(PwCharSet.Digits);
if (options.SpecialPatternSelected) pwProfile.CharSet.Add(PwCharSet.Special);
if (options.MinusPatternSelected) pwProfile.CharSet.Add('-');
if (options.UnderscorePatternSelected) pwProfile.CharSet.Add('_');
if (options.SpacePatternSelected) pwProfile.CharSet.Add(' ');
if (options.BracketsPatternSelected) pwProfile.CharSet.Add(PwCharSet.Brackets);
pwProfile.CharSet.Add(options.CustomChars);
PwGenerator.Generate(out var password, pwProfile, null, new CustomPwGeneratorPool());
return password.ReadString();
}
public uint EstimatePasswordComplexity(string password)
{
return QualityEstimation.EstimatePasswordBits(password?.ToCharArray());
}
public byte[] GenerateKeyFile(byte[] additionalEntropy)
{
return KcpKeyFile.Create(additionalEntropy);
}
}
}