Quantcast
Channel: Windows SDK Support Team Blog
Viewing all 126 articles
Browse latest View live

Windows Hotfix List for September 2015

$
0
0

Jeff here from the SDK team. It is that time of the month again, here are September’s Hotfixes. Enjoy!

 

 

KB3075623   Configuring registry policy processing causes MUP to ignore Group Policy setting in Windows

KB3078632   Backup software can't take server backups in Windows Server 2008 R2 SP1

KB2877115   Error message when you try to perform a LUN resynchronization in Windows Server 2012 or Windows Server 2008 R2 SP1

KB2921629   Stop Error 0x133 in the Netft.sys driver occurs in a node that is running Windows Server 2012 or Windows Server 2008 R2

KB3012714   Hyper-V storage migration failure and "ERROR_BAD_COMMAND" error in Windows Server 2012 R2 or Windows Server 2012

KB3025091   Shared Hyper-V virtual disk is inaccessible when it's located in Storage Spaces on a Windows Server 2012 R2-based computer

KB3067902   Can't connect to RemoteApps if Terminal Services Easy Print driver freezes in Windows Server 2008 R2

KB3069129   Blank page is displayed when you try to access RemoteApps on a Windows-based RD Web Access server

KB3073062   DPM server takes too long to complete backup tasks in Windows Server 2012 R2

KB3073629   Redirected printers go offline after print spooler is restarted on a Windows Server 2012 R2-based RD Session Host server

KB3073630   Remote Desktop Easy Print runs slowly in Windows Server 2012 R2

KB3076953   Cluster services go offline when there's a connectivity issue in Windows Server 2012 R2 or Windows Server 2012

KB3077665   Stop error 0xD1 when you set the SIO_LOOPBACK_FAST_PATH flag in Windows 8 or Windows Server 2012

KB3078420   0xC2 or 0xD1 Stop error on cluster nodes that are running Windows Server 2012 R2

KB3078584   0x133 or 0x13C Stop error occurs in Windows 8.1 or Windows Server 2012 R2

KB3078627   Offline Files network shares might not be available in Windows 8.1

KB3078630   32-bit applications can't change local Group Policy on 64-bit version of Windows 8.1 or Windows Server 2012 R2

KB3078631   Windows Server Backup fails despite sufficient space on the target volume in Windows Server 2012 R2

KB3078634   Virtual machines don't respond to your operation in SCVMM in Windows Server 2012

KB3080140   User files are available offline when SMB shares don't allow client caching in Windows 7 or Windows Server 2008 R2

KB3080777   Dsamain.exe process crashes when AD LDS instance raises an exception in Windows 8.1 or Windows Server 2012 R2

KB3080778   AD FS does not call OnError when MFA adapter throws an exception in Windows Server 2012 R2

KB3080780   Super user can't access or recover expired content in Windows Server 2012 R2

KB3082808   File filtering and device locking features can't be enabled by using custom UMDF drivers for WPD devices in Windows

KB3083424   "SYNC_E_METADATA_INVALID_OPERATION" error when Work Folders stops syncing in Windows Server 2012 R2

KB3084952   Users can't log on to a Windows Server 2012 R2-based server through remote desktop because of RDSLS database corruption

KB3087856   Non-queued commands are sent to disk controller on a Windows Server 2012 R2-based Hyper-V host server

KB3087873   "0x0000007E" Stop error after you install hotfix 2990941 in Windows 7 SP1 or Windows Server 2008 R2 SP1

/Jeff

Follow us on Twitter, www.twitter.com/WindowsSDK.

 


Virtual Desktop Switching in Windows 10

$
0
0

 

Windows 10 introduces a new concept (for Windows anyway) called Virtual Desktops.  Currently, the guidance for this on MSDN states:

The user can group a collection of windows together to create a virtual desktop. Every window is considered to be part of a virtual desktop. When one virtual desktop is hidden, all of the windows associated with it are also hidden. This enables the user to create multiple working environments and to be able to switch between them. Similarly, when a virtual desktop is selected to be active, the windows associated with that virtual desktop are displayed on the screen.

To support this concept, applications should avoid automatically switching the user from one virtual desktop to another. Only the user should instigate that change. In order to support this, newly created windows should appear on the currently active virtual desktop. In addition, if an application can reuse currently active windows, it should only reuse windows if they are on the currently active virtual desktop. Otherwise, a new window should be created.

That’s good advice as it makes for the best user experience in most cases and as a developer lets you ignore virtual desktops altogether in most simple applications; however, if you have an application or scenario that wants to do something such as always stay on top even when the user changes virtual desktops, what can you do?

IVirtualDesktopManager

To go along with the addition of virtual desktops in Windows 10, a new shell interface was introduced called IVirtualDesktopManager.  It only has three functions, but those allow you to do many things with virtual desktops and your own application.  Attempting to say move a window to another virtual desktop with these functions will not work for windows that your process doesn’t own.  As this isn’t a scenario that should be common or desired behavior for most applications, there’s isn’t a notification that you can subscribe to so that you know that your application window’s virtual desktop is no longer visible or that your application window has been moved to a new virtual desktop.  However, if your window has focus when the user switches to another virtual desktop, you will be told that you’ve lost focus.

IsWindowOnCurrentVirtualDesktop will tell you if your window is on the current virtual desktop.  GetWindowDesktopId will give you the ID of the desktop the specified window is on.  MoveWindowToDesktop will allow you to move a specified window to a specified desktop.

But how do you know what the current desktop ID is if you don’t have any windows on the current desktop?  That one turns out to be pretty simple.  If you create a new window with no parent, it will be placed on the current virtual desktop.

Demonstration

Putting all of the above together, here’s a straightforward C# WinForms app as an example of an always on top window that can move itself between Virtual Desktops (csproj attached at the end):

using System;using System.Runtime.InteropServices;using System.Windows.Forms;namespace VirtualDesktopSwitch
{/// <summary>
    /// Example form/// </summary>public partial class VDExampleWindow : Form{public VDExampleWindow()
        {
            InitializeComponent();
        }private VirtualDesktopManager vdm;private void VDExampleWindow_Load(object sender, EventArgs e)
        {//Create IVirtualDesktopManager on loadvdm = new VirtualDesktopManager();
        }private void label1_Click(object sender, EventArgs e)
        {//Show details on clickMessageBox.Show("Virtual Desktop ID: " + vdm.GetWindowDesktopId(Handle).ToString("X") + Environment.NewLine +"IsCurrentVirtualDesktop: " + vdm.IsWindowOnCurrentVirtualDesktop(Handle).ToString()
                );
        }//Timer tick to check if the window is on the current virtual desktop and change it otherwise
        //A timer does not have to be used, but something has to trigger the check
        //If the window was active before the vd change, it would trigger 
        //the deactivated and lost focus events when the vd changes
        //The timer always gets triggered which makes the example hopefully less confusingprivate void VDCheckTimer_Tick(object sender, EventArgs e)
        {try{if (!vdm.IsWindowOnCurrentVirtualDesktop(Handle))
                {using (NewWindow nw = new NewWindow())
                    {
                        nw.Show(null);
                        vdm.MoveWindowToDesktop(Handle, vdm.GetWindowDesktopId(nw.Handle));
                    }
                }
            }catch{//This will fail due to race conditions as currently written on occassion}
        }/// <summary>
        /// Required designer variable./// </summary>private System.ComponentModel.IContainer components = null;/// <summary>
        /// Clean up any resources being used./// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>protected override void Dispose(bool disposing)
        {if (disposing && (components != null))
            {
                components.Dispose();
            }base.Dispose(disposing);
        }#region Windows Form Designer generated code/// <summary>
        /// Required method for Designer support - do not modify/// the contents of this method with the code editor./// </summary>private void InitializeComponent()
        {this.components = new System.ComponentModel.Container();this.label1 = new System.Windows.Forms.Label();this.VDCheckTimer = new System.Windows.Forms.Timer(this.components);this.SuspendLayout();// 
            // label1
            // this.label1.Dock = System.Windows.Forms.DockStyle.Fill;this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 13.875F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));this.label1.Location = new System.Drawing.Point(0, 0);this.label1.Name = "label1";this.label1.Size = new System.Drawing.Size(1112, 368);this.label1.TabIndex = 0;this.label1.Text = "Example Contents";this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;this.label1.Click += new System.EventHandler(this.label1_Click);// 
            // VDCheckTimer
            // this.VDCheckTimer.Enabled = true;this.VDCheckTimer.Interval = 1000;this.VDCheckTimer.Tick += new System.EventHandler(this.VDCheckTimer_Tick);// 
            // VDExampleWindow
            // this.AutoScaleDimensions = new System.Drawing.SizeF(12F, 25F);this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;this.ClientSize = new System.Drawing.Size(1112, 368);this.Controls.Add(this.label1);this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;this.Name = "VDExampleWindow";this.Text = "VD Example";this.TopMost = true;this.Load += new System.EventHandler(this.VDExampleWindow_Load);this.ResumeLayout(false);

        }

        #endregionprivate System.Windows.Forms.Label label1;private System.Windows.Forms.Timer VDCheckTimer;

        [STAThread]static void Main()
        {Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);Application.Run(new VDExampleWindow());
        }
    }
    [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("a5cd92ff-29be-454c-8d04-d82879fb3f1b")]
    [System.Security.SuppressUnmanagedCodeSecurity]public interface IVirtualDesktopManager{
        [PreserveSig]int IsWindowOnCurrentVirtualDesktop(
            [In] IntPtr TopLevelWindow,
            [Out] out int OnCurrentDesktop
            );
        [PreserveSig]int GetWindowDesktopId(
            [In] IntPtr TopLevelWindow,
            [Out] out Guid CurrentDesktop
            );

        [PreserveSig]int MoveWindowToDesktop(
            [In] IntPtr TopLevelWindow,
            [MarshalAs(UnmanagedType.LPStruct)]
            [In]Guid CurrentDesktop
            );
    }public class NewWindow : Form{
    }
    [ComImport, Guid("aa509086-5ca9-4c25-8f95-589d3c07b48a")]public class CVirtualDesktopManager{

    }
    public class VirtualDesktopManager{public VirtualDesktopManager()
        {
            cmanager = new CVirtualDesktopManager();
            manager = (IVirtualDesktopManager)cmanager;
        }
        ~VirtualDesktopManager()
        {
            manager = null;
            cmanager = null;
        }private CVirtualDesktopManager cmanager = null;private IVirtualDesktopManager manager;public bool IsWindowOnCurrentVirtualDesktop(IntPtr TopLevelWindow)
        {int result;int hr;if ((hr = manager.IsWindowOnCurrentVirtualDesktop(TopLevelWindow, out result)) != 0)
            {Marshal.ThrowExceptionForHR(hr);
            }return result != 0;
        }public Guid GetWindowDesktopId(IntPtr TopLevelWindow)
        {Guid result;int hr;if ((hr = manager.GetWindowDesktopId(TopLevelWindow, out result)) != 0)
            {Marshal.ThrowExceptionForHR(hr);
            }return result;
        }public void MoveWindowToDesktop(IntPtr TopLevelWindow, Guid CurrentDesktop)
        {int hr;if ((hr = manager.MoveWindowToDesktop(TopLevelWindow, CurrentDesktop)) != 0)
            {Marshal.ThrowExceptionForHR(hr);
            }
        }
    }
}

Follow us on Twitter, www.twitter.com/WindowsSDK.

FileSystemWatcher Fencing(Part 2)

$
0
0
 

This post is a follow up to the FileSystemWatcher Follies post.  I received a lot of feedback that it would be useful to highlight what would be appropriate to guide against some of the pitfalls that I mentioned in that post.  I’ll cover several of the issues here over a couple of posts and propose things that could be done to detect that they are there before using the FileSystemWatcher class against them.  Though the code examples will all be in C#, there will be some P/Invoke involved here as not all of this functionality is exposed through .NET Framework classes at this time.

Using Change Journals

If you’ve already determined that your path is local and uses the NTFS or ReFS file system, a great alternative to the FileSystemWatcher is to use change journaling.  Change journals can be complicated, but they also give you very fine grained control over the information that you want.  However, your code must be running as an administrator or system in order to create or delete them, and they do take up some space on disk (the maximum amount that will be taken up can be specified).    Because change journals monitor an entire volume, if you’re designing an application to make optimal use of this functionality for consistent change monitoring, you may want to put the data that you’re consistently monitoring for changes on its own volume.

Other things to keep in mind when using change journals:

  1. Changes for files and directories are not full paths; parent directories are identified by IDs and those directory names can be looked up by OpenFileByID amongst other methods
  2. If BytesToRead is set to zero, it will immediately return with up to one entry; otherwise it will wait until that many bytes are filled in to the buffer or the specified timeout value.  If you want to get immediate notification
  3. It does not work on network file paths.
  4. All of the functionality works through the use of DeviceIOControl; consult the documentation for the structure type and enumeration value for additional details about how to use that value.

Basic Change Journal Wrapper

Below is sample code for a basic change journal class which monitors a volume for changes.  The changes monitored for are specifiable and the types available are included as an enumeration.  The values are hardcoded to only show file creation and delete events.  If the buffer size is set to anything less than 1024, the sample will use zero for BytesToRead to immediately return upon receiving each entry.

