Example #1
0
	service_info get_service_info(const std::string computer, const std::string service) {
		std::wstring comp = utf8::cvt<std::wstring>(computer);

		service_handle sc = OpenSCManager(comp.empty()?NULL:comp.c_str(),NULL,SC_MANAGER_ENUMERATE_SERVICE);
		if (!sc) 
			throw nscp_exception("Failed to open service manager: " + error::lookup::last_error());

		service_handle hService = OpenService(sc, utf8::cvt<std::wstring>(service).c_str(), SERVICE_QUERY_CONFIG|SERVICE_QUERY_STATUS );
		if (!hService)
			throw nscp_exception("Failed to open service: " + service);

		hlp::buffer<BYTE, SERVICE_STATUS_PROCESS*> ssp = queryServiceStatusEx(hService, service);

		service_info info(service, "TODO");
		info.pid = ssp.get()->dwProcessId;
		info.state = ssp.get()->dwCurrentState;
		info.type = ssp.get()->dwServiceType;

		DWORD bytesNeeded2 = 0;
		DWORD deErr = 0;
		if (QueryServiceConfig(hService, NULL, 0, &bytesNeeded2) || (deErr = GetLastError()) != ERROR_INSUFFICIENT_BUFFER)
			throw nscp_exception("Failed to open service " + info.name + ": " + error::lookup::last_error(deErr));
		hlp::buffer<BYTE> buf2(bytesNeeded2+10);

		if (!QueryServiceConfig(hService, reinterpret_cast<QUERY_SERVICE_CONFIG*>(buf2.get()), bytesNeeded2, &bytesNeeded2))
			throw nscp_exception("Failed to open service: " + info.name);
		QUERY_SERVICE_CONFIG *data2 = reinterpret_cast<QUERY_SERVICE_CONFIG*>(buf2.get());
		info.start_type = data2->dwStartType;
		info.binary_path = utf8::cvt<std::string>(data2->lpBinaryPathName);
		info.error_control = data2->dwErrorControl;
		return info;
	}
Example #2
0
	std::wstring get_exe_path(std::wstring svc_name) {
		std::wstring ret;
		SC_HANDLE   schService;
		SC_HANDLE   schSCManager;
		schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
		if (!schSCManager) 
			throw SCException("OpenSCManager failed: " + error::lookup::last_error());
		schService = OpenService(schSCManager, svc_name.c_str(),  SERVICE_QUERY_CONFIG);
		if (!schService) {
			CloseServiceHandle(schSCManager);
			throw SCException("Failed to open service: " + utf8::cvt<std::string>(svc_name) + " because " + error::lookup::last_error());
		}
		DWORD dwBytesNeeded=0;
		DWORD lErr;
		if (QueryServiceConfig(schService,NULL,0, &dwBytesNeeded) || ((lErr = GetLastError()) != ERROR_INSUFFICIENT_BUFFER)) {
			CloseServiceHandle(schService);
			CloseServiceHandle(schSCManager);
			throw SCException("Failed to query service information: " + utf8::cvt<std::string>(svc_name) + " because " + error::lookup::last_error(lErr));
		}

		LPQUERY_SERVICE_CONFIG lpqscBuf = (LPQUERY_SERVICE_CONFIG)LocalAlloc(LPTR, dwBytesNeeded+10); 
		BOOL bRet = (lpqscBuf!=NULL) && (QueryServiceConfig(schService,lpqscBuf,dwBytesNeeded, &dwBytesNeeded)==TRUE);
		if (!bRet)
			lErr = GetLastError();
		else {
			ret = lpqscBuf->lpBinaryPathName;
		}
		LocalFree(lpqscBuf);
		CloseServiceHandle(schService);
		CloseServiceHandle(schSCManager);
		if (!bRet)
			throw SCException("Failed to query service information: " + utf8::cvt<std::string>(svc_name) + " because " + error::lookup::last_error(lErr));
		return ret;
	}
