static string GrantedAccessToString(AccessMask granted_access, bool scm, bool map_to_generic) { GenericMapping generic_mapping = scm ? GetSCMGenericMapping() : GetServiceGenericMapping(); Type enum_type = scm ? typeof(ServiceControlManagerAccessRights) : typeof(ServiceAccessRights); return(NtObjectUtils.GrantedAccessAsString(granted_access, generic_mapping, enum_type, map_to_generic)); }
/// <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); } } }
internal override string Format() { StringBuilder builder = new StringBuilder(); builder.AppendLine($"Client Name : {ClientName}"); builder.AppendLine($"Client Realm : {ClientRealm}"); if (!string.IsNullOrEmpty(ClientTime)) { builder.AppendLine($"Client Time : {KerberosUtils.ParseKerberosTime(ClientTime, ClientUSec)}"); } if (Checksum != null) { Checksum.Format(builder); } if (SubKey != null) { builder.AppendLine("<Sub Session Key>"); builder.AppendLine($"Encryption Type : {SubKey.KeyEncryption}"); builder.AppendLine($"Encryption Key : {NtObjectUtils.ToHexString(SubKey.Key)}"); } if (SequenceNumber.HasValue) { builder.AppendLine($"Sequence Number : 0x{SequenceNumber:X}"); } if (AuthorizationData.Count > 0) { foreach (var ad in AuthorizationData) { ad.Format(builder); } builder.AppendLine(); } return(builder.ToString()); }
/// <summary> /// Modify groups in the context. /// </summary> /// <param name="type">The type of group to modify.</param> /// <param name="groups">The list of groups to modify.</param> /// <param name="operations">The list of operations. Should be same size of group list.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The NT status code.</returns> public NtStatus ModifyGroups(AuthZGroupSidType type, IEnumerable <UserGroup> groups, IEnumerable <AuthZSidOperation> operations, bool throw_on_error) { if (groups is null) { throw new ArgumentNullException(nameof(groups)); } if (operations is null) { throw new ArgumentNullException(nameof(operations)); } UserGroup[] group_array = groups.ToArray(); AuthZSidOperation[] ops_array = operations.ToArray(); if (group_array.Length != ops_array.Length) { throw new ArgumentException("Groups and Operations must be the same length."); } using (var buffer = SafeTokenGroupsBuffer.Create(groups)) { if (!SecurityNativeMethods.AuthzModifySids(_handle, SidTypeToInfoClass(type), ops_array, buffer)) { return(NtObjectUtils.MapDosErrorToStatus().ToNtException(throw_on_error)); } } return(NtStatus.STATUS_SUCCESS); }
/// <summary> /// Create a new AppContainerProfile. /// </summary> /// <param name="appcontainer_name">The name of the AppContainer.</param> /// <param name="display_name">A display name.</param> /// <param name="description">An optional description.</param> /// <param name="capabilities">An optional list of capability SIDs.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The created AppContainer profile.</returns> /// <remarks>If the profile already exists then it'll be opened instead.</remarks> public static NtResult <AppContainerProfile> Create( string appcontainer_name, string display_name, string description, IEnumerable <Sid> capabilities, bool throw_on_error) { using (var resources = new DisposableList()) { var caps = resources.CreateSidAndAttributes(capabilities); NtStatus status = Win32NativeMethods.CreateAppContainerProfile(appcontainer_name, display_name, description, caps.Length > 0 ? caps : null, caps.Length, out SafeSidBufferHandle sid); if (status == NtObjectUtils.MapDosErrorToStatus(Win32Error.ERROR_ALREADY_EXISTS)) { return(new AppContainerProfile(appcontainer_name).CreateResult()); } resources.AddResource(sid); return(status.CreateResult(throw_on_error, () => { using (sid) { return new AppContainerProfile(appcontainer_name, sid.ToSid(), capabilities, display_name, description); } })); } }
internal NtStatusResult(NtStatus status) { Status = (uint)status; Message = NtObjectUtils.GetNtStatusMessage(status); Win32Error = NtObjectUtils.MapNtStatusToDosError(status); StatusName = status.ToString(); }
/// <summary> /// Get a list of all console sessions. /// </summary> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The list of console sessions.</returns> public static NtResult <IEnumerable <ConsoleSession> > GetConsoleSessions(bool throw_on_error) { List <ConsoleSession> sessions = new List <ConsoleSession>(); IntPtr session_info = IntPtr.Zero; int session_count = 0; try { int level = 1; if (!Win32NativeMethods.WTSEnumerateSessionsEx(IntPtr.Zero, ref level, 0, out session_info, out session_count)) { return(NtObjectUtils.MapDosErrorToStatus().CreateResultFromError <IEnumerable <ConsoleSession> >(throw_on_error)); } IntPtr current = session_info; for (int i = 0; i < session_count; ++i) { WTS_SESSION_INFO_1 info = (WTS_SESSION_INFO_1)Marshal.PtrToStructure(current, typeof(WTS_SESSION_INFO_1)); sessions.Add(new ConsoleSession(info)); current += Marshal.SizeOf(typeof(WTS_SESSION_INFO_1)); } } finally { if (session_info != IntPtr.Zero) { Win32NativeMethods.WTSFreeMemoryEx(WTS_TYPE_CLASS.WTSTypeSessionInfoLevel1, session_info, session_count); } } return(sessions.AsReadOnly().CreateResult <IEnumerable <ConsoleSession> >()); }
/// <summary> /// Format the authentication token. /// </summary> /// <returns>The formatted token.</returns> public override string Format() { StringBuilder builder = new StringBuilder(); builder.AppendLine("<NTLM CHALLENGE>"); builder.AppendLine($"Flags : {Flags}"); if (!string.IsNullOrEmpty(TargetName)) { builder.AppendLine($"TargetName: {TargetName}"); } builder.AppendLine($"Challenge : {NtObjectUtils.ToHexString(ServerChallenge)}"); builder.AppendLine($"Reserved : {NtObjectUtils.ToHexString(Reserved)}"); builder.AppendLine($"Version : {Version}"); if (TargetInfo.Count > 0) { builder.AppendLine("=> Target Info"); foreach (var pair in TargetInfo) { builder.AppendLine(pair.ToString()); } } return(builder.ToString()); }
private static NtResult <AuditPerUserCategory> GetPerUserCategoryInternal(Sid user, AuditPolicyEventType type, bool throw_on_error) { if (!SecurityNativeMethods.AuditLookupCategoryGuidFromCategoryId(type, out Guid category)) { return(NtObjectUtils.MapDosErrorToStatus().CreateResultFromError <AuditPerUserCategory>(throw_on_error)); } return(GetPerUserCategoryInternal(user, category, throw_on_error)); }
internal static NtResult <T> CreateWin32Result <T>(this bool result, bool throw_on_error, Func <T> create_func) { if (result) { return(create_func().CreateResult()); } return(NtObjectUtils.MapDosErrorToStatus().CreateResultFromError <T>(throw_on_error)); }
static Form GetFormFromArgs(string[] args) { try { int pid = -1; int handle = -1; string text = string.Empty; bool show_help = false; OptionSet opts = new OptionSet() { { "p|pid=", "Specify a process ID to view the token.", v => pid = int.Parse(v) }, { "handle=", "Specify an inherited handle to view.", v => handle = int.Parse(v) }, { "text=", "Specify a text string for the token window.", v => text = v }, { "h|help", "Show this message and exit", v => show_help = v != null }, }; opts.Parse(args); if (show_help || (handle <= 0 && pid <= 0)) { ShowHelp(opts); } else if (handle > 0) { using (var obj = NtObjectUtils.FromHandle(new IntPtr(handle), true)) { if (obj is NtToken token) { return(new TokenForm(token.Duplicate(), text)); } else if (obj is NtProcess process) { return(new TokenForm(new ProcessTokenEntry(process), text, false)); } throw new ArgumentException("Passed handle is not a token or process."); } } else if (pid > 0) { using (NtProcess process = NtProcess.Open(pid, ProcessAccessRights.QueryLimitedInformation)) { return(new TokenForm(new ProcessTokenEntry(process), $"{process.Name}:{pid}", false)); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return(null); }
private protected override void FormatData(StringBuilder builder) { builder.AppendLine($"Signature Type : {SignatureType}"); builder.AppendLine($"Signature : {NtObjectUtils.ToHexString(Signature)}"); if (RODCIdentifier.HasValue) { builder.AppendLine($"RODC Identifier : {RODCIdentifier}"); } }
/// <summary> /// Set the Auditing Security Descriptor. /// </summary> /// <param name="security_information">The security information to set.</param> /// <param name="security_descriptor">The security descriptor to set.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The NT status code.</returns> public static NtStatus SetSecurity(SecurityInformation security_information, SecurityDescriptor security_descriptor, bool throw_on_error) { using (var buffer = security_descriptor.ToSafeBuffer()) { if (!SecurityNativeMethods.AuditSetSecurity(security_information, buffer)) { return(NtObjectUtils.MapDosErrorToStatus().ToNtException(throw_on_error)); } return(NtStatus.STATUS_SUCCESS); } }
/// <summary> /// Query the Auditing Security Descriptor. /// </summary> /// <param name="security_information">The security information to query.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The security descriptor.</returns> public static NtResult <SecurityDescriptor> QuerySecurity(SecurityInformation security_information, bool throw_on_error) { if (!SecurityNativeMethods.AuditQuerySecurity(security_information, out SafeAuditBuffer buffer)) { return(NtObjectUtils.MapDosErrorToStatus().CreateResultFromError <SecurityDescriptor>(throw_on_error)); } using (buffer) { return(SecurityDescriptor.Parse(buffer, NtType, throw_on_error)); } }
/// <summary> /// Get the address of an exported function from an ordinal. /// </summary> /// <param name="ordinal">The ordinal of the exported function.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>Pointer to the exported function.</returns> /// <exception cref="NtException">Thrown if the ordinal doesn't exist.</exception> public NtResult <IntPtr> GetProcAddress(IntPtr ordinal, bool throw_on_error) { IntPtr func = Win32NativeMethods.GetProcAddress(handle, ordinal); if (func == IntPtr.Zero) { return(NtObjectUtils.MapDosErrorToStatus().CreateResultFromError <IntPtr>(throw_on_error)); } return(func.CreateResult()); }
/// <summary> /// Get Win32 path name for a file. /// </summary> /// <param name="file">The file to get the path from.</param> /// <param name="flags">Flags for the path to return.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The win32 path.</returns> public static NtResult <string> GetWin32PathName(NtFile file, Win32PathNameFlags flags, bool throw_on_error) { StringBuilder builder = new StringBuilder(1000); if (Win32NativeMethods.GetFinalPathNameByHandle(file.Handle, builder, builder.Capacity, flags) == 0) { return(NtObjectUtils.MapDosErrorToStatus().CreateResultFromError <string>(throw_on_error)); } return(NtStatus.STATUS_SUCCESS.CreateResult(throw_on_error, () => RemoveDevicePrefix(builder.ToString()))); }
private protected override void FormatTicketData(StringBuilder builder) { builder.AppendLine($"Flags : {Flags}"); builder.AppendLine($"Client Name : {ClientName}"); builder.AppendLine($"Client Realm : {ClientRealm}"); if (!string.IsNullOrEmpty(AuthTime)) { builder.AppendLine($"Auth Time : {KerberosUtils.ParseKerberosTime(AuthTime, 0)}"); } if (!string.IsNullOrEmpty(StartTime)) { builder.AppendLine($"Start Time : {KerberosUtils.ParseKerberosTime(StartTime, 0)}"); } if (!string.IsNullOrEmpty(EndTime)) { builder.AppendLine($"End Time : {KerberosUtils.ParseKerberosTime(EndTime, 0)}"); } if (!string.IsNullOrEmpty(RenewTill)) { builder.AppendLine($"Renew Till Time : {KerberosUtils.ParseKerberosTime(RenewTill, 0)}"); } builder.AppendLine(); if (Key != null) { builder.AppendLine("<Session Key>"); builder.AppendLine($"Encryption Type : {Key.KeyEncryption}"); builder.AppendLine($"Encryption Key : {NtObjectUtils.ToHexString(Key.Key)}"); builder.AppendLine(); } if (TransitedType != null && TransitedType.Data.Length > 0) { builder.AppendLine($"<Transited Type - {TransitedType.TransitedType}>"); builder.AppendLine($"{NtObjectUtils.ToHexString(TransitedType.Data)}"); builder.AppendLine(); } if (HostAddresses.Count > 0) { builder.AppendLine("<Host Addresses>"); foreach (var addr in HostAddresses) { builder.AppendLine(addr.ToString()); } builder.AppendLine(); } if (AuthorizationData.Count > 0) { foreach (var ad in AuthorizationData) { ad.Format(builder); } builder.AppendLine(); } }
internal NtStatusResult(NtStatus status) { Status = (uint)status; Message = NtObjectUtils.GetNtStatusMessage(status); Win32Error = NtObjectUtils.MapNtStatusToDosError(status); StatusName = status.ToString(); Code = status.GetStatusCode(); CustomerCode = status.IsCustomerCode(); Reserved = status.IsReserved(); Facility = status.GetFacility(); Severity = status.GetSeverity(); }
/// <summary> /// Query the global SACL. /// </summary> /// <param name="type">The global SACL type.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The global SACL in a Security Descriptor.</returns> public static NtResult <SecurityDescriptor> QueryGlobalSacl(AuditGlobalSaclType type, bool throw_on_error) { if (!SecurityNativeMethods.AuditQueryGlobalSacl(type.ToString(), out SafeAuditBuffer buffer)) { return(NtObjectUtils.MapDosErrorToStatus().CreateResultFromError <SecurityDescriptor>(throw_on_error)); } using (buffer) { NtType nt_type = type == AuditGlobalSaclType.File ? NtType.GetTypeByType <NtFile>() : NtType.GetTypeByType <NtKey>(); return(new SecurityDescriptor(nt_type) { Sacl = new Acl(buffer.DangerousGetHandle(), false) }.CreateResult()); } }
/// <summary> /// Set the global SACL. /// </summary> /// <param name="type">The global SACL type.</param> /// <param name="security_descriptor">The SACL to set in an Security Descriptor.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The NT status code.</returns> public static NtStatus SetGlobalSacl(AuditGlobalSaclType type, SecurityDescriptor security_descriptor, bool throw_on_error) { if (!security_descriptor.SaclPresent) { throw new ArgumentException("Must specify a SACL."); } using (var buffer = security_descriptor.Sacl.ToSafeBuffer()) { if (!SecurityNativeMethods.AuditSetGlobalSacl(type.ToString(), buffer)) { return(NtObjectUtils.MapDosErrorToStatus().ToNtException(throw_on_error)); } return(NtStatus.STATUS_SUCCESS); } }
/// <summary> /// Set AppContainer Information to Context. /// </summary> /// <param name="package_sid">The package SID.</param> /// <param name="capabilities">List of capabilities.</param> /// <param name="throw_on_error">True to throw on error</param> /// <returns>The NT status code.</returns> public NtStatus SetAppContainer(Sid package_sid, IEnumerable <UserGroup> capabilities, bool throw_on_error) { using (var list = new DisposableList()) { var sid_buffer = list.AddResource(package_sid.ToSafeBuffer()); var cap_sids = capabilities?.ToArray() ?? new UserGroup[0]; SafeTokenGroupsBuffer cap_buffer = list.AddResource(SafeTokenGroupsBuffer.Create(cap_sids)); SafeBuffer buffer = cap_sids.Length > 0 ? cap_buffer.Data : SafeHGlobalBuffer.Null; if (!SecurityNativeMethods.AuthzSetAppContainerInformation(_handle, sid_buffer, cap_sids.Length, buffer)) { return(NtObjectUtils.MapDosErrorToStatus().ToNtException(throw_on_error)); } return(NtStatus.STATUS_SUCCESS); } }
private void BindInterface(Guid interface_id, Version interface_version) { var bind_msg = new AlpcMessageType <LRPC_BIND_MESSAGE>(new LRPC_BIND_MESSAGE(interface_id, interface_version)); var recv_msg = new AlpcMessageRaw(0x1000); using (var recv_attr = new AlpcReceiveMessageAttributes()) { _client.SendReceive(AlpcMessageFlags.SyncRequest, bind_msg, null, recv_msg, recv_attr, NtWaitTimeout.Infinite); using (var buffer = recv_msg.Data.ToBuffer()) { CheckForFault(buffer, LRPC_MESSAGE_TYPE.lmtBind); var value = buffer.Read <LRPC_BIND_MESSAGE>(0); if (value.RpcStatus != 0) { throw new NtException(NtObjectUtils.MapDosErrorToStatus(value.RpcStatus)); } } } }
private static NtResult <List <Sid> > GetValidUsers(bool throw_on_error) { if (!SecurityNativeMethods.AuditEnumeratePerUserPolicy(out SafeAuditBuffer buffer)) { return(NtObjectUtils.CreateResultFromDosError <List <Sid> >(throw_on_error)); } using (buffer) { List <Sid> sids = new List <Sid>(); buffer.Initialize <POLICY_AUDIT_SID_ARRAY>(1); var sid_array = buffer.Read <POLICY_AUDIT_SID_ARRAY>(0); for (int i = 0; i < sid_array.UsersCount; ++i) { sids.Add(new Sid(Marshal.ReadIntPtr(buffer.DangerousGetHandle(), i * IntPtr.Size))); } return(sids.CreateResult()); } }
internal AccessCheckResult(string name, string type_name, AccessMask granted_access, GenericMapping generic_mapping, string sddl, Type enum_type, TokenInformation token_info) { Name = name; TypeName = type_name; GrantedAccess = granted_access; GenericMapping = generic_mapping; TokenInfo = token_info; SecurityDescriptor = sddl; IsRead = generic_mapping.HasRead(granted_access); IsWrite = generic_mapping.HasWrite(granted_access); IsExecute = generic_mapping.HasExecute(granted_access); IsAll = generic_mapping.HasAll(granted_access); GrantedAccessString = NtObjectUtils.GrantedAccessAsString(granted_access, generic_mapping, enum_type, false); GrantedGenericAccessString = NtObjectUtils.GrantedAccessAsString(granted_access, generic_mapping, enum_type, true); TokenId = token_info.TokenId.ToInt64(); }
internal override void Format(StringBuilder builder) { builder.AppendLine("Checksum : GSSAPI"); builder.AppendLine($"Channel Binding : {NtObjectUtils.ToHexString(ChannelBinding)}"); builder.AppendLine($"Context Flags : {ContextFlags}"); if (Credentials != null) { builder.AppendLine($"Delegate Opt ID : {DelegationOptionIdentifier}"); builder.AppendLine(Credentials.Format()); } if (Extensions != null) { HexDumpBuilder hex = new HexDumpBuilder(false, true, true, false, 0); hex.Append(Extensions); hex.Complete(); builder.AppendLine(hex.ToString()); } }
private bool DecryptRC4WithKey(KerberosKey key, RC4KeyUsage key_usage, out byte[] decrypted) { HMACMD5 hmac = new HMACMD5(key.Key); byte[] key1 = hmac.ComputeHash(BitConverter.GetBytes((int)key_usage)); hmac = new HMACMD5(key1); byte[] checksum = new byte[16]; Buffer.BlockCopy(CipherText, 0, checksum, 0, checksum.Length); byte[] key2 = hmac.ComputeHash(checksum); byte[] result = ARC4.Transform(CipherText, 16, CipherText.Length - 16, key2); hmac = new HMACMD5(key1); byte[] calculated_checksum = hmac.ComputeHash(result); decrypted = new byte[result.Length - 8]; Buffer.BlockCopy(result, 8, decrypted, 0, decrypted.Length); return(NtObjectUtils.EqualByteArray(checksum, calculated_checksum)); }
/// <summary> /// Process record. /// </summary> protected override void ProcessRecord() { if (ParameterSetName == "FromStatus") { if (PassStatus) { WriteObject(NtObjectUtils.ConvertIntToNtStatus(Status)); } else { WriteObject(new NtStatusResult(Status)); } } else if (ParameterSetName == "FromName") { var result = GetAllStatus().Where(s => s.ToString().Equals(Name, StringComparison.OrdinalIgnoreCase)); if (!result.Any()) { throw new ArgumentException($"Can't find status with name {Name}"); } var status = result.First(); if (PassStatus) { WriteObject(status); } else { WriteObject(new NtStatusResult(status)); } } else { var status = GetAllStatus(); if (PassStatus) { WriteObject(status, true); } else { WriteObject(GetAllStatus().Select(s => new NtStatusResult(s)), true); } } }
internal override string Format() { StringBuilder builder = new StringBuilder(); if (!string.IsNullOrEmpty(ClientTime)) { builder.AppendLine($"Client Time : {KerberosUtils.ParseKerberosTime(ClientTime, ClientUSec)}"); } if (SubKey != null) { builder.AppendLine("<Sub Session Key>"); builder.AppendLine($"Encryption Type : {SubKey.KeyEncryption}"); builder.AppendLine($"Encryption Key : {NtObjectUtils.ToHexString(SubKey.Key)}"); } if (SequenceNumber.HasValue) { builder.AppendLine($"Sequence Number : 0x{SequenceNumber:X}"); } return(builder.ToString()); }
/// <summary> /// Format the authentication token. /// </summary> /// <returns>The token as a formatted string.</returns> public override string Format() { StringBuilder builder = new StringBuilder(); builder.AppendLine($"<SPNEGO {(this is NegotiateInitAuthenticationToken ? "Init" : "Response")}>"); FormatData(builder); if (MessageIntegrityCode?.Length > 0) { builder.AppendLine($"MIC : {NtObjectUtils.ToHexString(MessageIntegrityCode)}"); } string token_format = Token?.Format(); if (!string.IsNullOrWhiteSpace(token_format)) { builder.AppendLine("<SPNEGO Token>"); builder.AppendLine(token_format.TrimEnd()); builder.AppendLine("</SPNEGO Token>"); } return(builder.ToString()); }
/// <summary> /// ToString Method. /// </summary> /// <returns>The formatted string.</returns> public override string ToString() { switch (AddressType) { case KerberosHostAddressType.IPv4: if (Address.Length == 4) { return($"IPv4: {new IPAddress(Address)}"); } break; case KerberosHostAddressType.IPv6: if (Address.Length == 16) { return($"IPv6: {new IPAddress(Address)}"); } break; } return($"{AddressType} - {NtObjectUtils.ToHexString(Address)}"); }