using System;using System.Collections.Generic;using System.Text;using Microsoft.Win32.SafeHandles;using System.Runtime.InteropServices;using System.IO;using System.Threading;namespace ChangeJournal
{public class ChangeJournalHandle : SafeHandleMinusOneIsInvalid{

        [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]private static extern IntPtr CreateFileW(
            [MarshalAs(UnmanagedType.LPWStr)]string FileName,int DesiredAccess,FileShare ShareMode,IntPtr SecurityAttributes,int CreationDisposition,int FlagsAndAttributes,IntPtr hTemplateFile
            );

        [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]private static extern int GetVolumeInformationByHandleW(IntPtr hFile,StringBuilder lpVolumeNameBuffer,int nVolumeNameSize,out int lpVolumeSerialNumber,out intlpMaximumComponentLength,out int lpFileSystemFlags,StringBuilder lpFileSystemNameBuffer,int nFileSystemNameSize
);



        [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]private static extern int DeviceIoControl(IntPtr hDevice,int dwIoControlCode,IntPtr lpInBuffer,int nInBufferSize,IntPtr lpOutBuffer,int nOutBufferSize,out int lpBytesReturned,IntPtr lpOverlapped
    );

        [DllImport("kernel32", SetLastError = true)]private static extern bool CloseHandle(IntPtr handle);


        [DllImport("kernel32", SetLastError = true)]private static extern IntPtr OpenFileById(IntPtr hFile,ref FILE_ID_DESCRIPTOR lpFileID,int                 dwDesiredAccess,FileShare dwShareMode,IntPtr lpSecurityAttributes,int dwFlags
);
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]private static extern int GetFinalPathNameByHandleW(IntPtr hFile,StringBuilder lpszFilePath,int cchFilePath,int dwFlags
);
        [StructLayout(LayoutKind.Explicit)]public struct FILE_ID_DESCRIPTOR{ 
            [FieldOffset(0)]public int Size;
            [FieldOffset(4)]public int Type;
            [FieldOffset(8)]public long FileId;
            [FieldOffset(8)]public Guid ObjectId;
            [FieldOffset(8)]public Guid ExtendedFileId; //Use for ReFS; need to use v3 structures or later instead of v2 as done in this sample}public static int CTL_CODE(int DeviceType, int Function, int Method, int Access)
        {return ((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method);
        }protected override bool ReleaseHandle()
        {if(handle != IntPtr.Zero)
            {if(createdJournal == true)
                {
                    TryDeleteCurrentJournal();
                }
                StopListening(10);//this may cause a delayreturn CloseHandle(handle);
            }return false;
        }public const int FILE_DEVICE_FILE_SYSTEM = 0x00000009;public const int METHOD_BUFFERED = 0;public const int METHOD_IN_DIRECT = 1;public const int METHOD_OUT_DIRECT = 2;public const int METHOD_NEITHER = 3;public const int FILE_ANY_ACCESS = 0;public static int FSCTL_READ_USN_JOURNAL = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 46, METHOD_NEITHER, FILE_ANY_ACCESS);public static int FSCTL_ENUM_USN_DATA = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 44, METHOD_NEITHER, FILE_ANY_ACCESS);public static int FSCTL_CREATE_USN_JOURNAL = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 57, METHOD_NEITHER, FILE_ANY_ACCESS);public static int FSCTL_READ_FILE_USN_DATA = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 58, METHOD_NEITHER, FILE_ANY_ACCESS);public static int FSCTL_QUERY_USN_JOURNAL = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 61, METHOD_BUFFERED, FILE_ANY_ACCESS);public static int FSCTL_DELETE_USN_JOURNAL = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 62, METHOD_BUFFERED, FILE_ANY_ACCESS);public static int FSCTL_WRITE_USN_REASON = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 180, METHOD_BUFFERED, FILE_ANY_ACCESS);public static int FSCTL_USN_TRACK_MODIFIED_RANGES = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 189, METHOD_BUFFERED, FILE_ANY_ACCESS);

        [StructLayout(LayoutKind.Sequential)]public struct USN{public long Usn;
        }

        [StructLayout(LayoutKind.Sequential)]public struct MFT_ENUM_DATA_V0{public USN Low;public USN High;
        }

        [StructLayout(LayoutKind.Sequential)]public struct MFT_ENUM_DATA_V1{public long StartFileReferenceNumber;public USN Low;public USN High;public short MinMajorVersion;public short MaxMajorVersion;
        }


        [StructLayout(LayoutKind.Sequential)]public struct CREATE_USN_JOURNAL_DATA{public long MaximumSize;public long AllocationDelta;
        }


        [StructLayout(LayoutKind.Sequential)]public struct READ_USN_JOURNAL_DATA_V0{public USN StartUsn;public int ReasonMask;public int ReturnOnlyOnClose;public long Timeout;public long BytesToWaitFor;public long UsnJournalId;
        }


        [StructLayout(LayoutKind.Sequential)]public struct READ_USN_JOURNAL_DATA_V1{public USN StartUsn;public int ReasonMask;public int ReturnOnlyOnClose;public long Timeout;public long BytesToWaitFor;public long UsnJournalId;public short MinMajorVersion;public short MaxMajorVersion;
        }


        [StructLayout(LayoutKind.Sequential)]public struct USN_TRACK_MODIFIED_RANGES{public int Flags;public int Unused;public long ChunkSize;public long FileSizeThreshold;
        }

        [StructLayout(LayoutKind.Sequential)]public struct USN_RANGE_TRACK_OUTPUT{public USN Usn;
        }public const int FLAG_USN_TRACK_MODIFIED_RANGES_ENABLE = 0x00000001;public class UsnRecordV2WithName{public USN_RECORD_V2 Record { get; set; }public string Filename { get; set; }
        }

        [StructLayout(LayoutKind.Sequential)]public struct USN_RECORD_V2{public int RecordLength;public short MajorVersion;public short MinorVersion;public long FileReferenceNumber;public long ParentFileReferenceNumber;USN Usn;public long TimeStamp;public int Reason;public int SourceInfo;public int SecurityId;public int FileAttributes;public short FileNameLength;public short FileNameOffset;//WCHAR FileName[1];}

        [StructLayout(LayoutKind.Sequential)]public struct USN_RECORD_V3{public int RecordLength;public short MajorVersion;public short MinorVersion;public Guid FileReferenceNumber;public Guid ParentFileReferenceNumber;USN Usn;public long TimeStamp;public int Reason;public int SourceInfo;public int SecurityId;public int FileAttributes;public short FileNameLength;public short FileNameOffset;//WCHAR FileName[1];}


        [StructLayout(LayoutKind.Sequential)]public struct USN_RECORD_COMMON_HEADER{public int RecordLength;public short MajorVersion;public short MinorVersion;
        }

        [StructLayout(LayoutKind.Sequential)]public struct USN_RECORD_EXTENT{public long Offset;public long Length;
        }

        [StructLayout(LayoutKind.Sequential)]public struct USN_RECORD_V4{public USN_RECORD_COMMON_HEADER Header;public Guid FileReferenceNumber;public Guid ParentFileReferenceNumber;public USN Usn;public int Reason;public int SourceInfo;public int RemainingExtents;public short NumberOfExtents;public short ExtentSize;public USN_RECORD_EXTENT Extents; //Extents[1]}public const int USN_PAGE_SIZE = (0x1000);public const int USN_REASON_DATA_OVERWRITE = (0x00000001);public const int USN_REASON_DATA_EXTEND = (0x00000002);public const int USN_REASON_DATA_TRUNCATION = (0x00000004);public const int USN_REASON_NAMED_DATA_OVERWRITE = (0x00000010);public const int USN_REASON_NAMED_DATA_EXTEND = (0x00000020);public const int USN_REASON_NAMED_DATA_TRUNCATION = (0x00000040);public const int USN_REASON_FILE_CREATE = (0x00000100);public const int USN_REASON_FILE_DELETE = (0x00000200);public const int USN_REASON_EA_CHANGE = (0x00000400);public const int USN_REASON_SECURITY_CHANGE = (0x00000800);public const int USN_REASON_RENAME_OLD_NAME = (0x00001000);public const int USN_REASON_RENAME_NEW_NAME = (0x00002000);public const int USN_REASON_INDEXABLE_CHANGE = (0x00004000);public const int USN_REASON_BASIC_INFO_CHANGE = (0x00008000);public const int USN_REASON_HARD_LINK_CHANGE = (0x00010000);public const int USN_REASON_COMPRESSION_CHANGE = (0x00020000);public const int USN_REASON_ENCRYPTION_CHANGE = (0x00040000);public const int USN_REASON_OBJECT_ID_CHANGE = (0x00080000);public const int USN_REASON_REPARSE_POINT_CHANGE = (0x00100000);public const int USN_REASON_STREAM_CHANGE = (0x00200000);public const int USN_REASON_TRANSACTED_CHANGE = (0x00400000);public const int USN_REASON_INTEGRITY_CHANGE = (0x00800000);public const uint USN_REASON_CLOSE = (0x80000000);

        [Flags]public enum UsnReasonType : int{
            USN_REASON_DATA_OVERWRITE = (0x00000001),
            USN_REASON_DATA_EXTEND = (0x00000002),
            USN_REASON_DATA_TRUNCATION = (0x00000004),
            USN_REASON_NAMED_DATA_OVERWRITE = (0x00000010),
            USN_REASON_NAMED_DATA_EXTEND = (0x00000020),
            USN_REASON_NAMED_DATA_TRUNCATION = (0x00000040),
            USN_REASON_FILE_CREATE = (0x00000100),
            USN_REASON_FILE_DELETE = (0x00000200),
            USN_REASON_EA_CHANGE = (0x00000400),
            USN_REASON_SECURITY_CHANGE = (0x00000800),
            USN_REASON_RENAME_OLD_NAME = (0x00001000),
            USN_REASON_RENAME_NEW_NAME = (0x00002000),
            USN_REASON_INDEXABLE_CHANGE = (0x00004000),
            USN_REASON_BASIC_INFO_CHANGE = (0x00008000),
            USN_REASON_HARD_LINK_CHANGE = (0x00010000),
            USN_REASON_COMPRESSION_CHANGE = (0x00020000),
            USN_REASON_ENCRYPTION_CHANGE = (0x00040000),
            USN_REASON_OBJECT_ID_CHANGE = (0x00080000),
            USN_REASON_REPARSE_POINT_CHANGE = (0x00100000),
            USN_REASON_STREAM_CHANGE = (0x00200000),
            USN_REASON_TRANSACTED_CHANGE = (0x00400000),
            USN_REASON_INTEGRITY_CHANGE = (0x00800000),
            USN_REASON_CLOSE = unchecked((int)(0x80000000))
        }

        [StructLayout(LayoutKind.Sequential)]public struct USN_JOURNAL_DATA_V0{public long UsnJournalID;public USN FirstUsn;public USN NextUsn;public USN LowestValidUsn;public USN MaxUsn;public long MaximumSize;public long AllocationDelta;

        }
        [StructLayout(LayoutKind.Sequential)]public struct USN_JOURNAL_DATA_V1{public long UsnJournalID;public USN FirstUsn;public USN NextUsn;public USN LowestValidUsn;public USN MaxUsn;public long MaximumSize;public long AllocationDelta;public short MinSupportedMajorVersion;public short MaxSupportedMajorVersion;
        }

        [StructLayout(LayoutKind.Sequential)]public struct USN_JOURNAL_DATA_V2{public long UsnJournalID;public USN FirstUsn;public USN NextUsn;public USN LowestValidUsn;public USN MaxUsn;public long MaximumSize;public long AllocationDelta;public short MinSupportedMajorVersion;public short MaxSupportedMajorVersion;public int Flags;public long RangeTrackChunkSize;public long RangeTrackFileSizeThreshold;
        }



        [StructLayout(LayoutKind.Sequential)]public struct DELETE_USN_JOURNAL_DATA{public long UsnJournalID;public int DeleteFlags;
        }public int USN_DELETE_FLAG_DELETE = (0x00000001);public int USN_DELETE_FLAG_NOTIFY = (0x00000002);public int USN_DELETE_VALID_FLAGS = (0x00000003);public UsnReasonType EventTriggerMask
        {get{return (UsnReasonType)rdata.ReasonMask;
            }set{
                rdata.ReasonMask = (int)value;
            }
        }public long Timeout
        {get{return rdata.Timeout;
            }set{
                rdata.Timeout = value;
            }
        }public bool TriggerOnCloseOnly
        {get{return rdata.ReturnOnlyOnClose != 0;
            }set{
                rdata.ReturnOnlyOnClose = value ? 1 : 0;
            }
        }private ReaderWriterLockSlim readBufferLock = new ReaderWriterLockSlim();private int readBufferSize = 8192;//This could hang if there is a long timeout valuepublic int ReadBufferSize
        {get{
                readBufferLock.EnterWriteLock();try{return readBufferSize;
                }finally{
                    readBufferLock.ExitWriteLock();
                }
            }set{
                readBufferLock.EnterWriteLock();try{if (value > 0)
                    {if (readBuffer == IntPtr.Zero)
                        {
                            readBuffer = Marshal.AllocHGlobal(value);
                        }else{
                            readBuffer = Marshal.ReAllocHGlobal(readBuffer, (IntPtr)value);
                        }
                    }
                    readBufferSize = value;

                }
                finally{
                    readBufferLock.ExitWriteLock();
                }
            }
        }public event Action<ChangeJournalHandle, UsnRecordV2WithName> OnChange;public event Action<ChangeJournalHandle, Exception> OnError;private bool shouldRun = false;private Thread thread = null;public ChangeJournalHandle(string path) : base(true)
        {//TODO:Handle taking non-volume pathshandle = CreateFileW(path, unchecked((int)(0x80000000 | 0x40000000)),FileShare.ReadWrite, IntPtr.Zero, 3, 0, IntPtr.Zero);if (IsInvalid)
            {Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }
        }public bool TryCreateJournal(long maxSize = (1024 ^ 2) * 500, long allocationDelta = 8192)
        {CREATE_USN_JOURNAL_DATA data = new CREATE_USN_JOURNAL_DATA();
            data.AllocationDelta = allocationDelta;
            data.MaximumSize = maxSize;int size = Marshal.SizeOf(data);IntPtr buffer = Marshal.AllocHGlobal(size);try{int bufSizeOut;int result = DeviceIoControl(handle, FSCTL_CREATE_USN_JOURNAL, buffer, size, IntPtr.Zero, 0, out bufSizeOut, IntPtr.Zero);if (result == 0)
                {
                    ReportLastError();return false;
                }
                createdJournal = true;return true;
            }finally{Marshal.FreeHGlobal(buffer);
            }
        }public void CreateJournal(long maxSize = (1024 ^ 2) * 500, long allocationDelta = 8192)
        {CREATE_USN_JOURNAL_DATA data = new CREATE_USN_JOURNAL_DATA();
            data.AllocationDelta = allocationDelta;
            data.MaximumSize = maxSize;int size = Marshal.SizeOf(data);IntPtr buffer = Marshal.AllocHGlobal(size);try{int bufSizeOut;int result = DeviceIoControl(handle, FSCTL_CREATE_USN_JOURNAL, buffer, size, IntPtr.Zero, 0, out bufSizeOut, IntPtr.Zero);if (result == 0)
                {Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                }
            }finally{Marshal.FreeHGlobal(buffer);
            }
        }public bool TryDeleteCurrentJournal()
        {USN_JOURNAL_DATA_V0 data = new USN_JOURNAL_DATA_V0();int size = Marshal.SizeOf(data);IntPtr buffer = Marshal.AllocHGlobal(size);try{int outSize;int result = DeviceIoControl(handle, FSCTL_QUERY_USN_JOURNAL, IntPtr.Zero, 0, buffer, size, out outSize, IntPtr.Zero);if (result == 0)
                {
                    ReportLastError();return false;
                }
                data = Marshal.PtrToStructure<USN_JOURNAL_DATA_V0>(buffer);
            }finally{Marshal.FreeHGlobal(buffer);
            }DELETE_USN_JOURNAL_DATA d = new DELETE_USN_JOURNAL_DATA();
            d.UsnJournalID = data.UsnJournalID;
            d.DeleteFlags = 3;
            size = Marshal.SizeOf(d);
            buffer = Marshal.AllocHGlobal(size);try{Marshal.StructureToPtr(d, buffer, false);if (DeviceIoControl(handle, FSCTL_DELETE_USN_JOURNAL, buffer, size, IntPtr.Zero, 0, out size, IntPtr.Zero) == 0)
                {
                    ReportLastError();return false;
                }return true;
            }finally{Marshal.FreeHGlobal(buffer);
            }
        }public bool TryDeleteJournal(long UsnJournalID)
        {//Note that overloads would be needed for different versions of the structureDELETE_USN_JOURNAL_DATA d = new DELETE_USN_JOURNAL_DATA();
            d.UsnJournalID = UsnJournalID;
            d.DeleteFlags = 3;int size = Marshal.SizeOf(d);IntPtr buffer = Marshal.AllocHGlobal(size);try{Marshal.StructureToPtr(d, buffer, false);if (DeviceIoControl(handle, FSCTL_DELETE_USN_JOURNAL, buffer, size, IntPtr.Zero, 0, out size, IntPtr.Zero) == 0)
                {
                    ReportLastError();return false;
                }return true;
            }finally{Marshal.FreeHGlobal(buffer);
            }

        }
        public void DeleteAllJournals()
        {try{while (true)
                {USN_JOURNAL_DATA_V0 data = new USN_JOURNAL_DATA_V0();int size = Marshal.SizeOf(data);IntPtr buffer = Marshal.AllocHGlobal(size);try{int outSize;int result = DeviceIoControl(handle, FSCTL_QUERY_USN_JOURNAL, IntPtr.Zero, 0, buffer, size, out outSize, IntPtr.Zero);if (result == 0)
                        {
                            ReportLastError();break;
                        }
                        data = Marshal.PtrToStructure<USN_JOURNAL_DATA_V0>(buffer);
                    }finally{Marshal.FreeHGlobal(buffer);
                    }DELETE_USN_JOURNAL_DATA d = new DELETE_USN_JOURNAL_DATA();
                    d.UsnJournalID = data.UsnJournalID;
                    d.DeleteFlags = 3;
                    size = Marshal.SizeOf(d);
                    buffer = Marshal.AllocHGlobal(size);try{Marshal.StructureToPtr(d, buffer, false);if (DeviceIoControl(handle, FSCTL_DELETE_USN_JOURNAL, buffer, size, IntPtr.Zero, 0, out size, IntPtr.Zero) == 0)
                        {
                            ReportLastError();break;
                        }
                    }finally{Marshal.FreeHGlobal(buffer);
                    }
                }
            }catch (Exception ex)
            {
                ReportException(ex);
            }
        }public void StartListening()
        {//See https://msdn.microsoft.com/en-us/library/windows/desktop/aa365736(v=vs.85).aspxif (!shouldRun)
            {
                thread = new Thread(ListenProc);
                shouldRun = true;
                thread.Start();
            }
        }public void StopListening(int timeout = int.MaxValue)
        {if (shouldRun)
            {
                shouldRun = false;if (thread != null)
                {if(!thread.Join(timeout))
                    {
                        thread.Abort();
                    }
                    thread = null;
                }
            }
        }public string GetNameForId(long id)
        {try{FILE_ID_DESCRIPTOR fid = new FILE_ID_DESCRIPTOR();
                fid.FileId = id;
                fid.Size = Marshal.SizeOf(fid);IntPtr h = OpenFileById(handle, ref fid, unchecked((int)0x80), FileShare.ReadWrite | FileShare.Delete, IntPtr.Zero, 0);if (h == new IntPtr(-1))
                {Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                }int size = 1024;StringBuilder sb = new StringBuilder(size);if (GetFinalPathNameByHandleW(h, sb, size, 0) == 0)
                {int hr = Marshal.GetHRForLastWin32Error();
                    CloseHandle(h);Marshal.ThrowExceptionForHR(hr);
                }
                CloseHandle(h);return sb.ToString();
            }catch(Exception ex)
            {
                ReportException(ex);return id.ToString("X");
            }

        }
        private READ_USN_JOURNAL_DATA_V0 rdata = new READ_USN_JOURNAL_DATA_V0() { ReasonMask = unchecked((int)0xFFFFFFFF) };private IntPtr readBuffer;private bool createdJournal = false;void ListenProc()
        {try{USN_JOURNAL_DATA_V0 data = new USN_JOURNAL_DATA_V0();int size = Marshal.SizeOf(data);IntPtr buffer = Marshal.AllocHGlobal(size);try{int outSize;int result = DeviceIoControl(handle, FSCTL_QUERY_USN_JOURNAL, IntPtr.Zero, 0, buffer, size, out outSize, IntPtr.Zero);if (result == 0)
                    {if(TryCreateJournal())
                        {
                            result = DeviceIoControl(handle, FSCTL_QUERY_USN_JOURNAL, IntPtr.Zero, 0, buffer, size, out outSize, IntPtr.Zero);
                        }if(result == 0) ReportLastError();
                    }if(result != 0) data = Marshal.PtrToStructure<USN_JOURNAL_DATA_V0>(buffer);
                }finally{Marshal.FreeHGlobal(buffer);
                }
                rdata.UsnJournalId = data.UsnJournalID;
                rdata.StartUsn.Usn = 0;int rsize = Marshal.SizeOf(typeof(USN_RECORD_V2));
                size = Marshal.SizeOf(rdata);
                buffer = Marshal.AllocHGlobal(size);if (readBuffer == IntPtr.Zero)
                {//Allocates the buffer if it's emptyReadBufferSize = ReadBufferSize;
                }int usize = Marshal.SizeOf(typeof(USN));try{List<UsnRecordV2WithName> records = new List<UsnRecordV2WithName>();while (shouldRun)
                    {
                        records.Clear();int outSize;int result;if(readBufferSize >= 1024)
                        {
                            rdata.BytesToWaitFor = readBufferSize;
                        }else{//Returns immediatelyrdata.BytesToWaitFor = 0;
                        }Marshal.StructureToPtr(rdata, buffer, false);

                        readBufferLock.EnterReadLock();
                        try{
                            result = DeviceIoControl(handle, FSCTL_READ_USN_JOURNAL, buffer, size, readBuffer, readBufferSize, out outSize, IntPtr.Zero);if (result != 0 && outSize >= usize)
                            {USN usn = Marshal.PtrToStructure<USN>(readBuffer);
                                rdata.StartUsn = usn;int retbytes = outSize - usize;IntPtr record = IntPtr.Add(readBuffer, usize);while (retbytes > 0)
                                {USN_RECORD_V2 r = Marshal.PtrToStructure<USN_RECORD_V2>(record);UsnRecordV2WithName r2 = new UsnRecordV2WithName();
                                    r2.Record = r;
                                    r2.Filename = Marshal.PtrToStringUni(IntPtr.Add(record, r.FileNameOffset), (r.FileNameLength / 2));
                                    records.Add(r2);
                                    record = IntPtr.Add(record, r.RecordLength);
                                    retbytes -= r.RecordLength;
                                }
                            }else{
                                ReportLastError();
                            }
                        }finally{
                            readBufferLock.ExitReadLock();
                        }foreach (var r in records)
                        {
                            ReportChange(r);
                        }
                    }
                }finally{Marshal.FreeHGlobal(buffer);
                }
            }catch (ThreadAbortException tae)
            {

            }
        }

        void ReportChange(UsnRecordV2WithName record)
        {if (OnChange != null)
            {
                OnChange(this, record);
            }
        }void ReportLastError()
        {
            ReportException(Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()));
        }void ReportException(Exception ex)
        {if (OnError != null)
            {
                OnError(this, ex);
            }
        }private static void Cjh_OnError(ChangeJournalHandle arg1, Exception arg2)
        {Console.WriteLine("Error:/t{0}", arg2.ToString());
        }private static void Cjh_OnChange(ChangeJournalHandle arg1, UsnRecordV2WithName arg2)
        {//Note that it would be typically faster in the long run to build a dictionary 
            //of directory names by IDs and reset it whenever the change journal resets 
            //instead of looking up the directory each time
            //Also, note that if the directory is deleted before OpenFileById is called in GetNameById, it's going to fail with an out of range errorConsole.Write(arg1.GetNameForId(arg2.Record.ParentFileReferenceNumber));Console.Write("\\");Console.Write(arg2.Filename);Console.Write(":\t");Console.WriteLine(((ChangeJournalHandle.UsnReasonType)arg2.Record.Reason).ToString());
        }static void Main(string[] args)
        {string pathToVolumeToMonitor = @"\\?\C:";//This will filter to show only files that are deleted or createdUsnReasonType reasonsToMonitor = UsnReasonType.USN_REASON_FILE_CREATE | UsnReasonType.USN_REASON_FILE_DELETE;using (ChangeJournalHandle cjh = new ChangeJournalHandle(pathToVolumeToMonitor))
            {
                cjh.OnChange += Cjh_OnChange;
                cjh.OnError += Cjh_OnError;
                cjh.EventTriggerMask = reasonsToMonitor;
                cjh.StartListening();Console.ReadLine();
                cjh.StopListening();

                cjh.OnChange -= Cjh_OnChange;
                cjh.OnError -= Cjh_OnError;
            }
        }
    }
}