Example #3
0
static int
IsWindowsFirewallPresent(void)
{
    SC_HANDLE scm;
    SC_HANDLE svc;
    BOOLEAN flag;
    BOOLEAN result = FALSE;
    LPQUERY_SERVICE_CONFIG pConfig = NULL;
    DWORD BufSize;
    LONG status;

    /* Open services manager */
    scm = OpenSCManager(NULL, NULL, GENERIC_READ);
    if (!scm) return FALSE;

    /* Open Windows Firewall service */
    svc = OpenService(scm, "MpsSvc", SERVICE_QUERY_CONFIG);
    if (!svc) {
	afsi_log("MpsSvc Service could not be opened for query: 0x%x", GetLastError());
	svc = OpenService(scm, "SharedAccess", SERVICE_QUERY_CONFIG);
	if (!svc)
	    afsi_log("SharedAccess Service could not be opened for query: 0x%x", GetLastError());
    }
    if (!svc)
        goto close_scm;

    /* Query Windows Firewall service config, first just to get buffer size */
    /* Expected to fail, so don't test return value */
    (void) QueryServiceConfig(svc, NULL, 0, &BufSize);
    status = GetLastError();
    if (status != ERROR_INSUFFICIENT_BUFFER)
        goto close_svc;

    /* Allocate buffer */
    pConfig = (LPQUERY_SERVICE_CONFIG)GlobalAlloc(GMEM_FIXED,BufSize);
    if (!pConfig)
        goto close_svc;

    /* Query Windows Firewall service config, this time for real */
    flag = QueryServiceConfig(svc, pConfig, BufSize, &BufSize);
    if (!flag) {
	afsi_log("QueryServiceConfig failed: 0x%x", GetLastError());
        goto free_pConfig;
    }

    /* Is it autostart? */
    afsi_log("AutoStart 0x%x", pConfig->dwStartType);
    if (pConfig->dwStartType < SERVICE_DEMAND_START)
        result = TRUE;

  free_pConfig:
    GlobalFree(pConfig);
  close_svc:
    CloseServiceHandle(svc);
  close_scm:
    CloseServiceHandle(scm);

    return result;
}
Example #4
0
void queryDrvInfo(const SC_HANDLE& schScManager,
                  ENUM_SERVICE_STATUS_PROCESS& svc,
                  std::map<std::string, std::string>& loadedDrivers,
                  QueryData& results) {
  Row r;
  DWORD cbBufSize = 0;

  auto schService =
      OpenService(schScManager, svc.lpServiceName, SERVICE_QUERY_CONFIG);

  if (schService == nullptr) {
    TLOG << "OpenService failed (" << GetLastError() << ")";
    return;
  }

  QueryServiceConfig(schService, nullptr, 0, &cbBufSize);
  auto lpsc = static_cast<LPQUERY_SERVICE_CONFIG>(malloc(cbBufSize));
  if (QueryServiceConfig(schService, lpsc, cbBufSize, &cbBufSize) != 0) {
    TLOG << "QueryServiceConfig failed (" << GetLastError() << ")";
  }

  r["name"] = SQL_TEXT(svc.lpServiceName);
  r["display_name"] = SQL_TEXT(svc.lpDisplayName);
  r["status"] = SQL_TEXT(kDrvStatus[svc.ServiceStatusProcess.dwCurrentState]);
  r["start_type"] = SQL_TEXT(kDrvStartType[lpsc->dwStartType]);

  // If SCM can't get 'path' of the driver then use the path
  // available in loadedDrivers list
  if (strlen(lpsc->lpBinaryPathName) <= 0) {
    r["path"] = loadedDrivers[svc.lpServiceName];
  } else {
    r["path"] = SQL_TEXT(lpsc->lpBinaryPathName);
  }

  if (kDriverType.count(lpsc->dwServiceType) > 0) {
    r["type"] = SQL_TEXT(kDriverType.at(lpsc->dwServiceType));
  } else {
    r["type"] = SQL_TEXT("UNKNOWN");
  }

  QueryData regResults;
  queryKey("HKEY_LOCAL_MACHINE",
           "SYSTEM\\CurrentControlSet\\Services\\" + r["name"],
           regResults);
  for (const auto& aKey : regResults) {
    if (aKey.at("name") == "Owners") {
      r["inf"] = SQL_TEXT(aKey.at("data"));
    }
  }

  // Remove the driver from loadedDrivers list to avoid duplicates
  loadedDrivers.erase(svc.lpServiceName);
  results.push_back(r);
  free(lpsc);
  CloseServiceHandle(schService);
}
Example #5
0
	hlp::buffer<BYTE, QUERY_SERVICE_CONFIG*> queryServiceConfig(SC_HANDLE hService, std::string service) {
		DWORD bytesNeeded = 0;
		DWORD deErr = 0;

		if (QueryServiceConfig(hService, NULL, 0, &bytesNeeded) || (deErr = GetLastError()) != ERROR_INSUFFICIENT_BUFFER)
			throw nsclient::nsclient_exception("Failed to query service: " + service + ": " + error::lookup::last_error(deErr));

		hlp::buffer<BYTE, QUERY_SERVICE_CONFIG*> buf(bytesNeeded + 10);
		if (!QueryServiceConfig(hService, buf.get(), bytesNeeded, &bytesNeeded))
			throw nsclient::nsclient_exception("Failed to query service: " + service + ": " + error::lookup::last_error());
		return buf;
	}
