<?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 Danny Shemesh on Medium]]></title>
        <description><![CDATA[Stories by Danny Shemesh on Medium]]></description>
        <link>https://medium.com/@dany74q?source=rss-61284e9ecb66------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OrHe6DTz485qpGNfWF-C5w.jpeg</url>
            <title>Stories by Danny Shemesh on Medium</title>
            <link>https://medium.com/@dany74q?source=rss-61284e9ecb66------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 17:57:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dany74q/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[Service to Service Auth with Azure AD, MSI & OAuth 2.0 (Step by Step)]]></title>
            <link>https://medium.com/@dany74q/service-to-service-auth-with-azure-ad-msi-oauth-2-0-step-by-step-a1aed196b1e1?source=rss-61284e9ecb66------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1aed196b1e1</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[service-to-service]]></category>
            <category><![CDATA[azure-active-directory]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Danny Shemesh]]></dc:creator>
            <pubDate>Mon, 21 Oct 2019 22:30:44 GMT</pubDate>
            <atom:updated>2019-10-21T22:30:44.240Z</atom:updated>
            <content:encoded><![CDATA[<p>Heya, readers !</p><p>A few weeks ago, while coding a small framework for building lean microservices — I’ve tried to solve its authentication &amp; authorization layer needs by utilizing Azure AD with OAuth 2.</p><p>An appropriate service to service auth flow, I’ve imagined, should look something like the following:</p><figure><img alt="Service to Service OAuth flow" src="https://cdn-images-1.medium.com/max/695/1*tvmH_BKAQTbfuv2oiLUzOg.png" /><figcaption>Potential Auth flow between two services</figcaption></figure><p>At its core, I’d wanted to fulfill the following requirements from the auth layer — given two communicating services, A and B:</p><ul><li>Service A should be able to expose some specific ‘roles’ / ‘scopes’ (I’ll be using <em>roles</em> throughout this article), for instance, ‘Service A Reader’ and ‘Service A Writer’</li><li>An authorized Azure user, should be able to grant Service B access to some, or all roles of Service A — <strong>without </strong>tenant wide <em>admin consent</em></li><li>Roles should be visible in the signed JWT OAuth token, so RBAC could be implemented on top of it</li><li>An access to Service A endpoint with a given token should be verifiable by its audience (<em>aud</em> JWT field), issuing date (<em>nbf</em> JWT field), expiry (<em>exp </em>JWT field<em>)</em>, signature (JWT’s footer), issuer (<em>iss </em>JWT field) and roles (e.g. ‘Service A Writer’ for some write-semantic operation)</li><li><strong>Bonus #1</strong>: Make Azure AD deny token creation for AD entities with no assigned roles (i.e. only role-bearing clients would be able to create a token for our service, in the first place)</li><li><strong>Bonus #2</strong>: Have the ability to use Managed Identities (MSI &amp; IMDS) in order to issue access tokens from specific VMs without storing the generated client credentials</li><li><strong>Bonus #3</strong>: Minimize manual processes that requires user interaction with Azure Portal</li></ul><p>After a day or so of playing with Azure AD’s enterprise applications solution, I’ve managed to accommodate the above criteria, and in this article I’ll delve upon each point individually.</p><h4>Choosing an appropriate OAuth 2 flow</h4><p>We’ll be using OAuth 2 in our solution, and so one of the first things we need to cover is choosing an appropriate OAuth 2 flow.</p><p>A quick overview of Azure AD’s OAuth 2 flows is given below (feel free to skip if you’re already familiar with them):</p><ul><li><a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow"><strong>Authorization code</strong></a> flow — Requires user interaction and consent, typically via the web browser, to get a code which is then used to issue an access token</li><li><a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-implicit-grant-flow"><strong>Implicit grant</strong></a> flow — Created for single page web / mobile webview apps, where token creation and handling is done entirely from the front end</li><li><a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow"><strong>On-behalf-of</strong></a> flow — Helps us use one user-bound access token, to create another user-bound access token, for a different resource (e.g. Service A uses a given token to issue a new, user-bound token, for service B)</li><li><a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-device-code"><strong>Device code</strong></a> flow — Useful for input-constraint devices (IoT peripherals, for instance), helps the user to consent on an out-of-band channel, such as their browser on their computer, via a code and URL displayed on the constrained device</li><li><a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth-ropc"><strong>Resource Owner Password Credentials</strong></a> (<em>ROPC</em>) flow — Mostly used in legacy applications, where a service holds the actual user credentials</li><li><a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-saml-bearer-assertion"><strong>SAML bearer assertion</strong></a> flow — An interop between SAML assertions and OAuth, which allows a service to use an already issued SAML assertion to create an OAuth access token</li><li><a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow"><strong>Client Credentials</strong></a> flow — The only flow that does not require immediate user interaction, usually used when the OAuth client is acting on-behalf of itself, when user-consent doesn’t make sense, or when authorization primitives could be configured out-of-band (for instance via Azure AD)</li></ul><p>Reviewing the supported OAuth flows against our use case, where the user is a service, which would like issue token for a different service — the <em>client credentials flow </em>seems most appropriate, and indeed we’ll be using it throughout the rest of the article.</p><h4>Application registration within AAD</h4><p>Now that we’ve settled on the OAuth flow to be used by our services, we need to be able to identify them within Azure AD — for that end, let’s register our applications (Note: You must have app-registration permissions within your Azure AD instance)</p><p><strong>Registering our applications via the portal</strong></p><p>1. Go to your Azure AD instance</p><figure><img alt="Azure AD instance" src="https://cdn-images-1.medium.com/max/693/1*p52lWCBmV2O1w2K_kQd87A.png" /></figure><p>2. Click on ‘App registrations’ on the side bar</p><figure><img alt="App registrations" src="https://cdn-images-1.medium.com/max/306/1*2m00cFFjZrMQVV5eBjXVYA.png" /></figure><p>3. Click on ‘New registration’ on the top command bar</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*etBkNaHEgb0d4ZMXR-wJVA.png" /></figure><p>4. Choose an appropriate name, the tenant scope (single / multi tenant app), and ‘Web API’ as the platform configuration</p><p>5. Repeat steps 1–4 above for Service B</p><p>Great ! We now have our services identifiable in Azure AD via the application registrations we’ve just created.</p><h4>Adding custom service roles</h4><p>Our next requirement is to be able to expose custom roles in our applications — let’s do just that, in this example, I’m going to add ‘Service.A.Reader’ and ‘Service.A.Writer’ roles to the previously created ‘Service A’ application.</p><p><strong>Adding custom service roles via Azure Portal</strong></p><ol><li>Go to the ‘App registration’ blade within Azure Active Directory</li></ol><figure><img alt="AAD App registrations" src="https://cdn-images-1.medium.com/max/306/1*2m00cFFjZrMQVV5eBjXVYA.png" /></figure><p>2. Click on your application within the registration blade</p><figure><img alt="Owned application" src="https://cdn-images-1.medium.com/max/333/1*_2r7Khf3_dC48Upz5afZrA.png" /></figure><p>3. Go to the application manifest</p><figure><img alt="AAD application manifest" src="https://cdn-images-1.medium.com/max/328/1*29Rn7gl6sZcatXYY9_MXhA.png" /></figure><p>4. Add your custom application role objects to the ‘<em>appRoles</em>’ JSON field within the manifest:</p><pre>&quot;appRoles&quot;: [{<br>    &quot;allowedMemberTypes&quot;: [&quot;Application&quot;],<br>    &quot;description&quot;: &quot;Reader Role&quot;,<br>    &quot;displayName&quot;: &quot;Service A Reader&quot;,<br>    &quot;id&quot;: &quot;13371337-1337-1337-1337-133713371337&quot;,<br>    &quot;isEnabled&quot;: true,<br>    &quot;value&quot;: &quot;Service.A.Reader&quot;<br>},<br>{<br>    &quot;allowedMemberTypes&quot;: [&quot;Application&quot;],<br>    &quot;description&quot;: &quot;Writer Role&quot;,<br>    &quot;displayName&quot;: &quot;Service A Writer&quot;,<br>    &quot;id&quot;: &quot;13371337-1337-1337-1337-133713371338&quot;,<br>    &quot;isEnabled&quot;: true,<br>    &quot;value&quot;: &quot;Service.A.Writer&quot;<br>}],</pre><p>Note: The role “id” could be any string, and there’s no uniqueness constraints between cross-application roles; Using a GUID is a good best practice, though.</p><p>5. Click on ‘Save’ to save the manifest</p><p>You have now successfully configured custom roles for your application, using the above as a template, you may create any custom role with your own service semantics (Starting with CRUD-like semantics might make sense for a lot of services, though)</p><h4>Setting an Application ID URI (OAuth resource URI) and generating App Credentials</h4><p>At this point, we’ve introduced two applications to our Azure AD instance, and have configured some custom roles for one of them.</p><p>This is a good point to segue into configuring our applications to support the OAuth client credentials flow — for this we’d need to:</p><ol><li>Define a unique Application ID URI, and</li><li>Generate app credentials</li></ol><p><strong>Adding an Application ID URI via Azure Portal</strong></p><ol><li>Within Azure AD App registration blade, go to your application (as shown in previous steps)</li><li>Go to the ‘Expose an API’ blade</li></ol><figure><img alt="Expose API blade" src="https://cdn-images-1.medium.com/max/332/1*6cdzdkPXAiUu5joRoapXsQ.png" /></figure><p>3. Click on the ‘Set’ button near the Application ID URI div</p><figure><img alt="Set application ID URI" src="https://cdn-images-1.medium.com/max/264/1*0pWeXWCXg3496mJ9WIoYYQ.png" /></figure><p>4. You may accept the default value of ‘api://&lt;appId&gt;’, In this example I’ll set it to ‘api://service-a.example.com’ (Note: The URI could be any string with a supported URI scheme, e.g. api://, <a href="https://,/">https://,</a> …)</p><p>5. Repeat the above for service B, changing the URI appropriately</p><p>Neat — You have now configured a valid application URI to be used when issuing OAuth tokens for your services.</p><p><strong>Generating application credentials via Azure Portal</strong></p><p>Moving on, we would now like for service B to access service A, given the application URI set for it above.</p><p>In order to generate a valid access token with Azure AD, we’d need to generate application credentials to be used when authentication our service to Azure AD.</p><ol><li>Within Azure AD app registration blade, go to Service B (the <em>client</em> of service A — as shown in the previous steps)</li><li>Go to the ‘Certificates &amp; secrets’ blade</li></ol><figure><img alt="Certificates and secrets blade" src="https://cdn-images-1.medium.com/max/331/1*Fs0q37OFllioBf6XfuKO4g.png" /></figure><p>3. Click on ‘New client secret’ to generate application credentials (Note: you can think of the application ID as a <em>username</em>, and the generated secret as a <em>password</em>, for authenticating to Azure AD)</p><figure><img alt="New client secret" src="https://cdn-images-1.medium.com/max/307/1*nxKNZIUqLif1yMywf6hTkQ.png" /></figure><p>4. Set an appropriate description, and choose an expiry time which you’re comfortable with, then click ‘Add’</p><figure><img alt="Adding application credentials" src="https://cdn-images-1.medium.com/max/346/1*_gn551jDAcCy147041TkAg.png" /></figure><p>5. Save the generated credentials value, we’ll use it later on (from here on, I’ll reference it as ‘client secret’)</p><h4>Issuing &amp; inspecting our first OAuth token</h4><p>At this stage, we should be able to issue tokens to Service A, on behalf of Service B — let’s see that in action.</p><ol><li>In Azure AD application registration blade, go to Service B (as shown in previous steps)</li><li>In the <em>Overview</em> blade, Click on the ‘Endpoints’ button at the command bar</li></ol><figure><img alt="Azure AD endpoints" src="https://cdn-images-1.medium.com/max/303/1*KsiEPgHDanWK1GH7Dhrq7w.png" /></figure><p>3. In the opened <em>Endpoints </em>blade, copy the <em>OAuth 2.0 token endpoint (v2) </em>URL</p><figure><img alt="OAuth 2 token endpoint (v2)" src="https://cdn-images-1.medium.com/max/1019/1*68EiSLmgSBVb-9qwCsETRA.png" /></figure><p>4. Issue a HTTP POST call for the given URL with the following parameters (Note: Be sure to replace all templated parameters annotated by brackets, e.g. &lt;param&gt;):</p><pre>$&gt; curl -s -XPOST &lt;token-v2-endpoint&gt; \<br>-d grant_type=client_credentials \<br>-d client_id=&lt;service-<strong>b</strong>-app-id&gt; \<br>-d client_secret=&lt;service-<strong>b</strong>-client-secret&gt; \<br>-d scope=&lt;service-<strong>a</strong>-application-id-uri&gt;/.default</pre><p>Note: Append a <em>“/.default” </em>to the configured URI, in our example it would be: api://service-a.example.com/.default</p><p>5. You should now have been issued a valid, signed, JWT-encoded access token — for accessing service B on behalf of service A; Copy the ‘access_token’ value to <a href="https://jwt.ms/">https://jwt.ms</a> to inspect your token</p><figure><img alt="Decoded JWT" src="https://cdn-images-1.medium.com/max/660/1*uyON3dIPKXkXpvYkK-L_3Q.png" /></figure><p>Inspecting the above, we could note that:</p><ul><li>The <em>kid</em> (key id) field in the header identifies the certificate which was used to sign the JWT</li><li>The <em>aud (audience) </em>field represents our ‘server’ Application ID URI(Service A, in our example)</li><li>The <em>iss (issuer) </em>field represents the Security Token Service issued the token (Azure AD)</li><li>The <em>nbf (not before) </em>field represents the minimum acceptance time of the token (i.e. the token isn’t valid before that time)</li><li>The <em>exp </em>field denotes the expiry time as epoch in seconds</li><li>The <em>appid </em>field shows the <em>client </em>id (Service B, in our example)</li><li>We would use all of the above later on, when verifying that a token is indeed valid</li><li>You can read more about all the other fields in the JWT <a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/access-tokens">here</a></li></ul><p>Note that one thing that is missing from our token — is any mention of the custom roles we’ve assigned to service A; We’ll deal with that in the next step.</p><h4>Granting custom roles to an Azure AD application (without Tenant-Admin Consent)</h4><p>In order to implement RBAC on top of our issued OAuth JWT access tokens, we’d like to grant Service B a custom role of Service A.</p><p>Usually, the above is implemented via OAuth <em>scopes</em>, and you might’ve seen that in Azure AD’s ‘<em>Expose an API</em>’ blade</p><figure><img alt="OAuth scopes in AAD" src="https://cdn-images-1.medium.com/max/297/1*BqB__LrKZyuRNYz49PTytg.png" /></figure><p>However, adding custom scopes, at least in Azure AD — only applies for OAuth flows with user consent (not client credentials).</p><p>When using the client credentials flow, we must fallback to use application roles instead — if we were to try to add our configured <em>Service.A.Reader </em>role via the API permissions blade in Azure Portal, we’ll be quick to note that this operation requires tenant-admin consent;</p><figure><img alt="Tenant Admin consent" src="https://cdn-images-1.medium.com/max/1024/1*Q3AerBJDSUbLsMLCuydVFw.png" /></figure><p>In large enterprises, though, a tenant-admin consent might involve quite a bit of ceremony — dealing with in house ticketing systems, or talking to a remote IT / Ops department might take up to a few days, in some cases.</p><p>To grant a custom role to an application, without the need of admin consent, we can instead use the Microsoft Graph API (Note: There’s no way to execute this operation within Azure Portal, as of the time of writing).</p><p><strong>Using Graph API to grant roles to a registered application</strong></p><p>We’ll be invoking the <a href="https://docs.microsoft.com/en-us/graph/api/serviceprincipal-post-approleassignments?view=graph-rest-beta&amp;tabs=http">appRoleAssignment creation API</a> from Microsoft Graph on service A — this could be easily invoked via Azure CLI:</p><pre>$&gt; az rest \<br>--method post \<br>--uri https://graph.microsoft.com/beta/servicePrincipals/&lt;service-<strong>a</strong>-enterprise-object-id&gt;/appRoleAssignments \<br>-- headers &quot;{\&quot;content-type\&quot;: \&quot;application/json\&quot;}&quot; \<br>-- body &quot;{\&quot;appRoleId\&quot;: \&quot;&lt;roleId&gt;\&quot;, \&quot;principalId\&quot;: \&quot;&lt;service-<strong>b</strong>-enterprise-object-id&gt;\&quot;, <br>\&quot;principalType\&quot;: \&quot;ServicePrincipal\&quot;, \&quot;resourceId\&quot;: \&quot;&lt;service-<strong>a</strong>-enterprise-object-id&gt;\&quot;}&quot;</pre><p>Let’s break it down:</p><ul><li>We are invoking the appRoleassignments creation Graph API on the Enterprise Application (more on the difference between an Enterprise Application and Application registration below) of Service A (Denoted by the Object ID) — note that this is done similarly to how you would control access to Azure resources, like Azure Key Vault, where you add client grants to the ‘server’ service</li><li>We are passing it a role ID (In this tutorial, the Service.A.Reader role has an ID of <em>13371337–1337–1337–1337–133713371337)</em></li><li>We are passing in the principal ID of the Enterprise Application of Service B (Denoted by the Object ID)</li><li>The principal type is “Service Principal”</li><li>We pass in a target resource, which is once again, the Object ID of the Enterprise Application of Service A</li></ul><p>In order to get the proper Object ID of both services, you should:</p><ol><li>Go to the <em>App registration</em> blade in Azure AD (as shown in previous steps)</li><li>Go to the relevant application (as shown in previous steps)</li><li>In the <em>Overview </em>tab, verify the application has an Enterprise Associated with it, by looking at the “<em>Managed application in local directory</em>” div</li></ol><figure><img alt="Create service principal — enterprise application" src="https://cdn-images-1.medium.com/max/447/1*ZGiqSIy3xHBPspVqh6wrZg.png" /></figure><p>4. If you see a ‘Create Service Principal’ link like above, click on it and wait for a few minutes — this will create an Enterprise Application instance for your app registration</p><p>5. Once an Enterprise Application is created, you should see have a hyperlink pointing to it in the same div above</p><figure><img alt="Enterprise application hyperlink" src="https://cdn-images-1.medium.com/max/370/1*iB80IVfGrmaCs0izfSIRQw.png" /></figure><p>6. Clicking on the above will lead you to the relevant Enterprise Application, which will show the Object ID you should use in the REST call above</p><figure><img alt="Enterprise Application Object ID" src="https://cdn-images-1.medium.com/max/974/1*22ldxstd8harXWFrdgw75g.png" /></figure><p>7. Alternatively, you could search your application in the <em>Enterprise Applications </em>blade of your Azure AD instance</p><p>A successful invocation should look similar to the below:</p><pre>This command is in preview. It may be changed/removed in a future release.<br>{<br> &quot;<a href="http://twitter.com/odata">@odata</a>.context&quot;: &quot;<a href="https://graph.microsoft.com/beta/$metadata#appRoleAssignments/$entity">https://graph.microsoft.com/beta/$metadata#appRoleAssignments/$entity</a>&quot;,<br> &quot;appRoleId&quot;: &quot;13371337–1337–1337–1337–133713371339&quot;,<br> &quot;creationTimestamp&quot;: &quot;2019–10–21T18:20:53.9088367Z&quot;,<br> &quot;id&quot;: &quot;Hl8A-br-1kugbGxg1gpt2sQktBGJedJNiheeF4x1KBo&quot;,<br> &quot;principalDisplayName&quot;: &quot;Service B&quot;,<br> &quot;principalId&quot;: &quot;f9005f1e-feba-4bd6-a06c-6c60d60a6dda&quot;,<br> &quot;principalType&quot;: &quot;ServicePrincipal&quot;,<br> &quot;resourceDisplayName&quot;: &quot;Service A&quot;,<br> &quot;resourceId&quot;: &quot;38b8c0f9–837a-4abd-816f-bc51282519e2&quot;<br>}</pre><p>We may now verify that the role was in fact granted, by:</p><ol><li>Going to the <em>Enterprise Applications</em> blade within Azure AD</li></ol><figure><img alt="Enterprise application blade" src="https://cdn-images-1.medium.com/max/308/1*QZWkkRLHmSrMPLb4EF1Jeg.png" /></figure><p>2. Clicking on the Enterprise application instance of Service A (the ‘Server’ app)</p><figure><img alt="Service A enterprise application" src="https://cdn-images-1.medium.com/max/202/1*5Fxx8J5_r2Qycy5gRjRCdQ.png" /></figure><p>3. Going to the <em>Users and Groups</em> blade</p><figure><img alt="Users and groups blade" src="https://cdn-images-1.medium.com/max/312/1*WXH0UOfStS5fwNSIyC-ijA.png" /></figure><p>4. The users table should show Service B, in a fashion similar to the below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CxUisoqpd-WT-TfBm3oN4A.png" /><figcaption>As the time of this writing, the Azure Portal doesn’t render ServicePrincipal types correctly (note the missing Role assigned, the corrupted icon)</figcaption></figure><p>Note: You might’ve noticed that the object ID shown in the app registration blade for your service, differs from the object ID in the enterprise application blade.</p><p>The difference between app registrations and an enterprise applications, is that an app registration is an instance of your application in <strong>Azure AD</strong> (this could be single or multi tenant); The object id shown there represents the <strong>application</strong> itself.</p><p>An enterprise application, though, is a unique ‘<em>instance</em>’ of a given application within your Azure AD directory; You may install multi-tenant applications (from, say, the Azure AD gallery) in several directories, each of them will get a unique service principal (object id) in the enterprise application blade.</p><h4>Inspecting assigned roles within the JWT</h4><p>We have now assigned our custom roles to Service B, and subsequent AAD issued tokens should include them within the JWT — let’s take a quick look:</p><ol><li>Issue a new access token (similar to previous steps)</li></ol><pre>$&gt; curl -s -XPOST &lt;token-v2-endpoint&gt; \<br>-d grant_type=client_credentials \<br>-d client_id=&lt;service-b-app-id&gt; \<br>-d client_secret=&lt;service-b-client-secret&gt; \<br>-d scope=&lt;service-a-application-id-uri&gt;/.default</pre><p>2. Inspect the access token in <a href="https://jwt.ms/">https://jwt.ms</a></p><figure><img alt="JWT with roles" src="https://cdn-images-1.medium.com/max/654/1*I9pZKjKRiHunJ5Sab4zsCg.png" /></figure><p>3. Note that the JWT above now holds a ‘roles’ field, containing the role we’ve assigned to Service B</p><p>We may now verify that a token holds a requested role, and implement RBAC on top of it.</p><h4>Enforcing tokens could only be issued for applications with one or more roles</h4><p>Depending on your use case, it might be beneficial to delegate some authorization work to Azure AD, and have it enforce that only applications that have assigned roles, could issue tickets for your services.</p><p>The above could be configured on the server application (Service A, in this write up):</p><ol><li>Open your service Enterprise Application instance (as shown in previous steps)</li></ol><figure><img alt="Properties blade in Enterprise Applications" src="https://cdn-images-1.medium.com/max/309/1*tXQykff9-BsA9lhiGS-5TQ.png" /></figure><p>2. Set the <em>User assignment required ? </em>Options to <em>yes</em></p><figure><img alt="Enforce user assignment" src="https://cdn-images-1.medium.com/max/426/1*2RTPkc_K4zCjOaLDf5W6oQ.png" /></figure><p>3. Click the ‘Save’ button in the command bar</p><figure><img alt="Save button" src="https://cdn-images-1.medium.com/max/209/1*xVtgWktaW5U30MZcvE5exA.png" /></figure><p>That’s it — issuing tokens with applications that do not have at least one application role will now fail, as shown below:</p><pre>{<br>    &quot;error&quot;:&quot;invalid_grant&quot;,<br>    &quot;error_description&quot;:&quot;AADSTS501051: Application &#39;dd4f719c-fd7b-44f7–9c83–3eae26c72df6&#39;(Service C) is not assigned to a role for the application &#39;api://service-a.example.com&#39;(Service A).\r\nTrace ID: ce5fd681-b9fd-4d5c-a4d3-e10bcc072100\r\nCorrelation ID: bcc383b8–3680–41a2-b4c8–44fb33308776\r\nTimestamp: 2019–10–21 19:41:18Z&quot;,<br>    &quot;error_codes&quot;:[501051],<br>    &quot;timestamp&quot;:&quot;2019–10–21 19:41:18Z&quot;,<br>    &quot;trace_id&quot;:&quot;ce5fd681-b9fd-4d5c-a4d3-e10bcc072100&quot;,<br>    &quot;correlation_id&quot;:&quot;bcc383b8–3680–41a2-b4c8–44fb33308776&quot;,<br>    &quot;error_uri&quot;:&quot;<a href="https://login.microsoftonline.com/error?code=501051">https://login.microsoftonline.com/error?code=501051</a>&quot;<br>}</pre><h4>Using Managed Identities (MSI) and IMDS to issue tokens, without an app secret</h4><p>If you’re like me, you want to minimize the amount of secrets floating around in your services to a minimum — <a href="https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview">Managed Identities</a> are pretty cool, and can accommodate this need.</p><p>Using an Azure managed identity, and assigning it to an Azure VM, you’ll be able to issue tokens from that VM, on behalf of the identity, without supplying any credentials.</p><p>Let’s create a managed user identity, assign the ‘<em>Service.A.Writer</em>’ role to it, bind it to an azure VM, and use <a href="https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service">IMDS</a> to issue a token for service A:</p><ol><li>Create a resource group to host the identity via azure CLI:</li></ol><pre>$&gt; az group create --location westus --name &quot;service-b-identity-resource-group&quot;</pre><p>2. Create a managed user identity in the above resource group via azure CLI:</p><pre>$&gt; az identity create --location westus --resource-group &quot;service-b-identity-resource-group&quot; --name &quot;service-b-identity&quot;</pre><p>A successful operation should output something similar to:</p><pre>{<br>  &quot;clientId&quot;: &quot;15bd7d57-d563-433b-b018-d411baff4d49&quot;,<br>  &quot;clientSecretUrl&quot;: &quot;<a href="https://control-westus.identity.azure.net/subscriptions/002950da-c26e-496c-bf63-713556881cd9/resourcegroups/service-b-identity-resource-group/providers/Microsoft.ManagedIdentity/userAssignedIdentities/service-b-identity/credentials?tid=72f988bf-86f1-41af-91ab-2d7cd011db47&amp;oid=60795881-d04c-4435-9cac-66ee28613eac&amp;aid=15bd7d57-d563-433b-b018-d411baff4d49">https://control-westus.identity.azure.net/subscriptions/&lt;subscription-id&gt;/resourcegroups/service-b-identity-resource-group/providers/Microsoft.ManagedIdentity/userAssignedIdentities/service-b-identity/credentials?tid=&lt;tenant-id&gt;&amp;oid=&lt;object-id&gt;&amp;aid=&lt;</a>client-id&gt;&quot;,<br>  &quot;id&quot;: &quot;/subscriptions/&lt;subscription-id&gt;/service-b-identity-resource-group/providers/Microsoft.ManagedIdentity/userAssignedIdentities/service-b-identity&quot;,<br>  &quot;location&quot;: &quot;westus&quot;,<br>  &quot;name&quot;: &quot;service-b-identity&quot;,<br>  &quot;principalId&quot;: &quot;&lt;object-id&gt;&quot;,<br>  &quot;resourceGroup&quot;: &quot;service-b-identity-resource-group&quot;,<br>  &quot;tags&quot;: {},<br>  &quot;tenantId&quot;: &quot;&lt;tenant-id&gt;&quot;,<br>  &quot;type&quot;: &quot;Microsoft.ManagedIdentity/userAssignedIdentities&quot;<br>}</pre><p>3. Assign a custom role to the identity (You may need to wait a couple of minutes before issuing the below, or run it twice if you get a <em>Request_ResourceNotFound </em>error)</p><pre>$&gt; az rest --method post --uri <a href="https://graph.microsoft.com/beta/servicePrincipals/38b8c0f9-837a-4abd-816f-bc51282519e2/appRoleAssignments">https://graph.microsoft.com/beta/servicePrincipals/&lt;service-<strong>a</strong>-enterprise-object-id&gt;/appRoleAssignments</a> --headers &quot;{\&quot;content-type\&quot;: \&quot;application/json\&quot;}&quot; --body &quot;{\&quot;appRoleId\&quot;: \&quot;13371337-1337-1337-1337-133713371338\&quot;, \&quot;principalId\&quot;: \&quot;&lt;<strong>user-identity</strong>-principal-id&gt;\&quot;, \&quot;resourceId\&quot;: \&quot;&lt;service-<strong>a</strong>-enterprise-object-id&gt;\&quot;, \&quot;principalType\&quot;: \&quot;ServicePrincipal\&quot;}&quot;</pre><p>Once again, note that we need to use the Enterprise Application object ID of service A, and the object id (available in the <em>principalId </em>field in the az CLI response in step #2)</p><p>4. Assign the identity to an Azure VM (most likely, a VM that will host service B)</p><pre>$&gt; az vm identity assign -g &quot;&lt;vm-resource-group&gt;&quot; -n &quot;&lt;vm-name&gt;&quot; --identities &quot;&lt;user-identity-id&gt;&quot;</pre><p>Note: We need to use the <em>id</em> field from the az CLI response in step #2</p><p>5. Login to the VM and use IMDS to issue a token, without secrets</p><pre>$&gt; curl -s -H Metadata:true &quot;http://169.254.169.254/metadata/identity/oauth2/token?api-version=2019-06-04&amp;resource=api://service-a.example.com&amp;client_id=&lt;identity-client-id&gt;&quot;</pre><p>Note: You should use the <em>clientId </em>field given at the output of step #2; The client id query param can be omitted if the VM has only one identity assigned, however passing the id is a best practice</p><p>6. Inspect the token in <a href="https://jwt.ms/">https://jwt.ms</a></p><figure><img alt="Managed identities JWT" src="https://cdn-images-1.medium.com/max/639/1*XzLT5Hxd-ZBrbruZ4dQeQw.png" /></figure><p>Note how the <em>Service.A.Writer </em>role is assigned in the token above.</p><h4>Validating the JWT — step by step</h4><p>We now have the ability to issue access tokens that contain any number of custom app roles; Below I describe how service A should validate that a given token is valid.</p><ol><li>Validate that token is passed via a header / other mechanism (depending on the protocol used)</li><li>Parse the JWT via the library of your choice (I’ve settled on <a href="https://github.com/jwtk/jjwt">jjwt</a> for java) — note that you might need to trim the signature at this step (keep the last dot in the JWT, delete everything after), because you don’t have public key that signed on the JWT quite yet</li><li>Verify the <em>aud</em> (audience) field, it should match your application ID URI</li><li>Verify the <em>iss </em>(issuer) field, it should match https://sts.windows.net/&lt;tid&gt;/ (you might want to just compare the host, for multi tenant applications)</li><li>Verify that the current time is after the timestamp given at the <em>nbf </em>(not before) field</li><li>Verify that the current time is before the timestamp given at the <em>exp </em>(expiry) field</li><li>Optionally: Verify that the <em>appid</em> field contains a white-listed application, if such verification makes sense in your use case</li><li>Verify that an appropriate role is available under the <em>roles </em>field</li><li>If the above criteria passed, the token contents is valid — and you should continue to verify its signature</li><li>Retrieve the jwks uri from the OIDC configuration endpoint (this endpoint is available under the <em>Endpoints </em>blade in the app registration blade, shown in previous steps)</li></ol><figure><img alt="OIDC endpoint" src="https://cdn-images-1.medium.com/max/1024/1*jy1Fc0TTW3mTMJuO6vb8Gw.png" /></figure><p>11. Issuing an HTTP GET for the endpoint above, will yield a response with a <em>jwks_uri, </em>take note of it</p><figure><img alt="jwks_uri" src="https://cdn-images-1.medium.com/max/547/1*K0qrtrE_rB1CBcWrdEqN2A.png" /></figure><p>12. Issuing an HTTP GET for the jwks endpoint, will yield a response with a list of certificates, identifiable by a <em>kid (</em>key id<em>)</em></p><figure><img alt="jwks_uri keys" src="https://cdn-images-1.medium.com/max/534/1*G8M48DkMsFYpiHTINOXpuw.png" /></figure><p>13. Back to our JWT — you should now verify that the <em>kid </em>available in the JWT’s header is in the keys list</p><p>14. Once verified, you should take note of the certificate chain in the <em>x5c </em>field of the jwks endpoint response</p><p>15. Depending on the library you use, you may need to extract the public id from the first certificate in the chain</p><p>16. With the public key at hand, use the JWT library of your choice, now without omitting the JWT footer to validate the signature of your token; Alternatively, use the public key to sign on the JWT’s header and payload, and compare the signature yourself</p><p>Do note that:</p><ol><li>For multi tenant apps, you might want to use the issuing tenant’s jwks endpoint (you may use the <em>tid </em>field from the JWT)</li><li>You might want to keep an in memory copy of the STS public keys (jwks endpoint response) via having a background thread (or separate service) that keeps those up to date</li><li>You will probably want to introduce additional caching logic, verifying the same token over and over, for instance, could be redundant</li></ol><h4>Automating application creation with Azure CLI</h4><p>At our last stop, we’d like to automate the application creation to eliminate any Azure Portal user interaction.</p><p>Let’s do it step by step:</p><ol><li>Creating an application registration via Azure CLI</li></ol><pre>$&gt; az ad app create --display-name &quot;Auto Service A&quot; --credential-description &quot;Creds&quot; --identifier-uris &quot;api://auto-service-a.example.com&quot;  --password &quot;s0meSt0ngP@ssword1!&quot; --app-roles <a href="http://twitter.com/roles">@roles</a>.json</pre><pre>roles.json should be a file in current directory, with the following content (You may add or remove entries as you wish):<br>[{<br>    &quot;allowedMemberTypes&quot;: [<br>      &quot;Application&quot;<br>    ],<br>    &quot;description&quot;: &quot;Auto Service A Reader&quot;,<br>    &quot;displayName&quot;: &quot;Auto Service A Reader&quot;,<br>    &quot;isEnabled&quot;: &quot;true&quot;,<br>    &quot;value&quot;: &quot;Auto.Service.A.Reader&quot;,<br>    &quot;id&quot;: &quot;13371337-1337-1337-1337-133713371337&quot;<br>}]</pre><p>The above will create an application with our custom roles pre-assigned</p><p>2. Creating a service principal for a given application via Azure CLI</p><pre>$&gt; az ad sp create --id &lt;app-id&gt;</pre><pre>Use the app ID given in the <em>appId </em>field in the response of step #1</pre><p>3. Enforcing app roles assignment required for token issuing</p><pre>$&gt; az ad sp update --id &lt;object-id&gt; --set appRoleAssignmentRequired=true</pre><pre>Use the object ID given in the <em>objectId </em>field in the response of step #2</pre><p>4. Repeat 1–3 for the client application, change parameters where applicable</p><p>5. Assigning roles for a given application</p><pre>$&gt; az rest --method post --uri <a href="https://graph.microsoft.com/beta/servicePrincipals/8787a7b5-d86d-4d10-a618-6f42a1224794/appRoleAssignments">https://graph.microsoft.com/beta/servicePrincipals/&lt;sp-service-a-object-id&gt;/appRoleAssignments</a> --headers &quot;{\&quot;content-type\&quot;: \&quot;application/json\&quot;}&quot; --body &quot;{\&quot;appRoleId\&quot;: \&quot;&lt;role-id&gt;\&quot;, \&quot;principalId\&quot;: \&quot;&lt;sp-service-b-object-id&gt;\&quot;, \&quot;principalType\&quot;: \&quot;ServicePrincipal\&quot;, \&quot;resourceId\&quot;: \&quot;&lt;sp-service-a-object-id&gt;\&quot;}&quot;</pre><p>Note that the object IDs are the ones in the <em>objectId </em>field from the output of step #3; Also, you may need to run this twice if you get an <em>Request_ResourceNotFound </em>error (This API is still in beta, and a bit flaky, at the time of writing)</p><p>That is all — we have automatically:</p><ul><li>Created two app registrations, with one or more custom app roles</li><li>Created two service principals bound to an app registration</li><li>Enforced app role assignment requirement for token issuing</li><li>Assigned one or more custom role for a client-app service principal, on the server-app service principal</li></ul><h4>Final thoughts</h4><p>Following the steps above, you should have been able to meet all of the required service to service communication auth layer criteria we’ve discussed at the beginning of the article.</p><p>I believe that using the outlined steps, we’ve been able to meet most modern authentication and authorization requirements for ‘userless’ microservice communication, on top of Azure AD.</p><p>Thanks for reading !</p><p>Feel free to leave your comments, tips or tricks below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1aed196b1e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PyEBPF — eBPF proxy routines generation and Python callbacks (iovisor/bcc wrapper)]]></title>
            <link>https://medium.com/@dany74q/pyebpf-ebpf-proxy-routines-generation-and-python-callbacks-iovisor-bcc-wrapper-42d6cf558be4?source=rss-61284e9ecb66------2</link>
            <guid isPermaLink="false">https://medium.com/p/42d6cf558be4</guid>
            <category><![CDATA[performance-engineering]]></category>
            <category><![CDATA[bpf]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ebpf]]></category>
            <category><![CDATA[bcc]]></category>
            <dc:creator><![CDATA[Danny Shemesh]]></dc:creator>
            <pubDate>Sat, 19 Jan 2019 20:51:04 GMT</pubDate>
            <atom:updated>2019-01-19T20:51:04.531Z</atom:updated>
            <content:encoded><![CDATA[<h3>PyEBPF — eBPF proxy routines generation and Python callbacks (iovisor/bcc wrapper)</h3><p>Hey folks !</p><p>A couple of weeks ago, I’ve stumbled upon <em>Brendan Gregg’</em>s BPF tracing tools diagram (shown below) in the context of a small read-up I’ve done on <em>performance engineering</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_EDcJxRQVdtW5qfb.png" /><figcaption>BPF tracing tools taken from the iovisor/bcc repository</figcaption></figure><p>Looking at the diagram above, and shamefully realizing I’m not familiar with the vast majority of the tools within, I’ve decided to explore the available utilities alongside the infrastructure that enabled their creation.</p><p>And so, today I’m going to talk a bit about <strong><em>eBPF</em></strong> (extended-berkeley-packet-filter), <strong><em>bcc</em></strong> (BPF-compiler-collection) and how both of those could be used with Python more easily.</p><h3>A quick intro to eBPF</h3><p>You might be familiar with <em>BPF </em>filters as a tool of filtering packets, a common example would be using a BPF filter in <em>tcpdump</em> in order to filter incoming or outgoing network traffic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3f3s3drdH34vXZrU5fsTFA.png" /><figcaption>Filtering incoming SSH traffic via <em>tcpdump</em></figcaption></figure><p><strong>eBPF </strong>(extended-BPF) is an enhancement to BPF, which allows one to trace and filter <strong>much more</strong> than just packets; For example, eBPF could be used in order to trace all SYSENTER operations to a specific syscall, say, <em>open(2).</em></p><p>Code needs to be compiled to the <em>BPF </em>instruction set, which in turn, is loaded and ran by the kernel’s BPF virtual machine.</p><p>Using <em>eBPF </em>usually involves the following steps:</p><ol><li>You compile a source code to BPF <em>byte-code </em>(BPF is ran in a dedicated Virtual-Machine, and has its own instruction set) using a suitable compiler (e.g. LLVM)</li><li>Your user mode program requests the kernel to store the compiled instructions, via the <em>bpf(2) </em>syscall with the <em>BPF_PROG_LOAD </em>command and a <em>program type, </em>which determines the type of our BPF module (e.g. <em>BPF_PROG_TYPE_SOCKET_FILTER </em>for packet filtering, <em>BPF_PROG_TYPE_KPROBE</em> for kernel probes)</li><li>The kernel will now run a static-analyzer (<em>bpf_check, </em>source available <a href="https://github.com/torvalds/linux/blob/v4.18/kernel/bpf/verifier.c">here</a><em>) </em>and verify the control-flow-graph of the code is safe for use (The BPF VM is quite strict, most I/O operations are forbidden, infinite loops are detected, there could be up to BPF_MAXINSNS [2¹² under v.4.20], etc…)</li><li>If the static checks above pass, the <em>bpf(2) </em>syscall results in a file-descriptor, which the user-mode program may operate against</li><li>In addition to the above, one may create and use a predefined set of <em>BPF data-structures</em> in order to communicate between BPF routines, and between your routine and user-mode program</li><li>Lastly, we may operate against our BPF module; For example, we may attach a kernel probe to it, so our routine would be called before or after a specific syscall is called</li></ol><p>A simplified version of the process above could be depicted as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*7MSOgLGd-W4fY0qSdSggRw.png" /><figcaption>Loading and operating with an eBPF kernel probe</figcaption></figure><h3>A few words about BCC</h3><p>When searching for eBPF related resources, a toolchain that kept popping up was <a href="https://github.com/iovisor/bcc"><em>BCC</em></a><em> </em>(The BPF-Compiler-Collection).</p><p>BCC is a very neat wrapper (with Python &amp; Lua native bindings) for BPF code generation (using LLVM) and kernel metric collection.</p><p>When you work with BCC, you pass your source (as a file or buffer) to the library, which in turn enhances it, compiles it and wraps the relevant file-descriptors for use.</p><p>Looking at Python’s bcc library, there are a few things to note:</p><ol><li>The bcc library exposes a <a href="https://github.com/iovisor/bcc/blob/master/src/python/bcc/__init__.py">BPF Python object</a> that operates against a native library — <strong><em>libbcc</em></strong></li><li>In turn, libbcc uses <strong><em>libbpf</em></strong><em> </em>and <strong><em>bpf_module</em></strong><em>, </em>where <a href="https://github.com/iovisor/bcc/blob/master/src/cc/bpf_module.h"><em>bpf_module</em></a> deals with code generation via LLVM and <a href="https://github.com/iovisor/bcc/blob/master/src/cc/libbpf.h"><em>libbpf</em></a><em> </em>handles program loading, program-attachment and BPF data-structure management</li><li>Code is generated via LLVM on the fly, and your eBPF routines are usually written as a string in Python, and passed to BCC (and internally to LLVM) for compilation</li></ol><p>BCC has quite an extensive code base with various convenient wrappers and lots of useful c-macros for generating and using BPF data structures.</p><p>Let’s look at an example that traces all <em>bind(2) </em>syscalls, and prints the pid, process name and socket-fd of the process which called bind()</p><pre>from threading import Thread<br>from socket import socket<br>import ctypes as ct<br>import time</pre><pre>from bcc import BPF</pre><pre><br>prog = &#39;&#39;&#39;</pre><pre>#include &lt;linux/sched.h&gt;</pre><pre>/* This is a BCC macro for that creates a BPF data-structure that we can communicate with in user-mode */</pre><pre>BPF_PERF_OUTPUT(events);</pre><pre>// The following is the data-structure we&#39;ll pass to our user-land program<br>struct data_t {<br>    char process_name[TASK_COMM_LEN];    // Process name<br>    u32 pid;                             // Process ID<br>    int socket_fd;                       // Bound Socket FD<br>};</pre><pre>/* This is our BPF routine, it contains two arguments:</pre><pre>- A pt_regs* struct, which contains the BPF VM registers</pre><pre>- A socket fd - this will actually be transformed by bcc to a local variable that is set by the registers, see note below<br>*/</pre><pre>int on_bind(struct pt_regs* ctx, int sockfd) {<br>    struct data_t data = {};</pre><pre>    // A bpf helper that gets the process name that invoked the bind operation<br>    bpf_get_current_comm(&amp;data.process_name, sizeof(data.process_name));</pre><pre><br>    // Gets the pid via the bpf helper (pid is the upper 32 bits)<br>    data.pid = (u32) (bpf_get_current_pid_tgid() &gt;&gt; 32);<br>    data.socket_fd = sockfd;</pre><pre>    // Copies the data to the BPF structure, it is now available to user-mode<br>    events.perf_submit(ctx, &amp;data, sizeof(data));</pre><pre>    return 0;<br>}<br>&#39;&#39;&#39;</pre><pre># Compiles the BPF program via LLVM<br>b = BPF(text=prog)</pre><pre># Represents the native data-structure above<br>class Data(ct.Structure):<br>    _fields_ = [<br>        (&#39;process_name&#39;, ct.c_char * 16), <br>        (&#39;pid&#39;, ct.c_uint32),<br>        (&#39;socket_fd&#39;, ct.c_int32)<br>    ]</pre><pre># Prints header<br>print &#39;COMM PID SOCKETFD&#39;</pre><pre># A callback to be called for every record in the &#39;events&#39; BPF data structure<br>def print_event(cpu, data, size):<br>    data = ct.cast(data, ct.POINTER(Data)).contents</pre><pre>    print &#39;{process_name} {pid} {socket_fd}&#39;.format(process_name=data.process_name, pid=data.pid, socket_fd=data.socket_fd)</pre><pre># This calls libbpf, which in turns calls the bpf(2) syscall, and does a few more tricks to attach the kernel probe<br>b.attach_kprobe(event=b.get_syscall_fnname(&#39;bind&#39;), fn_name=&#39;on_bind&#39;)</pre><pre># An async function that binds to localhost:31337 (To get an output for the above)<br>def call_bind_async():<br>    time.sleep(2)<br>    print &#39;Calling bind...&#39;<br>    s = socket()<br>    s.bind((&#39;localhost&#39;, 31337))</pre><pre>t = Thread(target=call_bind_async)<br>t.start()</pre><pre># This will open the BPF data structure for polling<br>b[&#39;events&#39;].open_perf_buffer(print_event)</pre><pre>while True:<br>    try:<br>        # Poll the data structure till Ctrl+C<br>        b.perf_buffer_poll()<br>    except KeyboardInterrupt:<br>        print &#39;Bye !&#39;<br>        break</pre><p>Running the example above yields the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*PqusW42WzUIfUrGmisIOFw.png" /><figcaption>Output from trace_bind.py</figcaption></figure><p>To reveal some of the pre-processing BCC brings to table, we can pass the <em>debug=DEBUG_PREPROCESSOR </em>flag to BPF’s constructor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QIIvPlyzXE3-tuD9Jw5n7w.png" /><figcaption>trace_bind.py with the debug=DEBUG_PREPROCESSOR flag</figcaption></figure><p>As we can see, there are a few interesting things to note here:</p><ol><li>BCC loads an in-memory filesystem mapped to the /virtual directory</li><li>We’ve got additional #ifdefs at the top, preventing us from setting the BPF_LICENSE macro and conditionally defining the <em>CONFIG_CC_STACKPROTECTOR</em> macro</li><li>The <em>BPF_PERF_OUTPUT</em> macro was not expanded, but can be observed <a href="https://github.com/iovisor/bcc/blob/master/src/cc/export/helpers.h">here</a></li><li>Our routine has been annotated to be put in its own section (This is not mandatory for loading BPF routines, but is used later by bcc itself)</li><li>Our extra parameter was stripped from our method, and it now resides on stack and copied from the <em>di </em>register</li><li>Our use of events was replaced with a call to <em>bpf_perf_event_output</em> that uses <em>bpf_pseudo_fd</em> (Note that fd 3 is the first fd to be created after stdin, out, err)</li><li>There is an additional footer included — this footer defines the BPF_LICENSE macro as “GPL” (relevant <a href="https://github.com/iovisor/bcc/blob/master/src/cc/export/footer.h">code</a>) [Note that BCC’s license is actually <em>Apache v2.0</em>, this is only a parameters that is later passed on to the <em>bpf(2)</em> syscall]</li></ol><p>Now that we’ve dipped our toe in BCC’s waters, let’s continue in explaining what is PyEBPF and why it was created.</p><h3>PyEBPF — Yet Another Wrapper</h3><p>One aspect that felt a bit daunting when working with BCC’s python library was the fact that even with supposedly trivial examples (Like <em>trace_bind </em>above), there had to be written some boilerplate that deals with sharing data between our routine and our user-mode application.</p><p>I thought it would be fun, for educational purposes, to try and automate the process a bit, so one could have the ability to write simple tracing routines, <strong>without</strong> writing extra native code.</p><p>PyEBPF provides a simple wrapper that helps you attach kernel probes that are attached to any syscall without writing a single line of native code.</p><p>It does so by a few key steps:</p><ol><li>For a given kprobe_attach request, it inspects the syscall’s arguments, by trying to parse the <em>/sys/kernel/debug/tracing/events/syscalls/sys_enter_&lt;syscall&gt;/format </em>file</li><li>Then, it generates an appropriate BPF routine and inject the syscall arguments to it</li><li>A native data structure is generated, it will hold the syscall arguments, along with the pid, tid, current time in ns, uid, gid and invoking process name</li><li>A ctypes data structure that represents the native one is generated as well</li><li>A BPF map will be injected as well, to copy the information from our routine back to user mode</li><li>Finally, the wrapper will spawn a daemon thread that polls on our BPF map, casts the data object to our ctypes structure, and invokes a user-passed python function with it</li></ol><p>Thus, our <em>trace_bind </em>example above, transforms to the following:</p><pre>from threading import Thread<br>from socket import socket<br>import time</pre><pre>from pyebpf.ebpf_wrapper import EBPFWrapper</pre><pre># Note that there is no native code passing here<br>b = EBPFWrapper()</pre><pre># Prints header<br>print &#39;COMM PID SOCKETFD&#39;</pre><pre># A callback to be called by pyebpf<br>def on_bind(cpu, data, size):<br>    print &#39;{process_name} {pid} {socket_fd}&#39;.format(process_name=data.process_name, pid=data.process_id, socket_fd=data.fd)</pre><pre># Note that we pass a function object<br>b.attach_kprobe(event=b.get_syscall_fnname(&#39;bind&#39;), fn=on_bind)</pre><pre><br># An async function that binds to localhost:31337 (To get an output for the above)</pre><pre>def call_bind_async():<br>    time.sleep(2)<br>    print &#39;Calling bind...&#39;<br>    s = socket()<br>    s.bind((&#39;localhost&#39;, 31337))</pre><pre>t = Thread(target=call_bind_async)<br>t.start()</pre><pre>while True:<br>    try:<br>        time.sleep(1)<br>    except KeyboardInterrupt:<br>        print &#39;Bye !&#39;<br>        break</pre><p>Note how in the example above, we’ve basically halved the amount of code we needed to write.</p><h3>Conclusion</h3><p>PyEBPF is an tool written for educational purposes to lessen the burden of writing <strong>simple</strong> BPF routines.</p><p>Complex examples may, more often than not, use helpers and routines that are only available in kernel mode — and it would most definitely not fit those purposes.</p><p>However, if you’re just starting around with tracing syscalls, and you don’t mind having all of the control flow in user-mode, feel free to use and improve the library further (For example, it does not cover USDT’s, kretprobes, tracepoints, and most other very-cool functionality eBPF offers).</p><p>PyEBPF is available under an MIT license, you can find it’s source code <a href="https://github.com/dany74q/pyebpf">here</a> and you may install it via pip:</p><p>$&gt; <em>pip install pyebpf</em></p><p><strong>Note</strong>: You need to install BCC separately, please refer to this <a href="https://github.com/iovisor/bcc/blob/master/INSTALL.md">guide</a> if you haven’t done so already.</p><p>Hope you enjoyed the reading !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42d6cf558be4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Injecting JS into electron apps (And adding RTL support for ‘Microsoft Teams’)]]></title>
            <link>https://medium.com/@dany74q/injecting-js-into-electron-apps-and-adding-rtl-support-for-microsoft-teams-d315dfb212a6?source=rss-61284e9ecb66------2</link>
            <guid isPermaLink="false">https://medium.com/p/d315dfb212a6</guid>
            <category><![CDATA[electron]]></category>
            <category><![CDATA[microsoft-teams]]></category>
            <category><![CDATA[rtls]]></category>
            <category><![CDATA[injection]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Danny Shemesh]]></dc:creator>
            <pubDate>Sat, 20 Jan 2018 23:52:52 GMT</pubDate>
            <atom:updated>2018-01-21T11:11:28.984Z</atom:updated>
            <content:encoded><![CDATA[<p>Heya !</p><p>Last week our team at Microsoft had switched our intra-organization communication app — we moved from Slack to Teams, Microsoft’s own built service.</p><p>Both services offer similar capabilities, each with its own strengths and weaknesses; But one thing they both lack is RTL (Right-To-Left) support.</p><p>Our group chats often mix both English and Hebrew, and having your sentences mis-aligned proves to be quite a pain, ‘coercing’ us to use too many line breaks and leading to unnecessary confusion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*U-juQBc_Blf5Mv6CNNKFCw.png" /><figcaption>Bah…</figcaption></figure><h3>Creating an RTL solution for Microsoft Teams</h3><p>I wanted to scratch my own itch, and this had led me to search for an easy way to add RTL support for the app, at least a temporary one, before it is supported natively.</p><p>I started with peeking over at Teams directory; I could quickly see that much like Slack, it’s built on top of <a href="https://electronjs.org/">Electron</a> — A framework that lets one create cross-platform desktop apps with web front-end technologies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*65zUNh5LgbZJI_iYoHo0_Q.jpeg" /><figcaption>Teams Directory Contents</figcaption></figure><p>Above, you can see a typical electron app directory tree:</p><ul><li>app.asar.unpacked — Usually contains static assets and 3rd party npm modules</li><li>assets — Images, Icons and similar static files</li><li>locales — Multi language translations</li><li>app.asar — The packed app, in <a href="https://github.com/electron/asar">Electron’s archive format</a></li><li>electron.asar — Electron supplied libraries</li></ul><blockquote>Easy — just find a .js file that is loaded by Teams in the app.asar.unpacked, and add a custom payload there !</blockquote><p>Or so I thought, at least. Going over the app’s unpacked directory unveiled only pre-compiled node modules (Basically, a bunch of .dll’s).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*n5Y_8ndidjTyxtjrAijoOQ.jpeg" /><figcaption>Teams Various Modules</figcaption></figure><p>The next thing that came to mind was creating a proxy dll that would inject a given payload; This was quickly dismissed as it would require a separate solution for my Mac-using colleagues.</p><p>With DLL proxying off the table, I thought of two other methods that may work.</p><ol><li>Repackaging the app with a custom script that would provide the RTL logic</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*unYoOlZbo6VzplVa8_34FA.jpeg" /><figcaption>Teams’ app.asar unpacked via the asar packaging tool</figcaption></figure><p>2. Try to load the app in debug mode, and use chrome’s devtools protocol to inject a script in runtime (using Runtime.evaluate)</p><p>The clear advantage of the latter is that it won’t be overwritten by future updates, which tend to be quite frequent; And so I’ve decided to go through the second route.</p><h3>Running Teams with a debugger server</h3><p>Electron uses chromium as its under the hood engine, and so it’s possible to pass chromium-specific arguments when running electron based apps.</p><p>One of many useful parameters you may pass is ‘remote-debugging-port’, which let’s you connect a remote debugger to every window the app creates.</p><p>Firing up Teams with the flag set to a port of my choice, I could easily test it by surfing to <em>chrome://inspect </em>in chrome, after enabling network device lookup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_6VrNGQrCUDbCz0vPMJisw.jpeg" /><figcaption>Chrome Inspect While Running Teams w/ — remote-debugging-port</figcaption></figure><p>Great — feels like progress ! Next, I went on to inspect the chat window to get a sense of the elements I’d need to operate on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v4S2qBzhJFmEvzjM2JjWJA.jpeg" /><figcaption>Found You :)</figcaption></figure><p>I’ve identified three element sets that benefit from RTL-ing, and those are:</p><ul><li>Chat messages — CSS Selector `<em>.message-body-content</em>`</li><li>Chat previews (To the left) — CSS Selector`<em>.ts-channel-list-entry-preview</em>`</li><li>Chat text input — CSS Selector `<em>.ts-edit-box .cke_editable</em>`</li></ul><p>As for the RTL logic, I could just plug in a dir=”auto” attribute (Supported by most major browsers) to these elements and the browser should render them automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dL-8dDlPoXOIqeXlS4ofXQ.jpeg" /><figcaption>Manually testing dir=”auto” — looks much better !</figcaption></figure><p>And now, for the injection itself.</p><blockquote>From <a href="https://chromedevtools.github.io/devtools-protocol/">Chrome DevTools Protocol</a>: […] your application can discover available pages by requesting: <a href="http://localhost:9222/json">http://localhost:port/json</a> and getting a JSON object with information about inspectable pages along with the WebSocket addresses that you could use in order to start instrumenting them.</blockquote><p>That sounds promising — let’s take a look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e_o3rFvf_NWcxIBJHSw6pQ.jpeg" /><figcaption>webSocketDebuggerUrl sounds relevant…</figcaption></figure><p>The endpoint outputs the active windows of the debugged process, and switching between panes in Teams we could see the various websocket debug urls for each pane. For now, it looks like I’m most interested in the ‘Chat’ window.</p><p>Going through the DevTools protocol rich API, we would notice that we can evaluate a javascript payload using the ‘Runtime.evaluate’ method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dozbpFiYRvlI6AcV30cD1g.jpeg" /><figcaption>Runtime.evaluate — from DevTools Protocol</figcaption></figure><p>Communicating with the app is pretty straightforward from hereon, we connect to the websocket, and can send commands based on the following JSON:</p><p><em>{“id”: someId, “method”: methodName, “params”: {…}}</em></p><p>The quickest way to test this was via trying to evaluate an alert:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*LhPeBWc25REimmsnQA9jYw.jpeg" /><figcaption>Injected successfully.</figcaption></figure><p>Now all we need to do is:</p><ol><li>Write the RTL-ing payload</li><li>Open Teams w/ remote debugging enabled</li><li>Find the chat window</li><li>Inject script into said window</li><li>Profit</li></ol><p>The payload, together with a python-based Teams runner (It’s in charge of running Teams debugged and injecting the script) is available <a href="https://github.com/dany74q/microsoft-teams-rtl-runner">here</a>, it supports both Windows and Mac.</p><p>I’ve also packaged it into a <a href="https://chrome.google.com/webstore/detail/klliiciijffigonlnblmbecpjdefemja">chrome extension</a> that uses the same payload as a content script.</p><h3>A Quick Recap</h3><ul><li>We talked about a few potential script injection mechanism to electron based applications</li><li>We investigated the DevTools Protocol and have seen how to use it to evaluate a js payload</li><li>We have added a decent RTL support for Microsoft Teams</li></ul><p>Resources &amp; Thanks to:</p><ul><li><a href="https://chromedevtools.github.io/">Chrome DevTools Protocol Docs</a></li><li><a href="https://github.com/tintinweb/electron-inject">Electron-Inject Python Library</a></li><li>You, hope you had a great read !</li></ul><p>Feel free to leave a comment below :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d315dfb212a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>