Sample output:

\\?\C:\Windows\Temp\MSIc9528.LOG:       USN_REASON_FILE_CREATE
\\?\C:\Windows\Temp\MSIc9528.LOG:       USN_REASON_FILE_CREATE, USN_REASON_CLOSE

\\?\C:\Windows\Temp\MSIc9529.LOG:       USN_REASON_FILE_CREATE
\\?\C:\Windows\Temp\MSIc9529.LOG:       USN_REASON_FILE_CREATE, USN_REASON_CLOSE

\\?\C:\Windows\Temp\MSIc952a.LOG:       USN_REASON_FILE_CREATE
\\?\C:\Windows\Temp\MSIc952a.LOG:       USN_REASON_FILE_CREATE, USN_REASON_CLOSE

\\?\C:\Windows\Temp\MSIc952b.LOG:       USN_REASON_FILE_CREATE
\\?\C:\Windows\Temp\MSIc952b.LOG:       USN_REASON_FILE_CREATE, USN_REASON_CLOSE

 

 

 

Follow us on Twitter, www.twitter.com/WindowsSDK.

Windows Hotfixes for October 2015

$
0
0

Jeff here from the Windows SDK team. Here is the list of October 2015 Hotfixes

[Drum roll, please...]

KB3030736   "550 The process cannot access the file" error when you try to download a file in Windows

KB3044546   An updated reservation may disappear on a DHCP failover cluster in Windows Server 2012 or Windows Server 2012 R2

KB3049591   Transparent areas are printed as black when you use a v4 XPS printer driver in Windows

KB3053667   Users can't connect to virtual machines that are running Windows 8.1 or Windows Server 2012 R2 by remote desktop

KB3077354   Computer freezes when WFP leaks nonpaged pool memory in Windows Server 2012 R2 or Windows Server 2012

KB3084093   Child nodes under protected OU are deleted in Windows Server 2012 R2

KB3084426   System becomes unresponsive when file system minifilter drivers are installed in Windows 8 or Windows Server 2012

KB3084787   Event ID 4102 when DFS Replication cloning fails on a Windows Server 2012 R2-based cluster

KB3084953   OOBE crashes when you enter SIM card PIN in Windows 8.1

KB3084956   You can’t log on to a domain-joined computer in Windows 8 or Windows Server 2012

KB3084983   SetOptions or GetOptions method doesn't work for PRINTER_PROPERTY features in Windows

KB3086644   System freezes after you start a backup task for virtual machines in Windows Server 2012 R2

KB3090322   Space doesn't regenerate upon reallocation in Windows Server 2012 R2

KB3090973   Reenlist can't be called when SQL Server receives transaction outcome from MSDTC in Windows Server 2012 R2

KB3091057   Cluster validation fails in the "Validate Simultaneous Failover" test in a Windows Server 2012 R2-based failover cluster

KB3091061   Update to add CSVFS tracing for performance issues during backup operations in Windows Server 2012 R2

KB3091342   Computer crashes after you install update 3000850 in Windows 8.1

KB3091402   Site-to-site VPN goes down when you set a VNet-to-VNet connection in Azure in Windows 8.1 or Windows Server 2012 R2

KB3091403   High CPU usage for 12 seconds on a multiple-network-adapters computer in Windows Server 2012 R2 or Windows Server 2012