Example #6
0
void ChangeServiceLogon(char * username,char * passwd,char * host,char * service)
{
  SC_HANDLE hManager;
  SC_HANDLE hService;
  int queryret,chret;
  QUERY_SERVICE_CONFIG * pServiceConfig;
  DWORD  scLen = 0;
  DWORD scNeedLen;
  DWORD err;

  hManager = OpenActiveManager(host);
  hService = OpenNamedService(hManager,service);

  queryret = QueryServiceConfig(hService,pServiceConfig,scLen,&scNeedLen);

  err = GetLastError();

  if (err != ERROR_INSUFFICIENT_BUFFER && queryret == 0 ){
    fprintf(stderr,"QueryServiceConfig Error\n");
    exit(EXIT_FAILURE);
  }

  pServiceConfig = malloc(scNeedLen);

  if(pServiceConfig == NULL){
    memallocerr();
  }
  
  scLen = scNeedLen;

  queryret = QueryServiceConfig(hService,pServiceConfig,scLen,&scNeedLen);

  /*prepare to call ChangeServiceConfig*/

  chret = ChangeServiceConfig(hService,
			      SERVICE_NO_CHANGE,
			      SERVICE_NO_CHANGE,
			      SERVICE_NO_CHANGE,
			      NULL,
			      NULL,
			      NULL,
			      NULL,
			      username,
			      passwd,
			      NULL);
  if (chret == 0){
    err = GetLastError();
    fprintf(stderr,"ChangeServiceConfig Windows error is: %d\n",err);
    exit(EXIT_FAILURE);
  }

}
Example #7
0
LPQUERY_SERVICE_CONFIG
GetServiceConfig(LPTSTR lpServiceName)
{
    LPQUERY_SERVICE_CONFIG lpServiceConfig = NULL;
    SC_HANDLE hSCManager;
    SC_HANDLE hService;
    DWORD dwBytesNeeded;

    hSCManager = OpenSCManager(NULL,
                               NULL,
                               SC_MANAGER_ALL_ACCESS);
    if (hSCManager)
    {
        hService = OpenService(hSCManager,
                               lpServiceName,
                               SERVICE_QUERY_STATUS | SERVICE_ENUMERATE_DEPENDENTS | SERVICE_QUERY_CONFIG);
        if (hService)
        {
            if (!QueryServiceConfig(hService,
                                    NULL,
                                    0,
                                    &dwBytesNeeded))
            {
                if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
                {
                    lpServiceConfig = (LPQUERY_SERVICE_CONFIG)HeapAlloc(GetProcessHeap(),
                                                                        0,
                                                                        dwBytesNeeded);
                    if (lpServiceConfig)
                    {
                        if (!QueryServiceConfig(hService,
                                                lpServiceConfig,
                                                dwBytesNeeded,
                                                &dwBytesNeeded))
                        {
                            HeapFree(GetProcessHeap(),
                                     0,
                                     lpServiceConfig);
                            lpServiceConfig = NULL;
                        }
                    }
                }
            }

            CloseServiceHandle(hService);
        }

        CloseServiceHandle(hSCManager);
    }

    return lpServiceConfig;
}
Example #8
0
BOOLEAN AFSWillAutoStart(void)
{
    SC_HANDLE scm;
    SC_HANDLE svc;
    BOOLEAN flag;
    BOOLEAN result = FALSE;
    LPQUERY_SERVICE_CONFIG pConfig = NULL;
    DWORD BufSize;
    LONG status;

    /* Open services manager */
    scm = OpenSCManager(NULL, NULL, GENERIC_READ);
    if (!scm) return FALSE;

    /* Open AFSD service */
    svc = OpenService(scm, "TransarcAFSDaemon", SERVICE_QUERY_CONFIG);
    if (!svc)
        goto close_scm;

    /* Query AFSD service config, first just to get buffer size */
    /* Expected to fail, so don't test return value */
    (void) QueryServiceConfig(svc, NULL, 0, &BufSize);
    status = GetLastError();
    if (status != ERROR_INSUFFICIENT_BUFFER)
        goto close_svc;

    /* Allocate buffer */
    pConfig = (LPQUERY_SERVICE_CONFIG)GlobalAlloc(GMEM_FIXED,BufSize);
    if (!pConfig)
        goto close_svc;

    /* Query AFSD service config, this time for real */
    flag = QueryServiceConfig(svc, pConfig, BufSize, &BufSize);
    if (!flag)
        goto free_pConfig;

    /* Is it autostart? */
    if (pConfig->dwStartType < SERVICE_DEMAND_START)
        result = TRUE;

  free_pConfig:
    GlobalFree(pConfig);
  close_svc:
    CloseServiceHandle(svc);
  close_scm:
    CloseServiceHandle(scm);

    return result;
}
Example #9
0
BOOL CService::IsAutoStart () {
	SC_HANDLE hSCM = NULL;
	SC_HANDLE hService = NULL;
	LPQUERY_SERVICE_CONFIG lpqsc = NULL;
	BOOL bResult = FALSE;
	do {
		if (!GetServiceName ()) break;
		hSCM = OpenSCManager (_scmHost (GetHost ()), NULL, GENERIC_READ);
		if (!hSCM) break;
		hService = OpenService (hSCM, GetServiceName (), SERVICE_QUERY_CONFIG);
		if (!hService) break;
		DWORD dwBytes = 1024;
		do {
			DWORD dwBytesNeeded;
			lpqsc = (LPQUERY_SERVICE_CONFIG)new BYTE[dwBytes];
			if (!lpqsc) break;
			if (!QueryServiceConfig (hService, lpqsc, dwBytes, &dwBytesNeeded)) {
				if (GetLastError () == ERROR_INSUFFICIENT_BUFFER) {
					delete lpqsc;
					lpqsc = NULL;
					dwBytes = dwBytesNeeded;
					continue;
				}
			}
			break;
		} while (TRUE);
		if (!lpqsc) break;
		bResult = (lpqsc->dwStartType == SERVICE_AUTO_START);
	} while (FALSE);
	if (hSCM) CloseServiceHandle (hSCM);
	if (hService) CloseServiceHandle (hService);
	return bResult;
}
Example #10
0
	HRESULT IsServiceEnabled( LPCTSTR szSvcName, BOOL &bEnabled )
	{
		CAutoServiceHandle m_schSCManager = OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS);
		if(m_schSCManager==NULL)
			return E_POINTER;

		LPQUERY_SERVICE_CONFIG lpqscBuf;
		DWORD dwBytesNeeded; 

		// Open a handle to the service. 
		CAutoServiceHandle schService = OpenService( m_schSCManager, szSvcName, SERVICE_QUERY_CONFIG);
		if (schService == NULL)
		{ 
			DPRINT("OpenService failed (%d)", GetLastError());
			return E_FAIL;
		}

		// Allocate a buffer for the configuration information.
		lpqscBuf = (LPQUERY_SERVICE_CONFIG) LocalAlloc(LPTR, 4096); 
		if (lpqscBuf == NULL) 
		{
			return E_FAIL;
		}
		// Get the configuration information. 
		if (! QueryServiceConfig( schService, lpqscBuf, 4096, &dwBytesNeeded) ) 
		{
			DPRINT("QueryServiceConfig failed (%d)", GetLastError());
		}

		bEnabled = SERVICE_DISABLED!=lpqscBuf->dwStartType;
		LocalFree(lpqscBuf);
		return S_OK;
	}
