Blog

  • Mastering PRT Delayed Renewal in Microsoft Entra ID: Controls, Configurations, and Real-World Scenarios

    Mastering PRT Delayed Renewal in Microsoft Entra ID: Controls, Configurations, and Real-World Scenarios

    In the evolving landscape of identity management, the Primary Refresh Token (PRT) stands as a cornerstone of seamless single sign-on (SSO) in Microsoft Entra ID. As devices increasingly operate in hybrid environments—online, offline, or in hibernation—understanding how to control PRT delayed renewal is essential for security admins and architects. Delayed renewal refers to the postponement of PRT updates during periods of disconnection, allowing cached SSO while balancing risk.

    This technical deep-dive explores PRT mechanics, indirect control mechanisms (since direct timeline tweaks aren’t available), working configuration examples, expanded scenarios, and practical tips. We’ll leverage tables for clarity and draw from official Microsoft documentation to ensure accuracy as of late 2025. Whether you’re enforcing stricter security in a high-risk sector or optimizing for user experience, these insights will help you fine-tune PRT behavior.

    PRT Renewal Mechanics: The Foundation

    A PRT is a device-bound artifact enabling SSO across Entra-integrated apps on platforms like Windows, iOS, macOS, and Android. It’s issued during device registration or join and includes claims for user identity, device compliance, and more.

    Key Timelines

    • Validity Period: 90 days, with continuous renewal during active use.
    • Renewal Interval: Every 4 hours via the CloudAP plugin during Windows sign-in. For apps, the Web Account Manager (WAM) plugin renews PRTs under conditions like silent token requests without a refresh token or when the PRT is invalid (e.g., requiring MFA).
    • Delayed Renewal: If offline (e.g., due to network disconnect or hibernation), renewal pauses until reconnection and a qualifying event (e.g., sign-in or app token request). Cached PRTs remain usable for SSO up to the 90-day limit.
    • Offline Handling: No immediate termination; PRTs support offline SSO, but renewal requires internet for CloudAP or WAM checks.

    These intervals (4 hours, 90 days) are fixed and non-configurable directly, as per Microsoft’s design for consistency. However, policies can indirectly cap effective lifetimes by forcing re-authentication on reconnect.

    Table 1: PRT Renewal Triggers and Conditions

    Trigger TypeDescriptionInterval/ConditionOffline Impact
    CloudAP PluginRenews during Windows sign-in.Every 4 hoursDelayed until reconnect + sign-in
    WAM PluginRenews via app token requests (silent or interactive).On-demand (e.g., invalid PRT)Delayed; cached PRT used until reconnect
    Inactivity ExpiryPRT expires if unused.After 90 daysFull expiry; re-auth required
    Event-BasedPassword change or revocation invalidates PRT.Immediate on detectionCached until reconnect, then invalidated

    Control Mechanisms: Indirect Ways to Influence Delayed Renewal

    While you can’t adjust the 4-hour or 90-day windows, Entra ID offers policy-based levers to enforce re-evaluations on reconnect, effectively shortening offline PRT usability. Below, we detail each mechanism with additional nuances, configuration steps, and working examples.

    1. Sign-in Frequency (SIF) in Conditional Access

    SIF mandates re-authentication intervals, overriding PRT defaults by requiring fresh auth for renewal. It accounts for a 5-minute clock skew to avoid over-prompting.

    • Additional Details: SIF doesn’t evaluate during PRT issuance but impacts app-driven renewals (e.g., via WAM). In offline scenarios, it triggers on reconnect, potentially blocking renewal if unsatisfied.
    • Configuration Example (Entra Admin Center):
    1. Navigate to Entra ID > Security > Conditional Access > New Policy.
    2. Name: “High-Security SIF”.
    3. Users: Select groups (e.g., executives).
    4. Cloud Apps: All or specific (e.g., Exchange Online).
    5. Session > Sign-in Frequency: Set to “1 hour” or “Every time”.
    6. Enable in report-only mode first.
    • PowerShell Working Example (Using Microsoft Graph SDK):
      # Install if needed: Install-Module Microsoft.Graph
      Connect-MgGraph -Scopes "Policy.ReadWrite.ConditionalAccess"
      $params = @{
          DisplayName = "SIF Policy - 1 Hour"
          State = "enabledForReportingButNotEnforced"
          Conditions = @{
              Applications = @{ IncludeApplications = "All" }
              Users = @{ IncludeUsers = "All" }
          }
          SessionControls = @{
              SignInFrequency = @{
                  Value = 1
                  Type = "hours"
              }
          }
      }
      New-MgIdentityConditionalAccessPolicy -BodyParameter $params
    • Impact: Reduces offline window; e.g., a 1-hour SIF means re-auth on reconnect after >1 hour offline.

    2. Token Protection

    Binds PRTs cryptographically to devices (via TPM), preventing replay. It validates binding during renewal, invalidating unbound PRTs.

    • Additional Details: Supports Windows 10+ and specific apps (e.g., OneDrive 22.217+). Errors like AADSTS1002 (no device state) or 1006 (unsupported OS) trigger on unbound renewals. In hibernation, TPM failures can invalidate PRTs post-wake.
    • Configuration Example:
    1. Entra Admin Center: Conditional Access > New Policy.
    2. Target: Office 365 apps.
    3. Conditions: Windows platforms.
    4. Session > Require Token Protection: Enable.
    5. Test in report-only; monitor logs for tokenProtectionStatusDetails.
    • Working Log Query Example (Log Analytics):
      SigninLogs
      | where TimeGenerated > ago(7d)
      | where ConditionalAccessPolicies has "Require token protection"
      | summarize Count=count() by tokenProtectionStatusDetails, signInSessionStatusCode
    • Impact: Ensures delayed renewal only succeeds on the bound device; mismatches force re-auth.

    3. Continuous Access Evaluation (CAE)

    CAE enables real-time revocation via events (e.g., account disable) or policies (e.g., IP changes), extending tokens to 28 hours while allowing instant invalidation.

    • Additional Details: Uses claim challenges (401 errors) for revocation. In offline reconnects, CAE checks sync’ed policies; supports apps like Outlook/Teams.
    • Configuration Example:
    1. Entra Admin Center: Conditional Access > Customize CAE.
    2. Enable for IP/location policies.
    3. Define trusted IPs: Add IPv4/IPv6 ranges.
    • Working Scenario Simulation: Use “What If” tool to test a user reconnecting from an untrusted IP—CAE issues challenge, revoking PRT.
    • Impact: Overrides delayed renewal; e.g., if risk detected offline, revocation applies on reconnect.

    4. Device Compliance Policies

    Integrates with Intune; PRTs carry compliance claims, failing renewal if non-compliant on reconnect.

    • Additional Details: Checks OS version, encryption, etc. Non-compliance (e.g., post-hibernation patch miss) blocks renewal.
    • Configuration Example (Intune):
    1. Intune > Devices > Compliance Policies > Create Policy.
    2. Require: Windows 10+, BitLocker enabled.
    3. Link to CA: Require compliant devices.
    • PowerShell Example:
      # Requires Intune Graph access
      $complianceParams = @{ /* JSON for policy */ }
      New-IntuneDeviceCompliancePolicy -BodyParameter $complianceParams
    • Impact: Shortens offline validity by enforcing checks on reconnect.

    5. Administrative Revocation

    Admins revoke PRTs via Graph, invalidating on reconnect.

    • Additional Details: Affects refresh tokens; access tokens expire in ~1 hour. Use with CAE for near-real-time.
    • Working PowerShell Example:
      Connect-MgGraph -Scopes "User.ReadWrite.All"
      $user = Get-MgUser -UserId "[email protected]"
      Revoke-MgUserSignInSession -UserId $user.Id
      Update-MgUser -UserId $user.Id -AccountEnabled $false
    • Impact: Flags PRTs for invalidation; delayed until reconnect.

    6. Password Reset or Account Changes

    Invalidates password-based PRTs; requires re-auth for new issuance.

    • Additional Details: SSPR or admin reset triggers; non-password PRTs (e.g., FIDO2) may persist.
    • Configuration Example: Enable SSPR in Entra; users reset via myaccount.microsoft.com.
    • Impact: Forces renewal failure on reconnect post-change.

    Table 2: Control Mechanisms Comparison

    MechanismConfigurability LevelOffline Renewal ImpactReconnect EnforcementExample Use Case
    SIFHigh (intervals in hours/days)Delays renewal promptRe-auth requiredRisky users needing frequent MFA
    Token ProtectionMedium (enable per app)Binding validationBlocks unboundPreventing token theft
    CAEHigh (events/policies)Real-time revocationClaim challengeLocation-based access control
    Device ComplianceHigh (Intune rules)Compliance checkBlocks non-compliantEnforcing patches post-hibernation
    Admin RevocationManual (per user)Invalidation flagImmediate blockCompromised account response
    Password ResetUser/Admin-initiatedInvalidationRe-auth with new credsPost-breach remediation

    Limitations on Direct Control

    The 4-hour renewal and 90-day inactivity are hardcoded for reliability—no API or policy alters them. Controls are reactive (on reconnect), not proactive offline. TPM failures add uncontrolled invalidation.

    Sample Scenarios with Working Details

    1. High-Security Environment with SIF and Token Protection:
    • Setup: 1-hour SIF + Token Protection for Teams.
    • Scenario: Laptop hibernates for 48 hours. On wake/reconnect, SIF triggers MFA; Token Protection checks binding. If TPM intact, renewal succeeds; else, error 1002 blocks.
    • Outcome: Effective offline limit reduced to ~1 hour post-reconnect.
    1. CAE in Risky Offline Reconnect:
    • Setup: CAE enabled with IP policy (trusted: 192.168.1.0/24).
    • Scenario: User offline in trusted location, then reconnects from untrusted IP. CAE issues 401 challenge; client re-auths, denying if policy violated.
    • Outcome: PRT revoked mid-renewal attempt.
    1. Compliance Failure Post-Hibernation:
    • Setup: Intune policy requires OS build >22621.
    • Scenario: Device hibernates, misses update. On reconnect, compliance check fails; PRT renewal blocked until remediation.
    • Outcome: Forces update, invalidating stale PRT.
    1. Admin Revocation for Terminated Employee:
    • Setup: Run Revoke-MgUserSignInSession.
    • Scenario: Offline device uses cached PRT. On reconnect, invalidation applies; access denied.
    • Outcome: Near-instant post-reconnect block with CAE.

    Practical Considerations

    • Testing: Use report-only mode and sign-in logs (filter for PRT events). Simulate hibernation with powercfg /hibernate on and disconnect.
    • Usability vs. Security: Frequent SIF (e.g., every time) boosts security but may cause 30-second delays on mobile.
    • Monitoring: Query logs for errors like 1003 (unsupported device).
    • Best Practices: Combine mechanisms (e.g., SIF + CAE) for layered defense; migrate to MgGraph PowerShell.

    By mastering these controls, you can transform PRT delayed renewal from a potential vulnerability into a managed asset. Experiment in a lab environment to see the interplay.

    References

  • Understanding Tokens in Microsoft Entra ID: Types, Lifetimes, and Beyond

    Understanding Tokens in Microsoft Entra ID: Types, Lifetimes, and Beyond

    In the world of modern identity and access management, tokens are the digital keys that unlock secure access to resources. Microsoft Entra ID (formerly Azure Active Directory) relies on these tokens to authenticate users, authorize applications, and enforce security policies. Whether you’re a developer building apps, an admin managing access, or a security pro auditing sessions, grasping the nuances of token types, their lifespans, and how they interplay with features like Conditional Access, MFA, and authentication strengths is crucial. This post dives deep into these elements, complete with tables, scenarios, and references to official Microsoft documentation.

    We’ll cover token types and lifetimes first, then explore how Conditional Access policies influence them, the ties to MFA and authentication strengths, resource and application access patterns, and finally, who (or what) can end a token’s life—think admin revocations or even a simple laptop hibernation.

    Token Types in Entra ID: The Building Blocks

    Entra ID issues several token varieties, each serving a distinct role in the authentication and authorization flow. They primarily follow OAuth 2.0 and OpenID Connect standards, with JSON Web Tokens (JWTs) as the common format for portability and verifiability.

    Here’s a quick comparison table of the core token types:

    Token TypePurposeFormatKey Claims/FeaturesTypical Use Case
    Access TokenAuthorizes access to protected resources (e.g., APIs) on behalf of a user. Not for proving identity.JWT (opaque to clients)aud (audience/resource), scp (scopes), exp (expiry), iss (issuer). Versions: v1.0 (Entra-only apps), v2.0 (consumer support).Calling Microsoft Graph API for email access in a mobile app.
    ID TokenProves successful authentication and provides user identity details for the client app.JWTsub (subject/user ID), email, name, iat/nbf/exp (timestamps), nonce (anti-replay).Signing into a web app and displaying user profile info.
    Refresh TokenRequests new access/ID tokens without re-authentication. Long-lived for seamless sessions.Opaque stringBound to user+client combo; self-renewing. Types: Confidential (secure apps), Public (e.g., SPAs).Background refresh of an expired access token in a desktop client.
    Primary Refresh Token (PRT)Device-bound token for SSO across apps on registered devices (Windows, iOS, etc.). Carries device claims for policy enforcement.Secure artifactTypes: Registered (Entra-joined devices), Unregistered (personal devices). Includes NGCPRT (Next Gen Crypto PRT) for enhanced security.SSO to Teams and Outlook on a compliant Windows laptop.

    Access tokens are the workhorses for resource calls—clients send them to APIs, which validate claims like audience (aud) and issuer (iss) against OpenID Connect metadata. ID tokens, meanwhile, are client-facing proofs of auth, packed with user claims but unsuitable for authorization. Refresh tokens keep sessions alive by trading themselves for fresh pairs, while PRTs supercharge device SSO, embedding compliance info for Conditional Access checks.

    Scenario: Building a Multi-Tenant App
    Imagine developing a SaaS tool that integrates with Microsoft 365. You request an authorization code flow, yielding an ID token for user login (verifying aud matches your app ID) and an access token scoped to Mail.Read. A refresh token handles token rotation every 90 days. For device users, a PRT enables silent SSO across tenants.

    Token Lifetimes: Defaults, Configurability, and Variability

    Token lifetimes balance security (short-lived = less exposure) with usability (no constant re-auth). Entra ID defaults are randomized for resilience, but you can tweak them via policies.

    • Access Tokens: 60-90 minutes (avg. 75 min), variable to avoid thundering herd issues. With Conditional Access Sign-in Frequency (SIF), add the interval (e.g., 1-hour SIF + 75-min token = up to 2.5-hour sessions). Configurable: 10 min to 1 day via Token Lifetime Policies (TLPs).
    • ID Tokens: Fixed 1 hour. Configurable: 10 min to 1 day, controlling app session expiry.
    • Refresh Tokens: 24 hours (SPAs, due to cookie restrictions) or 90 days (others). Self-renewing; max inactive period is 90 days. Not configurable—use SIF instead.
    • PRTs: 90 days, renewed every 4 hours on Windows (or on reconnect). Limited by SIF controls.

    Configurable Token Lifetimes (CTL): Apply organization-wide or per-app/service principal via Microsoft Graph (e.g., New-MgPolicyTokenLifetimePolicy). Requires Entra ID P1. Can’t override for refresh/PRT; SAML tokens get 1-hour default + 5-min skew.

    Table: Lifetime Impacts by Feature

    Feature/PolicyAccess Token EffectID Token EffectRefresh/PRT Effect
    Default60-90 min1 hour90 days / 90 days
    CTL Policy10 min-1 day10 min-1 dayN/A
    SIF (1 hour)+SIF interval (up to 2.5 hours)N/AControls max session
    CAE EnabledUp to 28 hours (long-lived)UnaffectedRevocation on events, not expiry

    Scenario: Enforcing Shorter Lifetimes for High-Risk Apps
    For a finance app, set a TLP to 15-min access tokens. Users re-auth every 15 min, but a 90-day refresh token minimizes prompts—until SIF kicks in for weekly interactive MFA.

    Conditional Access Policies: Shaping Token Behavior

    Conditional Access (CA) policies dynamically evaluate signals like user risk, location, and device compliance to grant/deny access, directly influencing tokens.

    • Session Lifetime Controls: Use “Sign-in frequency” to cap sessions (e.g., every 8 hours), overriding token expiry for re-eval. “Persistent browser session” extends via PRT for compliant devices.
    • Token Protection: A CA session control binding refresh tokens to devices (via PRT) to thwart replay attacks. Enforced for Exchange/Teams/SharePoint; blocks unbound tokens with errors like 1002 (no device state).
    • Continuous Access Evaluation (CAE): Extends access tokens to 28 hours while monitoring real-time events (e.g., account disable). Revokes via claim challenges on policy violations, integrated with CA for IP/location checks.

    Scenario: CA for Remote Workers
    Policy: Require compliant device + MFA for VPN access. On violation (e.g., risky IP), CAE revokes the 28-hour token instantly, forcing re-auth. Token Protection ensures only the bound device succeeds.

    MFA Correlation, Authentication Strengths, and Auth Types

    MFA ties deeply to tokens: Entra requires MFA satisfaction for tokens with MFA claims, embedding proofs in ID/access tokens. Authentication strengths refine this in CA, specifying method combos (e.g., password + Authenticator app).

    Built-in Strengths (non-editable):

    • MFA Strength: Password + any “something you have” (e.g., Authenticator push).
    • Passwordless MFA: FIDO2 key or Windows Hello (no password).
    • Phishing-Resistant MFA: FIDO2/CBA (multi-factor certs) for proof-of-possession.

    Custom strengths allow tailoring (e.g., FIDO2 + biometrics). Evaluated post-initial auth; unsatisfied prompts registration.

    Auth Types Covered:

    • OAuth 2.0: For access tokens (delegated/implicit flows).
    • OpenID Connect: Layers ID tokens on OAuth for auth.
    • SAML: Federated tokens (1-hour default).

    Scenario: Risk-Based MFA
    High-risk sign-in? CA policy requires Phishing-Resistant MFA strength. User taps FIDO2 key; token issues with claims proving resistance. Without it, access denied—correlating MFA directly to token validity.

    Table: MFA Methods by Strength

    MethodMFA StrengthPasswordlessPhishing-Resistant
    FIDO2 Security KeyYesYesYes
    Windows HelloYesYesYes
    Authenticator (Push)YesNoNo
    SMS/OTPYesNoNo

    Resource and Application Access: Tokens in Action

    Tokens drive access: Access tokens scope permissions (e.g., User.Read) for APIs; ID tokens bootstrap app sessions. Apps validate via metadata endpoints (e.g., /v2.0/.well-known/openid-configuration). For applications, PRTs enable SSO; refresh tokens support background access.

    Sample Flow (OAuth 2.0 + OIDC):

    1. User auths → ID token issued (1-hour life).
    2. App requests access token for Graph API → Scoped to resource.
    3. Expiry? Refresh token swaps for new pair.
      CA might interject: “Require MFA strength” → Token only if satisfied.

    Scenario: API Access in a Web App
    A React SPA uses MSAL.js: On login, gets ID token for UI, access token for backend proxy to Graph. CA policy blocks if from untrusted IP, revoking via CAE.

    Terminating Tokens: Revocation, Actions, and Scenarios

    Tokens don’t last forever—revocation ensures security. Who can terminate? Admins (via roles like Global Admin) revoke all refresh/PRTs per user (Revoke-MgUserSignInSession). Users self-revoke via portal. Apps enforce based on policies.

    Actions/Scenarios:

    • Admin Revoke: Instant for refresh/PRTs; access tokens expire naturally (1 hour). Impacts: New tokens blocked; sessions end on expiry.
    • Password Change/SSPR: Invalidates non-password-based tokens; PRTs require re-issue.
    • Account Disable/Delete: PRTs/tokens invalidated; cached sessions may linger until detection.
    • Network Disconnect: PRTs cached for offline SSO (up to 90 days); no termination, but renewal waits for reconnect (every 4 hours on Windows).
    • System Hibernation: No direct termination—PRT remains valid. Renewal delayed until wake + internet; if >90 days inactive, expires. TPM issues (e.g., post-hibernation failure) trigger recovery, invalidating PRT.
    • CAE Event: High risk? Policy revokes mid-session via claim challenge.

    Scenario: Emergency Revocation
    Suspected compromise: Admin disables account + revokes sessions. User on hibernated laptop wakes to expired PRT; network reconnect fails renewal due to disable—forced re-auth reveals block.

    Table: Termination Triggers

    TriggerAffected TokensTime to ImpactMitigation Example
    Admin RevokeRefresh/PRT/SessionImmediatePowerShell: Revoke-MgUserSignInSession
    Password ChangePRT/Non-password tokensOn next useRe-auth with new creds
    Network DisconnectNone (cached)NoneOffline SSO via PRT
    HibernationPRT (delayed renewal)Up to 90 daysWake + reconnect for renewal

    In summary, Entra ID tokens are a symphony of security and convenience—tune them wisely with CA and strengths. For hands-on, check the Graph API for TLPs or test CA policies in report-only mode.

    References

  • Adding an Application Registration\ Service Principal to another Application Registration\ Service Principal

    Adding an Application Registration\ Service Principal to another Application Registration\ Service Principal

    Typically when working with App Roles in Azure Active Directory for a single application registration or service principal and then self consuming that app role as an Application API Permission you would see in the Enterprise Application > Users and Groups blade that service principals are added.

    Every now and then a question comes up on assign service principals (application registrations) to other service principals (application registrations) without creating app roles. Is that possible?

    The answer is YES! It is possible.

    Here is how:

  • Get all the domains controllers in the AD forest along with their current FSMO roles

    Get all the domains controllers in the AD forest along with their current FSMO roles

    In a large enterprise an admin would need to keep track of all the domains in a AD forest, the domain names, the domain controllers (DC) , their IPs, and what FSMO roles does a DC hold. Wrote a little script to just do that…

  • Force synchronization for DFSR-replicated SYSVOL

    Force synchronization for DFSR-replicated SYSVOL

    One of my clients had a problem with processing GPO on client computers. Different computers applied different settings from the same GPO but from different domain controllers. All tests related to replication was successful, all GPOs are applied, but replication between domain controllers was a problem, and because of that most clients had a different GPO configuration.

    I had a similar problem with a newly promoted domain controller which I previously blogged about here.

    Scenarios where this problem typically occurs:

    • Replication was moved  from FRS to DFSR
    • Demoting an old domain controller in the environment
    • When there is a problem with the DFS replication of the SYSVOL folder

    To solve this problem, I had to manually perform an authoritative synchronization between the domain controllers.

    I am including steps for authoritative and non-authoritative synchronization, but before we get started we need to see the state of the replication.

    Steps:

    1. Find the state of the replication state. Typically the problem DCs will be at 0 or 2. The goal is to get to state 4.
    2. Get to State 2
    3. Get to State 4

    Find the state of the replication of all DCs

    For /f %i IN ('dsquery server -o rdn') do @echo %i && @wmic /node:"%i" /namespace:\\root\microsoftdfs path dfsrreplicatedfolderinfo WHERE replicatedfoldername='SYSVOL share' get replicationgroupname,replicatedfoldername,state

    The states should translate as below

    0 = Uninitialized
    1 = Initialized
    2 = Initial Sync
    3 = Auto Recovery
    4 = Normal
    5 = In Error

    Non-authoritative synchronization of DFSR-replicated SYSVOL

    • Stop the DFS Replication service (net stop dfsr).
    • In the ADSIEDIT.MSC tool modify the following distinguished name (DN) value and attribute on each of the domain controllers that you want to make non-authoritative:
      CN=SYSVOL Subscription,CN=Domain System Volume,CN=DFSR-LocalSettings,CN=<the server name>,OU=Domain Controllers,DC=<domain>
      msDFSR-Enabled=FALSE
    • Force Active Directory replication throughout the domain  (repadmin /syncall primary_dc_name /APed )
    • Run the following command from an elevated command prompt on the same servers that you set as non-authoritative:
      DFSRDIAG POLLAD 
    • You will see Event ID 4114 in the DFSR event log indicating SYSVOL is no longer being replicated (Open up event viewer and navigate to Applications and Services Logs -> DFS Replication).
    • On the same DN from Step 1, set:
      msDFSR-Enabled=TRUE
    • Force Active Directory replication throughout the domain (repadmin /syncall primary_dc_name /APed).
    • Start the DFS Replication service (net start dfsr).
    • Run the following command from an elevated command prompt on the same servers that you set as non-authoritative:
      DFSRDIAG POLLAD
    • You will see Event ID 4614 and 4604 in the DFSR event log indicating SYSVOL has been initialized. That domain controller has now done non-authoritative sync of SYSVOL.
    • Run Wmic /namespace:\\root\microsoftdfs path dfsrreplicatedfolderinfo get replicationgroupname,replicatedfoldername,stat and make sure the state is at 4. If it is at 2, it may take some time to reach state 4. Wait a few minutes and try again until all DCs are at state 4.

    Authoritative synchronization of DFSR-replicated SYSVOL

    1. Find the PDC Emulator (Elevated Command Prompt: netdom query fsmo ) – which is usually the most up to date for SYSVOL contents. Or the server holding all the policies and scripts. Consider this the primary server.
    2. Stop the DFS Replication service (net stop dfsr) on the primary server.
    3. On the primary server, In the ADSIEDIT.MSC tool, modify the following DN and two attributes to make authoritative:
      CN=SYSVOL Subscription,CN=Domain System Volume,CN=DFSR-LocalSettings,CN=<the server name>,OU=Domain Controllers,DC=<domain>
      msDFSR-Enabled=FALSE
      msDFSR-options=1
    4. Modify the following DN and single attribute on all other domain controllers in that domain:
      CN=SYSVOL Subscription,CN=Domain System Volume,CN=DFSR-LocalSettings,CN=<each other server name>,OU=Domain Controllers,DC=<domain>
      msDFSR-Enabled=FALSE
    5. Force Active Directory replication throughout the domain and validate its success on all DCs (repadmin /syncall primary_dc_name /APed). Probably need to run the same command 3-4 times.
    6. Start the DFSR service set as authoritative (net start dfsr) on the primary DC.
    7. You will see Event ID 4114 in the DFSR event log indicating SYSVOL is no longer being replicated (Open up event viewer and navigate to Applications and Services Logs -> DFS Replication).
    8. On the same DN from Step 1, set:
      msDFSR-Enabled=TRUE
    9. Force Active Directory replication throughout the domain and validate its success on all DCs (repadmin /syncall primary_dc_name /APed ). Probably need to run the same command 3-4 times.
    10. Run the following command from an elevated command prompt on the same server that you set as authoritative (primary server):
      DFSRDIAG POLLAD 
    11. Wait a few minutes you will see Event ID 4602 in the DFSR event log (Open up event viewer and navigate to Applications and Services Logs -> DFS Replication) indicating SYSVOL has been initialized. That domain controller has now done an authoritative sync of SYSVOL.
    12. Start the DFSR service on the other non-authoritative DCs (net start dfsr). You will see Event ID 4114 in the DFSR event log indicating SYSVOL is no longer being replicated on each of them.
    13. Modify the following DN and single attribute on all other domain controllers in that domain:
      CN=SYSVOL Subscription,CN=Domain System Volume,CN=DFSR-LocalSettings,CN=<each other server name>,OU=Domain Controllers,DC=<domain>
      msDFSR-Enabled=TRUE
    14. Run the following command from an elevated command prompt on all non-authoritative DCs (i.e. all but the formerly authoritative one):
      DFSRDIAG POLLAD
    15. Verify you see Event ID 2002 and 4602 on all other domain controllers.
    16. Run Wmic /namespace:\\root\microsoftdfs path dfsrreplicatedfolderinfo get replicationgroupname,replicatedfoldername,stat and make sure the state is at 4. If it is at 2, it may take some time to reach state 4. Wait a few minutes and try again until all DCs are at state 4.

    [su_note note_color=”#f9f4ca” text_color=”#000000″ radius=”2″]If setting the authoritative flag on one DC, you must non-authoritatively synchronize all other DCs in the domain. Otherwise, you will see conflicts on DCs, originating from any DCs where you did not set auth/non-auth and restarted the DFSR service. For example, if all logon scripts were accidentally deleted and a manual copy of them was placed back on the PDC Emulator role holder, making that server authoritative and all other servers non-authoritative would guarantee success and prevent conflicts. If making any DC authoritative, the PDC Emulator as authoritative is preferable, since its SYSVOL contents are usually most up to date. The use of the authoritative flag is only necessary if you need to force synchronization of all DCs. If only repairing one DC, simply make it non-authoritative and do not touch other servers. This article is designed with a 2-DC environment in mind, for simplicity of description. If you had more than one affected DC, expand the steps to includeALL of those as well. It also assumes you have the ability to restore data that was deleted, overwritten, damaged, etc. previously if this is a disaster recovery scenario on all DCs in the domain.[/su_note]

    After these actions, all problems with GPO processing and SYSVOL replication disappeared. 🙂

  • Get Inactive Users Report for the past 60 days in a multi domain environment

    Get Inactive Users Report for the past 60 days in a multi domain environment

    I had a request recently to provide an inactive user report for the past 60 days. Basically, find out which accounts have not logged in for the past 60 days so action can be taken against them.

    The request was for a multi domain forest which queries every domain controller and gets the latest lastlogon value by comparing value from each. I wrote a script and wanted to share as other might find it handy too.

  • Get Primary, Secondary, Tertiary DNS values and more from Multiple Servers

    Get Primary, Secondary, Tertiary DNS values and more from Multiple Servers

    Came across a unique request to get primary, secondary, and tertiary DNS values for multiple computers/servers across the domain. I started writing the script and got what I wanted.

    Now this started off as just to query for DNS Server information, but then I thought to add other pieces to get myself a good Network Inventory of all the servers in the environment.

    I am utilizing the Win32_NetworkAdapterConfiguration WMI Class to get the required information.

    You can modify the script below to suit your needs. The complete list of settings that can be captured:

      string   Caption;
      string   Description;
      string   SettingID;
      boolean  ArpAlwaysSourceRoute;
      boolean  ArpUseEtherSNAP;
      string   DatabasePath;
      boolean  DeadGWDetectEnabled;
      string   DefaultIPGateway[];
      uint8    DefaultTOS;
      uint8    DefaultTTL;
      boolean  DHCPEnabled;
      datetime DHCPLeaseExpires;
      datetime DHCPLeaseObtained;
      string   DHCPServer;
      string   DNSDomain;
      string   DNSDomainSuffixSearchOrder[];
      boolean  DNSEnabledForWINSResolution;
      string   DNSHostName;
      string   DNSServerSearchOrder[];
      boolean  DomainDNSRegistrationEnabled;
      uint32   ForwardBufferMemory;
      boolean  FullDNSRegistrationEnabled;
      uint16   GatewayCostMetric[];
      uint8    IGMPLevel;
      uint32   Index;
      uint32   InterfaceIndex;
      string   IPAddress[];
      uint32   IPConnectionMetric;
      boolean  IPEnabled;
      boolean  IPFilterSecurityEnabled;
      boolean  IPPortSecurityEnabled;
      string   IPSecPermitIPProtocols[];
      string   IPSecPermitTCPPorts[];
      string   IPSecPermitUDPPorts[];
      string   IPSubnet[];
      boolean  IPUseZeroBroadcast;
      string   IPXAddress;
      boolean  IPXEnabled;
      uint32   IPXFrameType[];
      uint32   IPXMediaType;
      string   IPXNetworkNumber[];
      string   IPXVirtualNetNumber;
      uint32   KeepAliveInterval;
      uint32   KeepAliveTime;
      string   MACAddress;
      uint32   MTU;
      uint32   NumForwardPackets;
      boolean  PMTUBHDetectEnabled;
      boolean  PMTUDiscoveryEnabled;
      string   ServiceName;
      uint32   TcpipNetbiosOptions;
      uint32   TcpMaxConnectRetransmissions;
      uint32   TcpMaxDataRetransmissions;
      uint32   TcpNumConnections;
      boolean  TcpUseRFC1122UrgentPointer;
      uint16   TcpWindowSize;
      boolean  WINSEnableLMHostsLookup;
      string   WINSHostLookupFile;
      string   WINSPrimaryServer;
      string   WINSScopeID;
      string   WINSSecondaryServer;

    Since the scripts are querying for information it is best if it runs from a DC or a privileged server with an account that has privileged access.

    To get the results you need the following two scripts:

    I needed to get all the network information for all the domain controllers in the domain. So the following code retrieves it for me. This came really handy in viewing all the DNS settings setup on all the DCs and correcting them if needed.

    This will get the information and export to an excel file that you can have handy for reference or auditing. Hope this helps!

  • Fix Active Directory broken security inheritance problem

    Fix Active Directory broken security inheritance problem

    Ran into a situation at a client location where in Active Directory, the security permissions applied to an OU were not getting inherited permissions on to the objects. Basically, security inheritance was broken.This causes a problem when the administrative accounts or groups needing to modify an attribute on the AD object throw errors, or are unable to edit the AD object.

    To find out which objects were not getting the inherited permissions run the following :

    I ran it on the entire domain to identity potential problem accounts. 🙂

    To fix the issue:

    Reference:

    https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.objectsecurity.areaccessrulesprotected?view=netframework-4.8
    https://blogs.msdn.microsoft.com/adpowershell/2009/10/22/viewconfigure-protected-acl-and-fixing-broken-inheritance/

  • Get All DCs in the Entire Forest

    Get All DCs in the Entire Forest

    Getting a know a new environment for a new client and I a quickly needed information about all domain controllers in the entire forest.

    Wrote a small little script to provide me all the information I needed:

    Import-Module ActiveDirectory
    
    function Get-AllDCsInForest{
    [CmdletBinding()]
    param(
        [string]$ReferenceDomain = $env:USERDOMAIN
    )
     
    $ForestObj = Get-ADForest -Server $ReferenceDomain
    foreach($Domain in $ForestObj.Domains) {
        Get-ADDomainController -Filter * -Server $Domain | select Domain,HostName,Site, IPv4Address, OperatingSystem, OperatingSystemVersion
         
    }
     
    }
    
    Get-AllDCsInForest| Export-Csv -Path C:\Scripts\AllDcs.txt -NoTypeInformation