| 1 | + | using Microsoft.Win32.SafeHandles; |
| 2 | + | using Minidump.Decryptor; |
| 3 | + | using System; |
| 4 | + | using System.Linq; |
| 5 | + | using System.Runtime.ConstrainedExecution; |
| 6 | + | using System.Runtime.InteropServices; |
| 7 | + | using System.Security; |
| 8 | + | |
| 9 | + | namespace Minidump.Crypto |
| 10 | + | { |
| 11 | + | #pragma warning disable 618 |
| 12 | + | |
| 13 | + | [SecurityCritical(SecurityCriticalScope.Everything)] |
| 14 | + | #pragma warning restore 618 |
| 15 | + | public sealed class SafeBCryptAlgorithmHandle : SafeHandleZeroOrMinusOneIsInvalid |
| 16 | + | { |
| 17 | + | private SafeBCryptAlgorithmHandle() : base(true) |
| 18 | + | { |
| 19 | + | } |
| 20 | + | |
| 21 | + | protected override bool ReleaseHandle() |
| 22 | + | { |
| 23 | + | return (NTStatus)BCrypt.BCryptCloseAlgorithmProvider(handle, 0) == NTStatus.Success; |
| 24 | + | } |
| 25 | + | } |
| 26 | + | |
| 27 | + | [SecuritySafeCritical] |
| 28 | + | public sealed class SafeBCryptKeyHandle : SafeHandleZeroOrMinusOneIsInvalid |
| 29 | + | { |
| 30 | + | internal SafeBCryptKeyHandle() : base(true) |
| 31 | + | { |
| 32 | + | } |
| 33 | + | |
| 34 | + | [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] |
| 35 | + | protected override bool ReleaseHandle() |
| 36 | + | { |
| 37 | + | return (NTStatus)BCrypt.BCryptDestroyKey(handle) == NTStatus.Success; |
| 38 | + | } |
| 39 | + | } |
| 40 | + | |
| 41 | + | public enum NTStatus : uint |
| 42 | + | { |
| 43 | + | Success = 0x00000000, |
| 44 | + | Wait0 = 0x00000000, |
| 45 | + | Wait1 = 0x00000001, |
| 46 | + | Wait2 = 0x00000002, |
| 47 | + | Wait3 = 0x00000003, |
| 48 | + | Wait63 = 0x0000003f, |
| 49 | + | Abandoned = 0x00000080, |
| 50 | + | AbandonedWait0 = 0x00000080, |
| 51 | + | AbandonedWait1 = 0x00000081, |
| 52 | + | AbandonedWait2 = 0x00000082, |
| 53 | + | AbandonedWait3 = 0x00000083, |
| 54 | + | AbandonedWait63 = 0x000000bf, |
| 55 | + | UserApc = 0x000000c0, |
| 56 | + | KernelApc = 0x00000100, |
| 57 | + | Alerted = 0x00000101, |
| 58 | + | Timeout = 0x00000102, |
| 59 | + | Pending = 0x00000103, |
| 60 | + | Reparse = 0x00000104, |
| 61 | + | MoreEntries = 0x00000105, |
| 62 | + | NotAllAssigned = 0x00000106, |
| 63 | + | SomeNotMapped = 0x00000107, |
| 64 | + | OpLockBreakInProgress = 0x00000108, |
| 65 | + | VolumeMounted = 0x00000109, |
| 66 | + | RxActCommitted = 0x0000010a, |
| 67 | + | NotifyCleanup = 0x0000010b, |
| 68 | + | NotifyEnumDir = 0x0000010c, |
| 69 | + | NoQuotasForAccount = 0x0000010d, |
| 70 | + | PrimaryTransportConnectFailed = 0x0000010e, |
| 71 | + | PageFaultTransition = 0x00000110, |
| 72 | + | PageFaultDemandZero = 0x00000111, |
| 73 | + | PageFaultCopyOnWrite = 0x00000112, |
| 74 | + | PageFaultGuardPage = 0x00000113, |
| 75 | + | PageFaultPagingFile = 0x00000114, |
| 76 | + | CrashDump = 0x00000116, |
| 77 | + | ReparseObject = 0x00000118, |
| 78 | + | NothingToTerminate = 0x00000122, |
| 79 | + | ProcessNotInJob = 0x00000123, |
| 80 | + | ProcessInJob = 0x00000124, |
| 81 | + | ProcessCloned = 0x00000129, |
| 82 | + | ProcessIsTerminating = 0xC000010A, |
| 83 | + | FileLockedWithOnlyReaders = 0x0000012a, |
| 84 | + | FileLockedWithWriters = 0x0000012b, |
| 85 | + | |
| 86 | + | Informational = 0x40000000, |
| 87 | + | ObjectNameExists = 0x40000000, |
| 88 | + | ThreadWasSuspended = 0x40000001, |
| 89 | + | WorkingSetLimitRange = 0x40000002, |
| 90 | + | ImageNotAtBase = 0x40000003, |
| 91 | + | RegistryRecovered = 0x40000009, |
| 92 | + | |
| 93 | + | Warning = 0x80000000, |
| 94 | + | GuardPageViolation = 0x80000001, |
| 95 | + | DatatypeMisalignment = 0x80000002, |
| 96 | + | Breakpoint = 0x80000003, |
| 97 | + | SingleStep = 0x80000004, |
| 98 | + | BufferOverflow = 0x80000005, |
| 99 | + | NoMoreFiles = 0x80000006, |
| 100 | + | HandlesClosed = 0x8000000a, |
| 101 | + | PartialCopy = 0x8000000d, |
| 102 | + | DeviceBusy = 0x80000011, |
| 103 | + | InvalidEaName = 0x80000013, |
| 104 | + | EaListInconsistent = 0x80000014, |
| 105 | + | NoMoreEntries = 0x8000001a, |
| 106 | + | LongJump = 0x80000026, |
| 107 | + | DllMightBeInsecure = 0x8000002b, |
| 108 | + | |
| 109 | + | Error = 0xc0000000, |
| 110 | + | Unsuccessful = 0xc0000001, |
| 111 | + | NotImplemented = 0xc0000002, |
| 112 | + | InvalidInfoClass = 0xc0000003, |
| 113 | + | InfoLengthMismatch = 0xc0000004, |
| 114 | + | AccessViolation = 0xc0000005, |
| 115 | + | InPageError = 0xc0000006, |
| 116 | + | PagefileQuota = 0xc0000007, |
| 117 | + | InvalidHandle = 0xc0000008, |
| 118 | + | BadInitialStack = 0xc0000009, |
| 119 | + | BadInitialPc = 0xc000000a, |
| 120 | + | InvalidCid = 0xc000000b, |
| 121 | + | TimerNotCanceled = 0xc000000c, |
| 122 | + | InvalidParameter = 0xc000000d, |
| 123 | + | NoSuchDevice = 0xc000000e, |
| 124 | + | NoSuchFile = 0xc000000f, |
| 125 | + | InvalidDeviceRequest = 0xc0000010, |
| 126 | + | EndOfFile = 0xc0000011, |
| 127 | + | WrongVolume = 0xc0000012, |
| 128 | + | NoMediaInDevice = 0xc0000013, |
| 129 | + | NoMemory = 0xc0000017, |
| 130 | + | ConflictingAddresses = 0xc0000018, |
| 131 | + | NotMappedView = 0xc0000019, |
| 132 | + | UnableToFreeVm = 0xc000001a, |
| 133 | + | UnableToDeleteSection = 0xc000001b, |
| 134 | + | IllegalInstruction = 0xc000001d, |
| 135 | + | AlreadyCommitted = 0xc0000021, |
| 136 | + | AccessDenied = 0xc0000022, |
| 137 | + | BufferTooSmall = 0xc0000023, |
| 138 | + | InsufficientBuffer = 0x7a, |
| 139 | + | ObjectTypeMismatch = 0xc0000024, |
| 140 | + | NonContinuableException = 0xc0000025, |
| 141 | + | BadStack = 0xc0000028, |
| 142 | + | NotLocked = 0xc000002a, |
| 143 | + | NotCommitted = 0xc000002d, |
| 144 | + | InvalidParameterMix = 0xc0000030, |
| 145 | + | ObjectNameInvalid = 0xc0000033, |
| 146 | + | ObjectNameNotFound = 0xc0000034, |
| 147 | + | ObjectNameCollision = 0xc0000035, |
| 148 | + | ObjectPathInvalid = 0xc0000039, |
| 149 | + | ObjectPathNotFound = 0xc000003a, |
| 150 | + | ObjectPathSyntaxBad = 0xc000003b, |
| 151 | + | DataOverrun = 0xc000003c, |
| 152 | + | DataLate = 0xc000003d, |
| 153 | + | DataError = 0xc000003e, |
| 154 | + | CrcError = 0xc000003f, |
| 155 | + | SectionTooBig = 0xc0000040, |
| 156 | + | PortConnectionRefused = 0xc0000041, |
| 157 | + | InvalidPortHandle = 0xc0000042, |
| 158 | + | SharingViolation = 0xc0000043, |
| 159 | + | QuotaExceeded = 0xc0000044, |
| 160 | + | InvalidPageProtection = 0xc0000045, |
| 161 | + | MutantNotOwned = 0xc0000046, |
| 162 | + | SemaphoreLimitExceeded = 0xc0000047, |
| 163 | + | PortAlreadySet = 0xc0000048, |
| 164 | + | SectionNotImage = 0xc0000049, |
| 165 | + | SuspendCountExceeded = 0xc000004a, |
| 166 | + | ThreadIsTerminating = 0xc000004b, |
| 167 | + | BadWorkingSetLimit = 0xc000004c, |
| 168 | + | IncompatibleFileMap = 0xc000004d, |
| 169 | + | SectionProtection = 0xc000004e, |
| 170 | + | EasNotSupported = 0xc000004f, |
| 171 | + | EaTooLarge = 0xc0000050, |
| 172 | + | NonExistentEaEntry = 0xc0000051, |
| 173 | + | NoEasOnFile = 0xc0000052, |
| 174 | + | EaCorruptError = 0xc0000053, |
| 175 | + | FileLockConflict = 0xc0000054, |
| 176 | + | LockNotGranted = 0xc0000055, |
| 177 | + | DeletePending = 0xc0000056, |
| 178 | + | CtlFileNotSupported = 0xc0000057, |
| 179 | + | UnknownRevision = 0xc0000058, |
| 180 | + | RevisionMismatch = 0xc0000059, |
| 181 | + | InvalidOwner = 0xc000005a, |
| 182 | + | InvalidPrimaryGroup = 0xc000005b, |
| 183 | + | NoImpersonationToken = 0xc000005c, |
| 184 | + | CantDisableMandatory = 0xc000005d, |
| 185 | + | NoLogonServers = 0xc000005e, |
| 186 | + | NoSuchLogonSession = 0xc000005f, |
| 187 | + | NoSuchPrivilege = 0xc0000060, |
| 188 | + | PrivilegeNotHeld = 0xc0000061, |
| 189 | + | InvalidAccountName = 0xc0000062, |
| 190 | + | UserExists = 0xc0000063, |
| 191 | + | NoSuchUser = 0xc0000064, |
| 192 | + | GroupExists = 0xc0000065, |
| 193 | + | NoSuchGroup = 0xc0000066, |
| 194 | + | MemberInGroup = 0xc0000067, |
| 195 | + | MemberNotInGroup = 0xc0000068, |
| 196 | + | LastAdmin = 0xc0000069, |
| 197 | + | WrongPassword = 0xc000006a, |
| 198 | + | IllFormedPassword = 0xc000006b, |
| 199 | + | PasswordRestriction = 0xc000006c, |
| 200 | + | LogonFailure = 0xc000006d, |
| 201 | + | AccountRestriction = 0xc000006e, |
| 202 | + | InvalidLogonHours = 0xc000006f, |
| 203 | + | InvalidWorkstation = 0xc0000070, |
| 204 | + | PasswordExpired = 0xc0000071, |
| 205 | + | AccountDisabled = 0xc0000072, |
| 206 | + | NoneMapped = 0xc0000073, |
| 207 | + | TooManyLuidsRequested = 0xc0000074, |
| 208 | + | LuidsExhausted = 0xc0000075, |
| 209 | + | InvalidSubAuthority = 0xc0000076, |
| 210 | + | InvalidAcl = 0xc0000077, |
| 211 | + | InvalidSid = 0xc0000078, |
| 212 | + | InvalidSecurityDescr = 0xc0000079, |
| 213 | + | ProcedureNotFound = 0xc000007a, |
| 214 | + | InvalidImageFormat = 0xc000007b, |
| 215 | + | NoToken = 0xc000007c, |
| 216 | + | BadInheritanceAcl = 0xc000007d, |
| 217 | + | RangeNotLocked = 0xc000007e, |
| 218 | + | DiskFull = 0xc000007f, |
| 219 | + | ServerDisabled = 0xc0000080, |
| 220 | + | ServerNotDisabled = 0xc0000081, |
| 221 | + | TooManyGuidsRequested = 0xc0000082, |
| 222 | + | GuidsExhausted = 0xc0000083, |
| 223 | + | InvalidIdAuthority = 0xc0000084, |
| 224 | + | AgentsExhausted = 0xc0000085, |
| 225 | + | InvalidVolumeLabel = 0xc0000086, |
| 226 | + | SectionNotExtended = 0xc0000087, |
| 227 | + | NotMappedData = 0xc0000088, |
| 228 | + | ResourceDataNotFound = 0xc0000089, |
| 229 | + | ResourceTypeNotFound = 0xc000008a, |
| 230 | + | ResourceNameNotFound = 0xc000008b, |
| 231 | + | ArrayBoundsExceeded = 0xc000008c, |
| 232 | + | FloatDenormalOperand = 0xc000008d, |
| 233 | + | FloatDivideByZero = 0xc000008e, |
| 234 | + | FloatInexactResult = 0xc000008f, |
| 235 | + | FloatInvalidOperation = 0xc0000090, |
| 236 | + | FloatOverflow = 0xc0000091, |
| 237 | + | FloatStackCheck = 0xc0000092, |
| 238 | + | FloatUnderflow = 0xc0000093, |
| 239 | + | IntegerDivideByZero = 0xc0000094, |
| 240 | + | IntegerOverflow = 0xc0000095, |
| 241 | + | PrivilegedInstruction = 0xc0000096, |
| 242 | + | TooManyPagingFiles = 0xc0000097, |
| 243 | + | FileInvalid = 0xc0000098, |
| 244 | + | InstanceNotAvailable = 0xc00000ab, |
| 245 | + | PipeNotAvailable = 0xc00000ac, |
| 246 | + | InvalidPipeState = 0xc00000ad, |
| 247 | + | PipeBusy = 0xc00000ae, |
| 248 | + | IllegalFunction = 0xc00000af, |
| 249 | + | PipeDisconnected = 0xc00000b0, |
| 250 | + | PipeClosing = 0xc00000b1, |
| 251 | + | PipeConnected = 0xc00000b2, |
| 252 | + | PipeListening = 0xc00000b3, |
| 253 | + | InvalidReadMode = 0xc00000b4, |
| 254 | + | IoTimeout = 0xc00000b5, |
| 255 | + | FileForcedClosed = 0xc00000b6, |
| 256 | + | ProfilingNotStarted = 0xc00000b7, |
| 257 | + | ProfilingNotStopped = 0xc00000b8, |
| 258 | + | NotSameDevice = 0xc00000d4, |
| 259 | + | FileRenamed = 0xc00000d5, |
| 260 | + | CantWait = 0xc00000d8, |
| 261 | + | PipeEmpty = 0xc00000d9, |
| 262 | + | CantTerminateSelf = 0xc00000db, |
| 263 | + | InternalError = 0xc00000e5, |
| 264 | + | InvalidParameter1 = 0xc00000ef, |
| 265 | + | InvalidParameter2 = 0xc00000f0, |
| 266 | + | InvalidParameter3 = 0xc00000f1, |
| 267 | + | InvalidParameter4 = 0xc00000f2, |
| 268 | + | InvalidParameter5 = 0xc00000f3, |
| 269 | + | InvalidParameter6 = 0xc00000f4, |
| 270 | + | InvalidParameter7 = 0xc00000f5, |
| 271 | + | InvalidParameter8 = 0xc00000f6, |
| 272 | + | InvalidParameter9 = 0xc00000f7, |
| 273 | + | InvalidParameter10 = 0xc00000f8, |
| 274 | + | InvalidParameter11 = 0xc00000f9, |
| 275 | + | InvalidParameter12 = 0xc00000fa, |
| 276 | + | MappedFileSizeZero = 0xc000011e, |
| 277 | + | TooManyOpenedFiles = 0xc000011f, |
| 278 | + | Cancelled = 0xc0000120, |
| 279 | + | CannotDelete = 0xc0000121, |
| 280 | + | InvalidComputerName = 0xc0000122, |
| 281 | + | FileDeleted = 0xc0000123, |
| 282 | + | SpecialAccount = 0xc0000124, |
| 283 | + | SpecialGroup = 0xc0000125, |
| 284 | + | SpecialUser = 0xc0000126, |
| 285 | + | MembersPrimaryGroup = 0xc0000127, |
| 286 | + | FileClosed = 0xc0000128, |
| 287 | + | TooManyThreads = 0xc0000129, |
| 288 | + | ThreadNotInProcess = 0xc000012a, |
| 289 | + | TokenAlreadyInUse = 0xc000012b, |
| 290 | + | PagefileQuotaExceeded = 0xc000012c, |
| 291 | + | CommitmentLimit = 0xc000012d, |
| 292 | + | InvalidImageLeFormat = 0xc000012e, |
| 293 | + | InvalidImageNotMz = 0xc000012f, |
| 294 | + | InvalidImageProtect = 0xc0000130, |
| 295 | + | InvalidImageWin16 = 0xc0000131, |
| 296 | + | LogonServer = 0xc0000132, |
| 297 | + | DifferenceAtDc = 0xc0000133, |
| 298 | + | SynchronizationRequired = 0xc0000134, |
| 299 | + | DllNotFound = 0xc0000135, |
| 300 | + | IoPrivilegeFailed = 0xc0000137, |
| 301 | + | OrdinalNotFound = 0xc0000138, |
| 302 | + | EntryPointNotFound = 0xc0000139, |
| 303 | + | ControlCExit = 0xc000013a, |
| 304 | + | PortNotSet = 0xc0000353, |
| 305 | + | DebuggerInactive = 0xc0000354, |
| 306 | + | CallbackBypass = 0xc0000503, |
| 307 | + | PortClosed = 0xc0000700, |
| 308 | + | MessageLost = 0xc0000701, |
| 309 | + | InvalidMessage = 0xc0000702, |
| 310 | + | RequestCanceled = 0xc0000703, |
| 311 | + | RecursiveDispatch = 0xc0000704, |
| 312 | + | LpcReceiveBufferExpected = 0xc0000705, |
| 313 | + | LpcInvalidConnectionUsage = 0xc0000706, |
| 314 | + | LpcRequestsNotAllowed = 0xc0000707, |
| 315 | + | ResourceInUse = 0xc0000708, |
| 316 | + | ProcessIsProtected = 0xc0000712, |
| 317 | + | VolumeDirty = 0xc0000806, |
| 318 | + | FileCheckedOut = 0xc0000901, |
| 319 | + | CheckOutRequired = 0xc0000902, |
| 320 | + | BadFileType = 0xc0000903, |
| 321 | + | FileTooLarge = 0xc0000904, |
| 322 | + | FormsAuthRequired = 0xc0000905, |
| 323 | + | VirusInfected = 0xc0000906, |
| 324 | + | VirusDeleted = 0xc0000907, |
| 325 | + | TransactionalConflict = 0xc0190001, |
| 326 | + | InvalidTransaction = 0xc0190002, |
| 327 | + | TransactionNotActive = 0xc0190003, |
| 328 | + | TmInitializationFailed = 0xc0190004, |
| 329 | + | RmNotActive = 0xc0190005, |
| 330 | + | RmMetadataCorrupt = 0xc0190006, |
| 331 | + | TransactionNotJoined = 0xc0190007, |
| 332 | + | DirectoryNotRm = 0xc0190008, |
| 333 | + | CouldNotResizeLog = 0xc0190009, |
| 334 | + | TransactionsUnsupportedRemote = 0xc019000a, |
| 335 | + | LogResizeInvalidSize = 0xc019000b, |
| 336 | + | RemoteFileVersionMismatch = 0xc019000c, |
| 337 | + | CrmProtocolAlreadyExists = 0xc019000f, |
| 338 | + | TransactionPropagationFailed = 0xc0190010, |
| 339 | + | CrmProtocolNotFound = 0xc0190011, |
| 340 | + | TransactionSuperiorExists = 0xc0190012, |
| 341 | + | TransactionRequestNotValid = 0xc0190013, |
| 342 | + | TransactionNotRequested = 0xc0190014, |
| 343 | + | TransactionAlreadyAborted = 0xc0190015, |
| 344 | + | TransactionAlreadyCommitted = 0xc0190016, |
| 345 | + | TransactionInvalidMarshallBuffer = 0xc0190017, |
| 346 | + | CurrentTransactionNotValid = 0xc0190018, |
| 347 | + | LogGrowthFailed = 0xc0190019, |
| 348 | + | ObjectNoLongerExists = 0xc0190021, |
| 349 | + | StreamMiniversionNotFound = 0xc0190022, |
| 350 | + | StreamMiniversionNotValid = 0xc0190023, |
| 351 | + | MiniversionInaccessibleFromSpecifiedTransaction = 0xc0190024, |
| 352 | + | CantOpenMiniversionWithModifyIntent = 0xc0190025, |
| 353 | + | CantCreateMoreStreamMiniversions = 0xc0190026, |
| 354 | + | HandleNoLongerValid = 0xc0190028, |
| 355 | + | NoTxfMetadata = 0xc0190029, |
| 356 | + | LogCorruptionDetected = 0xc0190030, |
| 357 | + | CantRecoverWithHandleOpen = 0xc0190031, |
| 358 | + | RmDisconnected = 0xc0190032, |
| 359 | + | EnlistmentNotSuperior = 0xc0190033, |
| 360 | + | RecoveryNotNeeded = 0xc0190034, |
| 361 | + | RmAlreadyStarted = 0xc0190035, |
| 362 | + | FileIdentityNotPersistent = 0xc0190036, |
| 363 | + | CantBreakTransactionalDependency = 0xc0190037, |
| 364 | + | CantCrossRmBoundary = 0xc0190038, |
| 365 | + | TxfDirNotEmpty = 0xc0190039, |
| 366 | + | IndoubtTransactionsExist = 0xc019003a, |
| 367 | + | TmVolatile = 0xc019003b, |
| 368 | + | RollbackTimerExpired = 0xc019003c, |
| 369 | + | TxfAttributeCorrupt = 0xc019003d, |
| 370 | + | EfsNotAllowedInTransaction = 0xc019003e, |
| 371 | + | TransactionalOpenNotAllowed = 0xc019003f, |
| 372 | + | TransactedMappingUnsupportedRemote = 0xc0190040, |
| 373 | + | TxfMetadataAlreadyPresent = 0xc0190041, |
| 374 | + | TransactionScopeCallbacksNotSet = 0xc0190042, |
| 375 | + | TransactionRequiredPromotion = 0xc0190043, |
| 376 | + | CannotExecuteFileInTransaction = 0xc0190044, |
| 377 | + | TransactionsNotFrozen = 0xc0190045, |
| 378 | + | |
| 379 | + | MaximumNtStatus = 0xffffffff |
| 380 | + | } |
| 381 | + | |
| 382 | + | [StructLayout(LayoutKind.Sequential)] |
| 383 | + | public struct BCRYPT_ALG_HANDLE |
| 384 | + | { |
| 385 | + | private IntPtr handle; |
| 386 | + | |
| 387 | + | /// <summary>Initializes a new instance of the <see cref="BCRYPT_ALG_HANDLE"/> struct.</summary> |
| 388 | + | /// <param name="preexistingHandle">An <see cref="IntPtr"/> object that represents the pre-existing handle to use.</param> |
| 389 | + | public BCRYPT_ALG_HANDLE(IntPtr preexistingHandle) => handle = preexistingHandle; |
| 390 | + | |
| 391 | + | /// <summary>Returns an invalid handle by instantiating a <see cref="BCRYPT_ALG_HANDLE"/> object with <see cref="IntPtr.Zero"/>.</summary> |
| 392 | + | public static BCRYPT_ALG_HANDLE NULL => new BCRYPT_ALG_HANDLE(IntPtr.Zero); |
| 393 | + | |
| 394 | + | /// <summary>Gets a value indicating whether this instance is a null handle.</summary> |
| 395 | + | public bool IsNull => handle == IntPtr.Zero; |
| 396 | + | |
| 397 | + | /// <summary>Performs an explicit conversion from <see cref="BCRYPT_ALG_HANDLE"/> to <see cref="IntPtr"/>.</summary> |
| 398 | + | /// <param name="h">The handle.</param> |
| 399 | + | /// <returns>The result of the conversion.</returns> |
| 400 | + | public static explicit operator IntPtr(BCRYPT_ALG_HANDLE h) => h.handle; |
| 401 | + | |
| 402 | + | /// <summary>Performs an implicit conversion from <see cref="IntPtr"/> to <see cref="BCRYPT_ALG_HANDLE"/>.</summary> |
| 403 | + | /// <param name="h">The pointer to a handle.</param> |
| 404 | + | /// <returns>The result of the conversion.</returns> |
| 405 | + | public static implicit operator BCRYPT_ALG_HANDLE(IntPtr h) => new BCRYPT_ALG_HANDLE(h); |
| 406 | + | |
| 407 | + | /// <summary>Implements the operator !=.</summary> |
| 408 | + | /// <param name="h1">The first handle.</param> |
| 409 | + | /// <param name="h2">The second handle.</param> |
| 410 | + | /// <returns>The result of the operator.</returns> |
| 411 | + | public static bool operator !=(BCRYPT_ALG_HANDLE h1, BCRYPT_ALG_HANDLE h2) => !(h1 == h2); |
| 412 | + | |
| 413 | + | /// <summary>Implements the operator ==.</summary> |
| 414 | + | /// <param name="h1">The first handle.</param> |
| 415 | + | /// <param name="h2">The second handle.</param> |
| 416 | + | /// <returns>The result of the operator.</returns> |
| 417 | + | public static bool operator ==(BCRYPT_ALG_HANDLE h1, BCRYPT_ALG_HANDLE h2) => h1.Equals(h2); |
| 418 | + | |
| 419 | + | /// <inheritdoc/> |
| 420 | + | public override bool Equals(object obj) => obj is BCRYPT_ALG_HANDLE h ? handle == h.handle : false; |
| 421 | + | |
| 422 | + | /// <inheritdoc/> |
| 423 | + | public override int GetHashCode() => handle.GetHashCode(); |
| 424 | + | |
| 425 | + | /// <inheritdoc/> |
| 426 | + | public IntPtr DangerousGetHandle() => handle; |
| 427 | + | } |
| 428 | + | |
| 429 | + | [StructLayout(LayoutKind.Sequential)] |
| 430 | + | public struct BCRYPT_KEY_HANDLE |
| 431 | + | { |
| 432 | + | private IntPtr handle; |
| 433 | + | |
| 434 | + | /// <summary>Initializes a new instance of the <see cref="BCRYPT_KEY_HANDLE"/> struct.</summary> |
| 435 | + | /// <param name="preexistingHandle">An <see cref="IntPtr"/> object that represents the pre-existing handle to use.</param> |
| 436 | + | public BCRYPT_KEY_HANDLE(IntPtr preexistingHandle) => handle = preexistingHandle; |
| 437 | + | |
| 438 | + | /// <summary>Returns an invalid handle by instantiating a <see cref="BCRYPT_KEY_HANDLE"/> object with <see cref="IntPtr.Zero"/>.</summary> |
| 439 | + | public static BCRYPT_KEY_HANDLE NULL => new BCRYPT_KEY_HANDLE(IntPtr.Zero); |
| 440 | + | |
| 441 | + | /// <summary>Gets a value indicating whether this instance is a null handle.</summary> |
| 442 | + | public bool IsNull => handle == IntPtr.Zero; |
| 443 | + | |
| 444 | + | /// <summary>Performs an explicit conversion from <see cref="BCRYPT_KEY_HANDLE"/> to <see cref="IntPtr"/>.</summary> |
| 445 | + | /// <param name="h">The handle.</param> |
| 446 | + | /// <returns>The result of the conversion.</returns> |
| 447 | + | public static explicit operator IntPtr(BCRYPT_KEY_HANDLE h) => h.handle; |
| 448 | + | |
| 449 | + | /// <summary>Performs an implicit conversion from <see cref="IntPtr"/> to <see cref="BCRYPT_KEY_HANDLE"/>.</summary> |
| 450 | + | /// <param name="h">The pointer to a handle.</param> |
| 451 | + | /// <returns>The result of the conversion.</returns> |
| 452 | + | public static implicit operator BCRYPT_KEY_HANDLE(IntPtr h) => new BCRYPT_KEY_HANDLE(h); |
| 453 | + | |
| 454 | + | /// <summary>Implements the operator !=.</summary> |
| 455 | + | /// <param name="h1">The first handle.</param> |
| 456 | + | /// <param name="h2">The second handle.</param> |
| 457 | + | /// <returns>The result of the operator.</returns> |
| 458 | + | public static bool operator !=(BCRYPT_KEY_HANDLE h1, BCRYPT_KEY_HANDLE h2) => !(h1 == h2); |
| 459 | + | |
| 460 | + | /// <summary>Implements the operator ==.</summary> |
| 461 | + | /// <param name="h1">The first handle.</param> |
| 462 | + | /// <param name="h2">The second handle.</param> |
| 463 | + | /// <returns>The result of the operator.</returns> |
| 464 | + | public static bool operator ==(BCRYPT_KEY_HANDLE h1, BCRYPT_KEY_HANDLE h2) => h1.Equals(h2); |
| 465 | + | |
| 466 | + | /// <inheritdoc/> |
| 467 | + | public override bool Equals(object obj) => obj is BCRYPT_KEY_HANDLE h ? handle == h.handle : false; |
| 468 | + | |
| 469 | + | /// <inheritdoc/> |
| 470 | + | public override int GetHashCode() => handle.GetHashCode(); |
| 471 | + | |
| 472 | + | /// <inheritdoc/> |
| 473 | + | public IntPtr DangerousGetHandle() => handle; |
| 474 | + | } |
| 475 | + | |
| 476 | + | internal class BCrypt |
| 477 | + | { |
| 478 | + | [DllImport("bcrypt", CharSet = CharSet.Auto, SetLastError = true)] |
| 479 | + | public static extern NTStatus BCryptCloseAlgorithmProvider(BCRYPT_ALG_HANDLE hAlgorithm, uint dwFlags = 0); |
| 480 | + | |
| 481 | + | [DllImport("bcrypt", CharSet = CharSet.Auto, SetLastError = true)] |
| 482 | + | public static extern NTStatus BCryptDestroyKey(BCRYPT_KEY_HANDLE hKey); |
| 483 | + | |
| 484 | + | [DllImport("bcrypt", CharSet = CharSet.Auto, SetLastError = true)] |
| 485 | + | public static extern NTStatus BCryptDecrypt(SafeBCryptKeyHandle hKey, IntPtr pbInput, int cbInput, IntPtr pPaddingInfo, IntPtr pbIV, int cbIV, [Optional] IntPtr pbOutput, [Optional] int cbOutput, out int pcbResult, int dwFlags); |
| 486 | + | |
| 487 | + | [DllImport("bcrypt", CharSet = CharSet.Auto, SetLastError = true)] |
| 488 | + | public static extern NTStatus BCryptOpenAlgorithmProvider(out SafeBCryptAlgorithmHandle phAlgorithm, string pszAlgId, [Optional] string pszImplementation, int dwFlags = 0); |
| 489 | + | |
| 490 | + | [DllImport("bcrypt", CharSet = CharSet.Auto, SetLastError = true)] |
| 491 | + | public static extern NTStatus BCryptSetProperty(SafeBCryptAlgorithmHandle hObject, [MarshalAs(UnmanagedType.LPWStr)] string pszProperty, string pbInput, int cbInput, uint dwFlags = 0); |
| 492 | + | |
| 493 | + | [DllImport("bcrypt", CharSet = CharSet.Auto, SetLastError = true)] |
| 494 | + | public static extern NTStatus BCryptGenerateSymmetricKey(SafeBCryptAlgorithmHandle hAlgorithm, out SafeBCryptKeyHandle phKey, [Optional] IntPtr pbKeyObject, [Optional] int cbKeyObject, IntPtr pbSecret, int cbSecret, int dwFlags = 0); |
| 495 | + | |
| 496 | + | [DllImport("bcrypt", CharSet = CharSet.Auto, SetLastError = true)] |
| 497 | + | public static extern NTStatus BCryptGetProperty(SafeBCryptAlgorithmHandle hObject, [MarshalAs(UnmanagedType.LPWStr)] string pszProperty, byte[] pbOutput, int cbOutput, out uint pcbResult, int dwFlags = 0); |
| 498 | + | |
| 499 | + | public static string BCRYPT_AES_ALGORITHM = "AES"; |
| 500 | + | public static string BCRYPT_3DES_ALGORITHM = "3DES"; |
| 501 | + | public static string BCRYPT_CHAINING_MODE = "ChainingMode"; |
| 502 | + | |
| 503 | + | public static string BCRYPT_CHAIN_MODE_CBC = "ChainingModeCBC"; |
| 504 | + | public static string BCRYPT_CHAIN_MODE_CFB = "ChainingModeCFB"; |
| 505 | + | |
| 506 | + | //public static ArraySegment<byte> BCryptGetProperty(SafeBCryptAlgorithmHandle hObject, string propertyName) |
| 507 | + | //{ |
| 508 | + | // uint length; |
| 509 | + | // BCryptGetProperty(hObject, propertyName, IntPtr.Zero, 0, out length, 0); |
| 510 | + | // byte[] result = new byte[length]; |
| 511 | + | // BCryptGetProperty(hObject, propertyName, result, result.Length, out length, 0); |
| 512 | + | // return new ArraySegment<byte>(result, 0, length); |
| 513 | + | //} |
| 514 | + | |
| 515 | + | public static byte[] DecryptCredentials(byte[] encrypedPass, LsaDecryptor.LsaKeys lsakeys) |
| 516 | + | { |
| 517 | + | SafeBCryptAlgorithmHandle hProvider, hDesProvider; |
| 518 | + | SafeBCryptKeyHandle hAes, hDes; |
| 519 | + | int result; |
| 520 | + | NTStatus status; |
| 521 | + | |
| 522 | + | var passDecrypted = new byte[encrypedPass.Length + 1]; |
| 523 | + | var initializationVector = new byte[16]; |
| 524 | + | |
| 525 | + | Array.Copy(lsakeys.iv, initializationVector, lsakeys.iv.Length); |
| 526 | + | |
| 527 | + | if (encrypedPass.Length % 8 != 0) |
| 528 | + | { |
| 529 | + | initializationVector = new byte[16]; |
| 530 | + | |
| 531 | + | BCryptOpenAlgorithmProvider(out hProvider, BCRYPT_AES_ALGORITHM, null, 0); |
| 532 | + | |
| 533 | + | using (hProvider) |
| 534 | + | { |
| 535 | + | BCryptSetProperty(hProvider, BCRYPT_CHAINING_MODE, BCRYPT_CHAIN_MODE_CFB, BCRYPT_CHAIN_MODE_CFB.Length, 0); |
| 536 | + | |
| 537 | + | var pkeypinnedArray = GCHandle.Alloc(lsakeys.aes_key, GCHandleType.Pinned); |
| 538 | + | var pkey = pkeypinnedArray.AddrOfPinnedObject(); |
| 539 | + | |
| 540 | + | var pencrypedPasspinnedArray = GCHandle.Alloc(encrypedPass, GCHandleType.Pinned); |
| 541 | + | var pencrypedPass = pencrypedPasspinnedArray.AddrOfPinnedObject(); |
| 542 | + | |
| 543 | + | var pinitializationVectorpinnedArray = GCHandle.Alloc(initializationVector, GCHandleType.Pinned); |
| 544 | + | var pinitializationVector = pinitializationVectorpinnedArray.AddrOfPinnedObject(); |
| 545 | + | |
| 546 | + | var ppassDecryptedinnedArray = GCHandle.Alloc(passDecrypted, GCHandleType.Pinned); |
| 547 | + | var ppassDecrypted = ppassDecryptedinnedArray.AddrOfPinnedObject(); |
| 548 | + | |
| 549 | + | //byte[] testb = new byte[0]; |
| 550 | + | //BCryptGetProperty(hProvider, "ObjectLength", testb, 0, out uint pcbResult, 0); |
| 551 | + | //Console.WriteLine(pcbResult); |
| 552 | + | //testb = new byte[pcbResult]; |
| 553 | + | //BCryptGetProperty(hProvider, "ObjectLength", testb, testb.Length, out uint pcbResult2, 0); |
| 554 | + | //Console.WriteLine(Helpers.ByteArrayToString(testb)); |
| 555 | + | |
| 556 | + | BCryptGenerateSymmetricKey(hProvider, out hAes, IntPtr.Zero, 0, pkey, lsakeys.aes_key.Length, 0); |
| 557 | + | using (hAes) |
| 558 | + | { |
| 559 | + | status = (NTStatus)BCryptDecrypt(hAes, pencrypedPass, encrypedPass.Length, IntPtr.Zero, |
| 560 | + | pinitializationVector, initializationVector.Length, ppassDecrypted, passDecrypted.Length, out result, 0); |
| 561 | + | |
| 562 | + | if (status != 0) return new byte[0]; |
| 563 | + | } |
| 564 | + | } |
| 565 | + | } |
| 566 | + | else |
| 567 | + | { |
| 568 | + | BCryptOpenAlgorithmProvider(out hDesProvider, BCRYPT_3DES_ALGORITHM, null, 0); |
| 569 | + | |
| 570 | + | using (hDesProvider) |
| 571 | + | { |
| 572 | + | BCryptSetProperty(hDesProvider, BCRYPT_CHAINING_MODE, BCRYPT_CHAIN_MODE_CBC, |
| 573 | + | BCRYPT_CHAIN_MODE_CBC.Length, 0); |
| 574 | + | |
| 575 | + | var pkeypinnedArray = GCHandle.Alloc(lsakeys.des_key, GCHandleType.Pinned); |
| 576 | + | var pkey = pkeypinnedArray.AddrOfPinnedObject(); |
| 577 | + | |
| 578 | + | var pencrypedPasspinnedArray = GCHandle.Alloc(encrypedPass, GCHandleType.Pinned); |
| 579 | + | var pencrypedPass = pencrypedPasspinnedArray.AddrOfPinnedObject(); |
| 580 | + | |
| 581 | + | var pinitializationVectorpinnedArray = GCHandle.Alloc(initializationVector, GCHandleType.Pinned); |
| 582 | + | var pinitializationVector = pinitializationVectorpinnedArray.AddrOfPinnedObject(); |
| 583 | + | |
| 584 | + | var ppassDecryptedinnedArray = GCHandle.Alloc(passDecrypted, GCHandleType.Pinned); |
| 585 | + | var ppassDecrypted = ppassDecryptedinnedArray.AddrOfPinnedObject(); |
| 586 | + | |
| 587 | + | BCryptGenerateSymmetricKey(hDesProvider, out hDes, IntPtr.Zero, 0, pkey, lsakeys.des_key.Length, 0); |
| 588 | + | using (hDes) |
| 589 | + | { |
| 590 | + | status = (NTStatus)BCryptDecrypt(hDes, pencrypedPass, encrypedPass.Length, IntPtr.Zero, |
| 591 | + | pinitializationVector, (initializationVector.Length / 2), ppassDecrypted, passDecrypted.Length, out result, 0); |
| 592 | + | if (status != 0) return new byte[0]; |
| 593 | + | } |
| 594 | + | } |
| 595 | + | } |
| 596 | + | |
| 597 | + | Array.Resize(ref passDecrypted, result); |
| 598 | + | return passDecrypted; |
| 599 | + | } |
| 600 | + | |
| 601 | + | public static string GetHashSHA1(byte[] data) |
| 602 | + | { |
| 603 | + | using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider()) |
| 604 | + | { |
| 605 | + | return string.Concat(sha1.ComputeHash(data).Select(x => x.ToString("X2"))); |
| 606 | + | } |
| 607 | + | } |
| 608 | + | } |
| 609 | + | } |