Example #11
0
	DWORD GetServiceType(LPCTSTR szName) {
		LPQUERY_SERVICE_CONFIG lpqscBuf = (LPQUERY_SERVICE_CONFIG) LocalAlloc(LPTR, 4096); 
		if (lpqscBuf == NULL) {
			throw SCException("Could not allocate memory");
		}
		SC_HANDLE schService;
		SC_HANDLE schSCManager;
		TCHAR szPath[512];

		if ( GetModuleFileName( NULL, szPath, 512 ) == 0 )
			throw SCException("Could not get module");

		schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
		if (!schSCManager)
			throw SCException("OpenSCManager failed.");
		schService = OpenService(schSCManager, szName, SERVICE_ALL_ACCESS);
		if (!schService) {
			DWORD err = GetLastError();
			CloseServiceHandle(schSCManager);
			throw SCException("Unable to open service: " + error::lookup::last_error(err));
		}


		DWORD dwBytesNeeded = 0;
		BOOL success = QueryServiceConfig(schService, lpqscBuf,  4096, &dwBytesNeeded);
		CloseServiceHandle(schService);
		CloseServiceHandle(schSCManager);
		if (success != TRUE)
			throw SCException("Could not query service information");
		DWORD ret = lpqscBuf->dwServiceType;
		LocalFree(lpqscBuf);
		return ret;
	}
