C
C#12mo ago
Wemmer

Finding time source of Windows system using C# (equivalent of w32tm /query /source)

I want to find the current system's time source directly in C#, basically just like the output of w32tm /query /source does. Due to security reasons, the program may not spawn child processes, so just invoking w32tm and getting the output of it is not allowed and does not work. My initial plan was to read the NtpServer configuration for W32Time from the registry as in:
var w32timeRegistryPath = "SYSTEM\\CurrentControlSet\\Services\\W32Time\\Parameters";
using (var w32timeParameters = Registry.LocalMachine.OpenSubKey(w32timeRegistryPath))
{
var ntpServerProperty = w32timeParameters.GetValue("NtpServer");
}
var w32timeRegistryPath = "SYSTEM\\CurrentControlSet\\Services\\W32Time\\Parameters";
using (var w32timeParameters = Registry.LocalMachine.OpenSubKey(w32timeRegistryPath))
{
var ntpServerProperty = w32timeParameters.GetValue("NtpServer");
}
The problem that arises with that approach is that not all systems actually have their time source configured manually like that, but may instead inherit it from their Active Directory domain membership. For those systems the "NtpServer" REG_SZ simply doesn't exist. What I would like to know is if someone is familiar with some other method of getting the equivalent output of w32tm /query /source without spawning a new process to do so. It may effectively be impossible, which I feel like is entirely possible if the necessary API:s to make such a call simply aren't available.
2 Replies
jcotton42
jcotton4212mo ago
might be worth running that command under Process Monitor and seeing what it's querying if it's looking at multiple reg keys, that will tell you
Wemmer
WemmerOP12mo ago
Definitely a bit out of my depth with understanding everything that Process Monitor spits out...
But just going by what it does in regards to the registry, it doesn't seem to do anything with anything in ...CurrentControlSet\Services\W32Time\ whatsoever, and whatever else it reads from the registry doesn't to me make much sense as relevant for the query. However, svchost does access those keys, but again, there's nothing there that actually determines the effective time source. For example, a server might have the value NtpServer set to time.windows.com,0x8 but w32tm /query /source will still respond with the name of a domain controller that in practice provides the time.
Want results from more Discord servers?
Add your server