Ejemplo n.º 1
0
void 
	comm_serv::create_sec_attribute()
{
		char secDesc[ SECURITY_DESCRIPTOR_MIN_LENGTH ];
		secAttr.nLength = sizeof(secAttr);
		secAttr.bInheritHandle = FALSE;
		secAttr.lpSecurityDescriptor = &secDesc;
		InitializeSecurityDescriptor(secAttr.lpSecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
		SetSecurityDescriptorDacl(secAttr.lpSecurityDescriptor, TRUE, 0, FALSE);
		TCHAR * szSD = TEXT("D:")       // Discretionary ACL
			//TEXT("(D;OICI;GA;;;BG)")     // Deny access to built-in guests
			//TEXT("(D;OICI;GA;;;AN)")     // Deny access to anonymous logon
			TEXT("(A;OICI;GRGWGX;;;AU)") // Allow read/write/execute to authenticated users
			TEXT("(A;OICI;GA;;;BA)");    // Allow full control to administrators

		PSECURITY_DESCRIPTOR pSD;
		BOOL retcode =ConvertStringSecurityDescriptorToSecurityDescriptor("S:(ML;;NW;;;LW)",SDDL_REVISION_1,&pSD,NULL);
		DWORD aa=GetLastError();

		if(retcode != 0){ 
		PACL pSacl = NULL;
		BOOL fSaclPresent = FALSE;
		BOOL fSaclDefaulted = FALSE;
		retcode =GetSecurityDescriptorSacl(
			pSD,
			&fSaclPresent,
			&pSacl,
			&fSaclDefaulted);
		if (pSacl) retcode =SetSecurityDescriptorSacl(secAttr.lpSecurityDescriptor, TRUE, pSacl, FALSE); 
		}
}
Ejemplo n.º 2
0
BOOL CreateFullRightsDACL(SECURITY_ATTRIBUTES * pSA)
{
     pSA->nLength = sizeof(SECURITY_ATTRIBUTES);
     pSA->bInheritHandle = FALSE;

     // Define the SDDL for the DACL. This example sets
     // the following access:
     //     Built-in guests are denied all access.
     //     Anonymous logon is denied all access.
     //     Authenticated users are allowed
     //     read/write/execute access.
     //     Administrators are allowed full control.
     // Modify these values as needed to generate the proper
     // DACL for your application.
     TCHAR * szSD = TEXT("D:")       // Discretionary ACL
        FULL_RIGHTS(BG)     // Deny access to
                                     // built-in guests
        FULL_RIGHTS(AN)     // Deny access to
                                     // anonymous logon
        FULL_RIGHTS(AU) // Allow
                                     // read/write/execute
                                     // to authenticated
                                     // users
        FULL_RIGHTS(BA);    // Allow full control
                                     // to administrators

    if (NULL == pSA)
        return FALSE;

     return ConvertStringSecurityDescriptorToSecurityDescriptor(
                szSD,
                SDDL_REVISION_1,
                &(pSA->lpSecurityDescriptor),
                NULL);
}
Ejemplo n.º 3
0
BOOL KProcessPerfCacheMgr::SetObjectToLowIntegrity(HANDLE hObject, SE_OBJECT_TYPE type)
{
	bool  bRetCode       = false;
	DWORD dwErr          = ERROR_SUCCESS;
	PACL  pSacl          = NULL;
	BOOL  fSaclPresent   = FALSE;
	BOOL  fSaclDefaulted = FALSE;
	PSECURITY_DESCRIPTOR pSD = NULL;

#define LOW_INTEGRITY_SDDL_SACL     TEXT("S:(ML;;NW;;;LW)")
#ifndef LABEL_SECURITY_INFORMATION
#define LABEL_SECURITY_INFORMATION   (0x00000010L)
#endif

	if (
		ConvertStringSecurityDescriptorToSecurityDescriptor(
		LOW_INTEGRITY_SDDL_SACL, SDDL_REVISION_1, &pSD, NULL)
		)
	{
		if (GetSecurityDescriptorSacl(pSD, &fSaclPresent, &pSacl, &fSaclDefaulted))
		{
			dwErr = SetSecurityInfo( 
				hObject, type, LABEL_SECURITY_INFORMATION,
				NULL, NULL, NULL, pSacl
				);

			bRetCode = (ERROR_SUCCESS == dwErr);
		}

		LocalFree (pSD);
	}

	return bRetCode;
}
Ejemplo n.º 4
0
HANDLE GetAnonymousToken()
{
  ImpersonateAnonymousToken(GetCurrentThread());
  HANDLE hToken;
  OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, TRUE, &hToken);
  RevertToSelf();
  
  PSECURITY_DESCRIPTOR pSD;
  ULONG sd_length;
  if (!ConvertStringSecurityDescriptorToSecurityDescriptor(L"D:(A;;GA;;;WD)(A;;GA;;;AN)", SDDL_REVISION_1, &pSD, &sd_length))
  {
    printf("Error converting SDDL: %d\n", GetLastError());
    exit(1);
  }

  TOKEN_DEFAULT_DACL dacl;
  BOOL bPresent;
  BOOL bDefaulted;
  PACL pDACL;
  GetSecurityDescriptorDacl(pSD, &bPresent, &pDACL, &bDefaulted);
  dacl.DefaultDacl = pDACL;

  if (!SetTokenInformation(hToken, TokenDefaultDacl, &dacl, sizeof(dacl)))
  {
    printf("Error setting default DACL: %d\n", GetLastError());
    exit(1);
  }

  return hToken;
}
Ejemplo n.º 5
0
// CreateMyDACL
// Creates a security descriptor containing the
// desired DACL. This function uses SDDL to make Deny and Allow ACEs.
//
// Parameter:
//     SECURITY_ATTRIBUTES * pSA
// Address to a SECURITY_ATTRIBUTES structure. It is the caller's
// responsibility to properly initialize the structure, and to free 
// the structure's lpSecurityDescriptor member when done (by calling
// the LocalFree function).
// 
// Return value:
//    FALSE if the address to the structure is NULL. 
//    Otherwise, this function returns the value from the
//    ConvertStringSecurityDescriptorToSecurityDescriptor function.
BOOL CreateMyDACL(SECURITY_ATTRIBUTES * pSA)
{
    // Define the SDDL for the DACL. This example sets 
    // the following access:
    //     Built-in guests are denied all access.
    //     Anonymous Logon is denied all access.
    //     Authenticated Users are allowed read/write/execute access.
    //     Administrators are allowed full control.
    // Modify these values as needed to generate the proper
    // DACL for your application. 
    TCHAR * szSD = "D:"                   // Discretionary ACL
                   "(D;OICI;GA;;;BG)"     // Deny access to Built-in Guests
                   "(D;OICI;GA;;;AN)"     // Deny access to Anonymous Logon
                   "(A;OICI;GRGWGX;;;AU)" // Allow read/write/execute to Authenticated Users
                   "(A;OICI;GA;;;BA)";    // Allow full control to Administrators

    if (NULL == pSA)
        return FALSE;

    return ConvertStringSecurityDescriptorToSecurityDescriptor(
                                                              szSD,
                                                              SDDL_REVISION_1,
                                                              &(pSA->lpSecurityDescriptor),
                                                              NULL);
}
int MachineInstaller::PerformMachineInstallSetup()
{
	wchar_t packageName[512];

	if (!findPackageFromEmbeddedZip(packageName, sizeof(packageName))) {
		MessageBox(NULL, L"Corrupt installer", L"Cannot find package name for installer, is it created correctly?", MB_OK);
		return ERROR_INVALID_PARAMETER;
	}

	wchar_t machineInstallFolder[MAX_PATH];
	SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, machineInstallFolder);
	wcscat(machineInstallFolder, L"\\SquirrelMachineInstalls");

	// NB: This is the DACL for Program Files
	PSECURITY_DESCRIPTOR descriptor;
	ConvertStringSecurityDescriptorToSecurityDescriptor(
		L"D:PAI(A;;FA;;;S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464)(A;CIIO;GA;;;S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464)(A;;0x1301bf;;;SY)(A;OICIIO;GA;;;SY)(A;;0x1301bf;;;BA)(A;OICIIO;GA;;;BA)(A;;0x1200a9;;;BU)(A;OICIIO;GXGR;;;BU)(A;OICIIO;GA;;;CO)(A;;0x1200a9;;;AC)(A;OICIIO;GXGR;;;AC)",
		SDDL_REVISION_1,
		&descriptor, NULL);

	SECURITY_ATTRIBUTES attrs;
	attrs.nLength = sizeof(SECURITY_ATTRIBUTES);
	attrs.bInheritHandle = false;
	attrs.lpSecurityDescriptor = descriptor;

	if (!CreateDirectory(machineInstallFolder, &attrs) && GetLastError() != ERROR_ALREADY_EXISTS) {
		LocalFree(descriptor);
		return GetLastError();
	}

	LocalFree(descriptor);

	wcscat(machineInstallFolder, L"\\");
	wcscat(machineInstallFolder, packageName);
	wcscat(machineInstallFolder, L".exe");

	wchar_t ourFile[MAX_PATH];
	HMODULE hMod = GetModuleHandle(NULL);
	GetModuleFileName(hMod, ourFile, _countof(ourFile));

	if (!CopyFile(ourFile, machineInstallFolder, false)) {
		return GetLastError();
	}

	HKEY runKey;
	DWORD dontcare;
	if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, NULL, 0, KEY_ALL_ACCESS, NULL, &runKey, &dontcare) != ERROR_SUCCESS) {
		return GetLastError();
	}

	wcscat_s(machineInstallFolder, L" --checkInstall");

	if (RegSetValueEx(runKey, packageName, 0, REG_SZ, (BYTE*)machineInstallFolder, (wcsnlen(machineInstallFolder, sizeof(machineInstallFolder)) + 1) * sizeof(wchar_t)) != ERROR_SUCCESS) {
		return GetLastError();
	}

	RegCloseKey(runKey);
	return 0;
}
Ejemplo n.º 7
0
static BOOL create_DACL(LPSECURITY_ATTRIBUTES psa)
{

    return ConvertStringSecurityDescriptorToSecurityDescriptor(
                NTSD_STRING,
                SDDL_REVISION_1,
                &(psa->lpSecurityDescriptor),
                NULL);
}
Ejemplo n.º 8
0
//   FUNCTION: CreatePipeSecurity(PSECURITY_ATTRIBUTES *)
//
//   PURPOSE: The CreatePipeSecurity function creates and initializes a new 
//   SECURITY_ATTRIBUTES structure to allow Authenticated Users read and 
//   write access to a pipe, and to allow the Administrators group full 
//   access to the pipe.
//
//   PARAMETERS:
//   * ppSa - output a pointer to a SECURITY_ATTRIBUTES structure that allows 
//     Authenticated Users read and write access to a pipe, and allows the 
//     Administrators group full access to the pipe. The structure must be 
//     freed by calling FreePipeSecurity.
//
//   RETURN VALUE: Returns TRUE if the function succeeds..
//
//   EXAMPLE CALL:
//
//     PSECURITY_ATTRIBUTES pSa = NULL;
//     if (CreatePipeSecurity(&pSa))
//     {
//         // Use the security attributes
//         // ...
//
//         FreePipeSecurity(pSa);
//     }
//
BOOL CreatePipeSecurity(PSECURITY_ATTRIBUTES *ppSa)
{
    BOOL fSucceeded = TRUE;
    DWORD dwError = ERROR_SUCCESS;

    PSECURITY_DESCRIPTOR pSd = NULL;
    PSECURITY_ATTRIBUTES pSa = NULL;

    // Define the SDDL for the security descriptor.
    PCWSTR szSDDL = L"D:"       // Discretionary ACL
        L"(A;OICI;GRGW;;;AU)"   // Allow read/write to authenticated users
        L"(A;OICI;GA;;;BA)";    // Allow full control to administrators

    if (!ConvertStringSecurityDescriptorToSecurityDescriptor(szSDDL, 
        SDDL_REVISION_1, &pSd, NULL))
    {
        fSucceeded = FALSE;
        dwError = GetLastError();
        goto Cleanup;
    }
    
    // Allocate the memory of SECURITY_ATTRIBUTES.
    pSa = (PSECURITY_ATTRIBUTES)LocalAlloc(LPTR, sizeof(*pSa));
    if (pSa == NULL)
    {
        fSucceeded = FALSE;
        dwError = GetLastError();
        goto Cleanup;
    }

    pSa->nLength = sizeof(*pSa);
    pSa->lpSecurityDescriptor = pSd;
    pSa->bInheritHandle = FALSE;

    *ppSa = pSa;

Cleanup:
    // Clean up the allocated resources if something is wrong.
    if (!fSucceeded)
    {
        if (pSd)
        {
            LocalFree(pSd);
            pSd = NULL;
        }
        if (pSa)
        {
            LocalFree(pSa);
            pSa = NULL;
        }

        SetLastError(dwError);
    }
    
    return fSucceeded;
}
Ejemplo n.º 9
0
static VOID BuildSecurityAttributes(PSECURITY_ATTRIBUTES SecurityAttributes)
{
	LPWSTR sd = L"D:P(A;;GA;;;SY)(A;;GRGWGX;;;BA)(A;;GRGW;;;WD)(A;;GR;;;RC)";

	ZeroMemory(SecurityAttributes, sizeof(SECURITY_ATTRIBUTES));
	
	ConvertStringSecurityDescriptorToSecurityDescriptor(
		sd,
		SDDL_REVISION_1,
		&SecurityAttributes->lpSecurityDescriptor,
		NULL);

	SecurityAttributes->nLength = sizeof(SECURITY_ATTRIBUTES);
    SecurityAttributes->bInheritHandle = TRUE;
}
Ejemplo n.º 10
0
/*
 * Class:     sun_tools_attach_VirtualMachineImpl
 * Method:    createPipe
 * Signature: (Ljava/lang/String;)J
 */
