Autor
|
Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) (Leído 589,720 veces)
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.959
|
Métodos universales para trabajar aspectos básicos con fuentes de texto (.ttf, .otf y .fon). Aspectos destacables del código ◉ Nombres descriptivos y documentación extensa, no creo que requieran ejemplos de uso (de todas formas no me cabrían en este post). ◉ Ligeras micro optimizaciones para .NET 5+ mediante directiva del preprocesador ( #If NETCOREAPP...) Incluye varios métodos para: ◉ Instalar/desinstalar una fuente solamente para el usuario local, o de forma global. Para esto último es posible requerir permisos de administrador. ◉ Determinar si una fuente está actualmente instalada en el sistema operativo, identificando varios aspectos como si el nombre del archivo o el nombre de la fuente están registradas en el Registro de Windows. ◉ Determinar el formato de un archivo de fuente. Soporta los formatos: TrueType (.ttf), OpenType con contornos TrueType (.ttf), OpenType PostScript (CFF) (.otf), y raster/bitmap (.fon). ◉ Obtener el nombre amistoso completo de una fuente de texto, exactamente tal y como se muestra en la barra de título del visor de fuentes de Windows (FontView.exe). ◉ Obtener el nombre del archivo de recurso de fuente escalable (.FOT) a partir de un archivo de fuente. En torno a la instalación y desinstalación de fuentes: ◉ Al instalar una fuente permite cargarla en memoria, con lo cual se enviará el mensaje correspondiente a todas las ventanas del sistema operativo para notificar de un cambio (una nueva fuente disponible), de tal forma que otros programas puedan reconocer y utilizar dicha fuente. ◉ Al instalar una fuente se identifica correctamente el formato TrueType u OpenType y se registra apropiadamente en el nombre de la clave de registro correspondiente. Se puede anular este comportamiento mediante un parámetro Boolean para que siempre se añada el sufijo "(TrueType)" al nombre de la clave de registro tal y como lo hace la shell de Windows indiferentemente de si la fuente es OpenType. Esto no se aplica a fuentes raster/bitmap (.fon). ◉ Al desinstalar una fuente, permite eliminar el archivo. Si no se puede eliminar al primer intento, se detiene temporalmente el "Servicio de caché de fuentes de Windows" ('FontCache') para evitar posibles bloqueos y reintentar la eliminación. Al finalizar la desinstalación, se reanuda el servicio. Diferencias en los nombres de fuentesPara entrar en contexto y ver las diferencias en perspectiva, y tomando como ejemplo la fuente de texto OpenType PostScript (CFF) "JustBreatheBoldObliqueseven-7vgw.otf" ( descarga), estos son los resultados: ◉ Nombre de la clave de registro al instalar la fuente de forma tradicional mediante la shell de Windows 10 (Menú contextual -> Instalar): Just Breathe Bold ObliqueSeven (TrueType) (sí, pone 'TrueType' a pesar de ser una fuente OpenType CFF, sin contornos TrueType.)  ◉ Nombre mostrado en la barra de título del visor de fuentes de Microsoft Windows (FontView.exe) Just Breathe Bold ObliqueSeven (OpenType)  ◉ Nombre devuelto por mi función GetFontFriendlyName, con sufijo: Just Breathe Bold ObliqueSeven (OpenType) (Siempre debería devolver el mismo nombre que en el visor de fuentes de Microsoft Windows, eso sí, sin espacios en blanco adicionales al final del nombre ni antes del paréntesis del sufijo, cosa que FontView.exe no tiene en cuenta, pero mi código sí. Lo he comparado programaticamente con aprox. 14.000 fuentes de texto para asegurarme de su fiabilidad.) ◉ Nombre devuelto por mi función GetFontFriendlyName, sin sufijo: Just Breathe Bold ObliqueSeven ◉ Nombre devuelto por mi función GetFontResourceName: (A veces, GetFontResourceName devolverá el mismo nombre que GetFontFriendlyName sin sufijo, es decir, el nombre escrito en el recurso de fuente escalable puede ser idéntico.) ◉ Nombre devuelto utilizando una combinación de propiedades de la clase System.Windows.Media.GlyphTypeface: El código utilizado: Dim fontUri As New Uri("C:\JustBreatheBoldObliqueseven-7vgw.otf", UriKind.Absolute) Dim gtf As New System.Windows.Media.GlyphTypeface(fontUri) Dim fontName As String = String.Join(" "c, gtf.FamilyNames.Values) Dim fontFaceNames As String = String.Join(" "c, gtf.FaceNames.Values) Dim fullName As String = $"{fontName} {fontFaceNames}" Console.WriteLine(fullName)
◉ Nombre devuelto por las propiedades System.Drawing.Font.Name y System.Drawing.FontFamily.Name: ◉ Nombre devuelto por las propiedades System.Drawing.Font.OriginalName y System.Drawing.Font.SystemNameNINGUNO (VALOR VACÍO EN ESTE CASO CONCRETO) Acerca de fontreg.exeExiste una herramienta por línea de comandos llamada "fontreg.exe" ( GitHub) que funciona como un sustituto moderno —aunque ya algo anticuado— del obsoleto fontinst.exe de Microsoft Windows. Sin embargo, no la recomiendo para instalar fuentes de forma programática. Para un usuario común, esta herramienta será más que suficiente, pero para un programador no es lo ideal por las siguientes razones: ◉ Su funcionamiento requiere que "fontreg.exe" se coloque en el mismo directorio donde se encuentran las fuentes, y al ejecutarlo instalará todas las fuentes del directorio sin permitir seleccionar una instalación de fuentes individuales. ◉ El programa no imprime mensajes de salida que sirvan para depurar la operación de instalación. ◉ No puedes saber si la fuente se instalará solo para el usuario actual (HKCU) o de manera global en el sistema (HKLM). Además, he detectado varios fallos: ◉ En ocasiones extrae incorrectamente el nombre de la fuente, y, debido a esto, en algunos casos termina escribiendo caracteres ininteligibles en la clave de registro, ej.: "⿻⿷⿸⿹ (TrueType)", y ese es el nombre que verás al listar la fuente en tu editor de texto. ◉ Al igual que la shell de Windows al registrar el nombre de una fuente en el registro de Windows, no hace distinción entre TrueType y OpenType: siempre se añade el sufijo "(TrueType)". Por estas razones, su uso en entornos programáticos o controlados no es ni productivo, ni confiable. El código completo semi-completo (he tenido que eliminar mucha documentación XML ya que no me cabía en este post):Librerías (paquetes NuGet) necesarias: ◉ WindowsAPICodePack ◉ System.ServiceProcess.ServiceController (solo para usuarios de .NET 5+) Imports necesarios:#If NETCOREAPP Then Imports System.Buffers.Binary #End If Imports System.ComponentModel Imports System.Diagnostics.CodeAnalysis Imports System.IO Imports System.Runtime.InteropServices Imports System.Runtime.Versioning Imports System.Security Imports System.ServiceProcess Imports System.Text Imports Microsoft.Win32 Imports Microsoft.WindowsAPICodePack.Shell Imports DevCase.Win32 Imports DevCase.Win32.Enums
Clases secundarias requeridas:#Region " Constants " Namespace DevCase.Win32.Common.Constants <HideModuleName> Friend Module Constants #Region " Window Messaging " ''' <summary> ''' Handle to use with window messaging functions. ''' <para></para> ''' When used, the message is sent to all top-level windows in the system, ''' including disabled or invisible unowned windows, overlapped windows, and pop-up windows; ''' but the message is not sent to child windows. ''' </summary> Friend ReadOnly HWND_BROADCAST As New IntPtr(65535US) #End Region End Module End Namespace #End Region
#Region " Window Messages " Namespace DevCase.Win32.Enums Friend Enum WindowMessages As Integer ''' <summary> ''' An application sends the message to all top-level windows in the system after changing the ''' pool of font resources. ''' </summary> WM_FontChange = &H1D End Enum End Namespace #End Region
#Region " NativeMethods " Namespace DevCase.Win32.NativeMethods <SuppressUnmanagedCodeSecurity> Friend Module Gdi32 <DllImport("GDI32.dll", SetLastError:=False, CharSet:=CharSet.Auto, ThrowOnUnmappableChar:=True, BestFitMapping:=False)> Friend Function AddFontResource(fileName As String ) As Integer End Function <DllImport("GDI32.dll", SetLastError:=True, CharSet:=CharSet.Auto, ThrowOnUnmappableChar:=True, BestFitMapping:=False)> Friend Function RemoveFontResource(fileName As String ) As <MarshalAs(UnmanagedType.Bool)> Boolean End Function End Module <SuppressUnmanagedCodeSecurity> Friend Module User32 <DllImport("User32.dll", SetLastError:=True)> Friend Function SendMessage(hWnd As IntPtr, msg As WindowMessages, wParam As IntPtr, lParam As IntPtr ) As IntPtr End Function End Module End Namespace #End Region
Clase principal 'UtilFonts', que contiene los métodos universales (y otros miembros relacionados) en torno a fuentes de texto:Public Class UtilFonts ''' <summary> ''' Magic number located at the beginning of a TrueType font (.ttf) file header. ''' </summary> Private Shared ReadOnly TT_MAGIC As Byte() = { &H0, &H1, &H0, &H0 } ''' <summary> ''' Magic number located at the beginning of a TrueType font (.ttf) file header ''' that starts with ASCII string "true". ''' </summary> Private Shared ReadOnly TT_MAGIC_TRUE As Byte() = { &H74, &H72, &H75, &H65 ' "true" } ''' <summary> ''' Magic number located at the beginning of an OpenType font with CFF (PostScript) outlines (.otf) file header. ''' <para></para> ''' This distinguishes them from OpenType-TT fonts. ''' </summary> Private Shared ReadOnly OT_MAGIC As Byte() = { &H4F, &H54, &H54, &H4F ' "OTTO" } ''' <summary> ''' Retrieves a user-friendly name for a given font file, ''' that is identical to the 'Title' property shown by Windows Explorer, ''' allowing to provide consistent font identification in your application. ''' </summary> ''' ''' <param name="fontFile"> ''' The path to the font file (e.g., <b>"C:\font.ttf"</b>). ''' </param> ''' ''' <param name="includeSuffix"> ''' If <see langword="True"/>, includes a suffix that specifies ''' the underlying font technology (e.g., "Font name <c>(TrueType)</c>", "Font name <c>(OpenType)</c>"), ''' ensuring that the font name matches exactly the name shown in Microsoft's Windows Font Viewer (FontView.exe) title bar. ''' </param> ''' ''' <returns> ''' The user-friendly name for the given font file. ''' </returns> <DebuggerStepThrough> Public Shared Function GetFontFriendlyName(fontFile As String, includeSuffix As Boolean) As String If Not File. Exists(fontFile ) Then Dim msg As String = $"The font file does not exist: '{fontFile}'" Throw New FileNotFoundException(msg, fontFile) End If Dim fontTitle As String = ShellFile.FromFilePath(fontFile).Properties.System.Title.Value.Trim() If String.IsNullOrWhiteSpace(fontTitle) Then Dim msg As String = "'Title' property for the given font is empty." Throw New FormatException(msg) End If If includeSuffix Then Dim fontType As FontType = UtilFonts.GetFontType(fontFile) Select Case fontType Case FontType.Invalid Dim msg As String = "File does not seems a valid font file (file size is too small)." Throw New FileFormatException(msg) Case FontType.Unknown Dim msg As String = "Font file type is not recognized. " & "It might be an unsupported format, corrupted file Or Not a valid font file." Throw New FileFormatException(msg) Case FontType.TrueType Return $"{fontTitle} (TrueType)" Case FontType.OpenTypeCFF, FontType.OpenTypeTT Return $"{fontTitle} (OpenType)" Case Else ' FontType.Raster ' Nothing to do. End Select End If Return fontTitle End Function ''' <summary> ''' Determines the type of a font file. ''' <para></para> ''' Supports TrueType (.ttf), OpenType (.otf/.ttf) and Raster/Bitmap (.fon). ''' </summary> ''' ''' <param name="fontFile"> ''' The path to the font file (e.g., <b>"C:\font.ttf"</b>). ''' </param> ''' ''' <returns> ''' A <see cref="FontType"/> value indicating the font type of the given file. ''' <para></para> ''' If the font type cannot be recognized, it returns <see cref="FontType.Unknown"/>. ''' <para></para> ''' If the given file does not meet the criteria to be treated as a font file, it returns <see cref="FontType.Invalid"/>. ''' </returns> <DebuggerStepThrough> Public Shared Function GetFontType(fontFile As String) As FontType If Not File. Exists(fontFile ) Then Dim msg As String = $"The font file does not exist: '{fontFile}'" Throw New FileNotFoundException(msg, fontFile) End If ' 512 bytes is the minimum length I found sufficient ' to reliably read the header of any raster (.fon) font file ' to find its string markers that identifies this file type. Const minFontFileLength As Short = 512 Dim fi As New FileInfo(fontFile) If fi.Length <= minFontFileLength Then Return FontType.Invalid End If Try Using fs As FileStream = fi.OpenRead(), br As New BinaryReader(fs) Dim headerBytes As Byte() = br.ReadBytes(4) ' TrueType check. If headerBytes.SequenceEqual(UtilFonts.TT_MAGIC) OrElse headerBytes.SequenceEqual(UtilFonts.TT_MAGIC_TRUE) Then ' OpenType-TT check br.BaseStream.Seek(4, SeekOrigin.Begin) #If NETCOREAPP Then Dim numTables As UShort = BinaryPrimitives.ReverseEndianness(br.ReadUInt16()) #Else ' Read two bytes directly. Dim bytes As Byte() = br.ReadBytes(2) ' If the system is little-endian, reverse the bytes to interpret as big-endian. If BitConverter.IsLittleEndian Then Array.Reverse(bytes) End If ' Now get the UShort value in big-endian. Dim swapped As UShort = BitConverter.ToUInt16(bytes, 0) Dim numTables As UShort = swapped #End If br.BaseStream.Seek(6, SeekOrigin.Current) ' skip: searchRange, entrySelector, rangeShift ' Search advanced OpenType tables. For i As Integer = 0 To numTables - 1 Dim tag As String = Encoding.ASCII.GetString(br.ReadBytes(4)) br.ReadBytes(12) ' checkSum, offset, length If tag = "GSUB" OrElse tag = "GPOS" OrElse tag = "GDEF" OrElse tag = "BASE" Then Return FontType.OpenTypeTT End If Next Return FontType.TrueType End If ' OpenType CFF check. If headerBytes.SequenceEqual(UtilFonts.OT_MAGIC) Then Return FontType.OpenTypeCFF End If ' Raster/Bitmap check. br.BaseStream.Seek(0, SeekOrigin.Begin) headerBytes = br.ReadBytes(minFontFileLength) Dim headerText As String = Encoding.ASCII.GetString(headerBytes) If headerText.Contains("FONTDIR") AndAlso headerText.Contains("FONTRES") Then Return FontType.Raster End If End Using Catch ex As Exception Throw End Try Return FontType.Unknown End Function ''' <summary> ''' Specifies the type of a font file. ''' </summary> Public Enum FontType As Short ''' <summary> ''' A TrueType font (.ttf). ''' <para></para> ''' This is the traditional TrueType format developed by Apple™. ''' </summary> TrueType ''' <summary> ''' An OpenType font with PostScript (CFF) outlines (.otf). ''' <para></para> ''' These fonts use the .otf container from the OpenType format jointly developed by Adobe™ and Microsoft™. ''' </summary> OpenTypeCFF ''' <summary> ''' An OpenType font with TrueType outlines (.ttf). ''' <para></para> ''' Technically OpenType, but uses TrueType outlines inside a .ttf container. ''' <para></para> ''' Sometimes called 'OpenType-TT' for distinction. ''' </summary> OpenTypeTT ''' <summary> ''' A Raster / Bitmap font (.fon) with fixed-size glyphs. ''' <para></para> ''' Raster fonts store each character as a pixel grid, not as scalable outlines. ''' <para></para> ''' These were commonly used in older versions of Windows and DOS, and are mostly legacy fonts today. ''' </summary> Raster ''' <summary> ''' Font file type is not recognized. ''' <para></para> ''' It might be an unsupported format, corrupted file or not a valid font file. ''' </summary> Unknown ''' <summary> ''' File does not seems a valid font file (file size is too small). ''' </summary> Invalid End Enum ''' <summary> ''' Determines whether a font file is already installed in the current computer. ''' </summary> ''' ''' <param name="fontFilePathOrName"> ''' Either the full path to the font file or just the file name ''' (e.g., <b>"C:\font.ttf"</b> or else <b>"font.ttf"</b>). ''' </param> ''' ''' <param name="systemWide"> ''' If <see langword="True"/>, performs a system-wide search for the font installation (under <c>HKEY_LOCAL_MACHINE</c> base key). ''' otherwise, searches only the current user's installed fonts (under <c>HKEY_CURRENT_USER</c> base key). ''' </param> ''' ''' <returns> ''' If the font file is not installed, returns <see cref="CheckFontInstallationResults.NotInstalled"/>; ''' otherwise, can return a combination of <see cref="CheckFontInstallationResults"/> values. ''' </returns> <DebuggerStepThrough> Public Shared Function CheckFontInstallation(fontFilePathOrName As String, systemWide As Boolean) As CheckFontInstallationResults Dim fontFilePath As String = UtilFonts.BuildFullFontFilePath(fontFilePathOrName, systemWide) Dim fontFileName As String = Path.GetFileName(fontFilePath) Dim fontTitle As String = UtilFonts.GetFontFriendlyName(fontFilePath, includeSuffix:=False) Dim fontTitleTT As String = $"{fontTitle} (TrueType)" Dim fontTitleOT As String = $"{fontTitle} (OpenType)" Dim result As CheckFontInstallationResults = CheckFontInstallationResults.NotInstalled Dim baseKey As RegistryKey = If(systemWide, Registry.LocalMachine, Registry.CurrentUser) Dim regKeyPath As String = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts" Try Using key As RegistryKey = baseKey.OpenSubKey(regKeyPath, writable:=False) ' Fonts registry key does not exists. If key Is Nothing Then Exit Try End If Dim valueFontTitle As Object = CStr(key.GetValue(fontTitle)) Dim valueFontTitleTT As Object = CStr(key.GetValue(fontTitleTT)) Dim valueFontTitleOT As Object = CStr(key.GetValue(fontTitleOT)) Dim fontTitles() As String = {fontTitle, fontTitleTT, fontTitleOT} For Each title As String In fontTitles Dim regValue As Object = key.GetValue(title, Nothing, RegistryValueOptions.DoNotExpandEnvironmentNames) ' Font title found in registry If regValue IsNot Nothing Then result = result Or CheckFontInstallationResults.FontTitleFound ' Font file matches? If String.Equals(CStr(regValue), fontFileName, StringComparison.OrdinalIgnoreCase) Then result = result Or CheckFontInstallationResults.FileNameFound End If End If If result = (CheckFontInstallationResults.FontTitleFound Or CheckFontInstallationResults.FileNameFound) Then Exit For End If Next If Not result.HasFlag(CheckFontInstallationResults.FileNameFound) Then ' Additional check required for consistency because the font file name ' could be specified in a value name that differs from the compared font title vale names. Dim valueNames As String() = Array.ConvertAll(key.GetValueNames(), Function(str As String) str.ToLowerInvariant()) If valueNames.Contains(fontFileName.ToLowerInvariant()) Then result = result Or CheckFontInstallationResults.FileNameFound End If End If End Using Catch ex As Exception Throw End Try Return result End Function ''' <summary> ''' Specifies the installation status of a font file on the current computer. ''' </summary> <Flags> Public Enum CheckFontInstallationResults As Short ''' <summary> ''' The font is not installed. ''' </summary> NotInstalled = 0S ''' <summary> ''' A registry value with the font file name is present in the Windows <b>Fonts</b> registry key. ''' </summary> FileNameFound = 1S << 0S ''' <summary> ''' A registry value name with the font title ''' (which also may have suffix: "<b>(TrueType)</b>" or "<b>(OpenType)</b>") ''' is present in the Windows <b>Fonts</b> registry key. ''' </summary> FontTitleFound = 1S << 1S End Enum ''' <summary> ''' Installs a font file permanently on the current computer. ''' </summary> ''' ''' <param name="fontFile"> ''' The path to the font file to install (e.g., <b>"C:\font.ttf"</b>). ''' </param> ''' ''' <param name="systemWide"> ''' If <see langword="True"/>, performs a system-wide installation; ''' otherwise, installs the font for the current user only. ''' </param> ''' ''' <param name="useTrueTypeNameSuffix"> ''' If <see langword="True"/>, appends the "<b>(TrueType)</b>" suffix when ''' naming the font registry value for TrueType and OpenType fonts. ''' This is what Microsoft Windows does by default. ''' <para></para> ''' If <see langword="False"/>, appends the appropriate suffix for the font type: "<b>(TrueType)</b>" or "<b>(OpenType)</b>". ''' <para></para> ''' This setting does not apply to .fon files. ''' </param> ''' ''' <param name="addFontToSystemTable"> ''' If <see langword="True"/>, the font resource is loaded into memory and immediately available to other applications. ''' </param> <DebuggerStepThrough> Public Shared Sub InstallFont(fontFile As String, systemWide As Boolean, useTrueTypeNameSuffix As Boolean, addFontToSystemTable As Boolean) Dim isFontInstalled As Boolean Try isFontInstalled = (UtilFonts.CheckFontInstallation(fontFile, systemWide) <> UtilFonts.CheckFontInstallationResults.NotInstalled) Catch ex As FileNotFoundException ' Use this exception message for readness, since CheckFontInstallation calls BuildFullFontFilePath, which modifies the path. Dim msg As String = $"The font file does not exist: '{fontFile}'" Throw New FileNotFoundException(msg, fontFile) Catch ex As Exception Throw End Try If isFontInstalled Then Dim msg As String = $"The font file is already installed: '{fontFile}'" Throw New InvalidOperationException(msg) End If Dim fontFileName As String = Path.GetFileName(fontFile) Dim fontTitle As String = UtilFonts.GetFontFriendlyName(fontFile, includeSuffix:=True) If useTrueTypeNameSuffix Then fontTitle = fontTitle.Replace(" (OpenType)", " (TrueType)") End If Dim fontsDir As String = If(systemWide, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Fonts"), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft\Windows\Fonts")) If Not Directory.Exists(fontsDir) Then Directory.CreateDirectory(fontsDir) End If Dim fontFileDestPath As String = Path.Combine(fontsDir, fontFileName) If File. Exists(fontFileDestPath ) Then Dim msg As String = $"Font file already exists in Fonts directory: {fontFileDestPath}" Throw New InvalidOperationException(msg) End If Try File. Copy(fontFile, fontFileDestPath, overwrite: =False) Catch ex As Exception Dim msg As String = $"Error copying font file to Fonts directory: '{fontFileDestPath}'" Throw New IOException(msg, ex) End Try Dim baseKey As RegistryKey = If(systemWide, Registry.LocalMachine, Registry.CurrentUser) Dim regKeyPath As String = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts" Dim registrySuccess As Boolean Try Using key As RegistryKey = baseKey.CreateSubKey(regKeyPath, writable:=True) key.SetValue(fontTitle, fontFileName, RegistryValueKind.String) End Using registrySuccess = True Catch ex As Exception Throw Finally If Not registrySuccess Then ' Attempt to delete the copied font file in Fonts directory ' when registry manipulation has failed. Try File. Delete(fontFileDestPath ) Catch ' Ignore deletion exceptions; cleanup best effort. End Try End If End Try ' Add the font to the system font table. If addFontToSystemTable Then Dim fontsAdded As Integer = DevCase.Win32.NativeMethods.AddFontResource(fontFileDestPath) Dim win32Err As Integer = Marshal.GetLastWin32Error() If fontsAdded = 0 OrElse win32Err <> 0 Then Dim msg As String = $"Failed to add font to the system font table '{fontFileDestPath}'" Throw New InvalidOperationException(msg, New Win32Exception(win32Err)) End If ' Notify all top-level windows so they can immediately list the added font. DevCase.Win32.NativeMethods.SendMessage(DevCase.Win32.Common.Constants.HWND_BROADCAST, WindowMessages.WM_FontChange, IntPtr.Zero, IntPtr.Zero) End If End Sub ''' <summary> ''' Uninstalls a font file from the current computer. ''' </summary> ''' ''' <param name="fontFilePathOrName"> ''' Either the full path to the font file or just the file name ''' (e.g., <b>"C:\font.ttf"</b> or else <b>"font.ttf"</b>). ''' </param> ''' ''' <param name="systemWide"> ''' If <see langword="True"/>, performs a system-wide uninstallation; ''' otherwise, uninstalls the font for the current user only. ''' </param> ''' ''' <param name="deleteFile"> ''' If <see langword="True"/>, permanently deletes the font file from disk. ''' <para></para> ''' Note: The font file deletion will be performed after deleting associated registry values with the font file. ''' </param> <DebuggerStepThrough> Public Shared Sub UninstallFont(fontFilePathOrName As String, systemWide As Boolean, deleteFile As Boolean) Dim fontFilePath As String = UtilFonts.BuildFullFontFilePath(fontFilePathOrName, systemWide) Dim fontFileName As String = Path.GetFileName(fontFilePath) Dim checkFontInstallation As CheckFontInstallationResults = UtilFonts.CheckFontInstallation(fontFilePath, systemWide) Dim isFontInstalled As Boolean = (checkFontInstallation <> UtilFonts.CheckFontInstallationResults.NotInstalled) If Not isFontInstalled Then Dim msg As String = $"The font file is not installed: '{fontFilePath}'" Throw New InvalidOperationException(msg) End If Dim fontTitle As String = UtilFonts.GetFontFriendlyName(fontFilePath, includeSuffix:=False) Dim fontTitleTT As String = $"{fontTitle} (TrueType)" Dim fontTitleOT As String = $"{fontTitle} (OpenType)" Dim baseKey As RegistryKey = If(systemWide, Registry.LocalMachine, Registry.CurrentUser) Dim regKeyPath As String = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts" Try Using key As RegistryKey = baseKey.OpenSubKey(regKeyPath, writable:=True) Dim valueNames As String() = key.GetValueNames() ' Compare font title. If checkFontInstallation.HasFlag(CheckFontInstallationResults.FontTitleFound) Then If valueNames.Contains(fontTitle) Then key.DeleteValue(fontTitle, throwOnMissingValue:=True) ElseIf valueNames.Contains(fontTitleTT) Then key.DeleteValue(fontTitleTT, throwOnMissingValue:=True) ElseIf valueNames.Contains(fontTitleOT) Then key.DeleteValue(fontTitleOT, throwOnMissingValue:=True) End If ElseIf checkFontInstallation.HasFlag(CheckFontInstallationResults.FileNameFound) Then For Each valueName As String In valueNames ' Compare font file name. Dim value As String = CStr(key.GetValue(valueName)) If String.Equals(value, fontFileName, StringComparison.OrdinalIgnoreCase) Then key.DeleteValue(valueName, throwOnMissingValue:=True) Exit For End If Next End If End Using Catch ex As Exception Throw End Try If deleteFile Then Dim fontsDir As String = If(systemWide, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Fonts"), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft\Windows\Fonts")) Dim fontFileDestPath As String = Path.Combine(fontsDir, fontFileName) ' First attempt to delete the file. Try File. Delete(fontFileDestPath ) Catch End Try If File. Exists(fontFileDestPath ) Then ' Remove the font from the system font table, ' because in case of 'AddFontResource' was called for this font file in the current user session, ' the font will remain loaded in memory and cannot be deleted until unloaded from memory. Dim result As Boolean = DevCase.Win32.NativeMethods.RemoveFontResource(fontFileDestPath) Dim win32Err As Integer = Marshal.GetLastWin32Error() If result Then ' Notify all top-level windows so they can immediately delist the removed font. DevCase.Win32.NativeMethods.SendMessage(DevCase.Win32.Common.Constants.HWND_BROADCAST, WindowMessages.WM_FontChange, IntPtr.Zero, IntPtr.Zero) Else ' Ignore throwing an exception, since we don't really know if the font file was loaded in memory. 'Dim msg As String = $"Failed to remove font file from the system font table: '{fontFileDestPath}'" 'Throw New InvalidOperationException(msg, New Win32Exception(win32Err)) End If ' Second attempt to delete the file. Try File. Delete(fontFileDestPath ) Catch End Try End If If File. Exists(fontFileDestPath ) Then ' Ensure that the 'FontCache' service is stopped, as it could habe blocked the font file. Using sc As New ServiceController("FontCache") Dim previousStatus As ServiceControllerStatus = sc.Status If (sc.Status <> ServiceControllerStatus.Stopped) AndAlso (sc.Status <> ServiceControllerStatus.StopPending) Then Try sc.Stop() sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(3)) Catch ex As Exception ' Ignore throwing an exception, ' since we don't really know if the 'FontCache' service have blocked the font file at all. 'If sc.Status <> ServiceControllerStatus.Stopped Then ' Dim msg As String = "Unable to stop 'FontCache' service." ' Throw New InvalidOperationException(msg, ex) 'End If End Try End If ' Third and last attempt to delete the file. Try File. Delete(fontFileDestPath ) Catch ex As Exception Dim msg As String = $"Error deleting font file from Fonts directory: '{fontFileDestPath}'" Throw New IOException(msg, ex) Finally ' Restore previous 'FontCache' service status if it was started and not in automatic mode. If sc.StartType <> ServiceStartMode.Automatic AndAlso ( (previousStatus = ServiceControllerStatus.Running) OrElse (previousStatus = ServiceControllerStatus.StartPending) ) AndAlso sc.Status <> ServiceControllerStatus.Running Then Try sc.Start() sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(0.25)) Catch ' Ignore throwing an exception; best effort. End Try End If End Try End Using End If End If End Sub ''' <summary> ''' Builds a full path to a font file from the given value in <paramref name="fontFilePathOrName"/> parameter. ''' <para></para> ''' If the provided file path exists, it is returned as-is; otherwise, ''' the function constructs and returns a full file path based on ''' the value of <paramref name="systemWide"/> parameter. ''' <para></para> ''' Note: This function does not check whether the resulting file path exists. ''' </summary> ''' ''' <param name="fontFilePathOrName"> ''' Either the full path to the font file or just the file name ''' (e.g., <b>"C:\font.ttf"</b> or else <b>"font.ttf"</b>). ''' <para></para> ''' If the provided path exists, the function returns this path as-is. ''' </param> ''' ''' <param name="systemWide"> ''' If <see langword="True"/>, the function constructs a full font file path from the system's Fonts directory ''' (<b>%WINDIR%\Fonts</b>); otherwise, it constructs a full font file path from the current user's local Fonts directory ''' (<b>%LOCALAPPDATA%\Microsoft\Windows\Fonts</b>). ''' <para></para> ''' Note: The <paramref name="systemWide"/> parameter is ignored if ''' <paramref name="fontFilePathOrName"/> already specifies an existing file path. ''' </param> ''' ''' <returns> ''' The resulting full path to the font file. ''' </returns> <DebuggerStepThrough> Private Shared Function BuildFullFontFilePath(fontFilePathOrName As String, systemWide As Boolean) As String If File. Exists(fontFilePathOrName ) Then Return fontFilePathOrName End If Dim fontFileName As String = Path.GetFileName(fontFilePathOrName) If String.IsNullOrWhiteSpace(fontFileName) Then Throw New ArgumentException("The font file path or name is malformed or empty.", NameOf(fontFilePathOrName)) End If Dim fontsDir As String = If(systemWide, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Fonts"), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft\Windows\Fonts")) Return Path.Combine(fontsDir, fontFileName) End Function End Class
El código continúa aquí abajo 👇🙂
|
|
« Última modificación: 31 Agosto 2025, 16:16 pm por Eleкtro »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.959
|
Esta función pertenece a la clase 'UtilFonts' del anterior post, lo comparto aquí por que no me cabe en el otro post y por que esta función no depende de ninguna otra... ''' <summary> ''' Retrieves the resource name of a TrueType (.ttf) or OpenType font file (.otf) ''' by creating a temporary scalable font resource file and reading its contents. ''' <para></para> ''' This name may differ from the value of the following properties: ''' <list type="bullet"> ''' <item><description><see cref="System.Drawing.Font.Name"/>.</description></item> ''' <item><description><see cref="System.Drawing.Font.OriginalFontName"/>.</description></item> ''' <item><description><see cref="System.Drawing.Font.SystemFontName"/>.</description></item> ''' <item><description><see cref="System.Windows.Media.GlyphTypeface.FamilyNames"/>.</description></item> ''' <item><description><see cref="System.Windows.Media.GlyphTypeface.Win32FamilyNames"/>.</description></item> ''' </list> ''' </summary> ''' ''' <param name="fontFile"> ''' The path to the font file (e.g., <b>"C:\font.ttf"</b>). ''' </param> ''' ''' <returns> ''' The resource name of the given font file. ''' </returns> <DebuggerStepThrough> Public Shared Function GetFontResourceName(fontFile As String) As String If Not File. Exists(fontFile ) Then Dim msg As String = $"The font file does not exist: '{fontFile}'" Throw New FileNotFoundException(msg, fontFile) End If Dim fontName As String = Nothing Dim tempFile As String = Path.Combine(Path.GetTempPath(), "~FONT.RES") ' Ensure any previous existing temp file is deleted. If File. Exists(tempFile ) Then Try Catch ex As Exception Dim msg As String = $"Cannot delete existing temp resource file: '{tempFile}'" Throw New IOException(msg, ex) End Try End If ' Create a temporary scalable font resource. Dim created As Boolean = NativeMethods.CreateScalableFontResource(1UI, tempFile, fontFile, Nothing) If Not created Then Dim msg As String = "Failed to create scalable font resource." Throw New IOException(msg) End If Try ' Read the temp font file resource into a string. Dim buffer As Byte() = File. ReadAllBytes(tempFile ) Dim bufferStr As String = Encoding.Default.GetString(buffer) ' Look for the "FONTRES:" marker. Const fontResMarker As String = "FONTRES:" Dim pos As Integer = bufferStr.IndexOf(fontResMarker) If pos < 0 Then Dim msg As String = "FONTRES marker not found in temporary font resource file." Throw New InvalidOperationException(msg) End If pos += fontResMarker.Length Dim endPos As Integer = bufferStr.IndexOf(ControlChars.NullChar, pos) If endPos < 0 Then Dim msg As String = "Cannot determine the end position of the font name string in the font resource file content." Throw New InvalidOperationException(msg) End If fontName = bufferStr.Substring(pos, endPos - pos) Catch ex As Exception Throw Finally ' Always attempt to delete the created temporary resource file. Try Catch ' Ignore deletion exceptions; cleanup best effort. End Try End Try Return fontName End Function
#Region " NativeMethods " Namespace DevCase.Win32.NativeMethods <SuppressUnmanagedCodeSecurity> Friend Module User32 #Region " GDI32.dll " <DllImport("GDI32.dll", CharSet:=CharSet.Auto, SetLastError:=True, BestFitMapping:=False, ThrowOnUnmappableChar:=True)> Friend Function CreateScalableFontResource(hidden As UInteger, resourceFile As String, fontFile As String, currentPath As String ) As <MarshalAs(UnmanagedType.Bool)> Boolean End Function #End Region End Module End Namespace #End Region
OFF-TOPICSi alguien se pregunta: " ¿Y por qué esa obsesión con las diferentes formas que puede haber para obtener el nombre de una fuente?" " ¿Qué más te da un nombre u otro?" pues bueno, por que yo necesitaba hallar la forma de obtener el nombre completo amistoso exactamente tal y como se muestra en el visor de fuentes de texto de Windows (fontview.exe), por que esa es la representación más completa y la más sofisticada que he visto hasta ahora, " ¿Pero por qué motivo lo necesitas exactamente?" Pues por que se me metió en la cabeza conseguirlo, y yo soy muy cabezón, sin más, así que básicamente en eso ha consistido mi investigación, con varios días de ensayo y error, junto a treinta consultas a ChatGPT con sus cien respuestas inservibles que me sacan de quicio... En el post anterior simplemente he recopilado las diferencias que he ido encontrando al probar diversas maneras de obtener el nombre de una fuente (a lo mejor me he olvidado de alguna otra forma, no sé). A penas hay información sobre esto en Internet (sobre como obtener el nombre amistoso COMPLETO) por no decir que prácticamente no hay nada de nada; aunque bueno, una forma sé que sería leyendo las tablas en la cabecera de un archivo de fuente, pero eso es un auténtico coñazo y propenso a errores humanos, sobre todo si no eres un friki erudito... diseñador de fuentes que conoce todos los entresijos y las "variables" a tener en cuenta al analizar la cabecera de estos formatos de archivo, cosa que evidentemente yo no conozco, pero por suerte al final descubrí que la propiedad "Title" de la shell de Windows es suficiente para lograr mi propósito a la perfección, y sin tener que recurrir a experimentos tediosos que me causarían pesadillas por la noche. Lo de instalar y desinstalar fuentes vino a continuación de lo del nombre, primero necesitaba el nombre amistoso completo, y luego ya teniendo ese nombre -fiel a la representación de Microsoft Windows- podía empezar a desarrollar ideas para hacer cosas más útiles o interesantes. Todos los códigos que he visto por Internet en diferentes lenguajes de programación para instalar un archivo de fuente se quedan muuuy cortos para mis expectativas, carecíendo de las funcionalidades más esenciales, la optimización y los controles de errores más básicos... a diferencia de lo que yo he desarrollado y compartido en el anterior post, que aunque puede que no sea perfecto (por que la perfección absoluta no existe), es mejor que todo lo que he encontrado hasta ahora, y no es por echarme flores ni parecer engreído, pero es la verdad; Me siento sorprendido al no haber descubierto ningún otro programador que haya hecho/compartido un código universal para instalar fuentes de texto de forma más o menos eficiente, confiable y versátil. Quizás lo haya, pero yo no lo encontré. Códigos cortitos y que cumplen la funcionalidad mínima de "instalar una fuente" sin importar ningún factor, de esos hay muchos en Internet, pero como digo un BUEN CÓDIGO no encontré. Lo próximo que comparta en este hilo puede que sea un método universal que sirva para determinar si un archivo de fuente contiene glifos para representar caracteres específicos (ej. "áéíóú"). Ya tengo algo hecho que funciona... pero no siempre funciona de la forma esperada (da falsos positivos con algunos archivos de fuente). Me falta mucho por aprender del formato TrueType y OpenType. Por suerte existen herramientas especializadas como por ejemplo "otfinfo.exe" ( descarga) que sirven para obtener información general de una fuente, imprimir en consola los caracteres de un rango Unicode específico, volcar tablas completas y demás, y tener algo así me ayuda a hacer (y corregir) asunciones al leer este formato de archivo. 👋
|
|
« Última modificación: 31 Agosto 2025, 17:17 pm por Eleкtro »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.959
|
Métodos universales para trabajar (otros) aspectos básicos con fuentes de texto (.ttf y .otf)...(AL FINAL DE ESTE POST HE COMPARTIDO UN EJEMPLO DE USO 😏 )◉ Funciones 'UtilFonts.FontHasGlyph', 'UtilFonts.FontHasGlyphs', 'FontExtensions.HasGlyph' y 'FontExtensions.HasGlyphs' Sirven para determinar si existen glifos en una fuente de texto para un caracter o una serie de caracteres específicos. Se utilizaría, por ejemplo, con este tipo de fuente que no tiene glifos propios para las vocales con tilde:  ◉ Funciones 'UtilFonts.FontGlyphHasOutline' y 'FontExtensions.GlyphHasOutline' Sirven para determinar si un glifo está vacío (no hay contornos dibujados). Se utilizaría, por ejemplo, con este tipo de fuentes que no dibujan las vocales con tilde:  Tener en cuenta que esta función solo sirve para determinar si el glifo contiene algo, no puede determinar si el glifo es una figura incompleta como por ejemplo la de esta vocal que solo tiene la tilde: 
◉ El código fuenteImports necesariosImports System.ComponentModel Imports System.Drawing Imports System.Drawing.Text Imports System.IO Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports DevCase.Win32 Imports DevCase.Win32.Enums Imports DevCase.Win32.Structures
Clases secundarias requeridas(Lo siento pero he tenido que borrar mucha documentación XML -no esencial- para que me quepa todo el código en este post.)#Region " Constants " Namespace DevCase.Win32.Common.Constants <HideModuleName> Friend Module Constants #Region " GDI32 " ''' <summary> ''' Error return value for some GDI32 functions. ''' </summary> Public Const GDI_ERROR As UInteger = &HFFFFFFFFUI ''' <summary> ''' Error return value for some GDI32 functions. ''' </summary> Public ReadOnly HGDI_ERROR As New IntPtr(-1) #End Region End Module End Namespace #End Region
#Region " Enums " Namespace DevCase.Win32.Enums ''' <remarks> ''' List of System Error Codes: <see href="https://docs.microsoft.com/en-us/windows/desktop/Debug/system-error-codes"/>. ''' </remarks> Public Enum Win32ErrorCode As Integer ''' <summary> ''' The operation completed successfully. ''' </summary> ERROR_SUCCESS = &H0 End Enum ''' <remarks> ''' <see href="https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-wcrange"/> ''' </remarks> <Flags> Public Enum GetGlyphIndicesFlags ' GGI ''' <summary> ''' Marks unsupported glyphs with the hexadecimal value 0xFFFF. ''' </summary> MarkNonExistingGlyphs = 1 ' GGI_MARK_NONEXISTING_GLYPHS End Enum ''' <remarks> ''' <see href="https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-getglyphoutlinew"/> ''' </remarks> Public Enum GetGlyphOutlineFormat ' GGO Metrics = 0 Bitmap = 1 ''' <summary> ''' The function retrieves the curve data points in the rasterizer's native format and uses the font's design units. ''' </summary> Native = 2 Bezier = 3 BitmapGray2 = 4 BitmapGray4 = 5 BitmapGray8 = 6 GlyphIndex = &H80 Unhinted = &H100 End Enum End Namespace #End Region
#Region " Structures " Namespace DevCase.Win32.Structures #Region " GlyphMetrics " ''' <remarks> ''' <see href="https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-glyphmetrics"/> ''' </remarks> <StructLayout(LayoutKind.Sequential)> Public Structure GlyphMetrics Public BlackBoxX As UInteger Public BlackBoxY As UInteger Public GlyphOrigin As NativePoint Public CellIncX As Short Public CellIncY As Short End Structure #End Region #Region " NativePoint (POINT) " ''' <summary> ''' Defines the x- and y- coordinates of a point. ''' </summary> ''' ''' <remarks> ''' <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd162805%28v=vs.85%29.aspx"/> ''' </remarks> <DebuggerStepThrough> <StructLayout(LayoutKind.Sequential)> Public Structure NativePoint #Region " Fields " Public X As Integer Public Y As Integer #End Region #Region " Constructors " Public Sub New(x As Integer, y As Integer) Me.X = x Me.Y = y End Sub Public Sub New(pt As Point) Me.New(pt.X, pt.Y) End Sub #End Region #Region " Operator Conversions " Public Shared Widening Operator CType(pt As NativePoint) As Point Return New Point(pt.X, pt.Y) End Operator Public Shared Widening Operator CType(pt As Point) As NativePoint Return New NativePoint(pt.X, pt.Y) End Operator #End Region End Structure #End Region #Region " GlyphOutlineMatrix2 " ''' <remarks> ''' <see href="https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-mat2"/> ''' </remarks> <StructLayout(LayoutKind.Sequential)> Public Structure GlyphOutlineMatrix2 ' MAT2 Public M11 As Fixed Public M12 As Fixed Public M21 As Fixed Public M22 As Fixed ''' <summary> ''' Gets an <see cref="GlyphOutlineMatrix2"/> transformation in which the transformed graphical object is identical to the source object. ''' This is called an identity matrix. ''' <para></para> ''' In this identity matrix, ''' the value of <see cref="GlyphOutlineMatrix2.M11"/> is 1, ''' the value of <see cref="GlyphOutlineMatrix2.M12"/> is zero, ''' the value of <see cref="GlyphOutlineMatrix2.M21"/> is zero, ''' and the value of <see cref="GlyphOutlineMatrix2.M22"/> is 1. ''' </summary> ''' ''' <returns> ''' The resulting <see cref="GlyphOutlineMatrix2"/>. ''' </returns> Public Shared Function GetIdentityMatrix() As GlyphOutlineMatrix2 Return New GlyphOutlineMatrix2() With { .M11 = New Fixed With {.Value = 1}, .M22 = New Fixed With {.Value = 1} } End Function End Structure #End Region #Region " Fixed " ''' <summary> ''' Contains the integral and fractional parts of a fixed-point real number. ''' <para></para> ''' Note: The <see cref="Fixed"/> structure is used to describe the elements of the <see cref="GlyphOutlineMatrix2"/> structure. ''' </summary> ''' ''' <remarks> ''' <see href="https://docs.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-fixed"/> ''' </remarks> <StructLayout(LayoutKind.Sequential)> Public Structure Fixed #Region " Public Fields " ''' <summary> ''' The fractional value. ''' </summary> Public Fraction As UShort ''' <summary> ''' The integral value. ''' </summary> Public Value As Short #End Region #Region " Operator Conversions " Public Shared Widening Operator CType(f As Fixed) As Decimal Return Decimal.Parse($"{f.Value.ToString(NumberFormatInfo.InvariantInfo)}{NumberFormatInfo.InvariantInfo.NumberDecimalSeparator}{f.Fraction.ToString(NumberFormatInfo.InvariantInfo)}", NumberFormatInfo.InvariantInfo) End Operator Public Shared Widening Operator CType(dec As Decimal) As Fixed Return New Fixed With { .Value = CShort(System.Math.Truncate(System.Math.Truncate(dec))), .Fraction = UShort.Parse(dec.ToString(NumberFormatInfo.InvariantInfo).Split({NumberFormatInfo.InvariantInfo.NumberDecimalSeparator}, StringSplitOptions.None)(1), NumberFormatInfo.InvariantInfo) } End Operator #End Region #Region " Public Methods " Public Overrides Function ToString() As String Return CDec(Me).ToString() End Function #End Region End Structure #End Region End Namespace #End Region
#Region " NativeMethods " Namespace DevCase.Win32.NativeMethods <SuppressUnmanagedCodeSecurity> Friend Module Gdi32 ''' <summary> ''' Creates a memory device context (DC) compatible with the specified device. ''' </summary> ''' ''' <remarks> ''' <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd183489%28v=vs.85%29.aspx"/> ''' </remarks> <DllImport("gdi32.dll", SetLastError:=True)> Public Function CreateCompatibleDC(hdc As IntPtr ) As IntPtr End Function ''' <summary> ''' Deletes the specified device context (DC). ''' <para></para> ''' An application must not delete a DC whose handle was obtained by calling the <see cref="GetDC"/> function. ''' instead, it must call the <see cref="ReleaseDC"/> function to free the DC. ''' </summary> ''' ''' <remarks> ''' <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd183533%28v=vs.85%29.aspx"/> ''' </remarks> <DllImport("gdi32.dll")> Public Function DeleteDC(hdc As IntPtr ) As <MarshalAs(UnmanagedType.Bool)> Boolean End Function ''' <summary> ''' Selects an object into a specified device context. ''' <para></para> ''' The new object replaces the previous object of the same type. ''' </summary> ''' ''' <remarks> ''' <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd162957%28v=vs.85%29.aspx"/> ''' </remarks> <DllImport("gdi32.dll", ExactSpelling:=False)> Public Function SelectObject(hdc As IntPtr, hObject As IntPtr ) As IntPtr End Function ''' <summary> ''' Deletes a logical pen, brush, font, bitmap, region, or palette, ''' freeing all system resources associated with the object. ''' <para></para> ''' After the object is deleted, the specified handle is no longer valid. ''' <para></para> ''' Do not delete a drawing object (pen or brush) while it is still selected into a DC. ''' <para></para> ''' When a pattern brush is deleted, the bitmap associated with the brush is not deleted. ''' The bitmap must be deleted independently. ''' </summary> ''' ''' <remarks> ''' <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms633540%28v=vs.85%29.aspx"/> ''' </remarks> <DllImport("gdi32.dll", ExactSpelling:=False, SetLastError:=True)> Public Function DeleteObject(hObject As IntPtr ) As <MarshalAs(UnmanagedType.Bool)> Boolean End Function ''' <summary> ''' Translates a string into an array of glyph indices. ''' <para></para> ''' The function can be used to determine whether a glyph exists in a font. ''' </summary> ''' ''' <remarks> ''' <see href="https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-getglyphindicesw"/> ''' </remarks> <DllImport("gdi32.dll", SetLastError:=False, CharSet:=CharSet.Auto, BestFitMapping:=False, ThrowOnUnmappableChar:=True)> Public Function GetGlyphIndices(hdc As IntPtr, str As String, strLen As Integer, <[Out], MarshalAs(UnmanagedType.LPArray, SizeParamIndex:=2)> glyphIndices As UShort(), Optional flags As GetGlyphIndicesFlags = GetGlyphIndicesFlags.MarkNonExistingGlyphs ) As UInteger End Function ''' <summary> ''' Retrieves the outline or bitmap for a character in the TrueType font that is selected into the specified device context. ''' </summary> ''' ''' <remarks> ''' <see href="https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-getglyphoutlinew"/> ''' </remarks> <DllImport("gdi32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> Public Function GetGlyphOutline(hdc As IntPtr, ch As UInteger, format As GetGlyphOutlineFormat, <Out> ByRef refMetrics As GlyphMetrics, bufferSize As UInteger, buffer As IntPtr, ByRef refMatrix2 As GlyphOutlineMatrix2 ) As UInteger End Function End Module End Namespace #End Region
Clase principal 'UtilFonts' y modulo 'FontExtensions', que contienen los métodos universales en torno a fuentes de textoPublic Class UtilFonts ''' <summary> ''' Prevents a default instance of the <see cref="UtilFonts"/> class from being created. ''' </summary> Private Sub New() End Sub ''' <summary> ''' Determines whether a glyph exists in the given font file ''' for the specified character. ''' </summary> ''' ''' <param name="fontFile"> ''' Path to the font file used to check for glyph availability. ''' </param> ''' ''' <param name="ch"> ''' The character that represents the glyph to check. ''' </param> ''' ''' <returns> ''' <see langword="True"/> if a glyph exists in the font for the specified character; ''' otherwise, <see langword="False"/>. ''' </returns> <DebuggerStepThrough> Public Shared Function FontHasGlyph(fontFile As String, ch As Char) As Boolean Return UtilFonts.FontHasGlyphs(fontFile, ch) = 1 End Function ''' <summary> ''' Determines whether a glyph exists in the given font file ''' for all the characters in the speciied string. ''' </summary> ''' ''' <param name="fontFile"> ''' Path to the font file used to check for glyphs availability. ''' </param> ''' ''' <param name="str"> ''' A <see cref="String"/> with the character(s) that represents the glyphs to check. ''' <para></para> ''' Each character (or surrogate pair) is checked for a existing glyph in the font. ''' </param> ''' ''' <returns> ''' The count of characters from <paramref name="str"/> parameter that have a existing glyph in the font. ''' <para></para> ''' A count less than the length of <paramref name="str"/> indicates that the font does not have a existing glyph for one or more characters. ''' </returns> ''' ''' <exception cref="FileNotFoundException"> ''' Thrown when the font file is not found. ''' </exception> <DebuggerStepThrough> Public Shared Function FontHasGlyphs(fontFile As String, str As String) As UInteger If Not System. IO. File. Exists(fontFile ) Then Throw New FileNotFoundException("Font file not found.", fileName:=fontFile) End If Using pfc As New PrivateFontCollection() pfc.AddFontFile(fontFile) Using f As New Font(pfc.Families(0), emSize:=1) Return FontExtensions.HasGlyphs(f, str) End Using End Using End Function ''' <summary> ''' Determines whether a glyph for the specified character in the given font file has an outline. ''' <para></para> ''' This is useful to determine whether the glyph is empty (no character is drawn), ''' but note that a glyph with outlines does not necessarily mean that the character is fully represented. ''' Some fonts, for instance, only renders diacritical marks for accented vowels ''' instead the full letter (e.g., "<b>´</b>" instead of "<b>í</b>"). ''' This function solely determines whether the glyph draws an outline, nothing more. ''' <para></para> ''' To determine whether a glyph exists in the given font file for the specified character, use ''' <see cref="UtilFonts.FontHasGlyph"/> or <see cref="UtilFonts.FontHasGlyphs"/> instead. ''' </summary> ''' ''' <param name="fontFile"> ''' Path to the font file used to check for glyph availability. ''' </param> ''' ''' <param name="ch"> ''' The character that represents the glyph to check in the font. ''' </param> ''' ''' <returns> ''' Returns <see langword="True"/> if the glyph has an outline (visible shape data exists). ''' <para></para> ''' Returns <see langword="False"/> if the glyph does not have an outline, ''' meaning the glyph is empty/unsupported by the font. ''' </returns> ''' ''' <exception cref="FileNotFoundException"> ''' Thrown when the font file is not found. ''' </exception> <DebuggerStepThrough> Public Shared Function FontGlyphHasOutline(fontFile As String, ch As Char) As Boolean If Not System. IO. File. Exists(fontFile ) Then Throw New FileNotFoundException("Font file not found.", fileName:=fontFile) End If Using pfc As New PrivateFontCollection() pfc.AddFontFile(fontFile) Using f As New Font(pfc.Families(0), emSize:=1) Return FontExtensions.GlyphHasOutline(f, ch) End Using End Using End Function End Class
Module FontExtensions ''' <summary> ''' Determines whether a glyph exists in the given <see cref="System.Drawing.Font"/> ''' for the specified character. ''' </summary> ''' ''' <param name="font"> ''' The <see cref="System.Drawing.Font"/> used to check for glyph availability. ''' </param> ''' ''' <param name="ch"> ''' The character that represents the glyph to check. ''' </param> ''' ''' <returns> ''' <see langword="True"/> if a glyph exists in the font for the specified character; ''' otherwise, <see langword="False"/>. ''' </returns> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> <DebuggerStepThrough> Public Function HasGlyph(font As Font, ch As Char) As Boolean Return FontExtensions.HasGlyphs(font, ch) = 1 End Function ''' <summary> ''' Determines whether a glyph exists in the given <see cref="System.Drawing.Font"/> ''' for all the characters in the speciied string. ''' </summary> ''' ''' <param name="font"> ''' The <see cref="System.Drawing.Font"/> used to check for glyphs availability. ''' </param> ''' ''' <param name="str"> ''' A <see cref="String"/> with the character(s) that represents the glyphs to check. ''' <para></para> ''' Each character (or surrogate pair) is checked for a existing glyph in the font. ''' </param> ''' ''' <returns> ''' The count of characters from <paramref name="str"/> parameter that have a existing glyph in the font. ''' <para></para> ''' A count less than the length of <paramref name="str"/> indicates that the font does not have a existing glyph for one or more characters. ''' </returns> ''' ''' <exception cref="ArgumentNullException"> ''' Thrown when <paramref name="font"/> or <paramref name="str"/> are null. ''' </exception> ''' ''' <exception cref="Win32Exception"> ''' Thrown when a call to Windows API GDI32 functions (creating device context, selecting font, or retrieving glyph indices) fails. ''' </exception> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> <DebuggerStepThrough> Public Function HasGlyphs(font As Font, str As String) As UInteger If font Is Nothing Then Throw New ArgumentNullException(paramName:=NameOf(font)) End If If String.IsNullOrEmpty(str) Then Throw New ArgumentNullException(paramName:=NameOf(str)) End If Dim hdc As IntPtr Dim hFont As IntPtr Dim oldObj As IntPtr Dim win32Err As Integer Try hFont = font.ToHfont() hdc = NativeMethods.CreateCompatibleDC(IntPtr.Zero) win32Err = Marshal.GetLastWin32Error() If hdc = IntPtr.Zero Then Throw New Win32Exception(win32Err) End If oldObj = NativeMethods.SelectObject(hdc, hFont) win32Err = Marshal.GetLastWin32Error() If oldObj = IntPtr.Zero OrElse oldObj = DevCase.Win32.Common.Constants.HGDI_ERROR Then Throw New Win32Exception(win32Err) End If ' Reserve output for each text unit (can be 1 or 2 chars if it's a surrogate pair). Dim strLen As Integer = str.Length Dim indices As UShort() = New UShort(strLen - 1) {} ' Get the glyph indices for the string in the given device context. Dim converted As UInteger = NativeMethods.GetGlyphIndices(hdc, str, strLen, indices, GetGlyphIndicesFlags.MarkNonExistingGlyphs) win32Err = Marshal.GetLastWin32Error() If converted = DevCase.Win32.Common.Constants.GDI_ERROR Then Throw New Win32Exception(win32Err) End If ' Count glyphs that exist (index <> 0xFFFF). ' If any glyph index is 0xFFFF, the glyph does not exist in that font. Dim count As UInteger For Each index As UShort In indices If index <> &HFFFFUS Then count += 1UI End If Next Return count Finally If oldObj <> IntPtr.Zero Then NativeMethods.DeleteObject(oldObj) End If If hFont <> IntPtr.Zero Then NativeMethods.DeleteObject(hFont) End If If hdc <> IntPtr.Zero Then NativeMethods.DeleteDC(hdc) End If End Try End Function ''' <summary> ''' Determines whether a glyph for the specified character in the given <see cref="System.Drawing.Font"/> has an outline. ''' <para></para> ''' This is useful to determine whether the glyph is empty (no character is drawn), ''' but note that a glyph with outlines does not necessarily mean that the character is fully represented. ''' Some fonts, for instance, only renders diacritical marks for accented vowels ''' instead the full letter (e.g., "<b>´</b>" instead of "<b>í</b>"). ''' This function solely determines whether the glyph draws an outline, nothing more. ''' <para></para> ''' To determine whether a glyph exists in the given font file for the specified character, use ''' <see cref="FontExtensions.HasGlyph"/> or <see cref="FontExtensions.HasGlyphs"/> instead. ''' </summary> ''' ''' <param name="font"> ''' The <see cref="System.Drawing.Font"/> used to check for glyph availability. ''' </param> ''' ''' <param name="ch"> ''' The character that represents the glyph to check in the font. ''' </param> ''' ''' <returns> ''' Returns <see langword="True"/> if the glyph has an outline (visible shape data exists). ''' <para></para> ''' Returns <see langword="False"/> if the glyph does not have an outline, ''' meaning the glyph is empty/unsupported by the font. ''' </returns> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> <DebuggerStepThrough> Public Function GlyphHasOutline(font As Font, ch As Char) As Boolean If font Is Nothing Then Throw New ArgumentNullException(paramName:=NameOf(font)) End If Dim hdc As IntPtr Dim hFont As IntPtr Dim oldObj As IntPtr Dim win32Err As Integer Try hFont = font.ToHfont() hdc = NativeMethods.CreateCompatibleDC(IntPtr.Zero) oldObj = NativeMethods.SelectObject(hdc, hFont) win32Err = Marshal.GetLastWin32Error() If oldObj = IntPtr.Zero OrElse oldObj = DevCase.Win32.Common.Constants.HGDI_ERROR Then Throw New Win32Exception(win32Err) End If Dim chCode As UInteger = CUInt(Convert.ToInt32(ch)) Dim format As GetGlyphOutlineFormat = GetGlyphOutlineFormat.Native Dim matrix As GlyphOutlineMatrix2 = GlyphOutlineMatrix2.GetIdentityMatrix() Dim ptCount As UInteger = NativeMethods.GetGlyphOutline(hdc, chCode, format, Nothing, Nothing, Nothing, matrix) win32Err = Marshal.GetLastWin32Error() Select Case ptCount Case 0UI ' Zero curve data points were returned, meaning the glyph is empty/invisible. Return False Case DevCase.Win32.Common.Constants.GDI_ERROR If win32Err = Win32ErrorCode.ERROR_SUCCESS Then ' The function returned GDI_ERROR, but no error recorded by GetLastError, meaning the function succeeded. ' Tests carried out have shown that when this happens the glyph simply does not exists. Return False Else Throw New Win32Exception(win32Err) End If Case Else Return True End Select Finally If oldObj <> IntPtr.Zero Then NativeMethods.DeleteObject(oldObj) End If If hFont <> IntPtr.Zero Then NativeMethods.DeleteObject(hFont) End If If hdc <> IntPtr.Zero Then NativeMethods.DeleteDC(hdc) End If End Try ' =================================================== ' ALTERNATIVE METHODOLOGY USING PURE MANAGED GDI+ ' ' (results are the same than using Windows API calls) ' =================================================== ' ' 'If font Is Nothing Then ' Throw New ArgumentNullException(paramName:=NameOf(font)) 'End If ' 'If font.Unit = GraphicsUnit.Pixel AndAlso font.Size < 8 Then ' Dim msg As String = ' "Font size must be equals or greater than 8 pixels when using GraphicsUnit.Pixel to avoid unreliable pixel detection. " & ' "Suggested font size is 16 pixel size; A value of 32, 64 or bigger pixel size would produce the same results." ' Throw New ArgumentException(msg) ' 'ElseIf font.Size < 4 Then ' Dim msg As String = ' "Font size must be equals or greater than 4 to avoid unreliable pixel detection. " & ' "Suggested usage is GraphicsUnit.Pixel with a font size of 16 pixels; " & ' "A value of 32, 64 or bigger pixel size would produce the same results." ' Throw New ArgumentException(msg) ' 'End If ' '' Measure the required size for the glyph. 'Dim requiredSize As Size 'Using tempBmp As New Bitmap(1, 1) ' Using g As Graphics = Graphics.FromImage(tempBmp) ' Dim sizeF As SizeF = g.MeasureString(ch, font) ' ' Add a small margin to avoid clipping due to rounding. ' requiredSize = New Size(CInt(System.Math.Ceiling(sizeF.Width)) + 4, ' CInt(System.Math.Ceiling(sizeF.Height)) + 4) ' End Using 'End Using ' '' Create a bitmap big enough to render the glyph, '' filling the bitmap background with white color and '' drawing the character in black. 'Using bmp As New Bitmap(requiredSize.Width, requiredSize.Height), ' g As Graphics = Graphics.FromImage(bmp) ' ' Using AntiAlias may help ensure that very thin glyph strokes ' ' still produce detectable pixels, with gray edges. ' ' Without anti-aliasing, such strokes might render too faint or disappear entirely, ' ' causing the glyph to be misidentified as empty. ' g.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias ' g.Clear(Color.White) ' g.DrawString(ch, font, Brushes.Black, 0, 0) ' ' Dim rect As New Rectangle(0, 0, bmp.Width, bmp.Height) ' Dim bmpData As BitmapData = bmp.LockBits(rect, Imaging.ImageLockMode.ReadOnly, Imaging.PixelFormat.Format32bppArgb) ' ' Try ' Dim ptr As IntPtr = bmpData.Scan0 ' Dim bytes As Integer = System.Math.Abs(bmpData.Stride) * bmp.Height ' Dim pixelValues(bytes - 1) As Byte ' Marshal.Copy(ptr, pixelValues, 0, bytes) ' ' ' Iterate through each pixel. ' ' PixelFormat.Format32bppArgb stores pixels as [Blue][Green][Red][Alpha] ' ' i=Blue, i+1=Green, i+2=Red, i+3=Alpha ' For i As Integer = 0 To pixelValues.Length - 1 Step 4 ' Dim red As Byte = pixelValues(i + 2) ' ' ' Check if the pixel is darker than nearly-white (threshold 250) ' ' If so, we found a visible pixel, meaning the glyph is drawn. ' If red < 250 Then ' Return True ' End If ' Next ' Finally ' bmp.UnlockBits(bmpData) ' ' End Try 'End Using ' '' No visible pixels found, meaning the glyph is empty/unsupported by the font. 'Return False End Function End Module
◉ Modo de empleoEl siguiente ejemplo verifica en los archivos de fuente .ttf de un directorio específico si la tipografía incluye los glifos correspondientes a los caracteres á, é, í, ó y ú. En caso de que falte algún glifo, se imprime un mensaje en consola indicando los glifos ausentes, y finalmente envía el archivo de fuente a la papelera de reciclaje (hay que descomentar las lineas marcadas). Dim fontFiles As IEnumerable(Of String) = Directory.EnumerateFiles("C:\Fonts", "*.ttf", SearchOption.TopDirectoryOnly) Dim fontsToDelete As New HashSet(Of String)() Dim chars As Char() = "áéíóú".ToCharArray() For Each fontFile As String In fontFiles Dim missingChars As New HashSet(Of Char)() For Each ch As Char In chars If Not UtilFonts.FontHasGlyph(fontFile, ch) OrElse Not UtilFonts.FontGlyphHasOutline(fontFile, ch) Then missingChars.Add(ch) End If Next If missingChars.Count > 0 Then Console.WriteLine($"[{Path.GetFileName(fontFile)}] Missing glyphs: {String.Join(", ", missingChars)}") fontsToDelete.Add(fontFile) End If Next For Each fontFile As String In fontsToDelete ' Console.WriteLine($"Deleting font file: {fontFile}") ' Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile(fontFile, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.SendToRecycleBin) Next
Por último, quiero comentar que he experimentado estas funciones de forma muy minuciosa, primero con muestras pequeñas de 2 o 3 fuentes... varias veces por cada cambio significativo realizado en el código, y después he probado la versión final con aprox. 14.000 archivos de fuentes de texto, y los resultados han sido muy satisfactorios detectando varios miles de fuentes a los que le faltan los glifos especificados, y, aunque no he podido revisar todos esos miles de fuentes una a una, no he encontrado ningún falso positivo entre varios cientos de fuentes que sí he revisado manualmente.Eso es todo. 👋
|
|
« Última modificación: 3 Septiembre 2025, 01:36 am por Eleкtro »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.959
|
Métodos universales para trabajar (los últimos) aspectos básicos con fuentes de texto (.ttf y .otf)...◉ Funciones 'UtilFonts.GetFontGlyphOutlineData' y 'FontExtensions.GetGlyphOutlineData' Sirven para obtener los datos crudos de contorno (outline) de un glifo para un carácter específico en una fuente. Devuelven un array de bytes que representa la forma vectorial del glifo en el formato solicitado (Native o Bezier). Estos datos se pueden usar como base para comparaciones de glifos. ◉ Funciones 'UtilFonts.FontGlyphOutlinesAreEqual' y 'FontExtensions.GlyphOutlinesAreEqual' Sirven para comparar si dos fuentes producen los mismos datos de contorno (outline) de un glifo para un carácter específico. ◉ Funciones 'UtilFonts.GetFontGlyphOutlineSimilarity' y 'FontExtensions.GetGlyphOutlineSimilarity' Sirven para calcular un índice de similitud entre los contornos de un glifo para un carácter específico en dos fuentes distintas. Se puede usar cuando se quiere medir cuán parecidos son los glifos entre dos fuentes, en lugar de solo saber si son exactamente iguales.
◉ El código fuente⚠️ Importante: Para poder utilizar este código se requieren algunas definiciones de la API de Windows que he compartido en el post anterior a este. No lo comparto aquí de nuevo para evitar repetir código y evitar que este post quede demasiado grande y tedioso de leer. 🙏Public Class UtilFonts ''' <summary> ''' Prevents a default instance of the <see cref="UtilFonts"/> class from being created. ''' </summary> Private Sub New() End Sub ''' <summary> ''' Retrieves the raw outline data for a given glyph from the specified font file. ''' <para></para> ''' This function calls <see cref="DevCase.Win32.NativeMethods.GetGlyphOutline"/> in background ''' to retrieve outline data with the requested <paramref name="format"/>. ''' </summary> ''' ''' <param name="fontFile"> ''' Path to the font file from which the glyph will be obtained. ''' </param> ''' ''' <param name="ch"> ''' The character whose glyph outline will be requested. ''' </param> ''' ''' <param name="format"> ''' The format in which the glyph outline will be retrieved. ''' <para></para> ''' This value only can be <see cref="GetGlyphOutlineFormat.Native"/> or <see cref="GetGlyphOutlineFormat.Bezier"/>. ''' <para></para> ''' Note: callers must interpret the returned byte array based on the selected format. ''' </param> ''' ''' <param name="matrix"> ''' An optional <see cref="GlyphOutlineMatrix2"/> used to transform the glyph outline. ''' <para></para> ''' If no value is provided or default structure is passed, an identity matrix ''' will be used (see: <see cref="GlyphOutlineMatrix2.GetIdentityMatrix()"/>), ''' where the transfromed graphical object is identical to the source object. ''' </param> ''' ''' <returns> ''' A <see cref="Byte"/> array containing the raw glyph outline data with the requested <paramref name="format"/>. ''' <para></para> ''' Returns <see langword="Nothing"/> if the glyph is empty in the specified font. ''' </returns> ''' ''' <exception cref="FileNotFoundException"> ''' Thrown when the font file is not found. ''' </exception> <DebuggerStepThrough> Public Shared Function GetFontGlyphOutlineData(fontFile As String, ch As Char, format As GetGlyphOutlineFormat, Optional matrix As GlyphOutlineMatrix2 = Nothing) As Byte() If Not File. Exists(fontFile ) Then Throw New FileNotFoundException("Font file not found.", fileName:=fontFile) End If Using pfc As New PrivateFontCollection() pfc.AddFontFile(fontFile) Using f As New Font(pfc.Families(0), emSize:=1) Return FontExtensions.GetGlyphOutlineData(f, ch, format, matrix) End Using End Using End Function ''' <summary> ''' Determines whether the glyph outline for the specified character is identical in two font files. ''' </summary> ''' ''' <param name="firstFontFile"> ''' Path to the first font file to compare. ''' </param> ''' ''' <param name="secondFontFile"> ''' Path to the second font file to compare. ''' </param> ''' ''' <param name="ch"> ''' The character whose glyph outline will be compared between the two fonts. ''' </param> ''' ''' <returns> ''' <see langword="True"/> if both fonts produce identical outlines for the specified glyph. ''' <para></para> ''' <see langword="False"/> if the outlines differ or if one of the fonts has an empty glyph. ''' If the glyph outlines are empty in both fonts, returns <see langword="True"/>. ''' </returns> ''' ''' <exception cref="FileNotFoundException"> ''' Thrown when one of the font files is not found. ''' </exception> <DebuggerStepThrough> Public Shared Function FontGlyphOutlinesAreEqual(firstFontFile As String, secondFontFile As String, ch As Char) As Boolean If Not File. Exists(firstFontFile ) Then Throw New FileNotFoundException("First font file not found.", fileName:=firstFontFile) End If If Not File. Exists(secondFontFile ) Then Throw New FileNotFoundException("Second ont file not found.", fileName:=secondFontFile) End If Using firstPfc As New PrivateFontCollection(), secondPfc As New PrivateFontCollection() firstPfc.AddFontFile(firstFontFile) secondPfc.AddFontFile(secondFontFile) Using firstFont As New Font(firstPfc.Families(0), emSize:=1), secondFont As New Font(secondPfc.Families(0), emSize:=1) Return FontExtensions.GlyphOutlineIsEqualTo(firstFont, secondFont, ch) End Using End Using End Function ''' <summary> ''' Computes a similarity score between the glyph outline for the specified character in two font files. ''' </summary> ''' ''' <param name="firstFontFile"> ''' Path to the first font file to compare. ''' </param> ''' ''' <param name="secondFontFile"> ''' Path to the second font file to compare. ''' </param> ''' ''' <param name="ch"> ''' The character whose glyph outline will be compared between the two fonts. ''' </param> ''' ''' <returns> ''' A <see cref="Single"/> value between 0.0 and 1.0 representing the similarity ''' (the number of matching bytes in the outline data) of the glyph outlines. ''' <para></para> ''' If one of the fonts has an empty glyph, returns 0. If the glyph outlines are empty in both fonts, returns 1. ''' </returns> ''' ''' <exception cref="FileNotFoundException"> ''' Thrown when one of the font files is not found. ''' </exception> <DebuggerStepThrough> Public Shared Function GetFontGlyphOutlineSimilarity(firstFontFile As String, secondFontFile As String, ch As Char) As Single If Not File. Exists(firstFontFile ) Then Throw New FileNotFoundException("First font file not found.", fileName:=firstFontFile) End If If Not File. Exists(secondFontFile ) Then Throw New FileNotFoundException("Second ont file not found.", fileName:=secondFontFile) End If Using firstPfc As New PrivateFontCollection(), secondPfc As New PrivateFontCollection() firstPfc.AddFontFile(firstFontFile) secondPfc.AddFontFile(secondFontFile) Using firstFont As New Font(firstPfc.Families(0), emSize:=1), secondFont As New Font(secondPfc.Families(0), emSize:=1) Return FontExtensions.GetGlyphOutlineSimilarity(firstFont, secondFont, ch) End Using End Using End Function End Class
y: Module FontExtensions ''' <summary> ''' Retrieves the raw outline data for a given glyph from the specified <see cref="System.Drawing.Font"/>. ''' <para></para> ''' This function calls <see cref="DevCase.Win32.NativeMethods.GetGlyphOutline"/> in background ''' to retrieve outline data with the requested <paramref name="format"/>. ''' </summary> ''' ''' <param name="font"> ''' The <see cref="System.Drawing.Font"/> object from which the glyph will be obtained. ''' </param> ''' ''' <param name="ch"> ''' The character whose glyph outline will be requested. ''' </param> ''' ''' <param name="format"> ''' The format in which the glyph outline will be retrieved. ''' <para></para> ''' This value only can be <see cref="GetGlyphOutlineFormat.Native"/> or <see cref="GetGlyphOutlineFormat.Bezier"/>. ''' <para></para> ''' Note: callers must interpret the returned byte array based on the selected format. ''' </param> ''' ''' <param name="matrix"> ''' An optional <see cref="GlyphOutlineMatrix2"/> used to transform the glyph outline. ''' <para></para> ''' If no value is provided or default structure is passed, an identity matrix ''' will be used (see: <see cref="GlyphOutlineMatrix2.GetIdentityMatrix()"/>), ''' where the transfromed graphical object is identical to the source object. ''' </param> ''' ''' <returns> ''' A <see cref="Byte"/> array containing the raw glyph outline data with the requested <paramref name="format"/>. ''' <para></para> ''' Returns <see langword="Nothing"/> if the glyph is empty in the specified <paramref name="font"/>. ''' </returns> ''' ''' <exception cref="ArgumentNullException"> ''' Thrown when <paramref name="font"/> is <see langword="Nothing"/>. ''' </exception> ''' ''' <exception cref="ArgumentException"> ''' Thrown when the specified <paramref name="format"/> is invalid to request glyph outline data. ''' </exception> ''' ''' <exception cref="System.ComponentModel.Win32Exception"> ''' Thrown when a Win32 error occurs during font or device context operations. ''' </exception> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> <DebuggerStepThrough> Public Function GetGlyphOutlineData(font As Font, ch As Char, format As GetGlyphOutlineFormat, Optional matrix As GlyphOutlineMatrix2 = Nothing) As Byte() If font Is Nothing Then Throw New ArgumentNullException(paramName:=NameOf(font)) End If If format <> GetGlyphOutlineFormat.Native AndAlso format <> GetGlyphOutlineFormat.Bezier Then Dim msg As String = $"The specified format '{format}' does not produce glyph outline data. " & Environment.NewLine & $"Use '{NameOf(GetGlyphOutlineFormat.Native)}' or '{NameOf(GetGlyphOutlineFormat.Bezier)}' " & "formats to request glyph outline data." Throw New ArgumentException(msg, paramName:=NameOf(format)) End If Dim hdc As IntPtr Dim hFont As IntPtr Dim oldObj As IntPtr Dim win32Err As Integer Try hFont = font.ToHfont() hdc = NativeMethods.CreateCompatibleDC(IntPtr.Zero) oldObj = NativeMethods.SelectObject(hdc, hFont) win32Err = Marshal.GetLastWin32Error() If oldObj = IntPtr.Zero OrElse oldObj = DevCase.Win32.Common.Constants.HGDI_ERROR Then Throw New Win32Exception(win32Err) End If Dim chCode As UInteger = CUInt(Convert.ToInt32(ch)) If matrix.Equals(New GlyphOutlineMatrix2()) Then matrix = GlyphOutlineMatrix2.GetIdentityMatrix() End If Dim needed As UInteger = NativeMethods.GetGlyphOutline(hdc, chCode, format, Nothing, Nothing, Nothing, matrix) win32Err = Marshal.GetLastWin32Error() Select Case needed Case 0UI ' Zero curve data points were returned, meaning the glyph is empty. Return Nothing Case DevCase.Win32.Common.Constants.GDI_ERROR If win32Err = Win32ErrorCode.ERROR_SUCCESS Then ' The function returned GDI_ERROR, but no error recorded by GetLastError, meaning the function succeeded. ' Tests carried out have shown that when this happens the glyph simply does not exists. Return Nothing Else Throw New Win32Exception(win32Err) End If Case Else Dim bufferPtr As IntPtr = Marshal.AllocHGlobal(New IntPtr(needed)) Try Dim got As UInteger = NativeMethods.GetGlyphOutline(hdc, chCode, format, Nothing, needed, bufferPtr, matrix) win32Err = Marshal.GetLastWin32Error() If got = DevCase.Win32.Common.Constants.GDI_ERROR AndAlso win32Err <> Win32ErrorCode.ERROR_SUCCESS Then Throw New Win32Exception(win32Err) End If Dim result(CInt(got) - 1) As Byte Marshal.Copy(bufferPtr, result, 0, CInt(got)) Return result Finally Marshal.FreeHGlobal(bufferPtr) End Try End Select Finally If hFont <> IntPtr.Zero Then NativeMethods.DeleteObject(hFont) End If If oldObj <> IntPtr.Zero Then NativeMethods.DeleteObject(oldObj) End If If hdc <> IntPtr.Zero Then NativeMethods.DeleteDC(hdc) End If End Try End Function ''' <summary> ''' Determines whether the glyph outline for the specified character in the source <see cref="System.Drawing.Font"/> ''' is identical to the glyph outline of the same character in another <see cref="System.Drawing.Font"/>. ''' </summary> ''' ''' <param name="firstFont"> ''' The first <see cref="System.Drawing.Font"/> to compare. ''' </param> ''' ''' <param name="secondFont"> ''' The second <see cref="System.Drawing.Font"/> to compare. ''' </param> ''' ''' <param name="ch"> ''' The character whose glyph outline will be compared between the two fonts. ''' </param> ''' ''' <returns> ''' <see langword="True"/> if both fonts produce identical outlines for the specified glyph. ''' <para></para> ''' <see langword="False"/> if the outlines differ or if one of the fonts has an empty glyph. ''' If the glyph outlines are empty in both fonts, returns <see langword="True"/>. ''' </returns> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> <DebuggerStepThrough> Public Function GlyphOutlinesAreEqual(firstFont As Font, secondFont As Font, ch As Char) As Boolean Dim firstBytes As Byte() = FontExtensions.GetGlyphOutlineData(firstFont, ch, GetGlyphOutlineFormat.Native) Dim secondBytes As Byte() = FontExtensions.GetGlyphOutlineData(secondFont, ch, GetGlyphOutlineFormat.Native) Return (firstBytes Is Nothing AndAlso secondBytes Is Nothing) OrElse ( (firstBytes Is Nothing = (secondBytes Is Nothing)) AndAlso firstBytes.SequenceEqual(secondBytes) ) End Function ''' <summary> ''' Computes a similarity score between the glyph outline for the ''' specified character in the source <see cref="System.Drawing.Font"/>, ''' and the the glyph outline of the same character in another <see cref="System.Drawing.Font"/>. ''' </summary> ''' ''' <param name="firstFont"> ''' The first <see cref="System.Drawing.Font"/> to compare. ''' </param> ''' ''' <param name="secondFont"> ''' The second <see cref="System.Drawing.Font"/> to compare. ''' </param> ''' ''' <param name="ch"> ''' The character whose glyph outlines will be compared between the two fonts. ''' </param> ''' ''' <returns> ''' A <see cref="Single"/> value between 0.0 and 1.0 representing the similarity ''' (the number of matching bytes in the outline data) of the glyph outlines. ''' <para></para> ''' If one of the fonts has an empty glyph, returns 0. If the glyph outlines are empty in both fonts, returns 1. ''' </returns> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> <DebuggerStepThrough> Public Function GetGlyphOutlineSimilarity(firstFont As Font, secondFont As Font, ch As Char) As Single Dim firstBytes As Byte() = FontExtensions.GetGlyphOutlineData(firstFont, ch, GetGlyphOutlineFormat.Native) Dim secondBytes As Byte() = FontExtensions.GetGlyphOutlineData(secondFont, ch, GetGlyphOutlineFormat.Native) If firstBytes Is Nothing AndAlso secondBytes Is Nothing Then Return 1.0F End If If (firstBytes Is Nothing) <> (secondBytes Is Nothing) Then Return 0.0F End If Dim maxLength As Integer = System.Math.Max(firstBytes.Length, secondBytes.Length) Dim minLength As Integer = System.Math.Min(firstBytes.Length, secondBytes.Length) Dim equalCount As Integer = 0 For i As Integer = 0 To minLength - 1 If firstBytes(i) = secondBytes(i) Then equalCount += 1 End If Next Return CSng(equalCount) / maxLength End Function End Module
|
|
« Última modificación: 3 Septiembre 2025, 01:51 am por Eleкtro »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.959
|
Métodos universales para demostrar la vulnerabilidad de validación de firmas en WinVerifyTrust.— Cómo ocultar y ejecutar malware desde un ejecutable firmado digitalmente —Recientemente, descubrí el siguiente artículo sobre la vulnerabilidad CVE-2013-3900, conocida como la "Vulnerabilidad de validación de firmas en WinVerifyTrust": ◉ DeepInstinct - black hat USA 2016: Certificate Bypass: Hiding and Executing Malware from a Digitally Signed ExecutableEsta vulnerabilidad afecta a la función WinVerifyTrust de la API de Windows responsable de verificar la autenticidad de las firmas digitales en archivos (exe, dll, etc), y consiste en la capacidad de un atacante para poder modificar un archivo ejecutable firmado, adjuntando código malicioso en la tabla de certificado ¡sin invalidar la firma digital del archivo!, lo que proporciona una técnica de ocultación muy discreta. La vulnerabilidad se dio a conocer en el año 2013, pero sigue vigente en 2025 (también en Windows 11. De hecho, con más agravio que en versiones anteriores de Windows), y ha sido la forma de ataque a empresas en varias ocasiones (👉 10-Year-Old Windows Vulnerability Exploited in 3CX Attack)  Prueba de indetectabilidadVaya por delante que todo esto lo hago con fines educativos. No soy ningún experto en malware, y no experimento con ello. Pero intentaré aportar lo que pueda: Para ilustrar brevemente la efectividad de esta vulnerabilidad en 2025, podemos usar como ejemplo el EICAR, un archivo de prueba diseñado para evaluar y verificar el funcionamiento del software antivirus. Se trata de un virus simulado que provoca la reacción del motor antivirus, permitiendo demostrar su capacidad para detectar y neutralizar posibles amenazas. Se puede descargar aquí: https://www.eicar.org/download-anti-malware-testfile/Para esta prueba utilizaré el archivo eicar_com.zip (el zip comprimido tal cual). Bien. 👇 Este es el diagnóstico de VirusTotal del archivo eicar_com.zip: ◉ 2546dcffc5ad854d4ddc64fbf056871cd5a00f2471cb7a5bfd4ac23b6e9eedad — 62 detecciones de 69 AVs.  👇 Este es el diagnóstico de VirusTotal de una simple aplicación de consola desarrollada en .NET 4.8, que contiene la representación literal en bytes del archivo eicar_com.zip: Friend Module Module1 Private ReadOnly rawBytes As Byte() = { &H50, ... el resto de bytes ... } Sub Main() End Sub End Module
◉ 7a11573dbb67f839390c29a3615d4627d419d571ee29f6170cab22d87550f5b1 — 21 detecciones de 72 AVs.  👇 Este es el diagnóstico de VirusTotal de la misma aplicación de consola, pero cifrada con el packer Enigma: ◉ eab90e4659a3414e0b09c9036f07318d0356be6382a5198a16ef73621473c0f2 — 23 detecciones de 72 AVs.  Y, por último, 👇 este es el diagnóstico de VirusTotal de un archivo ejecutable firmado, en este caso el propio y legítimo explorer.exe con certificado digital de Microsoft, al que le he adjuntado la aplicación de consola anterior — cifrada con el packer Enigma — al final de la tabla de certificado: ◉ 310025562eb9c497615ffcb6040d9fa5ba6de82b272523656d3a585765d85580 — 3 detecciones de 72 AVs.  Y lo mejor de todo, aparte de la reducción en detecciones, es que la firma no se ha invalidado, por lo que a ojos del sistema operativo sigue siendo un archivo legítimo y totalmente confiable 👍:  Cabe mencionar que si solamente adjuntásemos un archivo PE malicioso y sin cifrar a la tabla de certificado, habría muchas detecciones de AVs, y Windows nos advertiría de que la firma no tiene un formato adecuado:  (Sin embargo, la firma sigue siendo válida, solo que Windows ha detectado que la tabla de certificado no sigue un formato apropiado.) Nota: El hipervínculo mostrado en la advertencia nos llevará al siguiente artículo: MS13-098: Una vulnerabilidad en Windows podría permitir la ejecución remota de código: 10 de diciembre de 2013Por lo que yo he experimentado, esta advertencia al examinar la firma digital de un archivo solo se produce al adjuntar archivos PE y sin cifrar a la tabla de certificado. Podemos adjuntar cualquier tipo de documento de texto plano, imágenes y videos, que estén sin cifrar, y Windows no mostrará ningún aviso sobre formato incorrecto. Por que sí, amigos, aunque esto sería un método descubierto y usado principalmente para ocultar malware, también podríamos darle un uso más didáctico y de utilidad para un mayor número de usuarios, como podría ser la capacidad de ocultar documentos o contraseñas de forma segura donde nadie jamás va a ponerse a mirar: en la tabla de certificado de un archivo PE. Para un archivo con un certificado corrupto, Windows puede mostrar esto:  Y para un archivo con un certificado digital inválido, Windows muestra este mensaje:  (Esa captura de pantalla la he sacado de Internet y la he editado, sí, pero creanme, he invalidado el certificado varias veces y ponía algo así, "El certificado no es válido.") Sin más dilación, vamos con el código que he desarrollado... Características principales del códigoEstas son las principales funciones que he desarrollado: ◉ AppendBlobToPECertificateTable: Añade un bloque de datos al final de la tabla de certificado de un archivo PE. ◉ RemoveBlobFromPECertificateTable: Elimina un bloque de datos específico de la tabla de certificado de un archivo PE. ◉ RemoveBlobsFromPECertificateTable: Elimina todos los bloques de datos de la tabla de certificado de un archivo PE. ◉ GetBlobsFromPECertificateTable: Devuelve una colección con todos los bloques de datos presentes en la tabla de certificado de un archivo PE. Además, también he incluído las siguientes funciones auxiliares de utilidad general: ◉ FileIsPortableExecutable: Determina si un archivo es de facto un archivo PE válido. ◉ FileHasCertificateTable: Determina si un archivo PE contiene una tabla de certificado que no esté vacía. No valida la firma ni el contenido de los certificados; solo verifica la presencia de la tabla. ◉ FileHasCertificate: Determina si un archivo PE contiene un certificado válido que se pueda leer/parsear. No valida la cadena de confianza, expiración ni revocación del certificado. ◉ MarshalExtensions.ConvertToStructure y MarshalExtensions.ConvertToBytes◉ StreamExtensions.ReadExact y StreamExtensions.CopyExactTo💡 Al final de este hilo muestro un breve ejemplo de uso para todas las funciones principales 👍 El código fuenteImports necesarios: Imports System.Collections.Immutable Imports System.Collections.ObjectModel Imports System.ComponentModel Imports System.IO Imports System.Reflection.PortableExecutable Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports System.Security.Cryptography Imports System.Security.Cryptography.X509Certificates Imports System.Text
Módulo MarshalExtensions: ''' <summary> ''' Provides extension methods related to marshaling operations. ''' </summary> Public Module MarshalExtensions ''' <summary> ''' Converts a byte array into a managed structure of type <typeparamref name="T"/>. ''' </summary> ''' ''' <typeparam name="T"> ''' The structure type to convert the byte array into. ''' </typeparam> ''' ''' <param name="structBytes"> ''' The byte array containing the raw data for the structure. ''' </param> ''' ''' <returns> ''' A managed structure of type <typeparamref name="T"/> populated with data from the <paramref name="structBytes"/> byte array. ''' </returns> <Extension> <EditorBrowsable(EditorBrowsableState.Advanced)> Public Function ConvertToStructure(Of T As Structure)(structBytes As Byte()) As T Dim handle As GCHandle = GCHandle.Alloc(structBytes, GCHandleType.Pinned) Try Return Marshal.PtrToStructure(Of T)(handle.AddrOfPinnedObject()) Finally handle.Free() End Try End Function ''' <summary> ''' Converts a managed structure of type <typeparamref name="T"/> into a byte array. ''' </summary> ''' ''' <typeparam name="T"> ''' The structure type to convert to a byte array. ''' </typeparam> ''' ''' <param name="struct"> ''' The structure instance to convert. ''' </param> ''' ''' <returns> ''' A byte array representing the raw memory of the structure. ''' </returns> <Extension> <EditorBrowsable(EditorBrowsableState.Advanced)> Public Function ConvertToBytes(Of T As Structure)(struct As T) As Byte() Dim size As Integer = Marshal.SizeOf(GetType(T)) Dim bytes(size - 1) As Byte Dim ptr As IntPtr = Marshal.AllocHGlobal(size) Try Marshal.StructureToPtr(struct, ptr, True) Marshal.Copy(ptr, bytes, 0, size) Finally Marshal.FreeHGlobal(ptr) End Try Return bytes End Function End Module
Módulo StreamExtensions: ''' <summary> ''' Provides extension methods for <see cref="Stream"/>. ''' </summary> Public Module StreamExtensions ''' <summary> ''' Reads exactly the specified amount of bytes from the current stream, and advances the position within the stream. ''' </summary> ''' ''' <param name="stream"> ''' The source <see cref="Stream"/> to read from. ''' </param> ''' ''' <param name="count"> ''' The exact number of bytes to be read from the stream. ''' </param> ''' ''' <returns> ''' A <see cref="Byte()"/> array containing the bytes read from the stream. ''' </returns> ''' ''' <exception cref="ArgumentNullException"> ''' Thrown if <paramref name="stream"/> is null. ''' </exception> ''' ''' <exception cref="ArgumentException"> ''' Thrown if <paramref name="stream"/> is empty. ''' </exception> ''' ''' <exception cref="ArgumentOutOfRangeException"> ''' Thrown if <paramref name="count"/> is less than or equal to zero. ''' <para></para> ''' Thrown if <paramref name="count"/> is greater than the bytes available from the current position in the stream. ''' </exception> ''' ''' <exception cref="IOException"> ''' Thrown if <paramref name="stream"/> is not readable. ''' </exception> ''' ''' <exception cref="EndOfStreamException"> ''' Thrown if the stream ends before <paramref name="count"/> bytes are read. ''' </exception> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> Public Function ReadExact(stream As Stream, count As Integer) As Byte() If stream Is Nothing Then Throw New ArgumentNullException(paramName:=NameOf(stream)) End If If Not stream.CanRead Then Dim msg As String = "The source stream does not support reading." Throw New IOException(msg) End If If stream.Length <= 0 Then Dim msg As String = "The source stream is empty, cannot read any bytes." Throw New ArgumentException(msg, paramName:=NameOf(stream)) End If If count <= 0 Then Dim msg As String = "Count must be greater than 0." Throw New ArgumentOutOfRangeException(paramName:=NameOf(count), count, msg) End If If (stream.Position + count) > stream.Length Then Dim msg As String = $"Requested {count} bytes, but only {stream.Length - stream.Position} bytes are available from the current position in the source stream." Throw New ArgumentOutOfRangeException(paramName:=NameOf(count), count, msg) End If Dim buffer(count - 1) As Byte Dim totalRead As Integer While totalRead < buffer.Length Dim read As Integer = stream.Read(buffer, totalRead, buffer.Length - totalRead) If read = 0 Then Dim msg As String = "Source stream ended before the requested number of bytes were read." Throw New EndOfStreamException(msg) End If totalRead += read End While Return buffer End Function ''' <summary> ''' Reads exactly the specified amount of bytes from the current stream and writes them to another stream. ''' </summary> ''' ''' <param name="source"> ''' The <see cref="Stream"/> from which to copy the contents to the <paramref name="destination"/> stream. ''' </param> ''' ''' <param name="destination"> ''' The <see cref="Stream"/> to which the contents of the <paramref name="source"/> stream will be copied. ''' </param> ''' ''' <param name="count"> ''' The exact number of bytes to copy from the source stream. ''' </param> ''' ''' <param name="bufferSize"> ''' The size of the buffer. This value must be greater than zero. ''' <para></para> ''' The default size is 81920. ''' </param> ''' ''' <exception cref="ArgumentNullException"> ''' Thrown if <paramref name="source"/> or <paramref name="destination"/> are null. ''' </exception> ''' ''' <exception cref="ArgumentException"> ''' Thrown if the <paramref name="source"/> stream is empty. ''' </exception> ''' ''' <exception cref="ArgumentOutOfRangeException"> ''' Thrown if <paramref name="count"/> or <paramref name="bufferSize"/> are less than or equal to zero. ''' </exception> ''' ''' <exception cref="IOException"> ''' Thrown if <paramref name="source"/> stream is not readable or <paramref name="destination"/> stream is not writable. ''' </exception> ''' ''' <exception cref="EndOfStreamException"> ''' Thrown if the <paramref name="source"/> stream ends before <paramref name="count"/> bytes are copied. ''' </exception> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> Public Sub CopyExactTo(source As Stream, destination As Stream, count As Integer, Optional bufferSize As Integer = 81920) If source Is Nothing Then Throw New ArgumentNullException(paramName:=NameOf(source)) End If If destination Is Nothing Then Throw New ArgumentNullException(paramName:=NameOf(destination)) End If If Not source.CanRead Then Dim msg As String = "The source stream does not support reading." Throw New IOException(msg) End If If Not destination.CanWrite Then Dim msg As String = "The destination stream does not support writting." Throw New IOException(msg) End If If source.Length <= 0 Then Dim msg As String = "The source stream is empty, cannot read any bytes." Throw New ArgumentException(msg, paramName:=NameOf(source)) End If If count <= 0 Then Dim msg As String = "Count must be greater than 0." Throw New ArgumentOutOfRangeException(paramName:=NameOf(count), count, msg) End If If bufferSize <= 0 Then Dim msg As String = "Buffer size must be greater than 0." Throw New ArgumentOutOfRangeException(paramName:=NameOf(bufferSize), bufferSize, msg) End If Dim buffer(bufferSize - 1) As Byte Dim remaining As Integer = count While remaining > 0 Dim toRead As Integer = Math.Min(buffer.Length, remaining) Dim read As Integer = source.Read(buffer, 0, toRead) If read = 0 Then Dim msg As String = "Source stream ended before the requested number of bytes were copied." Throw New EndOfStreamException(msg) End If destination.Write(buffer, 0, read) remaining -= read End While End Sub End Module
El código continúa aquí abajo 👇🙂
|
|
« Última modificación: Hoy a las 19:40 por Eleкtro »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.959
|
Clase PortableExecutableUtil (1ª PARTE): Nota: Para que me cupiera el código en este post, he tenido que eliminar TODA la documentación XML en torno a las excepciones de cada método, además de los códigos de ejemplo que había embedidos en la documentación (de todas formas en el siguiente post muestro ejemplos de uso). Disculpas. 🙏 ''' <summary> ''' Utility class for working with Portable Executable (PE) files. ''' </summary> Partial Public Class PortableExecutableUtil Private Sub New() End Sub ''' <summary> ''' Appends an arbitrary data blob to the Certificate Table data-directory entry ''' in the Portable Executable (PE) header of the given file. ''' </summary> ''' ''' <param name="inputFilePath"> ''' Path to the input —digitally signed— Portable Executable (PE) file (e.g., "C:\Windows\explorer.exe"). ''' </param> ''' ''' <param name="outputFilePath"> ''' Path to the output file that will be written with the modified Certificate Table. ''' <para></para> ''' Cannot be the same as <paramref name="inputFilePath"/>. ''' </param> ''' ''' <param name="blob"> ''' A <see cref="Byte()"/> array containing the arbitrary data blob to append into the certificate table. ''' </param> ''' ''' <param name="markerBegin"> ''' Optional. A byte sequence used to mark the beginning of the data blob within the Certificate Table content. ''' <para></para> ''' Cannot be null or empty. Default value is "<c>#CERT_BLOB_BEGIN#</c>" in UTF-8 encoding bytes. ''' <para></para> ''' It is strongly recommended to use a unique and long enough byte pattern ''' to avoid accidental conflicts when identifying/extracting the appended blob. ''' </param> ''' ''' <param name="markerEnd"> ''' Optional. A byte sequence used to mark the end of the data blob within the Certificate Table content. ''' <para></para> ''' Cannot be null or empty. Default value is "<c>#CERT_BLOB_END#</c>" in UTF-8 encoding bytes. ''' <para></para> ''' It is strongly recommended to use a unique and long enough byte pattern ''' to avoid accidental conflicts when identifying/extracting the appended blob. ''' </param> ''' ''' <param name="throwIfInvalidCertSize"> ''' Optional. Determines whether to allow appending data that will cause to exceed the maximum allowed certificate table size (~100 MB). ''' <para></para> ''' If set to <see langword="True"/>, the method will throw an <see cref="InvalidOperationException"/> ''' if the appended data would cause the certificate table size to exceed the maximum allowed limit, ''' preventing digital signature invalidation. ''' <para></para> ''' If set to <see langword="False"/>, the certificate table size limit can be exceeded (up to ~2 GB) when appending data, ''' but the digital signature will become invalid, as the operating system will ''' not recognize a certificate table greater than the maximum allowed size. ''' Use it at your own risk. ''' <para></para> ''' Default value is <see langword="True"/>. ''' </param> ''' ''' <param name="overwriteOutputFile"> ''' If <see langword="False"/> and the output file already exists, the method throws an <see cref="IOException"/>. ''' <para></para> ''' If <see langword="True"/>, any existing output file will be overwritten. ''' <para></para> ''' Default value is <see langword="False"/>. ''' </param> <DebuggerStepThrough> Public Shared Sub AppendBlobToPECertificateTable(inputFilePath As String, outputFilePath As String, blob As Byte(), Optional markerBegin As Byte() = Nothing, Optional markerEnd As Byte() = Nothing, Optional throwIfInvalidCertSize As Boolean = True, Optional overwriteOutputFile As Boolean = False) ValidateCommonParameters((NameOf(blob), blob)) Using ms As New MemoryStream(blob) AppendBlobToPECertificateTable(inputFilePath, outputFilePath, ms, markerBegin, markerEnd, throwIfInvalidCertSize, overwriteOutputFile) End Using End Sub ''' <summary> ''' Appends an arbitrary data blob to the Certificate Table data-directory entry ''' in the Portable Executable (PE) header of the given file. ''' </summary> ''' ''' <param name="inputFilePath"> ''' Path to the input —digitally signed— Portable Executable (PE) file (e.g., "C:\Windows\explorer.exe"). ''' </param> ''' ''' <param name="outputFilePath"> ''' Path to the output file that will be written with the modified Certificate Table. ''' <para></para> ''' Cannot be the same as <paramref name="inputFilePath"/>. ''' </param> ''' ''' <param name="blobStream"> ''' The <see cref="Stream"/> containing the arbitrary data to append into the certificate table. ''' </param> ''' ''' <param name="markerBegin"> ''' Optional. A byte sequence used to mark the beginning of the data blob within the Certificate Table content. ''' <para></para> ''' Cannot be null or empty. Default value is "<c>#CERT_BLOB_BEGIN#</c>" in UTF-8 encoding bytes. ''' <para></para> ''' It is strongly recommended to use a unique and long enough byte pattern ''' to avoid accidental conflicts when identifying/extracting the appended blob. ''' </param> ''' ''' <param name="markerEnd"> ''' Optional. A byte sequence used to mark the end of the data blob within the Certificate Table content. ''' <para></para> ''' Cannot be null or empty. Default value is "<c>#CERT_BLOB_END#</c>" in UTF-8 encoding bytes. ''' <para></para> ''' It is strongly recommended to use a unique and long enough byte pattern ''' to avoid accidental conflicts when identifying/extracting the appended blob. ''' </param> ''' ''' <param name="throwIfInvalidCertSize"> ''' Optional. Determines whether to allow appending data that will cause to exceed the maximum allowed certificate table size (~100 MB). ''' <para></para> ''' If set to <see langword="True"/>, the method will throw an <see cref="InvalidOperationException"/> ''' if the appended data would cause the certificate table size to exceed the maximum allowed limit, ''' preventing digital signature invalidation. ''' <para></para> ''' If set to <see langword="False"/>, the certificate table size limit can be exceeded (up to ~2 GB) when appending data, ''' but the digital signature will become invalid, as the operating system will ''' not recognize a certificate table greater than the maximum allowed size. ''' Use it at your own risk. ''' <para></para> ''' Default value is <see langword="True"/>. ''' </param> ''' ''' <param name="overwriteOutputFile"> ''' If <see langword="False"/> and the output file already exists, the method throws an <see cref="IOException"/>. ''' <para></para> ''' If <see langword="True"/>, any existing output file will be overwritten. ''' <para></para> ''' Default value is <see langword="False"/>. ''' </param> <DebuggerStepThrough> Public Shared Sub AppendBlobToPECertificateTable(inputFilePath As String, outputFilePath As String, blobStream As Stream, Optional markerBegin As Byte() = Nothing, Optional markerEnd As Byte() = Nothing, Optional throwIfInvalidCertSize As Boolean = True, Optional overwriteOutputFile As Boolean = False) ValidateCommonParameters((NameOf(inputFilePath), inputFilePath), (NameOf(outputFilePath), outputFilePath), (NameOf(blobStream), blobStream), (NameOf(markerBegin), markerBegin), (NameOf(markerEnd), markerEnd), (NameOf(overwriteOutputFile), overwriteOutputFile)) ' PE header alignment (it is aligned on 8-byte boundary). ' https://learn.microsoft.com/en-us/windows/win32/debug/pe-format#overview Const PeHeaderAlignment As Short = 8 ' Maximum Certificate Table size, in bytes, not counting the alignment (PeHeaderAlignment) bytes. ' If a Certificate Table exceeds this size (MaxCertTableSize + PeHeaderAlignment), ' the operating system rejects to parse the certificate. ' Note: This limit is somewhat arbitrary, derived from testing on Windows 10. Const MaxCertTableSize As Integer = 102400000 ' Kibibytes (KiB): 100000 ' Kilobytes (KB): 102400 ' Mebibytes (MiB): 97.65625 ' Megabytes (MB): 102.40 Dim metaStructSize As Integer = Marshal.SizeOf(GetType(CertBlobMeta)) Dim dataWithMarkersSize As Long = markerBegin.Length + metaStructSize + blobStream.Length + markerEnd.Length If throwIfInvalidCertSize AndAlso (dataWithMarkersSize > MaxCertTableSize) Then Dim msg As String = $"The size of the data to append ({NameOf(markerBegin)} + {NameOf(blobStream)} + {NameOf(markerEnd)} = {dataWithMarkersSize} bytes) " & $"exceeds the maximum allowed certificate table size ({MaxCertTableSize} bytes), which would invalidate the digital signature." Throw New InvalidOperationException(msg) End If Dim inputFileInfo As New FileInfo(inputFilePath) Dim inputFileLength As Long = inputFileInfo.Length If inputFileLength > Integer.MaxValue Then Dim msg As String = $"The input file '{inputFilePath}' is too large ({inputFileLength} bytes). " & $"Maximum supported file size is around {Integer.MaxValue} bytes." Throw New IOException(msg) End If Using fsInput As New FileStream(inputFileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.Read, 8192 * 2, FileOptions.None), peReader As New PEReader(fsInput, PEStreamOptions.Default) Dim headers As PEHeaders = Nothing Dim certDirRVA As Integer, certDirSize As Integer ValidatePEHeaderAndCertDir(peReader, headers, certDirRVA, certDirSize) ' Calculate aligned new certificate table size. Dim newCertDirSizeCandidate As Long = certDirSize + dataWithMarkersSize Dim newCertDirSizeAligned As Long = CLng(Math.Ceiling(newCertDirSizeCandidate / PeHeaderAlignment)) * PeHeaderAlignment If (inputFileLength - certDirSize) + newCertDirSizeAligned > Integer.MaxValue Then Dim msg As String = $"The required total size to create the output file ({newCertDirSizeAligned} bytes) " & "exceeds the practical limit for the Portable Executable." Throw New InvalidOperationException(msg) End If If throwIfInvalidCertSize AndAlso (newCertDirSizeAligned > MaxCertTableSize + PeHeaderAlignment) Then Dim msg As String = $"The size for the new certificate table ({newCertDirSizeAligned} bytes) " & $"exceeds the maximum allowed certificate table size ({MaxCertTableSize} + {PeHeaderAlignment} bytes), " & "which would invalidate the digital signature." Throw New InvalidOperationException(msg) End If Dim totalBytesLengthToAdd As Long = newCertDirSizeAligned - certDirSize Dim paddingLength As Integer = CInt(totalBytesLengthToAdd - dataWithMarkersSize) ' Create the blob meta structure. Dim meta As New CertBlobMeta With { .BlobSize = CInt(blobStream.Length), .PaddingLength = paddingLength } Dim metaBytes As Byte() = MarshalExtensions.ConvertToBytes(meta) ' Write changes to output file. Using fsOutput As New FileStream(outputFilePath, If(overwriteOutputFile, FileMode.Create, FileMode.CreateNew), FileAccess.Write, FileShare.Read, bufferSize:=8192 * 2, FileOptions.None) Dim writeBufferSize As Integer = 8192 * 2 Dim writeBuffer(writeBufferSize - 1) As Byte ' Write head (0 to certDirRVA-1) fsInput.Position = 0 StreamExtensions.CopyExactTo(fsInput, fsOutput, certDirRVA) ' Write original certificate table. fsInput.Position = certDirRVA StreamExtensions.CopyExactTo(fsInput, fsOutput, certDirSize) ' Append markerBegin + metaBytes + blobStream + markerEnd + padding (if required to align). fsOutput.Write(markerBegin, 0, markerBegin.Length) fsOutput.Write(metaBytes, 0, metaStructSize) StreamExtensions.CopyExactTo(blobStream, fsOutput, CInt(blobStream.Length)) fsOutput.Write(markerEnd, 0, markerEnd.Length) If paddingLength > 0 Then fsOutput.Write(New Byte(paddingLength - 1) {}, 0, paddingLength) End If ' Copy any original remainder bytes (tail). Dim tailStart As Integer = certDirRVA + certDirSize If tailStart < fsInput.Length Then fsInput.Position = tailStart Dim remainingTail As Integer = CInt(fsInput.Length - tailStart) StreamExtensions.CopyExactTo(fsInput, fsOutput, remainingTail) End If UpdateCertificateTableLengths(fsInput, fsOutput, headers, certDirRVA, CUInt(certDirSize + totalBytesLengthToAdd)) End Using ' fsOutput End Using ' fsInput, peReader End Sub ''' <summary> ''' Retrieves all the data blobs —that are enclosed between the specified <paramref name="markerBegin"/> and <paramref name="markerEnd"/> markers— ''' from the Certificate Table data-directory entry in the Portable Executable (PE) header of the given file. ''' <para></para> ''' These blobs must have been previously added with the <see cref="AppendBlobToPECertificateTable"/> function. ''' </summary> ''' ''' <param name="filePath"> ''' Path to the input —digitally signed— Portable Executable (PE) file ''' from which to extract data blobs (e.g., "C:\Windows\explorer.exe"). ''' </param> ''' ''' <param name="markerBegin"> ''' Optional. A byte sequence used to delimit the beginning of a data blob within the Certificate Table content. ''' <para></para> ''' Cannot be null or empty. Default value is "<c>#CERT_BLOB_BEGIN#</c>" in UTF-8 encoding bytes. ''' <para></para> ''' This value must be the same used when calling <see cref="AppendBlobToPECertificateTable"/> function. ''' </param> ''' ''' <param name="markerEnd"> ''' Optional. A byte sequence used to delimit the end of a data blob within the Certificate Table content. ''' <para></para> ''' Cannot be null or empty. Default value is "<c>#CERT_BLOB_END#</c>" in UTF-8 encoding bytes. ''' <para></para> ''' This value must be the same used when calling <see cref="AppendBlobToPECertificateTable"/> function. ''' </param> ''' ''' <returns> ''' An <see cref="ImmutableArray"/> of <see cref="ArraySegment(Of Byte)"/> representing each blob found. ''' </returns> <DebuggerStepThrough> Public Shared Function GetBlobsFromPECertificateTable(filePath As String, Optional markerBegin As Byte() = Nothing, Optional markerEnd As Byte() = Nothing) As ImmutableArray(Of ArraySegment(Of Byte)) ValidateCommonParameters((NameOf(filePath), filePath), (NameOf(markerBegin), markerBegin), (NameOf(markerEnd), markerEnd)) Dim metaStructSize As Integer = Marshal.SizeOf(GetType(CertBlobMeta)) Dim blobs As New Collection(Of ArraySegment (Of Byte)) Using fs As New FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize:=8192 * 2, FileOptions.SequentialScan), peReader As New PEReader(fs, PEStreamOptions.LeaveOpen) Dim headers As PEHeaders = Nothing Dim certDirRVA As Integer, certDirSize As Integer ValidatePEHeaderAndCertDir(peReader, headers, certDirRVA, certDirSize) ' Read the entire certificate table into memory. ' Note: This assumes the system has enough RAM for large tables up to ~2GB. fs.Position = certDirRVA Dim certBytes As Byte() = StreamExtensions.ReadExact(fs, certDirSize) Dim searchIndex As Integer ' Main loop to locate all blob segments enclosed by the markers. While searchIndex < certBytes.Length ' Locate the start marker. Dim idx As Integer = Array.IndexOf(certBytes, markerBegin(0), searchIndex) ' Ensure there's room for full marker and meta. If (idx = -1) OrElse (idx + markerBegin.Length + metaStructSize) >= certBytes.Length Then Exit While End If ' Verify full start marker match. Dim matchStart As Boolean = True For j As Integer = 1 To markerBegin.Length - 1 If certBytes(idx + j) <> markerBegin(j) Then matchStart = False Exit For End If Next If Not matchStart Then searchIndex = idx + 1 Continue While End If ' Read CertBlobMeta structure bytes. Dim metaStart As Integer = idx + markerBegin.Length Dim metaBytes(metaStructSize - 1) As Byte Array.Copy(certBytes, metaStart, metaBytes, 0, metaStructSize) Dim meta As CertBlobMeta = MarshalExtensions.ConvertToStructure(Of CertBlobMeta)(metaBytes) Dim blobStart As Integer = metaStart + metaStructSize Dim blobSize As Integer = meta.BlobSize ' Add the actual blob (skip padding). blobs.Add(New ArraySegment(Of Byte)(certBytes, blobStart, blobSize)) ' Move search index past the end marker. searchIndex = blobStart + blobSize + markerEnd.Length + meta.PaddingLength End While End Using Return blobs.ToImmutableArray() End Function ''' <summary> ''' Removes a specific blob —that is enclosed between the specified <paramref name="markerBegin"/> and <paramref name="markerEnd"/> markers— ''' from the Certificate Table data-directory entry in the Portable Executable (PE) header of the given file. ''' <para></para> ''' The blob must have been previously added with the <see cref="AppendBlobToPECertificateTable"/> function. ''' </summary> ''' ''' <param name="inputFilePath"> ''' Path to the input —digitally signed— Portable Executable (PE) file (e.g., "C:\Windows\explorer.exe") ''' from which the blob will be removed. ''' </param> ''' ''' <param name="outputFilePath"> ''' Path to the output file that will be written with the modified Certificate Table. ''' <para></para> ''' Cannot be the same as <paramref name="inputFilePath"/>. ''' </param> ''' ''' <param name="blobIndex"> ''' Zero-based index of the blob to remove from the Certificate Table. ''' </param> ''' ''' <param name="markerBegin"> ''' Optional. A byte sequence used to delimit the beginning of a data blob within the Certificate Table content. ''' <para></para> ''' Cannot be null or empty. Default value is "<c>#CERT_BLOB_BEGIN#</c>" in UTF-8 encoding bytes. ''' <para></para> ''' This value must be the same used when calling <see cref="AppendBlobToPECertificateTable"/> function. ''' </param> ''' ''' <param name="markerEnd"> ''' Optional. A byte sequence used to delimit the end of a data blob within the Certificate Table content. ''' <para></para> ''' Cannot be null or empty. Default value is "<c>#CERT_BLOB_END#</c>" in UTF-8 encoding bytes. ''' <para></para> ''' This value must be the same used when calling <see cref="AppendBlobToPECertificateTable"/> function. ''' </param> ''' ''' <param name="overwriteOutputFile"> ''' If <see langword="False"/> and the output file already exists, the method throws an <see cref="IOException"/>. ''' <para></para> ''' If <see langword="True"/>, any existing output file will be overwritten. ''' <para></para> ''' Default value is <see langword="False"/>. ''' </param> <DebuggerStepThrough> Public Shared Sub RemoveBlobFromPECertificateTable(inputFilePath As String, outputFilePath As String, blobIndex As Integer, Optional markerBegin As Byte() = Nothing, Optional markerEnd As Byte() = Nothing, Optional overwriteOutputFile As Boolean = False) ' The rest of parameters are validated in the following call to GetBlobsFromPECertificateTable function. ValidateCommonParameters((NameOf(outputFilePath), outputFilePath), (NameOf(blobIndex), blobIndex), (NameOf(overwriteOutputFile), overwriteOutputFile)) Dim blobs As ImmutableArray(Of ArraySegment(Of Byte)) = GetBlobsFromPECertificateTable(inputFilePath, markerBegin, markerEnd) If blobIndex >= blobs.Length Then Dim msg As String = "Blob index was out of range. Must be less than the length of existing blobs." Throw New ArgumentOutOfRangeException(NameOf(blobIndex), msg) End If Using fsInput As New FileStream(inputFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize:=8192 * 2, FileOptions.SequentialScan), peReader As New PEReader(fsInput, PEStreamOptions.LeaveOpen) Dim headers As PEHeaders = Nothing Dim certDirRVA As Integer, certDirSize As Integer ValidatePEHeaderAndCertDir(peReader, headers, certDirRVA, certDirSize) ' Read CertBlobMeta structure Dim metaStructSize As Integer = Marshal.SizeOf(GetType(CertBlobMeta)) Dim metaStart As Integer = blobs(blobIndex).Offset - metaStructSize - markerBegin.Length Dim metaBytes(metaStructSize - 1) As Byte fsInput.Position = certDirRVA + metaStart + markerBegin.Length fsInput.Read(metaBytes, 0, metaBytes.Length) Dim meta As CertBlobMeta = MarshalExtensions.ConvertToStructure(Of CertBlobMeta)(metaBytes) ' Compute region to remove: markerBegin + meta + blob + markerEnd + padding (if any) Dim removeStart As Integer = metaStart Dim removeLen As Integer = markerBegin.Length + metaStructSize + meta.BlobSize + markerEnd.Length + meta.PaddingLength ' Safety checks for corrupted meta or inconsistent Certificate Table. If removeStart < 0 Then Dim msg As String = "Computed removal region start is before the beginning of the Certificate Table." Throw New InvalidOperationException(msg) End If If (removeStart + removeLen) > certDirSize Then Dim msg As String = "Computed removal region extends beyond the Certificate Table." Throw New InvalidOperationException(msg) End If ' Write changes to output file. Using fsOutput As New FileStream(outputFilePath, If(overwriteOutputFile, FileMode.Create, FileMode.CreateNew), FileAccess.Write, FileShare.Read, bufferSize:=8192 * 2, FileOptions.None) ' Write head (0 to certDirRVA-1) fsInput.Position = 0 StreamExtensions.CopyExactTo(fsInput, fsOutput, certDirRVA) ' Write new certificate table. fsInput.Position = certDirRVA StreamExtensions.CopyExactTo(fsInput, fsOutput, removeStart) fsInput.Position = certDirRVA + removeStart + removeLen Dim remain As Integer = certDirSize - (removeStart + removeLen) If remain > 0 Then StreamExtensions.CopyExactTo(fsInput, fsOutput, remain) End If ' Copy any original remainder bytes (tail). Dim tailStart As Long = certDirRVA + certDirSize If tailStart < fsInput.Length Then fsInput.Position = tailStart StreamExtensions.CopyExactTo(fsInput, fsOutput, CInt(fsInput.Length - tailStart)) End If UpdateCertificateTableLengths(fsInput, fsOutput, headers, certDirRVA, CUInt(certDirSize - removeLen)) End Using End Using End Sub ''' <summary> ''' Removes all blobs —that were enclosed between the specified <paramref name="markerBegin"/> and <paramref name="markerEnd"/> markers— ''' from the Certificate Table data-directory entry in the Portable Executable (PE) header of the given file. ''' <para></para> ''' The blob(s) must have been previously added with the <see cref="AppendBlobToPECertificateTable"/> function. ''' </summary> ''' ''' <param name="inputFilePath"> ''' Path to the input —digitally signed— Portable Executable (PE) file (e.g., "C:\Windows\explorer.exe") ''' from which the blobs will be removed. ''' </param> ''' ''' <param name="outputFilePath"> ''' Path to the output file that will be written with the modified Certificate Table. ''' <para></para> ''' Cannot be the same as <paramref name="inputFilePath"/>. ''' </param> ''' ''' <param name="markerBegin"> ''' Optional. A byte sequence used to delimit the beginning of a data blob within the Certificate Table content. ''' <para></para> ''' Cannot be null or empty. Default value is "<c>#CERT_BLOB_BEGIN#</c>" in UTF-8 encoding bytes. ''' <para></para> ''' This value must be the same used when calling <see cref="AppendBlobToPECertificateTable"/> function. ''' </param> ''' ''' <param name="markerEnd"> ''' Optional. A byte sequence used to delimit the end of a data blob within the Certificate Table content. ''' <para></para> ''' Cannot be null or empty. Default value is "<c>#CERT_BLOB_END#</c>" in UTF-8 encoding bytes. ''' <para></para> ''' This value must be the same used when calling <see cref="AppendBlobToPECertificateTable"/> function. ''' </param> ''' ''' <param name="overwriteOutputFile"> ''' If <see langword="False"/> and the output file already exists, the method throws an <see cref="IOException"/>. ''' <para></para> ''' If <see langword="True"/>, any existing output file will be overwritten. ''' <para></para> ''' Default value is <see langword="False"/>. ''' </param> <DebuggerStepThrough> Public Shared Sub RemoveBlobsFromPECertificateTable(inputFilePath As String, outputFilePath As String, Optional markerBegin As Byte() = Nothing, Optional markerEnd As Byte() = Nothing, Optional overwriteOutputFile As Boolean = False) ValidateCommonParameters((NameOf(inputFilePath), inputFilePath), (NameOf(outputFilePath), outputFilePath), (NameOf(markerBegin), markerBegin), (NameOf(markerEnd), markerEnd), (NameOf(overwriteOutputFile), overwriteOutputFile)) Dim metaStructSize As Integer = Marshal.SizeOf(GetType(CertBlobMeta)) Dim removalRanges As New List(Of Tuple(Of Integer, Integer))() Using fsInput As New FileStream(inputFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize:=8192 * 2, FileOptions.SequentialScan), peReader As New PEReader(fsInput, PEStreamOptions.LeaveOpen) Dim headers As PEHeaders = Nothing Dim certDirRVA As Integer, certDirSize As Integer ValidatePEHeaderAndCertDir(peReader, headers, certDirRVA, certDirSize) fsInput.Position = certDirRVA Dim certBytes As Byte() = StreamExtensions.ReadExact(fsInput, certDirSize) Dim searchIndex As Integer While searchIndex < certBytes.Length Dim idx As Integer = Array.IndexOf(certBytes, markerBegin(0), searchIndex) ' Ensure there's room for full marker and meta. If (idx = -1) OrElse (idx + markerBegin.Length + metaStructSize) >= certBytes.Length Then Exit While End If ' Verify full start marker match. Dim matchStart As Boolean = True For j As Integer = 1 To markerBegin.Length - 1 If certBytes(idx + j) <> markerBegin(j) Then matchStart = False Exit For End If Next If Not matchStart Then searchIndex = idx + 1 Continue While End If ' Read CertBlobMeta structure bytes. Dim metaStart As Integer = idx + markerBegin.Length Dim metaBytes(metaStructSize - 1) As Byte Array.Copy(certBytes, metaStart, metaBytes, 0, metaStructSize) Dim meta As CertBlobMeta = MarshalExtensions.ConvertToStructure(Of CertBlobMeta)(metaBytes) ' Compute region to remove: markerBegin + meta + blob + markerEnd + padding (if any) Dim removeStart As Integer = idx Dim removeLen As Integer = markerBegin.Length + metaStructSize + meta.BlobSize + markerEnd.Length + meta.PaddingLength ' Safety checks for corrupted meta or inconsistent Certificate Table. If removeStart < 0 Then Dim msg As String = "Computed removal region start is before the beginning of the Certificate Table." Throw New InvalidOperationException(msg) End If If (removeStart + removeLen) > certDirSize Then Dim msg As String = "Computed removal region extends beyond the Certificate Table." Throw New InvalidOperationException(msg) End If removalRanges.Add(Tuple.Create(removeStart, removeLen)) ' Advance searchIndex past the removed region. searchIndex = removeStart + removeLen End While ' If nothing to remove -> copy input to output unchanged (but still produce output file). If removalRanges.Count = 0 Then Using fsOut As New FileStream(outputFilePath, If(overwriteOutputFile, FileMode.Create, FileMode.CreateNew), FileAccess.Write, FileShare.Read, bufferSize:=8192 * 2, FileOptions.None) fsInput.Position = 0 fsInput.CopyTo(fsOut) ' StreamExtensions.CopyExactTo(fsInput, fsOut, CInt(fsInput.Length)) End Using Exit Sub End If ' Total removed size. Dim totalRemoved As Integer = removalRanges.Sum(Function(t) t.Item2) ' Write changes to output file. Using fsOutput As New FileStream(outputFilePath, If(overwriteOutputFile, FileMode.Create, FileMode.CreateNew), FileAccess.Write, FileShare.Read, bufferSize:=8192 * 2, FileOptions.None) ' Write head (0 to certDirRVA-1) fsInput.Position = 0 StreamExtensions.CopyExactTo(fsInput, fsOutput, certDirRVA) ' Write filtered certificate table segments. Dim prevEnd As Integer = 0 For Each r As Tuple(Of Integer, Integer) In removalRanges Dim segStart As Integer = r.Item1 Dim segLen As Integer = segStart - prevEnd If segLen > 0 Then ' Copy segment (prevEnd to segStart-1) fsInput.Position = certDirRVA + prevEnd StreamExtensions.CopyExactTo(fsInput, fsOutput, segLen) End If ' Skip the removed region by moving prevEnd. prevEnd = segStart + r.Item2 Next ' Write remaining certificate bytes after last removal. If prevEnd < certDirSize Then Dim lastLen As Integer = certDirSize - prevEnd fsInput.Position = certDirRVA + prevEnd StreamExtensions.CopyExactTo(fsInput, fsOutput, lastLen) End If ' Copy any original remainder bytes (tail). Dim tailStart As Long = certDirRVA + certDirSize If tailStart < fsInput.Length Then fsInput.Position = tailStart StreamExtensions.CopyExactTo(fsInput, fsOutput, CInt(fsInput.Length - tailStart)) End If UpdateCertificateTableLengths(fsInput, fsOutput, headers, certDirRVA, CUInt(certDirSize - totalRemoved)) End Using End Using End Sub End Class
El código continúa aquí abajo 👇🙂
|
|
« Última modificación: Hoy a las 13:56 por Eleкtro »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.959
|
Clase PortableExecutableUtil (2ª PARTE): Partial Public Class PortableExecutableUtil ''' <summary> ''' Represents metadata for a blob stored in a Portable Executable (PE) Certificate Table data-directory entry ''' that was added with <see cref="AppendBlobToPECertificateTable"/> function. ''' </summary> <StructLayout(LayoutKind.Sequential, Pack:=1)> Private Structure CertBlobMeta ''' <summary> ''' The size of the certificate blob, in bytes, excluding markers and padding. ''' </summary> Friend BlobSize As Integer ''' <summary> ''' The padding length added after the blob to align the Certificate Table. ''' </summary> Friend PaddingLength As Integer End Structure ''' <summary> ''' Determines whether the given file is a valid Portable Executable (PE) file. ''' </summary> ''' ''' <param name="filePath"> ''' Path to the file to check (e.g., "C:\Windows\explorer.exe"). ''' </param> ''' ''' <returns> ''' <see langword="True"/> if the file is a valid Portable Executable (PE) file; ''' otherwise, <see langword="False"/>. ''' </returns> <DebuggerStepThrough> Public Shared Function FileIsPortableExecutable(filePath As String) As Boolean ValidateCommonParameters((NameOf(filePath), filePath)) Using fs As New FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 8192 * 2, FileOptions.None) Try Using peReader As New PEReader(fs) Return True End Using Catch ex As BadImageFormatException Return False End Try End Using End Function ''' <summary> ''' Determines whether the Portable Executable (PE) headers of the given file contains ''' a Certificate Table data-directory entry that is not empty, which may or may not contain a digital signature. ''' <para></para> ''' Note that this function checks only for the presence of a certificate table in the file. ''' It does <b>not</b> validate whether the file is actually digitally signed, ''' therefore it does not perform any form of cryptographic validation on a certificate. ''' <para></para> ''' Essentially, it only tells you: "This file has a Certificate Table data-directory entry that is not empty". ''' </summary> ''' ''' <param name="filePath"> ''' Path to the Portable Executable (PE) file to check (e.g., "C:\Windows\explorer.exe"). ''' </param> ''' ''' <returns> ''' <see langword="True"/> if the PE headers of the given file contains a certificate table and is not empty; ''' otherwise, <see langword="False"/>. ''' </returns> <DebuggerStepThrough> Public Shared Function FileHasCertificateTable(filePath As String) As Boolean ValidateCommonParameters((NameOf(filePath), filePath)) Using fs As New FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 8192 * 2, FileOptions.None), peReader As New PEReader(fs) Dim headers As PEHeaders = peReader.PEHeaders Dim certDir As DirectoryEntry? = headers?.PEHeader?.CertificateTableDirectory Return certDir.HasValue AndAlso certDir.Value.RelativeVirtualAddress <> 0 AndAlso certDir.Value.Size <> 0 End Using End Function ''' <summary> ''' Determines whether the Portable Executable (PE) headers of the given file contains ''' a valid certificate, indicating that the file is digitally signed. ''' <para></para> ''' Note that this function checks only for the presence of a valid certificate in the file. ''' It does <b>not</b> validate the certificate's trust chain, expiration, revocation, or any other form of validation. ''' <para></para> ''' Essentially, it only tells you: "This file has a valid certificate that can be read and parsed" ''' without performing any additional validation. ''' </summary> ''' ''' <param name="filePath"> ''' Path to the Portable Executable (PE) file to check (e.g., "C:\Windows\explorer.exe"). ''' </param> ''' ''' <returns> ''' <see langword="True"/> if the Portable Executable (PE) headers of the given file contains a valid certificate; ''' otherwise, <see langword="False"/>. ''' </returns> <DebuggerStepThrough> Public Shared Function FileHasCertificate(filePath As String) As Boolean ValidateCommonParameters((NameOf(filePath), filePath)) Try Using cert As X509Certificate = X509Certificate.CreateFromSignedFile(filePath) Return True End Using Catch ex As CryptographicException Return False End Try End Function ''' <summary> ''' Validates the state of common parameters shared by the Portable Executable functions. ''' </summary> ''' ''' <param name="parameters"> ''' A variable-length array of tuples representing the parameters to validate. ''' <para></para> ''' Each tuple is defined as follows: ''' <list type="bullet"> ''' <item><description><b>Name</b> (<see cref="String"/>) - The name of the parameter.</description></item> ''' <item><description><b>Value</b> (<see cref="Object"/>) - The value of the parameter.</description></item> ''' </list> ''' </param> <DebuggerStepThrough> Private Shared Sub ValidateCommonParameters(ParamArray parameters As (Name As String, Value As Object)()) If parameters.Length = 0 Then Exit Sub End If Dim paramsDict As New Dictionary(Of String, Object)(StringComparer. OrdinalIgnoreCase) For Each param As (Name As String, Value As Object) In parameters paramsDict.Add(param.Name, param.Value) Next Dim validatedParamsCount As Short Dim inputFilePath As String = Nothing Dim inputFilePathObj As Object = Nothing If paramsDict.TryGetValue("inputFilePath", inputFilePathObj) OrElse paramsDict.TryGetValue("filePath", inputFilePathObj) Then inputFilePath = DirectCast(inputFilePathObj, String) If Not File. Exists(inputFilePath ) Then Dim msg As String = $"The input file '{inputFilePath}' does not exist." Throw New FileNotFoundException(msg, fileName:=inputFilePath) End If validatedParamsCount += 1S End If Dim outputFilePath As String = Nothing Dim outputFilePathObj As Object = Nothing If paramsDict.TryGetValue("outputFilePath", outputFilePathObj) Then outputFilePath = DirectCast(outputFilePathObj, String) If String.IsNullOrEmpty(outputFilePath) Then Throw New ArgumentNullException(paramName:=NameOf(outputFilePath)) End If If outputFilePath.Equals(inputFilePath, StringComparison.OrdinalIgnoreCase) Then Dim msg As String = $"{NameOf(outputFilePath)} cannot be the same as {NameOf(inputFilePath)}." Throw New ArgumentException(msg, paramName:=NameOf(outputFilePath)) End If validatedParamsCount += 1S End If Dim overwriteOutputFile As Boolean Dim overwriteOutputFileObj As Object = Nothing If paramsDict.TryGetValue("overwriteOutputFile", overwriteOutputFileObj) Then overwriteOutputFile = DirectCast(overwriteOutputFileObj, Boolean) If Not overwriteOutputFile AndAlso File. Exists(outputFilePath ) Then Dim msg As String = $"Output file '{outputFilePath}' already exists." Throw New IOException(msg) End If validatedParamsCount += 1S End If Dim blob As Byte() Dim blobObj As Object = Nothing If paramsDict.TryGetValue("blob", blobObj) Then blob = DirectCast(blobObj, Byte()) If blob Is Nothing Then Dim msg As String = $"{NameOf(blob)} cannot be null." Throw New ArgumentNullException(paramName:=NameOf(blob), msg) End If If blob.Length = 0 Then Dim msg As String = $"{NameOf(blob)} cannot be empty." Throw New ArgumentException(msg, paramName:=NameOf(blob)) End If validatedParamsCount += 1S End If Dim blobStream As Stream Dim blobStreamObj As Object = Nothing If paramsDict.TryGetValue("blobStream", blobStreamObj) Then blobStream = DirectCast(blobStreamObj, Stream) If blobStream Is Nothing Then Dim msg As String = $"{NameOf(blobStream)} cannot be null." Throw New ArgumentNullException(paramName:=NameOf(blobStream), msg) End If If blobStream.Length = 0 Then Dim msg As String = $"{NameOf(blobStream)} cannot be empty." Throw New ArgumentException(msg, paramName:=NameOf(blobStream)) End If validatedParamsCount += 1S End If Dim blobIndex As Integer Dim blobIndexObj As Object = Nothing If paramsDict.TryGetValue("blobIndex", blobIndexObj) Then blobIndex = DirectCast(blobIndexObj, Integer) If blobIndex < 0 Then Dim msg As String = "Blob index must be equal to or greater than zero." Throw New ArgumentOutOfRangeException(NameOf(blobIndex), msg) End If validatedParamsCount += 1S End If Dim markerBegin As Byte() Dim markerBeginObj As Object = Nothing If paramsDict.TryGetValue("markerBegin", markerBeginObj) Then markerBegin = If(DirectCast(markerBeginObj, Byte()), Encoding.UTF8.GetBytes("#CERT_BLOB_BEGIN#")) If markerBegin.Length = 0 Then Dim msg As String = $"{NameOf(markerBegin)} cannot be empty." Throw New ArgumentException(msg, paramName:=NameOf(markerBegin)) End If validatedParamsCount += 1S End If Dim markerEnd As Byte() Dim markerEndObj As Object = Nothing If paramsDict.TryGetValue("markerEnd", markerEndObj) Then markerEnd = If(DirectCast(markerEndObj, Byte()), Encoding.UTF8.GetBytes("#CERT_BLOB_END#")) If markerEnd.Length = 0 Then Dim msg As String = $"{NameOf(markerEnd)} cannot be empty." Throw New ArgumentException(msg, paramName:=NameOf(markerEnd)) End If validatedParamsCount += 1S End If If validatedParamsCount < parameters.Count Then Dim msg As String = $"Validation logic is missing for {parameters.Count - validatedParamsCount} parameter(s)." Throw New NotSupportedException(msg) End If End Sub ''' <summary> ''' Validates the PE (Portable Executable) header of the specified <see cref="PEReader"/> ''' and ensures that it contains a valid Certificate Table data-directory entry that is not empty. ''' <para></para> ''' If validation passes, the certificate directory RVA and size are returned through the output parameters. ''' </summary> ''' ''' <param name="peReader"> ''' The <see cref="PEReader"/> instance used to read and validate the PE headers. ''' </param> ''' ''' <param name="refPEHeaders"> ''' On success, receives the parsed <see cref="PEHeaders"/> object that describes the PE file. ''' </param> ''' ''' <param name="refCertDirRVA"> ''' On success, receives the Relative Virtual Address (RVA) of the Certificate Table data-directory entry. ''' </param> ''' ''' <param name="refCertDirSize"> ''' On success, receives the size (in bytes) of the Certificate Table data-directory entry. ''' </param> <DebuggerStepThrough> Private Shared Sub ValidatePEHeaderAndCertDir(peReader As PEReader, ByRef refPEHeaders As PEHeaders, ByRef refCertDirRVA As Integer, ByRef refCertDirSize As Integer) Dim peHeader As PEHeader Try refPEHeaders = peReader.PEHeaders peHeader = refPEHeaders.PEHeader Catch ex As BadImageFormatException Dim msg As String = "The input file is not a valid Portable Executable (PE) file." Throw New BadImageFormatException(msg, ex) End Try Dim certDir As DirectoryEntry? = peHeader.CertificateTableDirectory If certDir.HasValue Then refCertDirRVA = certDir.Value.RelativeVirtualAddress refCertDirSize = certDir.Value.Size End If If refCertDirRVA = 0 OrElse refCertDirSize = 0 Then Dim msg As String = $"The input file does not contain a Certificate Table data-directory entry." Throw New InvalidOperationException(msg) End If End Sub ''' <summary> ''' Finds the file offset for the <c>Attribute Certificate Table</c> data-directory entry in the specified <see cref="FileStream"/>. ''' </summary> ''' ''' <param name="fs"> ''' The <see cref="FileStream"/> containing the PE file for which to find the file offset. ''' </param> ''' ''' <param name="headers"> ''' The <see cref="PEHeaders"/> instance that describes the structure of the PE file. ''' </param> ''' ''' <param name="certDirRVA"> ''' The Relative Virtual Address (RVA) of the Certificate Table to match. ''' </param> ''' ''' <returns> ''' The offset (in bytes from the beginning of the <see cref="FileStream"/>) that points to the Certificate Table data-directory entry. ''' </returns> <DebuggerStepperBoundary> Private Shared Function FindCertificateDataDirectoryEntryFileOffset(fs As FileStream, headers As PEHeaders, certDirRVA As Integer) As Integer ' The fixed size, in bytes, for each data-directory entry (IMAGE_DATA_DIRECTORY structure). ' https://learn.microsoft.com/en-us/windows/win32/debug/pe-format#optional-header-data-directories-image-only Const DataDirStructSize As Short = 8 Dim fsPosition As Long = fs.Position Dim optHeaderOffset As Integer = headers.PEHeaderStartOffset Dim optHeaderSize As Short = headers.CoffHeader.SizeOfOptionalHeader Dim dataDirsFileOffset As Integer = optHeaderOffset + optHeaderSize - (headers.PEHeader.NumberOfRvaAndSizes * DataDirStructSize) Dim certDirFileOffset As Integer = -1 For i As Integer = 0 To headers.PEHeader.NumberOfRvaAndSizes - 1 Dim entryOffset As Integer = dataDirsFileOffset + i * DataDirStructSize fs.Position = entryOffset ' Get IMAGE_DATA_DIRECTORY::VirtualAddress (DWORD) field. Dim rvaBytes As Byte() = StreamExtensions.ReadExact(fs, 4) Dim rva As UInteger = BitConverter.ToUInt32(rvaBytes, 0) If rva = CUInt(certDirRVA) Then certDirFileOffset = entryOffset Exit For End If Next If certDirFileOffset = -1 Then Dim msg As String = "Cannot find the Certificate Table data-directory entry." Throw New InvalidOperationException(msg) End If fs.Position = fsPosition Return certDirFileOffset End Function ''' <summary> ''' Updates the <see href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_data_directory">IMAGE_DATA_DIRECTORY::Size</see> ''' and <see href="https://learn.microsoft.com/en-us/windows/win32/api/wintrust/ns-wintrust-win_certificate">WIN_CERTIFICATE::dwLength</see> fields ''' of the Certificate Table data directory in the specified PE file to the given new length. ''' </summary> ''' ''' <param name="fsInput"> ''' The input <see cref="FileStream"/> used to resolve file offsets in the PE file. ''' </param> ''' ''' <param name="fsOutput"> ''' The output <see cref="FileStream"/> where updates will be written. ''' </param> ''' ''' <param name="headers"> ''' The <see cref="PEHeaders"/> of the PE file. ''' </param> ''' ''' <param name="certDirRVA"> ''' The Relative Virtual Address (RVA) of the Certificate Table data-directory entry. ''' </param> ''' ''' <param name="newLength"> ''' The new size to write to both IMAGE_DATA_DIRECTORY::Size and WIN_CERTIFICATE::dwLength fields. ''' </param> <DebuggerStepThrough> Private Shared Sub UpdateCertificateTableLengths(fsInput As FileStream, fsOutput As FileStream, headers As PEHeaders, certDirRVA As Integer, newLength As UInteger) ' Dynamically find the file offset for "Attribute Certificate Table" data-directory. Dim certDirFileOffset As Integer = FindCertificateDataDirectoryEntryFileOffset(fsInput, headers, certDirRVA) ' Update IMAGE_DATA_DIRECTORY::Size (DWORD) field in the Certificate Table data-directory. ' https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_data_directory fsOutput.Position = certDirFileOffset + 4 fsOutput.Write(BitConverter.GetBytes(newLength), 0, 4) ' Update WIN_CERTIFICATE::dwLength (DWORD) field. ' https://learn.microsoft.com/en-us/windows/win32/api/wintrust/ns-wintrust-win_certificate fsOutput.Position = certDirRVA fsOutput.Write(BitConverter.GetBytes(newLength), 0, 4) End Sub End Class
Ejemplos de uso◉ Ejemplo para adjuntar un blob de datos arbitrarios (en este caso solo le adjuntamos el contenido de un archivo de texto plano cualquiera) a un archivo PE. El archivo modificado se escribe en una nueva ubicación. Recordatorio: el archivo PE original que vayamos a modificar, debe contener un certificado digital. Dim inputFilePath As String = "C:\original_executable.exe" Dim outputFilePath As String = "modified_executable.exe" Dim fileToAppend As New FileInfo("C:\My Secret Document.txt") Dim markerBegin As Byte() = Encoding.UTF8.GetBytes("#CERT_BLOB_BEGIN#") Dim markerEnd As Byte() = Encoding.UTF8.GetBytes("#CERT_BLOB_END#") Using blobStream As FileStream = fileToAppend.OpenRead() PortableExecutableUtil.AppendBlobToPECertificateTable(inputFilePath, outputFilePath, blobStream, markerBegin, markerEnd, throwIfInvalidCertSize:=True, overwriteOutputFile:=False) End Using
◉ Ejemplo para obtener todos los blobs de datos que hayan sido adjuntados en un archivo PE, y seguidamente volcar el contenido del primer blob al disco. Dim inputFilePath As String = "modified_executable.exe" Dim markerBegin As Byte() = Encoding.UTF8.GetBytes("#CERT_BLOB_BEGIN#") Dim markerEnd As Byte() = Encoding.UTF8.GetBytes("#CERT_BLOB_END#") Dim extractedBlobs As ImmutableArray(Of ArraySegment(Of Byte)) = PortableExecutableUtil.GetBlobsFromPECertificateTable(inputFilePath, markerBegin, markerEnd) Dim selectedBlob As ArraySegment(Of Byte) = extractedBlobs.First() Dim outputFilePath As String = "Extracted_blob.bin" Using msBlob As New MemoryStream(selectedBlob.Array, selectedBlob.Offset, selectedBlob.Count, writable:=False), fsOutput As New FileStream(outputFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, bufferSize:=8192 * 2, FileOptions.None) msBlob.CopyTo(fsOutput) End Using
◉ Ejemplo para eliminar un blob de datos específico adjuntado en un archivo modificado. El archivo restaurado se escribe en una nueva ubicación. Dim inputFilePath As String = "modified_executable.exe" Dim outputFilePath As String = "restored_executable.exe" Dim blobIndexToRemove As Integer = 0 Dim markerBegin As Byte() = Encoding.UTF8.GetBytes("#CERT_BLOB_BEGIN#") Dim markerEnd As Byte() = Encoding.UTF8.GetBytes("#CERT_BLOB_END#") PortableExecutableUtil.RemoveBlobFromPECertificateTable(inputFilePath, outputFilePath, blobIndexToRemove, markerBegin, markerEnd, overwriteOutputFile:=False)
◉ Ejemplo para eliminar todos los blobs de datos adjuntados en un archivo modificado. El archivo restaurado se escribe en una nueva ubicación. Dim inputFilePath As String = "modified_executable.exe" Dim outputFilePath As String = "restored_executable.exe" Dim markerBegin As Byte() = Encoding.UTF8.GetBytes("#CERT_BLOB_BEGIN#") Dim markerEnd As Byte() = Encoding.UTF8.GetBytes("#CERT_BLOB_END#") PortableExecutableUtil.RemoveBlobsFromPECertificateTable(inputFilePath, outputFilePath, markerBegin, markerEnd, overwriteOutputFile:=False)
Fin de los ejemplos de uso. Como habrán podido comprobar, la forma de uso es sencillísima. Además, me gustaría mencionar que el código ha sido desarrollado siendo consciente de la eficiencia del uso de memoria, especialmente en el método AppendBlobToPECertificateTable. Para probar estos ejemplos pueden usar mismamente el archivo explorer.exe de Windows, que está firmado digitalmente por Microsoft. También quisiera resaltar otras cuestiones relacionadas y más técnicas a tener en cuenta: ◉ El layout de cada bloque de datos adjunto, es el siguiente:  Verde: Datos originales de la tabla de certificado del PE. Rojo: Marcador de inicio y marcador final del bloque de datos adjunto. Azul: Datos de la estructura CertBlobMeta. Rosa: Datos actuales adjuntados. Amarillo: Padding añadido para ajustar el alineamiento de la tabla de certificado. Dicho de otra forma: [MarkerBegin][CertBlobMeta][Blob][MarkerEnd][Padding] ◉ La estructura CertBlobMeta almacena "metadatos" que permiten identificar de manera óptima y eficiente el tamaño del blob y cualquier padding que se haya añadido. Esta estructura puede ampliarse para incluir otros datos que necesites, sin que el resto del código requiera modificaciones (siempre y cuando cada campo tenga un tamaño fijo en bytes). Por ejemplo: <StructLayout(LayoutKind.Sequential, Pack:=1)> Private Structure CertBlobMeta Friend BlobSize As Integer ' 4 bytes Friend PaddingLength As Integer ' 4 bytes Friend CustomShortValue As Short ' 2 bytes <MarshalAs(UnmanagedType.ByValArray, SizeConst:=256)> Friend CustomByteArray As Byte() ' 256 bytes End Structure ' 4 + 4 + 2 + 256 = 266 bytes
◉ El tamaño máximo para una tabla de certificado válida, es de aproximadamente 100 MB. No he encontrado el valor exacto en la SDK de Windows, sin embargo, bajo un proceso de ensayo y error he llegado a la conclusión de que el límite, al menos en Windows 10, es de '102400000 + 8' bytes (97,65438 MiB). Si la tabla supera este tamaño, el sistema operativo no reconocerá el certificado. La firma digital no se invalidará, simplemente no se reconocerá / no se parseará correctamente. Mi código maneja este límite y -opcionalmente- puede lanzar una excepción para evitar exceder dicho límite. ◉ El código permite trabajar con aproximadamente un búfer de 2 GB de tamaño, dependiendo de la memoria disponible en el sistema, y del tamaño actual del archivo PE y de su tabla de certificado. Sin embargo, y como ya he explicado, una tabla de certificado mayor de ~100 MB quedará irreconocible para el sistema operativo, pero si eso no te supone un inconveniente, pues adelante. Por si sirve de algo, he adjuntado archivos pesados de aprox. 1,80 GB a la tabla de certificado, y el ejecutable modificado ha seguido funcionando correctamente:  ◉ Si adjuntamos uno o más bloques de datos a la tabla de certificado de un archivo PE con el método AppendBlobToPECertificateTable, y luego eliminamos todos los bloques adjuntados con el método RemoveBlobFromPECertificateTable / RemoveBlobsFromPECertificateTable, el archivo restaurado será idéntico (byte a byte) al original antes de haberle efectuado ninguna modificación. 👍 ◉ Mientras hacía pruebas, me he topado con software comercial de terceros que parecen hacer sus propias comprobaciones de integridad del archivo ejecutable, por lo que al modificar el PE, dan un error genérico al intentar iniciar el programa. En conclusión, hay que verificar que el archivo ejecutable modificado funcione correctamente, sin asumir nada. Por último, un par de cuestiones a aclarar: ◉ La decisión de haber enfocado la lógica del código en escribir las modificaciones del PE en un nuevo archivo en vez de sobreescribir el archivo actual, ha sido una decisión personal, y no tengo intención de cambiar ese aspecto ya que lo considero una medida de seguridad muy importante. ◉ Los tamaños de los búferes para los FileStream han sido totalmente arbitrarios, se pueden cambiar. Actualmente en mi código de producción los búferes se ajustan de forma dinámica en base a ciertos factores específicos, pero eso no lo puedo mostrar aquí. ◉ En torno a la ejecución reflexiva de código que se abarca en el artículo que compartí de 'DeepInstinct - black hat USA 2016', no es mi intención profundizar en el tema y mostrar ningún ejemplo, pero si a alguien le interesa peudo decirle que en .NET es muy sencillo, siempre y cuando la intención sea ejecutar ensamblados .NET; Basta con realizar una llamada al método System.Reflection.Assembly.Load() para cargar un ensamblado .NET en memoria, y luego simplemente invocar el punto de entrada (entry point) del programa. Un ejemplo rápido: Dim assemblyBytes As Byte() = File. ReadAllBytes("MyAssembly.exe") Dim asm As Assembly = Assembly.Load(assemblyBytes) Dim entry As MethodInfo = asm.EntryPoint If entry.GetParameters().Length = 0 Then entry.Invoke(Nothing, Nothing) Else entry.Invoke(Nothing, New Object() {...ARGUMENTOS DE INVOCACIÓN...}) End If
⚠️Aunque considero haber probado lo suficiente todo el código que he compartido, yo también soy humano y puedo cometer algún que otro error o despiste, así que no me hago responsable de posibles daños causados al intentar modificar un archivo. Hagan siempre una copia de seguridad antes de modificar un archivo. 👍 Y hasta aquí, esto sería todo. 👋
|
|
« Última modificación: Hoy a las 16:38 por Eleкtro »
|
En línea
|
|
|
|
|
Mensajes similares |
|
Asunto |
Iniciado por |
Respuestas |
Vistas |
Último mensaje |
|
|
Librería de Snippets en C/C++
« 1 2 3 4 »
Programación C/C++
|
z3nth10n
|
31
|
28,921
|
2 Agosto 2013, 17:13 pm
por 0xDani
|
|
|
[APORTE] [VBS] Snippets para manipular reglas de bloqueo del firewall de Windows
Scripting
|
Eleкtro
|
1
|
4,669
|
3 Febrero 2014, 20:19 pm
por Eleкtro
|
|
|
Librería de Snippets para Delphi
« 1 2 »
Programación General
|
crack81
|
15
|
24,833
|
25 Marzo 2016, 18:39 pm
por crack81
|
|
|
Una organización en Github para subir, proyectos, snippets y otros?
Sugerencias y dudas sobre el Foro
|
z3nth10n
|
0
|
3,519
|
21 Febrero 2017, 10:47 am
por z3nth10n
|
|
|
índice de la Librería de Snippets para VB.NET !!
.NET (C#, VB.NET, ASP)
|
Eleкtro
|
7
|
7,519
|
4 Julio 2018, 21:35 pm
por Eleкtro
|
|