FtpFindFirstFile error using wininet.dll - c#

I'm having a problem with my FtpFindFirstFile function on my C# project. Basically this function is just to search the specified directory for a file that I mention in my program, but an error appears right before the function is finish executing, here's the screenshot of the error:
---------------START CODE------------------
[System.Runtime.InteropServices.DllImport("wininet.dll", EntryPoint = "InternetOpen", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
static extern IntPtr InternetOpen(
string lpszAgent, int dwAccessType, string lpszProxyName,
string lpszProxyBypass, int dwFlags);
[System.Runtime.InteropServices.DllImport("wininet.dll", EntryPoint = "InternetConnect", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
extern public static IntPtr /*IntPtr*/ InternetConnect(
IntPtr hInternet, string lpszServerName, int nServerPort,
string lpszUsername, string lpszPassword, int dwService,
int dwFlags, int dwContext);
[System.Runtime.InteropServices.DllImport("wininet.dll", EntryPoint = "FtpFindFirstFile", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
extern public static IntPtr FtpFindFirstFile(
IntPtr hConnect, string searchFile, out WIN32_FIND_DATA findFileData,
int flags, IntPtr context);
#region WIN32_Structure
public struct WIN32_FIND_DATA
{
public int dwFileAttributes;
public int nFileSizeHigh;
public int nFileSizeLow;
public int dwReserved0;
public int dwReserved1;
public string cFileName;
public string cAlternateFileName;
}
#endregion
public void PerformFTP(string HostIP, string logUsrName, string LogPwd, string SendType, string DefaultDir, string fileExtension)
{
#region Declaration
WIN32_FIND_DATA win32 = new WIN32_FIND_DATA();
bool pRoceed;
#endregion
pRoceed = true;
/* Initialize Internet Connection */
IntPtr hInternet = InternetOpen("browser", INTERNET_OPEN_TYPE_DIRECT, null, null, 0);
//IntPtr hInternet = InternetOpen("browser", 1, null, null, 0);
if (hInternet == IntPtr.Zero)
{
MessageBox.Show(hInternet.ToString(), "");
MessageBox.Show(System.Runtime.InteropServices.Marshal.GetLastWin32Error().ToString());
}
/* Initialize FTP Connection */
IntPtr hFTPhandle = InternetConnect(hInternet, HostIP, INTERNET_DEFAULT_FTP_PORT, logUsrName, LogPwd, INTERNET_SERVICE_FTP, INTERNET_FLAG_PASSIVE, 0);
//IntPtr hFTPhandle = InternetConnect(hInternet, "203.177.252.123", 21, "bomoracle", "bomoracle", 1, 0, 0);
/* To check if the FTP connection succeeded */
if (hFTPhandle == IntPtr.Zero)
{
pRoceed = false;
MessageBox.Show(hFTPhandle.ToString(), "");
MessageBox.Show(System.Runtime.InteropServices.Marshal.GetLastWin32Error().ToString());
return;
}
//IntPtr hFind = FtpFindFirstFile(hFTPhandle, "*.DAT" /*+ fileExtension*/ , out win32, 0, IntPtr.Zero);
IntPtr hFind = FtpFindFirstFile(hFTPhandle, "*.DAT" , out win32, 0, IntPtr.Zero); **//THIS IS WHERE THE ERROR APPEARS**
if (hFind == IntPtr.Zero)
{
if (System.Runtime.InteropServices.Marshal.GetLastWin32Error().ToString() == "RROR_NO_MORE_FILES")
{
MessageBox.Show("NO MORE .BOM FILES","EMPTY");
}
MessageBox.Show("SEARCHING IN THE DIRECTORY FAILED! ", "EMPTY");
}
}
---------------END CODE------------------
Here's the error message, it appears right before executing the if-else condition:
"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
I don't know what's causing the error, I was just searching the directory, I haven't done any get or put command on that ftp process. Hope you can help! Thanks!

I cann't answer your specific question but I strongly feel there is already a managed solution. Remember that you only need to fallback to interop when the framework has no implementation that suits your needs.
var request = (FtpWebRequest)WebRequest.Create("ftp://example.com/");
request.Credentials= new NetworkCredential("username", "password");
// List files
request.Method = WebRequestMethods.Ftp.ListDirectory;
var resp = (FtpWebResponse) request.GetResponse();
var stream = resp.GetResponseStream();
var readStream = new StreamReader(resp.GetResponseStream(), System.Text.Encoding.UTF8);
// handle the incoming stream, store in a List, print, find etc
var files = new List<String>();
if (readStream != null)
{
while(!readStream.EndOfStream)
{
files.Add(readStream.ReadLine());
}
}
// showe them
foreach(var file in files)
{
Console.WriteLine(file);
}
// find one
var fileToFind = "Public";
var foundFile = files.Find( f => f == fileToFind);
Console.WriteLine("found file {0}:", foundFile);
// show status
Console.WriteLine("List status: {0}",resp.StatusDescription);
In this snippet I used:
FtpWebResponse
FtpWebRequest
WebRequestMethods.Ftp
List.Find
StreamReader

Related

Read firefox passwords: System.ArgumentNullException

I have this funtion, and i get this exception:
"System.ArgumentNullException: The value cannot be null, name of parameter: ptr in System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointer(IntPtr ptr, Type t)"
Here is my code:
private const string ffFolderName = #"\Mozilla Firefox\";
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllFilePath);
static IntPtr NSS3;
[DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate long DLLFunctionDelegate(string configdir);
public static int PK11SDR_Decrypt(ref TSECItem data, ref TSECItem result, int cx)
{
IntPtr pProc = GetProcAddress(NSS3, "PK11SDR_Decrypt");
DLLFunctionDelegate5 dll = (DLLFunctionDelegate5)Marshal.GetDelegateForFunctionPointer(pProc, typeof(DLLFunctionDelegate5));
return dll(ref data, ref result, cx);
}
public static long NSS_Init(string configdir)
{
var mozillaPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + ffFolderName;
if (!System.IO.Directory.Exists(mozillaPath))
mozillaPath = #"C:\\Program Files\\" + ffFolderName;
if (!System.IO.Directory.Exists(mozillaPath))
throw new Exception("Firefox folder not found");
LoadLibrary(mozillaPath + "mozglue.dll");
NSS3 = LoadLibrary(mozillaPath + "nss3.dll");
IntPtr pProc = GetProcAddress(NSS3, "NSS_Init");
// Below throws the exception
DLLFunctionDelegate dll = (DLLFunctionDelegate)Marshal.GetDelegateForFunctionPointer(pProc, typeof(DLLFunctionDelegate));
return dll(configdir);
}
I really dont get it, when I debug, it throws an exception before the return on the function "NSS_Init", and the pProc variable have the value of "0x00000000", I don't know if it's supposed to get this value, and if it is, how can I solve this?
Thank's to all of you.

Reading printer data using ReadPrinter Winspool.Drv

I have Zebra printer connected via USB and I'm trying to read printer's memory using command ^XA^HWR:^XZ. The command works on TCP/IP.
I'm not even sure if I have method header right.
[DllImport("winspool.Drv", EntryPoint = "ReadPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
static extern bool ReadPrinter(IntPtr hPrinter, IntPtr pBuf, int cbBuf, out int pNoBytesRead);
Method ReadPrinter always returns false and 0 read bytes. When I'm trying to get LastWin32Error, I'm getting a variety of 0, 6 or 63 (ERROR_SUCCESS - although it returns false and no data, ERROR_INVALID_HANDLE or ERROR_PRINT_CANCELLED), depending on that I'm trying. I've tried several method headers and different approaches but none of them lead to the success data read. I have 'bidirectional support' enabled and printer drivers installed. It may seem as duplicates of other threads, but I've already got through them and none of them was helpful.
Code snippet:
private static void SendBytesToPrinter(string printerName, IntPtr pointerBytes, int bytesCount)
{
int written = 0;
PrintResult printResult = new PrintResult();
IntPtr pointerPrinter = new IntPtr(0);
DOCINFOA docInfo = new DOCINFOA();
bool success = false;
docInfo.DocName = "RAW Document";
docInfo.DataType = "RAW";
try
{
if (OpenPrinter(printerName.Normalize(), out pointerPrinter, IntPtr.Zero))
{
if (StartDocPrinter(pointerPrinter, 1, docInfo))
{
if (StartPagePrinter(pointerPrinter))
{
success = WritePrinter(pointerPrinter, pointerBytes, bytesCount, out written);
EndPagePrinter(pointerPrinter);
}
EndDocPrinter(pointerPrinter);
}
// READ HERE
Int32 bufLen = 32;
IntPtr pStatus = Marshal.AllocCoTaskMem(bufLen);
Int32 statusLen = 0;
bool bSuccess = ReadPrinter(hPrintJob, pStatus, bufLen, out statusLen);
ClosePrinter(pointerPrinter);
}
} catch (Exception ex) { }
}
I solved it by using Visual Basic example, using FileStreams and StreamReaders. Thanks to #kunif for pointing out the sample code.
kernel32.dll is way to go instead of winspool.Drv
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern SafeFileHandle CreateFile(string lpFileName, EFileAccess dwDesiredAccess,
EFileShare dwShareMode, IntPtr lpSecurityAttributes,
ECreationDisposition dwCreationDisposition,
EFileAttributes dwFlagsAndAttributes,
IntPtr hTemplateFile);
private static string ReadUsbPort(StreamReader sr)
{
string readResult = string.Empty;
if (sr != null && sr.BaseStream != null)
{
do
{
readResult += sr.ReadLine();
readResult += "\r";
}
while (sr.EndOfStream == false);
}
return readResult;
}
Very useful is combination of
GUID_DEVINTERFACE_USB_DEVICE and WinUSBNet

Impersonate Access Token with Backup And Restore Privilege for Copying File Across Domain

Computer A is on Domain A
Computer B is on Domain B
Domain A and Domain B have a trust allowing Accounts to connect to the other domain's computers
Account A is Admin on Computer A and has Backup&Restore Privileges
Account B is Admin on Computer B and has Backup&Restore Privileges
Account A IS NOT Admin on Computer B and does not have Backup&Restore Privileges
Account B IS NOT Admin on Computer A and does not have Backup&Restore Privileges
A person owns both Account A and Account B.
They want to copy a file from Computer A to Computer B.
They wish to copy this file from and into a folder they do not have permissions for. Therefore, they must both enable Backup&Restore Privileges on their Access Token they got from LogonUser
It is not allowed to change the DACL to grant these permissions on any folders or files and instead both Account A and Account B must enable B&R privileges which is recognized by the Computer, only then will they be able to copy the file without Access Denied.
The problem is I have tried using NETWORK, INTERACTIVE, and NEW_CREDENTIALS Access Tokens and enabling privileges on them, but only NETWORK contains the privileges and they are already enabled by default. Then when I try to WindowsIdentity.Impersonate the NETWORK token and then call "CreateFile" to open the file with privileges, it fails and returns an invalid file handle of -1. I can use INTERACTIVE to read an unrestricted file but it didn't have Access Token Privileges needed ( SeBackupPrivilege & SeRestorePrivilege ) when it was returned from LogonUser. I assume once Impersonate happens it generates a Token that "might" have those privileges, but I assume that's based on the machine the code is running on.
Is there a way to Impersonate Access Token -> Enable Access Token B&R Privileges on the remote computers they would have normally when at that machine running as administrator which could be enabled.
OR
Is there a way to use the NETWORK Token with Impersonation to successfully copy the file from Computer on Domain A to Computer on Domain B. If I run the program as Account B who isn't admin trying to impersonate Account A with network credential, it appears to not work on impersonation
Below is demo code in a Console Application that emulates the situation. You must change parts of it to test it accordingly:
You must create the file paths and the file to be read.
You must edit permissions on "DENYTHEIMPERSONATINGUSERHERE" folder so the impersonating user account is denied and must use privileges.
You must enter an actual account credentials to get an AccessToken.
class Program
{
static void Main(string[] args)
{
//Credentials of Account A
string usernameA = "AccountA";
string DomainA = "DomainA.com";
SecureString passwordA = new SecureString();
passwordA.AppendChar('P');
passwordA.AppendChar('W');
passwordA.AppendChar('D');
passwordA.AppendChar('A');
IntPtr AccessToken = IntPtr.Zero;
//Getting Network Access Token. (Network is an Impersonation Token, most other types are returned as Primary Tokens)
AccessTokenHelper.LOGON32_LOGONERROR lgnCode = AccessTokenHelper.GetAccessToken(DomainA, usernameA, passwordA, AccessTokenHelper.LOGON32_LOGONTYPE.LOGON32_LOGON_NETWORK, AccessTokenHelper.LOGON32_LOGONPROVIDER.LOGON32_PROVIDER_WINNT50, out AccessToken);
/*
//Getting INTERACTIVE Access Token. (returns Primary Token)
//Impersonation will work but won't have enabled privileges so will error when trying to write file.
AccessTokenHelper.LOGON32_LOGONERROR lgnCode = AccessTokenHelper.GetAccessToken(DomainA, usernameA, passwordA, AccessTokenHelper.LOGON32_LOGONTYPE.LOGON32_LOGON_INTERACTIVE, AccessTokenHelper.LOGON32_LOGONPROVIDER.LOGON32_PROVIDER_WINNT50, out AccessToken);
*/
if(AccessToken == IntPtr.Zero || AccessToken.ToInt32() == -1)
{
//Not valid creds
System.Diagnostics.Debug.WriteLine(lgnCode.ToString());
return;
}
//Enable Token Security Privileges
AccessTokenHelper.ElevateSecurityPrivileges(AccessToken);
//List Enabled Token Privileges
List<string> tokenEnabledPrivileges = AccessTokenHelper.ListEnabledPrivileges(AccessToken);
foreach(string s in tokenEnabledPrivileges)
{
System.Diagnostics.Debug.WriteLine(s);
}
string sourceFile = #"C:\Temp\Test1\TestData.txt";
string destFile = #"C:\Temp\Test1\DENYTHEIMPERSONATINGUSERHERE\PrivCopy.txt";
bool bCopied = PrivilegedEnterpriseCopyFile(sourceFile, destFile, AccessToken, AccessToken);
System.Diagnostics.Debug.WriteLine("DID THE COPY WORK? " + bCopied.ToString().ToUpper());
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr CreateFile(
string lpFileName,
uint dwDesiredAccess,
OPENFILE_SHAREACCESS dwShareMode, //If you are reading folders you better have OPENFILE_SHAREACCESS.FILE_SHARE_READ
IntPtr SecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile
);
private enum OPENFILE_SHAREACCESS : uint
{
NO_SHARING = 0x00000000,
FILE_SHARE_READ = 0x00000001,
FILE_SHARE_WRITE = 0x00000002,
FILE_SHARE_DELETE = 0x00000004
};
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool GetFileSizeEx(IntPtr hFile, out long lpFileSize);
/// <summary>
/// Goal: Enterprise Level Copy.... can copy file data between remote machines between domains.
/// </summary>
public static bool PrivilegedEnterpriseCopyFile(string sourceAbsoluteFileName, string destAbsoluteFileName, IntPtr sourceAccessToken, IntPtr destAccessToken, bool bOverwrite = false)
{
const uint GENERIC_READ = 0x80000000;
const uint GENERIC_WRITE = 0x40000000; //If you are writing to a file, best allow both READ and WRITE because Windows Performance suffers without.
const uint CREATE_ALWAYS = 2; //Create and overwrite if necesarry
const uint OPEN_EXISTING = 3; //Open only if exists
const uint FILE_FLAG_BACKUP_SEMANTICS = 0x02000000; //This makes it take enabled Backup&Restore privileges into account
const uint FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000; //This helps speed up reading.
const uint FILE_FLAG_WRITE_THROUGH = 0x80000000; //This helps speed up writing!
//We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K).
// The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant
// improvement in Copy performance.
const int DefaultCopyBufferSize = 81920; //80kb
bool bSuccess = false;
//Get File Ptr Handles. DO NOT ALLOW DELETE ON SOURCE OR DEST WHILE THIS IS HAPPENING.
//Get the file pointer by using an access token with access.
IntPtr pSource = IntPtr.Zero;
IntPtr pDest = IntPtr.Zero;
//As source user, connect for optimized READING
using (WindowsImpersonationContext impersonatedUser = WindowsIdentity.Impersonate(sourceAccessToken))
{
pSource = CreateFile(sourceAbsoluteFileName, GENERIC_READ, OPENFILE_SHAREACCESS.FILE_SHARE_READ,
IntPtr.Zero, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_SEQUENTIAL_SCAN, IntPtr.Zero);
}
if (pSource == IntPtr.Zero || pSource.ToInt32() == -1)
{
//Failed to get Source, return false
return bSuccess;
}
//Get Dest Path
string DestPath = Path.GetDirectoryName(destAbsoluteFileName);
string DestFileName = Path.GetFileName(destAbsoluteFileName);
//As dest user
using (WindowsImpersonationContext impersonatedUser = WindowsIdentity.Impersonate(destAccessToken))
{
try
{
bool bProceed = true;
if (!bOverwrite)
{
//We don't want to overwrite existing file, ensure it doesn't exist.
List<string> files = Directory.EnumerateFiles(DestPath).ToList();
if (files.Any(s => s.Equals(DestFileName, StringComparison.OrdinalIgnoreCase)))
{
//File exists, do not proceed
bProceed = false;
}
}
//Do we proceed?
if (bProceed)
{
//Create/Overwrite existing File
pDest = CreateFile(destAbsoluteFileName, GENERIC_READ | GENERIC_WRITE, OPENFILE_SHAREACCESS.NO_SHARING,
IntPtr.Zero, CREATE_ALWAYS,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_WRITE_THROUGH, IntPtr.Zero);
}
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
//If we successfully have both File Handles, we can proceed with Reading from source and writing to Dest.
//If valid file pointers!!!
if (pSource != IntPtr.Zero && pSource.ToInt32() != -1 &&
pDest != IntPtr.Zero && pDest.ToInt32() != -1)
{
//Put Handle into more supported SafeFileHandle Ptr.
SafeFileHandle safeSourcePtr = new SafeFileHandle(pSource, false); //We will close handle manually
SafeFileHandle safeDestPtr = new SafeFileHandle(pDest, false); //We will close handle manually
try
{
using (FileStream fsSource = new FileStream(safeSourcePtr, FileAccess.Read, DefaultCopyBufferSize))
{
using (FileStream fsDest = new FileStream(safeDestPtr, FileAccess.ReadWrite, DefaultCopyBufferSize))
{
//Here we read X bytes up to limit from fsSource and write to fsDest, until no more bytes!
// Read the source file into a byte array.
byte[] buffer = new byte[DefaultCopyBufferSize];
int bytesRead = -1;
while ((bytesRead = fsSource.Read(buffer, 0, buffer.Length)) > 0)
{
fsDest.Write(buffer, 0, bytesRead);
}
//Force data to be flushed to harddisk.
fsDest.Flush(true);
}
}
}
catch { }
//Compare File Size to know if we successfully wrote bytes to destination!
//We'll assume it'd error out if it didn't.
GetFileSizeEx(pSource, out long sourceSize);
GetFileSizeEx(pDest, out long destSize);
if (sourceSize == destSize)
{
//consider it a success
bSuccess = true;
}
}
if (pSource != IntPtr.Zero && pSource.ToInt32() != -1)
{
//Close file handle manually
CloseHandle(pSource);
}
if (pDest != IntPtr.Zero && pDest.ToInt32() != -1)
{
//Close file handle manually
CloseHandle(pDest);
}
return bSuccess;
}
}
public class AccessTokenHelper
{
public enum LOGON32_LOGONTYPE : int
{
LOGON32_LOGON_INTERACTIVE = 2,
LOGON32_LOGON_NETWORK = 3,
LOGON32_LOGON_BATCH = 4,
LOGON32_LOGON_SERVICE = 5,
LOGON32_LOGON_UNLOCK = 7,
LOGON32_LOGON_NETWORK_CLEARTEXT = 8,
LOGON32_LOGON_NEW_CREDENTIALS = 9,
};
public enum LOGON32_LOGONPROVIDER : int
{
LOGON32_PROVIDER_DEFAULT = 0,
LOGON32_PROVIDER_WINNT40 = 2,
LOGON32_PROVIDER_WINNT50 = 3,
};
public enum LOGON32_LOGONERROR : int
{
ERROR_SUCCESS = 0,
ERROR_NO_LOGON_SERVERS = 1311,
ERROR_INVALID_ACCOUNT_NAME = 1315,
ERROR_LOGON_FAILURE = 1326,
ERROR_ACCOUNT_RESTRICTION = 1327,
ERROR_INVALID_LOGON_HOURS = 1328,
ERROR_INVALID_WORKSTATION_LOGONDENIED = 1329,
ERROR_PASSWORD_EXPIRED = 1330,
ERROR_ACCOUNT_DISABLED = 1331,
ERROR_INVALID_LOGON_TYPE = 1367,
ERROR_LOGON_NOT_GRANTED = 1380,
ERROR_NETLOGON_NOT_STARTED = 1792,
ERROR_ACCOUNT_EXPIRED = 1793,
ERROR_PASSWORD_MUST_CHANGE = 1907,
ERROR_ACCOUNT_LOCKED_OUT = 1909,
};
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private extern static bool LogonUser(string username, string domain, IntPtr password, LOGON32_LOGONTYPE logonType, LOGON32_LOGONPROVIDER logonProvider, out IntPtr token);
/// <summary>
/// Attempts to create Access token from information given.
/// </summary>
public static LOGON32_LOGONERROR GetAccessToken(string domain, string username, SecureString securepassword, LOGON32_LOGONTYPE eLOGONTYPE, LOGON32_LOGONPROVIDER eLOGONPROVIDER, out IntPtr token)
{
token = IntPtr.Zero;
// Marshal the SecureString to unmanaged memory. I hate doing this but it's currently most secure way offered by Microsoft to get Access Token from Credentials.
IntPtr passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(securepassword);
bool bSuccess = LogonUser(username,
domain,
passwordPtr,
eLOGONTYPE,
eLOGONPROVIDER,
out token);
//return the error code, useful if not successful.
int errResult = Marshal.GetLastWin32Error();
// Zero-out and free the unmanaged string reference.
Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr);
return (LOGON32_LOGONERROR)errResult;
}
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool LookupPrivilegeName(string lpSystemName, IntPtr lpLuid, StringBuilder lpName, ref int cchName);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool LookupPrivilegeDisplayName(string systemName, string privilegeName, StringBuilder displayName, ref int cchDisplayName, out uint languageId);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, out long lpLuid);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool AdjustTokenPrivileges(
IntPtr TokenHandle,
[MarshalAs(UnmanagedType.Bool)]bool DisableAllPrivileges,
ref TOKEN_PRIVILEGES NewState,
uint prevStateBuffer,
IntPtr prevStateNA,
IntPtr prevBufferNA);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool GetTokenInformation(
IntPtr hToken,
uint TokenInformationClass,
IntPtr TokenInformation,
int TokenInformationLength,
out int ReturnLength);
[StructLayout(LayoutKind.Sequential)]
public struct LUID
{
public uint LowPart;
public uint HighPart;
};
[StructLayout(LayoutKind.Sequential)]
public struct LUID_AND_ATTRIBUTES
{
public LUID Luid;
public uint Attributes;
}
[StructLayout(LayoutKind.Sequential)]
public struct TOKEN_PRIVILEGES
{
public int PrivilegeCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
public LUID_AND_ATTRIBUTES[] Privileges;
};
[Flags]
public enum SE_PRIVILEGE_STATE : uint
{
SE_PRIVILEGE_DISABLED = 0x00,
SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x01,
SE_PRIVILEGE_ENABLED = 0x02,
SE_PRIVILEGE_REMOVED = 0x04,
SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000
};
/// <summary>
/// Will elevate Backup and Restore Privileges of Access Token (be it Primary Type or Impersonation Type) if Access Token has Privilege
/// 1) SeBackupPrivilege -- this grants read access regardless of DACL entries.
/// 2) SeRestorePrivilege -- this grants write access regardless of DACL entries.
/// 3) SeSecurityPrivilege -- this grants access to SACL for audits/security log.
/// </summary>
public static void ElevateSecurityPrivileges(IntPtr hToken, bool bEnabled = true)
{
SE_PRIVILEGE_STATE privSTATE = bEnabled ? SE_PRIVILEGE_STATE.SE_PRIVILEGE_ENABLED : SE_PRIVILEGE_STATE.SE_PRIVILEGE_DISABLED;
List<string> SecurityPrivNames = new List<string>() { "SeBackupPrivilege", "SeRestorePrivilege", "SeSecurityPrivilege" };
if (hToken != IntPtr.Zero)
{
AdjustAccessTokenPrivileges(hToken, SecurityPrivNames, privSTATE);
}
}
public static void AdjustAccessTokenPrivileges(IntPtr TokenHandle, List<string> PrivilegeNames, SE_PRIVILEGE_STATE eNewPrivilegeState, string remoteMachineName = null)
{
if (TokenHandle != IntPtr.Zero && PrivilegeNames != null && PrivilegeNames.Count > 0)
{
DataTable privDT = GetAccessTokenPrivilegesAsDataTable(TokenHandle, remoteMachineName);
if (privDT != null && privDT.Rows.Count > 0)
{
//If we have privileges, try to set state!
foreach (string privName in PrivilegeNames)
{
DataRow row = privDT.Select(string.Format("[{0}]='{1}'", privDT.Columns[1].ColumnName, privName)).FirstOrDefault();
if (row != null)
{
UpdateExistingTokenPrivilege(TokenHandle, row.Field<LUID>(0), eNewPrivilegeState);
}
}
}
}
}
private static bool UpdateExistingTokenPrivilege(IntPtr tokenHandle, LUID privLuid, SE_PRIVILEGE_STATE eNewPrivilegeState)
{
//Create our updated tokenPriv to send what privs we want updated.
TOKEN_PRIVILEGES tokenPrivs = new TOKEN_PRIVILEGES();
tokenPrivs.PrivilegeCount = 1;
tokenPrivs.Privileges = new LUID_AND_ATTRIBUTES[] { new LUID_AND_ATTRIBUTES() { Luid = privLuid, Attributes = (uint)eNewPrivilegeState } };
//Adjust Token Privilege!
bool bSuccess = AdjustTokenPrivileges(tokenHandle, false, ref tokenPrivs, 0, IntPtr.Zero, IntPtr.Zero);
//Return result of trying to adjust token privilege.
return bSuccess;
}
public static DataTable GetAccessTokenPrivilegesAsDataTable(IntPtr TokenHandle, string remoteMachineName = null)
{
TOKEN_PRIVILEGES tokenPrivData = GetAccessTokenPrivileges(TokenHandle);
DataTable privDT = new DataTable();
privDT.Columns.Add("PrivilegeLUID", typeof(LUID));
privDT.Columns.Add("PrivilegeName");
privDT.Columns.Add("PrivilegeState", typeof(SE_PRIVILEGE_STATE));
foreach (LUID_AND_ATTRIBUTES privData in tokenPrivData.Privileges)
{
string PrivilegeName = LookupPrivilegeName(privData.Luid, remoteMachineName);
if (!string.IsNullOrEmpty(PrivilegeName))
{
DataRow row = privDT.NewRow();
row[0] = privData.Luid;
row[1] = PrivilegeName;
row[2] = (SE_PRIVILEGE_STATE)privData.Attributes;
//Add Row
privDT.Rows.Add(row);
}
}
return privDT;
}
private static TOKEN_PRIVILEGES GetAccessTokenPrivileges(IntPtr TokenHandle)
{
uint TOKEN_INFORMATION_CLASS_TokenPrivileges = 3;
if (TokenHandle != IntPtr.Zero)
{
int nBufferSize = 0;
bool TokenInfoResult;
//First call is to get buffer size!
TokenInfoResult = GetTokenInformation(TokenHandle, TOKEN_INFORMATION_CLASS_TokenPrivileges, IntPtr.Zero, nBufferSize, out nBufferSize);
//Allocate Token Info correctly.
IntPtr pTokenInfo = Marshal.AllocHGlobal(nBufferSize);
//Get our Token Info Data
TokenInfoResult = GetTokenInformation(TokenHandle, TOKEN_INFORMATION_CLASS_TokenPrivileges, pTokenInfo, nBufferSize, out nBufferSize);
if (TokenInfoResult)
{
TOKEN_PRIVILEGES returnedPrivilegeSet = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(pTokenInfo, typeof(TOKEN_PRIVILEGES));
int PrivilegeCount = returnedPrivilegeSet.PrivilegeCount;
//lets create the array we should have had returned in the first place
LUID_AND_ATTRIBUTES[] AllPrivs = new LUID_AND_ATTRIBUTES[PrivilegeCount]; //initialize an array to the right size, including 0!
if (PrivilegeCount > 0)
{
LUID_AND_ATTRIBUTES currentPriv = new LUID_AND_ATTRIBUTES();
//pPrivileges will hold our new location to read from by taking the last pointer plus the size of the last structure read
IntPtr pPrivilege = new IntPtr(pTokenInfo.ToInt32() + sizeof(int)); //pointer math, we point to the first element of Privileges array in the struct.
currentPriv = (LUID_AND_ATTRIBUTES)Marshal.PtrToStructure(pPrivilege, typeof(LUID_AND_ATTRIBUTES)); //Get Privilege from pointer
AllPrivs[0] = currentPriv; //We'll add the first element to our array.
//After getting our first structure we can loop through the rest since they will all be the same
for (int i = 1; i < PrivilegeCount; ++i)
{
pPrivilege = new IntPtr(pPrivilege.ToInt32() + Marshal.SizeOf(currentPriv)); //This will point to the next Privilege element in the array
currentPriv = (LUID_AND_ATTRIBUTES)Marshal.PtrToStructure(pPrivilege, typeof(LUID_AND_ATTRIBUTES)); //Get Privilege from pointer
AllPrivs[i] = currentPriv; //Add element to the array
}
}
//Create our complete struct of TOKEN_PRIVILEGES
TOKEN_PRIVILEGES completePrivilegeSet = new TOKEN_PRIVILEGES();
completePrivilegeSet.PrivilegeCount = PrivilegeCount;
completePrivilegeSet.Privileges = AllPrivs;
//We can get release all the pointers now, we got what we wanted!
Marshal.FreeHGlobal(pTokenInfo); //Free up the reserved space in unmanaged memory (Should be done any time AllocHGlobal is used)
//Return our completePrivilegeSet!
return completePrivilegeSet;
}
}
return new TOKEN_PRIVILEGES() { PrivilegeCount = 0, Privileges = new LUID_AND_ATTRIBUTES[] { } };
}
private static string LookupPrivilegeName(LUID privLuid, string remoteMachineName = null)
{
string PrivilegeName = null;
StringBuilder sb = new StringBuilder();
int cchName = 0; //Holds the length of structure we will be receiving LookupPrivilagename
IntPtr ipLuid = Marshal.AllocHGlobal(Marshal.SizeOf(privLuid)); //Allocate a block of memory large enough to hold the structure
Marshal.StructureToPtr(privLuid, ipLuid, true); //Write the structure into the reserved space in unmanaged memory
LookupPrivilegeName(remoteMachineName, ipLuid, null, ref cchName); // call once to get the name length we will be receiving
sb.Capacity = cchName; //Our string builder is buffered for the name!
if (LookupPrivilegeName(remoteMachineName, ipLuid, sb, ref cchName))
{
// Successfully retrieved name!
PrivilegeName = sb.ToString();
}
Marshal.FreeHGlobal(ipLuid); //Free up the reserved space in unmanaged memory
return PrivilegeName;
}
public static List<string> ListEnabledPrivileges(IntPtr TokenHandle, string remoteMachineName = null)
{
List<string> enabledPrivs = null;
DataTable dt = GetAccessTokenPrivilegesAsDataTable(TokenHandle, remoteMachineName);
if (dt != null && dt.Rows.Count > 0)
{
uint nEnabled = (uint)SE_PRIVILEGE_STATE.SE_PRIVILEGE_ENABLED;
uint nEnabledAndDefault = (uint)(SE_PRIVILEGE_STATE.SE_PRIVILEGE_ENABLED_BY_DEFAULT | SE_PRIVILEGE_STATE.SE_PRIVILEGE_ENABLED);
string query = string.Format("[{0}] IN ( {1}, {2} )"
, dt.Columns[2].ColumnName
, nEnabled
, nEnabledAndDefault);
IEnumerable<DataRow> rows = dt.Select(query);
if (rows != null && rows.Count() > 0)
{
enabledPrivs = dt.Select(query).Select(r => r.Field<string>(1)).ToList();
}
}
return enabledPrivs;
}
}
So after much research it turns out this is locked down in Windows. Unless the current process token has SeTcbPrivilege (Act as Part of Operating System) and it's enabled, you cannot get an unrestricted/elevated token when deciding to impersonate from a non-elevated token.
Also if you then try to get the LinkedToken/Unrestricted Token of an Access Token but do not have the SeTcbPrivilege enabled, you will end up with a Token that has a SECURITY_IMPERSONATION_LEVEL of SecurityIdentification which cannot be used for impersonation. Without SECURITY_IMPERSONATION_LEVEL being SecurityImpersonation (Local Access) or SecurityDelegation (Local+Remote Access), you cannot impersonate the Unrestricted Access Token and will result in failure with LastError being ERROR_BAD_IMPERSONATION_LEVEL (Either a required impersonation level was not provided, or the provided impersonation level is invalid).
This means if you do not have SeTcbPrivilege and it is not enable on the token, it is required to have an elevated process token (ex. Run As Admin was used to start the program manually or forcefully via requestedExecutionLevel level="requireAdministrator") then Windows will not strip the privileges on Access Token when you decide to impersonate the Access Token.
By using a local administrator account that runs the program as administrator, and then using domain account credentials that are an admin on another machine to get an access token using the params of LOGON32_LOGONTYPE.LOGON32_LOGON_NEW_CREDENTIALS and LOGON32_LOGONPROVIDER.LOGON32_PROVIDER_WINNT50. It is then possible to elevate privileges on the NEWCRED token, impersonate the NEWCRED token which will not strip away the privileges, and have it successfully connect to another computer and read from a file and write to a file on another computer to which it has no permissions or is even explicitly denied, proving it was using the token backup and restore privileges!
Helpful Sources:
how do i convert restricted user token to unrestricted one?
How to call LogonUser() to get a non-restricted full token inside a Windows Service with UAC enabled?

Display X509Certificate with chain elements not in certificate store

I have an object of type X509Certificate2 and want to display it to the user. I'm doing this with the X509Certificate2UI.DisplayCertificate method.
The problem I have is that this certificate I want to show is issued by an intermediate CA whichs certificate is not in the machines certificate store, but its root is.
Now if I display said certificate the dialog is not able to build the chain (opposite to me, as I am able to with the X509Chain and the intermediate CA as an extra element)
How do I display the certificate with the whole chain?
X509Certificate2 endCert = ...;
X509Certificate2 intermediateCA = ...;
X509Chain chain = new X509Chain();
chain.ChainPolicy.ExtraStore.Add(intermediateCA);
chain.Build(endCert); // Whole chain!
X509Certificate2UI.DisplayCertificate(endCert); // Dialog shows: "The issuer of this certificate could not be found."
(I'm not able/allowed to add the intermediate CA to the user/machine store!)
(I'm not able/allowed to create my own dialog. It has to be the default Windows dialog!)
(P/Invoke is allowed if required)
Just as an example you can try these certificates to test above, but you have to reference System.Security.dll for X509Certificate2UI.DisplayCertificate:
X509Certificate2 endCert = new X509Certificate2(
Convert.FromBase64String(
"MIIE8zCCA9ugAwIBAgIQSBDq+mlsLsCZqWMIWj/YADANBgkqhkiG9w0BAQUFADA8MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMVGhhd3RlLCBJbmMuMRYwFAYDVQQDEw1UaGF3dGUgU1NMIENBMB4XDTExMTI" +
"yMDAwMDAwMFoXDTE0MDIxNzIzNTk1OVowgYsxCzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxQLRm9yZXN0IEhpbGwxIzAhBgNVBAoUGkFwYWNoZSBTb2Z0d2FyZSBGb3VuZGF0aW" +
"9uMRcwFQYDVQQLFA5JbmZyYXN0cnVjdHVyZTEVMBMGA1UEAxQMKi5hcGFjaGUub3JnMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEApyhxElzdnWks7MMCEx24FMhHCbFcgKbO+fh/+JYrV91Cs" +
"xsdqsAsv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4H7MIH4MDIGCCsGAQUFBwEBBCYwJDAiBggrBgEFBQcwAYYWaHR0cDovL29jc3AudGhhd3RlLmNvbTASBgNVHRMBAf8ECDAGAQH/AgEAMDQGA1UdHwQtMCswKa" +
"AnoCWGI2h0dHA6Ly9jcmwudGhhd3RlLmNvbS9UaGF3dGVQQ0EuY3JsMA4GA1UdDwEB/wQEAwIBBjAoBgNVHREEITAfpB0wGzEZMBcGA1UEAxMQVmVyaVNpZ25NUEtJLTItOTAdBgNVHQ4EFgQUp6KDuzRFQ" +
"D381TBPErk+oQGf9tswHwYDVR0jBBgwFoAUe1tFz6/Oy3r9MZIaarbzRutXSFAwDQYJKoZIhvcNAQEFBQADggEBAIAigOBsyJUW11cmh/NyNNvGclYnPtOW9i4lkaU+M5enS+Uv+yV9Lwdh+m+DdExMU3Ig" +
"pHrPUVFWgYiwbR82LMgrsYiZwf5Eq0hRfNjyRGQq2HGn+xov+RmNNLIjv8RMVR2OROiqXZrdn/0Dx7okQ40tR0Tb9tiYyLL52u/tKVxpEvrRI5YPv5wN8nlFUzeaVi/oVxBw9u6JDEmJmsEj9cIqzEHPIqt" +
"lbreUgm0vQF9Y3uuVK6ZyaFIZkSqudZ1OkubK3lTqGKslPOZkpnkfJn1h7X3S5XFV2JMXfBQ4MDzfhuNMrUnjl1nOG5srztxl1Asoa06ERlFE9zMILViXIa4="));
I am confident that this should be somehow possible, as the Internet Explorer is doing the same. You can try it with https://httpd.apache.org/ (The certificates above are from there)
If this is possible what you are going to need to do is to use CAPI to create an in memory certificate store and add your intermediate certs to that and then use the underlying call to CryptUIDlgViewCertificate to display the dialogue in a way that uses your temporary store.
Found in this MSDN forum thread, the example follows your original code:
X509Certificate2 endCert = new X509Certificate2(
Convert.FromBase64String(
"MIIE8zCCA9ugAwIBAgIQSBDq+mlsLsCZqWMIWj/YADANBgkqhkiG9w0BAQUFADA8MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMVGhhd3RlLCBJbmMuMRYwFAYDVQQDEw1U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ztxl1Asoa06ERlFE9zMILViXIa4="));
X509Chain chain = new X509Chain();
chain.ChainPolicy.ExtraStore.Add(intermediateCA);
chain.Build(endCert); // Whole chain!
X509Certificate2 fMainCertificate = null;
X509Certificate2Collection fExtraCertificates = new X509Certificate2Collection();
fMainCertificate = endCert;
fExtraCertificates.Add(intermediateCA);
X509Store lStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
// No need to write to the user's store, just read.
lStore.Open(OpenFlags.ReadOnly);
try
{
List<X509Certificate2> lAddedCertificates = new List<X509Certificate2>();
try
{
foreach (X509Certificate2 lCertificate in fExtraCertificates)
if (!lStore.Certificates.Contains(lCertificate))
{
lStore.Add(lCertificate);
lAddedCertificates.Add(lCertificate);
}
X509Certificate2UI.DisplayCertificate(fMainCertificate);
}
finally
{
foreach (X509Certificate2 lCertificate in lAddedCertificates)
lStore.Remove(lCertificate);
}
}
finally { lStore.Close(); }
When run, I get the default Windows dialog and the full chain appears to be present:
In case anybody needs the code:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct CRYPTUI_VIEWCERTIFICATE_STRUCT
{
public int dwSize;
public IntPtr hwndParent;
public int dwFlags;
[MarshalAs(UnmanagedType.LPWStr)]
public String szTitle;
public IntPtr pCertContext;
public IntPtr rgszPurposes;
public int cPurposes;
public IntPtr pCryptProviderData;
public Boolean fpCryptProviderDataTrustedUsage;
public int idxSigner;
public int idxCert;
public Boolean fCounterSigner;
public int idxCounterSigner;
public int cStores;
public IntPtr rghStores;
public int cPropSheetPages;
public IntPtr rgPropSheetPages;
public int nStartPage;
}
public static class CryptAPI
{
public static void ShowCertificateDialog(X509Chain chain, string title, IntPtr parent)
{
const int certStoreProvMemory = 2; // CERT_STORE_PROV_MEMORY
const int certCloseStoreCheckFlag = 2; // CERT_CLOSE_STORE_CHECK_FLAG
const uint certStoreAddAlways = 4; // CERT_STORE_ADD_ALWAYS
const uint x509AsnEncoding = 1; // X509_ASN_ENCODING
var storeHandle = CertOpenStore(certStoreProvMemory, 0, 0, 0, null);
if (storeHandle == IntPtr.Zero)
throw new Win32Exception();
try
{
foreach (var element in chain.ChainElements)
{
var certificate = element.Certificate;
var certificateBytes = certificate.Export(X509ContentType.Cert);
var certContextHandle = CertCreateCertificateContext(
x509AsnEncoding, certificateBytes, (uint)certificateBytes.Length);
if (certContextHandle == IntPtr.Zero)
throw new Win32Exception();
CertAddCertificateContextToStore(storeHandle, certContextHandle, certStoreAddAlways, IntPtr.Zero);
}
var extraStoreArray = new[] { storeHandle };
var extraStoreArrayHandle = GCHandle.Alloc(extraStoreArray, GCHandleType.Pinned);
try
{
var extraStorePointer = extraStoreArrayHandle.AddrOfPinnedObject();
var viewInfo = new CRYPTUI_VIEWCERTIFICATE_STRUCT();
viewInfo.hwndParent = parent;
viewInfo.dwSize = Marshal.SizeOf(viewInfo);
viewInfo.pCertContext = chain.ChainElements[0].Certificate.Handle;
viewInfo.szTitle = title;
viewInfo.nStartPage = 0;
viewInfo.cStores = 1;
viewInfo.rghStores = extraStorePointer;
var fPropertiesChanged = false;
CryptUIDlgViewCertificate(ref viewInfo, ref fPropertiesChanged);
}
finally
{
if (extraStoreArrayHandle.IsAllocated)
extraStoreArrayHandle.Free();
}
}
finally
{
CertCloseStore(storeHandle, certCloseStoreCheckFlag);
}
}
[DllImport("CRYPT32", EntryPoint = "CertOpenStore", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr CertOpenStore(int storeProvider, int encodingType, int hcryptProv, int flags, string pvPara);
[DllImport("crypt32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr CertCreateCertificateContext([In] uint dwCertEncodingType, [In] byte[] pbCertEncoded, [In] uint cbCertEncoded);
[DllImport("crypt32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool CertAddCertificateContextToStore([In] IntPtr hCertStore, [In] IntPtr pCertContext, [In] uint dwAddDisposition, [In, Out] IntPtr ppStoreContext);
[DllImport("crypt32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool CertFreeCertificateContext([In] IntPtr pCertContext);
[DllImport("CRYPT32", EntryPoint = "CertCloseStore", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertCloseStore(IntPtr storeProvider, int flags);
[DllImport("CryptUI.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool CryptUIDlgViewCertificate(ref CRYPTUI_VIEWCERTIFICATE_STRUCT pCertViewInfo, ref bool pfPropertiesChanged);
}
It takes a certificate chain, where each certificate may not be in user/machine store and shows a dialog with the first certificate in chain. Other certificates are used to build a certificate path.

open website without Process.start

How to open a website URL in browser without of Process.start(...) :
System.Diagnostics.Process.Start(#"http://www.google.com");
I can not use Process.Start() in Windows Service , I do not no know why.
See the answer to the question "How can a Windows service execute a GUI application?":
use WTSEnumerateSessions to find the right desktop, then CreateProcessAsUser to start the application on that desktop
Note also the opinion that you shouldn't do this :)
If all you are doing is launching a URL, the command might be
cmd.exe /c start http://example.com/
If you want to suppress the briefly-displayed Command Prompt window, you can set the wShowWindow field of the STARTUPINFO structure to SW_HIDE, or in .NET set the ProcessStartInfo.WindowStyle property to ProcessWindowStyle.Hidden.
Services run in an isolated session. That session has its own desktop, much like the login screen. A user however can never look at it. This is a very basic security measure, services typically run with a very privileged account. You can use Process.Start(), the user just will never be able to see the UI of the program.
This is not a real problem, it makes zero sense to start a browser in a service.
Services don't run using the Desktop, so I would not recommend trying to open a browser.
If you just need information from the website in question, in order to download and parse information, you might want to consider using a WebClient instead of a browser. This will allow you to download from any Uri, and parse the results in a service.
Services on Windows 7 CAN'T interact with desktop in any way.
So, what you need is a small process that will use some method of communication with the service, start it for the user that is logged on and wait for service message. You can start it in Startup group or any other means for that purpose, just make it very small and unnoticeable. Of course, if you want it to bi noticed, you can use tray icon for it or even some status window.
Service message could be something as simple as writing a file with an URL in the directory that is shared between service and the user process. That way you'll get what you need and stay compatible with most Windows versions.
Fixed code from here: http://18and5.blogspot.com/2008/01/i-hope-my-frustration-can-help-someone.html
I had to fix the parameter handling that the example below will actually work.
using System;
using System.Reflection;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace Common.Utilities.Processes
{
public class ProcessUtilities
{
/*** Imports ***/
#region Imports
[DllImport("advapi32.dll", EntryPoint = "AdjustTokenPrivileges", SetLastError = true)]
public static extern bool AdjustTokenPrivileges(IntPtr in_hToken, [MarshalAs(UnmanagedType.Bool)]bool DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, UInt32 BufferLength, IntPtr PreviousState, IntPtr ReturnLength);
[DllImport("advapi32.dll", EntryPoint = "OpenProcessToken", SetLastError = true)]
public static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);
[DllImport("advapi32.dll", EntryPoint = "LookupPrivilegeValue", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, out LUID lpLuid);
[DllImport("userenv.dll", EntryPoint = "CreateEnvironmentBlock", SetLastError = true)]
public static extern bool CreateEnvironmentBlock(out IntPtr out_ptrEnvironmentBlock, IntPtr in_ptrTokenHandle, bool in_bInheritProcessEnvironment);
[DllImport("kernel32.dll", EntryPoint = "CloseHandle", SetLastError = true)]
public static extern bool CloseHandle(IntPtr handle);
[DllImport("wtsapi32.dll", EntryPoint = "WTSQueryUserToken", SetLastError = true)]
public static extern bool WTSQueryUserToken(UInt32 in_nSessionID, out IntPtr out_ptrTokenHandle);
[DllImport("kernel32.dll", EntryPoint = "WTSGetActiveConsoleSessionId", SetLastError = true)]
public static extern uint WTSGetActiveConsoleSessionId();
[DllImport("Wtsapi32.dll", EntryPoint = "WTSQuerySessionInformation", SetLastError = true)]
public static extern bool WTSQuerySessionInformation(IntPtr hServer, int sessionId, WTS_INFO_CLASS wtsInfoClass, out IntPtr ppBuffer, out uint pBytesReturned);
[DllImport("wtsapi32.dll", EntryPoint = "WTSFreeMemory", SetLastError = false)]
public static extern void WTSFreeMemory(IntPtr memory);
[DllImport("userenv.dll", EntryPoint = "LoadUserProfile", SetLastError = true)]
public static extern bool LoadUserProfile(IntPtr hToken, ref PROFILEINFO lpProfileInfo);
[DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool CreateProcessAsUser(IntPtr in_ptrUserTokenHandle, string in_strApplicationName, string in_strCommandLine, ref SECURITY_ATTRIBUTES in_oProcessAttributes, ref SECURITY_ATTRIBUTES in_oThreadAttributes, bool in_bInheritHandles, CreationFlags in_eCreationFlags, IntPtr in_ptrEnvironmentBlock, string in_strCurrentDirectory, ref STARTUPINFO in_oStartupInfo, ref PROCESS_INFORMATION in_oProcessInformation);
#endregion //Imports
/*** Delegates ***/
/*** Structs ***/
#region Structs
[StructLayout(LayoutKind.Sequential)]
public struct LUID
{
public uint m_nLowPart;
public uint m_nHighPart;
}
[StructLayout(LayoutKind.Sequential)]
public struct TOKEN_PRIVILEGES
{
public int m_nPrivilegeCount;
public LUID m_oLUID;
public int m_nAttributes;
}
[StructLayout(LayoutKind.Sequential)]
public struct PROFILEINFO
{
public int dwSize;
public int dwFlags;
[MarshalAs(UnmanagedType.LPTStr)]
public String lpUserName;
[MarshalAs(UnmanagedType.LPTStr)]
public String lpProfilePath;
[MarshalAs(UnmanagedType.LPTStr)]
public String lpDefaultPath;
[MarshalAs(UnmanagedType.LPTStr)]
public String lpServerName;
[MarshalAs(UnmanagedType.LPTStr)]
public String lpPolicyPath;
public IntPtr hProfile;
}
[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;
}
#endregion //Structs
/*** Classes ***/
/*** Enums ***/
#region Enums
public enum CreationFlags
{
CREATE_SUSPENDED = 0x00000004,
CREATE_NEW_CONSOLE = 0x00000010,
CREATE_NEW_PROCESS_GROUP = 0x00000200,
CREATE_UNICODE_ENVIRONMENT = 0x00000400,
CREATE_SEPARATE_WOW_VDM = 0x00000800,
CREATE_DEFAULT_ERROR_MODE = 0x04000000,
}
public enum WTS_INFO_CLASS
{
WTSInitialProgram,
WTSApplicationName,
WTSWorkingDirectory,
WTSOEMId,
WTSSessionId,
WTSUserName,
WTSWinStationName,
WTSDomainName,
WTSConnectState,
WTSClientBuildNumber,
WTSClientName,
WTSClientDirectory,
WTSClientProductId,
WTSClientHardwareId,
WTSClientAddress,
WTSClientDisplay,
WTSClientProtocolType
}
#endregion //Enums
/*** Defines ***/
#region Defines
private const int TOKEN_QUERY = 0x08;
private const int TOKEN_ADJUST_PRIVILEGES = 0x20;
private const int SE_PRIVILEGE_ENABLED = 0x02;
public const int ERROR_NO_TOKEN = 1008;
public const int RPC_S_INVALID_BINDING = 1702;
#endregion //Defines
/*** Methods ***/
#region Methods
/*
If you need to give yourself permissions to inspect processes for their modules,
and create tokens without worrying about what account you're running under,
this is the method for you :) (such as the token privilege "SeDebugPrivilege")
*/
static public bool AdjustProcessTokenPrivileges(IntPtr in_ptrProcessHandle, string in_strTokenToEnable)
{
IntPtr l_hProcess = IntPtr.Zero;
IntPtr l_hToken = IntPtr.Zero;
LUID l_oRestoreLUID;
TOKEN_PRIVILEGES l_oTokenPrivileges;
Debug.Assert(in_ptrProcessHandle != IntPtr.Zero);
//Get the process security token
if (false == OpenProcessToken(in_ptrProcessHandle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out l_hToken))
{
return false;
}
//Lookup the LUID for the privilege we need
if (false == LookupPrivilegeValue(String.Empty, in_strTokenToEnable, out l_oRestoreLUID))
{
return false;
}
//Adjust the privileges of the current process to include the new privilege
l_oTokenPrivileges.m_nPrivilegeCount = 1;
l_oTokenPrivileges.m_oLUID = l_oRestoreLUID;
l_oTokenPrivileges.m_nAttributes = SE_PRIVILEGE_ENABLED;
if (false == AdjustTokenPrivileges(l_hToken, false, ref l_oTokenPrivileges, 0, IntPtr.Zero, IntPtr.Zero))
{
return false;
}
return true;
}
/*
Start a process the simplest way you can imagine
*/
static public int SimpleProcessStart(string in_strTarget, string in_strArguments)
{
Process l_oProcess = new Process();
Debug.Assert(l_oProcess != null);
l_oProcess.StartInfo.FileName = in_strTarget;
l_oProcess.StartInfo.Arguments = in_strArguments;
if (true == l_oProcess.Start())
{
return l_oProcess.Id;
}
return -1;
}
/*
All the magic is in the call to WTSQueryUserToken, it saves you changing DACLs,
process tokens, pulling the SID, manipulating the Windows Station and Desktop
(and its DACLs) - if you don't know what those things are, you're lucky and should
be on your knees thanking God at this moment.
DEV NOTE: This method currently ASSumes that it should impersonate the user
who is logged into session 1 (if more than one user is logged in, each
user will have a session of their own which means that if user switching
is going on, this method could start a process whose UI shows up in
the session of the user who is not actually using the machine at this
moment.)
DEV NOTE 2: If the process being started is a binary which decides, based upon
the user whose session it is being created in, to relaunch with a
different integrity level (such as Internet Explorer), the process
id will change immediately and the Process Manager will think
that the process has died (because in actuality the process it
launched DID in fact die only that it was due to self-termination)
This means beware of using this service to startup such applications
although it can connect to them to alarm in case of failure, just
make sure you don't configure it to restart it or you'll get non
stop process creation ;)
*/
static public int CreateUIProcessForServiceRunningAsLocalSystem(string in_strTarget, string in_strArguments)
{
PROCESS_INFORMATION l_oProcessInformation = new PROCESS_INFORMATION();
SECURITY_ATTRIBUTES l_oSecurityAttributes = new SECURITY_ATTRIBUTES();
STARTUPINFO l_oStartupInfo = new STARTUPINFO();
PROFILEINFO l_oProfileInfo = new PROFILEINFO();
IntPtr l_ptrUserToken = new IntPtr(0);
uint l_nActiveUserSessionId = 0xFFFFFFFF;
string l_strActiveUserName = "";
int l_nProcessID = -1;
IntPtr l_ptrBuffer = IntPtr.Zero;
uint l_nBytes = 0;
try
{
//The currently active user is running what session?
l_nActiveUserSessionId = WTSGetActiveConsoleSessionId();
if (l_nActiveUserSessionId == 0xFFFFFFFF)
{
throw new Exception("ProcessUtilities" + "->" + MethodInfo.GetCurrentMethod().Name + "->" + "The call to WTSGetActiveConsoleSessionId failed, GetLastError returns: " + Marshal.GetLastWin32Error().ToString());
}
if (false == WTSQuerySessionInformation(IntPtr.Zero, (int)l_nActiveUserSessionId, WTS_INFO_CLASS.WTSUserName, out l_ptrBuffer, out l_nBytes))
{
int l_nLastError = Marshal.GetLastWin32Error();
//On earlier operating systems from Vista, when no one is logged in, you get RPC_S_INVALID_BINDING which is ok, we just won't impersonate
if (l_nLastError != RPC_S_INVALID_BINDING)
{
throw new Exception("ProcessUtilities" + "->" + MethodInfo.GetCurrentMethod().Name + "->" + "The call to WTSQuerySessionInformation failed, GetLastError returns: " + Marshal.GetLastWin32Error().ToString());
}
//No one logged in so let's just do this the simple way
return SimpleProcessStart(in_strTarget, in_strArguments);
}
l_strActiveUserName = Marshal.PtrToStringAnsi(l_ptrBuffer);
WTSFreeMemory(l_ptrBuffer);
//We are supposedly running as a service so we're going to be running in session 0 so get a user token from the active user session
if (false == WTSQueryUserToken((uint)l_nActiveUserSessionId, out l_ptrUserToken))
{
int l_nLastError = Marshal.GetLastWin32Error();
//Remember, sometimes nobody is logged in (especially when we're set to Automatically startup) you should get error code 1008 (no user token available)
if (ERROR_NO_TOKEN != l_nLastError)
{
//Ensure we're running under the local system account
WindowsIdentity l_oIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();
if ("NT AUTHORITY\\SYSTEM" != l_oIdentity.Name)
{
throw new Exception("ProcessUtilities" + "->" + MethodInfo.GetCurrentMethod().Name + "->" + "The call to WTSQueryUserToken failed and querying the process' account identity results in an identity which does not match 'NT AUTHORITY\\SYSTEM' but instead returns the name:" + l_oIdentity.Name + " GetLastError returns: " + l_nLastError.ToString());
}
throw new Exception("ProcessUtilities" + "->" + MethodInfo.GetCurrentMethod().Name + "->" + "The call to WTSQueryUserToken failed, GetLastError returns: " + l_nLastError.ToString());
}
//No one logged in so let's just do this the simple way
return SimpleProcessStart(in_strTarget, in_strArguments);
}
//Create an appropriate environment block for this user token (if we have one)
IntPtr l_ptrEnvironment = IntPtr.Zero;
Debug.Assert(l_ptrUserToken != IntPtr.Zero);
if (false == CreateEnvironmentBlock(out l_ptrEnvironment, l_ptrUserToken, false))
{
throw new Exception("ProcessUtilities" + "->" + MethodInfo.GetCurrentMethod().Name + "->" + "The call to CreateEnvironmentBlock failed, GetLastError returns: " + Marshal.GetLastWin32Error().ToString());
}
l_oSecurityAttributes.Length = Marshal.SizeOf(l_oSecurityAttributes);
l_oStartupInfo.cb = Marshal.SizeOf(l_oStartupInfo);
//DO NOT set this to "winsta0\\default" (even though many online resources say to do so)
l_oStartupInfo.lpDesktop = String.Empty;
l_oProfileInfo.dwSize = Marshal.SizeOf(l_oProfileInfo);
l_oProfileInfo.lpUserName = l_strActiveUserName;
//Remember, sometimes nobody is logged in (especially when we're set to Automatically startup)
if (false == LoadUserProfile(l_ptrUserToken, ref l_oProfileInfo))
{
throw new Exception("ProcessUtilities" + "->" + MethodInfo.GetCurrentMethod().Name + "->" + "The call to LoadUserProfile failed, GetLastError returns: " + Marshal.GetLastWin32Error().ToString());
}
if (false == CreateProcessAsUser(l_ptrUserToken, in_strTarget, in_strTarget + " " + in_strArguments, ref l_oSecurityAttributes, ref l_oSecurityAttributes, false, CreationFlags.CREATE_UNICODE_ENVIRONMENT, l_ptrEnvironment, null, ref l_oStartupInfo, ref l_oProcessInformation))
{
//System.Diagnostics.EventLog.WriteEntry( "CreateProcessAsUser FAILED", Marshal.GetLastWin32Error().ToString() );
throw new Exception("ProcessUtilities" + "->" + MethodInfo.GetCurrentMethod().Name + "->" + "The call to CreateProcessAsUser failed, GetLastError returns: " + Marshal.GetLastWin32Error().ToString());
}
l_nProcessID = l_oProcessInformation.dwProcessID;
}
catch (Exception l_oException)
{
throw new Exception("ProcessUtilities" + "->" + MethodInfo.GetCurrentMethod().Name + "->" + "An unhandled exception was caught spawning the process, the exception was: " + l_oException.Message);
}
finally
{
if (l_oProcessInformation.hProcess != IntPtr.Zero)
{
CloseHandle(l_oProcessInformation.hProcess);
}
if (l_oProcessInformation.hThread != IntPtr.Zero)
{
CloseHandle(l_oProcessInformation.hThread);
}
}
return l_nProcessID;
}
#endregion //Methods
}
}
And this is the call you have to do:
Common.Utilities.Processes.ProcessUtilities.CreateUIProcessForServiceRunningAsLocalSystem(
#"C:\Windows\System32\cmd.exe",
" /c \"start http://www.google.com\""
);
I have tested it on my own system and it worked like a charm (Windows 7 x64 with enabled UAC)
However I recommend to create a tiny stub application which will not make the cmd window flash. And which will accept the url as parameter.
Plus you should not use the hardcoded path to cmd.exe like I did in the example. However the code works, the rest should be clear I hope :-)
HTH
It is a design problem if a service has to interact with the user (as example, services are started before logon).
I usally solve this problem by making a small program that starts with the user's session. If I have to interact with the user in the service, it will first look if the user level program is running and if it is, it will send commands to it.
If you are interested in the response try:
string url = #"http://www.google.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream);
Why not try to Impersonate a user who has logon privilages on the machine only for that particular piece of code that starts the web browser using System.Diagnostics.Process.Start.
What exactly do you intend to do with browser once the web page gets loaded?
You can try to run your service with "interact with desktop" set. This should fix your problem, but may cause other issues like your service will stop when someone logs out of the main console.

Categories