JNIEXPORT jlong JNICALL Java_sun_tools_attach_VirtualMachineImpl_createPipe
  (JNIEnv *env, jclass cls, jstring pipename)
{
    HANDLE hPipe;
    char name[MAX_PIPE_NAME_LENGTH];

    SECURITY_ATTRIBUTES sa;
    LPSECURITY_ATTRIBUTES lpSA = NULL;
    // Custom Security Descriptor is required here to "get" Medium Integrity Level.
    // In order to allow Medium Integrity Level clients to open
    // and use a NamedPipe created by an High Integrity Level process.
    TCHAR *szSD = TEXT("D:")                  // Discretionary ACL
                  TEXT("(A;OICI;GRGW;;;WD)")  // Allow read/write to Everybody
                  TEXT("(A;OICI;GA;;;SY)")    // Allow full control to System
                  TEXT("(A;OICI;GA;;;BA)");   // Allow full control to Administrators

    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.bInheritHandle = FALSE;
    sa.lpSecurityDescriptor = NULL;

    if (ConvertStringSecurityDescriptorToSecurityDescriptor
          (szSD, SDDL_REVISION_1, &(sa.lpSecurityDescriptor), NULL)) {
        lpSA = &sa;
    }

    jstring_to_cstring(env, pipename, name, MAX_PIPE_NAME_LENGTH);

    hPipe = CreateNamedPipe(
          name,                         // pipe name
          PIPE_ACCESS_INBOUND,          // read access
          PIPE_TYPE_BYTE |              // byte mode
            PIPE_READMODE_BYTE |
            PIPE_WAIT,                  // blocking mode
          1,                            // max. instances
          128,                          // output buffer size
          8192,                         // input buffer size
          NMPWAIT_USE_DEFAULT_WAIT,     // client time-out
          lpSA);        // security attributes

    LocalFree(sa.lpSecurityDescriptor);

    if (hPipe == INVALID_HANDLE_VALUE) {
        char msg[256];
        _snprintf(msg, sizeof(msg), "CreateNamedPipe failed: %d", GetLastError());
        JNU_ThrowIOExceptionWithLastError(env, msg);
    }
    return (jlong)hPipe;
}
Ejemplo n.º 11
0
Archivo: rootkit.c Proyecto: XOR2/GoBot
_Bool SelfDefense()
{
	HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId());
	SECURITY_ATTRIBUTES sa;
	TCHAR * szSD = TEXT("D:P");
	TEXT("(D;OICI;GA;;;BG)");
	TEXT("(D;OICI;GA;;;AN)");

	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	sa.bInheritHandle = FALSE;
	if (!ConvertStringSecurityDescriptorToSecurityDescriptor(szSD, SDDL_REVISION_1, &(sa.lpSecurityDescriptor), NULL))
		return FALSE;
	if (!SetKernelObjectSecurity(hProcess, DACL_SECURITY_INFORMATION, sa.lpSecurityDescriptor))
		return FALSE;
	return TRUE;
}
Ejemplo n.º 12
0
/// Prelude actions to start up the service, e.g. to set any global variables from the settings or perform
/// any system specific actions. E.g. the Windows implementation registers with the service control manager
/// and can optionally set the security descriptor on the process to allow clients to kill/restart it.
///
/// @param[in] nReason how the startup is occuring (e.g. SERVICE_RUN_INLINE) - different actions may be
/// required depending on whether the code is running direct from main() or through another mechansim
static void _ServiceStartup (int nReason) {
	CSettings oSettings;
#ifdef _WIN32
	if (nReason == SERVICE_RUN_SCM) {
		g_hServiceStatus = RegisterServiceCtrlHandler (oSettings.GetServiceName (), ServiceHandler);
	}
	PCTSTR pszSDDL = oSettings.GetServiceSDDL ();
	if (pszSDDL) {
		LOGDEBUG (TEXT ("Setting security descriptor ") << pszSDDL);
		PSECURITY_DESCRIPTOR psdRelative;
		if (ConvertStringSecurityDescriptorToSecurityDescriptor (pszSDDL, SDDL_REVISION_1, &psdRelative, NULL)) {
			DWORD cbAbsolute = 1024;
			PSECURITY_DESCRIPTOR psdAbsolute = (PSECURITY_DESCRIPTOR)malloc (cbAbsolute);
			DWORD cbD = 1024;
			PACL paclD = (PACL)malloc (cbD);
			DWORD cbS = 1024;
			PACL paclS = (PACL)malloc (cbS);
			DWORD cbOwner = 1024;
			PSID psidOwner = (PSID)malloc (cbOwner);
			DWORD cbPGroup = 1024;
			PSID psidPGroup = (PSID)malloc (cbPGroup);
			if (MakeAbsoluteSD (psdRelative, psdAbsolute, &cbAbsolute, paclD, &cbD, paclS, &cbS, psidOwner, &cbOwner, psidPGroup, &cbPGroup)) {
				DWORD dwError = SetSecurityInfo (GetCurrentProcess (), SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, paclD, NULL);
				if (dwError == ERROR_SUCCESS) {
					LOGINFO (TEXT ("Security descriptor set on process handle"));
				} else {
					LOGWARN (TEXT ("Couldn't set security descriptor on process handle, error ") << GetLastError ());
				}
			} else {
				LOGWARN (TEXT ("Couldn't create absolute security description, error ") << GetLastError ());
			}
			free (psdAbsolute);
			free (paclD);
			free (paclS);
			free (psidOwner);
			free (psidPGroup);
			LocalFree (psdRelative);
		} else {
			LOGWARN (TEXT ("Couldn't parse SDDL ") << pszSDDL << TEXT (", error ") << GetLastError ());
		}
	} else {
		LOGDEBUG (TEXT ("No security descriptor specified"));
	}
#endif /* ifdef _WIN32 */
	g_lBusyTimeout = oSettings.GetBusyTimeout ();
	_ReportStateStarting ();
}
Ejemplo n.º 13
0
VOID TestPrivateNamespace()
{
	HANDLE hBoundaryDescriptor = NULL;
	BOOL cond = FALSE;
	SECURITY_ATTRIBUTES sa;

	BYTE localAdminSID[SECURITY_MAX_SID_SIZE];
	PSID pLocalAdminSID = &localAdminSID; 
	DWORD cbSID = sizeof(localAdminSID);
	CHAR text[1000];

	do {
		RtlSecureZeroMemory(&localAdminSID, sizeof(localAdminSID));
		hBoundaryDescriptor = CreateBoundaryDescriptor(TEXT("TestBoundaryDescriptor"), 0);
		if (hBoundaryDescriptor == NULL) {
			break;
		}

		if (!CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, pLocalAdminSID, &cbSID)) {
			break;
		}
		if (!AddSIDToBoundaryDescriptor(&hBoundaryDescriptor, pLocalAdminSID)) {
			break;
		}

		RtlSecureZeroMemory(&sa, sizeof(sa));
		sa.nLength = sizeof(sa); 
		sa.bInheritHandle = FALSE;
		if (!ConvertStringSecurityDescriptorToSecurityDescriptor(TEXT("D:(A;;GA;;;BA)"),
			SDDL_REVISION_1, &sa.lpSecurityDescriptor, NULL)) {
			break;
		}

		g_hNamespace = CreatePrivateNamespace(&sa, hBoundaryDescriptor, TEXT("Mynamespace2"));
		LocalFree(sa.lpSecurityDescriptor);
		
		if (g_hNamespace == NULL) {
			ultostr_a(GetLastError(), text);
			OutputDebugStringA(text);
			break;
		}

		g_hMutex = CreateMutex(NULL, FALSE, TEXT("Mynamespace2\\TestMutex"));

	} while (cond);

}
Ejemplo n.º 14
0
gboolean
spice_win32_set_low_integrity (void* handle, GError **error)
{
    g_return_val_if_fail (handle != NULL, FALSE);
    g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

    /* see also http://msdn.microsoft.com/en-us/library/bb625960.aspx */
    PSECURITY_DESCRIPTOR psd = NULL;
    PACL psacl = NULL;
    BOOL sacl_present = FALSE;
    BOOL sacl_defaulted = FALSE;
    char *emsg;
    int errsv;
    gboolean success = FALSE;

    if (!ConvertStringSecurityDescriptorToSecurityDescriptor ("S:(ML;;NW;;;LW)",
            SDDL_REVISION_1, &psd, NULL))
        goto failed;

    if (!GetSecurityDescriptorSacl (psd, &sacl_present, &psacl, &sacl_defaulted))
        goto failed;

    if (SetSecurityInfo (handle, SE_KERNEL_OBJECT, LABEL_SECURITY_INFORMATION,
                         NULL, NULL, NULL, psacl) != ERROR_SUCCESS)
        goto failed;

    success = TRUE;
    goto end;

failed:
    errsv = GetLastError ();
    emsg = g_win32_error_message (errsv);
    g_set_error (error, G_IO_ERROR,
                 g_io_error_from_win32_error (errsv),
                 "Error setting integrity: %s",
                 emsg);
    g_free (emsg);

end:
    if (psd != NULL)
        LocalFree (psd);

    return success;
}
Ejemplo n.º 15
0
/* Cygwin/Mingw do not define ConvertStringSecurityDescriptorToSecurityDescriptor().
 * This would allow for ./smtpf -quit by an admin. user. The current alternative is
 * to use the Windows service console or "net start smtp" and "net stop smtpf".
 */
