1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
|
using System;
using System.Collections.Generic;
using System.Linq;
using KeePassLib;
using KeePassLib.Collections;
using KeePassLib.Security;
using KeePassLib.Utility;
using KeePassRPC.Models;
using KeePassRPC.Models.DataExchange;
using KeePassRPC.Models.DataExchange.V2;
using KeePassRPC.Models.Persistent;
using KeePassRPC.Models.Shared;
namespace KeePassRPC
{
public partial class KeePassRPCService
{
#region Utility functions to convert between KeePassRPC object schema and KeePass schema
private LightEntry2 GetEntry2FromPwEntry(PwEntry pwe, int matchAccuracy, bool fullDetails, PwDatabase db,
bool urlRequired)
{
return GetEntry2FromPwEntry(pwe, matchAccuracy, fullDetails, db, false, urlRequired);
}
private LightEntry2 GetEntry2FromPwEntry(PwEntry pwe, int matchAccuracy, bool fullDetails, PwDatabase db,
bool abortIfHidden, bool urlRequired)
{
EntryConfigv2 conf = pwe.GetKPRPCConfigNormalised(db.GetKPRPCConfig().DefaultMatchAccuracy);
if (conf == null)
return null;
return GetEntry2FromPwEntry(pwe, conf, matchAccuracy, fullDetails, db, abortIfHidden, urlRequired);
}
private LightEntry2 GetEntry2FromPwEntry(PwEntry pwe, EntryConfigv2 conf, int matchAccuracy, bool fullDetails,
PwDatabase db, bool abortIfHidden, bool urlRequired)
{
var fields = new List<ResolvedField>();
var urls = new List<string>();
string usernameValue = "";
string usernameName = "";
if (!string.IsNullOrEmpty(pwe.Strings.ReadSafe("URL")))
{
urls.Add(pwe.Strings.ReadSafe("URL"));
}
// Hide always blocks if matcher is even present
if (abortIfHidden && conf.MatcherConfigs.Any(mc => mc.MatcherType == EntryMatcherType.Hide))
return null;
if (conf.AltUrls != null)
urls.AddRange(conf.AltUrls);
bool dbDefaultPlaceholderHandlingEnabled =
db.GetKPRPCConfig().DefaultPlaceholderHandling == PlaceholderHandling.Enabled;
foreach (Field field in conf.Fields)
{
if (!fullDetails && field.ValuePath != PwDefs.UserNameField)
continue;
var fieldPlaceholderHandling = field.PlaceholderHandling.GetValueOrDefault(PlaceholderHandling.Default);
bool enablePlaceholders = fieldPlaceholderHandling == PlaceholderHandling.Enabled ||
(fieldPlaceholderHandling == PlaceholderHandling.Default &&
dbDefaultPlaceholderHandlingEnabled);
string ffValue = field.ValuePath == "."
? field.Value
: _keePassRpcPlugin.GetPwEntryString(pwe, field.ValuePath, db);
string derefValue = enablePlaceholders
? _keePassRpcPlugin.GetPwEntryStringFromDereferencableValue(pwe, ffValue, db)
: ffValue;
if (fullDetails)
{
if (!string.IsNullOrEmpty(ffValue))
{
fields.Add(new ResolvedField
{
ResolvedValue = derefValue,
ValuePath = field.ValuePath,
Value = field.Value,
Uuid = field.Uuid,
MatcherConfigs = field.MatcherConfigs.Where(mc => mc != null).ToArray(),
PlaceholderHandling = field.PlaceholderHandling,
Name = field.Name,
Page = field.Page,
Type = field.Type
});
}
}
else
{
usernameName = !string.IsNullOrWhiteSpace(field.Name) ? field.Name : "username";
usernameValue = derefValue;
}
}
Icon icon = _iconConverter.iconToDto(ClientMetadata, pwe.CustomIconUuid, pwe.IconId);
if (fullDetails)
{
string realm = "";
if (!string.IsNullOrEmpty(conf.HttpRealm))
realm = conf.HttpRealm;
var temp = fields.ToArray();
var mc = (ClientMetadata != null && ClientMetadata.Features != null &&
ClientMetadata.Features.Contains("KPRPC_FEATURE_ENTRY_CLIENT_MATCHERS"))
? conf.MatcherConfigs
: null;
return new Entry2(
urls.ToArray(), realm,
pwe.Strings.ReadSafe(PwDefs.TitleField), temp,
conf.Behaviour,
MemUtil.ByteArrayToHexString(pwe.Uuid.UuidBytes),
GetGroup2FromPwGroup(pwe.ParentGroup), icon,
GetDatabase2FromPwDatabase(db, false, true, urlRequired), matchAccuracy, mc,
conf.AuthenticationMethods);
}
return new LightEntry2(urls.ToArray(),
pwe.Strings.ReadSafe(PwDefs.TitleField),
MemUtil.ByteArrayToHexString(pwe.Uuid.UuidBytes),
icon, usernameName, usernameValue, conf.AuthenticationMethods);
}
private Group2 GetGroup2FromPwGroup(PwGroup pwg)
{
Icon icon = _iconConverter.iconToDto(ClientMetadata, pwg.CustomIconUuid, pwg.IconId);
return new Group2(pwg.Name, MemUtil.ByteArrayToHexString(pwg.Uuid.UuidBytes),
icon, pwg.GetFullPath("/", false));
}
private Database2 GetDatabase2FromPwDatabase(PwDatabase pwd, bool fullDetail, bool noDetail, bool urlRequired)
{
try
{
if (fullDetail && noDetail)
throw new ArgumentException("Don't be silly");
PwGroup pwg = GetRootPwGroup(pwd);
Group2 rt = GetGroup2FromPwGroup(pwg);
if (fullDetail)
rt.ChildEntries = (Entry2[])GetChildEntries2(pwd, pwg, fullDetail, urlRequired);
else if (!noDetail)
rt.ChildLightEntries = GetChildEntries2(pwd, pwg, fullDetail, urlRequired);
if (!noDetail)
rt.ChildGroups = GetChildGroups2(pwd, pwg, true, fullDetail);
// Can just send a null icon if we know the client can get it elsewhere
var icon = (ClientMetadata != null && ClientMetadata.Features != null &&
ClientMetadata.Features.Contains("KPRPC_FEATURE_ICON_REFERENCES"))
? null
: new Icon
{
Base64 = IconCache<string>.GetIconEncoding(pwd.IOConnectionInfo.Path) ?? ""
};
return new Database2(pwd.Name, pwd.IOConnectionInfo.Path, rt,
(pwd == _host.Database) ? true : false, icon);
}
catch (Exception ex)
{
if (_keePassRpcPlugin.logger != null)
_keePassRpcPlugin.logger.WriteLine("Failed to parse database. Exception: " + ex);
return null;
}
}
private void setPwEntryFromEntry2(PwEntry pwe, Entry2 entry)
{
EntryConfigv2 conf =
(new EntryConfigv1(_host.Database.GetKPRPCConfig().DefaultMatchAccuracy))
.ConvertToV2(new GuidService());
List<Field> fields = new List<Field>();
foreach (ResolvedField incomingField in entry.Fields)
{
if (incomingField.ValuePath == PwDefs.PasswordField)
{
pwe.Strings.Set(PwDefs.PasswordField,
new ProtectedString(_host.Database.MemoryProtection.ProtectPassword, incomingField.Value));
}
else if (incomingField.ValuePath == PwDefs.UserNameField)
{
pwe.Strings.Set(PwDefs.UserNameField,
new ProtectedString(_host.Database.MemoryProtection.ProtectUserName, incomingField.Value));
}
fields.Add(new Field
{
Name = incomingField.Name,
Page = Math.Max(incomingField.Page, 1),
ValuePath = incomingField.ValuePath,
Uuid = incomingField.Uuid,
Type = incomingField.Type,
MatcherConfigs = incomingField.MatcherConfigs.Where(mc => mc != null).ToArray(),
Value = incomingField.ValuePath == "." ? incomingField.Value : null
});
}
conf.Fields = fields.ToArray();
List<string> altUrls = new List<string>();
for (int i = 0; i < entry.Urls.Length; i++)
{
string url = entry.Urls[i];
if (i == 0)
{
// We can't use the framework Uri.Port property here because
// we are interested in whether it is explicit or not - the
// Port property returns the default port for a protocol if
// one is not explicitly included in the URL
URLSummary urlsum = URLSummary.FromURL(url);
// Require more strict default matching for entries that come
// with a port configured (user can override in the rare case
// that they want the loose domain-level matching)
if (!string.IsNullOrEmpty(urlsum.Port))
{
var mc = conf.MatcherConfigs.First(emc => emc.MatcherType == EntryMatcherType.Url);
mc.UrlMatchMethod = MatchAccuracyMethod.Hostname;
}
pwe.Strings.Set("URL", new ProtectedString(_host.Database.MemoryProtection.ProtectUrl, url ?? ""));
}
else
altUrls.Add(url);
}
conf.AltUrls = altUrls.ToArray();
conf.HttpRealm = string.IsNullOrEmpty(entry.Realm) ? null : entry.Realm;
conf.Version = 2;
// Set some of the string fields
pwe.Strings.Set(PwDefs.TitleField,
new ProtectedString(_host.Database.MemoryProtection.ProtectTitle, entry.Title ?? ""));
// update the icon for this entry (in most cases we'll
// just detect that it is the same standard icon as before)
PwUuid customIconUuid = PwUuid.Zero;
PwIcon iconId = PwIcon.Key;
if (entry.Icon != null
&& _iconConverter.dtoToIcon(ClientMetadata, entry.Icon, ref customIconUuid, ref iconId))
{
if (ReferenceEquals(customIconUuid, PwUuid.Zero))
pwe.IconId = iconId;
else
pwe.CustomIconUuid = customIconUuid;
}
pwe.SetKPRPCConfig(conf);
}
#endregion
/// <summary>
/// Returns a list of every entry contained within a group (not recursive)
/// </summary>
/// <param name="pwd">the database to search in</param>
/// <param name="group">the group to search in</param>
/// <param name="fullDetails">true = all details; false = some details ommitted (e.g. password)</param>
/// <param name="urlRequired">true = URL field must exist for a child entry to be returned, false = all entries are returned</param>
/// <returns>the list of every entry directly inside the group.</returns>
private LightEntry2[] GetChildEntries2(PwDatabase pwd, PwGroup group, bool fullDetails, bool urlRequired)
{
List<Entry2> allEntries = new List<Entry2>();
List<LightEntry2> allLightEntries = new List<LightEntry2>();
if (group != null)
{
PwObjectList<PwEntry> output;
output = group.GetEntries(false);
foreach (PwEntry pwe in output)
{
if (EntryIsInRecycleBin(pwe, pwd))
continue; // ignore if it's in the recycle bin
if (urlRequired && string.IsNullOrEmpty(pwe.Strings.ReadSafe("URL")))
continue;
if (fullDetails)
{
Entry2 kpe = (Entry2)GetEntry2FromPwEntry(pwe, MatchAccuracy.None, true, pwd, true);
if (kpe != null) // is null if entry is marked as hidden from KPRPC
allEntries.Add(kpe);
}
else
{
LightEntry2 kpe = GetEntry2FromPwEntry(pwe, MatchAccuracy.None, false, pwd, true);
if (kpe != null) // is null if entry is marked as hidden from KPRPC
allLightEntries.Add(kpe);
}
}
if (fullDetails)
{
allEntries.Sort(delegate(Entry2 e1, Entry2 e2) { return e1.Title.CompareTo(e2.Title); });
return allEntries.ToArray();
}
allLightEntries.Sort(delegate(LightEntry2 e1, LightEntry2 e2)
{
return e1.Title.CompareTo(e2.Title);
});
return allLightEntries.ToArray();
}
return null;
}
/// <summary>
/// Returns a list of every group contained within a group
/// </summary>
/// <param name="group">the unique ID of the group we're interested in.</param>
/// <param name="complete">true = recursive, including Entries too (direct child entries are not included)</param>
/// <param name="fullDetails">true = all details; false = some details ommitted (e.g. password)</param>
/// <returns>the list of every group directly inside the group.</returns>
private Group2[] GetChildGroups2(PwDatabase pwd, PwGroup group, bool complete, bool fullDetails)
{
List<Group2> allGroups = new List<Group2>();
if (pwd == null || group == null)
{
return null;
}
PwObjectList<PwGroup> output;
output = group.Groups;
foreach (PwGroup pwg in output)
{
if (pwd.RecycleBinUuid.Equals(pwg.Uuid))
continue; // ignore if it's the recycle bin
Group2 kpg = GetGroup2FromPwGroup(pwg);
if (complete)
{
kpg.ChildGroups = GetChildGroups2(pwd, pwg, true, fullDetails);
if (fullDetails)
kpg.ChildEntries = (Entry2[])GetChildEntries2(pwd, pwg, fullDetails, true);
else
kpg.ChildLightEntries = GetChildEntries2(pwd, pwg, fullDetails, true);
}
allGroups.Add(kpg);
}
allGroups.Sort(delegate(Group2 g1, Group2 g2) { return g1.Title.CompareTo(g2.Title); });
return allGroups.ToArray();
}
}
}
|