473,396 Members | 1,866 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

SetLocalTime/SetSystemTime P/Invoke call fails under Vista (even witha requireAdministrator manifest)


I am posting at the end of this post some code that P/Invoke's
SetSystemTime to set the local system time. This call fails -- i.e
the time is not set and the API returns false. However calling
Marshal.GetLastWin32Error immediately afterwards returns an errorcode
of 0 indicating that the operation somehow executed successfully.

This is a plain vanilla console app written in C#. It runs on vista
and has a manifest embedded in it that has 'requireAdministrator'
privilege level on it. The logged on user belongs to the
administrator group and the UAC is set at "prompt for consent".

What am I missing? (FWIW, I didn't write the P/Invoke signatures
myself. I just lifted them out of various postings on the internet --
is there a mistake in that somewhere)?

It seems similar to what was reported here:
http://forums.microsoft.com/MSDN/Sho...07068&SiteID=1

/********** CODE ********************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel;

namespace VistaUACTest
{
class Program
{
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct SystemTime
{
public short year;
public short month;
public short dayOfWeek;
public short day;
public short hour;
public short minute;
public short second;
public short milliseconds;
}

[DllImport("kernel32.dll")]
private static extern bool SetLocalTime(ref SystemTime
systime);

[DllImport("kernel32.dll")]
private static extern bool SetSystemTime(ref SystemTime
systime);

private const int ANYSIZE_ARRAY = 1;
private const string SE_SYSTEMTIME_NAME =
"SeSystemtimePrivilege";
private const int SE_PRIVILEGE_ENABLED = 0x00000002;
private const int TOKEN_QUERY = 0x0008;
private const int TOKEN_ADJUST_PRIVILEGES = 0x0020;

[StructLayout(LayoutKind.Sequential)]
public struct LUID
{
public int LowPart;
public int HighPart;
}

[StructLayout(LayoutKind.Sequential)]
public struct LUID_AND_ATTRIBUTES
{
public LUID Luid;
public int Attributes;
}

[StructLayout(LayoutKind.Sequential)]
public struct TOKEN_PRIVILEGES
{
public int PrivilegeCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst =
ANYSIZE_ARRAY)]
public LUID_AND_ATTRIBUTES[] Privileges;
}

[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
public static extern bool OpenProcessToken(int ProcessHandle,
int DesiredAccess, ref int TokenHandle);

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetCurrentProcess();

[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
public static extern bool LookupPrivilegeValue(string
lpSystemName, string lpName,

[MarshalAs(UnmanagedType.Struct)] ref LUID lpLuid);

[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
public static extern bool AdjustTokenPrivileges(int
TokenHandle,
int
DisableAllPrivileges,

[MarshalAs(UnmanagedType.Struct)] ref TOKEN_PRIVILEGES NewState,
int
BufferLength,

[MarshalAs(UnmanagedType.Struct)] ref TOKEN_PRIVILEGES PreviousState,
ref
int ReturnLength);

static void Main(string[] args)
{
try
{
// because the docs for SetSystemTime says that the
SE_SYSTEMTIME_NAME privilege is disabled by default
// this call doesn't really help though
AdjustPrivileges();
SystemTime st = new SystemTime();
st.hour = 10;
if (!SetSystemTime(ref st))
{
// the return value says the call failed, however
Marshal.GetLastWin32Error() says the previous P/Invoke operation
// completed successfully (the default ctor of
Win32Exception calls GetLastWin32Error)
throw new Win32Exception();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.Read();
}

public static bool AdjustPrivileges()
{
TOKEN_PRIVILEGES tkNew = new TOKEN_PRIVILEGES();
tkNew.Privileges = new LUID_AND_ATTRIBUTES[ANYSIZE_ARRAY];
TOKEN_PRIVILEGES tkOld = new TOKEN_PRIVILEGES();
tkOld.Privileges = new LUID_AND_ATTRIBUTES[ANYSIZE_ARRAY];

LUID luid = new LUID();
int token = -1;
int oldluidSize = 0;

if (LookupPrivilegeValue(null, SE_SYSTEMTIME_NAME, ref
luid))
{
if (OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref token))
{
tkNew.PrivilegeCount = 1;
tkNew.Privileges[0].Attributes =
SE_PRIVILEGE_ENABLED;
tkNew.Privileges[0].Luid = luid;
int luidSize =
Marshal.SizeOf(typeof(TOKEN_PRIVILEGES));
if (AdjustTokenPrivileges(token, 0, ref tkNew,
luidSize, ref tkOld, ref oldluidSize))
{
return true;
}
}
}
return false;
}
}
}
/************ CODE ************************/
Jun 27 '08 #1
2 8369
Well, the signatures for the time APIs are correct (mostly) along with your
SystemTime struct. Win32 BOOL is actually an int. Yes I know the marshalling
will happen automatically, I'm just picky. Might want to turn off the UAC
and try it again to see if that's causing the problem, I had no problem on
my machine with UAC off. If so, there's a problem with how you're elevating
the privileges of the current user.
<rd*****@gmail.comwrote in message
news:d5**********************************@l42g2000 hsc.googlegroups.com...
>
I am posting at the end of this post some code that P/Invoke's
SetSystemTime to set the local system time. This call fails -- i.e
the time is not set and the API returns false. However calling
Marshal.GetLastWin32Error immediately afterwards returns an errorcode
of 0 indicating that the operation somehow executed successfully.