static int
createMyDACL(SECURITY_ATTRIBUTES *sa)
{
	TCHAR * szSD =
	TEXT("D:")			/* Discretionary ACL */
	TEXT("(OD;OICI;GA;;;BG)")     	/* Deny access to built-in guests */
	TEXT("(OD;OICI;GA;;;AN)")     	/* Deny access to anonymous logon */
#  ifdef ALLOW_AUTH_USER
	TEXT("(OA;OICI;GRGWGX;;;AU)") 	/* Allow read/write/execute auth. users */
#  endif
	TEXT("(OA;OICI;GA;;;BA)");    	/* Allow full control to administrators. */

	if (sa == NULL)
		return 0;

	return ConvertStringSecurityDescriptorToSecurityDescriptor(
		szSD, SDDL_REVISION_1, &sa->lpSecurityDescriptor, NULL
	);
}
Ejemplo n.º 16
0
BOOLEAN DbgCreateSecurityAttributes(
    _Inout_ PPH_DBGEVENTS_CONTEXT Context
    )
{
    Context->SecurityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
    Context->SecurityAttributes.bInheritHandle = TRUE;

    if (ConvertStringSecurityDescriptorToSecurityDescriptor(
        L"D:(A;;GRGWGX;;;WD)(A;;GA;;;SY)(A;;GA;;;BA)(A;;GRGWGX;;;AN)(A;;GRGWGX;;;RC)(A;;GRGWGX;;;S-1-15-2-1)S:(ML;;NW;;;LW)",
        SDDL_REVISION,
        &Context->SecurityAttributes.lpSecurityDescriptor,
        NULL
        ))
    {
        return TRUE;
    }

    return FALSE;
}
Ejemplo n.º 17
0
BOOL createMyDACL(SECURITY_ATTRIBUTES *pSA)
{
    TCHAR* sd =
        L"D:"
        L"(D;OICI;GA;;;BG)"
        L"(D;OICI;GA;;;AN)"
        L"(A;OICI;GRGWGX;;;AU)"
        L"(A;OICI;GA;;;BA)";
    if (sd == NULL) {
        return false;
    }

    return ConvertStringSecurityDescriptorToSecurityDescriptor(
               sd,
               SDDL_REVISION,
               &pSA->lpSecurityDescriptor,
               NULL);

}
Ejemplo n.º 18
0
static int ctrl_iface_parse(struct ctrl_iface_priv *priv, const char *params)
{
	const char *sddl = NULL;
	TCHAR *t_sddl;

	if (os_strncmp(params, "SDDL=", 5) == 0)
		sddl = params + 5;
	if (!sddl) {
		sddl = os_strstr(params, " SDDL=");
		if (sddl)
			sddl += 6;
	}

	if (!sddl)
		return 0;

	wpa_printf(MSG_DEBUG, "CTRL: SDDL='%s'", sddl);
	os_memset(&priv->attr, 0, sizeof(priv->attr));
	priv->attr.nLength = sizeof(priv->attr);
	priv->attr.bInheritHandle = FALSE;
	t_sddl = wpa_strdup_tchar(sddl);
	if (t_sddl == NULL)
		return -1;
	if (!ConvertStringSecurityDescriptorToSecurityDescriptor(
		    t_sddl, SDDL_REVISION_1,
		    (PSECURITY_DESCRIPTOR *) (void *)
		    &priv->attr.lpSecurityDescriptor,
		    NULL)) {
		os_free(t_sddl);
		wpa_printf(MSG_ERROR, "CTRL: SDDL='%s' - could not convert to "
			   "security descriptor: %d",
			   sddl, (int) GetLastError());
		return -1;
	}
	os_free(t_sddl);

	priv->sec_attr_set = 1;

	return 0;
}
Ejemplo n.º 19
0
BOOL CreateMyDACL(SECURITY_ATTRIBUTES * pSA)
{
     TCHAR * szSD = TEXT("D:")       // Discretionary ACL
        TEXT("(D;OICI;GA;;;BG)")     // Deny access to
                                     // built-in guests
        TEXT("(D;OICI;GA;;;AN)")     // Deny access to
                                     // anonymous logon
        TEXT("(A;OICI;GRGWGX;;;AU)") // Allow
                                     // read/write/execute
                                     // to authenticated
                                     // users
        TEXT("(A;OICI;GA;;;BA)");    // Allow full control
                                     // to administrators

    if (NULL == pSA)
        return FALSE;

     return ConvertStringSecurityDescriptorToSecurityDescriptor(
                szSD,
                SDDL_REVISION_1,
                &(pSA->lpSecurityDescriptor),
                NULL);
}
Ejemplo n.º 20
0
int Event_Create(
						PVOID pVoid,
						BOOL bManualReset,
						BOOL bInitialState,
						const char *szName
					)
{

	PEVENT pEvent;

#if FIX_NAMED_OBJECT_NAMESPACE

    char szFixedUpNameBuffer[255] = {0};
#endif
    const char* lpszFixedObjectName = szName;
    LPSECURITY_ATTRIBUTES pSecurityAttributes = 0;
    SECURITY_DESCRIPTOR secDesc = {0};
    SECURITY_ATTRIBUTES attr = {0};
    PSECURITY_DESCRIPTOR pSD = NULL;

	if(!pVoid)
		return ERROR_INVALID_ARGUMENT;
	pEvent = (PEVENT) pVoid;

	if(pEvent->hEvent != NULL)
		return SUCCESS;


    //if this is a named object then we are going to open up the permissions on it
    //so people in other accounts / sessions can also use the same shared named object.
    //Starting w/ vista services and the logged in users are no longer in the same session anymore aswell.
    if(szName)
    {
#if FIX_SECURITY_DACL
        if(InitializeSecurityDescriptor(&secDesc,SECURITY_DESCRIPTOR_REVISION))
        {
            //all access to this object for everyone
            if(SetSecurityDescriptorDacl(&secDesc, TRUE, NULL, FALSE))
            {
                attr.nLength = sizeof(attr);
                attr.lpSecurityDescriptor = &secDesc;
                pSecurityAttributes = &attr;

                //Vista introduces "integrity" check levels.  We are going to set this to "low"
                //to prevent us from locking out a low-integrity process if someone in 
                //a service uses the api to open the mutex first.
                if(IsVistaOrBetter())
                {
                    if(ConvertStringSecurityDescriptorToSecurityDescriptor( "S:(ML;;NW;;;LW)", // "low integrity"
                        SDDL_REVISION_1,
                        &pSD,
                        NULL))
                    {
                        PACL pSacl = NULL;                  // not allocated
                        BOOL fSaclPresent = FALSE;
                        BOOL fSaclDefaulted = FALSE;
                        GetSecurityDescriptorSacl(
                            pSD,
                            &fSaclPresent,
                            &pSacl,
                            &fSaclDefaulted);
                        SetSecurityDescriptorSacl(attr.lpSecurityDescriptor, TRUE, pSacl, FALSE);
                    }
                }
            }
        }
#endif        
#if FIX_NAMED_OBJECT_NAMESPACE
        //For creating the event in the global namespace
        strcat(szFixedUpNameBuffer,"Global\\");
        strcat(szFixedUpNameBuffer,szName);
        lpszFixedObjectName = szFixedUpNameBuffer;
#endif
    }

    pEvent->hEvent = CreateEvent(
							pSecurityAttributes,    /*  no security attributes */
							bManualReset,			/*  manual-reset event flag */
							bInitialState,			/*  initial state flag */
							lpszFixedObjectName			/*  object name */
						  ); 
    //local free if needed
    if(pSD)
    {
        //preserve last error
        DWORD dwLastError = GetLastError();
        LocalFree((HLOCAL)pSD);
        SetLastError(dwLastError);
    }

	if(pEvent->hEvent == NULL)
		return ERROR_CREATE_EVENT_FAILED;

	return SUCCESS;
}
Ejemplo n.º 21
0
bool comm_serv::Init(char *name,int IN_datasize_IN,int IN_datasize_OUT,bool app,bool master)
{
	datasize_IN=IN_datasize_IN;
	datasize_OUT=IN_datasize_OUT;

	char secDesc[ SECURITY_DESCRIPTOR_MIN_LENGTH ];
		secAttr.nLength = sizeof(secAttr);
		secAttr.bInheritHandle = FALSE;
		secAttr.lpSecurityDescriptor = &secDesc;
		InitializeSecurityDescriptor(secAttr.lpSecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
		SetSecurityDescriptorDacl(secAttr.lpSecurityDescriptor, TRUE, 0, FALSE);
		TCHAR * szSD = TEXT("D:")       // Discretionary ACL
			//TEXT("(D;OICI;GA;;;BG)")     // Deny access to built-in guests
			//TEXT("(D;OICI;GA;;;AN)")     // Deny access to anonymous logon
			TEXT("(A;OICI;GRGWGX;;;AU)") // Allow read/write/execute to authenticated users
			TEXT("(A;OICI;GA;;;BA)");    // Allow full control to administrators

		PSECURITY_DESCRIPTOR pSD;
		BOOL retcode =ConvertStringSecurityDescriptorToSecurityDescriptor("S:(ML;;NW;;;LW)",SDDL_REVISION_1,&pSD,NULL);
		DWORD aa=GetLastError();

		if(retcode != 0){ 
		PACL pSacl = NULL;
		BOOL fSaclPresent = FALSE;
		BOOL fSaclDefaulted = FALSE;
		retcode =GetSecurityDescriptorSacl(
			pSD,
			&fSaclPresent,
			&pSacl,
			&fSaclDefaulted);
		if (pSacl) retcode =SetSecurityDescriptorSacl(secAttr.lpSecurityDescriptor, TRUE, pSacl, FALSE); 
		}

	char savename[42];
	strcpy_s(savename,42,name);
	if (app)
	{
		strcpy_s(filemapping_IN,64,"");
		strcpy_s(filemapping_OUT,64,"");
		strcpy_s(event_IN,64,"");
		strcpy_s(event_IN_DONE,64,"");
		strcpy_s(event_OUT,64,"");
		strcpy_s(event_OUT_DONE,64,"");

		strcat_s(filemapping_IN,64,name);
		strcat_s(filemapping_IN,64,"fm_IN");
		strcat_s(filemapping_OUT,64,name);
		strcat_s(filemapping_OUT,64,"fm_OUT");
		strcat_s(event_IN,64,name);
		strcat_s(event_IN,64,"event_IN");
		strcat_s(event_IN_DONE,64,name);
		strcat_s(event_IN_DONE,64,"event_IN_DONE");
		strcat_s(event_OUT,64,name);
		strcat_s(event_OUT,64,"event_OUT");
		strcat_s(event_OUT_DONE,64,name);
		strcat_s(event_OUT_DONE,64,"event_OUT_DONE");
	}
	else
	{
		strcpy_s(filemapping_IN,64,"Global\\");
		strcpy_s(filemapping_OUT,64,"Global\\");
		strcpy_s(event_IN,64,"Global\\");
		strcpy_s(event_IN_DONE,64,"Global\\");
		strcpy_s(event_OUT,64,"Global\\");
		strcpy_s(event_OUT_DONE,64,"Global\\");

		strcat_s(filemapping_IN,64,name);
		strcat_s(filemapping_IN,64,"fm_IN");
		strcat_s(filemapping_OUT,64,name);
		strcat_s(filemapping_OUT,64,"fm_OUT");
		strcat_s(event_IN,64,name);
		strcat_s(event_IN,64,"event_IN");
		strcat_s(event_IN_DONE,64,name);
		strcat_s(event_IN_DONE,64,"event_IN_DONE");
		strcat_s(event_OUT,64,name);
		strcat_s(event_OUT,64,"event_OUT");
		strcat_s(event_OUT_DONE,64,name);
		strcat_s(event_OUT_DONE,64,"event_OUT_DONE");
	}

	if (master)
	{
	if (!app)
	{
		if (datasize_IN!=0)
		{
		hMapFile_IN = CreateFileMapping(INVALID_HANDLE_VALUE,&secAttr,PAGE_READWRITE,0,datasize_IN,filemapping_IN);
		if (hMapFile_IN == NULL) return false;
		data_IN=(char*)MapViewOfFile(hMapFile_IN,FILE_MAP_ALL_ACCESS,0,0,datasize_IN);           
		if(data_IN==NULL) return false;
		}
		event_E_IN=CreateEvent(&secAttr, FALSE, FALSE, event_IN);
		if(event_E_IN==NULL) return false;
		event_E_IN_DONE=CreateEvent(&secAttr, FALSE, FALSE, event_IN_DONE);
		if(event_IN_DONE==NULL) return false;

		if (datasize_OUT!=0)
		{
		hMapFile_OUT = CreateFileMapping(INVALID_HANDLE_VALUE,&secAttr,PAGE_READWRITE,0,datasize_OUT,filemapping_OUT);
		if (hMapFile_OUT == NULL) return false;
		data_OUT=(char*)MapViewOfFile(hMapFile_OUT,FILE_MAP_ALL_ACCESS,0,0,datasize_OUT);           
		if(data_OUT==NULL) return false;
		}
		event_E_OUT=CreateEvent(&secAttr, FALSE, FALSE, event_OUT);
		if(event_E_OUT==NULL) return false;
		event_E_OUT_DONE=CreateEvent(&secAttr, FALSE, FALSE, event_OUT_DONE);
		if(event_OUT_DONE==NULL) return false;
	}
	else
	{
		if (datasize_IN!=0)
		{
		hMapFile_IN = CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,datasize_IN,filemapping_IN);
		if (hMapFile_IN == NULL) return false;
		data_IN=(char*)MapViewOfFile(hMapFile_IN,FILE_MAP_ALL_ACCESS,0,0,datasize_IN);           
		if(data_IN==NULL) return false;
		}
		event_E_IN=CreateEvent(NULL, FALSE, FALSE, event_IN);
		if(event_E_IN==NULL) return false;
		event_E_IN_DONE=CreateEvent(NULL, FALSE, FALSE, event_IN_DONE);
		if(event_IN_DONE==NULL) return false;

		if (datasize_OUT!=0)
		{
		hMapFile_OUT = CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,datasize_OUT,filemapping_OUT);
		if (hMapFile_OUT == NULL) return false;
		data_OUT=(char*)MapViewOfFile(hMapFile_OUT,FILE_MAP_ALL_ACCESS,0,0,datasize_OUT);           
		if(data_OUT==NULL) return false;
		}
		event_E_OUT=CreateEvent(NULL, FALSE, FALSE, event_OUT);
		if(event_E_OUT==NULL) return false;
		event_E_OUT_DONE=CreateEvent(NULL, FALSE, FALSE, event_OUT_DONE);
		if(event_OUT_DONE==NULL) return false;
	}
	}
	else
	{
		if (!app)
		{
			if (datasize_IN!=0)
			{
			hMapFile_IN = OpenFileMapping(FILE_MAP_ALL_ACCESS,FALSE,filemapping_IN);
			DWORD aa=GetLastError();
			if (hMapFile_IN == NULL) return false;
			data_IN=(char*)MapViewOfFile(hMapFile_IN,FILE_MAP_ALL_ACCESS,0,0,datasize_IN);           
			if(data_IN==NULL) return false;
			}
			event_E_IN=OpenEvent(EVENT_ALL_ACCESS, FALSE, event_IN);
			if(event_E_IN==NULL) return false;
			ResetEvent(event_E_IN);
			event_E_IN_DONE=OpenEvent(EVENT_ALL_ACCESS, FALSE, event_IN_DONE);
			if(event_IN_DONE==NULL) return false;
			ResetEvent(event_IN_DONE);
			if (datasize_OUT!=0)
			{
			hMapFile_OUT = OpenFileMapping(FILE_MAP_ALL_ACCESS,FALSE,filemapping_OUT);
			if (hMapFile_OUT == NULL) return false;
			data_OUT=(char*)MapViewOfFile(hMapFile_OUT,FILE_MAP_ALL_ACCESS,0,0,datasize_OUT);           
			if(data_OUT==NULL) return false;
			}
			event_E_OUT=OpenEvent(EVENT_ALL_ACCESS, FALSE, event_OUT);
			if(event_E_OUT==NULL) return false;
			ResetEvent(event_E_OUT);
			event_E_OUT_DONE=OpenEvent(EVENT_ALL_ACCESS, FALSE, event_OUT_DONE);
			if(event_OUT_DONE==NULL) return false;
			ResetEvent(event_OUT_DONE);
		}
		else
		{
			if (datasize_IN!=0)
			{
			hMapFile_IN = OpenFileMapping(FILE_MAP_ALL_ACCESS,FALSE,filemapping_IN);
			if (hMapFile_IN == NULL) return false;
			data_IN=(char*)MapViewOfFile(hMapFile_IN,FILE_MAP_ALL_ACCESS,0,0,datasize_IN);           
			if(data_IN==NULL) return false;
			}
			event_E_IN=OpenEvent(EVENT_ALL_ACCESS, FALSE, event_IN);
			if(event_E_IN==NULL) return false;
			ResetEvent(event_E_IN);
			event_E_IN_DONE=OpenEvent(EVENT_ALL_ACCESS, FALSE, event_IN_DONE);
			if(event_IN_DONE==NULL) return false;
			ResetEvent(event_IN_DONE);

			if (datasize_OUT!=0)
			{
			hMapFile_OUT =OpenFileMapping(FILE_MAP_ALL_ACCESS,FALSE,filemapping_OUT);
			if (hMapFile_OUT == NULL) return false;
			data_OUT=(char*)MapViewOfFile(hMapFile_OUT,FILE_MAP_ALL_ACCESS,0,0,datasize_OUT);           
			if(data_OUT==NULL) return false;
			}
			event_E_OUT=OpenEvent(EVENT_ALL_ACCESS, FALSE, event_OUT);
			if(event_E_OUT==NULL) return false;
			ResetEvent(event_E_OUT);
			event_E_OUT_DONE=OpenEvent(EVENT_ALL_ACCESS, FALSE, event_OUT_DONE);
			if(event_OUT_DONE==NULL) return false;
			ResetEvent(event_OUT_DONE);
		}
	}
	return true;
}
Ejemplo n.º 22
0
STDAPI DllRegisterServer (VOID)
{
    TCHAR       szModuleName[MAX_PATH]; 
    HRESULT     hResult = S_OK;
    TCHAR       szBuffer[MAX_PATH+10] = TEXT("");
    TCHAR       szClsid[MAX_PATH] = TEXT("");
    TCHAR       szSubKey[MAX_PATH] = TEXT("");
    TCHAR       szColumnProvider[MAX_PATH] = TEXT("");
    TCHAR       szDescription[MAX_PATH] = TEXT("");

    SECURITY_ATTRIBUTES SA;
    SA.nLength = sizeof(SECURITY_ATTRIBUTES);
    SA.bInheritHandle = TRUE;
    WCHAR *pwszSD=L"D:(A;OICI;GA;;;SY)(A;OICI;GA;;;BA)(A;OICI;GA;;;CO)(A;OICI;GRGWGX;;;IU)";
    //
    //  Load some necessary string values
    //
    //
    //  Initialize the security attributes structure
    //
    if (ConvertStringSecurityDescriptorToSecurityDescriptor(pwszSD,
							    SDDL_REVISION_1, 
							    &(SA.lpSecurityDescriptor), 
							    NULL)) 
      {
	LoadString (hDllInstance, IDS_CLSID, szClsid, MAX_PATH);
	LoadString (hDllInstance, IDS_DESCRIPTION, szDescription, MAX_PATH);
	LoadString (hDllInstance, IDS_REGKEY_COLUMNPROVIDER, szColumnProvider, MAX_PATH);
	
	
	//
	//  Get the name of this module
	//
	GetModuleFileName (hDllInstance, szModuleName, MAX_PATH);
	
	//
	//  Register the component under HKCR\CLSID
	//
	HKEY    hKey            = NULL;
	DWORD   dwDisposition   = 0;
	LRESULT lResult         = 0;
	
	wsprintf (szSubKey, TEXT("CLSID\\%s"), szClsid);
	lResult = RegCreateKeyEx (HKEY_CLASSES_ROOT, szSubKey,
				  0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS,
				  &SA, &hKey, &dwDisposition);
	
	if (lResult == NOERROR)
	  {
	    lResult = RegSetValueEx (hKey, TEXT(""), 0, REG_SZ, 
				     (LPBYTE) szDescription, GetStringByteSize(szDescription));
	    if (lResult != NOERROR)
	      hResult = SELFREG_E_CLASS;
	    RegCloseKey (hKey);
	    hKey = NULL;
	  }
	else
	  {
	    hResult = SELFREG_E_CLASS;
	  }
	
	//
	//  Register component information under HKCR\CLSID\{CLSID}
	//
	StrCatBuff (szSubKey, TEXT("\\InprocServer32"), ARRAYSIZE(szSubKey));
	lResult = RegCreateKeyEx (HKEY_CLASSES_ROOT, szSubKey,
				  0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS,
				  &SA, &hKey, &dwDisposition);
	
	if (lResult == NOERROR)
	  {
	    lstrcpyn (szBuffer, TEXT("Apartment"), ARRAYSIZE(szBuffer));
	    lResult = RegSetValueEx (hKey, TEXT("ThreadingModel"), 0, 
				     REG_SZ, (LPBYTE) szBuffer, GetStringByteSize (szBuffer));
	    if (lResult != NOERROR)
	      hResult = SELFREG_E_CLASS;
	    
	    lResult = RegSetValueEx (hKey, TEXT(""), 0, 
				     REG_SZ, (LPBYTE) szModuleName, GetStringByteSize(szModuleName));
	    if (lResult != NOERROR)
	      hResult = SELFREG_E_CLASS;
	    
	    RegCloseKey (hKey);
	    hKey = NULL;
	  }
	else
	  {
	    hResult = SELFREG_E_CLASS;
	  }
	
	//
	//  Register the component as a column provider extension under
	//  HKCR\Folder\shellex\ColumnHandlers
	//
	wsprintf (szSubKey, TEXT("%s\\%s"), szColumnProvider, szClsid);
	lResult = RegCreateKeyEx (HKEY_CLASSES_ROOT, szSubKey,
				  0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS,
				  &SA, &hKey, &dwDisposition);
	
	if (lResult != NOERROR)
	  {
	    hResult = SELFREG_E_CLASS;
	  }
	
	LocalFree(SA.lpSecurityDescriptor);
      } else {
	hResult = E_FAIL;
      }
    
    return hResult;
}
Ejemplo n.º 23
0
void CreateNamespaceForUser(LPCWSTR account_name)
{
  BYTE sid_bytes[MAX_SID_SIZE];
  WCHAR domain[256];
  SID_NAME_USE name_use;
  DWORD sid_size = MAX_SID_SIZE;
  DWORD domain_size = _countof(domain);

  if (!LookupAccountName(nullptr, account_name, (PSID)sid_bytes, &sid_size, domain, &domain_size, &name_use))
  {
    printf("[ERROR] getting SId for account %ls: %d\n", account_name, GetLastError());
    return;
  }

  LPWSTR sid_str;
  ConvertSidToStringSid((PSID)sid_bytes, &sid_str);

  std::wstring boundary_name = L"IEUser_";
  boundary_name += sid_str;
  boundary_name += L"_MicrosoftEdge";

  BoundaryDescriptor boundry;
  if (!boundry.Initialize(boundary_name.c_str()))
  {
    printf("[ERROR] initializing boundary descriptor: %d\n", GetLastError());
    return;
  }

  PSECURITY_DESCRIPTOR psd;
  ULONG sd_size = 0;
  std::wstring sddl = L"D:(A;OICI;GA;;;WD)(A;OICI;GA;;;AC)(A;OICI;GA;;;WD)(A;OICI;GA;;;S-1-0-0)";
  sddl += L"(A;OICI;GA;;;" + GetCurrentUserSid() + L")";
  sddl += L"(A;OICI;GA;;;" + GetCurrentLogonSid() + L")";
  sddl += L"S:(ML;OICI;NW;;;S-1-16-0)";

  if (!ConvertStringSecurityDescriptorToSecurityDescriptor(sddl.c_str(), SDDL_REVISION_1, &psd, &sd_size))
  {
    printf("[ERROR] converting SDDL: %d\n", GetLastError());
    return;
  }
  std::unique_ptr<void, LocalFreeDeleter> sd_buf(psd);

  SECURITY_ATTRIBUTES secattr = {};
  secattr.nLength = sizeof(secattr);
  secattr.lpSecurityDescriptor = psd;

  private_namespace ns(CreatePrivateNamespace(&secattr, boundry.boundry_desc(), boundary_name.c_str()));
  if (!ns)
  {
    printf("[ERROR] creating private namespace - %ls: %d\n", boundary_name.c_str(), GetLastError());
    return;
  }

  printf("[SUCCESS] Created Namespace %ls, start Edge as other user\n", boundary_name.c_str());
  
  std::wstring section_name = boundary_name + L"\\!PrivacIE!SharedMem!Settings";

  while (true)
  {
    HANDLE hMapping = OpenFileMapping(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, section_name.c_str());
    if (hMapping)
    {
      printf("[SUCCESS] Opened other user's !PrivacIE!SharedMem!Settings section for write access\n");
      return;
    }
    Sleep(1000);
  }
}
Ejemplo n.º 24
0
void DocConverterThread::run()
{
	HRESULT hr = E_FAIL;

	SECURITY_ATTRIBUTES SecurityAttributes = {0};

	HANDLE hNotifyPipe = NULL;

	do 
	{
		QStringList args = QCoreApplication::arguments();

		if(2 != args.count())
		{
			break;
		}

		QString strCommandLine = args[1].trimmed();
		
		int nEventPosition = strCommandLine.lastIndexOf("\\");

		if (-1 == nEventPosition)
		{
			break;
		}

		QString strEvent = strCommandLine.mid(nEventPosition + 1);
		
		if (true == strEvent.endsWith(":"))
		{
			strEvent.remove(strEvent.length() - 1, 1);
		}

		strExtractedFolder = strCommandLine.mid(0, nEventPosition);

		if (false == strExtractedFolder.endsWith("\\"))
		{
			strExtractedFolder.append("\\");
		}

		QString strEventName = QString("Global\\%1").arg(strEvent);

		HANDLE hEvent = OpenEvent(EVENT_MODIFY_STATE,
								  FALSE,
								  strEventName.toStdWString().c_str());

		//Validate Handle.
		if (NULL == hEvent)
		{
			break;
		}

		LPCWSTR lpwcsSDDL = NULL;

		//Grant ALL Access Permissions to Everyone.
		lpwcsSDDL = L"D:"                 //Discretionary ACL.
					L"(A;OICI;GA;;;WD)";  //Allow full control. 

		//Convert SDDL to Security Descriptor.
		if (FALSE == ConvertStringSecurityDescriptorToSecurityDescriptor(
								lpwcsSDDL,
								SDDL_REVISION_1,
								&(SecurityAttributes.lpSecurityDescriptor),
								NULL))
		{
			break;
		}

		//Create a Pipe Name from the Event Name.
        QString strPipeName = QString("\\\\.\\pipe\\%1_Pipe").arg(strEvent);

		hNotifyPipe = CreateNamedPipe(
                        strPipeName.toStdWString().c_str(),          //pipe name.
                        PIPE_ACCESS_INBOUND,       //read/write access.
                        PIPE_TYPE_BYTE |          //binary type pipe.
                        PIPE_READMODE_BYTE |      //byte-read mode.
                        PIPE_WAIT,                //blocking mode.
                        1,                        //max. instances.  
                        0,						  //output buffer size.
                        sizeof(NOTIFYSTATE) +
						sizeof(FPNOTIFY),		  //input buffer size.
                        NMPWAIT_USE_DEFAULT_WAIT, //client time-out.
                        &SecurityAttributes);     //default security attribute.

		if (INVALID_HANDLE_VALUE == hNotifyPipe) 
		{
			break;
		}

		if (FALSE == SetEvent(hEvent))
		{
			break;
		}

		//Wait for the client to connect; if it succeeds, 
        //the function returns a nonzero value. If the function
        //returns zero, GetLastError returns ERROR_PIPE_CONNECTED. 
        BOOL bConnected = ConnectNamedPipe(
                            hNotifyPipe, NULL) ? 
                            TRUE : 
                            (ERROR_PIPE_CONNECTED == GetLastError()); 

        if (FALSE == bConnected)
        {
            break;
        }

		//emit xpsPipeConnected();

		bool bErrorFound = false;

		INT nItem = 0;

		do
		{
			NOTIFYSTATE NotifyState; 

			//Reset the the structure.
			ZeroMemory(&NotifyState, sizeof(NotifyState));

			DWORD dwBytesRead = 0;

			DWORD dwBytesToRead = sizeof(NOTIFYSTATE);

			if (FALSE == ReadFile(hNotifyPipe,
								  //buffer to read from.
								  &NotifyState,
								  //number of bytes to read.
								  dwBytesToRead, 
								  //number of bytes read.
								  &dwBytesRead,   
								  //not overlapped I/O.
								  NULL))        
			{
				break;
			}

			//Compare the bytes read.
			if (dwBytesRead != dwBytesToRead)
			{
				break;
			}

			FDSNOTIFY FDSNotify = {0};

			FPNOTIFY FPNotify = {0};

			FDNOTIFY FDNotify = {0};

			//If the event is error then return failure.
			switch (NotifyState.eEvent)
			{
			case eFDS:
				{
					dwBytesRead = 0;

					dwBytesToRead = NotifyState.unSize;

					if (FALSE == ReadFile(hNotifyPipe,
										  //buffer to read from.
										  &FDSNotify,
										  //number of bytes to read.
										  dwBytesToRead, 
										  //number of bytes read.
										  &dwBytesRead,   
										  //not overlapped I/O.
										  NULL))        
					{
						bErrorFound = true;
						break;
					}

					//Compare the bytes read.
					if (dwBytesRead != dwBytesToRead)
					{
						bErrorFound = true;
						break;
					}
				}
				break;
			case eFD:
				{
					dwBytesRead = 0;

					dwBytesToRead = NotifyState.unSize;

					if (FALSE == ReadFile(hNotifyPipe,
										  //buffer to read from.
										  &FDNotify,
										  //number of bytes to read.
										  dwBytesToRead, 
										  //number of bytes read.
										  &dwBytesRead,   
										  //not overlapped I/O.
										  NULL))        
					{
						bErrorFound = true;
						break;
					}
					//Compare the bytes read.
					if (dwBytesRead != dwBytesToRead)
					{
						bErrorFound = true;
						break;
					}
				}
				break;
			case eFP:
				{
					/*if (sizeof(FPNOTIFY) != NotifyState.unSize)
					{
						bErrorFound = true;
						break;
					}*/

					dwBytesRead = 0;

					dwBytesToRead = NotifyState.unSize;

					if (FALSE == ReadFile(hNotifyPipe,
										  //buffer to read from.
										  &FPNotify,
										  //number of bytes to read.
										  dwBytesToRead, 
										  //number of bytes read.
										  &dwBytesRead,   
										  //not overlapped I/O.
										  NULL))        
					{
						bErrorFound = true;
						break;
					}
					//Compare the bytes read.
					if (dwBytesRead != dwBytesToRead)
					{
						bErrorFound = true;
						break;
					}

					addItem(QString::fromWCharArray(FPNotify.wszPageURI));
				}
				break;
			case eError:
				{
					QCoreApplication::quit();
				}
				break;
			default:
				{
					bErrorFound = true;
					break;
				}
			}
		}while(1);

		if (true == bErrorFound)
		{
			break;
		}

	} while (0);

	//Close pipe
	if (INVALID_HANDLE_VALUE != hNotifyPipe)
	{
		CloseHandle(hNotifyPipe);
		hNotifyPipe = INVALID_HANDLE_VALUE;
	}

	//Free the memory allocated for the SECURITY_DESCRIPTOR.
	if (NULL != SecurityAttributes.lpSecurityDescriptor)
	{
		if (NULL != LocalFree(SecurityAttributes.lpSecurityDescriptor))
		{
		}
	}
}
Ejemplo n.º 25
0
/// Prelude actions to start up the service, e.g. to set any global variables from the settings or perform
/// any system specific actions. E.g. the Windows implementation registers with the service control manager
/// and can optionally set the security descriptor on the process to allow clients to kill/restart it.
///
/// @param[in] nReason how the startup is occuring (e.g. SERVICE_RUN_INLINE) - different actions may be
/// required depending on whether the code is running direct from main() or through another mechansim
static void _ServiceStartup (int nReason) {
	CSettings oSettings;
#ifdef _WIN32
	if (nReason == SERVICE_RUN_SCM) {
		g_hServiceStatus = RegisterServiceCtrlHandler (oSettings.GetServiceName (), ServiceHandler);
	}
	PCTSTR pszSDDL = oSettings.GetServiceSDDL ();
	if (pszSDDL) {
		LOGDEBUG (TEXT ("Setting security descriptor ") << pszSDDL);
		PSECURITY_DESCRIPTOR psdRelative;
		if (ConvertStringSecurityDescriptorToSecurityDescriptor (pszSDDL, SDDL_REVISION_1, &psdRelative, NULL)) {
			DWORD cbAbsolute = 1024;
			PSECURITY_DESCRIPTOR psdAbsolute = (PSECURITY_DESCRIPTOR)malloc (cbAbsolute);
			DWORD cbD = 1024;
			PACL paclD = (PACL)malloc (cbD);
			DWORD cbS = 1024;
			PACL paclS = (PACL)malloc (cbS);
			DWORD cbOwner = 1024;
			PSID psidOwner = (PSID)malloc (cbOwner);
			DWORD cbPGroup = 1024;
			PSID psidPGroup = (PSID)malloc (cbPGroup);
			if (MakeAbsoluteSD (psdRelative, psdAbsolute, &cbAbsolute, paclD, &cbD, paclS, &cbS, psidOwner, &cbOwner, psidPGroup, &cbPGroup)) {
				DWORD dwError = SetSecurityInfo (GetCurrentProcess (), SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, paclD, NULL);
				if (dwError == ERROR_SUCCESS) {
					LOGINFO (TEXT ("Security descriptor set on process handle"));
				} else {
					LOGWARN (TEXT ("Couldn't set security descriptor on process handle, error ") << GetLastError ());
				}
				if (nReason == SERVICE_RUN_SCM) {
					SC_HANDLE hSCM = OpenSCManager (NULL, NULL, GENERIC_READ);
				    if (hSCM) {
						SC_HANDLE hService = OpenService (hSCM, oSettings.GetServiceName (), GENERIC_WRITE | WRITE_DAC);
						if (hService) {
							dwError = SetSecurityInfo (hService, SE_SERVICE, DACL_SECURITY_INFORMATION, NULL, NULL, paclD, NULL);
							if (dwError == ERROR_SUCCESS) {
								LOGINFO (TEXT ("Security descriptor set on service"));
							} else {
								LOGWARN (TEXT ("Couldn't set security descriptor on service, error ") << GetLastError ());
							}
							CloseServiceHandle (hService);
						} else {
							LOGWARN (TEXT ("Couldn't open service, error ") << GetLastError ());
						}
						CloseServiceHandle (hSCM);
					} else {
						LOGWARN (TEXT ("Couldn't open SCM, error ") << GetLastError ());
					}
				}
			} else {
				LOGWARN (TEXT ("Couldn't create absolute security description, error ") << GetLastError ());
			}
			free (psdAbsolute);
			free (paclD);
			free (paclS);
			free (psidOwner);
			free (psidPGroup);
			LocalFree (psdRelative);
		} else {
			LOGWARN (TEXT ("Couldn't parse SDDL ") << pszSDDL << TEXT (", error ") << GetLastError ());
		}
	} else {
		LOGDEBUG (TEXT ("No security descriptor specified"));
	}
#else /* ifdef _WIN32 */
	if (nReason == SERVICE_RUN_DAEMON) {
		const TCHAR *pszPID = oSettings.GetPidFile ();
		if (pszPID) {
			LOGINFO (TEXT ("Creating PID file ") << pszPID);
			FILE *f = fopen (pszPID, "wt");
			if (f) {
				fprintf (f, "%d", getpid ());
				fclose (f);
			} else {
				LOGWARN (TEXT ("Couldn't write to PID file ") << pszPID << TEXT (", error ") << GetLastError ());
			}
		} else {
			LOGWARN (TEXT ("No PID file"));
		}
	}
#endif /* ifdef _WIN32 */
	g_lBusyTimeout = oSettings.GetBusyTimeout ();
	_ReportStateStarting ();
}
Ejemplo n.º 26
0
_IMPEXP_ETK void*
etk_create_area(const char *name, void **start_addr, size_t size, euint32 protection, const char *domain, etk_area_access area_access)
{
	if(size <= 0) return NULL;

	char *ipc_name = etk_area_ipc_name(name, domain);
	if(!ipc_name) return NULL;

	etk_win32_area_t *area = new etk_win32_area_t();
	if(!area)
	{
		free(ipc_name);
		return NULL;
	}

	area->prot = protection;

#if 0
	SECURITY_ATTRIBUTES sa;
	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	sa.bInheritHandle = TRUE;
	sa.lpSecurityDescriptor = NULL;

	EString szStr;
	szStr << "D:";				// Discretionary ACL
	szStr << "(D;OICI;GA;;;BG)";		// Deny access to built-in guests
	szStr << "(D;OICI;GA;;;AN)";		// Deny access to anonymous logon
	szStr << "(A;OICI;GA;;;BA)";		// Allow full control to administrators
	szStr << "(A;OICI;GA;;;CO)";		// Allow full control to creator owner

	if((area_access & ETK_AREA_ACCESS_GROUP_READ) || (area_access & ETK_AREA_ACCESS_GROUP_WRITE))
	{
		if(area_access & ETK_AREA_ACCESS_GROUP_WRITE)
			szStr << "(A;OICI;GA;;;CG)";	// Allow full control to creator group
		else
			szStr << "(A;OICI;GR;;;CG)";	// Allow read control to creator group
	}

	if((area_access & ETK_AREA_ACCESS_OTHERS_READ) || (area_access & ETK_AREA_ACCESS_OTHERS_WRITE))
	{
		if(area_access & ETK_AREA_ACCESS_OTHERS_WRITE)
			szStr << "(A;OICI;GA;;;BU)";	// Allow full control to others
		else
			szStr << "(A;OICI;GR;;;BU)";	// Allow read control to others
	}

	if(!ConvertStringSecurityDescriptorToSecurityDescriptor(szStr.String(), SDDL_REVISION_1, (PSECURITY_DESCRIPTOR*)&(sa.lpSecurityDescriptor), NULL))
	{
		delete area;
		free(ipc_name);
		return NULL;
	}
#endif

	HANDLE handler;

	_ETK_LOCK_AREA_();
	if((handler = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE | SEC_COMMIT, 0, size + sizeof(etk_win32_area_info_t), ipc_name)) == NULL)
	{
		_ETK_UNLOCK_AREA_();
		ETK_DEBUG("[KERNEL]: %s --- Can't create area : CreateFileMapping failed.", __PRETTY_FUNCTION__);
		free(ipc_name);
		delete area;
		return NULL;
	}

