elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Recopilación Tutoriales y Manuales Hacking, Seguridad, Privacidad, Hardware, etc


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación C/C++ (Moderadores: Eternal Idol, Littlehorse, K-YreX)
| | |-+  ¿Por qué este servicio no muestra ventana?
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: ¿Por qué este servicio no muestra ventana?  (Leído 2,078 veces)
Kaxperday


Desconectado Desconectado

Mensajes: 702


The man in the Middle


Ver Perfil WWW
¿Por qué este servicio no muestra ventana?
« en: 27 Diciembre 2015, 21:57 pm »

Es un copy/paste hay muchas cosas que cambiaría si y no es la manera.. pero simplemente quiero que el servicio muestre una ventana diciendo si soy admin o no cuando se ejecuta nada más, es de codeproyect el código.

Código
  1. #include <Windows.h>
  2. #include <tchar.h>
  3.  
  4. bool ejecucion_admin()
  5. {
  6. HANDLE h = NULL;
  7. if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &h)){
  8. TOKEN_ELEVATION Elevation;
  9. DWORD cbSize = sizeof(TOKEN_ELEVATION);
  10. if (GetTokenInformation(h, TokenElevation, &Elevation, sizeof(Elevation), &cbSize)){
  11. CloseHandle(h);
  12. return Elevation.TokenIsElevated;
  13. }
  14. }
  15. CloseHandle(h);
  16. return false;
  17. }
  18.  
  19. SERVICE_STATUS        g_ServiceStatus = { 0 };
  20. SERVICE_STATUS_HANDLE g_StatusHandle = NULL;
  21. HANDLE                g_ServiceStopEvent = INVALID_HANDLE_VALUE;
  22.  
  23. VOID WINAPI ServiceMain(DWORD argc, LPTSTR *argv);
  24. VOID WINAPI ServiceCtrlHandler(DWORD);
  25. DWORD WINAPI ServiceWorkerThread(LPVOID lpParam);
  26.  
  27. #define SERVICE_NAME  _T("My Sample Service")
  28.  
  29. int _tmain(int argc, TCHAR *argv[])
  30. {
  31. OutputDebugString(_T("My Sample Service: Main: Entry"));
  32.  
  33. SERVICE_TABLE_ENTRY ServiceTable[] =
  34. {
  35. { SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION)ServiceMain },
  36. { NULL, NULL }
  37. };
  38.  
  39. if (StartServiceCtrlDispatcher(ServiceTable) == FALSE)
  40. {
  41. OutputDebugString(_T("My Sample Service: Main: StartServiceCtrlDispatcher returned error"));
  42. return GetLastError();
  43. }
  44.  
  45. OutputDebugString(_T("My Sample Service: Main: Exit"));
  46. return 0;
  47. }
  48.  
  49.  
  50. VOID WINAPI ServiceMain(DWORD argc, LPTSTR *argv)
  51. {
  52. DWORD Status = E_FAIL;
  53.  
  54. OutputDebugString(_T("My Sample Service: ServiceMain: Entry"));
  55.  
  56. g_StatusHandle = RegisterServiceCtrlHandler(SERVICE_NAME, ServiceCtrlHandler);
  57.  
  58. if (g_StatusHandle == NULL)
  59. {
  60. OutputDebugString(_T("My Sample Service: ServiceMain: RegisterServiceCtrlHandler returned error"));
  61. goto EXIT;
  62. }
  63.  
  64. // Tell the service controller we are starting
  65. ZeroMemory(&g_ServiceStatus, sizeof (g_ServiceStatus));
  66. g_ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
  67. g_ServiceStatus.dwControlsAccepted = 0;
  68. g_ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
  69. g_ServiceStatus.dwWin32ExitCode = 0;
  70. g_ServiceStatus.dwServiceSpecificExitCode = 0;
  71. g_ServiceStatus.dwCheckPoint = 0;
  72.  
  73. if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE)
  74. {
  75. OutputDebugString(_T("My Sample Service: ServiceMain: SetServiceStatus returned error"));
  76. }
  77.  
  78. /*
  79. * Perform tasks neccesary to start the service here
  80. */
  81. OutputDebugString(_T("My Sample Service: ServiceMain: Performing Service Start Operations"));
  82.  
  83. // Create stop event to wait on later.
  84. g_ServiceStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  85. if (g_ServiceStopEvent == NULL)
  86. {
  87. OutputDebugString(_T("My Sample Service: ServiceMain: CreateEvent(g_ServiceStopEvent) returned error"));
  88.  
  89. g_ServiceStatus.dwControlsAccepted = 0;
  90. g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
  91. g_ServiceStatus.dwWin32ExitCode = GetLastError();
  92. g_ServiceStatus.dwCheckPoint = 1;
  93.  
  94. if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE)
  95. {
  96. OutputDebugString(_T("My Sample Service: ServiceMain: SetServiceStatus returned error"));
  97. }
  98. goto EXIT;
  99. }
  100.  
  101. // Tell the service controller we are started
  102. g_ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
  103. g_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
  104. g_ServiceStatus.dwWin32ExitCode = 0;
  105. g_ServiceStatus.dwCheckPoint = 0;
  106.  
  107. if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE)
  108. {
  109. OutputDebugString(_T("My Sample Service: ServiceMain: SetServiceStatus returned error"));
  110. }
  111.  
  112. // Start the thread that will perform the main task of the service
  113. HANDLE hThread = CreateThread(NULL, 0, ServiceWorkerThread, NULL, 0, NULL);
  114.  
  115. OutputDebugString(_T("My Sample Service: ServiceMain: Waiting for Worker Thread to complete"));
  116.  
  117. // Wait until our worker thread exits effectively signaling that the service needs to stop
  118. WaitForSingleObject(hThread, INFINITE);
  119.  
  120. OutputDebugString(_T("My Sample Service: ServiceMain: Worker Thread Stop Event signaled"));
  121.  
  122.  
  123. /*
  124. * Perform any cleanup tasks
  125. */
  126. OutputDebugString(_T("My Sample Service: ServiceMain: Performing Cleanup Operations"));
  127.  
  128. CloseHandle(g_ServiceStopEvent);
  129.  
  130. g_ServiceStatus.dwControlsAccepted = 0;
  131. g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
  132. g_ServiceStatus.dwWin32ExitCode = 0;
  133. g_ServiceStatus.dwCheckPoint = 3;
  134.  
  135. if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE)
  136. {
  137. OutputDebugString(_T("My Sample Service: ServiceMain: SetServiceStatus returned error"));
  138. }
  139.  
  140. EXIT:
  141. OutputDebugString(_T("My Sample Service: ServiceMain: Exit"));
  142.  
  143. return;
  144. }
  145.  
  146.  
  147. VOID WINAPI ServiceCtrlHandler(DWORD CtrlCode)
  148. {
  149. OutputDebugString(_T("My Sample Service: ServiceCtrlHandler: Entry"));
  150.  
  151. switch (CtrlCode)
  152. {
  153. case SERVICE_CONTROL_STOP:
  154.  
  155. OutputDebugString(_T("My Sample Service: ServiceCtrlHandler: SERVICE_CONTROL_STOP Request"));
  156.  
  157. if (g_ServiceStatus.dwCurrentState != SERVICE_RUNNING)
  158. break;
  159.  
  160. /*
  161. * Perform tasks neccesary to stop the service here
  162. */
  163.  
  164. g_ServiceStatus.dwControlsAccepted = 0;
  165. g_ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
  166. g_ServiceStatus.dwWin32ExitCode = 0;
  167. g_ServiceStatus.dwCheckPoint = 4;
  168.  
  169. if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE)
  170. {
  171. OutputDebugString(_T("My Sample Service: ServiceCtrlHandler: SetServiceStatus returned error"));
  172. }
  173.  
  174. // This will signal the worker thread to start shutting down
  175. SetEvent(g_ServiceStopEvent);
  176.  
  177. break;
  178.  
  179. default:
  180. break;
  181. }
  182.  
  183. OutputDebugString(_T("My Sample Service: ServiceCtrlHandler: Exit"));
  184. }
  185.  
  186.  
  187. DWORD WINAPI ServiceWorkerThread(LPVOID lpParam)
  188. {
  189. //MessageBoxA(NULL, "Error al abrir dll", "Cannot open DLL", MB_ICONERROR | MB_OK);
  190. OutputDebugString(_T("My Sample Service: ServiceWorkerThread: Entry"));
  191. if (ejecucion_admin())
  192. MessageBox(NULL, L"EJECUCION DE ADMIN", L"EJECUCION DE ADMIN", MB_ICONINFORMATION | MB_OK);
  193. else
  194. MessageBox(NULL, L"EJECUCION USUARIO", L"EJECUCION SIN NINGUN TIPO DE PRIVILEGIOS", MB_ICONINFORMATION | MB_OK);
  195. //  Periodically check if the service has been requested to stop
  196. while (WaitForSingleObject(g_ServiceStopEvent, 0) != WAIT_OBJECT_0)
  197. {
  198. MessageBoxA(NULL, "Error al abrir dll", "Cannot open DLL", MB_ICONERROR | MB_OK);
  199. /*
  200. * Perform main service function here
  201. */
  202.  
  203. //  Simulate some work by sleeping
  204. Sleep(3000);
  205. }
  206.  
  207. OutputDebugString(_T("My Sample Service: ServiceWorkerThread: Exit"));
  208.  
  209. return ERROR_SUCCESS;
  210. }
  211.  