This is a plain vanilla console app written in C#. It runs on vista
and has a manifest embedded in it that has 'requireAdministrator'
privilege level on it. The logged on user belongs to the
administrator group and the UAC is set at "prompt for consent".

What am I missing? (FWIW, I didn't write the P/Invoke signatures
myself. I just lifted them out of various postings on the internet --
is there a mistake in that somewhere)?

It seems similar to what was reported here:
http://forums.microsoft.com/MSDN/Sho...07068&SiteID=1

/********** CODE ********************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel;

namespace VistaUACTest
{
class Program
{
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct SystemTime
{
public short year;
public short month;
public short dayOfWeek;
public short day;
public short hour;
public short minute;
public short second;
public short milliseconds;
}

[DllImport("kernel32.dll")]
private static extern bool SetLocalTime(ref SystemTime
systime);

[DllImport("kernel32.dll")]
private static extern bool SetSystemTime(ref SystemTime
systime);

private const int ANYSIZE_ARRAY = 1;
private const string SE_SYSTEMTIME_NAME =
"SeSystemtimePrivilege";
private const int SE_PRIVILEGE_ENABLED = 0x00000002;
private const int TOKEN_QUERY = 0x0008;
private const int TOKEN_ADJUST_PRIVILEGES = 0x0020;

[StructLayout(LayoutKind.Sequential)]
public struct LUID
{
public int LowPart;
public int HighPart;
}

[StructLayout(LayoutKind.Sequential)]
public struct LUID_AND_ATTRIBUTES
{
public LUID Luid;
public int Attributes;
}

[StructLayout(LayoutKind.Sequential)]
public struct TOKEN_PRIVILEGES
{
public int PrivilegeCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst =
ANYSIZE_ARRAY)]
public LUID_AND_ATTRIBUTES[] Privileges;
}

[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
public static extern bool OpenProcessToken(int ProcessHandle,
int DesiredAccess, ref int TokenHandle);

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetCurrentProcess();

[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
public static extern bool LookupPrivilegeValue(string
lpSystemName, string lpName,

[MarshalAs(UnmanagedType.Struct)] ref LUID lpLuid);

[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
public static extern bool AdjustTokenPrivileges(int
TokenHandle,
int
DisableAllPrivileges,

[MarshalAs(UnmanagedType.Struct)] ref TOKEN_PRIVILEGES NewState,
int
BufferLength,

[MarshalAs(UnmanagedType.Struct)] ref TOKEN_PRIVILEGES PreviousState,
ref
int ReturnLength);

static void Main(string[] args)
{
try
{
// because the docs for SetSystemTime says that the
SE_SYSTEMTIME_NAME privilege is disabled by default
// this call doesn't really help though
AdjustPrivileges();
SystemTime st = new SystemTime();
st.hour = 10;
if (!SetSystemTime(ref st))
{
// the return value says the call failed, however
Marshal.GetLastWin32Error() says the previous P/Invoke operation
// completed successfully (the default ctor of
Win32Exception calls GetLastWin32Error)
throw new Win32Exception();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.Read();
}

public static bool AdjustPrivileges()
{
TOKEN_PRIVILEGES tkNew = new TOKEN_PRIVILEGES();
tkNew.Privileges = new LUID_AND_ATTRIBUTES[ANYSIZE_ARRAY];
TOKEN_PRIVILEGES tkOld = new TOKEN_PRIVILEGES();
tkOld.Privileges = new LUID_AND_ATTRIBUTES[ANYSIZE_ARRAY];

LUID luid = new LUID();
int token = -1;
int oldluidSize = 0;

if (LookupPrivilegeValue(null, SE_SYSTEMTIME_NAME, ref
luid))
{
if (OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref token))
{
tkNew.PrivilegeCount = 1;
tkNew.Privileges[0].Attributes =
SE_PRIVILEGE_ENABLED;
tkNew.Privileges[0].Luid = luid;
int luidSize =
Marshal.SizeOf(typeof(TOKEN_PRIVILEGES));
if (AdjustTokenPrivileges(token, 0, ref tkNew,
luidSize, ref tkOld, ref oldluidSize))
{
return true;
}
}
}
return false;
}
}
}
/************ CODE ************************/
Jun 27 '08 #2
On May 16, 8:30 pm, "Jeff Winn" <jw...@nospam.comwrote:
Well, the signatures for the time APIs are correct (mostly) along with your
SystemTime struct. Win32 BOOL is actually an int. Yes I know the marshalling
will happen automatically, I'm just picky. Might want to turn off the UAC
and try it again to see if that's causing the problem, I had no problem on
my machine with UAC off. If so, there's a problem with how you're elevating
the privileges of the current user.
Jeff
Thanks for responding. The privilege adjusting code is there for no
particular reason. I believe the admin privileges already include
SE_SYSTEMTIME_NAME (which is enabled).