KB3092002   Set-Acl cmdlet fails although delegated admins have "Change Permissions" enabled in Windows Server 2012 R2

KB3092003   Page loads repeatedly and authentication fails when users use MFA in Windows Server 2012 R2 AD FS

KB3092005   Group Policy settings are set back to factory settings in GPMC in Windows Server 2012 R2

KB3092006   Subfolders disappear from FSRM console after you rename the root folder in Windows Server 2012 R2 or Windows Server 2012

KB3092695   Licensing report file is corrupted in Windows Server 2012 R2 RDS environments for large report files

KB3093550   All ScriptProperty members are invoked when you run the Add-Member PowerShell command in Windows 8.1

KB3093571   Update to replicate multiple VM groups and VMs that use shared VHDs in Windows Server 2012 R2 or Windows Server 2012

KB3093803   Error 0x800704C9 occurs when you try to copy file to NFS share in Windows 8 or Windows Server 2012

KB3093899   VMs that run on CSVs fail if DCM can't query volumes in Windows Server 2012 R2

KB3093900   0x50 Stop error and users can't access documents on shared folders or home folders in Windows Server 2012 R2

KB3094197   Files aren't fully optimized and a deduplication cache lock contention issue occurs in Windows Server 2012 R2

KB3094199   Application module can't receive correct process status after security update 3045999 is installed in Windows

KB3094202   Directory listing fails when sharing violations occur on Windows Server 2012 R2 or Windows Server 2012-based NFS server

KB3094446   Authentication through proxy fails in Windows Server 2012 or Windows Server 2008 R2 SP1

KB3095308   VMs may not get additional memory although they're set to use Dynamic Memory in Windows Server 2012 R2

KB3095319   You receive an error message when you use GPMC to manage audit policies in Windows 8.1 or Windows Server 2012 R2

KB3095663   VSS_E_PROVIDER_VETO error occurs when you restore a LUN from backup in Windows Server 2012 R2

KB3095711   Update to support LTO-7 tape drives in Windows Server 2012 R2 and Windows Server 2012

KB3095737   Azure Backup takes a long time to back up data with a guest OS that's running Windows Server 2012

Happy patching…

/Jeff

Follow us on Twitter, www.twitter.com/WindowsSDK.

 

Hotfixes for November 2015

$
0
0

Jeff here from the SDK team. Here are the hotfixes for November 2015.

KB3040017   XPS driver is slower than GDI driver to print files in Windows

KB3063109   Virtual machine crashes and WAL consistency is not maintained for Guest clustered VMs in Windows Server 2012 R2

KB3078414   NFS service freezes on a Windows Server 2012 cluster and a client computer can't access NFS share

KB3080141   Cluster service freezes on a Windows Server 2012 R2 or Windows Server 2012-based failover cluster

KB3086918   Original file is lost with new file not being saved in WebDAV folder in Windows 8.1

KB3091411   User connection fails when many connections are made to Windows Server 2012 R2-based RD Connection Broker

KB3092604   Network is corrupted between Guest OS and external network for VMs hosted on Windows 8.1 or Windows Server 2012 R2

KB3092688   UPD profiles corrupted when a network connectivity issue occurs in Windows Server 2012 R2

KB3095113   Update to enable WSUS support for Windows 10 feature upgrades

KB3095682   File Explorer shows thumbnail contents even though files are marked with offline flag in Windows

KB3098841   Application crashes with access violation error in Windows 7 or Windows Server 2008 R2

KB3100460   Video stops playing unexpectedly when another video pauses in the same application in Windows 8 or Windows Server 2012

KB3100474   Can't connect to wireless network when you resume the computer from hibernate mode in Windows

KB3100477   A large file upload or a large repository clone fails on VSO in Windows Server 2012 R2

KB3100527   System becomes unresponsive and crashes on Windows Server 2012 R2-based file servers

KB3100530   Windows backup fails with no sufficient free space on target volume in Windows Server 2012

KB3101217   Client requests take a long time to execute or COM+ application freezes in Windows 7 SP1 or Windows Server 2008 R2 SP1

KB3101694   "0x000000D1" Stop error in Pacer.sys when there's heavy QoS traffic in Windows Server 2012 R2

KB3101705   Schema load failures or SPF failures in Windows Server 2012 R2 in Turkey

KB3101718   Application freezes when you switch the system from DC mode to AC mode in Windows 8.1 or Windows Server 2012 R2

KB3102236   Group membership removal operation fails when this operation is for a deleted user account in Windows Server 2008 R2

KB3102242   Computer crashes or restarts unexpectedly when it's resumed from sleep mode in Windows

KB3102354   Hyper-V generation 2 virtual machines can't start with some pass-through disks in Windows Server 2012 R2

KB3102770   The chkdsk command together with the spotfix option doesn't fix extended volumes corruption in Windows Server 2012 R2

KB3103000   RemoteApp windows disappear and screen flickers when you switch between windows in Windows 8.1 or Windows Server 2012 R2

KB3103616   WMI query doesn't work in Windows Server 2012

KB3105881   Can't access applications when device authentication is enabled in Windows Server 2012 R2-based AD FS server

Happy patching.

/Jeff

Follow us on Twitter, www.twitter.com/WindowsSDK.

Using SHA256 with the SignedXml Class

$
0
0

With the industry moving away from SHA1 including Microsoft (see http://social.technet.microsoft.com/wiki/contents/articles/32288.windows-enforcement-of-authenticode-code-signing-and-timestamping.aspx), many developers should start using SHA2 in their code.  There are resources on the internet that describe how to use SHA256 with SignedXml. This blog is meant to summarize it in one place.

First of all, we need to register a SignatureDescription class that defines the DigestAlgorithm as SHA256.  The .NET Cryptography namespace implements a class called RSAPKCS1SHA1SignatureDescription that supports SHA1.  So we need a similar class called RSAPKCS1SHA256SignatureDescription that supports SHA256.

If your code is based on .NET 4.5 or higher, there is an RSAPKCS1SHA256SignatureDescription class you can register.  You have to reference the System.Deployment assembly in your project.  The full namespace is System.Deployment.Internal.CodeSigning.RSAPKCS1SHA256SignatureDescription.  You must call CryptoConfig.AddAlgorithm to register the class.

Here's the MSDN SignedXml sample modified to use SHA256:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.Xml;
using System.Deployment.Internal.CodeSigning;
               
namespace SignVerify
{
    public class SignVerifyEnvelope
    {
        public static void Main(String[] args)
        {
            try
            {
                CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
               
                // Generate a signing key.
                RSACryptoServiceProvider Key = new RSACryptoServiceProvider();
               
                // Create an XML file to sign.
                CreateSomeXml("Example.xml");
                Console.WriteLine("New XML file created.");
               
                // Sign the XML that was just created and save it in a
                // new file.
                SignXmlFile("Example.xml", "signedExample.xml", Key);
                Console.WriteLine("XML file signed.");
               
                // Verify the signature of the signed XML.
                Console.WriteLine("Verifying signature...");
                bool result = VerifyXmlFile("SignedExample.xml", Key);
               
                // Display the results of the signature verification to
                // the console.
                if (result)
                {
                    Console.WriteLine("The XML signature is valid.");
                }
                else
                {
                    Console.WriteLine("The XML signature is not valid.");
                }
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);
            }
        }

        // Sign an XML file and save the signature in a new file. This method does not 
        // save the public key within the XML file.  This file cannot be verified unless 
        // the verifying code has the key with which it was signed.
        public static void SignXmlFile(string FileName, string SignedFileName, RSA Key)
        {
            // Create a new XML document.
            XmlDocument doc = new XmlDocument();
               
            // Load the passed XML file using its name.
            doc.Load(new XmlTextReader(FileName));
               
            // Create a SignedXml object.
            SignedXml signedXml = new SignedXml(doc);
               
            // Add the key to the SignedXml document.
            signedXml.SigningKey = Key;
            signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
               
            // Create a reference to be signed.
            Reference reference = new Reference();
            reference.Uri = "";
               
            // Add an enveloped transformation to the reference.           
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            reference.AddTransform(new XmlDsigExcC14NTransform());
            reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";
               
            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);
               
            // Compute the signature.
            signedXml.ComputeSignature();
               
            // Get the XML representation of the signature and save
            // it to an XmlElement object.
            XmlElement xmlDigitalSignature = signedXml.GetXml();
               
            // Append the element to the XML document.
            doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
            if (doc.FirstChild is XmlDeclaration)
            {
                doc.RemoveChild(doc.FirstChild);
            }
               
            // Save the signed XML document to a file specified
            // using the passed string.
            XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));
            doc.WriteTo(xmltw);
            xmltw.Close();
        }
               
        // Verify the signature of an XML file against an asymetric
        // algorithm and return the result.
        public static Boolean VerifyXmlFile(String Name, RSA Key)
        {
            // Create a new XML document.
            XmlDocument xmlDocument = new XmlDocument();
               
            // Load the passed XML file into the document.
            xmlDocument.Load(Name);
               
            // Create a new SignedXml object and pass it
            // the XML document class.
            SignedXml signedXml = new SignedXml(xmlDocument);
               
            // Find the "Signature" node and create a new
            // XmlNodeList object.
            XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature");
               
            // Load the signature node.
            signedXml.LoadXml((XmlElement)nodeList[0]);
               
            // Check the signature and return the result.
            return signedXml.CheckSignature(Key);
        }

        // Create example data to sign.
        public static void CreateSomeXml(string FileName)
        {
            // Create a new XmlDocument object.
            XmlDocument document = new XmlDocument();
               
            // Create a new XmlNode object.
            XmlNode node = document.CreateNode(XmlNodeType.Element, "", "MyElement", "samples");
               
            // Add some text to the node.
            node.InnerText = "Example text to be signed.";
               
            // Append the node to the document.
            document.AppendChild(node);
               
            // Save the XML document to the file name specified.
            XmlTextWriter xmltw = new XmlTextWriter(FileName, new UTF8Encoding(false));
            document.WriteTo(xmltw);
            xmltw.Close();
        }
    }
}
               
If your code is based on .NET 4.0 or you prefer not to depend on System.Deployment you can implement your own RSAPKCS1SHA256SignatureDescription class.
Shawn Neal at GitHub provides a good implementation - https://gist.github.com/sneal/f35de432115b840c4c1f#file-rsapkcs1sha256signaturedescription.  
One thing though, Microsoft recommends that you avoid using any managed classes.  You should change SHA256Managed to SHA256CryptoServiceProvider.
.NET versions below 4.0 won't work because the CryptoConfig class did not provide the AddAlgorithm method to add additional algorithms to the internal algorithm table.

                             

SHA-1 Code Signing Deprecation in Windows beginning January 1, 2016

$
0
0

This post is to help the product team spread the word on Windows (version 7 and higher) and Windows Server will no longer trust any code that is signed with a SHA-1 code signing certificate and that contains a timestamp value greater than January 1,2016, effective January 1, 2016.

For more information or to get the latest information on this topic, please check out the following WIKI on Microsoft Technet, http://aka.ms/sha1

Hotfixes for December 2015

$
0
0

Jeff here, from the SDK team with the Holiday Hotfixes. Happy patching.

KB2920591   High CPU usage and performance issues occur when access-based enumeration is enabled in Windows 7 Service Pack 1 or Windows Server 2008 R2 Service Pack 1

KB3084463   WSUSutil.exe csaimport fails upon import in Windows Server 2012 R2 or Windows Server 2012

KB3095319   You receive an error message when you use GPMC to manage audit policies in Windows 8.1 or Windows Server 2012 R2

KB3102997   Data is corrupted after iSCSI sessions or paths recover in Windows Server 2012 R2 or Windows Server 2012

KB3102998   Application can't connect to iSCSI servers in Windows Server 2012 R2 or Windows Server 2012

KB3106296   Can't connect to a wireless network when you resume the computer from hibernation

KB3107128   Search result is incomplete if search criteria contain digits in Windows

KB3108319   VSS backup of the PI Data server fails and the computer crashes in Windows 8.1 or Windows Server 2012 R2

KB3109093   Applications can't communicate over TCP loopback path in Windows 8.1 or Windows Server 2012 R2

KB3109099   Update adds support for the slow timer in LACP in Windows Server 2012 R2

KB3109156   Applications may freeze when ADSI APIs waits infinitely for server to respond in Windows Server 2012 R2

KB3109600   Users can't log on to Outlook Web App client from a browser in Windows

KB3109973   Backup fails with a "File Not Found" error on a Windows Server 2012 R2 cluster

KB3114133   Windows Server Backup fails when you back up multiple volumes in Windows Server 2012 R2

Happy Holidays,

/Jeff

Follow us on Twitter, www.twitter.com/WindowsSDK.


Why CryptCATAdminCalcHashFromFileHandle fails with a seemingly unexpected error code

$
0
0

CryptCATAdminCalcHashFromFileHandle can fail when evaluating a file path to an executable while setting the last error code to 0x800700c1.  It’s an HRESULT instead of just an error code, but the relevant portion of the error code is 0xc1 (193L).  That is the error code for ERROR_BAD_EXE_FORMAT.  In some cases, this will happen even though the executable can run without an error.  So why would this function return ERROR_BAD_EXE_FORMAT when directly executing the file works without issue?

There are actually several reasons why this error can be returned, and only some of them would actually prevent an executable from being able to run on an unrestricted system.  All of them come from the portable executable (PE) header of the file.  The types used below can be found in the Windows SDK, primarily in winnt.h.  Here are most of the reasons:

  • PIMAGE_DOS_HEADER->e_magic is an invalid value
  • PIMAGE_DOS_HEADER->e_lfanew is an invalid value
  • PIMAGE_NT_HEADERS->Signature is an invalid value
  • PIMAGE_NT_HEADERS->FileHeader.SizeOfOptionalHeader is an invalid value
  • PIMAGE_NT_HEADERS->FileHeader.Machine is an invalid value
  • PIMAGE_NT_HEADERS->OptionalHeader.Magic is an invalid value
  • PIMAGE_NT_HEADERS->OptionalHeader.FileAlignment is an invalid value
  • Any of the populated members of PIMAGE_NT_HEADERS->OptionalHeader.DataDirectory have invalid values
  • The certificate directory (IMAGE_DIRECTORY_ENTRY_SECURITY) has an offset that puts its data in an invalid location; see https://msdn.microsoft.com/en-us/windows/hardware/gg463180 for more details on what the standards for that are.

