Create Process As User - visual-c++

I have a service that runs as system. I am creating a process but that process also runs under system account.
I want to run that particular process as user. For this I have used CreateProcessAsUser API. What is wrong with it?. I copied my code below.
void Create_Process()
{
PHANDLE primaryToken = GetCurrentUserToken();
if (primaryToken == 0)
{
return FALSE;
}
STARTUPINFO StartupInfo;
PROCESS_INFORMATION processInfo;
StartupInfo.cb = sizeof(STARTUPINFO);
SECURITY_ATTRIBUTES Security1;
SECURITY_ATTRIBUTES Security2;
void* lpEnvironment = NULL;
// Get all necessary environment variables of logged in user
// to pass them to the process
BOOL resultEnv = CreateEnvironmentBlock(&lpEnvironment,primaryToken, FALSE);
if (resultEnv == 0)
{
long nError = GetLastError();
}
// Launch the process in the client's logon session.
BOOL result= CreateProcessAsUser(
primaryToken,
_T("c:\\windows\\system32\\abc.exe"),
NULL,
&Security1,
&Security2,
FALSE,
NORMAL_PRIORITY_CLASS | CREATE_UNICODE_ENVIRONMENT,
lpEnvironment,
NULL,
&StartupInfo,
&processInfo
);
}
PHANDLE GetCurrentUserToken()
{
PHANDLE currentToken = 0;
PHANDLE primaryToken = 0;
int dwSessionId = 0;
PHANDLE hUserToken = 0;
PHANDLE hTokenDup = 0;
PWTS_SESSION_INFO pSessionInfo = 0;
DWORD dwCount = 0;
// Get the list of all terminal sessions
WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pSessionInfo, &dwCount);
int dataSize = sizeof(WTS_SESSION_INFO);
// look over obtained list in search of the active session
for (DWORD i = 0; i < dwCount; ++i)
{
WTS_SESSION_INFO si = pSessionInfo[i];
if (WTSActive == si.State)
{
// If the current session is active – store its ID
dwSessionId = si.SessionId;
break;
}
}
// Get token of the logged in user by the active session ID
BOOL bRet = WTSQueryUserToken(dwSessionId, currentToken);
if (bRet == false)
{
return 0;
}
bRet = DuplicateTokenEx(currentToken, TOKEN_ASSIGN_PRIMARY | TOKEN_ALL_ACCESS, 0, SecurityImpersonation, TokenPrimary, primaryToken);
if (bRet == false)
{
return 0;
}
return primaryToken;
}

Related

How to send Dictionary datatype( a{ias} ) through gdbus?

I was trying to send different datatypes over dbus using gdbus. I am stuck at sending the following datatype : a{ias}. Does anyone send me a snippet or any ways to approach this problem?
I have got a snippet here,just replace the busname,path,interface,methodname in the below code.
GDBusProxy *proxy;
GDBusConnection *connection;
GError *error;
GVariantBuilder* builder;
error = NULL;
**//Acquire bus connection**
connection = g_bus_get_sync (G_BUS_TYPE_SYSTEM,
NULL,
&error);
g_assert_no_error (error);
error = NULL;
**//Create proxy of remote object**
proxy= g_dbus_proxy_new_sync(connection,
G_DBUS_PROXY_FLAGS_NONE,
NULL, /* GDBusInterfaceInfo */
"org.busname", /* Services */
"/org/buspath", /* Path */
"org.interface", /* Interface */
NULL, /* GCancellable */
error);
GVariant *result;
GVariant *value;
GError *error;
error = NULL;
int i;
g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
**//Sending dictionary datatype start**
for (i = 0; i < 2; i++)
{
GVariantBuilder* builderAs = g_variant_builder_new(G_VARIANT_TYPE("as"));
for (int j = 0; j < 2; j++) {
g_variant_builder_add(builderAs, "s", "SomeString");
}
g_variant_builder_add(&builder, "{ias}",i,builderAs);
}
**//Sending dictionary end**
GVariant *v1 = g_variant_builder_end(&builder);
result = g_dbus_proxy_call_sync(proxy,
"MethodName",
g_variant_new_tuple(&v1, 1),
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
&error);