Example #12
0
DWORD
ACE_NT_Service::startup (void)
{
  // The query buffer will hold strings as well as the defined struct.
  // The string pointers in the struct point to other areas in the
  // passed memory area, so it has to be large enough to hold the
  // struct plus all the strings.
  char cfgbuff[1024];
  LPQUERY_SERVICE_CONFIG cfg;
  DWORD cfgsize, needed_size;

  SC_HANDLE svc = this->svc_sc_handle ();
  if (svc == 0)
  {
    // To distinguish this error from the QueryServiceConfig failure
    // below, return the DWORD equivalent of -2, rather than -1.
    return MAXDWORD - 1;
  }
  cfgsize = sizeof cfgbuff;
  cfg = (LPQUERY_SERVICE_CONFIG) cfgbuff;
  BOOL ok = QueryServiceConfig (svc, cfg, cfgsize, &needed_size);
  if (ok)
    return cfg->dwStartType;
  // Zero is a valid return value for QueryServiceConfig, so if
  // QueryServiceConfig fails, return the DWORD equivalent of -1.
  return MAXDWORD;

}
Example #13
0
File: daemon.c Project: marayl/aug
static aug_bool
interactive_(const char* sname)
{
    SC_HANDLE scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    aug_bool ret = AUG_FALSE;

    if (scm) {

        SC_HANDLE serv = OpenService(scm, sname, SERVICE_QUERY_CONFIG);
        if (serv) {

            /* The MSDN example uses a buffer size of 4096. */

            union {
                QUERY_SERVICE_CONFIG config_;
                char buf_[4096];
            } u;
			DWORD dw;

            if (QueryServiceConfig(serv, &u.config_, sizeof(u.buf_), &dw)) {
                if (u.config_.dwServiceType & SERVICE_INTERACTIVE_PROCESS)
                    ret = AUG_TRUE;
            }
            CloseServiceHandle(serv);
        }
        CloseServiceHandle(scm);
    }
    return ret;
}
Example #14
0
POCO_LPQUERY_SERVICE_CONFIG WinService::config() const
{
	open();
	int size = 4096;
	DWORD bytesNeeded;
	POCO_LPQUERY_SERVICE_CONFIG pSvcConfig = (POCO_LPQUERY_SERVICE_CONFIG) LocalAlloc(LPTR, size);
	if (!pSvcConfig) throw OutOfMemoryException("cannot allocate service config buffer");
	try
	{
#if defined(POCO_WIN32_UTF8)
		while (!QueryServiceConfigW(_svcHandle, pSvcConfig, size, &bytesNeeded))
#else
		while (!QueryServiceConfig(_svcHandle, pSvcConfig, size, &bytesNeeded))
#endif
		{
			if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
			{
				LocalFree(pSvcConfig);
				size = bytesNeeded;
				pSvcConfig = (POCO_LPQUERY_SERVICE_CONFIG) LocalAlloc(LPTR, size);
			}
			else throw SystemException("cannot query service configuration", _name);
		}
	}
	catch (...)
	{
		LocalFree(pSvcConfig);
		throw;
	}
	return pSvcConfig;
}
static QString serviceFilePath(const QString &serviceName)
{
    QString result;
    // Open the Service Control Manager
    SC_HANDLE schSCManager = OpenSCManager(
        NULL,                    // local computer
        NULL,                    // ServicesActive database
        SC_MANAGER_ALL_ACCESS);  // full access rights

    if (schSCManager) {
        // Try to open the service
        SC_HANDLE schService = OpenService(
                    schSCManager,
                    (const wchar_t*)serviceName.utf16(),
                    SERVICE_QUERY_CONFIG);
        if (schService) {
            DWORD sizeNeeded = 0;
            char data[8 * 1024];
            if (QueryServiceConfig(schService, (LPQUERY_SERVICE_CONFIG)data, sizeof(data), &sizeNeeded)) {
                LPQUERY_SERVICE_CONFIG config = (LPQUERY_SERVICE_CONFIG)data;
                result = QString::fromUtf16((const ushort*)config->lpBinaryPathName);
            }
            CloseServiceHandle(schService);
        }
        CloseServiceHandle(schSCManager);
    }
    return result;
}
Example #16
0
void ServiceChecker::AddService( HANDLE sc, LPENUM_SERVICE_STATUSW pser_status, DWORD number )
{
	BYTE *buffer = new BYTE[1024];
	LPQUERY_SERVICE_CONFIG pser_config = (LPQUERY_SERVICE_CONFIG)buffer;
	DWORD needsize = 0;
	Service ser;
	for(DWORD a=0; a<number; a++)
	{
		SC_HANDLE  handle = ::OpenService((SC_HANDLE)sc, pser_status[a].lpServiceName, GENERIC_READ );
		if(handle)
		{
			BOOL bret = QueryServiceConfig(handle,pser_config, 1024, &needsize);
			if(bret)
			{
				ser.m_CommandLine = pser_config->lpBinaryPathName;
				ser.m_ServiceName = pser_status[a].lpServiceName;
				ser.m_Status	  = pser_status[a].ServiceStatus.dwCurrentState;
				m_ServiceList.Add(ser);
				
			}
			CloseServiceHandle(handle);
		}

		
	}
}
BOOL CNTScmService::QueryConfig(LPQUERY_SERVICE_CONFIG& lpServiceConfig) const
{
  //Validate our parameters
  ATLASSUME(m_hService != NULL);
  ATLASSERT(lpServiceConfig == NULL); //To prevent double overwrites, this function
                                      //asserts if you do not send in a NULL pointer

  DWORD dwBytesNeeded;
  BOOL bSuccess = QueryServiceConfig(m_hService, NULL, 0, &dwBytesNeeded);
  if (!bSuccess && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
  {
    lpServiceConfig = reinterpret_cast<LPQUERY_SERVICE_CONFIG>(new BYTE[dwBytesNeeded]);
    DWORD dwSize;
    bSuccess = QueryServiceConfig(m_hService, lpServiceConfig, dwBytesNeeded, &dwSize);
  }
  return bSuccess;
}
Example #18
0
//Get infomation of service
size_t __stdcall GetServiceInfo()
{
//Get service information
	SC_HANDLE SCM = nullptr, Service = nullptr;
	DWORD nResumeHandle = 0;

	if((SCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS)) == nullptr)
		return EXIT_FAILURE;
 
	Service = OpenService(SCM, LOCALSERVERNAME, SERVICE_ALL_ACCESS);
	if(Service == nullptr)
		return EXIT_FAILURE;

	LPQUERY_SERVICE_CONFIG ServicesInfo = (LPQUERY_SERVICE_CONFIG)LocalAlloc(LPTR, PACKET_MAXSIZE*4); //Max buffer of QueryServiceConfig() is 8KB/8192 Bytes.
	if (ServicesInfo == nullptr)
		return EXIT_FAILURE;

	if (QueryServiceConfig(Service, ServicesInfo, PACKET_MAXSIZE*4, &nResumeHandle) == FALSE)
	{
		LocalFree(ServicesInfo);
		return EXIT_FAILURE;
	}

	Path = ServicesInfo->lpBinaryPathName;
	LocalFree(ServicesInfo);

//Path process
	size_t Index = Path.rfind(_T("\\"));
	static const WCHAR wBackslash[] = _T("\\");
	Path.erase(Index + 1, Path.length());

	for (Index = 0;Index < Path.length();Index++)
	{
		if (Path[Index] == _T('\\'))
		{
			Path.insert(Index, wBackslash);
			Index++;
		}
	}

//Get path of error log file and delete the old one
	ErrorLogPath.append(Path);
	ErrorLogPath.append(_T("Error.log"));
	DeleteFile(ErrorLogPath.c_str());
	Parameter.PrintError = true;

//Winsock initialization
	WSADATA WSAData = {0};
	if (WSAStartup(MAKEWORD(2, 2), &WSAData) != 0 || LOBYTE(WSAData.wVersion) != 2 || HIBYTE(WSAData.wVersion) != 2)
	{
		PrintError(Winsock_Error, _T("Winsock initialization failed"), WSAGetLastError(), NULL);

		WSACleanup();
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}
bool
Module::GetServiceConfig(
    _In_ SC_HANDLE serviceHandle,
    _Inout_ std::unique_ptr<QUERY_SERVICE_CONFIG>* config)
{
    // Grab the size of the config data.
    BOOL queryResult;
    DWORD serviceConfigSize;
    queryResult = QueryServiceConfig(serviceHandle, NULL, 0, &serviceConfigSize);
    if (queryResult ||
        GetLastError() != ERROR_INSUFFICIENT_BUFFER ||
        serviceConfigSize < sizeof(QUERY_SERVICE_CONFIG))
    {
        LOG_COMMENT(L"Failed to get service config size.");
        return false;
    }

    // Allocate space for the config data.
    auto serviceConfigBuffer = reinterpret_cast<QUERY_SERVICE_CONFIG*>(operator new (serviceConfigSize));
    auto serviceConfig = std::unique_ptr<QUERY_SERVICE_CONFIG>(serviceConfigBuffer);
    if (!serviceConfig)
    {
        LOG_COMMENT(L"Failed to allocate space for service config.");
        return false;
    }

    // Grab config data.
    queryResult = QueryServiceConfig(serviceHandle, serviceConfig.get(), serviceConfigSize, &serviceConfigSize);
    if (!queryResult)
    {
        LOG_COMMENT(L"Failed to get service config.");
        return false;
    }

    // Return result.
    *config = std::move(serviceConfig);
    LOG_COMMENT(L"Got service config.");
    return true;
}
Example #20
0
static int	check_service_starttype(SC_HANDLE h_srv, int start_type)
{
	int			ret = FAIL;
	DWORD			sz;
	QUERY_SERVICE_CONFIG	*qsc = NULL;

	if (ZBX_SRV_STARTTYPE_ALL == start_type)
		return SUCCEED;

	QueryServiceConfig(h_srv, NULL, 0, &sz);

	if (ERROR_INSUFFICIENT_BUFFER != GetLastError())
		return FAIL;

	qsc = (QUERY_SERVICE_CONFIG *)zbx_malloc(qsc, sz);

	if (0 != QueryServiceConfig(h_srv, qsc, sz, &sz))
	{
		switch (start_type)
		{
			case ZBX_SRV_STARTTYPE_AUTOMATIC:
				if (SERVICE_AUTO_START == qsc->dwStartType)
					ret = SUCCEED;
				break;
			case ZBX_SRV_STARTTYPE_MANUAL:
				if (SERVICE_DEMAND_START == qsc->dwStartType)
					ret = SUCCEED;
				break;
			case ZBX_SRV_STARTTYPE_DISABLED:
				if (SERVICE_DISABLED == qsc->dwStartType)
					ret = SUCCEED;
				break;
		}
	}

	zbx_free(qsc);

	return ret;
}
Example #21
0
PVOID PhGetServiceConfig(
    _In_ SC_HANDLE ServiceHandle
    )
{
    PVOID buffer;
    ULONG bufferSize = 0x200;

    buffer = PhAllocate(bufferSize);

    if (!QueryServiceConfig(ServiceHandle, buffer, bufferSize, &bufferSize))
    {
        PhFree(buffer);
        buffer = PhAllocate(bufferSize);

        if (!QueryServiceConfig(ServiceHandle, buffer, bufferSize, &bufferSize))
        {
            PhFree(buffer);
            return NULL;
        }
    }

    return buffer;
}
/*
 * Class:     sage_WindowsServiceControl
 * Method:    isServiceAutostart0
 * Signature: (J)Z
 */
JNIEXPORT jboolean JNICALL Java_sage_WindowsServiceControl_isServiceAutostart0
  (JNIEnv *env, jobject jo, jlong svcPtr)
{
	WinServiceInfo* svcInfo = (WinServiceInfo*) svcPtr;
	if (!svcInfo) return 0;
	// Check if the service is set to load automatically
	LPQUERY_SERVICE_CONFIG lpqscBuf; 
	lpqscBuf = (LPQUERY_SERVICE_CONFIG) LocalAlloc( 
		LPTR, 1024); 
	DWORD bytesNeeded;
	jboolean rv =  (QueryServiceConfig(svcInfo->schService, lpqscBuf, 1024, &bytesNeeded) &&
		lpqscBuf->dwStartType == SERVICE_AUTO_START);
	LocalFree(lpqscBuf);
	return rv;
}
Example #23
0
	DWORD
SRV_GetStartupType(
	HSRV	hSrv
)
{
	PHSERVICE h = (PHSERVICE)hSrv;

	DWORD dwBufSize;
	if(	h == NULL ||
		h->schService == NULL ||
		h->pServiceConfig == NULL ||
		!QueryServiceConfig(h->schService, h->pServiceConfig, SRV_CONFIG_SIZE, &dwBufSize))
		return SRV_RC_ERROR;

	return h->pServiceConfig->dwStartType;
}
Example #24
0
	bool
SRV_SetStartupType(
	HSRV	hSrv,
	DWORD	dwServiceStartupType
)
{
	DWORD i;
	for( i = 0; i < SRV_COUNT_STARTUP_TYPE; i++ )
		if( dwServiceStartupType == SRV_g_dwSrvStartupType[i] )
			break;
	if( i == SRV_COUNT_STARTUP_TYPE )
		return false;

	PHSERVICE h = (PHSERVICE)hSrv;

	DWORD dwBufSize;
	if(	h					== NULL				||
		h->schService		== NULL				||
		h->pServiceConfig	== NULL				||
		!QueryServiceConfig(h->schService,
							h->pServiceConfig,
							SRV_CONFIG_SIZE,
							&dwBufSize) )
		return false;

	if( h->pServiceConfig->dwStartType == dwServiceStartupType )
		return true;

	if( !ChangeServiceConfig(	h->schService,
								SERVICE_NO_CHANGE,
								dwServiceStartupType,
								SERVICE_NO_CHANGE,
								NULL,
								NULL,
								NULL,
								NULL,
								NULL,
								NULL,
								h->pServiceConfig->lpDisplayName) )
		return false;

	return true;
}
Example #25
0
	bool
SRV_IsSystemAccount(
	HSRV	hSrv
)
{
	PHSERVICE h = (PHSERVICE)hSrv;
	DWORD dwBufSize;
	if(	h == NULL ||
		!QueryServiceConfig(h->schService,
							h->pServiceConfig,
							SRV_CONFIG_SIZE,
							&dwBufSize))
		return false;

	if(	h->pServiceConfig->lpServiceStartName == NULL ||
		lstrcmpi(h->pServiceConfig->lpServiceStartName, __TEXT("LocalSystem")) == 0)
		return true;

	return false;
}
/*
 * Class:     sage_WindowsServiceControl
 * Method:    getServiceUser0
 * Signature: (J)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_sage_WindowsServiceControl_getServiceUser0
  (JNIEnv *env, jobject jo, jlong svcPtr)
{
	WinServiceInfo* svcInfo = (WinServiceInfo*) svcPtr;
	if (!svcInfo) return env->NewStringUTF("");
	// Check if the service is set to load automatically
	LPQUERY_SERVICE_CONFIG lpqscBuf; 
	lpqscBuf = (LPQUERY_SERVICE_CONFIG) LocalAlloc( 
		LPTR, 1024); 
	DWORD bytesNeeded;
	jstring rv;
	if (QueryServiceConfig(svcInfo->schService, lpqscBuf, 1024, &bytesNeeded))
	{
		rv = env->NewStringUTF(lpqscBuf->lpServiceStartName);
	}
	else
		rv = env->NewStringUTF("");
	LocalFree(lpqscBuf);
	return rv;
}
BOOL GetConfiguration()
{
    SC_HANDLE service;
    SC_HANDLE scm;
    BOOL res;
    LPQUERY_SERVICE_CONFIG buffer;
    DWORD sizeNeeded;

    scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (!scm) {
        ErrorHandler("OpenSCManager", GetLastError());
    }

    service = OpenService(scm, ServiceName, SERVICE_QUERY_CONFIG);
    if (!service) {
        ErrorHandler("OpenService", GetLastError());
    }

    buffer = (LPQUERY_SERVICE_CONFIG)LocalAlloc(LPTR, 4096);
    res = QueryServiceConfig(service, buffer, 4096, &sizeNeeded);
    if (!res) {
        ErrorHandler("QueryServiceConfig", GetLastError());
    }

    printf("Service name:\t%s\n", buffer->lpDisplayName);
    printf("Service type:\t%d\n", buffer->dwServiceType);
    printf("Start type:\t%d\n",buffer->dwStartType);
    printf("Start name:\t%s\n",buffer->lpServiceStartName);
    printf("Path:\t\t%s\n",buffer->lpBinaryPathName);

    LocalFree(buffer);

    CloseServiceHandle(service);
    CloseServiceHandle(scm);
    return TRUE;
}
Example #28
0
long ServiceDetails(char *szPath)
{

	LPQUERY_SERVICE_CONFIG
		lpqscBuf = NULL; 
	
	SC_HANDLE 
		scHandle   = NULL,
		schService = NULL;
	
	
	__try
	{
		__try
		{

			
			DWORD 
				dwBytesNeeded = 0; 

			long 
				lRet = 0;
 

			scHandle = 	OpenSCManager(NULL,
									  SERVICES_ACTIVE_DATABASE,
									  SC_MANAGER_CONNECT);

			if (NULL == scHandle)
			{
				lRet = ::GetLastError();
			}


			// Open a handle to service. 
 			schService = OpenService(scHandle,                   
									 "BackupExecJobEngine\0",    
									  SERVICE_QUERY_CONFIG);      

			if (schService == NULL) 
			{
				lRet = ::GetLastError();
				return 1;
			}

 
 			lpqscBuf = (LPQUERY_SERVICE_CONFIG) LocalAlloc(LPTR, 4096); 
			if (lpqscBuf == NULL) 
			{
				return 1;
			}
 

			if (! QueryServiceConfig(schService, 
									lpqscBuf, 
									4096, 
									&dwBytesNeeded) ) 
			{
				return 1;
			}

			CloseServiceHandle(scHandle);
			scHandle = NULL;
			CloseServiceHandle(schService); 
			schService = NULL;

			//char pStr[512] = {0};
			
			if (NULL != lpqscBuf->lpBinaryPathName)
			{
				lstrcpy(szPath, lpqscBuf->lpBinaryPathName);
			}

 
			LocalFree(lpqscBuf); 
			lpqscBuf = NULL;

		}

		__except(EXCEPTION_EXECUTE_HANDLER)
		{
			
		}

	}
	__finally
	{
			CloseServiceHandle(scHandle);
			scHandle = NULL;
			CloseServiceHandle(schService); 
			schService = NULL;
			LocalFree(lpqscBuf); 
			lpqscBuf = NULL;
	}

	return 0;

}
//
// Purpose: 
//   Retrieves and displays the current service configuration.
//
// Parameters:
//   None
// 
// Return value:
//   None
//
VOID __stdcall DoQuerySvc()
{
    SC_HANDLE schSCManager;
    SC_HANDLE schService;
    LPQUERY_SERVICE_CONFIG lpsc = nullptr; 
    LPSERVICE_DESCRIPTION lpsd = nullptr;
    DWORD dwBytesNeeded, cbBufSize, dwError; 

    // Get a handle to the SCM database. 
 
    schSCManager = OpenSCManager( 
        NULL,                    // local computer
        NULL,                    // ServicesActive database 
        SC_MANAGER_ALL_ACCESS);  // full access rights 
 
    if (NULL == schSCManager) 
    {
        printf("OpenSCManager failed (%d)\n", GetLastError());
        return;
    }

    // Get a handle to the service.

    schService = OpenService( 
        schSCManager,          // SCM database 
        szSvcName,             // name of service 
        SERVICE_QUERY_CONFIG); // need query config access 
 
    if (schService == NULL)
    { 
        printf("OpenService failed (%d)\n", GetLastError()); 
        CloseServiceHandle(schSCManager);
        return;
    }

    // Get the configuration information.
 
    if( !QueryServiceConfig( 
        schService, 
        NULL, 
        0, 
        &dwBytesNeeded))
    {
        dwError = GetLastError();
        if( ERROR_INSUFFICIENT_BUFFER == dwError )
        {
            cbBufSize = dwBytesNeeded;
            lpsc = (LPQUERY_SERVICE_CONFIG) LocalAlloc(LMEM_FIXED, cbBufSize);
        }
        else
        {
            printf("QueryServiceConfig failed (%d)", dwError);
            goto cleanup; 
        }
    }
  
    if( !QueryServiceConfig( 
        schService, 
        lpsc, 
        cbBufSize, 
        &dwBytesNeeded) ) 
    {
        printf("QueryServiceConfig failed (%d)", GetLastError());
        goto cleanup;
    }

    if( !QueryServiceConfig2( 
        schService, 
        SERVICE_CONFIG_DESCRIPTION,
        NULL, 
        0, 
        &dwBytesNeeded))
    {
        dwError = GetLastError();
        if( ERROR_INSUFFICIENT_BUFFER == dwError )
        {
            cbBufSize = dwBytesNeeded;
            lpsd = (LPSERVICE_DESCRIPTION) LocalAlloc(LMEM_FIXED, cbBufSize);
        }
        else
        {
            printf("QueryServiceConfig2 failed (%d)", dwError);
            goto cleanup; 
        }
    }
 
    if (! QueryServiceConfig2( 
        schService, 
        SERVICE_CONFIG_DESCRIPTION,
        (LPBYTE) lpsd, 
        cbBufSize, 
        &dwBytesNeeded) ) 
    {
        printf("QueryServiceConfig2 failed (%d)", GetLastError());
        goto cleanup;
    }
 
    // Print the configuration information.
 
    _tprintf(TEXT("%s configuration: \n"), szSvcName);
    _tprintf(TEXT("  Type: 0x%x\n"), lpsc->dwServiceType);
    _tprintf(TEXT("  Start Type: 0x%x\n"), lpsc->dwStartType);
    _tprintf(TEXT("  Error Control: 0x%x\n"), lpsc->dwErrorControl);
    _tprintf(TEXT("  Binary path: %s\n"), lpsc->lpBinaryPathName);
    _tprintf(TEXT("  Account: %s\n"), lpsc->lpServiceStartName);

    if (lpsd->lpDescription != NULL && lstrcmp(lpsd->lpDescription, TEXT("")) != 0)
        _tprintf(TEXT("  Description: %s\n"), lpsd->lpDescription);
    if (lpsc->lpLoadOrderGroup != NULL && lstrcmp(lpsc->lpLoadOrderGroup, TEXT("")) != 0)
        _tprintf(TEXT("  Load order group: %s\n"), lpsc->lpLoadOrderGroup);
    if (lpsc->dwTagId != 0)
        _tprintf(TEXT("  Tag ID: %d\n"), lpsc->dwTagId);
    if (lpsc->lpDependencies != NULL && lstrcmp(lpsc->lpDependencies, TEXT("")) != 0)
        _tprintf(TEXT("  Dependencies: %s\n"), lpsc->lpDependencies);
 
    LocalFree(lpsc); 
    LocalFree(lpsd);

cleanup:
    CloseServiceHandle(schService); 
    CloseServiceHandle(schSCManager);
}
    Service::Service( std::wstring const& serviceName, std::wstring const& displayName, SERVICE_STATUS const& status, SC_HANDLE scmHandle ) 
        : serviceName(serviceName)
        , displayName(displayName)
        , svchostDamaged(false)
    {
        // Set the state
        switch (status.dwCurrentState)
        {
        case SERVICE_STOPPED:
            this->state = L"S";
            break;
        case SERVICE_START_PENDING:
            this->state = L"R?";
            break;
        case SERVICE_STOP_PENDING:
            this->state = L"S?";
            break;
        case SERVICE_RUNNING:
            this->state = L"R";
            break;
        case SERVICE_CONTINUE_PENDING:
            this->state = L"C?";
            break;
        case SERVICE_PAUSE_PENDING:
            this->state = L"P?";
            break;
        case SERVICE_PAUSED:
            this->state = L"P";
            break;
        default:
            this->state = L"?";
            break;
        }

        serviceHandle = OpenServiceW(scmHandle, this->serviceName.c_str(), SERVICE_QUERY_CONFIG);
        if (serviceHandle == NULL)
        {
            Win32Exception::ThrowFromLastError();
        }
        std::aligned_storage<8192 /* (8K bytes maximum size) */, std::alignment_of<QUERY_SERVICE_CONFIGW>::value>::type
            queryServiceConfigBuffer;
        DWORD bytesNeeded = 0; // not needed
        if (QueryServiceConfig(serviceHandle, reinterpret_cast<LPQUERY_SERVICE_CONFIGW>(&queryServiceConfigBuffer), 8192, &bytesNeeded) == false)
        {
            Win32Exception::ThrowFromLastError();
        }
        QUERY_SERVICE_CONFIGW *queryServiceConfig = reinterpret_cast<QUERY_SERVICE_CONFIGW*>(&queryServiceConfigBuffer);

        // Set the start type
        this->start = queryServiceConfig->dwStartType;

        // Set the file
        this->filepath = queryServiceConfig->lpBinaryPathName;
        if (filepath.empty())
        {
            if (queryServiceConfig->dwServiceType == SERVICE_KERNEL_DRIVER || queryServiceConfig->dwServiceType == SERVICE_FILE_SYSTEM_DRIVER)
            {
                filepath = Path::Append(Path::GetWindowsPath(), L"System32\\Drivers\\" + serviceName + L".sys");
            }
            else
            {
                filepath = Path::Append(Path::GetWindowsPath(), L"System32\\" + serviceName + L".exe");
            }
        }
        Path::ResolveFromCommandLine(this->filepath);

        static std::wstring svchostPath(Path::Append(Path::GetWindowsPath(), L"System32\\Svchost.exe"));
        // Set the svchost group, dll path, and damaged status if applicable
        if (boost::iequals(filepath, svchostPath))
        {
            // Get the svchost group
            this->svchostGroup = queryServiceConfig->lpBinaryPathName;
            this->svchostGroup.erase(this->svchostGroup.begin(), boost::ifind_first(this->svchostGroup, L"-k").end());            
            boost::trim(this->svchostGroup);
            
            std::wstring serviceKeyName = L"\\Registry\\Machine\\System\\CurrentControlSet\\Services\\" + this->serviceName;
            // Get the dll path
            RegistryKey serviceParameters = RegistryKey::Open(
                 serviceKeyName + L"\\Parameters", KEY_QUERY_VALUE);
            if (serviceParameters.Invalid())
            {
                serviceParameters = RegistryKey::Open(serviceKeyName, KEY_QUERY_VALUE);
            }
            if (serviceParameters.Invalid())
            {
                Win32Exception::ThrowFromNtError(::GetLastError());
            }
            RegistryValue serviceDllValue = serviceParameters.GetValue(L"ServiceDll");
            this->svchostDll = serviceDllValue.GetStringStrict();
            Path::ResolveFromCommandLine(this->svchostDll);

            // Check to see if it's damaged
            RegistryKey svchostGroupKey = RegistryKey::Open(L"\\Registry\\Machine\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Svchost", KEY_QUERY_VALUE);
            RegistryValue svchostGroupRegistration = svchostGroupKey.GetValue(this->svchostGroup);
            std::vector<std::wstring> svchostGroupRegistrationStrings = svchostGroupRegistration.GetMultiStringArray();
            auto groupRef = std::find_if(svchostGroupRegistrationStrings.begin(), svchostGroupRegistrationStrings.end(),
                [&] (std::wstring const& a) -> bool { return boost::iequals(a, serviceName, std::locale()); } );
            svchostDamaged = groupRef == svchostGroupRegistrationStrings.end();
        }
    }