If you encounter this error on an executable file, these can be identified manually by looking at the output of a couple of tools.  If there’s a problem with the IMAGE_DIRECTORY_ENTRY_SECURITY section, then running SignTool.exe verify /v filename will output “SignTool Error: File not valid: filename”.  The rest of them can be identified by looking through the output of dumpbin.exe.  Dumpbin is available through Visual Studio and SignTool is available through the Windows SDK.

Follow us on Twitter, www.twitter.com/WindowsSDK.

Hotfix for January 2016

Hotfix List for February 2016

$
0
0

Hi guys,

Jeff here from the Windows SDK team. Here are the Windows hotfixes for February 2016.

KB3007507   "HTTP Error 500.19" error when you browse an IIS 8.5 website in Windows

KB3090343   Cluster service stops during the VSS backup in a Windows Server 2012 R2 or Windows Server 2012-based Hyper-V cluster

KB3123593   A multi-site failover cluster goes into a split brain situation in Windows Server 2012 R2

KB3133689   UBPM doesn't set environmental variables correctly when you run scheduled tasks in Windows Server 2012 R2

Happy patching!

/Jeff

Follow us on Twitter, www.twitter.com/WindowsSDK.

Virtual Desktop Switching in Windows 10

$
0
0

 

Windows 10 introduces a new concept (for Windows anyway) called Virtual Desktops.  Currently, the guidance for this on MSDN states:

The user can group a collection of windows together to create a virtual desktop. Every window is considered to be part of a virtual desktop. When one virtual desktop is hidden, all of the windows associated with it are also hidden. This enables the user to create multiple working environments and to be able to switch between them. Similarly, when a virtual desktop is selected to be active, the windows associated with that virtual desktop are displayed on the screen.

To support this concept, applications should avoid automatically switching the user from one virtual desktop to another. Only the user should instigate that change. In order to support this, newly created windows should appear on the currently active virtual desktop. In addition, if an application can reuse currently active windows, it should only reuse windows if they are on the currently active virtual desktop. Otherwise, a new window should be created.

That’s good advice as it makes for the best user experience in most cases and as a developer lets you ignore virtual desktops altogether in most simple applications; however, if you have an application or scenario that wants to do something such as always stay on top even when the user changes virtual desktops, what can you do?

IVirtualDesktopManager

To go along with the addition of virtual desktops in Windows 10, a new shell interface was introduced called IVirtualDesktopManager.  It only has three functions, but those allow you to do many things with virtual desktops and your own application.  Attempting to say move a window to another virtual desktop with these functions will not work for windows that your process doesn’t own.  As this isn’t a scenario that should be common or desired behavior for most applications, there’s isn’t a notification that you can subscribe to so that you know that your application window’s virtual desktop is no longer visible or that your application window has been moved to a new virtual desktop.  However, if your window has focus when the user switches to another virtual desktop, you will be told that you’ve lost focus.

IsWindowOnCurrentVirtualDesktop will tell you if your window is on the current virtual desktop.  GetWindowDesktopId will give you the ID of the desktop the specified window is on.  MoveWindowToDesktop will allow you to move a specified window to a specified desktop.

But how do you know what the current desktop ID is if you don’t have any windows on the current desktop?  That one turns out to be pretty simple.  If you create a new window with no parent, it will be placed on the current virtual desktop.

Demonstration

Putting all of the above together, here’s a straightforward C# WinForms app as an example of an always on top window that can move itself between Virtual Desktops (csproj attached at the end):

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace VirtualDesktopSwitch
{
    /// <summary>
    /// Example form
    /// </summary>
    public partial class VDExampleWindow : Form
    {
        public VDExampleWindow()
        {
            InitializeComponent();
        }
        private VirtualDesktopManager vdm;
        private void VDExampleWindow_Load(object sender, EventArgs e)
        {
            //Create IVirtualDesktopManager on load
            vdm = new VirtualDesktopManager();
        }

        private void label1_Click(object sender, EventArgs e)
        {
            //Show details on click
            MessageBox.Show("Virtual Desktop ID: " + vdm.GetWindowDesktopId(Handle).ToString("X") + Environment.NewLine +
                "IsCurrentVirtualDesktop: " + vdm.IsWindowOnCurrentVirtualDesktop(Handle).ToString()
                );
        }
        //Timer tick to check if the window is on the current virtual desktop and change it otherwise
        //A timer does not have to be used, but something has to trigger the check
        //If the window was active before the vd change, it would trigger
        //the deactivated and lost focus events when the vd changes
        //The timer always gets triggered which makes the example hopefully less confusing
        private void VDCheckTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                if (!vdm.IsWindowOnCurrentVirtualDesktop(Handle))
                {
                    using (NewWindow nw = new NewWindow())
                    {
                        nw.Show(null);
                        vdm.MoveWindowToDesktop(Handle, vdm.GetWindowDesktopId(nw.Handle));
                    }
                }
            }
            catch
            {
                //This will fail due to race conditions as currently written on occassion
            }
        }

        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.label1 = new System.Windows.Forms.Label();
            this.VDCheckTimer = new System.Windows.Forms.Timer(this.components);
            this.SuspendLayout();
            //
            // label1
            //
            this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 13.875F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.Location = new System.Drawing.Point(0, 0);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(1112, 368);
            this.label1.TabIndex = 0;
            this.label1.Text = "Example Contents";
            this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.label1.Click += new System.EventHandler(this.label1_Click);
            //
            // VDCheckTimer
            //
            this.VDCheckTimer.Enabled = true;
            this.VDCheckTimer.Interval = 1000;
            this.VDCheckTimer.Tick += new System.EventHandler(this.VDCheckTimer_Tick);
            //
            // VDExampleWindow
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(12F, 25F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(1112, 368);
            this.Controls.Add(this.label1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
            this.Name = "VDExampleWindow";
            this.Text = "VD Example";
            this.TopMost = true;
            this.Load += new System.EventHandler(this.VDExampleWindow_Load);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Timer VDCheckTimer;

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new VDExampleWindow());
        }
    }
    [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("a5cd92ff-29be-454c-8d04-d82879fb3f1b")]
    [System.Security.SuppressUnmanagedCodeSecurity]
    public interface IVirtualDesktopManager
    {
        [PreserveSig]
        int IsWindowOnCurrentVirtualDesktop(
            [In] IntPtr TopLevelWindow,
            [Out] out int OnCurrentDesktop
            );
        [PreserveSig]
        int GetWindowDesktopId(
            [In] IntPtr TopLevelWindow,
            [Out] out Guid CurrentDesktop
            );

        [PreserveSig]
        int MoveWindowToDesktop(
            [In] IntPtr TopLevelWindow,
            [MarshalAs(UnmanagedType.LPStruct)]
            [In]Guid CurrentDesktop
            );
    }

    public class NewWindow : Form
    {
    }
    [ComImport, Guid("aa509086-5ca9-4c25-8f95-589d3c07b48a")]
    public class CVirtualDesktopManager
    {

    }
    public class VirtualDesktopManager
    {
        public VirtualDesktopManager()
        {
            cmanager = new CVirtualDesktopManager();
            manager = (IVirtualDesktopManager)cmanager;
        }
        ~VirtualDesktopManager()
        {
            manager = null;
            cmanager = null;
        }
        private CVirtualDesktopManager cmanager = null;
        private IVirtualDesktopManager manager;

        public bool IsWindowOnCurrentVirtualDesktop(IntPtr TopLevelWindow)
        {
            int result;
            int hr;
            if ((hr = manager.IsWindowOnCurrentVirtualDesktop(TopLevelWindow, out result)) != 0)
            {
                Marshal.ThrowExceptionForHR(hr);
            }
            return result != 0;
        }

        public Guid GetWindowDesktopId(IntPtr TopLevelWindow)
        {
            Guid result;
            int hr;
            if ((hr = manager.GetWindowDesktopId(TopLevelWindow, out result)) != 0)
            {
                Marshal.ThrowExceptionForHR(hr);
            }
            return result;
        }

        public void MoveWindowToDesktop(IntPtr TopLevelWindow, Guid CurrentDesktop)
        {
            int hr;
            if ((hr = manager.MoveWindowToDesktop(TopLevelWindow, CurrentDesktop)) != 0)
            {
                Marshal.ThrowExceptionForHR(hr);
            }
        }
    }
}

Follow us on Twitter, www.twitter.com/WindowsSDK.

VirtualDesktopSwitch.zip

FileSystemWatcher Fencing(Part 2)

$
0
0
 

This post is a follow up to the FileSystemWatcher Follies post.  I received a lot of feedback that it would be useful to highlight what would be appropriate to guide against some of the pitfalls that I mentioned in that post.  I’ll cover several of the issues here over a couple of posts and propose things that could be done to detect that they are there before using the FileSystemWatcher class against them.  Though the code examples will all be in C#, there will be some P/Invoke involved here as not all of this functionality is exposed through .NET Framework classes at this time.

Using Change Journals

If you’ve already determined that your path is local and uses the NTFS or ReFS file system, a great alternative to the FileSystemWatcher is to use change journaling.  Change journals can be complicated, but they also give you very fine grained control over the information that you want.  However, your code must be running as an administrator or system in order to create or delete them, and they do take up some space on disk (the maximum amount that will be taken up can be specified).    Because change journals monitor an entire volume, if you’re designing an application to make optimal use of this functionality for consistent change monitoring, you may want to put the data that you’re consistently monitoring for changes on its own volume.

Other things to keep in mind when using change journals:

  1. Changes for files and directories are not full paths; parent directories are identified by IDs and those directory names can be looked up by OpenFileByID amongst other methods
  2. If BytesToRead is set to zero, it will immediately return with up to one entry; otherwise it will wait until that many bytes are filled in to the buffer or the specified timeout value.  If you want to get immediate notification
  3. It does not work on network file paths.
  4. All of the functionality works through the use of DeviceIOControl; consult the documentation for the structure type and enumeration value for additional details about how to use that value.

Basic Change Journal Wrapper

Below is sample code for a basic change journal class which monitors a volume for changes.  The changes monitored for are specifiable and the types available are included as an enumeration.  The values are hardcoded to only show file creation and delete events.  If the buffer size is set to anything less than 1024, the sample will use zero for BytesToRead to immediately return upon receiving each entry.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;

namespace ChangeJournal
{
    public class ChangeJournalHandle : SafeHandleMinusOneIsInvalid
    {

