/*! @brief ユーザフルネームの取得 (Unicode) */ BOOL CUserInfoDlg::GetFullNameW(wchar_t *UserName, wchar_t *, wchar_t *dest) { LPBYTE ComputerName = 0; struct _USER_INFO_2 *ui; // User structure BOOL bFoundDC = TRUE; DWORD nRet = NetGetDCName(NULL, NULL, &ComputerName ); // Get the computer name of a DC for the specified domain. if (nRet != NERR_Success) { printf("Error getting user information.\n" ); bFoundDC = FALSE; } // Look up the user on the DC. nRet = NetUserGetInfo((LPWSTR) ComputerName, (LPWSTR) UserName, 2, (LPBYTE *) &ui); if (nRet != NERR_Success) { if (bFoundDC == TRUE) { NetApiBufferFree(ComputerName); } printf("Error getting user information.\n" ); return(FALSE ); } if (bFoundDC == TRUE) { NetApiBufferFree(ComputerName); } wcsncpy_s(dest, 256, ui->usri2_full_name, _TRUNCATE); return(TRUE ); }
int main(int argc, const char **argv) { NET_API_STATUS status; struct libnetapi_ctx *ctx = NULL; const char *hostname = NULL; const char *domain = NULL; uint8_t *buffer = NULL; poptContext pc; int opt; struct poptOption long_options[] = { POPT_AUTOHELP POPT_COMMON_LIBNETAPI_EXAMPLES POPT_TABLEEND }; status = libnetapi_init(&ctx); if (status != 0) { return status; } pc = poptGetContext("getdc", argc, argv, long_options, 0); poptSetOtherOptionHelp(pc, "hostname domainname"); while((opt = poptGetNextOpt(pc)) != -1) { } if (!poptPeekArg(pc)) { poptPrintHelp(pc, stderr, 0); goto out; } hostname = poptGetArg(pc); if (!poptPeekArg(pc)) { poptPrintHelp(pc, stderr, 0); goto out; } domain = poptGetArg(pc); /* NetGetDCName */ status = NetGetDCName(hostname, domain, &buffer); if (status != 0) { printf("GetDcName failed with: %s\n", libnetapi_errstr(status)); } else { printf("%s\n", (char *)buffer); } out: NetApiBufferFree(buffer); libnetapi_free(ctx); poptFreeContext(pc); return status; }
/*! @brief ユーザグループの取得 (MBCS) */ BOOL CUserInfoDlg::GetGroupNameA(char *UserName, char *dest) { WCHAR wszUserName[256]; // Unicode user name LPBYTE ComputerName = 0; // Convert ASCII user name and domain to Unicode. MultiByteToWideChar(CP_ACP, 0, UserName, strlen(UserName) + 1, wszUserName, sizeof(wszUserName) / sizeof(WCHAR)); // Get the computer name of a DC for the specified domain. BOOL bFoundDC = TRUE; DWORD nRet = NetGetDCName(NULL, NULL, &ComputerName ); if (nRet != NERR_Success) { printf("Error getting group information.\n" ); bFoundDC = FALSE; } LPLOCALGROUP_USERS_INFO_0 pBuf = NULL; DWORD dwEntriesRead = 0; DWORD dwTotalEntries = 0; // Look up the user on the DC. nRet = NetUserGetLocalGroups((LPWSTR) ComputerName, (LPWSTR) wszUserName, 0, LG_INCLUDE_INDIRECT, (LPBYTE *) &pBuf, MAX_PREFERRED_LENGTH, &dwEntriesRead, &dwTotalEntries); if (nRet != NERR_Success) { if (bFoundDC == TRUE) { NetApiBufferFree(ComputerName); } printf("Error getting group information.\n" ); return(FALSE ); } if (bFoundDC == TRUE) { NetApiBufferFree(ComputerName); } LPLOCALGROUP_USERS_INFO_0 pTmpBuf = pBuf; for (unsigned int i = 0; i < dwEntriesRead; i++) { if (pTmpBuf == NULL) { fprintf(stderr, "An access violation has occurred\n"); break; } strcat_s(dest, (GNLEN + 1) * 5, ","); char szGroupName[GNLEN + 1]; // Convert the Unicode full name to ASCII. WideCharToMultiByte(CP_ACP, 0, pTmpBuf->lgrui0_name, -1, szGroupName, GNLEN, NULL, NULL ); strcat_s(dest, (GNLEN + 1) * 5, szGroupName); pTmpBuf++; } NetApiBufferFree(pBuf); return (TRUE); }
APIERR MNetGetDCName( const TCHAR FAR * pszServer, const TCHAR FAR * pszDomain, BYTE FAR ** ppbBuffer ) { APIERR err = 0 ; err = (APIERR) NetGetDCName( (TCHAR *)pszServer, (TCHAR *)pszDomain, ppbBuffer ); return err ; } // MNetGetDCName
WORD MNetGetDCName( LPTSTR pszServer, LPTSTR pszDomain, LPBYTE * ppbBuffer ) { DWORD nRes; // return from Netapi nRes = NetGetDCName(pszServer, pszDomain, ppbBuffer); return LOWORD(nRes); }
void CShowActiveDirUsers::GetDCName(LPTSTR szDCName, LPTSTR szDomain) { NET_API_STATUS ret = 0; LPBYTE bufptr; SERVER_INFO_100* pS100; LPWSTR pServer = NULL; DWORD dwEntriesRead = 0; DWORD dwTotalEntries = 0; ret = NetGetDCName(NULL, NULL, (LPBYTE*)&pServer); if (ret == NERR_Success) { _tcscpy(szDCName, pServer); NetApiBufferFree(pServer); ret = NetGetDCName(szDCName, szDomain, (LPBYTE*)&pServer); if (ret == NERR_Success) { _tcscpy(szDCName, pServer); NetApiBufferFree(pServer); return; } return; } ret = NetServerEnum(NULL, 100, &bufptr, MAX_PREFERRED_LENGTH, &dwEntriesRead, &dwTotalEntries, SV_TYPE_DOMAIN_BAKCTRL, szDomain, 0); if (ret == NERR_Success && dwEntriesRead > 0) { pS100 = (SERVER_INFO_100*)bufptr; _tcscpy(szDCName, _T("\\\\")); _tcscat(szDCName, pS100->sv100_name); NetApiBufferFree(bufptr); return; } }
AUTHADMIN_API BOOL CUGP(char * userin,char *password,char *machine,char *groupin,int locdom) { DWORD dwLogonType; DWORD dwLogonProvider; HANDLE hToken; bool returnvalue=false; dwLogonType = LOGON32_LOGON_INTERACTIVE; dwLogonProvider = LOGON32_PROVIDER_DEFAULT; byte *buf = 0; byte *buf2 = 0; char domain[MAXLEN * sizeof(wchar_t)]; DWORD rcdomain = NetGetDCName( 0, 0, &buf ); NetApiBufferFree( buf ); printf("Logonuser: % s %s \n", userin, "."); if (LogonUser(userin, ".", password, dwLogonType, dwLogonProvider, &hToken)) if (ImpersonateLoggedOnUser(hToken)) { returnvalue=IsAdmin(); RevertToSelf(); CloseHandle(hToken); } if (returnvalue==true) return returnvalue; if (!rcdomain) { DWORD result=NetWkstaGetInfo( 0 , 100 , &buf2 ) ; if (!result) { wcstombs( domain, ((WKSTA_INFO_100_NT *) buf2)->wki100_langroup, MAXLEN ); NetApiBufferFree( buf2 ); printf("Logonuser: % s %s \n", userin, domain); if (LogonUser(userin, domain, password, dwLogonType, dwLogonProvider, &hToken)) if (ImpersonateLoggedOnUser(hToken)) { returnvalue=IsAdmin(); RevertToSelf(); CloseHandle(hToken); } } } return returnvalue; }
/*! @brief ユーザグループの取得 (Unicode) */ BOOL CUserInfoDlg::GetGroupNameW(TCHAR *UserName, TCHAR *dest) { LPBYTE ComputerName = 0; // Get the computer name of a DC for the specified domain. BOOL bFoundDC = TRUE; DWORD nRet = NetGetDCName(NULL, NULL, &ComputerName ); if (nRet != NERR_Success) { printf("Error getting group information.\n" ); bFoundDC = FALSE; } LPLOCALGROUP_USERS_INFO_0 pBuf = NULL; DWORD dwEntriesRead = 0; DWORD dwTotalEntries = 0; // Look up the user on the DC. nRet = NetUserGetLocalGroups((LPWSTR) ComputerName, (LPWSTR) UserName, 0, LG_INCLUDE_INDIRECT, (LPBYTE *) &pBuf, MAX_PREFERRED_LENGTH, &dwEntriesRead, &dwTotalEntries); if (nRet != NERR_Success) { if (bFoundDC == TRUE) { NetApiBufferFree(ComputerName); } printf("Error getting group information.\n" ); return (FALSE); } if (bFoundDC == TRUE) { NetApiBufferFree(ComputerName); } LPLOCALGROUP_USERS_INFO_0 pTmpBuf = pBuf; for (unsigned int i = 0; i <dwEntriesRead; i++) { if (pTmpBuf == NULL) { fprintf(stderr, "An access violation has occurred\n"); break; } wcscat_s(dest, (GNLEN + 1) * 5, L","); wcscat_s(dest, (GNLEN + 1) * 5, pTmpBuf->lgrui0_name); pTmpBuf++; } NetApiBufferFree(pBuf); return (TRUE); }
/*! @brief ユーザフルネームの取得 (MBCS) */ BOOL CUserInfoDlg::GetFullNameA(char *UserName, char *Domain, char *dest) { WCHAR wszUserName[256]; // Unicode user name WCHAR wszDomain[256]; LPBYTE ComputerName = 0; struct _USER_INFO_2 *ui; // User structure // Convert ASCII user name and domain to Unicode. MultiByteToWideChar(CP_ACP, 0, UserName, strlen(UserName)+1, wszUserName, sizeof(wszUserName) / sizeof(WCHAR)); MultiByteToWideChar(CP_ACP, 0, Domain, strlen(Domain)+1, wszDomain, sizeof(wszDomain) / sizeof(WCHAR) ); BOOL bFoundDC = TRUE; DWORD nRet = NetGetDCName(NULL, NULL, &ComputerName ); // Get the computer name of a DC for the specified domain. if (nRet != NERR_Success) { printf("Error getting user information.\n" ); bFoundDC = FALSE; } // Look up the user on the DC. nRet = NetUserGetInfo((LPWSTR) ComputerName, (LPWSTR) wszUserName, 2, (LPBYTE *) &ui); if (nRet != NERR_Success) { if (bFoundDC == TRUE) { NetApiBufferFree(ComputerName); } printf("Error getting user information.\n" ); return(FALSE ); } if (bFoundDC == TRUE) { NetApiBufferFree(ComputerName); } // Convert the Unicode full name to ASCII. WideCharToMultiByte(CP_ACP, 0, ui->usri2_full_name, -1, dest, 256, NULL, NULL ); return(TRUE ); }
VOID ConfigInfoUpdate( ) /*++ Routine Description: Arguments: Return Value: --*/ { BOOL InDomain = FALSE; BOOL IsPDC = FALSE; USHORT cbTotalAvail, cbBuffer; LPBYTE pbBuffer; NET_API_STATUS uRet; PSERVER_INFO_101 pServer1; DWORD ReplicationType, ReplicationTime; TCHAR pDomain[MAX_COMPUTERNAME_LENGTH + 1]; NT_PRODUCT_TYPE NtType; #if DBG if (TraceFlags & TRACE_FUNCTION_TRACE) dprintf(TEXT("LLS TRACE: ConfigInfoUpdate\n")); #endif // // Try to get a domain // lstrcpy(pDomain, TEXT("")); if ( !NTDomainGet(NULL, pDomain) ) { InDomain = TRUE; // // If we aren't a BDC/PDC then count us as a member // NtType = NtProductLanManNt; RtlGetNtProductType(&NtType); if (NtType != NtProductLanManNt) IsPDC = FALSE; else { // // Let's check if we are a PDC... // IsPDC = NTIsPDC(ConfigInfo.ComputerName); } } else { IsPDC = TRUE; InDomain = FALSE; } RtlEnterCriticalSection(&ConfigInfoLock); ConfigInfo.IsMaster = TRUE; ConfigInfo.Replicate = FALSE; // // If we are in a domain, and not the PDC then we replicate to the PDC // if (!IsPDC && InDomain) { // // Get the PDC of the domain // uRet = NetGetDCName(NULL, pDomain, &pbBuffer); if (uRet == 0) { lstrcpy(ConfigInfo.ReplicateTo, (LPWSTR) pbBuffer); NetApiBufferFree(pbBuffer); ConfigInfo.IsMaster = FALSE; ConfigInfo.Replicate = TRUE; } else { InDomain = FALSE; memset(ConfigInfo.ReplicateTo, 0, sizeof(ConfigInfo.ReplicateTo)); #if DBG dprintf(TEXT("LLS: (WARNING) NetGetDCName: 0x%lX\n"), uRet); #endif } } // // Update values from Registry // ReplicationTime = ConfigInfo.ReplicationTime; ReplicationType = ConfigInfo.ReplicationType; ConfigInfoRegistryInit( &ConfigInfo.UseEnterprise, ConfigInfo.EnterpriseServer, &ConfigInfo.ReplicationType, &ConfigInfo.ReplicationTime, &ConfigInfo.LogLevel ); // // Have all registy init'd values - now need to figure out who to // replicate to. // // If we are not in a domain or are a PDC then we can go to the // Enterprise Server. // if (IsPDC || !InDomain) { if (ConfigInfo.UseEnterprise) { ConfigInfo.IsMaster = FALSE; ConfigInfo.Replicate = TRUE; // // Make sure we have an enterprise server to go to // if ( ConfigInfo.EnterpriseServer[0] == TEXT('\0') ) { ConfigInfo.UseEnterprise = FALSE; ConfigInfo.IsMaster = TRUE; ConfigInfo.Replicate = FALSE; } else { // // Base ReplicateTo on enterprise server name // if (ConfigInfo.EnterpriseServer[0] != TEXT('\\')) lstrcpy(ConfigInfo.ReplicateTo, TEXT("\\\\")); else lstrcpy(ConfigInfo.ReplicateTo, TEXT("")); lstrcat(ConfigInfo.ReplicateTo, ConfigInfo.EnterpriseServer); } } else ConfigInfo.IsMaster = TRUE; } else ConfigInfo.UseEnterprise = FALSE; if (ConfigInfo.IsMaster == FALSE) { if ( (ConfigInfo.ReplicateTo == NULL) || (lstrlen(ConfigInfo.ReplicateTo) == 0) || ( (*ConfigInfo.ReplicateTo == TEXT('\\')) && (lstrlen(ConfigInfo.ReplicateTo) < 3) )) { ConfigInfo.IsMaster = TRUE; ConfigInfo.Replicate = FALSE; } } // // Adjust replication time if it has changed // if ((ReplicationTime != ConfigInfo.ReplicationTime) || (ReplicationType != ConfigInfo.ReplicationType)) ReplicationTimeSet(); IsMaster = ConfigInfo.IsMaster; RtlLeaveCriticalSection(&ConfigInfoLock); } // ConfigInfoUpdate
HRESULT TCUserAccount::Init(LPCWSTR szUserName) { // Not supported under Windows9x if (IsWin9x()) return S_FALSE; // Delete any previous user name m_spszUserName = NULL; // Delete any previous SID m_spSIDPrincipal = NULL; // Get the SID and domain name of the specified user RETURN_FAILED(GetSID(szUserName, &m_spSIDPrincipal, &m_spszDomainName)); // Get a pointer to just the user name (no domain) LPCWSTR pszWhack = wcschr(szUserName, L'\\'); LPCWSTR pszUserOnly = pszWhack ? pszWhack + 1 : szUserName; // Save the user name int cchUserName = wcslen(pszUserOnly) + 1; m_spszUserName = (LPWSTR)CoTaskMemAlloc(cchUserName * sizeof(WCHAR)); wcscpy(m_spszUserName, pszUserOnly); // Get the server information of the local machine TCNetApiPtr<SERVER_INFO_101*> si101; DWORD dw = NetServerGetInfo(NULL, 101, (LPBYTE*)&si101); if (NERR_Success != dw) return HRESULT_FROM_WIN32(dw); // Declare and initialize an LSA_OBJECT_ATTRIBUTES structure LSA_OBJECT_ATTRIBUTES oa = {sizeof(oa)}; // Special processing when the local computer is a backup domain controller TCNetApiPtr<WCHAR*> domainController; if (si101->sv101_type & SV_TYPE_DOMAIN_BAKCTRL) { // Get the server name of the primary domain controller TCNetApiPtr<USER_MODALS_INFO_2*> umi2; if (0 == (dw = NetUserModalsGet(NULL, 2, (LPBYTE*)&umi2))) { // Get the domain name of the primary domain controller NetGetDCName(NULL, umi2->usrmod2_domain_name, (LPBYTE*)&domainController); // Create an LSA_UNICODE_STRING for the name of the PDC LSA_UNICODE_STRING lsaPDC; lsaPDC.Length = (USHORT)((wcslen(domainController) * sizeof(WCHAR))-2); lsaPDC.MaximumLength = (USHORT)(lsaPDC.Length + sizeof(WCHAR)); lsaPDC.Buffer = &domainController[2]; // Open the policy of the primary domain controller RETURN_FAILED(LsaOpenPolicy(&lsaPDC, &oa, POLICY_CREATE_ACCOUNT | POLICY_LOOKUP_NAMES, &m_hPolicy)); } } // Open the policy of the local computer if not a BDC or if anything failed if (domainController.IsNull()) { RETURN_FAILED(LsaOpenPolicy(NULL, &oa, POLICY_CREATE_ACCOUNT | POLICY_LOOKUP_NAMES, &m_hPolicy)); } // Indicate success return S_OK; }
// Get user name e.g. Julian Smart bool wxGetUserName(wxChar *buf, int maxSize) { wxCHECK_MSG( buf && ( maxSize > 0 ), false, _T("empty buffer in wxGetUserName") ); #if defined(__WXWINCE__) wxLogNull noLog; wxRegKey key(wxRegKey::HKCU, wxT("ControlPanel\\Owner")); if(!key.Open(wxRegKey::Read)) return false; wxString name; if(!key.QueryValue(wxT("Owner"),name)) return false; wxStrncpy(buf, name.c_str(), maxSize-1); buf[maxSize-1] = _T('\0'); return true; #elif defined(USE_NET_API) CHAR szUserName[256]; if ( !wxGetUserId(szUserName, WXSIZEOF(szUserName)) ) return false; // TODO how to get the domain name? CHAR *szDomain = ""; // the code is based on the MSDN example (also see KB article Q119670) WCHAR wszUserName[256]; // Unicode user name WCHAR wszDomain[256]; LPBYTE ComputerName; USER_INFO_2 *ui2; // User structure // Convert ANSI user name and domain to Unicode MultiByteToWideChar( CP_ACP, 0, szUserName, strlen(szUserName)+1, wszUserName, WXSIZEOF(wszUserName) ); MultiByteToWideChar( CP_ACP, 0, szDomain, strlen(szDomain)+1, wszDomain, WXSIZEOF(wszDomain) ); // Get the computer name of a DC for the domain. if ( NetGetDCName( NULL, wszDomain, &ComputerName ) != NERR_Success ) { wxLogError(wxT("Can not find domain controller")); goto error; } // Look up the user on the DC NET_API_STATUS status = NetUserGetInfo( (LPWSTR)ComputerName, (LPWSTR)&wszUserName, 2, // level - we want USER_INFO_2 (LPBYTE *) &ui2 ); switch ( status ) { case NERR_Success: // ok break; case NERR_InvalidComputer: wxLogError(wxT("Invalid domain controller name.")); goto error; case NERR_UserNotFound: wxLogError(wxT("Invalid user name '%s'."), szUserName); goto error; default: wxLogSysError(wxT("Can't get information about user")); goto error; } // Convert the Unicode full name to ANSI WideCharToMultiByte( CP_ACP, 0, ui2->usri2_full_name, -1, buf, maxSize, NULL, NULL ); return true; error: wxLogError(wxT("Couldn't look up full user name.")); return false; #else // !USE_NET_API // Could use NIS, MS-Mail or other site specific programs // Use wxWidgets configuration data bool ok = GetProfileString(WX_SECTION, eUSERNAME, wxEmptyString, buf, maxSize - 1) != 0; if ( !ok ) { ok = wxGetUserId(buf, maxSize); } if ( !ok ) { wxStrncpy(buf, wxT("Unknown User"), maxSize); } return true; #endif // Win32/16 }
/** * @brief * add_service_account: creates the PBS service account if it doesn't exist, * otherwise, validate the password against the existing the service * account. * * @param[in] password - The password to be validated. * * @return int */ int add_service_account(char *password) { char dname[PBS_MAXHOSTNAME+1] = {'\0'}; char dctrl[PBS_MAXHOSTNAME+1] = {'\0'}; wchar_t unamew[UNLEN+1] = {L'\0'}; wchar_t dnamew[UNLEN+1] = {L'\0'}; wchar_t dctrlw[PBS_MAXHOSTNAME+1] = {L'\0'}; LPWSTR dcw = NULL; char dctrl_buf[PBS_MAXHOSTNAME+1] = {'\0'}; NET_API_STATUS nstatus = 0; USER_INFO_1 *ui1_ptr = NULL; /* better indicator of lookup */ /* permission */ struct passwd *pw = NULL; char sa_name[PBS_MAXHOSTNAME+UNLEN+2] = {'\0'}; /* service account fullname */ /* domain\user\0 */ int ret_val = 0; int in_domain_environment = 0; USER_INFO_1 ui = {0}; wchar_t passwordw[LM20_PWLEN+1] = {L'\0'}; /* find domain name, group name to add service account to */ in_domain_environment = GetComputerDomainName(dname); strcpy(dctrl, dname); if (in_domain_environment) { char dname_a[PBS_MAXHOSTNAME+1] = {'\0'}; get_dcinfo(dname, dname_a, dctrl); } mbstowcs(unamew, service_accountname, UNLEN+1); mbstowcs(dnamew, dname, PBS_MAXHOSTNAME+1); mbstowcs(dctrlw, dctrl, PBS_MAXHOSTNAME+1); if (in_domain_environment && dctrlw[0] == '\0' ) { if (NERR_Success == NetGetDCName(NULL, dnamew, (LPBYTE *)&dcw)) { wcstombs(dctrl_buf, dcw, PBS_MAXHOSTNAME + 1); mbstowcs(dctrlw, dctrl_buf, PBS_MAXHOSTNAME + 1); } else { fprintf(stderr, "Failed to fetch domain controller name"); goto end_add_service_account; } } /* create account if it doesn't exist */ /* FIX: Perform the following "if action" if either */ /* 1) in a domain environment, and the */ /* executing account (i.e. intaller) is an account in */ /* the domain, */ /* 2) in a standalone environment, and the */ /* executing account (i.e. installer) is a local account */ /* in the local computer. */ /* This fix is needed as during testing, I was finding that */ /* the local "Administrator" account itself has permission */ /* to query the domain, and to create accounts on the domain. */ /* However, the created domain "pbsadmin" account would have */ /* weirdness to it in that attempts to impersonate it would */ /* initially fail, and even after adding the account to the */ /* local "Administrators" group, that user entry on the group */ /* would suddenly disappear. */ if ((stricmp(exec_dname, dname) == 0) && ((nstatus=wrap_NetUserGetInfo(dctrlw, unamew, 1, (LPBYTE *)&ui1_ptr)) == NERR_UserNotFound)) { mbstowcs(passwordw, password, LM20_PWLEN+1); ui.usri1_name = (wchar_t *)unamew; ui.usri1_password = (wchar_t *)passwordw; ui.usri1_password_age = 0; ui.usri1_priv = USER_PRIV_USER; ui.usri1_home_dir = NULL; ui.usri1_comment = NULL; ui.usri1_flags = UF_PASSWD_CANT_CHANGE|UF_DONT_EXPIRE_PASSWD; ui.usri1_script_path = NULL; if (for_info_only) nstatus = NERR_Success; else nstatus=NetUserAdd(dctrlw, 1, (LPBYTE)&ui, NULL); if ((nstatus != NERR_Success) && (nstatus != NERR_UserExists)) { fprintf(stderr, "Failed to create %s\\%S: error status=%d\n", dname, unamew, nstatus); goto end_add_service_account; } printf("%s account %s\\%S\n", (for_info_only?"Creating":"Created"), dname, unamew); set_account_expiration(dnamew, dctrlw, unamew, TIMEQ_FOREVER); /* cache new token since the account was just created */ cache_usertoken_and_homedir(service_accountname, NULL, 0, read_sa_password, (char *)service_accountname, decrypt_sa_password, 1); if (add_to_administrators_group(dnamew, unamew) != 0) goto end_add_service_account; } /* Verify password */ if (pw == NULL) { pw = getpwnam(service_accountname); if (pw == NULL) { fprintf(stderr, "Password could not be validated against %s\\%s.\n", dname, service_accountname); goto end_add_service_account; } } /* validate password */ sprintf(sa_name, "%s\\%s", dname, service_accountname); if (!for_info_only) { if (pw->pw_userlogin != INVALID_HANDLE_VALUE) { if (ImpersonateLoggedOnUser(pw->pw_userlogin) == 0) { /* fail */ if (validate_account_password(sa_name, password) == 0) { /* we still call validate_account_password() as backup since */ /* under Windows 2000, LogonUser(), called from */ /* cache_usertoken_and_homedir(), might fail due to not */ /* having the SE_TCB_NAME privilege. This must be */ /* already set before calling the "cmd" process that */ /* executes the install program. */ fprintf(stderr, "Password did not validate against %s\\%s err=%d\n\nClick BACK button to retry a different password.\nClick NEXT button to abort installation.", dname, service_accountname, GetLastError()); goto end_add_service_account; } } else { printf("Validated password for %s\n", sa_name); RevertToSelf(); } } } else { printf("Validating password for %s\n", sa_name); } /* add service account to appropriate Admin group */ if (!for_info_only && !isLocalAdminMember(service_accountname)) { if (add_to_administrators_group(dnamew, unamew) != 0) goto end_add_service_account; } wcsset(passwordw, 0); ret_val = 1; if (for_info_only) { printf("%s will need the following privileges:\n", sa_name); printf("\n\tCreate Token Object\n"); printf("\n\tReplace Process Level Token\n"); printf("\n\tLogon On As a Service\n"); printf("\n\tAct As Part of the Operating System\n"); } end_add_service_account: if (ui1_ptr != NULL) NetApiBufferFree(ui1_ptr); return (ret_val); }
Boolean System::isPrivilegedUser(const String& userName) { Boolean isPrivileged = false; char mUserName[UNLEN+1]; char mDomainName[UNLEN+1]; wchar_t wUserName[UNLEN+1]; wchar_t wDomainName[UNLEN+1]; char* pbs; char userStr[UNLEN+1]; bool usingDomain = false; LPBYTE pComputerName=NULL; DWORD dwLevel = 1; LPUSER_INFO_1 pUserInfo = NULL; NET_API_STATUS nStatus = NULL; //get the username in the correct format strcpy(userStr, (const char*)userName.getCString()); //separate the domain and user name if both are present. if (NULL != (pbs = strchr(userStr, '\\'))) { *pbs = '\0'; strcpy(mDomainName, userStr); strcpy(mUserName, pbs+1); usingDomain = true; } else if ((NULL != (pbs = (strchr(userStr, '@')))) || (NULL != (pbs = (strchr(userStr, '.'))))) { *pbs = '\0'; strcpy(mDomainName, pbs+1); strcpy(mUserName, userStr); usingDomain = true; } else { strcpy(mDomainName, "."); strcpy(mUserName, userStr); } //convert domain name to unicode if (!MultiByteToWideChar( CP_ACP, 0, mDomainName, -1, wDomainName, (int)(strlen(mDomainName) + 1))) { return false; } //convert username to unicode if (!MultiByteToWideChar( CP_ACP, 0, mUserName, -1, wUserName, (int)(strlen(mUserName) + 1))) { return false; } if (usingDomain) { //get domain controller DWORD rc = NetGetDCName(NULL, wDomainName, &pComputerName); if (rc == NERR_Success) { // this is automatically prefixed with "\\" wcscpy(wDomainName, (LPWSTR) pComputerName); } /* else { // failover // ATTN: This is commented out until there is resolution on // Bugzilla 2236. -hns 2/2005 // This needs to be more thoroughly tested when we uncomment it out. PDOMAIN_CONTROLLER_INFO DomainControllerInfo = NULL; //this function does not take wide strings rc = DsGetDcName(NULL, mDomainName, NULL, NULL, // not sure what flags we want here DS_DIRECTORY_SERVICE_REQUIRED, &DomainControllerInfo); if (rc == ERROR_SUCCESS && DomainControllerInfo) { strcpy(mDomainName, DomainControllerInfo->DomainName); NetApiBufferFree(DomainControllerInfo); if (!MultiByteToWideChar( CP_ACP, 0, mDomainName, -1, wDomainName, strlen(mDomainName) + 1)) { return false; } } } */ } //get privileges nStatus = NetUserGetInfo(wDomainName, wUserName, dwLevel, (LPBYTE *)&pUserInfo); if ((nStatus == NERR_Success) && (pUserInfo != NULL) && (pUserInfo->usri1_priv == USER_PRIV_ADMIN)) { isPrivileged = true; } if (pComputerName != NULL) { NetApiBufferFree(pComputerName); } if (pUserInfo != NULL) { NetApiBufferFree(pUserInfo); } return isPrivileged; }
Boolean System::isSystemUser(const char* userName) { if (processUserName.size() == 0) { // Lock and recheck the processUserName length in case two threads // enter this block simultaneously AutoMutex mut(processUserNameMut); if (processUserName.size() == 0) { processUserName = getEffectiveUserName(); } } if (processUserName == userName) { return true; } Boolean isSystemUser = false; char mUserName[UNLEN+1]; char mDomainName[UNLEN+1]; char tUserName[UNLEN+1]; wchar_t wUserName[UNLEN+1]; wchar_t wDomainName[UNLEN+1]; char* pbs; bool usingDomain = false; LPBYTE pComputerName=NULL; DWORD dwLevel = 1; LPUSER_INFO_1 pUserInfo = NULL; NET_API_STATUS nStatus = NULL; // Make a copy of the specified username, it cannot be used directly // because it's declared as const and strchr() may modify the string. strncpy(tUserName, userName, sizeof(tUserName) - 1); tUserName[sizeof(tUserName)- 1] = '\0'; //separate the domain and user name if both are present. if (NULL != (pbs = strchr(tUserName, '\\'))) { *pbs = '\0'; strcpy(mDomainName, tUserName); strcpy(mUserName, pbs+1); usingDomain = true; } else if ((NULL != (pbs = (strchr(tUserName, '@')))) || (NULL != (pbs = (strchr(tUserName, '.'))))) { *pbs = '\0'; strcpy(mDomainName, pbs+1); strcpy(mUserName, tUserName); usingDomain = true; } else { strcpy(mDomainName, "."); strcpy(mUserName, tUserName); } //convert domain name to unicode if (!MultiByteToWideChar( CP_ACP, 0, mDomainName, -1, wDomainName, (int)(strlen(mDomainName) + 1))) { return false; } //convert username to unicode if (!MultiByteToWideChar( CP_ACP, 0, mUserName, -1, wUserName, (int)(strlen(mUserName) + 1))) { return false; } if (usingDomain) { //get domain controller DWORD rc = NetGetDCName(NULL, wDomainName, &pComputerName); if (rc == NERR_Success) { // this is automatically prefixed with "\\" wcscpy(wDomainName, (LPWSTR) pComputerName); } /* else { // failover // ATTN: This is commented out until there is resolution on // Bugzilla 2236. -hns 2/2005 // This needs to be more thoroughly tested when we uncomment it out. PDOMAIN_CONTROLLER_INFO DomainControllerInfo = NULL; //this function does not take wide strings rc = DsGetDcName(NULL, mDomainName, NULL, NULL, //not sure what flags we want here DS_DIRECTORY_SERVICE_REQUIRED, &DomainControllerInfo); if (rc == ERROR_SUCCESS && DomainControllerInfo) { strcpy(mDomainName, DomainControllerInfo->DomainName); NetApiBufferFree(DomainControllerInfo); if (!MultiByteToWideChar( CP_ACP, 0, mDomainName, -1, wDomainName, strlen(mDomainName) + 1)) { return false; } } } */ } //get user info nStatus = NetUserGetInfo(wDomainName, wUserName, dwLevel, (LPBYTE *)&pUserInfo); if (nStatus == NERR_Success) { isSystemUser = true; } if (pComputerName != NULL) { NetApiBufferFree(pComputerName); } if (pUserInfo != NULL) { NetApiBufferFree(pUserInfo); } return isSystemUser; }
// // Determines if user is a member of the global group group_name on domain group_domain // // 1 = yes, 0 = no, -1 = error // int perm::userInGlobalGroup( const char *account, const char *domain, const char* group_name, const char* group_domain ) { dprintf(D_FULLDEBUG,"in perm::processGlobalGroupTrustee() looking at group '%s\\%s'\n", (group_domain) ? group_domain : "NULL", (group_name) ? group_name : "NULL" ); unsigned char* BufPtr; // buffer pointer wchar_t group_domain_unicode[MAX_DOMAIN_LENGTH+1]; // computer names restricted to 254 chars wchar_t group_name_unicode[MAX_GROUP_LENGTH+1]; // groups limited to 256 chars _snwprintf(group_domain_unicode, MAX_DOMAIN_LENGTH+1, L"%S", group_domain); _snwprintf(group_name_unicode, MAX_GROUP_LENGTH+1, L"%S", group_name); GROUP_USERS_INFO_0 *group_members; unsigned long entries_read, total_entries; NET_API_STATUS status; // get domain controller name for the domain in question status = NetGetDCName( NULL, // servername group_domain_unicode, // domain to lookup &BufPtr // pointer to buffer containing the name (Unicode string) of the Domain Controller ); if (status == NERR_DCNotFound ) { dprintf(D_ALWAYS, "perm::NetGetDCName() failed: DCNotFound (domain looked up: %s)\n", group_domain); NetApiBufferFree( BufPtr ); return -1; } else if ( status == ERROR_INVALID_NAME ) { dprintf(D_ALWAYS, "perm::NetGetDCName() failed: Error Invalid Name (domain looked up: %s)", group_domain); NetApiBufferFree( BufPtr ); return -1; } wchar_t* DomainController = (wchar_t*) BufPtr; do { status = NetGroupGetUsers( DomainController, // domain controller name group_name_unicode, // domain to query 0, // level of info &BufPtr, // pointer to buffer containing group members 16384, // preferred size of buffer &entries_read, // # entries read &total_entries, // total # of entries NULL // resume pointer ); group_members = (GROUP_USERS_INFO_0*) BufPtr; switch ( status ) { case NERR_Success: case ERROR_MORE_DATA: break; case ERROR_ACCESS_DENIED: case NERR_InvalidComputer: case NERR_GroupNotFound: char* DCname = new char[ wcslen( DomainController )+1 ]; wsprintf(DCname, "%ws", DomainController); dprintf(D_ALWAYS, "perm::NetGroupGetUsers failed: (domain: %s, domain controller: %s, total entries: %d, entries read: %d, err=%d)", group_domain, DCname, total_entries, entries_read, GetLastError()); delete[] DCname; NetApiBufferFree( BufPtr ); NetApiBufferFree( DomainController ); return -1; } DWORD i; for ( i = 0; i < entries_read; i++ ) { char t_name[MAX_ACCOUNT_LENGTH+1]; // account names are restricted to 20 chars, but I'm // gonna be safe and say 256. snprintf(t_name, MAX_ACCOUNT_LENGTH+1, "%S", group_members[i].grui0_name); dprintf(D_FULLDEBUG, "GlobalGroupMember: %s\n", t_name); //getDomainAndName( t_str, t_domain, t_name); if ( domainAndNameMatch( account, t_name, domain, group_domain ) ) { //delete[] t_str; NetApiBufferFree( BufPtr ); NetApiBufferFree( DomainController ); return 1; } } }while ( status == ERROR_MORE_DATA ); // loop if there's more group members to look at // exiting the for loop means we didn't find anything NetApiBufferFree( BufPtr ); NetApiBufferFree( DomainController ); return 0; }
DWORD BreakNameIntoParts(LPCTSTR name, LPWSTR w_name, LPWSTR w_domain, LPWSTR w_pdc) { static wchar_t *pw_pdc; const TCHAR *ptr; wchar_t w_defaultdomain[DNLEN+1]= {0}; int is_domain = isDomainMember(w_defaultdomain); #ifdef TRACE if(is_domain) TRACE(3,"Machine is domain member"); else TRACE(3,"Machine is standalone"); #endif ptr=_tcschr(name, '\\'); if (ptr) { #ifdef _UNICODE _tcscpy(w_name,ptr+1); _tcsncpy(w_domain,name,ptr-name); w_domain[ptr-name]='\0'; #else w_name[MultiByteToWideChar(CP_ACP,0,ptr+1,-1,w_name,UNLEN+1)]='\0'; w_domain[MultiByteToWideChar(CP_ACP,0,name,ptr-name,w_domain,DNLEN)]='\0'; #endif } else { #ifdef _UNICODE _tcscpy(w_name,name); #else w_name[MultiByteToWideChar(CP_ACP,0,name,-1,w_name,UNLEN+1)]='\0'; #endif if(is_domain) wcscpy(w_domain,w_defaultdomain); else *w_domain='\0'; } if(w_pdc) { typedef DWORD (WINAPI *DsGetDcNameW_t)(LPCWSTR ComputerName,LPCWSTR DomainName,GUID *DomainGuid,LPCWSTR SiteName,ULONG Flags,PDOMAIN_CONTROLLER_INFOW *DomainControllerInfo); DsGetDcNameW_t pDsGetDcNameW; pDsGetDcNameW=(DsGetDcNameW_t)GetProcAddress(GetModuleHandle(_T("netapi32")),"DsGetDcNameW"); w_pdc[0]='\0'; if(w_domain[0] && pDsGetDcNameW) { PDOMAIN_CONTROLLER_INFOW pdi; if(!pDsGetDcNameW(NULL,w_domain,NULL,NULL,DS_IS_FLAT_NAME,&pdi) || !pDsGetDcNameW(NULL,w_domain,NULL,NULL,DS_IS_DNS_NAME,&pdi)) { wcscpy(w_pdc,pdi->DomainControllerName); NetApiBufferFree(pdi); } } else if(w_domain[0]) { if(!NetGetAnyDCName(NULL,w_domain,(LPBYTE*)&pw_pdc) || !NetGetDCName(NULL,w_domain,(LPBYTE*)&pw_pdc)) { wcscpy(w_pdc,pw_pdc); NetApiBufferFree(pw_pdc); } } #ifdef TRACE TRACE(3,"Authenticating server: %S",w_pdc[0]?w_pdc:L"(local)"); #endif } return ERROR_SUCCESS; }
BOOL CSettingsPage::OnInitDialog() { int t; BYTE buf[_MAX_PATH*sizeof(TCHAR)]; DWORD bufLen; DWORD dwType; CWaitCursor wait; CTooltipPropertyPage::OnInitDialog(); SetDlgItemInt(IDC_PSERVERPORT,(t=QueryDword(_T("PServerPort")))>=0?t:2401,FALSE); bufLen=sizeof(buf); if(RegQueryValueEx(g_hServerKey,_T("LockServer"),NULL,&dwType,buf,&bufLen)) { SetDlgItemText(IDC_LOCKSERVER,_T("localhost")); SetDlgItemInt(IDC_LOCKSERVERPORT,(t=QueryDword(_T("LockServerPort")))>=0?t:2402,FALSE); } else { RegDeleteValue(g_hServerKey,_T("LockServerPort")); TCHAR *p=_tcschr((TCHAR*)buf,':'); if(p) *p='\0'; m_edLockServer.SetWindowText((LPCTSTR)buf); SetDlgItemInt(IDC_LOCKSERVERPORT,p?_tstoi(p+1):2402,FALSE); } if(!RegQueryValueEx(g_hServerKey,_T("AnonymousUsername"),NULL,&dwType,buf,&bufLen)) m_edAnonUser.SetWindowText((TCHAR*)buf); SendDlgItemMessage(IDC_PSERVERPORT,EM_LIMITTEXT,4); SendDlgItemMessage(IDC_LOCKSERVERPORT,EM_LIMITTEXT,4); m_sbServerPort.SetRange32(1,65535); m_sbLockPort.SetRange32(1,65535); bufLen=sizeof(buf); if(RegQueryValueEx(g_hServerKey,_T("TempDir"),NULL,&dwType,buf,&bufLen) && SHRegGetUSValue(_T("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"),_T("TEMP"),NULL,(LPVOID)buf,&bufLen,TRUE,NULL,0) && !GetEnvironmentVariable(_T("TEMP"),(LPTSTR)buf,sizeof(buf)) && !GetEnvironmentVariable(_T("TMP"),(LPTSTR)buf,sizeof(buf))) { // Not set *buf='\0'; } m_edTempDir.SetWindowText((LPCTSTR)buf); m_cbEncryption.ResetContent(); m_cbEncryption.SetItemData(m_cbEncryption.AddString(_T("Optional")),0); m_cbEncryption.SetItemData(m_cbEncryption.AddString(_T("Request Authentication")),1); m_cbEncryption.SetItemData(m_cbEncryption.AddString(_T("Request Encryption")),2); m_cbEncryption.SetItemData(m_cbEncryption.AddString(_T("Require Authentication")),3); m_cbEncryption.SetItemData(m_cbEncryption.AddString(_T("Require Encryption")),4); m_cbCompression.ResetContent(); m_cbCompression.SetItemData(m_cbCompression.AddString(_T("Optional")),0); m_cbCompression.SetItemData(m_cbCompression.AddString(_T("Request Compression")),1); m_cbCompression.SetItemData(m_cbCompression.AddString(_T("Require Compression")),2); m_cbEncryption.SetCurSel((t=QueryDword(_T("EncryptionLevel")))>=0?t:0); m_cbCompression.SetCurSel((t=QueryDword(_T("CompressionLevel")))>=0?t:0); /* Migrate the old setting */ if((t=QueryDword(_T("DontUseDomain")))>=0) { if(t) { /* If dont use domain is set, force domain to computer name */ /* The server will automatically pick up the domain otherwise */ bufLen=sizeof(buf); GetComputerName((LPTSTR)buf,&bufLen); RegSetValueEx(g_hServerKey,_T("DefaultDomain"),0,REG_SZ,(BYTE*)buf,_tcslen((LPCTSTR)buf)); } RegDeleteValue(g_hServerKey,_T("DontUseDomain")); if(g_bPrivileged) GetParent()->PostMessage(PSM_CHANGED, (WPARAM)m_hWnd); /* SetModified happens too early */ } m_cbDefaultDomain.ResetContent(); DWORD dwLen = sizeof(mw_computer)/sizeof(mw_computer[0]); m_cbDefaultDomain.AddString(_T("(default)")); GetComputerName(mw_computer,&dwLen); m_cbDefaultDomain.AddString(mw_computer); if(isDomainMember(mw_domain)) { LPWSTR pw_pdc; m_cbDefaultDomain.AddString(mw_domain); if(!NetGetAnyDCName(NULL,mw_domain,(LPBYTE*)&pw_pdc) || !NetGetDCName(NULL,mw_domain,(LPBYTE*)&pw_pdc)) { wcscpy(mw_pdc,pw_pdc); NetApiBufferFree(pw_pdc); } } CString szDefaultDomain = QueryString(_T("DefaultDomain")); int n = m_cbDefaultDomain.FindStringExact(-1,szDefaultDomain); m_cbDefaultDomain.SetCurSel(n>0?n:0); m_cbRunAsUser.ResetContent(); m_cbRunAsUser.AddString(_T("(client user)")); CString usr = QueryString(_T("RunAsUser")); if(!usr.GetLength()) m_cbRunAsUser.SetCurSel(0); else m_cbRunAsUser.SetCurSel(m_cbRunAsUser.AddString(usr)); if(!g_bPrivileged) { m_edTempDir.EnableWindow(FALSE); m_edLockServer.EnableWindow(FALSE); m_cbEncryption.EnableWindow(FALSE); m_cbCompression.EnableWindow(FALSE); m_sbServerPort.EnableWindow(FALSE); m_sbLockPort.EnableWindow(FALSE); m_cbDefaultDomain.EnableWindow(FALSE); m_cbRunAsUser.EnableWindow(FALSE); m_edAnonUser.EnableWindow(FALSE); ::EnableWindow(*GetDlgItem(IDC_CHANGETEMP),FALSE); ::EnableWindow(*GetDlgItem(IDC_LOCKSERVERPORT),FALSE); ::EnableWindow(*GetDlgItem(IDC_PSERVERPORT),FALSE); } return TRUE; }