/// <summary> /// Get the NT type for a SE Object Type. /// </summary> /// <param name="type">The type of the resource.</param> /// <returns>The NT type if known, otherwise null.</returns> public static NtType GetNativeType(SeObjectType type) { switch (type) { case SeObjectType.File: case SeObjectType.LMShare: return(NtType.GetTypeByType <NtFile>()); case SeObjectType.RegistryKey: case SeObjectType.RegistryWow6432Key: case SeObjectType.RegistryWow6464Key: return(NtType.GetTypeByType <NtKey>()); case SeObjectType.Service: return(NtType.GetTypeByName(ServiceUtils.SERVICE_NT_TYPE_NAME)); case SeObjectType.WmiGuid: return(NtType.GetTypeByType <NtEtwRegistration>()); case SeObjectType.Ds: case SeObjectType.DsAll: return(NtType.GetTypeByName(DirectoryServiceUtils.DS_NT_TYPE_NAME)); case SeObjectType.Printer: return(NtType.GetTypeByName(PrintSpoolerUtils.PRINTER_NT_TYPE_NAME)); } return(null); }
/// <summary> /// Finds ALPC endpoints which allows for the server binding. This brute forces all ALPC ports to try and find /// something which will accept the bind. /// </summary> /// <remarks>This could hang if the ALPC port is owned by a suspended process.</remarks> /// <param name="interface_id">Interface UUID to lookup.</param> /// <param name="interface_version">Interface version lookup.</param> /// <returns>A list of RPC endpoints which can bind the interface.</returns> /// <exception cref="NtException">Throws on error.</exception> public static IEnumerable <RpcEndpoint> FindAlpcEndpointForInterface(Guid interface_id, Version interface_version) { using (var dir = NtDirectory.Open(@"\RPC Control")) { var nt_type = NtType.GetTypeByType <NtAlpc>().Name; foreach (var port in dir.Query().Where(e => e.NtTypeName == nt_type)) { bool success = false; try { using (var server = new RpcClient(interface_id, interface_version)) { server.Connect(port.Name); success = true; } } catch { } if (success) { yield return(new RpcEndpoint(interface_id, interface_version, SafeRpcBindingHandle.Compose(null, "ncalrpc", null, port.Name, null), false)); } } } }
internal EntryInfo(string name, NtType type, EntryFlags flags, long lastChange) { Name = name; Type = type; Flags = flags; LastChange = lastChange; }
private protected override void RunAccessCheckPath(IEnumerable <TokenEntry> tokens, string path) { FileOpenOptions options = _open_for_backup ? FileOpenOptions.OpenForBackupIntent : FileOpenOptions.None; if (!FollowLink) { options |= FileOpenOptions.OpenReparsePoint; } NtType type = NtType.GetTypeByType <NtFile>(); AccessMask access_rights = type.MapGenericRights(Access); AccessMask dir_access_rights = type.MapGenericRights(DirectoryAccess); using (var result = OpenFile(path, null, options)) { NtFile file = result.GetResultOrThrow(); if (FollowPath(file, GetFilePath)) { DumpFile(tokens, access_rights, dir_access_rights, null, result.Result); if (IsDirectoryNoThrow(result.Result)) { DumpDirectory(tokens, access_rights, dir_access_rights, file, options, GetMaxDepth()); } } } }
private void RunAccessCheckDesktop(IEnumerable <TokenEntry> tokens, NtWindowStation winsta) { NtType desktop_type = NtType.GetTypeByType <NtDesktop>(); AccessMask desktop_access_rights = desktop_type.GenericMapping.MapMask(DesktopAccessRights); using (var desktops = winsta.GetAccessibleDesktops().ToDisposableList()) { foreach (var desktop in desktops) { if (desktop.IsAccessGranted(DesktopAccessRights.ReadControl)) { var sd = desktop.SecurityDescriptor; foreach (TokenEntry token in tokens) { AccessMask granted_access = NtSecurity.GetMaximumAccess(sd, token.Token, desktop_type.GenericMapping); if (IsAccessGranted(granted_access, desktop_access_rights)) { WriteAccessCheckResult($"{winsta.FullPath}{desktop.FullPath}", desktop_type.Name, granted_access, desktop_type.GenericMapping, sd, desktop_type.AccessRightsType, true, token.Information); } } } } } }
private IEnumerable <AccessCheckResult> RunAuditCheck(NtToken token, NtType type, ObjectTypeEntry[] object_types) { _dict.GetValue("SubsystemName", out string subsystem_name); _dict.GetValue("HandleId", out IntPtr? handle_id); _dict.GetValue("ObjectTypeName", out string object_type_name); _dict.GetValue("ObjectName", out string object_name); _dict.GetValue("ObjectCreation", out SwitchParameter? object_creation); _dict.GetValue("AuditType", out AuditEventType? event_type); _dict.GetValue("AuditFlags", out AuditAccessCheckFlags? flags); var results = new List <AccessCheckResult>(); if (ResultList) { results.AddRange(NtSecurity.AccessCheckWithResultListAudit( subsystem_name, handle_id ?? IntPtr.Zero, object_type_name, object_name, object_creation ?? new SwitchParameter(), event_type ?? AuditEventType.AuditEventObjectAccess, flags ?? AuditAccessCheckFlags.None, GetSecurityDescriptor(), token, GetDesiredAccess(), Principal, type.GenericMapping, object_types)); } else { results.Add(NtSecurity.AccessCheckAudit( subsystem_name, handle_id ?? IntPtr.Zero, object_type_name, object_name, object_creation ?? new SwitchParameter(), event_type ?? AuditEventType.AuditEventObjectAccess, flags ?? AuditAccessCheckFlags.None, GetSecurityDescriptor(), token, GetDesiredAccess(), Principal, type.GenericMapping, object_types)); } return(results); }
private protected override void RunAccessCheck(IEnumerable <TokenEntry> tokens) { NtType winsta_type = NtType.GetTypeByType <NtWindowStation>(); AccessMask winsta_access_rights = winsta_type.GenericMapping.MapMask(AccessRights); bool check_winsta = CheckMode == WindowStationCheckMode.WindowStationOnly || CheckMode == WindowStationCheckMode.WindowStationAndDesktop; bool check_desktop = CheckMode == WindowStationCheckMode.DesktopOnly || CheckMode == WindowStationCheckMode.WindowStationAndDesktop; using (var winstas = NtWindowStation.GetAccessibleWindowStations().ToDisposableList()) { foreach (var winsta in winstas) { if (check_winsta && winsta.IsAccessGranted(WindowStationAccessRights.ReadControl)) { var sd = winsta.SecurityDescriptor; foreach (TokenEntry token in tokens) { AccessMask granted_access = NtSecurity.GetMaximumAccess(sd, token.Token, winsta_type.GenericMapping); if (IsAccessGranted(granted_access, winsta_access_rights)) { WriteAccessCheckResult(winsta.FullPath, winsta_type.Name, granted_access, winsta_type.GenericMapping, sd, winsta_type.AccessRightsType, true, token.Information); } } } if (check_desktop && winsta.IsAccessGranted(WindowStationAccessRights.EnumDesktops)) { RunAccessCheckDesktop(tokens, winsta); } } } }
internal SecurityDescriptorInheritanceSource( Ace ace, INHERITED_FROM inherited_from, SeObjectType type, NtType native_type, bool container, bool query_security, bool sacl) { InheritedAce = ace; if (native_type != null) { Access = NtSecurity.AccessMaskToString(ace.Mask, container ? native_type.ContainerAccessRightsType : native_type.AccessRightsType, native_type.GenericMapping, false); GenericAccess = NtSecurity.AccessMaskToString(ace.Mask, container ? native_type.ContainerAccessRightsType : native_type.AccessRightsType, native_type.GenericMapping, true); } else { Access = NtSecurity.AccessMaskToString(ace.Mask.ToGenericAccess()); GenericAccess = NtSecurity.AccessMaskToString(ace.Mask.ToGenericAccess()); } Depth = inherited_from.GenerationGap; Name = Marshal.PtrToStringUni(inherited_from.AncestorName); if (query_security && Name != null) { SecurityInformation sec_info = sacl ? SecurityInformation.All : SecurityInformation.AllNoSacl; var sd = Win32Security.GetSecurityInfo(Name, type, sec_info, false); if (sd.IsSuccess) { SecurityDescriptor = sd.Result; } } }
static Type GetTypeAccessRights(NtType type) { switch (type.Name.ToLower()) { case "directory": return(typeof(DirectoryAccessRights)); case "event": return(typeof(EventAccessRights)); case "section": return(typeof(SectionAccessRights)); case "mutant": return(typeof(MutantAccessRights)); case "semaphore": return(typeof(SemaphoreAccessRights)); case "job": return(typeof(JobAccessRights)); case "symboliclink": return(typeof(SymbolicLinkAccessRights)); default: throw new ArgumentException("Can't get type for access rights"); } }
private void CheckAccess(TokenEntry token, NtFile file, AccessMask access_rights, SecurityDescriptor sd, SecurityDescriptor parent_sd) { NtType type = file.NtType; AccessMask granted_access = NtSecurity.GetMaximumAccess(sd, token.Token, type.GenericMapping); // Determine if the parent gives additonal rights to this file. if (!granted_access.IsAllAccessGranted(FileDirectoryAccessRights.ReadAttributes | FileDirectoryAccessRights.Delete) && parent_sd != null) { AccessMask parent_granted_access = NtSecurity.GetMaximumAccess(parent_sd, token.Token, type.GenericMapping); if (parent_granted_access.IsAccessGranted(FileDirectoryAccessRights.DeleteChild)) { granted_access |= FileAccessRights.Delete; } if (parent_granted_access.IsAccessGranted(FileDirectoryAccessRights.ListDirectory)) { granted_access |= FileAccessRights.ReadAttributes; } } if (IsAccessGranted(granted_access, access_rights)) { bool is_directory = IsDirectoryNoThrow(file); WriteAccessCheckResult(FormatWin32Path ? file.Win32PathName : file.FullPath, type.Name, granted_access, type.GenericMapping, sd, is_directory ? typeof(FileDirectoryAccessRights) : typeof(FileAccessRights), is_directory, token.Information); } }
private void ShowProcessSecurity(ProcessTokenEntry process) { var viewer = new SecurityDescriptorViewerForm($"{process.Name}:{process.ProcessId}", process.ProcessSecurity, NtType.GetTypeByType <NtProcess>(), false); viewer.ShowDialog(this); }
/// <summary> /// Get the NT type for a SE Object Type. /// </summary> /// <param name="type">The type of the resource.</param> /// <returns>The NT type if known, otherwise null.</returns> public static NtType GetNativeType(SeObjectType type) { switch (type) { case SeObjectType.File: case SeObjectType.LMShare: return(NtType.GetTypeByType <NtFile>()); case SeObjectType.RegistryKey: case SeObjectType.RegistryWow6432Key: case SeObjectType.RegistryWow6464Key: return(NtType.GetTypeByType <NtKey>()); case SeObjectType.Service: return(ServiceUtils.GetServiceNtType("Service")); case SeObjectType.WmiGuid: return(NtType.GetTypeByType <NtEtwRegistration>()); case SeObjectType.Ds: case SeObjectType.DsAll: return(DirectoryServiceUtils.NtType); } return(null); }
internal static string GetString(this NtType ntType) { switch (ntType) { case NtType.Boolean: return("Boolean"); case NtType.Double: return("Double"); case NtType.String: return("String"); case NtType.Raw: return("Raw"); case NtType.BooleanArray: return("BooleanArray"); case NtType.DoubleArray: return("DoubleArray"); case NtType.StringArray: return("StringArray"); case NtType.Rpc: return("Rpc"); default: return("Unknown"); } }
/// <summary> /// Overridden process record method. /// </summary> protected override void ProcessRecord() { using (NtToken token = GetToken()) { NtType type = GetNtType(); if (type == null) { throw new ArgumentException("Must specify a type."); } var result = NtSecurity.AccessCheck(GetSecurityDescriptor(), token, AccessMask, Principal, type.GenericMapping, ObjectType).ToSpecificAccess(type.AccessRightsType); if (PassResult) { WriteObject(result); return; } var mask = result.SpecificGrantedAccess; if (MapToGeneric) { mask = result.SpecificGenericGrantedAccess; } if (ConvertToString) { string access_string = NtObjectUtils.GrantedAccessAsString(mask, type.GenericMapping, type.AccessRightsType, false); WriteObject(access_string); } else { WriteObject(mask); } } }
public void TestReadType() { byte[] rawData = { 0x00, 0x01, 0x02, 0x03, 0x10, 0x11, 0x12, 0x20 }; WireDecoder d = new WireDecoder(rawData); NtType val = 0; Assert.That(d.ReadType(ref val)); Assert.That(val, Is.EqualTo(NtType.Boolean)); Assert.That(d.ReadType(ref val)); Assert.That(val, Is.EqualTo(NtType.Double)); Assert.That(d.ReadType(ref val)); Assert.That(val, Is.EqualTo(NtType.String)); Assert.That(d.ReadType(ref val)); Assert.That(val, Is.EqualTo(NtType.Raw)); Assert.That(d.ReadType(ref val)); Assert.That(val, Is.EqualTo(NtType.BooleanArray)); Assert.That(d.ReadType(ref val)); Assert.That(val, Is.EqualTo(NtType.DoubleArray)); Assert.That(d.ReadType(ref val)); Assert.That(val, Is.EqualTo(NtType.StringArray)); Assert.That(d.ReadType(ref val)); Assert.That(val, Is.EqualTo(NtType.Rpc)); Assert.That(!d.ReadType(ref val)); Assert.That(d.Error, Is.Null); }
/// <summary> /// Creates a new <see cref="TableKeyDifferentTypeException"/>. /// </summary> /// <param name="key">The table key that was different.</param> /// <param name="requested">The type requested.</param> /// <param name="typeInTable">The type actually in the table.</param> public TableKeyDifferentTypeException(string key, NtType requested, NtType typeInTable) : base($"Key: {key}, Requested Type: {requested}, Type in Table: {typeInTable}") { RequestedKey = key; RequestedType = requested; TypeInTable = typeInTable; ThrownByValueGet = false; }
private protected SamObject(SafeSamHandle handle, AccessMask granted_access, string type_name, string object_name, string server_name) { _handle = handle; _granted_access = granted_access; NtType = NtType.GetTypeByName(type_name); ObjectName = object_name; ServerName = server_name; }
/// <summary> /// Creates a new <see cref="TableKeyDifferentTypeException"/> during a <see cref="Value"/> error /// </summary> /// <param name="requested">The type requested.</param> /// <param name="typeInTable">The type actually in the value.</param> public TableKeyDifferentTypeException(NtType requested, NtType typeInTable) : base($"Requested Type {requested} does not match actual Type {typeInTable}.") { RequestedKey = ""; RequestedType = requested; TypeInTable = typeInTable; ThrownByValueGet = true; }
private NtResult <NtObject> ReopenUnderImpersonation(TokenEntry token, NtType type, NtObject obj) { using (ObjectAttributes obj_attributes = new ObjectAttributes(string.Empty, AttributeFlags.CaseInsensitive, obj)) { return(token.Token.RunUnderImpersonate(() => type.Open(obj_attributes, GenericAccessRights.MaximumAllowed, false))); } }
internal static NtType GetType(string name) { UIntPtr size; IntPtr str = CreateCachedUTF8String(name, out size); NtType retVal = Interop.NT_GetType(str, size); return(retVal); }
/// <summary> /// Gets an array of entry information /// </summary> /// <remarks> /// The results are optionally filtered by a string prefix and entry type to only /// return a subset of all entries /// </remarks> /// <param name="prefix">A required entry prefix. Only entries with this prefix will be returned</param> /// <param name="types">Bitmask of <see cref="NtType"/> values, 0 is "don't care"</param> /// <returns>Array of entry information</returns> public static List <EntryInfo> GetEntryInfo(string prefix, NtType types) { #if CORE return(CoreMethods.GetEntryInfo(prefix, types)); #else return(Storage.Instance.GetEntryInfo(prefix, types)); #endif }
static Dictionary <uint, String> GetMaskDictionary(NtType type) { Dictionary <uint, String> access = new Dictionary <uint, String>(); AddEnumToDictionary(access, type.AccessRightsType, type.ValidAccess.Access); return(access); }
private protected override void RunAccessCheck(IEnumerable <TokenEntry> tokens) { if (!NtToken.EnableDebugPrivilege()) { WriteWarning("Current process doesn't have SeDebugPrivilege, results may be inaccurate"); } NtType type = NtType.GetTypeByType <NtToken>(); AccessMask access_rights = type.MapGenericRights(AccessRights); int current_session_id = NtProcess.Current.SessionId; using (var procs = NtProcess.GetProcesses(ProcessAccessRights.QueryInformation | ProcessAccessRights.ReadControl, false).ToDisposableList()) { IEnumerable <NtProcess> proc_enum = procs; if (CurrentSession) { proc_enum = proc_enum.Where(p => CheckSession(p, current_session_id)); } foreach (var proc in proc_enum.Where(p => ShowDeadProcesses || !p.IsDeleting)) { using (var result = NtToken.OpenProcessToken(proc, TokenAccessRights.ReadControl | TokenAccessRights.Query, false)) { if (!result.IsSuccess) { WriteWarning($"Couldn't open token for Process {proc.Name} PID: {proc.ProcessId} Status: {result.Status}"); continue; } NtToken primary_token = result.Result; var sd_result = primary_token.GetSecurityDescriptor(SecurityInformation.AllBasic, false); if (!sd_result.IsSuccess) { WriteWarning($"Couldn't get token's Security Descriptor for Process {proc.Name} PID: {proc.ProcessId} Status: {sd_result.Status}"); continue; } var sd = sd_result.Result; string process_name = proc.Name; string process_cmdline = proc.CommandLine; string image_path = proc.FullPath; int process_id = proc.ProcessId; foreach (var token in tokens) { if (proc.GetMaximumAccess(token.Token).HasFlag(ProcessAccessRights.QueryLimitedInformation)) { AccessMask granted_access = NtSecurity.GetMaximumAccess(sd, token.Token, type.GenericMapping); if (IsAccessGranted(granted_access, access_rights)) { WriteObject(new TokenAccessCheckResult(primary_token, proc, granted_access, sd, token.Information)); } } } } } } }
static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); try { if (args.Length == 0) { MessageBox.Show("Usage: ViewSecurityDescriptor.exe (handle [--readonly]|Name (SDDL|-B64) NtType [Container])", "Usage", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { if (args.Length < 3) { var handle = new SafeKernelObjectHandle(new IntPtr(int.Parse(args[0])), true); bool read_only = args.Length > 1 ? args[1].Equals("--readonly") : false; using (var obj = NtGeneric.FromHandle(handle)) { Application.Run(new SecurityDescriptorViewerForm(obj.ToTypedObject(), read_only)); } } else { NtType type = null; if (args[2].Equals("DirectoryService", StringComparison.OrdinalIgnoreCase)) { type = DirectoryServiceUtils.NtType; } else { type = ServiceUtils.GetServiceNtType(args[2]) ?? new NtType(args[2]); } SecurityDescriptor sd; if (args[1].StartsWith("-")) { sd = new SecurityDescriptor(Convert.FromBase64String(args[1].Substring(1))); } else { sd = new SecurityDescriptor(args[1]); } bool container = false; if (args.Length > 3) { container = bool.Parse(args[3]); } Application.Run(new SecurityDescriptorViewerForm(args[0], sd, type, container)); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private ServiceAccessRights GetTriggerAccess(Win32Service service, NtToken token) { if (IgnoreTrigger) { return(0); } ServiceAccessRights granted_access = 0; NtType type = NtType.GetTypeByType <NtEtwRegistration>(); foreach (var trigger in service.Triggers) { bool accessible = false; if (trigger.TriggerType == ServiceTriggerType.NetworkEndpoint) { accessible = true; } else if (trigger is EtwServiceTriggerInformation etw_trigger) { if (etw_trigger.SecurityDescriptor == null) { WriteWarning($"Can't access ETW Security Descriptor for service {service.Name}. Running as Administrator might help."); } else { accessible = CheckForAccess(etw_trigger.SecurityDescriptor, token, TraceAccessRights.GuidEnable, type.GenericMapping); } } else if (trigger is WnfServiceTriggerInformation wnf_trigger) { if (wnf_trigger.Name?.SecurityDescriptor == null) { WriteWarning($"Can't access WNF Security Descriptor for service {service.Name}"); } else { accessible = CheckForAccess(wnf_trigger.Name.SecurityDescriptor, token, WnfAccessRights.WriteData, NtWnf.GenericMapping); } } if (accessible) { if (trigger.Action == ServiceTriggerAction.Start) { granted_access |= ServiceAccessRights.Start; } else { granted_access |= ServiceAccessRights.Stop; } } } return(granted_access); }
internal ThreadAccessCheckResult(string name, string image_path, int thread_id, string thread_description, int process_id, int session_id, string command_line, AccessMask granted_access, NtType type, string sddl, TokenInformation token_info) : base($"{name}/{process_id}.{thread_id}", image_path, process_id, session_id, command_line, granted_access, true, type, sddl, token_info) { ThreadId = thread_id; ThreadDescription = thread_description; }
internal ProcessAccessCheckResult(string name, string image_path, int process_id, int session_id, string command_line, AccessMask granted_access, NtType type, string sddl, TokenInformation token_info) : base(name, type.Name, granted_access, type.GenericMapping, sddl, type.AccessRightsType, token_info) { ProcessImagePath = image_path; ProcessId = process_id; ProcessCommandLine = command_line; }
private NtResult <NtObject> OpenObject(ObjectDirectoryInformation entry, NtObject root, AccessMask desired_access) { NtType type = entry.NtType; using (var obja = new ObjectAttributes(entry.Name, AttributeFlags.CaseInsensitive, root)) { return(type.Open(obja, desired_access, false)); } }
static string AccessMaskToString(NtType type, uint granted_access) { if (type.HasFullPermission(granted_access)) { return("Full Permission"); } return(NtObject.AccessRightsToString(GetTypeAccessRights(type), type.MapGenericRights(granted_access))); }
private void DumpDirectory(IEnumerable <TokenEntry> tokens, HashSet <string> type_filter, AccessMask access_rights, NtDirectory dir, int current_depth) { DumpObject(tokens, type_filter, access_rights, dir, true); if (Stopping || current_depth <= 0) { return; } if (Recurse && dir.IsAccessGranted(DirectoryAccessRights.Query)) { foreach (var entry in dir.Query()) { if (entry.IsDirectory) { using (var new_dir = OpenDirectory(entry.Name, dir)) { if (new_dir.IsSuccess) { DumpDirectory(tokens, type_filter, access_rights, new_dir.Result, current_depth - 1); } else { WriteAccessWarning(dir, entry.Name, new_dir.Status); } } } else { NtType type = entry.NtType; if (IsTypeFiltered(type.Name, type_filter) && !type.Name.Equals("Device", StringComparison.OrdinalIgnoreCase) && !type.Name.Equals("Key", StringComparison.OrdinalIgnoreCase)) { if (type.CanOpen) { using (var result = OpenObject(entry, dir, GenericAccessRights.MaximumAllowed)) { if (result.IsSuccess) { DumpObject(tokens, type_filter, access_rights, result.Result, false); } else { WriteAccessWarning(dir, entry.Name, result.Status); } } } else { WriteWarning(String.Format(@"Can't open {0}\{1} with type {2}", dir.FullPath, entry.Name, entry.NtTypeName)); } } } } } }
private UpnpNt(Guid id, string domainName, string itemCustom, string itemType, string itemVersion, NtType type) { this.id = id; ItemCuston = itemCustom; DomainName = domainName; ItemType = itemType; ItemVersion = itemVersion; Type = type; }
public HashSet<string> GetKeys(NtType types) { return null; }
public void WriteType(NtType type) { switch (type) { case NtType.Boolean: m_buffer.Add(0x00); break; case NtType.Double: m_buffer.Add(0x01); break; case NtType.String: m_buffer.Add(0x02); break; case NtType.Raw: //We will only ever call this from a 3.0 protocol. So we don't need to check; m_buffer.Add(0x03); break; case NtType.BooleanArray: m_buffer.Add(0x10); break; case NtType.DoubleArray: m_buffer.Add(0x11); break; case NtType.StringArray: m_buffer.Add(0x12); break; case NtType.Rpc: //We will only ever call this from a 3.0 protocol. So we don't need to check; m_buffer.Add(0x20); break; default: Console.WriteLine("Unrecognized Type"); return; } }
public bool ReadType(ref NtType type) { byte itype = 0; if (!Read8(ref itype)) return false; switch (itype) { case 0x00: type = NtType.Boolean; break; case 0x01: type = NtType.Double; break; case 0x02: type = NtType.String; break; case 0x03: type = NtType.Raw; break; case 0x10: type = NtType.BooleanArray; break; case 0x11: type = NtType.DoubleArray; break; case 0x12: type = NtType.StringArray; break; case 0x20: type = NtType.Rpc; break; default: type = NtType.Unassigned; Error = "unrecognized value type"; return false; } return true; }
public RpcValue ReadValue(NtType type) { byte size = 0; byte[] buf; Error = null; switch (type) { case NtType.Boolean: byte vB = 0; return !Read8(ref vB) ? null : RpcValue.MakeBoolean(vB != 0); case NtType.Double: double vD = 0; return !ReadDouble(ref vD) ? null : RpcValue.MakeDouble(vD); case NtType.Raw: byte[] vRa = null; return !ReadRaw(ref vRa) ? null : RpcValue.MakeRaw(vRa); case NtType.Rpc: case NtType.String: string vS = ""; return !ReadString(ref vS) ? null : RpcValue.MakeString(vS); case NtType.BooleanArray: if (!Read8(ref size)) return null; buf = ReadArray(size); if (buf == null) return null; bool[] bBuf = new bool[buf.Length]; for (int i = 0; i < buf.Length; i++) { bBuf[i] = buf[i] != 0; } return RpcValue.MakeBooleanArray(bBuf); case NtType.DoubleArray: if (!Read8(ref size)) return null; buf = ReadArray(size * 8); if (buf == null) return null; double[] dBuf = new double[size]; for (int i = 0; i < size; i++) { dBuf[i] = ReadDouble(buf, i * 8); } return RpcValue.MakeDoubleArray(dBuf); case NtType.StringArray: if (!Read8(ref size)) return null; string[] sBuf = new string[size]; for (int i = 0; i < size; i++) { if (!ReadString(ref sBuf[i])) return null; } return RpcValue.MakeStringArray(sBuf); default: Error = "invalid type when trying to read value"; Console.WriteLine("invalid type when trying to read value"); return null; } }
private static void ThrowException(string name, byte[] namePtr, UIntPtr size, NtType requestedType) { NtType typeInTable = Interop.NT_GetType(namePtr, size); if (typeInTable == NtType.Unassigned) { throw new TableKeyNotDefinedException(name); } else { throw new TableKeyDifferentTypeException(name, requestedType, typeInTable); } }
internal static EntryInfo[] GetEntries(string prefix, NtType types) { UIntPtr size; byte[] str = CreateUTF8String(prefix, out size); UIntPtr arrSize = UIntPtr.Zero; IntPtr arr = Interop.NT_GetEntryInfo(str, size, (uint)types, ref arrSize); int entryInfoSize = Marshal.SizeOf(typeof(NtEntryInfo)); int arraySize = (int)arrSize.ToUInt64(); EntryInfo[] entryArray = new EntryInfo[arraySize]; for (int i = 0; i < arraySize; i++) { IntPtr data = new IntPtr(arr.ToInt64() + entryInfoSize * i); NtEntryInfo info = (NtEntryInfo)Marshal.PtrToStructure(data, typeof(NtEntryInfo)); entryArray[i] = new EntryInfo(info.name.ToString(), info.type, (EntryFlags)info.flags, (long)info.last_change); } Interop.NT_DisposeEntryInfoArray(arr, arrSize); return entryArray; }
public NtRpcResultDef(string name, NtType type) { Name = name; Type = type; }
/// <summary> /// Creates a new <see cref="TableKeyDifferentTypeException"/>. /// </summary> /// <param name="key">The table key that was different.</param> /// <param name="requested">The type requested.</param> /// <param name="typeInTable">The type actually in the table.</param> public TableKeyDifferentTypeException(string key, NtType requested, NtType typeInTable) : base($"Key: {key}, Requested Type: {requested}, Type in Table: {typeInTable}") { }