Lo instalé y está en ejecución pero no muestra nada.

Bueno lo dejaré por hoy, ya lo miraré con detalle como funciona y demás.

O de otra manera, ¿dónde debería de ir el código?.

Saludos.


« Última modificación: 29 Diciembre 2015, 21:54 pm por Kaxperday » En línea

Cuando el poder económico parasita al político ningún partido ni dictador podrá liberarnos de él. Se reserva el 99% ese poder.
Zekkk

Desconectado Desconectado

Mensajes: 10


Ver Perfil
Re: ¿Por qué este servicio no muestra ventana?
« Respuesta #1 en: 27 Diciembre 2015, 23:04 pm »

Porque no estas creando ninguna ventana. Ve como crear una ventana, en WINAPI me parece que es con CreateWindow, o puedes mostrar los resultados en una consola.


En línea

Kaxperday


Desconectado Desconectado

Mensajes: 702


The man in the Middle


Ver Perfil WWW
Re: ¿Por qué este servicio no muestra ventana?
« Respuesta #2 en: 28 Diciembre 2015, 00:16 am »

Porque no estas creando ninguna ventana. Ve como crear una ventana, en WINAPI me parece que es con CreateWindow, o puedes mostrar los resultados en una consola.

??

Código
  1. MessageBox(NULL, L"EJECUCION DE ADMIN", L"EJECUCION DE ADMIN", MB_ICONINFORMATION | MB_OK);
  2.  

