Harden assembly timestamp handling
This commit is contained in:
@@ -0,0 +1,107 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using NUnit.Framework;
|
||||
using Sarand.Net.Standard.Base.Utils;
|
||||
|
||||
namespace Sarand.UnitTests.Core.Base.Utils
|
||||
{
|
||||
[TestFixture]
|
||||
public class AssemblyUtil_Tester
|
||||
{
|
||||
// --- Tests ---
|
||||
|
||||
[Test]
|
||||
public void TryGetBuildDateTime_ReadsCoffTimestamp()
|
||||
{
|
||||
DateTime expected = new DateTime(2024, 7, 8, 9, 10, 11, DateTimeKind.Utc);
|
||||
String assemblyPath = CreatePeFile((UInt32)(expected - DateTime.UnixEpoch).TotalSeconds);
|
||||
|
||||
try
|
||||
{
|
||||
Boolean result = AssemblyUtil.TryGetBuildDateTime(assemblyPath, out DateTime actual);
|
||||
|
||||
Assert.That(result, Is.True);
|
||||
Assert.That(actual, Is.EqualTo(expected));
|
||||
Assert.That(actual.Kind, Is.EqualTo(DateTimeKind.Utc));
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(assemblyPath);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TryGetBuildDateTime_ReturnsFalseForInvalidPeSignature()
|
||||
{
|
||||
String assemblyPath = CreatePeFile(0, 0);
|
||||
|
||||
try
|
||||
{
|
||||
Boolean result = AssemblyUtil.TryGetBuildDateTime(assemblyPath, out DateTime buildDateTime);
|
||||
|
||||
Assert.That(result, Is.False);
|
||||
Assert.That(buildDateTime, Is.EqualTo(DateTime.MinValue));
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(assemblyPath);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TryGetBuildDateTime_ReturnsFalseForTruncatedFile()
|
||||
{
|
||||
String assemblyPath = Path.GetTempFileName();
|
||||
|
||||
try
|
||||
{
|
||||
Boolean result = AssemblyUtil.TryGetBuildDateTime(assemblyPath, out DateTime buildDateTime);
|
||||
|
||||
Assert.That(result, Is.False);
|
||||
Assert.That(buildDateTime, Is.EqualTo(DateTime.MinValue));
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(assemblyPath);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TryGetBuildDateTime_ReadsLoadedAssembly()
|
||||
{
|
||||
Assembly assembly = typeof(AssemblyUtil).Assembly;
|
||||
|
||||
Boolean result = assembly.TryGetBuildDateTime(out DateTime buildDateTime);
|
||||
|
||||
Assert.That(result, Is.True);
|
||||
Assert.That(buildDateTime.Kind, Is.EqualTo(DateTimeKind.Utc));
|
||||
Assert.That(assembly.GetBuildDateTime(), Is.EqualTo(buildDateTime));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TryGetBuildDateTime_RejectsNullAssembly()
|
||||
{
|
||||
Assembly assembly = null;
|
||||
|
||||
Assert.That(() => assembly.TryGetBuildDateTime(out _), Throws.ArgumentNullException);
|
||||
}
|
||||
|
||||
// --- Test Support ---
|
||||
|
||||
private static String CreatePeFile(UInt32 timeDateStamp, UInt32 peSignature = 0x00004550)
|
||||
{
|
||||
const Int32 coffHeaderOffset = 0x80;
|
||||
Byte[] content = new Byte[coffHeaderOffset + 12];
|
||||
BitConverter.GetBytes((UInt32)coffHeaderOffset).CopyTo(content, 0x3c);
|
||||
BitConverter.GetBytes(peSignature).CopyTo(content, coffHeaderOffset);
|
||||
BitConverter.GetBytes(timeDateStamp).CopyTo(content, coffHeaderOffset + 8);
|
||||
|
||||
String path = Path.Combine(Path.GetTempPath(), $"AssemblyUtil-{Guid.NewGuid():N}.dll");
|
||||
File.WriteAllBytes(path, content);
|
||||
return path;
|
||||
}
|
||||
|
||||
// --- The End ---
|
||||
}
|
||||
}
|
||||
@@ -1,62 +1,84 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Sarand.Net.Standard.Base.Utils
|
||||
{
|
||||
//=======================================================================
|
||||
public static class AssemblyUtil
|
||||
{
|
||||
//-------------------------------------------------------------------
|
||||
#region Gets the build date and time (by reading the COFF header)
|
||||
// http://msdn.microsoft.com/en-us/library/ms680313
|
||||
// --- Definitions ---
|
||||
|
||||
struct _IMAGE_FILE_HEADER
|
||||
{
|
||||
#pragma warning disable CS0649
|
||||
public ushort Machine;
|
||||
public ushort NumberOfSections;
|
||||
public uint TimeDateStamp;
|
||||
public uint PointerToSymbolTable;
|
||||
public uint NumberOfSymbols;
|
||||
public ushort SizeOfOptionalHeader;
|
||||
public ushort Characteristics;
|
||||
#pragma warning restore CS0649
|
||||
};
|
||||
private const Int32 DosHeaderPeOffsetPosition = 0x3c;
|
||||
private const UInt32 PeSignature = 0x00004550;
|
||||
private const Int32 CoffTimeDateStampPosition = 8;
|
||||
|
||||
// --- Build Information ---
|
||||
|
||||
/// <summary>
|
||||
/// Gets the UTC date and time represented by the assembly's PE/COFF timestamp.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Deterministic builds may not store the physical build time in this field.
|
||||
/// Use <see cref="TryGetBuildDateTime(Assembly, out DateTime)"/> when the caller
|
||||
/// needs to distinguish an unavailable timestamp from <see cref="DateTime.MinValue"/>.
|
||||
/// </remarks>
|
||||
|
||||
public static DateTime GetBuildDateTime(this Assembly assembly)
|
||||
{
|
||||
var path = assembly.Location;
|
||||
if (File.Exists(path))
|
||||
{
|
||||
var buffer = new byte[Math.Max(Marshal.SizeOf(typeof(_IMAGE_FILE_HEADER)), 4)];
|
||||
using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
|
||||
{
|
||||
fileStream.Position = 0x3C;
|
||||
fileStream.Read(buffer, 0, 4);
|
||||
fileStream.Position = BitConverter.ToUInt32(buffer, 0); // COFF header offset
|
||||
fileStream.Read(buffer, 0, 4); // "PE\0\0"
|
||||
fileStream.Read(buffer, 0, buffer.Length);
|
||||
}
|
||||
var pinnedBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);
|
||||
try
|
||||
{
|
||||
var coffHeader = (_IMAGE_FILE_HEADER)Marshal.PtrToStructure(pinnedBuffer.AddrOfPinnedObject(), typeof(_IMAGE_FILE_HEADER));
|
||||
DateTime buildDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
return buildDate.AddSeconds(coffHeader.TimeDateStamp);
|
||||
//return TimeZoneInfo.Local.ToLocalTime(new DateTime(1970, 1, 1) + new TimeSpan(coffHeader.TimeDateStamp * TimeSpan.TicksPerSecond));
|
||||
}
|
||||
finally
|
||||
{
|
||||
pinnedBuffer.Free();
|
||||
}
|
||||
}
|
||||
return new DateTime();
|
||||
return TryGetBuildDateTime(assembly, out DateTime buildDateTime)
|
||||
? buildDateTime
|
||||
: DateTime.MinValue;
|
||||
}
|
||||
#endregion
|
||||
|
||||
//-------------------------------------------------------------------
|
||||
/// <summary>
|
||||
/// Tries to get the UTC date and time represented by the assembly's PE/COFF timestamp.
|
||||
/// </summary>
|
||||
public static Boolean TryGetBuildDateTime(this Assembly assembly, out DateTime buildDateTime)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(assembly);
|
||||
|
||||
if (String.IsNullOrEmpty(assembly.Location))
|
||||
{
|
||||
buildDateTime = DateTime.MinValue;
|
||||
return false;
|
||||
}
|
||||
|
||||
return TryGetBuildDateTime(assembly.Location, out buildDateTime);
|
||||
}
|
||||
|
||||
// --- PE Header Parsing ---
|
||||
|
||||
internal static Boolean TryGetBuildDateTime(String assemblyPath, out DateTime buildDateTime)
|
||||
{
|
||||
buildDateTime = DateTime.MinValue;
|
||||
|
||||
try
|
||||
{
|
||||
using FileStream fileStream = new FileStream(assemblyPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||
using BinaryReader reader = new BinaryReader(fileStream);
|
||||
|
||||
fileStream.Position = DosHeaderPeOffsetPosition;
|
||||
UInt32 coffHeaderOffset = reader.ReadUInt32();
|
||||
fileStream.Position = coffHeaderOffset;
|
||||
if (reader.ReadUInt32() != PeSignature)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
fileStream.Position = coffHeaderOffset + CoffTimeDateStampPosition;
|
||||
UInt32 timeDateStamp = reader.ReadUInt32();
|
||||
buildDateTime = DateTime.UnixEpoch.AddSeconds(timeDateStamp);
|
||||
return true;
|
||||
}
|
||||
catch (Exception exception) when (exception is IOException
|
||||
or UnauthorizedAccessException
|
||||
or ArgumentException
|
||||
or NotSupportedException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// --- The End ---
|
||||
}
|
||||
//=======================================================================
|
||||
}
|
||||
|
||||
@@ -7,11 +7,12 @@ table td {
|
||||
}
|
||||
</style>
|
||||
|
||||
Last updated: 2026-09-15
|
||||
Last updated: 2026-09-16
|
||||
|
||||
| Component | Scope | Status | Date reviewed | Next steps | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| `SaCommonVS.sln` | .NET 10 migration build and tests | Migration complete; passing with warnings | 2026-09-15 | Continue the staged package review with the remaining framework-aligned and separately tested major updates. | All supported projects target .NET 10 only. The completed low-risk batch, System.Data.Odbc 10.0.12, and Microsoft.Data.SqlClient 7.0.3 pass the complete validation. The solution builds with zero errors and all 144 tests pass; BusinessMgr builds with 11 Control and 13 Portal tests passing. Xamarin remains isolated and unchanged. |
|
||||
| `SacsStandardBase/Base/Utils/AssemblyUtil.cs` | PE/COFF timestamp utility | Hardened and covered | 2026-09-16 | Retain the focused tests; use the non-throwing `TryGetBuildDateTime` API where an unavailable timestamp must be distinguished from `DateTime.MinValue`. | Exact primitive reads replace unchecked partial reads and marshaling. Five tests cover a known timestamp, invalid signature, truncated input, a loaded assembly, and null input. COFF timestamps are not presented as reliable physical build times for deterministic builds. Existing framework APIs already cover assembly identity, version, and metadata, so no duplicate convenience wrappers were added. |
|
||||
| `SaCommonVS.sln` | .NET 10 migration build and tests | Migration complete; passing with warnings | 2026-09-16 | Continue the staged package review with the remaining framework-aligned and separately tested major updates. | All supported projects target .NET 10 only. The completed package and utility updates pass the complete validation. The solution builds with zero errors and all 149 tests pass; BusinessMgr builds with 11 Control and 13 Portal tests passing. Xamarin remains isolated and unchanged. |
|
||||
| `SacsStandardBase/Base/Utils/ImageUtils.cs` | ImageSharp wrapper | Covered; package retained pending later functional review | 2026-09-16 | Leave ImageSharp 3.1.12 unchanged and revisit raster handling, licensing, and alternatives separately. | Five in-memory tests cover PNG and JPEG metadata, invalid and truncated input, SVG recognition, format-preserving encoding, proportional landscape and portrait resizing, no-upscale behavior, and invalid constraints. Later options are to license and upgrade to ImageSharp 4.1.2, retain a secure 3.x release, migrate to MIT-licensed SkiaSharp with its native assets and wrapper rewrite, or evaluate Magick.NET/ImageMagick for its broad format and processing support while accounting for native binaries and a heavier dependency footprint. This raster concern is distinct from BusinessMgr's Windows-only report printing. |
|
||||
| `SacsStandardBase` JSON utilities and `SysId` converter | Newtonsoft.Json integration | Covered for package upgrades | 2026-09-14 | Retain the suite for future Newtonsoft.Json updates. | Six tests cover objects, arrays, nulls, serializer settings, valid and invalid parsing paths, dynamic access, `SysId` conversion, independent deep copies, nested collections, and constructor-value replacement. |
|
||||
| `SacsStandardDbas` provider and parameter creation | Microsoft.Data.SqlClient, System.Data.Odbc, and registry integration | Providers aligned with .NET 10; broader coverage complete | 2026-09-15 | Add optional configured database integration tests when a suitable SQL Server or ODBC test database is available. | Microsoft.Data.SqlClient 7.0.3 and System.Data.Odbc 10.0.12 are covered by eleven database-free tests for provider selection, parsed SQL connection security and authentication settings, adapter creation, parameter order, scalar and null types, SQL `DateTime2`, ODBC `DateTime`, precision normalization, and sentinel dates. The suite explicitly verifies SqlClient 7's mandatory-encryption option. |
|
||||
@@ -25,4 +26,4 @@ Last updated: 2026-09-15
|
||||
| `SacsStandardProc/Proc/Excel/SaMsSpreadsheet_OpenXml.cs` | Class | Dependency upgrade complete; implementation remains incomplete | 2026-09-15 | Scope functional completion and dedicated wrapper tests separately if this implementation is to be revived. | DocumentFormat.OpenXml 3.5.1 builds and passes the existing spreadsheet and downstream validation. The Open XML implementation contains numerous pre-existing unsupported or placeholder operations, so this update does not present it as production-complete. |
|
||||
| `SacsStandardProc/Proc/Excel/SaMsSpreadsheet_POI.cs` | Class | Dependency upgrade complete | 2026-09-12 | Retain the focused spreadsheet suite for future NPOI updates; do not adopt NPOI 2.8.0 without an explicit licensing decision. | NPOI 2.7.6 is paired with an explicit `System.Security.Cryptography.Xml` 10.0.12 reference and NuGet reports no vulnerable packages for `SacsStandardProc`. Nullable date and indexed-colour API changes were adapted. Ten focused tests and all 111 Common tests pass; BusinessMgr builds and its 21 tests pass. |
|
||||
| `SacsStandardBase/Base/Helpers/SacsEncryptionHelper.cs` and `SacsStandardBase/Base/Data/SacsAesIvCrypter.cs` | Classes | Reviewed; action required | 2026-09-08 | Design a versioned authenticated-encryption format with legacy migration and tamper tests. | Current CBC encryption is unauthenticated; password-based key derivation uses a fixed salt and low iteration count. |
|
||||
| `eng/validate.ps1` | Repository validation | Complete; passing | 2026-09-15 | Use as the standard validation entry point and extend it when repository-wide checks change. | Builds serially, runs the 11-test focused SQL/ODBC-provider suite, the 10-test focused NPOI suite, and all 144 Common tests; audits both package-owning projects; verifies changed-file line endings and diffs; then invokes BusinessMgr validation. |
|
||||
| `eng/validate.ps1` | Repository validation | Complete; passing | 2026-09-16 | Use as the standard validation entry point and extend it when repository-wide checks change. | Builds serially, runs the 11-test focused SQL/ODBC-provider suite, the 10-test focused NPOI suite, and all 149 Common tests; audits both package-owning projects; verifies changed-file line endings and diffs; then invokes BusinessMgr validation. |
|
||||
|
||||
+3
-2
@@ -7,13 +7,13 @@ table td {
|
||||
}
|
||||
</style>
|
||||
|
||||
Last updated: 2026-09-15
|
||||
Last updated: 2026-09-16
|
||||
|
||||
## Prioritised Topics to Be Actioned
|
||||
|
||||
| Priority | Topic | Date noted | Next step | Notes |
|
||||
|---|---|---|---|---|
|
||||
| P2 | Resolve .NET 10 migration warnings in non-MAUI Common code | 2026-09-10 | Replace the obsolete `Rfc2898DeriveBytes` constructor and make the three `FileStream.Read` operations exact. | The redundant Registry package has been removed. The remaining .NET 10 build warnings are `SYSLIB0060` and three `CA2022` warnings. The cryptography change overlaps the existing encryption-hardening topic and requires compatibility tests. |
|
||||
| P2 | Resolve the remaining .NET 10 migration warning in non-MAUI Common code | 2026-09-10 | Replace the obsolete `Rfc2898DeriveBytes` constructor with an explicitly compatible derivation configuration. | The Registry and `AssemblyUtil` warning work is complete. The remaining warning is `SYSLIB0060`; its cryptography change overlaps the existing encryption-hardening topic and requires compatibility tests. |
|
||||
| P3 | Review raster image handling and ImageSharp | 2026-09-16 | Retain ImageSharp 3.1.12 for now and revisit the wrapper, licensing, and alternatives as a separately scoped functional review. | Version 3.1.12 has no reported vulnerability and five focused tests cover the current narrow use. Later options are: obtain an eligible free or commercial licence and upgrade to ImageSharp 4.1.2; retain a supported secure 3.x release; migrate to MIT-licensed SkiaSharp, accepting native runtime assets and a wrapper rewrite; or evaluate Magick.NET/ImageMagick as a candidate with broad image-format and processing support but native binaries and a heavier dependency footprint. This review is separate from BusinessMgr's Windows printer integration. |
|
||||
| P1 | Prevent synchronous and asynchronous execution from overlapping in `SaProcess_Base` | 2026-09-09 | Route `RunProcess()` and `RunAsync()` through one guarded start operation and extend the lifecycle tests. | A synchronous call can currently reuse and dispose the asynchronous worker's task data. |
|
||||
| P2 | Retain cancellation as a completed process outcome | 2026-09-09 | Store a durable cancellation result until the next process reset and test post-completion state. | `IsInterrupted` currently loses token-based cancellation after task-data cleanup. |
|
||||
@@ -45,6 +45,7 @@ Last updated: 2026-09-15
|
||||
|
||||
| Topic | Date noted | Date started | Date completed | Outcome |
|
||||
|---|---|---|---|---|
|
||||
| Harden and cover `AssemblyUtil` PE timestamp handling | 2026-09-10 | 2026-09-16 | 2026-09-16 | Replaced the unchecked partial reads and marshalled COFF structure with exact primitive reads, PE-signature validation, and graceful handling of missing, malformed, or truncated files. Added a public `TryGetBuildDateTime` extension while preserving `GetBuildDateTime`, plus five focused tests. The API documentation notes that deterministic-build COFF timestamps need not represent physical build time. |
|
||||
| Upgrade Microsoft.Data.SqlClient and expand SQL provider coverage | 2026-09-15 | 2026-09-15 | 2026-09-15 | Updated Microsoft.Data.SqlClient from 5.2.3 to 7.0.3. Expanded the database-free provider suite from eight to eleven tests, adding parsed SQL connection security and authentication settings plus complete SQL scalar and typed-null parameter coverage. The tests explicitly verify SqlClient 7's mandatory-encryption option. Full Common and downstream BusinessMgr validation passes. |
|
||||
| Align System.Data.Odbc with .NET 10 and expand provider coverage | 2026-09-15 | 2026-09-15 | 2026-09-15 | Updated the Common ODBC dependency from 6.0.2 to 10.0.12 and removed six redundant direct references from BusinessMgr consumers. Expanded the database-free provider suite from four to eight tests, covering non-SQL connections, adapter creation, parameter order, scalar types, and typed nulls. The tests exposed and prompted correction of missing explicit `Int64`, `Decimal`, `Boolean`, `Guid`, and string mappings. All 141 Common tests and both BusinessMgr suites pass. |
|
||||
| Update ZstdNet and cover HTTP decompression | 2026-09-15 | 2026-09-15 | 2026-09-15 | Updated ZstdNet from 1.4.5 to 1.5.7. Added an in-process loopback HTTP test that creates a Zstandard-compressed UTF-8 response and verifies status, headers, native decompression, and decoded content through `SacsHttpClient`. The focused test, all 137 Common tests, and downstream BusinessMgr validation pass. |
|
||||
|
||||
Reference in New Issue
Block a user