public int Compare(string x, string y) { x = x ?? ""; y = y ?? ""; return(Shlwapi.StrCmpLogicalW(x, y)); }
public override IEnumerable <CommandDTOBase?> Execute(string[] args) { if (String.IsNullOrEmpty(ThisRunTime.ComputerName) && Shlwapi.IsWindowsServer()) { WriteHost("Cannot enumerate antivirus. root\\SecurityCenter2 WMI namespace is not available on Windows Servers"); yield break; } // lists installed VA products via WMI (the AntiVirusProduct class) var AVResults = new List <AntiVirusDTO>(); try { var wmiData = ThisRunTime.GetManagementObjectSearcher(@"root\SecurityCenter2", "SELECT * FROM AntiVirusProduct"); var data = wmiData.Get(); foreach (var virusChecker in data) { AVResults.Add(new AntiVirusDTO( virusChecker["displayName"], virusChecker["pathToSignedProductExe"], virusChecker["pathToSignedReportingExe"] )); } } catch { } foreach (var AVResult in AVResults) { yield return(AVResult); } }
/// <summary> /// For a file extension (with leading period) and a verb (or null for default /// verb), returns the (full?) path to the executable file that is assigned to /// that extension/verb. Returns null if an error occurs. /// </summary> public static string GetExecutablePath(string extension, string verb) { int capacity = 270; attempt: // we may need to retry with a different (larger) value for "capacity" StringBuilder buffer = new StringBuilder(capacity); // the buffer that will hold the result int hresult = Shlwapi.AssocQueryString(ASSOCF.NOTRUNCATE, ASSOCSTR.EXECUTABLE, extension, verb, buffer, ref capacity); switch (hresult) { case HRESULT.S_OK: return(buffer.ToString()); // success; return the path // failure; buffer was too small case HRESULT.E_POINTER: case HRESULT.S_FALSE: // the capacity variable now holds the number of chars necessary (AssocQueryString // assigns it). it should work if we try again. goto attempt; // failure. the default case will catch all, but I'm explicitly // calling out the two failure codes I know about in case we need // them someday. case HRESULT.E_INVALIDARG: case HRESULT.E_FAILED: default: return(null); } }
/// <summary> /// Create a valid url from a file path /// </summary> /// <param name="path">file path</param> /// <returns>valid url</returns> public static string CreateUrlFromPath(string path) { return(SafeToAbsoluteUri(new Uri(path))); #if FALSE // This is the old implementation which exposes problems with URL encoded characters in paths. // (such as c:\temp\232323232%7Ffp%3A%3C%3Dot%3E2378%3D664%3D88%3B%3DXROQDF%3E2323%3A77%3B9%3B537ot1lsi.gif) // // It was replaced with the above implementation to address this type of bug, (bug #608613) // The only downside of using the Uri above is that it doesn't handle UNC paths of the form: // \\?\UNC\... // allocate buffer to hold url uint bufferSize = 4096; StringBuilder buffer = new StringBuilder(Convert.ToInt32(bufferSize)); // normalize the url int result = Shlwapi.UrlCreateFromPath(path, buffer, ref bufferSize, 0); // successfully converted if (result == HRESULT.S_OK) { // return URL converted to a .NET URL encoded value string url = buffer.ToString(); url = ShlwapiFileUrlToDotnetEncodedUrl(url); //fixes bug 47859 try { if (new FileInfo(path).FullName != new FileInfo(new Uri(url).LocalPath).FullName) { Trace.Fail("Possible bug encoding/decoding path: " + path); } } catch (Exception ex) { Trace.Fail("Exception while checking path encoding. Original path: " + path + " url from Shlwapi: " + url); throw ex; } return(url); } // didn't need conversion else if (result == HRESULT.S_FALSE) { // docs say that even if we don't need conversion it will // copy the buffer we passed it to the result Debug.Assert(path.Equals(buffer.ToString())); // return start url return(path); } // unxpected error occurred! else { throw new COMException("Error calling UrlCreateFromPath for path " + path, result); } #endif }
protected override void OnLoad(EventArgs e) { // call base base.OnLoad(e); using (new AutoGrow(this, AnchorStyles.Right, true)) { LayoutHelper.EqualizeButtonWidthsVert(AnchorStyles.Left, btnOK.Width, int.MaxValue, btnOK, btnCancel, buttonAdvanced); } // install auto-complete on the address text box int result = Shlwapi.SHAutoComplete(txtURL.Handle, SHACF.URLALL | SHACF.AUTOSUGGEST_FORCE_ON); // ensure we installed it successfully (if we didn't, no biggie -- the user will // just not get autocomplete support) Debug.Assert(result == HRESULT.S_OK, "Unexpected failure to install AutoComplete"); // prepopulate the text box w/ http prefix and move the cursor to the end if (txtURL.Text == String.Empty) { txtURL.Text = HTTP_PREFIX; } txtText.Focus(); if (!string.IsNullOrEmpty(comboBoxRel.Rel) || !string.IsNullOrEmpty(txtTitle.Text)) { RefreshAdvancedState(true); } }
/// <summary> /// Combines a basepath and relative path to create a complete URL. /// Note: this utility provides workarounds to problems with Shlwapi.UrlCombine() /// </summary> public static string UrlCombine(string baseUrl, string relativeUrl) { //bug fix: Shlwapi.UrlCombine() fails with combining paths for mhtml:file:// URLs if (!baseUrl.StartsWith("mhtml:file://", StringComparison.OrdinalIgnoreCase)) { // UrlCombine is escaping the urls, which means if the URL is already escaped, it is being // double escaped. if (IsUrl(baseUrl)) { baseUrl = HttpUtility.UrlDecode(baseUrl); } relativeUrl = Shlwapi.UrlCombine( baseUrl, relativeUrl); } else { while (relativeUrl.StartsWith("/", StringComparison.OrdinalIgnoreCase)) { relativeUrl = relativeUrl.Substring(1); } if (baseUrl.IndexOf("!", StringComparison.OrdinalIgnoreCase) > -1) { baseUrl = baseUrl.Split('!')[0]; } relativeUrl = String.Format(CultureInfo.InvariantCulture, "{0}!{1}", baseUrl, relativeUrl); } return(relativeUrl); }
public static string GetIndirectResourceString(string fullName, string packageName, string resource) { var resUri = new Uri(resource); var resourceString = string.Empty; if (resource.StartsWith("ms-resource://")) { resourceString = $"@{{{fullName}? {resource}}}"; } else if (resource.Contains('/')) { resourceString = $"@{{{fullName}? ms-resource://{packageName}/{resource.Replace("ms-resource:", "").Trim('/')}}}"; } else { resourceString = $"@{{{fullName}? ms-resource://{packageName}/resources/{resUri.Segments.Last()}}}"; } var sb = new StringBuilder(1024); var result = Shlwapi.SHLoadIndirectString(resourceString, sb, sb.Capacity, IntPtr.Zero); if (result == 0) { return(sb.ToString()); } resourceString = $"@{{{fullName}? ms-resource://{packageName}/{resUri.Segments.Last()}}}"; result = Shlwapi.SHLoadIndirectString(resourceString, sb, sb.Capacity, IntPtr.Zero); if (result == 0) { return(sb.ToString()); } return(string.Empty); }
private Uri FileUriFromPathInternal(string path) { const string device = @"\\"; path = extendedRegex.Replace(path, device); var match = prefixRegex.Match(path); string share; if (match.Success) { share = match.Groups[1].Value; if (!share.Equals("localhost", StringComparison.OrdinalIgnoreCase)) { string local = match.Groups[2].Value; path = device + local; } } else { share = null; } string uri = Shlwapi.UrlCreateFromPath(path); if (uri == null) { throw new ArgumentException("Argument is not a valid path.", "path"); } if (share != null && share.Equals("localhost", StringComparison.OrdinalIgnoreCase)) { uri = filePrefixRegex.Replace(uri, "file://" + share + "/"); } return(new Uri(uri)); }
/// <summary> /// インデックス一覧をファイルに保存 /// </summary> public void Save() { StreamWriter sw = null; try { sw = new StreamWriter(fileName, false, TwinDll.DefaultEncoding); foreach (ThreadHeader header in items) { if (ThreadIndexer.Exists(cache, header)) { // 相対パスに変換 string relative = Shlwapi.GetRelativePath( Application.StartupPath, cache.GetIndexPath(header)); sw.WriteLine(relative); } } } finally { if (sw != null) { sw.Close(); } } }
/// <summary> /// 获取显示名称 /// </summary> public static string GetNameByIShell(IShellFolder Root, IntPtr pidlSub) { IntPtr strr = Marshal.AllocCoTaskMem(MAX_PATH * 2 + 4); Marshal.WriteInt32(strr, 0, 0); StringBuilder buf = new StringBuilder(MAX_PATH); Root.GetDisplayNameOf(pidlSub, SHGNO.INFOLDER, strr); Shlwapi.StrRetToBuf(strr, pidlSub, buf, MAX_PATH); return(buf.ToString()); }
public static string ToFileSizeString(ulong size) { try { return(Shlwapi.StrFormatByteSizeEx(size, SFBSFlags.TruncateUndisplayedDecimalDigits)); } catch (Exception ex) { Logger.LogError(ex); return(Files.SizeSuffix((long)size)); } }
private static string GetPackageDisplayName(Package package) { using (var key = Registry.ClassesRoot.OpenSubKey( @"Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel" + $@"\Repository\Packages\{package.Id.FullName}\App\Capabilities")) { var sb = new StringBuilder(256); Shlwapi.SHLoadIndirectString((string)key.GetValue("ApplicationName"), sb, sb.Capacity, IntPtr.Zero); return(sb.ToString()); } }
private static string?GetFFmpegAbsolutePathFromEnvVar() { var sb = new StringBuilder(Shlwapi.MAX_PATH); sb.Append(FFmpegExecutable); var res = Shlwapi.PathFindOnPath(sb, null); var p = sb.ToString(); return(res && File.Exists(p) ? p : null); }
public int Compare(string x, string y) { var emptyX = string.IsNullOrWhiteSpace(x); var emptyY = string.IsNullOrWhiteSpace(y); if (emptyY && emptyX) return 0; if (emptyX) return 1*_order; if (emptyY) return -1*_order; return Shlwapi.StrCmpLogicalW(x, y)*_order; }
/// <summary> /// Attempts to extract the localized keyboard layout name using the SHLoadIndirectString API. /// Returning null from this method will force us to use the legacy codepath (pulling the text /// directly from the registry). /// </summary> private static string?GetLocalizedKeyboardLayoutName(string?layoutDisplayName) { if (layoutDisplayName != null) { var sb = new StringBuilder(512); HRESULT res = Shlwapi.SHLoadIndirectString(layoutDisplayName, sb, (uint)sb.Capacity, IntPtr.Zero); if (res == HRESULT.S_OK) { return(sb.ToString()); } } return(null); }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { ImageSource ret = null; var iconInfo = (IconLoadInfo)value; if (iconInfo.IsLoadComplete) { return(iconInfo.CachedValue); } try { if (iconInfo.IsDesktopApp) { if (!string.IsNullOrWhiteSpace(iconInfo.IconPath)) { var iconPath = new StringBuilder(iconInfo.IconPath); int iconIndex = Shlwapi.PathParseIconLocationW(iconPath); if (iconIndex != 0) { ret = IconUtils.GetIconAsImageSourceFromFile(iconPath.ToString(), iconIndex); } else { using (var icon = System.Drawing.Icon.ExtractAssociatedIcon(iconInfo.IconPath)) { ret = icon.ToImageSource(); } } } } else { var bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.UriSource = new Uri(iconInfo.IconPath); bitmap.EndInit(); ret = bitmap; } } catch (Exception ex) { Trace.WriteLine($"Failed to load icon: {ex}"); } iconInfo.IsLoadComplete = true; iconInfo.CachedValue = ret; return(ret); }
public static bool MathcesFilePattern(string filePath, string pattern) { if (filePath.IsNullOrEmpty() || pattern.IsNullOrEmpty()) { return(false); } if (pattern.Contains(';')) { return(Shlwapi.PathMatchSpecExW(filePath, pattern, MatchPatternFlags.Multiple) == 0); } else { return(Shlwapi.PathMatchSpecExW(filePath, pattern, MatchPatternFlags.Normal) == 0); } }
public static Icon GetDesktopIconFromFile(string path) { if (!string.IsNullOrWhiteSpace(path)) { var iconPath = new StringBuilder(path); int iconIndex = Shlwapi.PathParseIconLocationW(iconPath); if (iconIndex != 0) { return(IconUtils.ShellExtractIcon(iconPath.ToString(), iconIndex)); } else { return(System.Drawing.Icon.ExtractAssociatedIcon(path)); } } return(null); }
public string PathFromFileUri(Uri uri) { var bareUri = new UriBuilder(uri) { Fragment = null }.Uri; string absUri = bareUri.AbsoluteUri; string path = Shlwapi.PathCreateFromUrl(absUri); if (bareUri.Host == "localhost") { return(@"\\localhost" + path); } else { return(path); } }
/// <summary> /// Gets the friendly type string for an extension. /// </summary> public static string GetTypeNameForExtension(string extension) { if (extension != null) { extension = extension.Trim(); } int capacity = 270; attempt: StringBuilder builder = new StringBuilder(capacity); int hresult = Shlwapi.AssocQueryString(ASSOCF.NOTRUNCATE, ASSOCSTR.FRIENDLYDOCNAME, extension, null, builder, ref capacity); switch (hresult) { case HRESULT.S_OK: return(builder.ToString()); case HRESULT.E_POINTER: case HRESULT.S_FALSE: // the capacity variable now holds the number of chars necessary. try again goto attempt; case HRESULT.E_INVALIDARG: case HRESULT.E_FAILED: default: break; } if (extension == null || extension == string.Empty) { return("Unknown"); } else { return(extension.TrimStart('.').ToUpper(CultureInfo.InvariantCulture) + " File"); } }
public static Icon LoadIconForTaskbar(string path, uint dpi) { Icon icon = null; if (path.StartsWith("pack://")) { using (var stream = System.Windows.Application.GetResourceStream(new Uri(path)).Stream) { icon = new Icon(stream, new Size( User32.GetSystemMetricsForDpi(User32.SystemMetrics.SM_CXICON, dpi), User32.GetSystemMetricsForDpi(User32.SystemMetrics.SM_CYICON, dpi))); } } else { var iconPath = new StringBuilder(path); int iconIndex = Shlwapi.PathParseIconLocationW(iconPath); icon = LoadIconResource(iconPath.ToString(), iconIndex, User32.GetSystemMetricsForDpi(User32.SystemMetrics.SM_CXSMICON, dpi), User32.GetSystemMetricsForDpi(User32.SystemMetrics.SM_CYSMICON, dpi)); } Trace.WriteLine($"IconHelper LoadIconForTaskbar {path} {icon?.Width}x{icon?.Height}"); return(icon); }
public static Icon LoadIconForTaskbar(string path) { var dpi = WindowsTaskbar.Dpi; Icon icon = null; if (path.StartsWith("pack://")) { using (var stream = System.Windows.Application.GetResourceStream(new Uri(path)).Stream) { icon = new Icon(stream, new Size( User32.GetSystemMetricsForDpi(User32.SystemMetrics.SM_CXICON, dpi), User32.GetSystemMetricsForDpi(User32.SystemMetrics.SM_CYICON, dpi))); } } else { var iconPath = new StringBuilder(path); int iconIndex = Shlwapi.PathParseIconLocationW(iconPath); icon = LoadIconResource(iconPath.ToString(), iconIndex, User32.GetSystemMetricsForDpi(User32.SystemMetrics.SM_CXSMICON, dpi), User32.GetSystemMetricsForDpi(User32.SystemMetrics.SM_CYSMICON, dpi)); } return(icon); }
public async Task RestartScreenCaster(List <string> viewerIDs, string serviceID, string requesterID, HubConnection hubConnection, int targetSessionID = -1) { try { var rcBinaryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Desktop", EnvironmentHelper.DesktopExecutableFileName); // Start Desktop app. if (EnvironmentHelper.IsWindows) { Logger.Write("Restarting screen caster."); if (EnvironmentHelper.IsDebug) { // SignalR Connection IDs might start with a hyphen. We surround them // with quotes so the command line will be parsed correctly. Process.Start(rcBinaryPath, $"-mode Unattended -requester \"{requesterID}\" -serviceid \"{serviceID}\" -deviceid {ConnectionInfo.DeviceID} -host {ConnectionInfo.Host} -relaunch true -viewers {String.Join(",", viewerIDs)}"); } else { // Give a little time for session changing, etc. await Task.Delay(1000); var result = Win32Interop.OpenInteractiveProcess(rcBinaryPath + $" -mode Unattended -requester \"{requesterID}\" -serviceid \"{serviceID}\" -deviceid {ConnectionInfo.DeviceID} -host {ConnectionInfo.Host} -relaunch true -viewers {String.Join(",", viewerIDs)}", targetSessionId: targetSessionID, forceConsoleSession: Shlwapi.IsOS(OsType.OS_ANYSERVER) && targetSessionID == -1 ? true : false, desktopName: "default", hiddenWindow: true, out _); if (!result) { Logger.Write("Failed to relaunch screen caster."); await hubConnection.SendAsync("SendConnectionFailedToViewers", viewerIDs); await hubConnection.SendAsync("DisplayMessage", "Remote control failed to start on target device.", "Failed to start remote control.", requesterID); } } } else if (EnvironmentHelper.IsLinux) { var args = $"{rcBinaryPath} -mode Unattended -requester \"{requesterID}\" -serviceid \"{serviceID}\" -deviceid {ConnectionInfo.DeviceID} -host {ConnectionInfo.Host} -relaunch true -viewers {string.Join(",", viewerIDs)} & disown"; StartLinuxDesktopApp(args); } } catch (Exception ex) { await hubConnection.SendAsync("SendConnectionFailedToViewers", viewerIDs); Logger.Write(ex); throw; } }
/// <summary> /// Override OnLoad /// </summary> /// <param name="e">event args</param> protected override void OnLoad(EventArgs e) { // call base base.OnLoad(e); // scale size of btnOptions based on text if (!_slimOptions) { int existingWidth = btnOptions.Width; int preferredWidth = btnOptions.GetPreferredWidth(); btnOptions.Left = btnOptions.Right - preferredWidth; btnOptions.Width = preferredWidth; textBoxAddress.Width = btnOptions.Left - 5 - textBoxAddress.Left; } else { textBoxAddress.Width = btnOptions.Right - textBoxAddress.Left; btnOptions.Visible = false; labelRel.Visible = false; comboBoxRel.Visible = false; labelTitle.Visible = false; textBoxTitle.Visible = false; ckboxNewWindow.Visible = false; ckBoxGlossary.Visible = false; btnAdvanced.Visible = false; ClientSize = new Size(ClientSize.Width, textBoxLinkText.Bottom + textBoxLinkText.Left); } if (btnRemove != null) { DisplayHelper.AutoFitSystemButton(btnRemove, buttonInsert.Width, int.MaxValue); if (btnAdvanced != null) { btnRemove.Left = btnAdvanced.Left - btnRemove.Width - (int)Math.Round(DisplayHelper.ScaleX(8)); } } using (new AutoGrow(this, AnchorStyles.Right, true)) { LayoutHelper.EqualizeButtonWidthsVert(AnchorStyles.Left, buttonInsert.Width, int.MaxValue, buttonInsert, buttonCancel); } //now, need to move the advanced button over if (btnAdvanced.Visible) { SetAdvancedText(); DisplayHelper.AutoFitSystemButton(btnAdvanced, buttonInsert.Width, int.MaxValue); btnAdvanced.Left = buttonInsert.Right - btnAdvanced.Width; } // install auto-complete on the address text box int result = Shlwapi.SHAutoComplete(textBoxAddress.Handle, SHACF.URLALL | SHACF.AUTOSUGGEST_FORCE_ON); // ensure we installed it successfully (if we didn't, no biggie -- the user will // just not get autocomplete support) Debug.Assert(result == HRESULT.S_OK, "Unexpected failure to install AutoComplete"); // prepopulate the text box w/ http prefix and move the cursor to the end if (textBoxAddress.Text == String.Empty) { try { if (Clipboard.ContainsText()) { string clipboardText = Clipboard.GetText(); if (Regex.IsMatch(clipboardText ?? "", "^https?://", RegexOptions.IgnoreCase) && UrlHelper.IsUrl(clipboardText)) { textBoxAddress.Text = clipboardText; textBoxAddress.Select(0, textBoxAddress.TextLength); } } } catch (ExternalException) { } catch (ThreadStateException) { } } if (textBoxAddress.Text == String.Empty) { textBoxAddress.Text = HTTP_PREFIX; textBoxAddress.Select(HTTP_PREFIX.Length, 0); } //decide whether it should be maximized ShowAdvancedOptions = (LinkSettings.ShowAdvancedOptions || Rel != String.Empty || LinkTitle != String.Empty) && comboBoxRel.Visible; //use new window sticky setting if this isn't an edit if (!_editStyle) { NewWindow = LinkSettings.OpenInNewWindow; } }
public async Task LaunchRemoteControl(int targetSessionId, string requesterID, string serviceID, HubConnection hubConnection) { try { if (!File.Exists(_rcBinaryPath)) { await hubConnection.SendAsync("DisplayMessage", "Remote control executable not found on target device.", "Executable not found on device.", "bg-danger", requesterID); return; } // Start Desktop app. await hubConnection.SendAsync("DisplayMessage", "Starting remote control.", "Starting remote control.", "bg-success", requesterID); if (WindowsIdentity.GetCurrent().IsSystem) { var result = Win32Interop.OpenInteractiveProcess(_rcBinaryPath + $" -mode Unattended" + $" -requester \"{requesterID}\"" + $" -serviceid \"{serviceID}\"" + $" -deviceid {ConnectionInfo.DeviceID}" + $" -host {ConnectionInfo.Host}" + $" -orgid \"{ConnectionInfo.OrganizationID}\"", targetSessionId: targetSessionId, forceConsoleSession: Shlwapi.IsOS(OsType.OS_ANYSERVER) && targetSessionId == -1, desktopName: "default", hiddenWindow: true, out _); if (!result) { await hubConnection.SendAsync("DisplayMessage", "Remote control failed to start on target device.", "Failed to start remote control.", "bg-danger", requesterID); } } else { // SignalR Connection IDs might start with a hyphen. We surround them // with quotes so the command line will be parsed correctly. Process.Start(_rcBinaryPath, $"-mode Unattended " + $"-requester \"{requesterID}\" " + $"-serviceid \"{serviceID}\" " + $"-deviceid {ConnectionInfo.DeviceID} " + $"-host {ConnectionInfo.Host} " + $"-orgid \"{ConnectionInfo.OrganizationID}\""); } } catch (Exception ex) { Logger.Write(ex); await hubConnection.SendAsync("DisplayMessage", "Remote control failed to start on target device.", "Failed to start remote control.", "bg-danger", requesterID); } }
public async Task RestartScreenCaster(List <string> viewerIDs, string serviceID, string requesterID, HubConnection hubConnection, int targetSessionID = -1) { try { // Start Desktop app. Logger.Write("Restarting screen caster."); if (WindowsIdentity.GetCurrent().IsSystem) { // Give a little time for session changing, etc. await Task.Delay(1000); var result = Win32Interop.OpenInteractiveProcess(_rcBinaryPath + $" -mode Unattended" + $" -requester \"{requesterID}\"" + $" -serviceid \"{serviceID}\"" + $" -deviceid {ConnectionInfo.DeviceID}" + $" -host {ConnectionInfo.Host}" + $" -orgid \"{ConnectionInfo.OrganizationID}\"" + $" -relaunch true" + $" -viewers {String.Join(",", viewerIDs)}", targetSessionId: targetSessionID, forceConsoleSession: Shlwapi.IsOS(OsType.OS_ANYSERVER) && targetSessionID == -1, desktopName: "default", hiddenWindow: true, out _); if (!result) { Logger.Write("Failed to relaunch screen caster."); await hubConnection.SendAsync("SendConnectionFailedToViewers", viewerIDs); await hubConnection.SendAsync("DisplayMessage", "Remote control failed to start on target device.", "Failed to start remote control.", "bg-danger", requesterID); } } else { // SignalR Connection IDs might start with a hyphen. We surround them // with quotes so the command line will be parsed correctly. Process.Start(_rcBinaryPath, $"-mode Unattended " + $"-requester \"{requesterID}\" " + $"-serviceid \"{serviceID}\" " + $"-deviceid {ConnectionInfo.DeviceID} " + $"-host {ConnectionInfo.Host} " + $" -orgid \"{ConnectionInfo.OrganizationID}\"" + $"-relaunch true " + $"-viewers {String.Join(",", viewerIDs)}"); } } catch (Exception ex) { await hubConnection.SendAsync("SendConnectionFailedToViewers", viewerIDs); Logger.Write(ex); throw; } }
public override IEnumerable <CommandDTOBase?> Execute(string[] args) { if (!SecurityUtil.IsHighIntegrity() && !ThisRunTime.ISRemote()) { WriteError("Unable to collect. Must be an administrator/in a high integrity context."); yield break; } var NTLMv1Users = new HashSet <string>(); var NTLMv2Users = new HashSet <string>(); var KerberosUsers = new HashSet <string>(); // grab events from the last X days - 10 for workstations, 30 for "-full" collection // Always use the user-supplied value, if specified var lastDays = 10; if (ThisRunTime.ISRemote()) { lastDays = 5; } else if (Shlwapi.IsWindowsServer()) { lastDays = 1; } string?userRegex = null; if (args.Length >= 1) { if (!int.TryParse(args[0], out lastDays)) { throw new ArgumentException("Argument is not an integer"); } } if (args.Length >= 2) { userRegex = args[1]; } WriteVerbose($"Listing 4624 Account Logon Events for the last {lastDays} days.\n"); if (userRegex != null) { WriteVerbose($"Username Filter: {userRegex}"); } var startTime = DateTime.Now.AddDays(-lastDays); var endTime = DateTime.Now; var query = $@"*[System/EventID=4624] and *[System[TimeCreated[@SystemTime >= '{startTime.ToUniversalTime():o}']]] and *[System[TimeCreated[@SystemTime <= '{endTime.ToUniversalTime():o}']]]"; var logReader = ThisRunTime.GetEventLogReader("Security", query); WriteHost(" TimeCreated,TargetUser,LogonType,IpAddress,SubjectUsername,AuthenticationPackageName,LmPackageName,TargetOutboundUser"); for (var eventDetail = logReader.ReadEvent(); eventDetail != null; eventDetail = logReader.ReadEvent()) { //var subjectUserSid = eventDetail.Properties[0].Value.ToString(); var subjectUserName = eventDetail.Properties[1].Value.ToString(); var subjectDomainName = eventDetail.Properties[2].Value.ToString(); //var subjectLogonId = eventDetail.Properties[3].Value.ToString(); //var targetUserSid = eventDetail.Properties[4].Value.ToString(); var targetUserName = eventDetail.Properties[5].Value.ToString(); var targetDomainName = eventDetail.Properties[6].Value.ToString(); //var targetLogonId = eventDetail.Properties[7].Value.ToString(); //var logonType = eventDetail.Properties[8].Value.ToString(); var logonType = $"{(SECURITY_LOGON_TYPE)(int.Parse(eventDetail.Properties[8].Value.ToString()))}"; //var logonProcessName = eventDetail.Properties[9].Value.ToString(); var authenticationPackageName = eventDetail.Properties[10].Value.ToString(); //var workstationName = eventDetail.Properties[11].Value.ToString(); //var logonGuid = eventDetail.Properties[12].Value.ToString(); //var transmittedServices = eventDetail.Properties[13].Value.ToString(); var lmPackageName = eventDetail.Properties[14].Value.ToString(); lmPackageName = lmPackageName == "-" ? "" : lmPackageName; //var keyLength = eventDetail.Properties[15].Value.ToString(); //var processId = eventDetail.Properties[16].Value.ToString(); //var processName = eventDetail.Properties[17].Value.ToString(); var ipAddress = eventDetail.Properties[18].Value.ToString(); //var ipPort = eventDetail.Properties[19].Value.ToString(); //var impersonationLevel = eventDetail.Properties[20].Value.ToString(); //var restrictedAdminMode = eventDetail.Properties[21].Value.ToString(); var targetOutboundUserName = "******"; var targetOutboundDomainName = "-"; if (eventDetail.Properties.Count > 22) // Not available on older versions of Windows { targetOutboundUserName = eventDetail.Properties[22].Value.ToString(); targetOutboundDomainName = eventDetail.Properties[23].Value.ToString(); } //var VirtualAccount = eventDetail.Properties[24].Value.ToString(); //var TargetLinkedLogonId = eventDetail.Properties[25].Value.ToString(); //var ElevatedToken = eventDetail.Properties[26].Value.ToString(); // filter out SYSTEM, computer accounts, local service accounts, UMFD-X accounts, and DWM-X accounts (for now) var userIgnoreRegex = "^(SYSTEM|LOCAL SERVICE|NETWORK SERVICE|UMFD-[0-9]+|DWM-[0-9]+|ANONYMOUS LOGON|" + Environment.MachineName + "\\$)$"; if (userRegex == null && Regex.IsMatch(targetUserName, userIgnoreRegex, RegexOptions.IgnoreCase)) { continue; } var domainIgnoreRegex = "^(NT VIRTUAL MACHINE)$"; if (userRegex == null && Regex.IsMatch(targetDomainName, domainIgnoreRegex, RegexOptions.IgnoreCase)) { continue; } // Handle the user filter if (userRegex != null && !Regex.IsMatch(targetUserName, userRegex, RegexOptions.IgnoreCase)) { continue; } // Analyze the output if (logonType == "Network") { var accountName = $"{targetDomainName}\\{targetUserName}"; if (authenticationPackageName == "NTLM") { switch (lmPackageName) { case "NTLM V1": NTLMv1Users.Add(accountName); break; case "NTLM V2": NTLMv2Users.Add(accountName); break; } } else if (authenticationPackageName == "Kerberos") { KerberosUsers.Add(accountName); } } yield return(new LogonEventsDTO( eventDetail.TimeCreated?.ToUniversalTime(), targetUserName, targetDomainName, logonType, ipAddress, subjectUserName, subjectDomainName, authenticationPackageName, lmPackageName, targetOutboundUserName, targetOutboundDomainName )); } // TODO: Move all of this into a Foramtter class if (NTLMv1Users.Count > 0 || NTLMv2Users.Count > 0) { WriteHost("\n Other accounts authenticate to this machine using NTLM! NTLM-relay may be possible"); } if (NTLMv1Users.Count > 0) { WriteHost("\n Accounts authenticate to this machine using NTLM v1!"); WriteHost(" You can obtain these accounts' **NTLM** hashes by sniffing NTLM challenge/responses and then cracking them!"); WriteHost(" NTLM v1 authentication is 100% broken!\n"); PrintUserSet(NTLMv1Users); } if (NTLMv2Users.Count > 0) { WriteHost("\n Accounts authenticate to this machine using NTLM v2!"); WriteHost(" You can obtain NetNTLMv2 for these accounts by sniffing NTLM challenge/responses."); WriteHost(" You can then try and crack their passwords.\n"); PrintUserSet(NTLMv2Users); } if (KerberosUsers.Count > 0) { WriteHost("\n The following users have authenticated to this machine using Kerberos.\n"); PrintUserSet(KerberosUsers); } }