### SMB2 Session Setup Response Example Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/types.md Demonstrates sending an SMB2 session setup request and accessing the session flags from the response. ```csharp var smb = new Smb2ProtocolTest(); var response = smb.SendSessionSetupRequests(credential); Console.WriteLine($"Session Flags: 0x{response.SessionFlags:X4}"); ``` -------------------------------- ### JavaScript Document Setup Function Source: https://github.com/netwrix/pingcastle/blob/master/PingCastleCommon/Template/dashboardtest.html Sets the current document for the selector engine and performs initial setup. ```javascript function m(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener ``` -------------------------------- ### GetSessionKey Example Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/rpc-sspi.md Shows how to obtain the session key and print its length in bytes. ```csharp byte[] sessionKey = sspi.GetSessionKey(); Console.WriteLine($"Session key length: {sessionKey.Length} bytes"); ``` -------------------------------- ### ExportBase Description Property Example Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/report-generation.md Provides an example of implementing the abstract 'Description' property for an export handler, returning a detailed explanation of the export's functionality. ```csharp public override string Description => "Exports Active Directory users with account details"; ``` -------------------------------- ### Perform Simple Update Check and Install Source: https://github.com/netwrix/pingcastle/blob/master/PingCastleAutoUpdater/README.md Executes a basic update check, downloads, and installs the latest stable release of PingCastle if available. Handles configuration migrations automatically. ```bash PingCastleAutoUpdater.exe ``` -------------------------------- ### SSPIHelperFactory Usage Example Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/rpc-sspi.md Demonstrates creating an SSPIHelper instance via the factory and logging in the client with network credentials. ```csharp var factory = new SSPIHelperFactory(); var sspi = factory.Create("ldap/dc.corp.local"); sspi.LoginClient(new NetworkCredential("user", "pass", "CORP")); ``` -------------------------------- ### Force Download and Install Latest Release Source: https://github.com/netwrix/pingcastle/blob/master/PingCastleAutoUpdater/README.md Forces the download and installation of the latest release, even if the current version is already up to date. Useful for re-installation or downgrading. ```bash PingCastleAutoUpdater.exe --force-download ``` -------------------------------- ### ExportBase Initialize Method Example Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/report-generation.md Demonstrates how to initialize an export handler with runtime settings, including server details and credentials. ```csharp var exporter = new ExportUsers(); var settings = new RuntimeSettings(tokenFactory); settings.Server = "dc.corp.local"; settings.Credential = new NetworkCredential("user", "pass"); exporter.Initialize(settings); ``` -------------------------------- ### ADConnectionType Example Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/types.md Demonstrates how to set and use the ADConnectionType enumeration to specify how to connect to Active Directory. ```csharp var connectionType = ADConnectionType.LDAPOnly; var connection = CreateConnection(server, ADConnectionType.LDAPOnly); ``` -------------------------------- ### DisplayState Example Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/types.md Shows how to use the DisplayState enumeration to manage UI state transitions and application flow. ```csharp var state = settings.EnsureDataCompleted("Scanner", "Export"); if (state == DisplayState.Run) { ExecuteOperation(); } else if (state == DisplayState.Exit) { Environment.Exit(0); } ``` -------------------------------- ### SSPIHelper Usage Example Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/rpc-sspi.md Shows basic usage of the SSPIHelper, including setting the security package and logging in the client. ```csharp var sspi = new SSPIHelper(); sspi.SecurityPackage = "Kerberos"; ``` -------------------------------- ### ExportBase QueryForAdditionalParameterInInteractiveMode Example Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/report-generation.md Shows how to query for additional parameters in interactive mode and proceed with the export if the state indicates readiness. ```csharp var state = exporter.QueryForAdditionalParameterInInteractiveMode(); if (state == DisplayState.Run) { exporter.Export("output.csv"); } ``` -------------------------------- ### SMB2 Negotiate Response Example Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/types.md Illustrates how to create an SMB2 protocol test instance and send a negotiate request, then access the response details. ```csharp var smb = new Smb2ProtocolTest(); var response = smb.SendNegotiateRequest(0x0311); // SMB 3.1.1 Console.WriteLine($"Dialect: 0x{response.Dialect:X4}"); Console.WriteLine($"Security Mode: {response.SecurityMode}"); ``` -------------------------------- ### ExportBase Name Property Example Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/report-generation.md Provides an example of implementing the abstract 'Name' property for an export handler, returning a display name for the export operation. ```csharp public override string Name => "Export Users to CSV"; ``` -------------------------------- ### Create ISSPIHelper Example Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/rpc-sspi.md Demonstrates creating an ISSPIHelper instance using the factory pattern, specifying the target server's SPN. ```csharp var factory = new SSPIHelperFactory(); var sspi = factory.Create("ldap/dc.corp.local"); ``` -------------------------------- ### ISmb2Protocol.SendSessionSetupRequests Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/scanners.md Performs SMB2 session setup, optionally with authentication credentials. This is crucial for establishing a secure session for further operations. ```APIDOC ## ISmb2Protocol.SendSessionSetupRequests ### Description Performs SMB2 session setup with optional authentication. ### Method ```csharp SMB2_SessionSetupResponse SendSessionSetupRequests(NetworkCredential optionalCredential = null) ``` ### Parameters #### Path Parameters - **optionalCredential** (NetworkCredential) - Optional - Credentials for authenticated setup (null for null session) ### Response #### Success Response - **SMB2_SessionSetupResponse** - Contains session info #### Throws - **PingCastleException** - if session setup fails or credentials are invalid ``` -------------------------------- ### Dry-Run Example Output Source: https://github.com/netwrix/pingcastle/blob/master/PingCastleAutoUpdater/README.md Illustrates the expected output when running PingCastleAutoUpdater with the --dry-run flag, showing simulated file operations and configuration conversion analysis. ```text [DRY-RUN] No files will be modified. Analyzing update contents... [DRY-RUN] Would save PingCastle.exe [DRY-RUN] Would merge .config file: PingCastle.exe.config [DRY-RUN] Would save PingCastleCommon.dll ... [DRY-RUN MODE - NO CHANGES WILL BE MADE] Analyzing configuration conversion... [OK] Analysis completed - Configuration would be converted successfully [Report] Preview report saved: ConversionPreview_20240115_143022.txt [Data] Sections to convert: 5 [Settings] Settings to map: 24 To proceed with conversion, run without --dry-run flag. ``` -------------------------------- ### SMB2 Network Interface Capability Example Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/types.md Illustrates checking for RDMA capability on network interfaces using the SMB2_NETWORK_INTERFACE_INFO_Capability enumeration. ```csharp var smb = new Smb2ProtocolTest(); var interfaces = smb.GetNetworkInterfaceInfo(); foreach (var iface in interfaces) { if ((iface.Capability & SMB2_NETWORK_INTERFACE_INFO_Capability.RDMA_CAPABLE) != 0) { Console.WriteLine($"RDMA capable on {iface.IP}"); } } ``` -------------------------------- ### Complete PingCastle Configuration Example Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/configuration.md This JSON structure represents a complete configuration file, including settings for Brand, Encryption, Smtp, and other PingCastle features. ```json { "Brand": { "BrandCss": "body { font-family: Arial; }", "BrandJs": "" }, "Encryption": { "EncryptionKey": "", "RSAKeys": [] }, "CustomRules": { "CustomRules": [] }, "HoneyPot": { "HoneyPots": [] }, "Infrastructure": { "Riverbeds": [] }, "Smtp": { "From": "pingcastle@corp.local", "DeliveryMethod": "Network", "Host": "smtp.corp.local", "Port": 25, "UserName": "", "Password": "" }, "License": { "License": "" } } ``` -------------------------------- ### Perform SMB2 Session Setup Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/scanners.md Establishes an SMB2 session with the target server. Supports both null sessions for unauthenticated access and authenticated sessions using provided credentials. ```csharp var smb = new Smb2ProtocolTest(); // Null session var nullResponse = smb.SendSessionSetupRequests(); // Authenticated session var cred = new NetworkCredential("user", "password"); var authResponse = smb.SendSessionSetupRequests(cred); Console.WriteLine($"Session flags: 0x{authResponse.SessionFlags:X4}"); ``` -------------------------------- ### JavaScript Attribute Handler Setup Source: https://github.com/netwrix/pingcastle/blob/master/PingCastleCommon/Template/dashboardtest.html Sets up attribute handlers for the selector engine, mapping attribute names to functions. ```javascript function ja(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b} ``` -------------------------------- ### SMB2 Tree Connect Response Example Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/types.md Shows how to send an SMB2 tree connect request and retrieve share type and maximal access information from the response. ```csharp var smb = new Smb2ProtocolTest(); var response = smb.SendTreeConnect("\\server\share"); Console.WriteLine($"Share Type: {response.ShareType}"); Console.WriteLine($"Maximal Access: 0x{response.MaximalAccess:X8}"); ``` -------------------------------- ### Get Brand Options from Configuration Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/utilities-helpers.md Retrieves specific BrandOptions from an IConfiguration object. Ensure appsettings.json is configured and loaded. ```csharp var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var brandOptions = config.GetBrandOptions(); ``` -------------------------------- ### Verify Signed Message Example Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/rpc-sspi.md Demonstrates how to verify a signed message received from a server and handle potential signature validation failures. ```csharp var signed = ReceiveFromServer(); try { sspi.VerifyMessage(signed.Length, signed, out byte[] verified); Console.WriteLine("Message verified: " + Encoding.UTF8.GetString(verified)); } catch { Console.WriteLine("Signature invalid - message may be tampered"); } ``` -------------------------------- ### ListDetailItem Example Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/report-generation.md Instantiates a ListDetailItem to capture multiple string values, like a list of privileged group names. ```csharp var riskyGroups = new List { "Domain Admins", "Schema Admins", "Enterprise Admins" }; var detail = new ListDetailItem("PrivilegedGroups", riskyGroups); ``` -------------------------------- ### DisplayAdvancement Method Example Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/report-generation.md Illustrates the usage of the protected 'DisplayAdvancement' method to log progress messages with timestamps during an export operation. ```csharp DisplayAdvancement("Enumerating users..."); DisplayAdvancement("Processing 1000 users completed"); ``` -------------------------------- ### AJAX Request Setup Source: https://github.com/netwrix/pingcastle/blob/master/PingCastleCommon/Template/dashboardtest.html Configures and sends an AJAX request, handling success, error, and completion callbacks. Supports various data types and headers. ```javascript contentType)&&w.setRequestHeader("Content-Type",l.contentType),w.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+("*"!==l.dataTypes[0] ?", ":"")+"q=0.01":"):l.accepts["*" ]);for(e in l.headers)w.setRequestHeader(e,l.headers[e]);if(l.beforeSend&&(l.beforeSend.call(m,w,l)===!1||2===u))return w.abort();v="abort";for(e in{success:1,error:1,complete:1})w[e](l[e]);if(j=Ub(Pb,l,c,w)){if(w.readyState=1,i&&o.trigger("ajaxSend",[w,l]),2===u)return w;l.async&&l.timeout>0&&(h=a.setTimeout(function(){w.abort("timeout")},l.timeout));try{u=1,j.send(s,y)}catch(x){if(!(2>u))throw x;y(-1,x)}}else y(-1,"No Transport");function y(b,c,d,e){var k,s,t,v,x,y=c;2!==u&&(u=2,h&&a.clearTimeout(h),j=void 0,g=e||"",w.readyState=b>0?4:0,k=b>=200&&300>b||304===b,d&&(v=Wb(l,w,d)),v=Xb(l,v,w,k),k?(l.ifModified&&(x=w.getResponseHeader("Last-Modified"),x&&(n.lastModified[f]=x),x=w.getResponseHeader("etag"),x&&(n.etag[f]=x)),204===b||"HEAD"===l.type?y="nocontent":304===b?y="notmodified":(y=v.state,s=v.data,t=v.error,k=!t)):(t=y,!b&&y||(y="error",0>b&&(b=0))),w.status=b,w.statusText=(c||y)+"",k?p.resolveWith(m,[s,y,w]):p.rejectWith(m,[w,y,t]),w.statusCode(r),r=void 0,i&&o.trigger(k?"ajaxSuccess":"ajaxError",[w,l,k?s:t]),q.fireWith(m,[w,y]),i&&(o.trigger("ajaxComplete",[w,l]),--n.active||n.event.trigger("ajaxStop")))}return w} ``` -------------------------------- ### Configure Trace Listener for PingCastle Logs Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/errors.md Configure the app.config or appsettings.json to direct trace output to a file named 'pingcastle.log'. This setup is essential for capturing detailed diagnostic information. ```xml ``` -------------------------------- ### Logging Stack Traces for Diagnostics Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/errors.md Example of how to log both the exception message and its stack trace for detailed diagnostics when an error occurs during report loading. ```csharp try { var report = LoadHealthcheck(filename); } catch (PingCastleException ex) { Trace.WriteLine($"Error loading report: {ex.Message}"); Trace.WriteLine($"Stack trace: {ex.StackTrace}"); throw; } ``` -------------------------------- ### Service Principal Authentication Setup Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/cloud-azure.md Demonstrates how to configure Azure service principal authentication in PingCastle using a certificate. This is used for programmatic access to Azure resources. ```bash // In Azure CLI: // az ad sp create-for-rbac --name PingCastleAnalyzer ``` ```csharp // In PingCastle: var credential = new CertificateCredential( clientId: "00000000-0000-0000-0000-000000000000", tenantId: "11111111-1111-1111-1111-111111111111", thumbprint: "ABCDEF1234567890", certificatePath: "C:\\certs\\pingcastle.pfx", password: "certpassword" ); var token = await credential.GetToken(); ``` -------------------------------- ### Get All Files Recursively Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/core-interfaces.md Retrieves a list of all file paths, including those in nested subdirectories, starting from a specified path. ```csharp List allFiles = fileConnection.GetAllSubFiles(path); ``` -------------------------------- ### Get All Subdirectories Recursively Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/core-interfaces.md Retrieves a list of all subdirectory paths, including nested ones, starting from a specified path. ```csharp List allSubDirs = fileConnection.GetAllSubDirectories(path); ``` -------------------------------- ### Test Basic SMB2 Connectivity Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/scanners.md Tests the basic SMB2 connectivity to a target, including negotiation and session setup. Use this to verify if a target responds to SMB2 requests. ```csharp public class SMB2ConnectivityTest { public bool TestSmb2Connectivity(string target) { var smb = new Smb2ProtocolTest(target); smb.LogPrefix = target; try { // Test negotiate var negotiateResp = smb.SendNegotiateRequest((int)SMB2_DIALECTS.SMB2_DIALECT_3_1_1); Console.WriteLine($"✓ SMB2 Negotiation successful"); Console.WriteLine($" Dialect: 0x{negotiateResp.Dialect:X4}"); // Test session setup var sessionResp = smb.SendSessionSetupRequests(); Console.WriteLine($"✓ SMB2 Session setup successful"); return true; } catch (PingCastleException ex) { Console.WriteLine($"✗ SMB2 Test failed: {ex.Message}"); return false; } } } ``` -------------------------------- ### Get All Scanners Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/factories-extensions.md Discovers all available scanner implementations from registered assemblies. Returns a dictionary mapping scanner names to their types. Logs warnings if assemblies fail to load. ```csharp public static Dictionary GetAllScanners() { // Implementation details omitted for brevity return new Dictionary(); } ``` ```csharp var scanners = PingCastleFactory.GetAllScanners(); Console.WriteLine("Available scanners:"); foreach (var scanner in scanners) { Console.WriteLine($" {scanner.Key}"); } ``` -------------------------------- ### Get File Pattern for Report Loading Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/factories-extensions.md Gets the file glob pattern for loading reports of a specific type T, where T must implement IPingCastleReport. Useful for finding report files in a directory. ```csharp public static string GetFilePatternForLoad() where T : IPingCastleReport { // Implementation details omitted for brevity return string.Empty; } ``` ```csharp var pattern = PingCastleFactory.GetFilePatternForLoad(); var files = Directory.GetFiles(reportsPath, pattern); ``` -------------------------------- ### Tooltip Get UID Source: https://github.com/netwrix/pingcastle/blob/master/PingCastleCommon/Template/dashboardtest.html Generates a unique identifier for the tooltip. ```javascript c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a} ``` -------------------------------- ### Display Help Message Source: https://github.com/netwrix/pingcastle/blob/master/PingCastleAutoUpdater/README.md Shows the help message, listing all available command-line options and their descriptions. ```bash PingCastleAutoUpdater.exe --help ``` -------------------------------- ### IFileConnection.GetLastWriteTime Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/core-interfaces.md Gets the last modification time of a file or directory. ```APIDOC ## GetLastWriteTime ### Description Gets the last modification time of a file or directory. ### Method C# method ### Parameters - **path** (string) - Required - File system path ### Returns DateTime of last write ``` -------------------------------- ### Access Configuration Settings Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/configuration.md Demonstrates how to bind configuration sections to strongly-typed objects for easier access to settings like Brand and Smtp. ```csharp var brandOptions = new BrandOptions(); config.GetSection("Brand").Bind(brandOptions); var smtpOptions = config.GetSection("Smtp").Get(); ``` -------------------------------- ### Tooltip Get Title Source: https://github.com/netwrix/pingcastle/blob/master/PingCastleCommon/Template/dashboardtest.html Retrieves the title for the tooltip, prioritizing 'data-original-title' or the title option. ```javascript c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||"function"==typeof c.title?c.title.call(b[0]):c.title} ``` -------------------------------- ### Tooltip Get Position Source: https://github.com/netwrix/pingcastle/blob/master/PingCastleCommon/Template/dashboardtest.html Calculates the position and dimensions of an element, considering scroll and viewport. ```javascript c.prototype.getPosition=function(b){b=b||this.$element;var c=b[0],d="BODY"==c.tagName,e=c.getBoundingClientRect();null==e.width&&(e=a.extend({},e,{width:e.right-e.left,height:e.bottom-e.top}));var f=window.SVGElement&&c instanceof window.SVGElement,g=d?{top:0,left:0}:f?null:b.offset(),h={scroll:d?document.documentElement.scrollTop||document.body.scrollTop:b.scrollTop()},i=d?{width:a(window).width(),height:a(window).height()}:null;return a.extend({},e,h,i,g)} ``` -------------------------------- ### Generate Help Center Link Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/utilities-helpers.md Constructs a URL to a specific topic in the PingCastle help documentation. Pass the desired topic as a string. ```csharp string link = HelpCenterLink.GetHelpLink("password-policy"); Console.WriteLine($"Learn more: {link}"); ``` -------------------------------- ### TextDetailItem Example Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/report-generation.md Instantiates a TextDetailItem to capture a single text value, such as a specific finding name. ```csharp var detail = new TextDetailItem("RiskyAccount", "administrator"); ``` -------------------------------- ### Tooltip Get Calculated Offset Source: https://github.com/netwrix/pingcastle/blob/master/PingCastleCommon/Template/dashboardtest.html Calculates the offset for placing the tooltip based on its position and dimensions. ```javascript c.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}} ``` -------------------------------- ### Get Last Modification Time Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/core-interfaces.md Retrieves the date and time when a file or directory was last modified. ```csharp DateTime lastWrite = fileConnection.GetLastWriteTime(path); ``` -------------------------------- ### Initialize Smb2ProtocolTest with Hostname Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/scanners.md Creates an instance of Smb2ProtocolTest, specifying the target hostname or IP address for SMB2 operations. This is the primary way to configure the target for testing. ```csharp var tester = new Smb2ProtocolTest("dc.corp.local"); ``` -------------------------------- ### Get Immediate Subdirectories Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/core-interfaces.md Returns an enumerable collection of immediate subdirectory paths from a given path. ```csharp IEnumerable subDirs = fileConnection.GetSubDirectories(path); ``` -------------------------------- ### Initialize SSPI Client with Credentials Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/rpc-sspi.md Use this snippet to initialize client-side SSPI authentication with network credentials. Ensure the SecurityPackage property is set before calling. ```csharp var sspi = new SSPIHelper(); sspi.SecurityPackage = "Kerberos"; sspi.LoginClient(new NetworkCredential("user", "password", "CORP")); ``` -------------------------------- ### Get Human-Readable File Name Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/core-interfaces.md Obtain a human-readable filename for a report. Useful for display purposes. ```csharp string GetHumanReadableFileName() { // Implementation details omitted for brevity return "Report_Domain_Date.txt"; } ``` ```csharp var report = LoadReport(); string displayName = report.GetHumanReadableFileName(); Console.WriteLine($"Report: {displayName}"); ``` -------------------------------- ### Get File Security ACL Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/core-interfaces.md Retrieves the Access Control List (ACL) for a specified file path. ```csharp var security = fileConnection.GetFileSecurity(path); ``` -------------------------------- ### Get Directory Security ACL Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/core-interfaces.md Retrieves the Access Control List (ACL) for a specified directory path. ```csharp var security = fileConnection.GetDirectorySecurity(path); ``` -------------------------------- ### Validating Configuration Early Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/errors.md Shows how to perform early validation of runtime settings, specifically checking certificate validity before proceeding with operations. ```csharp var settings = new RuntimeSettings(tokenFactory); if (!settings.CheckCertificate()) { Console.Error.WriteLine("Invalid certificate configuration"); return DisplayState.Exit; } // Continue with valid settings ExecuteOperation(settings); ``` -------------------------------- ### Get Machine-Readable File Name Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/core-interfaces.md Obtain a machine-readable filename for a report. Suitable for file system storage. ```csharp string GetMachineReadableFileName() { // Implementation details omitted for brevity return "Report_Domain_Date_Timestamp.json"; } ``` ```csharp var report = LoadReport(); string storageName = report.GetMachineReadableFileName(); File.WriteAllText(storageName, reportContent); ``` -------------------------------- ### Preview Update Changes with Dry-Run Source: https://github.com/netwrix/pingcastle/blob/master/PingCastleAutoUpdater/README.md Simulates an update process without making any file modifications. Useful for testing, verifying configuration migrations, and auditing potential changes. ```bash PingCastleAutoUpdater.exe --dry-run ``` -------------------------------- ### AJAX Transport Setup Source: https://github.com/netwrix/pingcastle/blob/master/PingCastleCommon/Template/dashboardtest.html JavaScript function to set up AJAX transports, which handle the actual data transfer for requests. ```javascript function Ub(a,b,c,d){var e={},f=a===Pb;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")} ``` -------------------------------- ### AJAX Prefilter Setup Source: https://github.com/netwrix/pingcastle/blob/master/PingCastleCommon/Template/dashboardtest.html JavaScript function to set up AJAX prefilters, allowing modification of request settings before they are sent. ```javascript function Tb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(G)||[];if(n.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}} ``` -------------------------------- ### SMB2 Protocol Operations Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/INDEX.md Interface for performing SMB2 operations, including negotiation, session setup, and share access. ```APIDOC ## ISmb2Protocol ### Description Interface for performing SMB2 operations. ### Properties - **LogPrefix** (string): A prefix for logging messages. ### Methods - **SendNegotiateRequest()**: Performs dialect negotiation. - **SendSessionSetupRequests()**: Establishes a session. - **SendTreeConnect()**: Tests access to a share. - **GetNetworkInterfaceInfo()**: Discovers network interfaces. ``` -------------------------------- ### Smb2ProtocolTest Constructor Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/scanners.md Creates an instance of Smb2ProtocolTest, optionally specifying the target hostname or IP address for SMB2 testing. ```APIDOC ## Smb2ProtocolTest Constructor ### Description Creates an SMB2 protocol tester, optionally specifying the target host. ### Method ```csharp public Smb2ProtocolTest() public Smb2ProtocolTest(string hostname) ``` ### Parameters #### Path Parameters - **hostname** (string) - Optional - Target hostname or IP address ``` -------------------------------- ### Perform SMB2 Testing Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/README.md Tests SMB2 protocol negotiation, session setup, and share access on a target server. ```csharp using PingCastleCommon.Scanners; var smb = new Smb2ProtocolTest("target.corp.local"); // Test SMB2 negotiation var negotiateResp = smb.SendNegotiateRequest((int)SMB2_DIALECTS.SMB2_DIALECT_3_1_1); Console.WriteLine($"Dialect: 0x{negotiateResp.Dialect:X4}"); // Test session setup var sessionResp = smb.SendSessionSetupRequests(); Console.WriteLine($"Session established"); // Test share access try { var treeResp = smb.SendTreeConnect("\\\\target\\admin$"); Console.WriteLine("Admin share accessible"); } catch { Console.WriteLine("Admin share not accessible"); } ``` -------------------------------- ### Configure Basic SMTP Settings Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/configuration.md Set up basic email notification delivery, including sender address, host, port, and authentication credentials. ```json { "Smtp": { "From": "pingcastle@corp.local", "DeliveryMethod": "Network", "Host": "smtp.corp.local", "Port": 25, "UserName": "pingcastle_svc", "Password": "SecurePassword123" } } ``` -------------------------------- ### AJAX Request Setup and Execution Source: https://github.com/netwrix/pingcastle/blob/master/PingCastleCommon/Template/dashboardtest.html Configures and sends an AJAX request, handling responses and potential errors. It includes logic for setting headers, sending data, and processing the response based on ready state and status. ```javascript d["X-Requested-With"]=(d["X-Requested-With"]="XMLHttpRequest");for(f in d)void 0!==d[f]&&g.setRequestHeader(f,d[f]+"");g.send(b.hasContent&&b.data||null),c=function(a,d){var f,i,j;if(c&&(d||4===g.readyState))if(delete fc[h],c=void 0,g.onreadystatechange=n.noop,d)4!==g.readyState&&g.abort();else{j={},f=g.status,"string"==typeof g.responseText&&(j.text=g.responseText);try{i=g.statusText}catch(k){i=""}f||!b.isLocal||b.crossDomain?1223===f&&(f=204):f=j.text?200:404}j&&e(f,i,j,g.getAllResponseHeaders())},b.async?4===g.readyState?a.setTimeout(c):g.onreadystatechange=fc[h]=c:c()},abort:function(){c&&c(void 0,!0)}}}});function hc(){try{return new a.XMLHttpRequest}catch(b){}}function ic(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}} ``` -------------------------------- ### Loading XML Reports Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/errors.md Demonstrates how to load multiple XML reports using PingCastleReportHelper. Handles potential exceptions during file loading and parsing. ```csharp try { var reports = PingCastleReportHelper.LoadXmls( reportsDirectory, DateTime.Now.AddYears(-1) ); // UI displays: "Reports loaded: 5 - on a total of 7 valid files" // Indicates 2 files had errors } catch (PingCastleException ex) { Console.Error.WriteLine($"Report batch loading failed: {ex.Message}"); } ``` -------------------------------- ### ISSPIHelper.LoginClient Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/rpc-sspi.md Initializes client-side authentication with provided network credentials. This method sets up the necessary context for subsequent SSPI operations. ```APIDOC ## ISSPIHelper.LoginClient ### Description Initializes client-side authentication with credentials. This method is crucial for establishing a security context before performing other SSPI operations. ### Method void ### Parameters #### Parameters - **login** (NetworkCredential) - Description: User credentials (domain, username, password) ### Throws `PingCastleException` if credential initialization fails ### Example ```csharp var sspi = new SSPIHelper(); sspi.SecurityPackage = "Kerberos"; sspi.LoginClient(new NetworkCredential("user", "password", "CORP")); ``` ``` -------------------------------- ### Tooltip Get Viewport Adjusted Delta Source: https://github.com/netwrix/pingcastle/blob/master/PingCastleCommon/Template/dashboardtest.html Calculates adjustments needed for tooltip placement to fit within the viewport. ```javascript c.prototype.getViewportAdjustedDelta=function(a,b,c,d){var e={top:0,left:0};if(!this.$viewport)return e;var f=this.options.viewport&&this.options.viewport.padding||0,g=this.getPosition(this.$viewport);if(/right|left/.test(a)){var h=b.top-f-g.scroll,i=b.top+f-g.scroll+d;hg.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;jg.right&&(e.left=g.left+g.width-k)}return e} ``` -------------------------------- ### IADWebService.BuildOUExplorationList Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/core-interfaces.md Constructs a list of Organizational Units (OUs) for exploration. It allows for configurable depth splitting to optimize performance by dividing the exploration into separate queries. ```APIDOC ## IADWebService.BuildOUExplorationList ### Description Builds a list of OUs for exploration with configurable depth splitting for performance. ### Method List ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **OU** (`string`) - Required - Distinguished name of the OU to explore from * **NumberOfDepthForSplit** (`int`) - Required - Depth at which to split exploration into separate queries ### Request Example ```csharp var connection = CreateConnection("dc.corp.local"); var ous = connection.BuildOUExplorationList("DC=corp,DC=local", 2); foreach (var ou in ous) { Console.WriteLine($"Explore: {ou.OuName}"); } ``` ### Response #### Success Response * **List** - representing the OU hierarchy ``` -------------------------------- ### Get Specific Export Handler Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/factories-extensions.md Instantiates a specific export handler by name. Requires initialization with RuntimeSettings before use. ```csharp public static IExport GetExport(string exportName) { // Implementation details omitted for brevity throw new NotImplementedException(); } ``` ```csharp var csvExporter = PingCastleFactory.GetExport("CSV"); var settings = new RuntimeSettings(tokenFactory); csvExporter.Initialize(settings); csvExporter.Export("output.csv"); ``` -------------------------------- ### Get All Exports Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/factories-extensions.md Discovers all available export handler implementations. Returns a dictionary mapping export names to their types. ```csharp public static Dictionary GetAllExports() { // Implementation details omitted for brevity return new Dictionary(); } ``` ```csharp var exports = PingCastleFactory.GetAllExports(); Console.WriteLine("Available export formats:"); foreach (var export in exports) { Console.WriteLine($" {export.Key}"); } ``` -------------------------------- ### Activity Tracing with Stopwatch Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/utilities-helpers.md Traces the start, end, and duration of an activity. Use this to measure performance of specific operations. ```csharp public class ActivityTracer { public void TraceActivity(string activity, Action work) { try { Trace.WriteLine($"[START] {activity}"); var stopwatch = Stopwatch.StartNew(); work(); stopwatch.Stop(); Trace.WriteLine($"[END] {activity} - {stopwatch.ElapsedMilliseconds}ms"); } catch (Exception ex) { Trace.WriteLine($"[ERROR] {activity} - {ex.Message}"); throw; } } } // Usage var tracer = new ActivityTracer(); tracer.TraceActivity("Domain Enumeration", () => { // Enumeration code... }); ``` -------------------------------- ### ISSPIHelper.InitializeServer Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/rpc-sspi.md Processes the client's token on the server side and generates a response token. This is used in the server's part of the SSPI handshake. ```APIDOC ## ISSPIHelper.InitializeServer ### Description Processes client token on server side and generates server response token. This method is essential for authenticating clients attempting to connect to the server. ### Method void ### Parameters #### Parameters - **clientToken** (byte[]) - Description: Client's token to validate - **serverToken** (byte[] out) - Description: Response token for client - **bContinueProcessing** (bool out) - Description: True if another round-trip needed ### Example ```csharp var sspi = new SSPIHelper(); byte[] clientToken = ReceiveFromClient(); sspi.InitializeServer(clientToken, out byte[] serverToken, out bool continue); SendToClient(serverToken); if (continue) { // Multi-step authentication... } ``` ``` -------------------------------- ### Fluent Scanner Configuration Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/api-reference/factories-extensions.md Configure scanners fluently by discovering available scanners, registering custom ones from an assembly, and building a specific scanner instance. ```csharp public class ScannerConfiguration { private Dictionary _scanners; private RuntimeSettings _settings; public ScannerConfiguration DiscoverScanners() { _scanners = PingCastleFactory.GetAllScanners(); return this; } public ScannerConfiguration RegisterCustom(Assembly assembly) { PingCastleFactoryRegistry.RegisterAssembly(assembly); return this; } public IScanner BuildScanner(string name) { var scanner = PingCastleFactory.GetScanner(name); if (_settings != null) { scanner.Initialize(_settings); } return scanner; } } // Usage var scanner = new ScannerConfiguration() .DiscoverScanners() .RegisterCustom(typeof(CustomScanner).Assembly) .BuildScanner("SMB2"); ``` -------------------------------- ### Load Default Configuration from JSON File Source: https://github.com/netwrix/pingcastle/blob/master/_autodocs/configuration.md This code loads application settings from an 'appsettings.json' file. The file is optional, meaning the application can run without it. ```csharp var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: true) .Build(); ``` -------------------------------- ### AJAX Helper Methods Source: https://github.com/netwrix/pingcastle/blob/master/PingCastleCommon/Template/dashboardtest.html Provides convenience methods for making GET and POST requests, and for fetching JSON or script resources. ```javascript getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax(n.extend({url:a,type:b,dataType:e,data:c,success:d},n.isPlainObject(a)&&a))}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})} ``` -------------------------------- ### Get AD Computer Information Source: https://github.com/netwrix/pingcastle/blob/master/PingCastleCommon/Template/dashboardtest.html Retrieves detailed information about Active Directory computers. Can be filtered for specific operating systems. ```powershell Get-ADComputer -Filter * -Property * | Format-Table Name,OperatingSystem,OperatingSystemServicePack,OperatingSystemVersion -Wrap –Auto ``` ```powershell Get-ADComputer -Filter {OperatingSystem -Like "Windows Server*"} -Property * | Format-Table Name,OperatingSystem,OperatingSystemServicePack,OperatingSystemVersion -Wrap –Auto ``` -------------------------------- ### Affix Plugin Initialization Source: https://github.com/netwrix/pingcastle/blob/master/PingCastleCommon/Template/dashboardtest.html Initializes the affix plugin, which pins an element to the viewport when it scrolls past a specified offset. Useful for navigation or sidebars. ```javascript function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e\[b\]()})} ``` ```javascript var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()} ``` ```javascript c.VERSION="3.3.7",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={"offset":0,"target":window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return e=a-d&&"bottom"} ``` ```javascript c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a} ``` ```javascript c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)} ``` ```javascript c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}} ``` ```javascript var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('\\[data-spy="affix"\\]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})}) ```