Command Timeout, longer to get response back

I am executing large query,so my app throwing time out error. Some of the thread suggested to added command time out but after adding those lines it take longer to get response back, any idea why or what am i missing in my code?
public int CreateRecord(string theCommand, DataSet theInputData)
{
int functionReturnValue = 0;
int retVal = 0;
SqlParameter objSqlParameter = default(SqlParameter);
DataSet dsParameter = new DataSet();
int i = 0;
try
{
//Set the command text (stored procedure name or SQL statement).
mobj_SqlCommand.CommandTimeout = 120;
mobj_SqlCommand.CommandText = theCommand;
mobj_SqlCommand.CommandType = CommandType.StoredProcedure;
for (i = 0; i <= (theInputData.Tables.Count - 1); i++)
{
if (theInputData.Tables[i].Rows.Count > 0)
{
dsParameter.Tables.Add(theInputData.Tables[i].Copy());
}
}
objSqlParameter = new SqlParameter("#theXmlData", SqlDbType.Text);
objSqlParameter.Direction = ParameterDirection.Input;
objSqlParameter.Value = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" + dsParameter.GetXml();
//Attach to the parameter to mobj_SqlCommand.
mobj_SqlCommand.Parameters.Add(objSqlParameter);
//Finally, execute the command.
retVal = (int)mobj_SqlCommand.ExecuteScalar();
//Detach the parameters from mobj_SqlCommand, so it can be used again.
mobj_SqlCommand.Parameters.Clear();
functionReturnValue = retVal;
}
catch (Exception ex)
{
throw new System.Exception(ex.Message);
}
finally
{
//Clean up the objects created in this object.
if (mobj_SqlConnection.State == ConnectionState.Open)
{
mobj_SqlConnection.Close();
mobj_SqlConnection.Dispose();
mobj_SqlConnection = null;
}
if ((mobj_SqlCommand != null))
{
mobj_SqlCommand.Dispose();
mobj_SqlCommand = null;
}
if ((mobj_SqlDataAdapter != null))
{
mobj_SqlDataAdapter.Dispose();
mobj_SqlDataAdapter = null;
}
if ((dsParameter != null))
{
dsParameter.Dispose();
dsParameter = null;
}
objSqlParameter = null;
}
return functionReturnValue;
}

How can i download only new records from Anviz EP300?

All,
Currently i'm using Anviz EP300 time attendance machine. I need to download only new records from device.
I'm using following sdk. Click here
There is some method already have in sdk. Which is i used like...
int i = 0;
int Ret = 0;
int RecordCount = 0;
int RetCount = 0;
int pClockings = 0;
int pLongRun = 0;
CKT_DLL.CLOCKINGRECORD clocking = new CKT_DLL.CLOCKINGRECORD();
clocking.Time = new byte[20];
int ptemp = 0;
ProgressBar1.Value = 0;
//If CKT_GetClockingNewRecordEx(IDNumber, pLongRun) Then 'IF GET NewRecord
if (CKT_DLL.CKT_GetClockingNewRecordEx(IDNumber, ref pLongRun) != 0) //IF GET Record
{
while (true)
{
Ret = CKT_DLL.CKT_GetClockingRecordProgress(pLongRun, ref RecordCount, ref RetCount, ref pClockings);
if (RecordCount > 0)
{
ProgressBar1.Maximum = RecordCount;
}
if (Ret == 0)
{
return;
}
if (Ret != 0)
{
ptemp = pClockings;
for (i = 1; i <= RetCount; i++)
{
PCopyMemory(ref clocking, pClockings, CKT_DLL.CLOCKINGRECORDSIZE);
pClockings = pClockings + CKT_DLL.CLOCKINGRECORDSIZE;
insertTimeAttendance(clocking.PersonID, clocking.Stat, Encoding.Default.GetString(clocking.Time), clocking.ID);
ProgressBar1.Value += 1;
}
if (ptemp != 0)
{
CKT_DLL.CKT_FreeMemory(ptemp);
}
}
if (Ret == 1)
{
return;
}
}
}
CKT_GetClockingNewRecordEx that method should be return new records. But it returns all records.
I guess, there is should be one method or config should be mark as downloaded.
Anyone some idea or solution?
Thanks,
Eba
I created the SDK you downloaded (basically written in Vb, and I just convert it to C#)
Actually for the Anviz EP300 device, there is no way you can just retrieve new records,neither retrieve user lists (for example), at list with that SDK.. It has a lot of methods, but unfortunately few of them works fine. You will have to Use CKT_GetClockingRecordEx, instead of CKT_DLL.CKT_GetClockingNewRecordEx

CoSign API: SAPI User Management (add edit delete) example?

My app enables external signers to sign documents. —Signers who are not employees. My app will create a CoSign digital certificate for them. Then they'll sign the document, then the user should be deleted from the system. I want my app to programmatically create/delete the users.
Is there a C# example of for the SAPI User Management API?
Here's a C# example of how to get user info
namespace UMSample
{
class Program
{
private const string ADMIN_USER = "AdminUser";
private const string ADMIN_PASS = "AdminPass";
static public int AddUser(string uid)
{
SAPIUM sapium = new SAPIUMClass();
SAPICrypt sapicrypt = new SAPICrypt();
int rc;
if ((rc = sapicrypt.Init()) != 0) return 1;
if ((rc = sapium.Init()) != 0) return 1;
UMSESHandle hSes = null;
// Handle Acquire
if ((rc = sapium.HandleAcquire(out hSes)) != 0) return 1;
// Logon as Administrator
if ((rc = sapium.Logon(hSes, ADMIN_USER, "", ADMIN_PASS)) != 0)
{
sapium.HandleRelease(hSes);
return 1;
}
string UserCN = uid + " Test User";
string UserEmail = uid+"#demo.com";
string Pwd = "12345678";
if ((rc = sapium.UserAdd(
hSes,
uid,
UserCN,
UserEmail,
Pwd,
1)) != 0)
{
sapium.Logoff(hSes);
sapium.HandleRelease(hSes);
return 1;
}
/*----------------------------------*/
// An example of how to get user info
UserHandle uh;
string s1, s2, s3, s4;
int c1, c2, c3, mask = 0, updtime = 0;
SAPI_UM_ENUM_USER_CERT_STATUS_TYPE certsts;
SAPI_UM_ENUM_USER_LOGIN_STATUS loginstat;
SAPI_UM_ENUM_USER_TYPE kind = SAPI_UM_ENUM_USER_TYPE.SAPI_UM_USER_TYPE_NONE;
SAPI_UM_ENUM_USER_ENROLLMENT_STATUS enroll = SAPI_UM_ENUM_USER_ENROLLMENT_STATUS.SAPI_UM_NONE_USER_ENROLLMENT_STATUS;
SAPI_UM_ENUM_USER_ENROLLMENT_REASON enrReason;
SAPI_UM_ENUM_PENDING_REQUEST_STATUS_TYPE certrqsts;
rc = sapium.UserGetByLoginName(hSes, uid, out uh);
rc = sapium.UserInfoGetEx(hSes, uh, out s1, out s2, out s3, ref kind, ref mask, ref updtime, out s4,
out enroll, out enrReason, out loginstat, out c1, out c2, out c3, out certsts, out certrqsts);
/*----------------------------------*/
sapium.Logoff(hSes);
sapium.HandleRelease(hSes);
return 0;
}
static public int DelUser(string uid)
{
SAPIUM sapium = new SAPIUMClass();
int rc;
if ((rc = sapium.Init()) != 0) return 1;
UMSESHandle hSes = null;
if ((rc = sapium.HandleAcquire(out hSes)) != 0) return 1;
if ((rc = sapium.Logon(hSes, ADMIN_USER, "", ADMIN_PASS)) != 0)
{
sapium.HandleRelease(hSes);
return 1;
}
if ((rc = sapium.UserDelete(hSes, uid)) != 0)
{
sapium.Logoff(hSes);
sapium.HandleRelease(hSes);
return 1;
}
sapium.Logoff(hSes);
sapium.HandleRelease(hSes);
return 0;
}
static void Main(string[] args)
{
int rc;
for (int i = 0; i < 10; i++)
{
string uid = "Test" + i;
rc = AddUser(uid);
if (rc != 0) {
Console.WriteLine ("Error adding user: " + uid);
return;
}
rc = DelUser(uid);
if (rc != 0) {
Console.WriteLine ("Error deleting user: " + uid);
return;
}
Console.WriteLine("After handling user: " + uid);
}
Console.WriteLine("Press <Enter> to end");
Console.ReadKey();
}
}
}

WinCE: How can I determine the module that contains a code address?

I wrote a solution that involved OpenProcess, EnumProcessModules, GetModuleInformation and GetModuleBaseName, but apparently EnumProcessModules and GetModuleBaseName do not exist in Windows CE! What alternative is there?
I found a way to do this with CreateToolhelp32Snapshot, Module32First, Module32Next, Process32First and Process32Next. First you have to get a list of modules, then search through the list of modules to find the desired address.
#include <Tlhelp32.h>
struct MyModuleInfo
{
BYTE* Base;
HMODULE Handle;
DWORD Size;
enum { MaxNameLen = 36 };
TCHAR Name[MaxNameLen];
};
bool GetModuleList(vector<MyModuleInfo>& moduleList)
{
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS | TH32CS_SNAPMODULE | TH32CS_GETALLMODS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE)
return false;
MODULEENTRY32 moduleInfo;
moduleInfo.dwSize = sizeof(moduleInfo);
if (Module32First(hSnapshot, &moduleInfo)) do {
MyModuleInfo myInfo;
myInfo.Handle = moduleInfo.hModule;
myInfo.Base = moduleInfo.modBaseAddr;
myInfo.Size = moduleInfo.modBaseSize;
memcpy(myInfo.Name, moduleInfo.szModule, min(sizeof(myInfo.Name), sizeof(moduleInfo.szModule)));
myInfo.Name[myInfo.MaxNameLen-1] = '\0';
moduleList.push_back(myInfo);
} while (Module32Next(hSnapshot, &moduleInfo));
// The module list obtained above only contains DLLs! To get the EXE files
// also, we must call Process32First and Process32Next in a loop.
PROCESSENTRY32 processInfo;
processInfo.dwSize = sizeof(processInfo);
if (Process32First(hSnapshot, &processInfo)) do {
MyModuleInfo myInfo;
myInfo.Handle = NULL; // No handle given
myInfo.Base = (BYTE*)processInfo.th32MemoryBase;
myInfo.Size = 0x800000; // No size provided! Allow max 8 MB
memcpy(myInfo.Name, processInfo.szExeFile, min(sizeof(myInfo.Name), sizeof(processInfo.szExeFile)));
myInfo.Name[myInfo.MaxNameLen-1] = '\0';
moduleList.push_back(myInfo);
} while(Process32Next(hSnapshot, &processInfo));
// Debug output
for (int i = 0; i < (int)moduleList.size(); i++) {
MyModuleInfo& m = moduleList[i];
TRACE(_T("%-30s: 0x%08x - 0x%08x\n"), m.Name, (DWORD)m.Base, (DWORD)m.Base + m.Size);
}
CloseToolhelp32Snapshot(hSnapshot);
return true;
}
const MyModuleInfo* GetModuleForAddress(vector<MyModuleInfo>& moduleList, void* address)
{
for (int m = 0; m < (int)moduleList.size(); m++) {
const MyModuleInfo& mInfo = moduleList[m];
if (address >= mInfo.Base && address < mInfo.Base + mInfo.Size)
return &mInfo;
}
return NULL;
}

Resources