Asp.net penetration Session 0 isolation (2)

Source: Internet
Author: User

For simple interactions, the service can use the WTSSendMessage function to display the message window on the user Session. For some complex UI interactions, you must call CreateProcessAsUser or other methods (such as WCF and. NET remote processing) for cross-Session communication and create an application interface on the desktop user.

WTSSendMessage Function
If the service simply sends a message window to the desktop user Session, you can use the WTSSendMessage function. First, add an Interop. cs class to the code downloaded in the previous article, and add the following code to the class:

Copy codeThe Code is as follows:
Public static IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr. Zero;

Public static void ShowMessageBox (string message, string title)
{
Int resp = 0;
WTSSendMessage (
WTS_CURRENT_SERVER_HANDLE,
WTSGetActiveConsoleSessionId (),
Title, title. Length,
Message, message. Length,
0, 0, out resp, false );
}

[DllImport ("kernel32.dll", SetLastError = true)]
Public static extern int WTSGetActiveConsoleSessionId ();

[DllImport ("wtsapi32.dll", SetLastError = true)]
Public static extern bool WTSSendMessage (
IntPtr hServer,
Int SessionId,
String pTitle,
Int TitleLength,
String pMessage,
Int MessageLength,
Int Style,
Int Timeout,
Out int pResponse,
Bool bWait );

In the ShowMessageBox function, the WTSSendMessage is called to send the information window, so that we can use it in the OnStart function of the Service. Open Service1.cs and add the following code:
Copy codeThe Code is as follows:
Protected override void OnStart (string [] args)
{
Interop. ShowMessageBox ("This a message from AlertService.", "AlertService Message ");
}

After the program is compiled, restart the AlertService service in the Service Manager. The message window is displayed on the current user's desktop, rather than in Session 0.

CreateProcessAsUser Function

If you want to create a complex UI program interface for the desktop user Session through the service, you need to use the CreateProcessAsUser function to create a new process for the user to run the corresponding program. Open the Interop class and add the following code:

Copy codeThe Code is as follows:
Public static void CreateProcess (string app, string path)
{
Bool result;
IntPtr hToken = WindowsIdentity. GetCurrent (). Token;
IntPtr hDupedToken = IntPtr. Zero;

PROCESS_INFORMATION pi = new PROCESS_INFORMATION ();
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES ();
Sa. Length = Marshal. SizeOf (sa );

STARTUPINFO si = new STARTUPINFO ();
Si. cb = Marshal. SizeOf (si );

Int dwSessionID = WTSGetActiveConsoleSessionId ();
Result = WTSQueryUserToken (dwSessionID, out hToken );

If (! Result)
{
ShowMessageBox ("WTSQueryUserToken failed", "AlertService Message ");
}

Result = DuplicateTokenEx (
HToken,
GENERIC_ALL_ACCESS,
Ref sa,
(Int) SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
(Int) TOKEN_TYPE.TokenPrimary,
Ref hDupedToken
);

If (! Result)
{
ShowMessageBox ("DuplicateTokenEx failed", "AlertService Message ");
}

IntPtr lpEnvironment = IntPtr. Zero;
Result = CreateEnvironmentBlock (out lpEnvironment, hDupedToken, false );

If (! Result)
{
ShowMessageBox ("CreateEnvironmentBlock failed", "AlertService Message ");
}

Result = CreateProcessAsUser (
HDupedToken,
App,
String. Empty,
Ref sa, ref sa,
False, 0, IntPtr. Zero,
Path, ref si, ref pi );

If (! Result)
{
Int error = Marshal. GetLastWin32Error ();
String message = String. Format ("CreateProcessAsUser Error: {0}", error );
ShowMessageBox (message, "AlertService Message ");
}

If (pi. hProcess! = IntPtr. Zero)
CloseHandle (pi. hProcess );
If (pi. hThread! = IntPtr. Zero)
CloseHandle (pi. hThread );
If (hDupedToken! = IntPtr. Zero)
CloseHandle (hDupedToken );
}