//	if(sa.lpSecurityDescriptor != NULL) LocalFree(sa.lpSecurityDescriptor);

	DWORD prot = (protection & E_WRITE_AREA ? FILE_MAP_ALL_ACCESS : FILE_MAP_READ);

	if((area->addr = MapViewOfFile(handler, prot, 0, 0, 0)) == NULL)
	{
		ETK_DEBUG("[KERNEL]: %s --- Can't create area : MapViewOfFile failed.", __PRETTY_FUNCTION__);
		CloseHandle(handler);
		_ETK_UNLOCK_AREA_();
		free(ipc_name);
		delete area;
		return NULL;
	}

	etk_win32_area_info_t area_info;
	area_info.magic = WIN32_AREA_INFO_MAGIC;
	area_info.closed = false;
	area_info.length = size;
	memcpy(area->addr, &area_info, sizeof(etk_win32_area_info_t));

	area->length = size;
	area->mapping = handler;
	area->name = e_strdup(name);
	area->domain = e_strdup(domain);
	area->ipc_name = ipc_name;
	area->created = true;

	_ETK_UNLOCK_AREA_();

	if(start_addr) *start_addr = (void*)((char*)area->addr + sizeof(etk_win32_area_info_t));
	return area;
}
Ejemplo n.º 27
0
int Mutex_Create(PVOID pVoid, const char *szName)
{
	PMUTEX pMutex;
#if FIX_NAMED_OBJECT_NAMESPACE
    char szFixedUpNameBuffer[255] = {0};
#endif
    const char* lpszFixedObjectName = szName;
    LPSECURITY_ATTRIBUTES pSecurityAttributes = 0;

    SECURITY_DESCRIPTOR secDesc = {0};
    SECURITY_ATTRIBUTES attr = {0};
    PSECURITY_DESCRIPTOR pSD = NULL;

	if(!pVoid)
		return ERROR_INVALID_ARGUMENT;

	pMutex = (PMUTEX)pVoid;
	if(pMutex->hMutex != NULL)
		return SUCCESS;
  
    //if this is a named object then we are going to open up the permissions on it
    //so people in other accounts / sessions can also use the same shared named object.
    //Starting w/ vista services and the logged in users are no longer in the same session anymore aswell.
    if(szName)
    {
#if FIX_SECURITY_DACL
        if(InitializeSecurityDescriptor(&secDesc,SECURITY_DESCRIPTOR_REVISION))
        {
            //Give a NULL DACL for all access to everyone
            if(SetSecurityDescriptorDacl(&secDesc, TRUE, NULL, FALSE))
            {
                attr.nLength = sizeof(attr);
                attr.lpSecurityDescriptor = &secDesc;
                pSecurityAttributes = &attr;

                //Vista introduces "integrity" check levels.  We are going to set this to "low"
                //to prevent us from locking out a low-integrity process if someone in 
                //a service uses the api to open the mutex first.
                if(IsVistaOrBetter())
                {
                    if(ConvertStringSecurityDescriptorToSecurityDescriptor( "S:(ML;;NW;;;LW)", // "low integrity"
                        SDDL_REVISION_1,
                        &pSD,
                        NULL))
                    {
                        PACL pSacl = NULL;                  // not allocated
                        BOOL fSaclPresent = FALSE;
                        BOOL fSaclDefaulted = FALSE;
                        GetSecurityDescriptorSacl(
                            pSD,
                            &fSaclPresent,
                            &pSacl,
                            &fSaclDefaulted);
                        //Set the SACL w/ low-integrity checks
                        SetSecurityDescriptorSacl(attr.lpSecurityDescriptor, TRUE, pSacl, FALSE);
                    }
                }
            }
        }
#endif        

#if FIX_NAMED_OBJECT_NAMESPACE
        //now fix up the namespace on the object...
        strcat(szFixedUpNameBuffer,"Global\\");
        strcat(szFixedUpNameBuffer,szName);
        lpszFixedObjectName = szFixedUpNameBuffer;
#endif
    }

	/* Create a mutex with specified params */
	pMutex->hMutex = CreateMutex(	
							pSecurityAttributes,
							FALSE,
							lpszFixedObjectName
						);

    //local free if needed
    if(pSD)
    {
        //preserve last error
        DWORD dwLastError = GetLastError();
        LocalFree((HLOCAL)pSD);
        SetLastError(dwLastError);
    }

	if(pMutex->hMutex == NULL)
		return ERROR_CREATE_MUTEX_FAILED;
	return SUCCESS;
}
Ejemplo n.º 28
0
void CheckInstances() 
{
   /* Create a SID corresponding to the Local Administrator group */
   BYTE localAdminSID[SECURITY_MAX_SID_SIZE];
   PSID pLocalAdminSID = &localAdminSID;
   DWORD cbSID = sizeof(localAdminSID); 
   BOOL CreateWellKnownSidResult;
   BOOL AddSIDToBoundaryResult;
   BOOL ConvertStringResult;
   DWORD dwLastError;
   /* Create the boundary descriptor 
    * A new boundary descriptor must have at least one security identifier (SID). 
	* To add a SID to a boundary descriptor, use the AddSIDToBoundaryDescriptor function.
    */
   g_hBoundary = CreateBoundaryDescriptor(g_szBoundary, 0);
   /* The CreateWellKnownSid function creates a SID for predefined aliases. 
    * The first parameter WellKnownSidType is WELL_KNOWN_SID_TYPE enumeration.
	* The WELL_KNOWN_SID_TYPE enumeration is a list of commonly used security identifiers (SIDs).
	* Programs can pass these values to the CreateWellKnownSid function 
	* to create a SID from this list.
	* Examples of possible values:
	* WinBuiltinDomainSid                          = 25,
    * WinBuiltinAdministratorsSid                  = 26,
    * WinBuiltinUsersSid                           = 27,
    * WinBuiltinGuestsSid                          = 28,
    * WinBuiltinPowerUsersSid                      = 29
	* We choose only administrators SID
	* DomainSid [in, optional] - A pointer to a SID 
	* that identifies the domain to use when creating the SID. 
	* Pass NULL to use the local computer.
	* cbSid [in, out]
    * A pointer to a DWORD that contains the number of bytes available at pSid. 
	* The CreateWellKnownSid function stores the number of bytes actually used at this location.
    */
   CreateWellKnownSidResult = 
	   CreateWellKnownSid(
	     WinBuiltinAdministratorsSid,
         NULL,
         &cbSID,
		 NULL);
   /* If we cannot create SID, we show a message on the interface. */ 
   if (CreateWellKnownSidResult == FALSE) 
   {
	    AddText(
			TEXT("AddSIDToBoundaryDescriptor failed: %u\r\n"), 
            GetLastError());
        return;
   }
   /* Associate the Local Admin SID to the boundary descriptor
    * --> only applications running under an administrator user
    *     will be able to access the kernel objects in the same namespace
	* The following function 
	* adds a security identifier (SID) to the specified boundary descriptor.
	* The first parameter HANDLE *BoundaryDescriptor is a handle to the boundary descriptor. 
	* RequiredSid [in] a pointer to a SID structure.
	*/
   AddSIDToBoundaryResult = 
	   AddSIDToBoundaryDescriptor(
	     &g_hBoundary, 
		 pLocalAdminSID);
    /* If we cannot add the SID to the boundary descriptor,
	 * we show a message on the interface. */ 
   if (CreateWellKnownSidResult == FALSE) 
   {
        AddText(
			TEXT("AddSIDToBoundaryDescriptor failed: %u\r\n"), 
            GetLastError());
        return;
   }
   /* Create the namespace for Local Administrators only */
   SECURITY_ATTRIBUTES sa;
   sa.nLength = sizeof(sa);
   sa.bInheritHandle = FALSE;
   /* The ConvertStringSecurityDescriptorToSecurityDescriptor function converts 
    * a string-format security descriptor into a valid, functional security descriptor.
	* This function retrieves a security descriptor that the 
	* ConvertSecurityDescriptorToStringSecurityDescriptor function converted to string format. 
	* Parameters:
	* LPCTSTR StringSecurityDescriptor - A pointer to a null-terminated string containing 
	*                                    the string-format security descriptor to convert.
	*
	* The Security Descriptor String Format is a text format for storing 
	* or transporting information in a security descriptor. The format is a null-terminated string 
	* with tokens to indicate each of the four main components of a security descriptor: 
	* owner (O:), primary group (G:), DACL (D:), and SACL (S:).
	*
	* We use this pattern string
	* D:dacl_flags(string_ace1)(string_ace2)... (string_acen)
	* dacl_flags - Security descriptor control flags that apply to the DACL. 
	* The dacl_flags string can be a concatenation of zero or more of the following strings.
	*
	* DWORD StringSDRevision - Specifies the revision level of the StringSecurityDescriptor string.
	*                          Currently this value must be SDDL_REVISION_1.
    * SecurityDescriptor[out] - A pointer to a variable that receives a pointer to the converted security descriptor. 
	* 
	*/
   ConvertStringResult = 
	  ConvertStringSecurityDescriptorToSecurityDescriptor(
         TEXT("D:(A;;GA;;;BA)"),
         SDDL_REVISION_1,
         &sa.lpSecurityDescriptor,
	     NULL);
    /* If we cannot convert string sequrity descriptor,
	 * we show a message on the interface. */ 
   if (ConvertStringResult == FALSE) 
   {
      AddText(
		  TEXT("Security Descriptor creation failed: %u\r\n"), 
		  GetLastError());
      return;
   }
   /* Creates a private namespace. 
    *
    * lpPrivateNamespaceAttributes [in, optional] -
	*   A pointer to a SECURITY_ATTRIBUTES structure 
    *   that specifies the security attributes of the namespace object.
	* 
 	* lpBoundaryDescriptor [in] -
    *   A descriptor that defines how the namespace is to be isolated. 
	*   The caller must be within this boundary. 
	*   The CreateBoundaryDescriptor function creates a boundary descriptor.
	* 
	* lpAliasPrefix [in] -
    *   The prefix for the namespace. To create an object in this namespace,
	*   specify the object name as prefix\objectname.
    *   The system supports multiple private namespaces with the same name, 
	*   as long as they define different boundaries.
	* 
	* Return value
    *   If the function succeeds, it returns a handle to the new namespace.
    *   If the function fails, the return value is NULL. 
	*   To get extended error information, call GetLastError. 
    */
   g_hNamespace = 
	  CreatePrivateNamespace(
	    &sa, 
	    g_hBoundary, 
	    g_szNamespace);
   /* The memory for sa.lpSecurityDescriptor has been allocated by Convert...
    * windows function. It up to us to free the memory.
    * Don't forget to release memory for the security descriptor.
    */
   LocalFree(sa.lpSecurityDescriptor);
   /* Check the private namespace creation result */
   dwLastError = GetLastError();
   /* If the function has returned null. That means that some error
    * has happened. In this case we need to investigate a GetLastError()
    */
   if (g_hNamespace == NULL) 
   {
      /* Nothing to do if access is denied
       * --> this code must run under a Local Administrator account
	   */
      if (dwLastError == ERROR_ACCESS_DENIED) 
	  {
         AddText(TEXT("Access denied when creating the namespace.\r\n"));
         AddText(TEXT("   You must be running as Administrator.\r\n\r\n"));
         return;
	  }
	  else 
	  { 
         /* If another instance has already created the namespace, 
            we need to open it instead.  */
         if (dwLastError == ERROR_ALREADY_EXISTS) 
		 {
            AddText(TEXT("CreatePrivateNamespace failed: %u\r\n"), dwLastError);
			/* Try to open existed private namespace 
			 * pBoundaryDescriptor [in] - A descriptor that defines how 
			 * the namespace is to be isolated. The CreateBoundaryDescriptor function
			 * creates a boundary descriptor.
			 */
            g_hNamespace = OpenPrivateNamespace(g_hBoundary, g_szNamespace);
			/* If the function returns null, that means that some error has happened */
			if (g_hNamespace == NULL) 
			{
               AddText(
				   TEXT("   and OpenPrivateNamespace failed: %u\r\n"), 
                   dwLastError);
               return;
            } 
			else 
			{
               g_bNamespaceOpened = TRUE;
               AddText(TEXT("   but OpenPrivateNamespace succeeded\r\n\r\n"));
            }
		 }
	  }
   }

   /* Try to create the mutex object with a name 
    * based on the private namespace 
	*/
   TCHAR szMutexName[64];
   StringCchPrintf(
	   szMutexName, 
	   _countof(szMutexName), 
	   TEXT("%s\\%s"), 
       g_szNamespace, 
	   TEXT("Singleton"));
   /* Try to create mutex */
   g_hSingleton = CreateMutex(NULL, FALSE, szMutexName);
   if (GetLastError() == ERROR_ALREADY_EXISTS) 
   {
      /* There is already an instance of this Singleton object */
      AddText(TEXT("Another instance of Singleton is running:\r\n"));
      AddText(TEXT("--> Impossible to access application features.\r\n"));
   } 
   else  
   {
      /* First time the Singleton object is created */
      AddText(TEXT("First instance of Singleton:\r\n"));
      AddText(TEXT("--> Access application features now.\r\n"));
   }
}
Ejemplo n.º 29
0
BOOL
CreateNdasCommandServerDefaultDACL(
	__inout LPSECURITY_ATTRIBUTES SecurityAttributes)
{
#define NDASSVC_ALLOW_INTERACTIVE_USERS
// Anonymous in SDDL in Windows 2000 does not work
// #define NDASSVC_DENY_ANONYMOUS

	// Define the SDDL for the DACL. This example sets 
	// the following access:
	//     Built-in guests are denied all access.
	//     Anonymous Logon is denied all access.
	//     Authenticated Users are allowed read/write/execute access.
	//     Administrators are allowed full control.
	// Modify these values as needed to generate the proper
	// DACL for your application. 
#if 0
	LPCWSTR securityDescriptor = 
		L"D:"                   // Discretionary ACL
		L"(D;OICI;GA;;;BG)"     // Deny access to Built-in Guests
		L"(D;OICI;GA;;;AN)"     // Deny access to Anonymous Logon
		L"(A;OICI;GRGWGX;;;AU)" // Allow read/write/execute to Authenticated Users
		L"(A;OICI;GA;;;BA)";    // Allow full control to Administrators
#else
	LPCTSTR securityDescriptor = 
		SDDL_DACL 
		SDDL_DELIMINATOR
		// Deny access to Built-in Guests
		SDDL_ACE_BEGIN
			SDDL_ACCESS_DENIED SDDL_SEPERATOR
			SDDL_OBJECT_INHERIT SDDL_CONTAINER_INHERIT SDDL_SEPERATOR
			SDDL_GENERIC_ALL SDDL_SEPERATOR
			SDDL_SEPERATOR
			SDDL_SEPERATOR
			SDDL_BUILTIN_GUESTS
		SDDL_ACE_END
		//
		// Anonymous DOES NOT work in Windows 2000
		//
#ifdef NDASSVC_DENY_ANONYMOUS
		// Deny access to Anonymous
		SDDL_ACE_BEGIN
			SDDL_ACCESS_DENIED SDDL_SEPERATOR
			SDDL_OBJECT_INHERIT SDDL_CONTAINER_INHERIT SDDL_SEPERATOR
			SDDL_GENERIC_ALL SDDL_SEPERATOR
			SDDL_SEPERATOR
			SDDL_SEPERATOR
			SDDL_ANONYMOUS
		SDDL_ACE_END
#endif
#ifdef NDASSVC_ALLOW_INTERACTIVE_USERS
		// Allow RWX to Interactive Users
		SDDL_ACE_BEGIN
			SDDL_ACCESS_ALLOWED SDDL_SEPERATOR
			SDDL_OBJECT_INHERIT SDDL_CONTAINER_INHERIT SDDL_SEPERATOR
			SDDL_GENERIC_READ SDDL_GENERIC_WRITE SDDL_GENERIC_EXECUTE SDDL_SEPERATOR
			SDDL_SEPERATOR
			SDDL_SEPERATOR
			SDDL_INTERACTIVE
		SDDL_ACE_END
#endif
		// Allow Full Control to Administrators
		SDDL_ACE_BEGIN
			SDDL_ACCESS_ALLOWED SDDL_SEPERATOR
			SDDL_OBJECT_INHERIT SDDL_CONTAINER_INHERIT SDDL_SEPERATOR
			SDDL_GENERIC_ALL SDDL_SEPERATOR
			SDDL_SEPERATOR
			SDDL_SEPERATOR
			SDDL_BUILTIN_ADMINISTRATORS
		SDDL_ACE_END
		// Allow Full Control to Local System
		SDDL_ACE_BEGIN
			SDDL_ACCESS_ALLOWED SDDL_SEPERATOR
			SDDL_OBJECT_INHERIT SDDL_CONTAINER_INHERIT SDDL_SEPERATOR
			SDDL_GENERIC_ALL SDDL_SEPERATOR
			SDDL_SEPERATOR
			SDDL_SEPERATOR
			SDDL_LOCAL_SYSTEM
		SDDL_ACE_END;
#endif
	if (NULL == SecurityAttributes)
	{
		XTLASSERT(FALSE);
		return FALSE;
	}

	BOOL success;

	XTLVERIFY( 
	success = ConvertStringSecurityDescriptorToSecurityDescriptor(
			securityDescriptor,
			SDDL_REVISION_1,
			&(SecurityAttributes->lpSecurityDescriptor),
			NULL) );

	return success;

}
Ejemplo n.º 30
-1
void CheckInstances() {

   // Create the boundary descriptor, the descriptor is not a kernel object. 
   // It is a pointer to a user-mode structure containing the definition of the boundary.
   g_hBoundary = CreateBoundaryDescriptor(g_szBoundary, 0);

   // Create a SID corresponding to the Local Administrator group
   BYTE localAdminSID[SECURITY_MAX_SID_SIZE];
   PSID pLocalAdminSID = &localAdminSID;
   DWORD cbSID = sizeof(localAdminSID);
   if (!CreateWellKnownSid(
      WinBuiltinAdministratorsSid, NULL, pLocalAdminSID, &cbSID)
      ) {
      AddText(TEXT("AddSIDToBoundaryDescriptor failed: %u\r\n"), 
         GetLastError());
      return;
   }
   
   // Associate the Local Admin SID to the boundary descriptor
   // --> only applications running under an administrator user
   //     will be able to access the kernel objects in the same namespace
   if (!AddSIDToBoundaryDescriptor(&g_hBoundary, pLocalAdminSID)) {
      AddText(TEXT("AddSIDToBoundaryDescriptor failed: %u\r\n"), 
         GetLastError());
      return;
   }

   // Create the namespace for Local Administrators only
   SECURITY_ATTRIBUTES sa;
   sa.nLength = sizeof(sa);
   sa.bInheritHandle = FALSE;
   if (!ConvertStringSecurityDescriptorToSecurityDescriptor(
      TEXT("D:(A;;GA;;;BA)"), 
      SDDL_REVISION_1, &sa.lpSecurityDescriptor, NULL)) {
      AddText(TEXT("Security Descriptor creation failed: %u\r\n"), GetLastError());
      return;
   }

   g_hNamespace = 
      CreatePrivateNamespace(&sa, g_hBoundary, g_szNamespace);

   // Don't forget to release memory for the security descriptor
   LocalFree(sa.lpSecurityDescriptor);


   // Check the private namespace creation result
   DWORD dwLastError = GetLastError();
   if (g_hNamespace == NULL) {
      // Nothing to do if access is denied
      // --> this code must run under a Local Administrator account
      if (dwLastError == ERROR_ACCESS_DENIED) {
         AddText(TEXT("Access denied when creating the namespace.\r\n"));
         AddText(TEXT("   You must be running as Administrator.\r\n\r\n"));
         return;
      } else { 
         if (dwLastError == ERROR_ALREADY_EXISTS) {
         // If another instance has already created the namespace, 
         // we need to open it instead. 
            AddText(TEXT("CreatePrivateNamespace failed: %u\r\n"), dwLastError);
            g_hNamespace = OpenPrivateNamespace(g_hBoundary, g_szNamespace);
            if (g_hNamespace == NULL) {
               AddText(TEXT("   and OpenPrivateNamespace failed: %u\r\n"), 
               dwLastError);
               return;
            } else {
               g_bNamespaceOpened = TRUE;
               AddText(TEXT("   but OpenPrivateNamespace succeeded\r\n\r\n"));
            }
         } else {
            AddText(TEXT("Unexpected error occured: %u\r\n\r\n"),
               dwLastError);
            return;
         }
      }
   }
   
   // Try to create the mutex object with a name 
   // based on the private namespace 
   TCHAR szMutexName[64];
   StringCchPrintf(szMutexName, _countof(szMutexName), TEXT("%s\\%s"), 
      g_szNamespace, TEXT("Singleton"));

   g_hSingleton = CreateMutex(NULL, FALSE, szMutexName);
   if (GetLastError() == ERROR_ALREADY_EXISTS) {
      // There is already an instance of this Singleton object
      AddText(TEXT("Another instance of Singleton is running:\r\n"));
      AddText(TEXT("--> Impossible to access application features.\r\n"));
   } else  {
      // First time the Singleton object is created
      AddText(TEXT("First instance of Singleton:\r\n"));
      AddText(TEXT("--> Access application features now.\r\n"));
   }
}