¿No debería esto de mostrar una ventana?, al compilarlo como ejecutable la muestra otra cosa sea que no llegue a esa línea de código que es lo que me pregunto, ¿dónde debería de ir el código? ¿El main de la aplicación, del servicio, lo que quiero que haga?, bueno me quiero adelantar ahora, pero realmente tendré que leer y aprender de servicios un poco, y ver si este es el camino que busco.

¿En qué linea debería de mostrar datos o una ventana?.

Saludos.
« Última modificación: 28 Diciembre 2015, 00:29 am por Kaxperday » En línea

Cuando el poder económico parasita al político ningún partido ni dictador podrá liberarnos de él. Se reserva el 99% ese poder.
Eternal Idol
Kernel coder
Moderador
***
Desconectado Desconectado

Mensajes: 5.937


Israel nunca torturó niños, ni lo volverá a hacer.


Ver Perfil WWW
Re: ¿Por qué este servicio no muestra ventana?
« Respuesta #3 en: 28 Diciembre 2015, 09:06 am »

MB_SERVICE_NOTIFICATION
https://msdn.microsoft.com/en-us/library/windows/desktop/ms645505%28v=vs.85%29.aspx

https://msdn.microsoft.com/en-us/library/windows/desktop/ms683502%28v=vs.85%29.aspx

Mejor no usar nada visual en un servicio, la idea es de segundo plano y en versiones mas recientes de Windows se ejecutan en una sesion propia separada de las interactivas del usuario loggeado.



No es casualidad que el ejemplo use abundantemente OutputDebugString, aca tenes una herramienta para ver ese output:
https://technet.microsoft.com/en-us/sysinternals/debugview.aspx
« Última modificación: 28 Diciembre 2015, 09:25 am por Eternal Idol » En línea

La economía nunca ha sido libre: o la controla el Estado en beneficio del Pueblo o lo hacen los grandes consorcios en perjuicio de éste.
Juan Domingo Perón
Kaxperday


Desconectado Desconectado

Mensajes: 702


The man in the Middle


Ver Perfil WWW
Re: ¿Por qué este servicio no muestra ventana?
« Respuesta #4 en: 28 Diciembre 2015, 13:51 pm »

MB_SERVICE_NOTIFICATION

Eso es, así si que muestra una ventana. He probado a ponerlo en diferentes zonas del código pero solo me ha funcionado en el _tmain que lo he puesto en su primera línea:

Código
  1. MessageBox(NULL, L"EJECUCION DE ADMIN", L"EJECUCION DE ADMIN", MB_SERVICE_NOTIFICATION | MB_OK);

¿Cual sería la línea o la función donde debería de poner mi código ¿en el _tmain?, quiero decir donde meter un programa en su conjunto con sus threads y todo, ¿solo con el _tmail me basta?, porque había cosas de iniciaizar servicio y controlador y demás que ni idea, y supongo que en mitad de eso no sea buena idea meter el codigo.

¿Dónde debería ponerlo?

Muchas gracias y un saludo.

Edito: Una vez que lo compilo lo instalo con:

Código:
C:\WINDOWS\system32>sc create mysample2 binpath= "C:\Users\Usuario\Desktop\servicio2.exe"

Entonces lo inicio desde el administrador de tareas y muestra estado  "en ejecución", pero no muestra ninguna ventana, sin embargo al ejecutarlo en VS13 si lo hacía, ¿que pasa?.

El objetivo final es comprobar que un servicio se va a ejecutar siempre como localsystem a fin de cuentas concederá los mismos permisos que de administrador si de código hablamos que es lo que busco, y que lo haga sin UAC, solo lo pida en su instalación y después ya sea capaz de actuar siempre con esos permisos, nada más.

También me he dado cuenta que "sc delete "nombreservicio" elimina el servicio, pero no su ejecutable asociado, por lo tanto podrían volverlo a instalar sin problema de nuevo.

Un saludo.
« Última modificación: 28 Diciembre 2015, 14:14 pm por Kaxperday » En línea

Cuando el poder económico parasita al político ningún partido ni dictador podrá liberarnos de él. Se reserva el 99% ese poder.
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines