500+ FAQ по Delphi

Перейти на: Главную | Индексную | Предыдущую | Следующую страницу
интернет магазины в беларуси одежда

Как запустить или закрыть скринсэйвер?

Starting
~~~~~~~~
The method for starting a screen saver is simple, but surprising. You post your
own window a message ! Post yourself the WM_SYSCOMMAND message with the
SC_SCREENSAVE parameter :

// Uses MFC CWnd::PostMessage
PostMessage (WM_SYSCOMMAND, SC_SCREENSAVE);


Stopping
~~~~~~~~
Stopping a screen saver is somewhat more complex. The Microsoft-documented way
of doing this is to look for the special screen-saver desktop, enumerate all
windows on that desktop, and close them, as follows:

hdesk = OpenDesktop(TEXT("Screen-saver"),
0,
FALSE,
DESKTOP_READOBJECTS | DESKTOP_WRITEOBJECTS);
if (hdesk)
{
EnumDesktopWindows (hdesk, (WNDENUMPROC)KillScreenSaverFunc, 0);
CloseDesktop (hdesk);
}

BOOL CALLBACK KillScreenSaverFunc (HWND hwnd, LPARAM lParam)
{
PostMessage(hwnd, WM_CLOSE, 0, 0);
return TRUE;
}


However, I can't recommend this approach. I have found when using this code,
NT4 very occasionally seems to get confused and pass you back the normal
desktop handle, in which case you end up trying to close all the normal
application windows. Note, in MS' defence, that the code above for closing
32 bit savers is derived from a sample that is only marked as valid for
NT3.51 - there is no mention of NT4 in the sample. Unfortunately, there
is also nothing to indicate that it doesn't work properly.

I have subsequently performed some tests, and found that the stock screen
savers supplied with NT4 will in any case get a hit on the window class search
normally used for 16 bit savers ("WindowsScreenSaverClass"). I don't believe
for a moment that the OpenGL savers (for example) are 16 bit, so maybe MS are
supplying a saver window class that will give the necessary hit.
So anyway, you can use this route :

HWND hSaver = FindWindow ("WindowsScreenSaverClass", NULL);

if (hSaver)
PostMessage (hSaver, WM_CLOSE, 0, 0);


Yet another alternative is now available, which depends upon new functionality
in SystemParametersInfo. This should be even more general :

BOOL bSaver;
if (::SystemParametersInfo (SPI_GETSCREENSAVEACTIVE,0,&bSaver,0))
{
if (bSaver)
{
::PostMessage (::GetForegroundWindow(), WM_CLOSE, 0L, 0L);
}
}

Как выполнить shutdown для удалённого компьютера?

int main(int argc, char **argv)
{
HANDLE hToken;
TOKEN_PRIVILEGES tkp;

char *name=""; // address of name of computer to shut down
char *msg=""; //address of message to display in dialog box
DWORD time=0; // time to display dialog box
bool force=true; // force applications with unsaved changes flag
bool reboot=true; //reboot flag

OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
&hToken);

if(!LookupPrivilegeValue(name, SE_SHUTDOWN_NAME,&tkp.Privileges[0].Luid)){
printf ("SE_SHUTDOWN_NAME Privilege облом \n");
return 1 ;};

tkp.PrivilegeCount =1;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,(PTOKEN_PRIVILEGES)NULL, 0);

if(!LookupPrivilegeValue(name,
SE_REMOTE_SHUTDOWN_NAME,&tkp.Privileges[0].Luid)){
printf("SE_REMOTE_SHUTDOWN_NAME Privilege облом \n");
return 2 ;};

tkp.PrivilegeCount =1;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,(PTOKEN_PRIVILEGES)NULL, 0);

if (InitiateSystemShutdown(name,msg,time,force,reboot))
printf("%s shutdown Ok\n",name);
else printf("Can't shutdown %s \n",name);

return 0;
}

Как терминировать процесс (в том числе системный)?

#include <windows.h>
#include <stdio.h>
#pragma hdrstop

// fkill forces a kill -- it will attempt to enable SeDebugPrivilege
// before opening its process handles, allowing it to kill processes
// running under builtin\system (LocalSystem, to the users out there).

int main( int argc, char *argv[] );
void getDebugPriv( void );

#define isBadHandle(h) ( (h) == NULL || (h) == INVALID_HANDLE_VALUE )
#define lenof(x) ( sizeof (x) / sizeof ((x)[0]) )

const int MAXPID = 1024;