        [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern IntPtr CreateFileW(
            [MarshalAs(UnmanagedType.LPWStr)]
            string FileName,
            int DesiredAccess,
            FileShare ShareMode,
            IntPtr SecurityAttributes,
            int CreationDisposition,
            int FlagsAndAttributes,
            IntPtr hTemplateFile
            );

        [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern int GetVolumeInformationByHandleW(
  IntPtr hFile,
  StringBuilder lpVolumeNameBuffer,
  int nVolumeNameSize,
  out int lpVolumeSerialNumber,
  out int
     lpMaximumComponentLength,
  out int lpFileSystemFlags,
  StringBuilder lpFileSystemNameBuffer,
  int nFileSystemNameSize
);



        [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern int DeviceIoControl(
    IntPtr hDevice,
    int dwIoControlCode,
    IntPtr lpInBuffer,
    int nInBufferSize,
    IntPtr lpOutBuffer,
    int nOutBufferSize,
    out int lpBytesReturned,
    IntPtr lpOverlapped
    );

        [DllImport("kernel32", SetLastError = true)]
        private static extern bool CloseHandle(
            IntPtr handle);


        [DllImport("kernel32", SetLastError = true)]
        private static extern IntPtr OpenFileById(
  IntPtr hFile,
  ref FILE_ID_DESCRIPTOR lpFileID,
  int                 dwDesiredAccess,
  FileShare dwShareMode,
  IntPtr lpSecurityAttributes,
  int dwFlags
);
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern int GetFinalPathNameByHandleW(
  IntPtr hFile,
  StringBuilder lpszFilePath,
  int cchFilePath,
  int dwFlags
);
        [StructLayout(LayoutKind.Explicit)]
        public struct FILE_ID_DESCRIPTOR
        {
            [FieldOffset(0)]
            public int Size;
            [FieldOffset(4)]
            public int Type;
            [FieldOffset(8)]
            public long FileId;
            [FieldOffset(8)]
            public Guid ObjectId;
            [FieldOffset(8)]
            public Guid ExtendedFileId; //Use for ReFS; need to use v3 structures or later instead of v2 as done in this sample
        }

        public static int CTL_CODE(int DeviceType, int Function, int Method, int Access)
        {
            return ((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method);
        }

        protected override bool ReleaseHandle()
        {

            if(handle != IntPtr.Zero)
            {
                if(createdJournal == true)
                {
                    TryDeleteCurrentJournal();
                }
                StopListening(10);//this may cause a delay
                return CloseHandle(handle);
            }
            return false;
        }

        public const int FILE_DEVICE_FILE_SYSTEM = 0x00000009;
        public const int METHOD_BUFFERED = 0;
        public const int METHOD_IN_DIRECT = 1;
        public const int METHOD_OUT_DIRECT = 2;
        public const int METHOD_NEITHER = 3;
        public const int FILE_ANY_ACCESS = 0;

        public static int FSCTL_READ_USN_JOURNAL = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 46, METHOD_NEITHER, FILE_ANY_ACCESS);
        public static int FSCTL_ENUM_USN_DATA = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 44, METHOD_NEITHER, FILE_ANY_ACCESS);
        public static int FSCTL_CREATE_USN_JOURNAL = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 57, METHOD_NEITHER, FILE_ANY_ACCESS);
        public static int FSCTL_READ_FILE_USN_DATA = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 58, METHOD_NEITHER, FILE_ANY_ACCESS);
        public static int FSCTL_QUERY_USN_JOURNAL = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 61, METHOD_BUFFERED, FILE_ANY_ACCESS);
        public static int FSCTL_DELETE_USN_JOURNAL = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 62, METHOD_BUFFERED, FILE_ANY_ACCESS);
        public static int FSCTL_WRITE_USN_REASON = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 180, METHOD_BUFFERED, FILE_ANY_ACCESS);
        public static int FSCTL_USN_TRACK_MODIFIED_RANGES = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 189, METHOD_BUFFERED, FILE_ANY_ACCESS);

        [StructLayout(LayoutKind.Sequential)]
        public struct USN
        {
            public long Usn;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct MFT_ENUM_DATA_V0
        {
            public USN Low;
            public USN High;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct MFT_ENUM_DATA_V1
        {
            public long StartFileReferenceNumber;
            public USN Low;
            public USN High;
            public short MinMajorVersion;
            public short MaxMajorVersion;
        }


        [StructLayout(LayoutKind.Sequential)]
        public struct CREATE_USN_JOURNAL_DATA
        {
            public long MaximumSize;
            public long AllocationDelta;
        }


        [StructLayout(LayoutKind.Sequential)]
        public struct READ_USN_JOURNAL_DATA_V0
        {
            public USN StartUsn;
            public int ReasonMask;
            public int ReturnOnlyOnClose;
            public long Timeout;
            public long BytesToWaitFor;
            public long UsnJournalId;
        }


        [StructLayout(LayoutKind.Sequential)]
        public struct READ_USN_JOURNAL_DATA_V1
        {
            public USN StartUsn;
            public int ReasonMask;
            public int ReturnOnlyOnClose;
            public long Timeout;
            public long BytesToWaitFor;
            public long UsnJournalId;
            public short MinMajorVersion;
            public short MaxMajorVersion;
        }


        [StructLayout(LayoutKind.Sequential)]
        public struct USN_TRACK_MODIFIED_RANGES
        {
            public int Flags;
            public int Unused;
            public long ChunkSize;
            public long FileSizeThreshold;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct USN_RANGE_TRACK_OUTPUT
        {
            public USN Usn;
        }

        public const int FLAG_USN_TRACK_MODIFIED_RANGES_ENABLE = 0x00000001;

        public class UsnRecordV2WithName
        {
            public USN_RECORD_V2 Record { get; set; }
            public string Filename { get; set; }
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct USN_RECORD_V2
        {
            public int RecordLength;
            public short MajorVersion;
            public short MinorVersion;
            public long FileReferenceNumber;
            public long ParentFileReferenceNumber;
            USN Usn;
            public long TimeStamp;
            public int Reason;
            public int SourceInfo;
            public int SecurityId;
            public int FileAttributes;
            public short FileNameLength;
            public short FileNameOffset;
            //WCHAR FileName[1];

        }

        [StructLayout(LayoutKind.Sequential)]
        public struct USN_RECORD_V3
        {
            public int RecordLength;
            public short MajorVersion;
            public short MinorVersion;
            public Guid FileReferenceNumber;
            public Guid ParentFileReferenceNumber;
            USN Usn;
            public long TimeStamp;
            public int Reason;
            public int SourceInfo;
            public int SecurityId;
            public int FileAttributes;
            public short FileNameLength;
            public short FileNameOffset;
            //WCHAR FileName[1];

        }


        [StructLayout(LayoutKind.Sequential)]
        public struct USN_RECORD_COMMON_HEADER
        {
            public int RecordLength;
            public short MajorVersion;
            public short MinorVersion;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct USN_RECORD_EXTENT
        {
            public long Offset;
            public long Length;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct USN_RECORD_V4
        {
            public USN_RECORD_COMMON_HEADER Header;
            public Guid FileReferenceNumber;
            public Guid ParentFileReferenceNumber;
            public USN Usn;
            public int Reason;
            public int SourceInfo;
            public int RemainingExtents;
            public short NumberOfExtents;
            public short ExtentSize;
            public USN_RECORD_EXTENT Extents; //Extents[1]
        }


        public const int USN_PAGE_SIZE = (0x1000);
        public const int USN_REASON_DATA_OVERWRITE = (0x00000001);
        public const int USN_REASON_DATA_EXTEND = (0x00000002);
        public const int USN_REASON_DATA_TRUNCATION = (0x00000004);
        public const int USN_REASON_NAMED_DATA_OVERWRITE = (0x00000010);
        public const int USN_REASON_NAMED_DATA_EXTEND = (0x00000020);
        public const int USN_REASON_NAMED_DATA_TRUNCATION = (0x00000040);
        public const int USN_REASON_FILE_CREATE = (0x00000100);
        public const int USN_REASON_FILE_DELETE = (0x00000200);
        public const int USN_REASON_EA_CHANGE = (0x00000400);
        public const int USN_REASON_SECURITY_CHANGE = (0x00000800);
        public const int USN_REASON_RENAME_OLD_NAME = (0x00001000);
        public const int USN_REASON_RENAME_NEW_NAME = (0x00002000);
        public const int USN_REASON_INDEXABLE_CHANGE = (0x00004000);
        public const int USN_REASON_BASIC_INFO_CHANGE = (0x00008000);
        public const int USN_REASON_HARD_LINK_CHANGE = (0x00010000);
        public const int USN_REASON_COMPRESSION_CHANGE = (0x00020000);
        public const int USN_REASON_ENCRYPTION_CHANGE = (0x00040000);
        public const int USN_REASON_OBJECT_ID_CHANGE = (0x00080000);
        public const int USN_REASON_REPARSE_POINT_CHANGE = (0x00100000);
        public const int USN_REASON_STREAM_CHANGE = (0x00200000);
        public const int USN_REASON_TRANSACTED_CHANGE = (0x00400000);
        public const int USN_REASON_INTEGRITY_CHANGE = (0x00800000);
        public const uint USN_REASON_CLOSE = (0x80000000);

        [Flags]
        public enum UsnReasonType : int
        {
            USN_REASON_DATA_OVERWRITE = (0x00000001),
            USN_REASON_DATA_EXTEND = (0x00000002),
            USN_REASON_DATA_TRUNCATION = (0x00000004),
            USN_REASON_NAMED_DATA_OVERWRITE = (0x00000010),
            USN_REASON_NAMED_DATA_EXTEND = (0x00000020),
            USN_REASON_NAMED_DATA_TRUNCATION = (0x00000040),
            USN_REASON_FILE_CREATE = (0x00000100),
            USN_REASON_FILE_DELETE = (0x00000200),
            USN_REASON_EA_CHANGE = (0x00000400),
            USN_REASON_SECURITY_CHANGE = (0x00000800),
            USN_REASON_RENAME_OLD_NAME = (0x00001000),
            USN_REASON_RENAME_NEW_NAME = (0x00002000),
            USN_REASON_INDEXABLE_CHANGE = (0x00004000),
            USN_REASON_BASIC_INFO_CHANGE = (0x00008000),
            USN_REASON_HARD_LINK_CHANGE = (0x00010000),
            USN_REASON_COMPRESSION_CHANGE = (0x00020000),
            USN_REASON_ENCRYPTION_CHANGE = (0x00040000),
            USN_REASON_OBJECT_ID_CHANGE = (0x00080000),
            USN_REASON_REPARSE_POINT_CHANGE = (0x00100000),
            USN_REASON_STREAM_CHANGE = (0x00200000),
            USN_REASON_TRANSACTED_CHANGE = (0x00400000),
            USN_REASON_INTEGRITY_CHANGE = (0x00800000),
            USN_REASON_CLOSE = unchecked((int)(0x80000000))
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct USN_JOURNAL_DATA_V0
        {
            public long UsnJournalID;
            public USN FirstUsn;
            public USN NextUsn;
            public USN LowestValidUsn;
            public USN MaxUsn;
            public long MaximumSize;
            public long AllocationDelta;

        }
        [StructLayout(LayoutKind.Sequential)]
        public struct USN_JOURNAL_DATA_V1
        {
            public long UsnJournalID;
            public USN FirstUsn;
            public USN NextUsn;
            public USN LowestValidUsn;
            public USN MaxUsn;
            public long MaximumSize;
            public long AllocationDelta;
            public short MinSupportedMajorVersion;
            public short MaxSupportedMajorVersion;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct USN_JOURNAL_DATA_V2
        {
            public long UsnJournalID;
            public USN FirstUsn;
            public USN NextUsn;
            public USN LowestValidUsn;
            public USN MaxUsn;
            public long MaximumSize;
            public long AllocationDelta;
            public short MinSupportedMajorVersion;
            public short MaxSupportedMajorVersion;
            public int Flags;
            public long RangeTrackChunkSize;
            public long RangeTrackFileSizeThreshold;
        }



        [StructLayout(LayoutKind.Sequential)]
        public struct DELETE_USN_JOURNAL_DATA
        {
            public long UsnJournalID;
            public int DeleteFlags;
        }

        public int USN_DELETE_FLAG_DELETE = (0x00000001);
        public int USN_DELETE_FLAG_NOTIFY = (0x00000002);
        public int USN_DELETE_VALID_FLAGS = (0x00000003);

        public UsnReasonType EventTriggerMask
        {
            get
            {
                return (UsnReasonType)rdata.ReasonMask;
            }
            set
            {
                rdata.ReasonMask = (int)value;
            }
        }

        public long Timeout
        {
            get
            {
                return rdata.Timeout;
            }
            set
            {
                rdata.Timeout = value;
            }
        }

        public bool TriggerOnCloseOnly
        {
            get
            {
                return rdata.ReturnOnlyOnClose != 0;
            }
            set
            {
                rdata.ReturnOnlyOnClose = value ? 1 : 0;
            }
        }
        private ReaderWriterLockSlim readBufferLock = new ReaderWriterLockSlim();

        private int readBufferSize = 8192;

        //This could hang if there is a long timeout value
        public int ReadBufferSize
        {
            get
            {
                readBufferLock.EnterWriteLock();
                try
                {
                    return readBufferSize;
                }
                finally
                {
                    readBufferLock.ExitWriteLock();
                }
            }
            set
            {
                readBufferLock.EnterWriteLock();
                try
                {

                    if (value > 0)
                    {
                        if (readBuffer == IntPtr.Zero)
                        {
                            readBuffer = Marshal.AllocHGlobal(value);
                        }
                        else
                        {
                            readBuffer = Marshal.ReAllocHGlobal(readBuffer, (IntPtr)value);
                        }
                    }
                    readBufferSize = value;

                }
                finally
                {
                    readBufferLock.ExitWriteLock();
                }
            }
        }
        public event Action<ChangeJournalHandle, UsnRecordV2WithName> OnChange;
        public event Action<ChangeJournalHandle, Exception> OnError;

        private bool shouldRun = false;

        private Thread thread = null;

        public ChangeJournalHandle(string path) : base(true)
        {
            //TODO:Handle taking non-volume paths
            handle = CreateFileW(path, unchecked((int)(0x80000000 | 0x40000000)),
                FileShare.ReadWrite, IntPtr.Zero, 3, 0, IntPtr.Zero);
            if (IsInvalid)
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }
        }

        public bool TryCreateJournal(long maxSize = (1024 ^ 2) * 500, long allocationDelta = 8192)
        {
            CREATE_USN_JOURNAL_DATA data = new CREATE_USN_JOURNAL_DATA();
            data.AllocationDelta = allocationDelta;
            data.MaximumSize = maxSize;
            int size = Marshal.SizeOf(data);
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try
            {
                int bufSizeOut;
                int result = DeviceIoControl(handle, FSCTL_CREATE_USN_JOURNAL, buffer, size, IntPtr.Zero, 0, out bufSizeOut, IntPtr.Zero);
                if (result == 0)
                {
                    ReportLastError();
                    return false;
                }
                createdJournal = true;
                return true;
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }
        public void CreateJournal(long maxSize = (1024 ^ 2) * 500, long allocationDelta = 8192)
        {
            CREATE_USN_JOURNAL_DATA data = new CREATE_USN_JOURNAL_DATA();
            data.AllocationDelta = allocationDelta;
            data.MaximumSize = maxSize;
            int size = Marshal.SizeOf(data);
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try
            {
                int bufSizeOut;
                int result = DeviceIoControl(handle, FSCTL_CREATE_USN_JOURNAL, buffer, size, IntPtr.Zero, 0, out bufSizeOut, IntPtr.Zero);
                if (result == 0)
                {
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                }
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }
        public bool TryDeleteCurrentJournal()
        {
            USN_JOURNAL_DATA_V0 data = new USN_JOURNAL_DATA_V0();
            int size = Marshal.SizeOf(data);
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try
            {
                int outSize;
                int result = DeviceIoControl(handle, FSCTL_QUERY_USN_JOURNAL, IntPtr.Zero, 0, buffer, size, out outSize, IntPtr.Zero);
                if (result == 0)
                {
                    ReportLastError();
                    return false;
                }
                data = Marshal.PtrToStructure<USN_JOURNAL_DATA_V0>(buffer);
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
            DELETE_USN_JOURNAL_DATA d = new DELETE_USN_JOURNAL_DATA();
            d.UsnJournalID = data.UsnJournalID;
            d.DeleteFlags = 3;
            size = Marshal.SizeOf(d);
            buffer = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.StructureToPtr(d, buffer, false);
                if (DeviceIoControl(handle, FSCTL_DELETE_USN_JOURNAL, buffer, size, IntPtr.Zero, 0, out size, IntPtr.Zero) == 0)
                {
                    ReportLastError();
                    return false;
                }
                return true;
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }
        public bool TryDeleteJournal(long UsnJournalID)
        {
            //Note that overloads would be needed for different versions of the structure
            DELETE_USN_JOURNAL_DATA d = new DELETE_USN_JOURNAL_DATA();
            d.UsnJournalID = UsnJournalID;
            d.DeleteFlags = 3;
            int size = Marshal.SizeOf(d);
            IntPtr buffer = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.StructureToPtr(d, buffer, false);
                if (DeviceIoControl(handle, FSCTL_DELETE_USN_JOURNAL, buffer, size, IntPtr.Zero, 0, out size, IntPtr.Zero) == 0)
                {
                    ReportLastError();
                    return false;
                }
                return true;
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }

        }
        public void DeleteAllJournals()
        {
            try
            {
                while (true)
                {
                    USN_JOURNAL_DATA_V0 data = new USN_JOURNAL_DATA_V0();
                    int size = Marshal.SizeOf(data);
                    IntPtr buffer = Marshal.AllocHGlobal(size);
                    try
                    {
                        int outSize;
                        int result = DeviceIoControl(handle, FSCTL_QUERY_USN_JOURNAL, IntPtr.Zero, 0, buffer, size, out outSize, IntPtr.Zero);
                        if (result == 0)
                        {
                            ReportLastError();
                            break;
                        }
                        data = Marshal.PtrToStructure<USN_JOURNAL_DATA_V0>(buffer);
                    }
                    finally
                    {
                        Marshal.FreeHGlobal(buffer);
                    }
                    DELETE_USN_JOURNAL_DATA d = new DELETE_USN_JOURNAL_DATA();
                    d.UsnJournalID = data.UsnJournalID;
                    d.DeleteFlags = 3;
                    size = Marshal.SizeOf(d);
                    buffer = Marshal.AllocHGlobal(size);
                    try
                    {
                        Marshal.StructureToPtr(d, buffer, false);
                        if (DeviceIoControl(handle, FSCTL_DELETE_USN_JOURNAL, buffer, size, IntPtr.Zero, 0, out size, IntPtr.Zero) == 0)
                        {
                            ReportLastError();
                            break;
                        }
                    }
                    finally
                    {
                        Marshal.FreeHGlobal(buffer);
                    }
                }
            }
            catch (Exception ex)
            {
                ReportException(ex);
            }
        }
        public void StartListening()
        {
            //See https://msdn.microsoft.com/en-us/library/windows/desktop/aa365736(v=vs.85).aspx
            if (!shouldRun)
            {
                thread = new Thread(ListenProc);
                shouldRun = true;
                thread.Start();
            }
        }

        public void StopListening(int timeout = int.MaxValue)
        {
            if (shouldRun)
            {
                shouldRun = false;
                if (thread != null)
                {
                    if(!thread.Join(timeout))
                    {
                        thread.Abort();
                    }
                    thread = null;
                }
            }
        }

        public string GetNameForId(long id)
        {
            try
            {
                FILE_ID_DESCRIPTOR fid = new FILE_ID_DESCRIPTOR();
                fid.FileId = id;
                fid.Size = Marshal.SizeOf(fid);
                IntPtr h = OpenFileById(handle, ref fid, unchecked((int)0x80), FileShare.ReadWrite | FileShare.Delete, IntPtr.Zero, 0);
                if (h == new IntPtr(-1))
                {
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                }
                int size = 1024;
                StringBuilder sb = new StringBuilder(size);
                if (GetFinalPathNameByHandleW(h, sb, size, 0) == 0)
                {
                    int hr = Marshal.GetHRForLastWin32Error();
                    CloseHandle(h);
                    Marshal.ThrowExceptionForHR(hr);
                }
                CloseHandle(h);
                return sb.ToString();
            }
            catch(Exception ex)
            {
                ReportException(ex);
                return id.ToString("X");
            }

        }
        private READ_USN_JOURNAL_DATA_V0 rdata = new READ_USN_JOURNAL_DATA_V0() { ReasonMask = unchecked((int)0xFFFFFFFF) };
        private IntPtr readBuffer;
        private bool createdJournal = false;
        void ListenProc()
        {
            try
            {
                USN_JOURNAL_DATA_V0 data = new USN_JOURNAL_DATA_V0();
                int size = Marshal.SizeOf(data);
                IntPtr buffer = Marshal.AllocHGlobal(size);
                try
                {
                    int outSize;
                    int result = DeviceIoControl(handle, FSCTL_QUERY_USN_JOURNAL, IntPtr.Zero, 0, buffer, size, out outSize, IntPtr.Zero);
                    if (result == 0)
                    {
                        if(TryCreateJournal())
                        {
                            result = DeviceIoControl(handle, FSCTL_QUERY_USN_JOURNAL, IntPtr.Zero, 0, buffer, size, out outSize, IntPtr.Zero);
                        }
                        if(result == 0) ReportLastError();
                    }
                    if(result != 0) data = Marshal.PtrToStructure<USN_JOURNAL_DATA_V0>(buffer);
                }
                finally
                {
                    Marshal.FreeHGlobal(buffer);
                }
                rdata.UsnJournalId = data.UsnJournalID;
                rdata.StartUsn.Usn = 0;
                int rsize = Marshal.SizeOf(typeof(USN_RECORD_V2));
                size = Marshal.SizeOf(rdata);
                buffer = Marshal.AllocHGlobal(size);
                if (readBuffer == IntPtr.Zero)
                {
                    //Allocates the buffer if it's empty
                    ReadBufferSize = ReadBufferSize;
                }
                int usize = Marshal.SizeOf(typeof(USN));
                try
                {
                    List<UsnRecordV2WithName> records = new List<UsnRecordV2WithName>();
                    while (shouldRun)
                    {
                        records.Clear();
                        int outSize;
                        int result;
                        if(readBufferSize >= 1024)
                        {
                            rdata.BytesToWaitFor = readBufferSize;
                        }
                        else
                        {
                            //Returns immediately
                            rdata.BytesToWaitFor = 0;
                        }
                        Marshal.StructureToPtr(rdata, buffer, false);

                        readBufferLock.EnterReadLock();
                        try
                        {
                            result = DeviceIoControl(handle, FSCTL_READ_USN_JOURNAL, buffer, size, readBuffer, readBufferSize, out outSize, IntPtr.Zero);
                            if (result != 0 && outSize >= usize)
                            {
                                USN usn = Marshal.PtrToStructure<USN>(readBuffer);
                                rdata.StartUsn = usn;
                                int retbytes = outSize - usize;
                                IntPtr record = IntPtr.Add(readBuffer, usize);
                                while (retbytes > 0)
                                {
                                    USN_RECORD_V2 r = Marshal.PtrToStructure<USN_RECORD_V2>(record);
                                    UsnRecordV2WithName r2 = new UsnRecordV2WithName();
                                    r2.Record = r;
                                    r2.Filename = Marshal.PtrToStringUni(IntPtr.Add(record, r.FileNameOffset), (r.FileNameLength / 2));
                                    records.Add(r2);
                                    record = IntPtr.Add(record, r.RecordLength);
                                    retbytes -= r.RecordLength;
                                }
                            }
                            else
                            {
                                ReportLastError();
                            }
                        }
                        finally
                        {
                            readBufferLock.ExitReadLock();
                        }
                        foreach (var r in records)
                        {
                            ReportChange(r);
                        }
                    }
                }
                finally
                {
                    Marshal.FreeHGlobal(buffer);
                }
            }
            catch (ThreadAbortException tae)
            {

            }
        }

        void ReportChange(UsnRecordV2WithName record)
        {
            if (OnChange != null)
            {
                OnChange(this, record);
            }
        }

        void ReportLastError()
        {
            ReportException(Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()));
        }

        void ReportException(Exception ex)
        {
            if (OnError != null)
            {
                OnError(this, ex);
            }
        }



        private static void Cjh_OnError(ChangeJournalHandle arg1, Exception arg2)
        {
            Console.WriteLine("Error:/t{0}", arg2.ToString());
        }

        private static void Cjh_OnChange(ChangeJournalHandle arg1, UsnRecordV2WithName arg2)
        {
            //Note that it would be typically faster in the long run to build a dictionary
            //of directory names by IDs and reset it whenever the change journal resets
            //instead of looking up the directory each time
            //Also, note that if the directory is deleted before OpenFileById is called in GetNameById, it's going to fail with an out of range error
            Console.Write(arg1.GetNameForId(arg2.Record.ParentFileReferenceNumber));
            Console.Write("\\");
            Console.Write(arg2.Filename);
            Console.Write(":\t");
            Console.WriteLine(((ChangeJournalHandle.UsnReasonType)arg2.Record.Reason).ToString());
        }
        static void Main(string[] args)
        {
            string pathToVolumeToMonitor = @"\\?\C:";
            //This will filter to show only files that are deleted or created
            UsnReasonType reasonsToMonitor = UsnReasonType.USN_REASON_FILE_CREATE | UsnReasonType.USN_REASON_FILE_DELETE;
            using (ChangeJournalHandle cjh = new ChangeJournalHandle(pathToVolumeToMonitor))
            {
                cjh.OnChange += Cjh_OnChange;
                cjh.OnError += Cjh_OnError;
                cjh.EventTriggerMask = reasonsToMonitor;

                cjh.StartListening();
                Console.ReadLine();
                cjh.StopListening();


                cjh.OnChange -= Cjh_OnChange;
                cjh.OnError -= Cjh_OnError;
            }
        }
    }
}

Sample output:

\\?\C:\Windows\Temp\MSIc9528.LOG:       USN_REASON_FILE_CREATE

\\?\C:\Windows\Temp\MSIc9528.LOG:       USN_REASON_FILE_CREATE, USN_REASON_CLOSE

\\?\C:\Windows\Temp\MSIc9529.LOG:       USN_REASON_FILE_CREATE

\\?\C:\Windows\Temp\MSIc9529.LOG:       USN_REASON_FILE_CREATE, USN_REASON_CLOSE

\\?\C:\Windows\Temp\MSIc952a.LOG:       USN_REASON_FILE_CREATE

\\?\C:\Windows\Temp\MSIc952a.LOG:       USN_REASON_FILE_CREATE, USN_REASON_CLOSE

\\?\C:\Windows\Temp\MSIc952b.LOG:       USN_REASON_FILE_CREATE

\\?\C:\Windows\Temp\MSIc952b.LOG:       USN_REASON_FILE_CREATE, USN_REASON_CLOSE

 

 

 

Follow us on Twitter, www.twitter.com/WindowsSDK.

Windows Hotfixes for October 2015

$
0
0

Jeff here from the Windows SDK team. Here is the list of October 2015 Hotfixes

[Drum roll, please…]

KB3030736   “550 The process cannot access the file” error when you try to download a file in Windows

KB3044546   An updated reservation may disappear on a DHCP failover cluster in Windows Server 2012 or Windows Server 2012 R2

KB3049591   Transparent areas are printed as black when you use a v4 XPS printer driver in Windows

KB3053667   Users can’t connect to virtual machines that are running Windows 8.1 or Windows Server 2012 R2 by remote desktop

KB3077354   Computer freezes when WFP leaks nonpaged pool memory in Windows Server 2012 R2 or Windows Server 2012

KB3084093   Child nodes under protected OU are deleted in Windows Server 2012 R2

KB3084426   System becomes unresponsive when file system minifilter drivers are installed in Windows 8 or Windows Server 2012

KB3084787   Event ID 4102 when DFS Replication cloning fails on a Windows Server 2012 R2-based cluster

KB3084953   OOBE crashes when you enter SIM card PIN in Windows 8.1

KB3084956   You can’t log on to a domain-joined computer in Windows 8 or Windows Server 2012

KB3084983   SetOptions or GetOptions method doesn’t work for PRINTER_PROPERTY features in Windows

KB3086644   System freezes after you start a backup task for virtual machines in Windows Server 2012 R2

KB3090322   Space doesn’t regenerate upon reallocation in Windows Server 2012 R2

KB3090973   Reenlist can’t be called when SQL Server receives transaction outcome from MSDTC in Windows Server 2012 R2

KB3091057   Cluster validation fails in the “Validate Simultaneous Failover” test in a Windows Server 2012 R2-based failover cluster

KB3091061   Update to add CSVFS tracing for performance issues during backup operations in Windows Server 2012 R2

KB3091342   Computer crashes after you install update 3000850 in Windows 8.1

KB3091402   Site-to-site VPN goes down when you set a VNet-to-VNet connection in Azure in Windows 8.1 or Windows Server 2012 R2

KB3091403   High CPU usage for 12 seconds on a multiple-network-adapters computer in Windows Server 2012 R2 or Windows Server 2012

KB3092002   Set-Acl cmdlet fails although delegated admins have “Change Permissions” enabled in Windows Server 2012 R2

KB3092003   Page loads repeatedly and authentication fails when users use MFA in Windows Server 2012 R2 AD FS

KB3092005   Group Policy settings are set back to factory settings in GPMC in Windows Server 2012 R2

KB3092006   Subfolders disappear from FSRM console after you rename the root folder in Windows Server 2012 R2 or Windows Server 2012

KB3092695   Licensing report file is corrupted in Windows Server 2012 R2 RDS environments for large report files

KB3093550   All ScriptProperty members are invoked when you run the Add-Member PowerShell command in Windows 8.1

KB3093571   Update to replicate multiple VM groups and VMs that use shared VHDs in Windows Server 2012 R2 or Windows Server 2012

KB3093803   Error 0x800704C9 occurs when you try to copy file to NFS share in Windows 8 or Windows Server 2012

KB3093899   VMs that run on CSVs fail if DCM can’t query volumes in Windows Server 2012 R2

KB3093900   0x50 Stop error and users can’t access documents on shared folders or home folders in Windows Server 2012 R2

KB3094197   Files aren’t fully optimized and a deduplication cache lock contention issue occurs in Windows Server 2012 R2

KB3094199   Application module can’t receive correct process status after security update 3045999 is installed in Windows

KB3094202   Directory listing fails when sharing violations occur on Windows Server 2012 R2 or Windows Server 2012-based NFS server

KB3094446   Authentication through proxy fails in Windows Server 2012 or Windows Server 2008 R2 SP1

KB3095308   VMs may not get additional memory although they’re set to use Dynamic Memory in Windows Server 2012 R2

KB3095319   You receive an error message when you use GPMC to manage audit policies in Windows 8.1 or Windows Server 2012 R2

KB3095663   VSS_E_PROVIDER_VETO error occurs when you restore a LUN from backup in Windows Server 2012 R2

KB3095711   Update to support LTO-7 tape drives in Windows Server 2012 R2 and Windows Server 2012

KB3095737   Azure Backup takes a long time to back up data with a guest OS that’s running Windows Server 2012

Happy patching…

/Jeff

Follow us on Twitter, www.twitter.com/WindowsSDK.

 

Hotfixes for November 2015

$
0
0

Jeff here from the SDK team. Here are the hotfixes for November 2015.

KB3040017   XPS driver is slower than GDI driver to print files in Windows

KB3063109   Virtual machine crashes and WAL consistency is not maintained for Guest clustered VMs in Windows Server 2012 R2

KB3078414   NFS service freezes on a Windows Server 2012 cluster and a client computer can’t access NFS share

KB3080141   Cluster service freezes on a Windows Server 2012 R2 or Windows Server 2012-based failover cluster

KB3086918   Original file is lost with new file not being saved in WebDAV folder in Windows 8.1

KB3091411   User connection fails when many connections are made to Windows Server 2012 R2-based RD Connection Broker

KB3092604   Network is corrupted between Guest OS and external network for VMs hosted on Windows 8.1 or Windows Server 2012 R2

KB3092688   UPD profiles corrupted when a network connectivity issue occurs in Windows Server 2012 R2

KB3095113   Update to enable WSUS support for Windows 10 feature upgrades

KB3095682   File Explorer shows thumbnail contents even though files are marked with offline flag in Windows

KB3098841   Application crashes with access violation error in Windows 7 or Windows Server 2008 R2

KB3100460   Video stops playing unexpectedly when another video pauses in the same application in Windows 8 or Windows Server 2012

KB3100474   Can’t connect to wireless network when you resume the computer from hibernate mode in Windows

KB3100477   A large file upload or a large repository clone fails on VSO in Windows Server 2012 R2

KB3100527   System becomes unresponsive and crashes on Windows Server 2012 R2-based file servers

KB3100530   Windows backup fails with no sufficient free space on target volume in Windows Server 2012

KB3101217   Client requests take a long time to execute or COM+ application freezes in Windows 7 SP1 or Windows Server 2008 R2 SP1

KB3101694   “0x000000D1″ Stop error in Pacer.sys when there’s heavy QoS traffic in Windows Server 2012 R2

KB3101705   Schema load failures or SPF failures in Windows Server 2012 R2 in Turkey

KB3101718   Application freezes when you switch the system from DC mode to AC mode in Windows 8.1 or Windows Server 2012 R2

KB3102236   Group membership removal operation fails when this operation is for a deleted user account in Windows Server 2008 R2

KB3102242   Computer crashes or restarts unexpectedly when it’s resumed from sleep mode in Windows

KB3102354   Hyper-V generation 2 virtual machines can’t start with some pass-through disks in Windows Server 2012 R2

KB3102770   The chkdsk command together with the spotfix option doesn’t fix extended volumes corruption in Windows Server 2012 R2

KB3103000   RemoteApp windows disappear and screen flickers when you switch between windows in Windows 8.1 or Windows Server 2012 R2

KB3103616   WMI query doesn’t work in Windows Server 2012

KB3105881   Can’t access applications when device authentication is enabled in Windows Server 2012 R2-based AD FS server

Happy patching.

/Jeff

Follow us on Twitter, www.twitter.com/WindowsSDK.


Using SHA256 with the SignedXml Class

$
0
0

With the industry moving away from SHA1 including Microsoft (see http://social.technet.microsoft.com/wiki/contents/articles/32288.windows-enforcement-of-authenticode-code-signing-and-timestamping.aspx), many developers should start using SHA2 in their code.  There are resources on the internet that describe how to use SHA256 with SignedXml. This blog is meant to summarize it in one place.

First of all, we need to register a SignatureDescription class that defines the DigestAlgorithm as SHA256.  The .NET Cryptography namespace implements a class called RSAPKCS1SHA1SignatureDescription that supports SHA1.  So we need a similar class called RSAPKCS1SHA256SignatureDescription that supports SHA256.

If your code is based on .NET 4.5 or higher, there is an RSAPKCS1SHA256SignatureDescription class you can register.  You have to reference the System.Deployment assembly in your project.  The full namespace is System.Deployment.Internal.CodeSigning.RSAPKCS1SHA256SignatureDescription.  You must call CryptoConfig.AddAlgorithm to register the class.

Here’s the MSDN SignedXml sample modified to use SHA256:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.Xml;
using System.Deployment.Internal.CodeSigning;
               
namespace SignVerify
{
    public class SignVerifyEnvelope
    {
        public static void Main(String[] args)
        {
            try
            {
                CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), “http://www.w3.org/2001/04/xmldsig-more#rsa-sha256″);
               
                // Generate a signing key.
                RSACryptoServiceProvider Key = new RSACryptoServiceProvider();
               
                // Create an XML file to sign.
                CreateSomeXml(“Example.xml”);
                Console.WriteLine(“New XML file created.”);
               
                // Sign the XML that was just created and save it in a
                // new file.
                SignXmlFile(“Example.xml”, “signedExample.xml”, Key);
                Console.WriteLine(“XML file signed.”);
               
                // Verify the signature of the signed XML.
                Console.WriteLine(“Verifying signature…”);
                bool result = VerifyXmlFile(“SignedExample.xml”, Key);
               
                // Display the results of the signature verification to
                // the console.
                if (result)
                {
                    Console.WriteLine(“The XML signature is valid.”);
                }
                else
                {
                    Console.WriteLine(“The XML signature is not valid.”);
                }
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);
            }
        }
        // Sign an XML file and save the signature in a new file. This method does not 
        // save the public key within the XML file.  This file cannot be verified unless 
        // the verifying code has the key with which it was signed.
        public static void SignXmlFile(string FileName, string SignedFileName, RSA Key)
        {
            // Create a new XML document.
            XmlDocument doc = new XmlDocument();
               
            // Load the passed XML file using its name.
            doc.Load(new XmlTextReader(FileName));
               
            // Create a SignedXml object.
            SignedXml signedXml = new SignedXml(doc);
               
            // Add the key to the SignedXml document.
            signedXml.SigningKey = Key;
            signedXml.SignedInfo.SignatureMethod = “http://www.w3.org/2001/04/xmldsig-more#rsa-sha256″;
               
            // Create a reference to be signed.
            Reference reference = new Reference();
            reference.Uri = “”;
               
            // Add an enveloped transformation to the reference.           
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            reference.AddTransform(new XmlDsigExcC14NTransform());
            reference.DigestMethod = “http://www.w3.org/2001/04/xmlenc#sha256″;
               
            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);
               
            // Compute the signature.
            signedXml.ComputeSignature();
               
            // Get the XML representation of the signature and save
            // it to an XmlElement object.
            XmlElement xmlDigitalSignature = signedXml.GetXml();
               
            // Append the element to the XML document.
            doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
            if (doc.FirstChild is XmlDeclaration)
            {
                doc.RemoveChild(doc.FirstChild);
            }
               
            // Save the signed XML document to a file specified
            // using the passed string.
            XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));
            doc.WriteTo(xmltw);
            xmltw.Close();
        }
               
        // Verify the signature of an XML file against an asymetric
        // algorithm and return the result.
        public static Boolean VerifyXmlFile(String Name, RSA Key)
        {
            // Create a new XML document.
            XmlDocument xmlDocument = new XmlDocument();
               
            // Load the passed XML file into the document.
            xmlDocument.Load(Name);
               
            // Create a new SignedXml object and pass it
            // the XML document class.
            SignedXml signedXml = new SignedXml(xmlDocument);
               
            // Find the “Signature” node and create a new
            // XmlNodeList object.
            XmlNodeList nodeList = xmlDocument.GetElementsByTagName(“Signature”);
               
            // Load the signature node.
            signedXml.LoadXml((XmlElement)nodeList[0]);
               
            // Check the signature and return the result.
            return signedXml.CheckSignature(Key);
        }
        // Create example data to sign.
        public static void CreateSomeXml(string FileName)
        {
            // Create a new XmlDocument object.
            XmlDocument document = new XmlDocument();
               
            // Create a new XmlNode object.
            XmlNode node = document.CreateNode(XmlNodeType.Element, “”, “MyElement”, “samples”);
               
            // Add some text to the node.
            node.InnerText = “Example text to be signed.”;
               
            // Append the node to the document.
            document.AppendChild(node);
               
            // Save the XML document to the file name specified.
            XmlTextWriter xmltw = new XmlTextWriter(FileName, new UTF8Encoding(false));
            document.WriteTo(xmltw);
            xmltw.Close();
        }
    }
}
               
If your code is based on .NET 4.0 or you prefer not to depend on System.Deployment you can implement your own RSAPKCS1SHA256SignatureDescription class.
Shawn Neal at GitHub provides a good implementation – https://gist.github.com/sneal/f35de432115b840c4c1f#file-rsapkcs1sha256signaturedescription.  
One thing though, Microsoft recommends that you avoid using any managed classes.  You should change SHA256Managed to SHA256CryptoServiceProvider.
.NET versions below 4.0 won’t work because the CryptoConfig class did not provide the AddAlgorithm method to add additional algorithms to the internal algorithm table.
                             

SHA-1 Code Signing Deprecation in Windows beginning January 1, 2016

$
0
0

This post is to help the product team spread the word on Windows (version 7 and higher) and Windows Server will no longer trust any code that is signed with a SHA-1 code signing certificate and that contains a timestamp value greater than January 1,2016, effective January 1, 2016.

For more information or to get the latest information on this topic, please check out the following WIKI on Microsoft Technet, http://aka.ms/sha1

Hotfixes for December 2015

$
0
0

Jeff here, from the SDK team with the Holiday Hotfixes. Happy patching.

KB2920591   High CPU usage and performance issues occur when access-based enumeration is enabled in Windows 7 Service Pack 1 or Windows Server 2008 R2 Service Pack 1

KB3084463   WSUSutil.exe csaimport fails upon import in Windows Server 2012 R2 or Windows Server 2012

KB3095319   You receive an error message when you use GPMC to manage audit policies in Windows 8.1 or Windows Server 2012 R2

KB3102997   Data is corrupted after iSCSI sessions or paths recover in Windows Server 2012 R2 or Windows Server 2012

KB3102998   Application can’t connect to iSCSI servers in Windows Server 2012 R2 or Windows Server 2012

KB3106296   Can’t connect to a wireless network when you resume the computer from hibernation

KB3107128   Search result is incomplete if search criteria contain digits in Windows

KB3108319   VSS backup of the PI Data server fails and the computer crashes in Windows 8.1 or Windows Server 2012 R2

KB3109093   Applications can’t communicate over TCP loopback path in Windows 8.1 or Windows Server 2012 R2

KB3109099   Update adds support for the slow timer in LACP in Windows Server 2012 R2

KB3109156   Applications may freeze when ADSI APIs waits infinitely for server to respond in Windows Server 2012 R2

KB3109600   Users can’t log on to Outlook Web App client from a browser in Windows

KB3109973   Backup fails with a “File Not Found” error on a Windows Server 2012 R2 cluster

KB3114133   Windows Server Backup fails when you back up multiple volumes in Windows Server 2012 R2

Happy Holidays,

/Jeff

Follow us on Twitter, www.twitter.com/WindowsSDK.

Why CryptCATAdminCalcHashFromFileHandle fails with a seemingly unexpected error code

$
0
0

CryptCATAdminCalcHashFromFileHandle can fail when evaluating a file path to an executable while setting the last error code to 0x800700c1.  It’s an HRESULT instead of just an error code, but the relevant portion of the error code is 0xc1 (193L).  That is the error code for ERROR_BAD_EXE_FORMAT.  In some cases, this will happen even though the executable can run without an error.  So why would this function return ERROR_BAD_EXE_FORMAT when directly executing the file works without issue?

There are actually several reasons why this error can be returned, and only some of them would actually prevent an executable from being able to run on an unrestricted system.  All of them come from the portable executable (PE) header of the file.  The types used below can be found in the Windows SDK, primarily in winnt.h.  Here are most of the reasons:

  • PIMAGE_DOS_HEADER->e_magic is an invalid value
  • PIMAGE_DOS_HEADER->e_lfanew is an invalid value
  • PIMAGE_NT_HEADERS->Signature is an invalid value
  • PIMAGE_NT_HEADERS->FileHeader.SizeOfOptionalHeader is an invalid value
  • PIMAGE_NT_HEADERS->FileHeader.Machine is an invalid value
  • PIMAGE_NT_HEADERS->OptionalHeader.Magic is an invalid value
  • PIMAGE_NT_HEADERS->OptionalHeader.FileAlignment is an invalid value
  • Any of the populated members of PIMAGE_NT_HEADERS->OptionalHeader.DataDirectory have invalid values
  • The certificate directory (IMAGE_DIRECTORY_ENTRY_SECURITY) has an offset that puts its data in an invalid location; see https://msdn.microsoft.com/en-us/windows/hardware/gg463180 for more details on what the standards for that are.

If you encounter this error on an executable file, these can be identified manually by looking at the output of a couple of tools.  If there’s a problem with the IMAGE_DIRECTORY_ENTRY_SECURITY section, then running SignTool.exe verify /v filename will output “SignTool Error: File not valid: filename”.  The rest of them can be identified by looking through the output of dumpbin.exe.  Dumpbin is available through Visual Studio and SignTool is available through the Windows SDK.

Follow us on Twitter, www.twitter.com/WindowsSDK.

Hotfix for January 2016

Viewing all 126 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>