[StructLayout (LayoutKind. Sequential)]
Public struct STARTUPINFO
{
Public Int32 cb;
Public string lpReserved;
Public string lpDesktop;
Public string lpTitle;
Public Int32 dwX;
Public Int32 dwY;
Public Int32 dwXSize;
Public Int32 dwXCountChars;
Public Int32 dwYCountChars;
Public Int32 dwFillAttribute;
Public Int32 dwFlags;
Public Int16 wShowWindow;
Public Int16 cbReserved2;
Public IntPtr lpReserved2;
Public IntPtr hStdInput;
Public IntPtr hStdOutput;
Public IntPtr hStdError;
}

[StructLayout (LayoutKind. Sequential)]
Public struct PROCESS_INFORMATION
{
Public IntPtr hProcess;
Public IntPtr hThread;
Public Int32 dwProcessID;
Public Int32 dwThreadID;
}

[StructLayout (LayoutKind. Sequential)]
Public struct SECURITY_ATTRIBUTES
{
Public Int32 Length;
Public IntPtr lpSecurityDescriptor;
Public bool bInheritHandle;
}

Public enum SECURITY_IMPERSONATION_LEVEL
{
SecurityAnonymous,
SecurityIdentification,
SecurityImpersonation,
SecurityDelegation
}

Public enum TOKEN_TYPE
{
TokenPrimary = 1,
TokenImpersonation
}

Public const int GENERIC_ALL_ACCESS = 0x10000000;

[DllImport ("kernel32.dll", SetLastError = true,
CharSet = CharSet. Auto, CallingConvention = CallingConvention. StdCall)]
Public static extern bool CloseHandle (IntPtr handle );

[DllImport ("advapi32.dll", SetLastError = true,
CharSet = CharSet. Ansi, CallingConvention = CallingConvention. StdCall)]
Public static extern bool CreateProcessAsUser (
IntPtr hToken,
String lpApplicationName,
String lpCommandLine,
Ref SECURITY_ATTRIBUTES lpProcessAttributes,
Ref SECURITY_ATTRIBUTES lpThreadAttributes,
Bool bInheritHandle,
Int32 dwCreationFlags,
IntPtr lpEnvrionment,
String lpCurrentDirectory,
Ref STARTUPINFO lpStartupInfo,
Ref PROCESS_INFORMATION lpProcessInformation );

[DllImport ("advapi32.dll", SetLastError = true)]
Public static extern bool DuplicateTokenEx (
IntPtr hExistingToken,
Int32 dwDesiredAccess,
Ref SECURITY_ATTRIBUTES lpThreadAttributes,
Int32 ImpersonationLevel,
Int32 dwTokenType,
Ref IntPtr phNewToken );

[DllImport ("wtsapi32.dll", SetLastError = true)]
Public static extern bool WTSQueryUserToken (
Int32 sessionId,
Out IntPtr Token );

[DllImport ("userenv. dll", SetLastError = true)]
Static extern bool CreateEnvironmentBlock (
Out IntPtr lpEnvironment,
IntPtr hToken,
Bool bInherit );

The CreateProcess function also involves the use of DuplicateTokenEx, WTSQueryUserToken, and CreateEnvironmentBlock functions. If you are interested, you can learn through MSDN. After the CreateProcess function is created, you can actually use it to call the application. Return to Service1.cs and modify OnStart to open a CMD window. The following code:
Copy codeThe Code is as follows:
Protected override void OnStart (string [] args)
{
Interop. CreateProcess ("cmd.exe", @ "C: \ Windows \ System32 \");
}

Recompile the program and start the AlertService service to view the interface. So far, we can solve the Session 0 isolation problem through some simple methods. You can also use technologies such as WCF to complete more complex cross-Session communication methods, and implement interaction between services and desktop users in Windows 7 and Vista.

References

1. WTSSendMessage Function
The http://msdn.microsoft.com/en-us/library/aa383842 (VS.85). aspx

2. CreateProcessAsUser Function
Http://msdn.microsoft.com/en-us/library/ms682429 (v = VS.85). aspx

3. WTSSendMessage (wtsapi32)
Http://www.pinvoke.net/default.aspx/wtsapi32/WTSSendMessage.html

4. WTSQueryUserToken Function
The http://msdn.microsoft.com/en-us/library/aa383840 (VS.85). aspx

5. http://www.pinvoke.net/

Code download AlertService2_jb51.rar

Author: Li jingran (Gnie)
Source: {GnieTech} (http://www.cnblogs.com/gnielee)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.