int main( int argc, char *argv[] )
{
int pidCount, i, errors;
char *p;
HANDLE hProcess;
static DWORD pid[MAXPID];

// parse args, build PID list
errors = pidCount = 0;

for ( i = 1; i < argc; i ++ )
{
if ( pidCount == lenof( pid ) ) {
errors ++;
break;
}

pid[pidCount] = strtol( argv[i], &p, 0 );
if ( p == argv[i] || *p )
errors ++;
else
pidCount ++;
}

if ( errors || pidCount == 0 )
{
puts( "Usage: fkill pid [...]" );
puts( "fkill tries to kill the processes specified by the PIDs. If the" );
puts( "user has debug privileges, fkill is able to kill system processes." );
puts( "PIDs may be decimal, octal (starts with 0), or hex (starts with 0x)."
);
return MAXPID + 1;
}

// try to acquire SeDebugPrivilege
getDebugPriv(); //см. faq выше

errors = 0;
// for each PID:
for ( i = 0; i < pidCount; i ++ )
{
printf( "pid %lu: ", pid[i] );

// open process
hProcess = OpenProcess( PROCESS_TERMINATE, FALSE, pid[i] );
if ( isBadHandle( hProcess ) )
printf( "OpenProcess() failed, err = %lu\n", GetLastError() );
else
{
// kill process
if ( ! TerminateProcess( hProcess, (DWORD) -1 ) )
printf( "TerminateProcess() failed, err = %lu\n", GetLastError() );
else
puts( "killed." );

// close handle
CloseHandle( hProcess );
}
}

return 0;
}

Как включить/выключить аудит?

#include <windows.h>
#include <stdio.h>
#include <ntsecapi.h>
#pragma hdrstop

// This code was kindly provided by Marc Esipovich, marc@mucom.co.il.
// The original filename was "isauditon.c".
// Modifications by felixk:
// IsAuditOn() now accepts a BOOL; if FALSE, the code will
// _not_ force the audit settings to ON.
// Changed return type to int, as it may return 0, 1, -1.
// Added a small main() to call IsAuditOn(FALSE).

/*

RETURNS: 1 if Auditing has been enabled, 0 if no action taken, -1 on error.

COMMENT: Automatically enables all audit policy events.

Values are, 0 for no log at all, 1 for success only, 2 for failure only,
3 for both success and failure.

typedef struct _POLICY_BUFFER {
DWORD IsAuditEnabled; // 1 = ON, 0 = OFF.
PVOID pPolicies; // pointer to the start policy struct.

DWORD restart_shutdown_and_system;
DWORD junk1;
DWORD logon_and_logoff;
DWORD junk2;
DWORD file_and_object_access;
DWORD junk3;
DWORD use_of_user_rights;
DWORD junk4;
DWORD process_tracking;
DWORD junk5;
DWORD security_policy_changes;
DWORD junk6;
DWORD user_and_group_management;
DWORD junk7;
} POLICY_BUFFER, *PPOLICY_BUFFER;
*/

int IsAuditOn( BOOL forceAuditOn )
{
int rc = 0;
POLICY_ACCOUNT_DOMAIN_INFO *ppadi = NULL;
SECURITY_QUALITY_OF_SERVICE sqos;
LSA_OBJECT_ATTRIBUTES lsaOA;
LSA_HANDLE polHandle;

NTSTATUS nts;


// fill the Quality Of Service struct.
sqos.Length = sizeof(SECURITY_QUALITY_OF_SERVICE);
sqos.ImpersonationLevel = SecurityImpersonation;
sqos.ContextTrackingMode = SECURITY_DYNAMIC_TRACKING;
sqos.EffectiveOnly = FALSE;

// fill the Object Attributes struct.
lsaOA.Length = sizeof(LSA_OBJECT_ATTRIBUTES);
lsaOA.RootDirectory = NULL;
lsaOA.ObjectName = NULL;
lsaOA.Attributes = 0;
lsaOA.SecurityDescriptor = NULL;
lsaOA.SecurityQualityOfService = &sqos;

nts = LsaOpenPolicy(
NULL, // NULL = current machine.
&lsaOA,
POLICY_VIEW_LOCAL_INFORMATION | GENERIC_READ | GENERIC_EXECUTE |
POLICY_ALL_ACCESS,
&polHandle);
if (nts != 0) return -1;


nts = LsaQueryInformationPolicy(
polHandle,
PolicyAuditEventsInformation,
&ppadi);
if (nts != 0) return -1;

if ( forceAuditOn )
{
// set policies
ppadi->DomainName.Buffer[0] = 3; // restart_shutdown_and_system
ppadi->DomainName.Buffer[2] = 3; // logon_and_logoff
ppadi->DomainName.Buffer[4] = 3; // file_and_object_access
ppadi->DomainName.Buffer[6] = 3; // use_of_user_rights
ppadi->DomainName.Buffer[8] = 3; // process_tracking
ppadi->DomainName.Buffer[10] = 3; // security_policy_changes
ppadi->DomainName.Buffer[12] = 3; // user_and_group_management

ppadi->DomainName.Length = 1;

nts = LsaSetInformationPolicy(
polHandle,
PolicyAuditEventsInformation,
ppadi);
if (nts != 0) return -1;
rc = 1;
}

LsaFreeMemory(polHandle);

return rc;
}


