| | 1 | | using System; |
| | 2 | | using System.Security.Principal; |
| | 3 | | using System.Threading; |
| | 4 | | using System.Threading.Tasks; |
| | 5 | | using SharpHoundRPC.NetAPINative; |
| | 6 | |
|
| | 7 | | namespace SharpHoundRPC |
| | 8 | | { |
| | 9 | | public static class Extensions |
| | 10 | | { |
| | 11 | | public static bool IsError(this NtStatus status) |
| 0 | 12 | | { |
| 0 | 13 | | if (status != NtStatus.StatusSuccess && status != NtStatus.StatusMoreEntries && |
| 0 | 14 | | status != NtStatus.StatusSomeMapped && status != NtStatus.StatusNoMoreEntries) |
| 0 | 15 | | return true; |
| | 16 | |
|
| 0 | 17 | | return false; |
| 0 | 18 | | } |
| | 19 | |
|
| | 20 | | /// <summary> |
| | 21 | | /// Gets the relative identifier for a SID |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="securityIdentifier"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public static int Rid(this SecurityIdentifier securityIdentifier) |
| 0 | 26 | | { |
| 0 | 27 | | var value = securityIdentifier.Value; |
| 0 | 28 | | var rid = int.Parse(value.Substring(value.LastIndexOf("-", StringComparison.Ordinal) + 1)); |
| 0 | 29 | | return rid; |
| 0 | 30 | | } |
| | 31 | |
|
| | 32 | | public static byte[] GetBytes(this SecurityIdentifier identifier) |
| 1 | 33 | | { |
| 1 | 34 | | var bytes = new byte[identifier.BinaryLength]; |
| 1 | 35 | | identifier.GetBinaryForm(bytes, 0); |
| 1 | 36 | | return bytes; |
| 1 | 37 | | } |
| | 38 | |
|
| 30 | 39 | | public static async Task<Result<T>> TimeoutAfter<T>(this Task<Result<T>> task, TimeSpan timeout) { |
| | 40 | |
|
| 60 | 41 | | using (var timeoutCancellationTokenSource = new CancellationTokenSource()) { |
| | 42 | |
|
| 30 | 43 | | var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token)); |
| 58 | 44 | | if (completedTask == task) { |
| 28 | 45 | | timeoutCancellationTokenSource.Cancel(); |
| 28 | 46 | | return await task; // Very important in order to propagate exceptions |
| | 47 | | } |
| | 48 | |
|
| 2 | 49 | | var result = Result<T>.Fail("Timeout"); |
| 2 | 50 | | result.IsTimeout = true; |
| 2 | 51 | | return result; |
| | 52 | | } |
| 30 | 53 | | } |
| | 54 | |
|
| 10 | 55 | | public static async Task<NetAPIResult<T>> TimeoutAfter<T>(this Task<NetAPIResult<T>> task, TimeSpan timeout) { |
| | 56 | |
|
| 20 | 57 | | using (var timeoutCancellationTokenSource = new CancellationTokenSource()) { |
| | 58 | |
|
| 10 | 59 | | var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token)); |
| 18 | 60 | | if (completedTask == task) { |
| 8 | 61 | | timeoutCancellationTokenSource.Cancel(); |
| 8 | 62 | | return await task; // Very important in order to propagate exceptions |
| | 63 | | } |
| | 64 | |
|
| 2 | 65 | | var result = NetAPIResult<T>.Fail("Timeout"); |
| 2 | 66 | | return result; |
| | 67 | | } |
| 10 | 68 | | } |
| | 69 | | } |
| | 70 | | } |