In any case, the funny thing is I can't get it to work even:

* if I run this application from a elevated command prompt
* if I mark the manifest as 'requireAdministrator' and grant consent
to the UAC dialog that pops up.

I thought the latter option was at least morally the same as turning
off UAC? I will turn off UAC and see how that goes.

There is another weird thing going on here. SetSystemTime seems to
return false indicating the call failed (and the time obviously isn't
set), however if I call Marshal.GetLastWin32Error() immediately after,
it returns 0 saying "the operation completed successfully".

Does that make sense to you?
Jun 27 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: smerf | last post by:
I haven't delved into the beast that is Vista from a programming standpoint yet. But, if the blog at http://west-wind.com/WebLog/posts/4983.aspx is any indication of what we're in for.....I say we...
4
by: Podi | last post by:
I am trying to set the system time on my Windows computer, but avoid using the DOS command (date, time). Does anyone know what parameter to pass to function SetLocalTime? CSharp ref...
11
by: =?Utf-8?B?Um9iS2lubmV5MQ==?= | last post by:
Hello, We are testing and tweaking some of our software to run on Vista, but it turns out that we are having problems with one of our programs. Here is our code: // attempt an experiment to...
3
by: =?Utf-8?B?Um9iS2lubmV5MQ==?= | last post by:
Hello, This is a continuation of a question I was working with Willy and Kevin last week (both provided excellent information). I am still having troubles in final stages. I am trying to get...
3
by: gourmet | last post by:
Hello! I need to restart the "Windows Audio Service" (audiosrv) via C#. I'm using the ServiceController Class to do this. It is no problem under XP and no problem under vista if UAC is...
9
by: Bruce | last post by:
Under Vista, the Dev Studio program installer adds a desktop shortcut to the Desktop. (.Net application.) The shortcut does not have a context menu item to run as administrator. However, if you...
13
by: Mark Rae | last post by:
Hi, I have used the code below to return the default printer in 32-bit WinXP Pro, but now that I am running 64-bit Vista Business I'm getting an error: using System.Drawing.Printing; using...
2
by: 13Rockes | last post by:
I am in the process of writing programs using VB6 in XP Pro. However, I am thinking about starting over using VB2005 as my company is migrating to Vista. Two questions... What kinds of...
1
by: rufusking | last post by:
My requirement is to change the IP Address of local system programatically using .net. IP Address should change to 10.1.2.100, subnet mask = 255.255.255.0, default gateway=10.1.2.1 I have...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.