int main( void )
{
int rc;

rc = IsAuditOn( FALSE );

if ( rc == 1 )
puts( "Auditing has been enabled." );
else if ( rc == 0 )
puts( "The audit state is unchanged." );
else
puts( "Oops!" );

return 0;
}

Как взять себе привилегию?

Hапример берем привилегию отладки программ:

void getDebugPriv( void )
{
HANDLE hToken;
LUID sedebugnameValue;
TOKEN_PRIVILEGES tkp;

if ( ! OpenProcessToken( GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken ) )
return;

if ( !LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &sedebugnameValue ) )
{
CloseHandle( hToken );
return;
}

tkp.PrivilegeCount = 1;
tkp.Privileges[0].Luid = sedebugnameValue;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

AdjustTokenPrivileges( hToken, FALSE, &tkp, sizeof tkp, NULL, NULL );

CloseHandle( hToken );
}

Как дать (забрать) привилегии?

См.ниже: (c)"Getadmin"

#include <ntsecapi.h>
#include <lmaccess.h>


NTSTATUS
SetPrivilegeOnAccount(
LSA_HANDLE PolicyHandle, // open policy handle
PSID AccountSid, // SID to grant privilege to
LPWSTR PrivilegeName, // privilege to grant (Unicode)
BOOL bEnable // enable or disable
)
{
LSA_UNICODE_STRING PrivilegeString;

//
// Create a LSA_UNICODE_STRING for the privilege name.
//
InitLsaString(&PrivilegeString, PrivilegeName);//см.ниже

//
// grant or revoke the privilege, accordingly
//
if(bEnable) {
return LsaAddAccountRights(
PolicyHandle, // open policy handle
AccountSid, // target SID
&PrivilegeString, // privileges
1 // privilege count
);
}
else {
return LsaRemoveAccountRights(
PolicyHandle, // open policy handle
AccountSid, // target SID
FALSE, // do not disable all rights
&PrivilegeString, // privileges
1 // privilege count
);
}
}

А как для вышеприведенного фрагмента получить хэндл полиси???

Getadmin sources...

#include <ntsecapi.h>
#include <lmaccess.h>

void
InitLsaString(
PLSA_UNICODE_STRING LsaString,
LPWSTR String
)
{
DWORD StringLength;

if (String == NULL) {
LsaString->Buffer = NULL;
LsaString->Length = 0;
LsaString->MaximumLength = 0;
return;
}

StringLength = wcslen(String);
LsaString->Buffer = String;
LsaString->Length = (USHORT) StringLength * sizeof(WCHAR);
LsaString->MaximumLength=(USHORT)(StringLength+1) * sizeof(WCHAR);
}
NTSTATUS
OpenPolicy(
LPWSTR ServerName,
DWORD DesiredAccess,
PLSA_HANDLE PolicyHandle
)
{
LSA_OBJECT_ATTRIBUTES ObjectAttributes;
LSA_UNICODE_STRING ServerString;
PLSA_UNICODE_STRING Server = NULL;

//
// Always initialize the object attributes to all zeroes.
//
ZeroMemory(&ObjectAttributes, sizeof(ObjectAttributes));

if (ServerName != NULL) {
//
// Make a LSA_UNICODE_STRING out of the LPWSTR passed in
//
InitLsaString(&ServerString, ServerName);
Server = &ServerString;
}

//
// Attempt to open the policy.
//
return LsaOpenPolicy(
Server,
&ObjectAttributes,
DesiredAccess,
PolicyHandle
);
}

бесшовные натяжные потолки clipso Черутти.

Материалы находятся на сайте http://cracklab.narod.ru/faq/


Создатель этого HTML файла не претендует на авторство вопросов/ответов представленных в нём, не отвечает за их содержание и достоверность, а также за последствия использования программных кодов , полученных из этого HTML файла. Также не принимаются претензии относительно не размещённой информации об авторе каждого конкретного FAQ'а. Любые другие вопросы присылайте на bad_guy@cracklab.ru (обращаться к Bad_guy'ю).
Hosted by uCoz