Ejemplo n.º 1
0
        /// <summary>
        /// Based on the YOUR AAD ApplicationId determine if the Tenant already has the ServicePrincipal in their directory
        /// </summary>
        /// <param name="client"></param>
        /// <param name="applicationId"></param>
        /// <returns></returns>
        private static async Task <IServicePrincipal> GetServicePrincipalAsync(IActiveDirectoryClient client, string applicationId)
        {
            IPagedCollection <IServicePrincipal> servicePrincipals = null;

            try
            {
                servicePrincipals = await client.ServicePrincipals.ExecuteAsync();
            }
            catch (Exception e)
            {
                Program.WriteError("\nError getting Service Principal {0}", Program.ExtractErrorMessage(e));
            }

            while (servicePrincipals != null)
            {
                List <IServicePrincipal> servicePrincipalsList = servicePrincipals.CurrentPage.ToList();
                IServicePrincipal        servicePrincipal      =
                    servicePrincipalsList.FirstOrDefault(x => x.AppId.Equals(applicationId));

                if (servicePrincipal != null)
                {
                    return(servicePrincipal);
                }

                servicePrincipals = await servicePrincipals.GetNextPageAsync();
            }

            return(null);
        }
Ejemplo n.º 2
0
        public void CanCRUDServicePrincipal()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                IGraphRbacManager manager          = TestHelper.CreateGraphRbacManager();
                IServicePrincipal servicePrincipal = null;
                string            name             = SdkContext.RandomResourceName("javasdksp", 20);
                try
                {
                    servicePrincipal = manager.ServicePrincipals.Define(name)
                                       .WithNewApplication("http://easycreate.azure.com/anotherapp/" + name)
                                       .DefinePasswordCredential("sppass")
                                       .WithPasswordValue("StrongPass!12")
                                       .Attach()
                                       .DefineCertificateCredential("spcert")
                                       .WithAsymmetricX509Certificate()
                                       .WithPublicKey(File.ReadAllBytes("Assets/myTest.cer"))
                                       .WithDuration(TimeSpan.FromDays(1))
                                       .Attach()
                                       .Create();
                    Console.WriteLine(servicePrincipal.Id + " - " + string.Join(", ", servicePrincipal.ServicePrincipalNames));
                    Assert.NotNull(servicePrincipal.Id);
                    Assert.NotNull(servicePrincipal.ApplicationId);
                    Assert.Equal(2, servicePrincipal.ServicePrincipalNames.Count);
                    Assert.Equal(1, servicePrincipal.PasswordCredentials.Count);
                    Assert.Equal(1, servicePrincipal.CertificateCredentials.Count);

                    // Get
                    servicePrincipal = manager.ServicePrincipals.GetByName(servicePrincipal.ApplicationId);
                    Assert.NotNull(servicePrincipal);
                    Assert.NotNull(servicePrincipal.ApplicationId);
                    Assert.Equal(2, servicePrincipal.ServicePrincipalNames.Count);
                    Assert.Equal(1, servicePrincipal.PasswordCredentials.Count);
                    Assert.Equal(1, servicePrincipal.CertificateCredentials.Count);

                    // Update
                    servicePrincipal.Update()
                    .WithoutCredential("sppass")
                    .DefineCertificateCredential("spcert")
                    .WithAsymmetricX509Certificate()
                    .WithPublicKey(File.ReadAllBytes("Assets/myTest2.cer"))
                    .WithDuration(TimeSpan.FromDays(2))
                    .Attach()
                    .Apply();
                    Assert.NotNull(servicePrincipal);
                    Assert.NotNull(servicePrincipal.ApplicationId);
                    Assert.Equal(2, servicePrincipal.ServicePrincipalNames.Count);
                    Assert.Equal(0, servicePrincipal.PasswordCredentials.Count);
                    Assert.Equal(2, servicePrincipal.CertificateCredentials.Count);
                }
                finally
                {
                    if (servicePrincipal != null)
                    {
                        manager.ServicePrincipals.DeleteById(servicePrincipal.Id);
                        manager.Applications.DeleteById(manager.Applications.GetByName(servicePrincipal.ApplicationId).Id);
                    }
                }
            }
        }
Ejemplo n.º 3
0
        public IServicePrincipal GetServicePrincipal(string appId)
        {
            IServicePrincipal servicePrincipal = null;

            servicePrincipal = _activeDirectoryClient.ServicePrincipals.Where(s => s.AppId == appId).ExecuteSingleAsync().Result;
            return(servicePrincipal);
        }
        /**
         * Azure Service Principal sample for managing Service Principal -
         *  - Create an Active Directory application
         *  - Create a Service Principal for the application and assign a role
         *  - Export the Service Principal to an authentication file
         *  - Use the file to list subcription virtual machines
         *  - Update the application
         *  - Update the service principal to revoke the password credential and the role
         *  - Delete the Service Principal.
         */
        public static void RunSample(Azure.IAuthenticated authenticated)
        {
            string subscriptionId = authenticated.Subscriptions.List().First <ISubscription>().SubscriptionId;

            Utilities.Log("Selected subscription: " + subscriptionId);
            IActiveDirectoryApplication activeDirectoryApplication = null;
            string authFilePath = Path.Combine(Utilities.ProjectPath, "Asset", "mySamplAuthdFile.azureauth").ToString();

            try
            {
                activeDirectoryApplication = CreateActiveDirectoryApplication(authenticated);
                IServicePrincipal servicePrincipal = CreateServicePrincipalWithRoleForApplicationAndExportToFile(authenticated, activeDirectoryApplication, BuiltInRole.Contributor, subscriptionId, authFilePath);
                // Wait until Service Principal is ready
                SdkContext.DelayProvider.Delay(15);
                UseAuthFile(authFilePath);
                UpdateApplication(authenticated, activeDirectoryApplication);
                UpdateServicePrincipal(authenticated, servicePrincipal);
            }
            finally
            {
                Utilities.Log("Deleting Active Directory application and Service Principal...");
                if (activeDirectoryApplication != null)
                {
                    // this will delete Service Principal as well
                    authenticated.ActiveDirectoryApplications.DeleteById(activeDirectoryApplication.Id);
                }
            }
        }
Ejemplo n.º 5
0
 public ProvisionAzure(ISettings settings, IServicePrincipal principal, IAzureRestClient azureRestClient)
 {
     Principal       = principal;
     Settings        = settings;
     AzureRestClient = azureRestClient;
     CommonTags      = new Dictionary <string, string>();
 }
        private static async Task CleanupPermissionGrantsAsync(IActiveDirectoryClient client, OAuthGrant grant)
        {
            IServicePrincipal servicePrincipal = await GetServicePrincipalAsync(client, grant.Application.AppId);

            if (servicePrincipal == null)
            {
                Log(string.Format("No existing service principal for app {0}", grant.Application.DisplayName));
                return;
            }
            Log(string.Format("Deleting existing service principal for app {0}", grant.Application.DisplayName));
            await servicePrincipal.DeleteAsync();
        }
Ejemplo n.º 7
0
        /// <summary>
        /// To ensure the latest Service Principal with the most up-to-date permissions are created,
        /// if exists, remove the existing Service Principal for YOUR AAD application
        /// </summary>
        /// <param name="client"></param>
        /// <param name="grant"></param>
        /// <returns></returns>
        private static async Task CleanupPermissionGrantsAsync(IActiveDirectoryClient client,
                                                               OAuthGrant grant)
        {
            IServicePrincipal servicePrincipal = await GetServicePrincipalAsync(client, grant.Application.AppId);

            if (servicePrincipal == null)
            {
                Program.WriteInfo($"No existing service principal for app {grant.Application.DisplayName}");
                return;
            }
            Program.WriteInfo($"Deleting existing service principal for app {grant.Application.DisplayName}");
            await servicePrincipal.DeleteAsync();
        }
Ejemplo n.º 8
0
        static async Task AddAdminRoleAssignmentToServer(IServicePrincipal serverApplication)
        {
            // Get the admin role,
            var role = serverApplication.AppRoles.First(r => r.Value == "admin_signservice");

            var ara = new AppRoleAssignment
            {
                PrincipalId   = Guid.Parse(authResult.UserInfo.UniqueId),
                PrincipalType = "User",
                Id            = role.Id,
                ResourceId    = Guid.Parse(serverApplication.ObjectId)
            };

            await graphClient.Users.GetByObjectId(authResult.UserInfo.UniqueId).AppRoleAssignments.AddAppRoleAssignmentAsync(ara);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// If the ServicePrincipal does not already exist in the tenant's directory,
        /// then creates a ServicePrincipal for the specified application in the tenant's directory,
        /// otherwise return the found ServicePrincipal
        /// </summary>
        /// <param name="client"></param>
        /// <param name="application"></param>
        /// <returns>IServicePrincipal</returns>
        private static async Task <IServicePrincipal> CreateServicePrincipalAsync(IActiveDirectoryClient client, IApplication application)
        {
            IServicePrincipal servicePrincipal = null;

            if (application.AppId != null)
            {
                // does the Service Principal already exist?
                servicePrincipal = await GetServicePrincipalAsync(client, application.AppId);

                // if exists then return the found Service Principal
                if (servicePrincipal != null)
                {
                    return(servicePrincipal);
                }

                // if not found then create a Service Principal for this tenant
                servicePrincipal = new ServicePrincipal()
                {
                    AccountEnabled = true,
                    AppId          = application.AppId,
                    DisplayName    = application.DisplayName
                };

                try
                {
                    await client.ServicePrincipals.AddServicePrincipalAsync(servicePrincipal);
                }
                catch (Exception e)
                {
                    Program.WriteError("\nError creating Service Principal for {0}: {1}", application.DisplayName, Program.ExtractErrorMessage(e));
                    return(null);
                }
            }
            else
            {
                Program.WriteError("\nRefusing to create Service Principal for {0} because ApplicationID was not supplied", application.DisplayName);
                return(null);
            }


            return(servicePrincipal);
        }
Ejemplo n.º 10
0
        public void CanCRUDKeyVault()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                // Create user service principal
                String            sp           = SdkContext.RandomResourceName("sp", 20);
                String            us           = SdkContext.RandomResourceName("us", 20);
                IGraphRbacManager graphManager = TestHelper.CreateGraphRbacManager();
                string            vaultName1   = TestUtilities.GenerateName("vault1");
                string            rgName       = TestUtilities.GenerateName("rgNEMV");

                IKeyVaultManager manager = TestHelper.CreateKeyVaultManager();

                IServicePrincipal servicePrincipal = graphManager.ServicePrincipals
                                                     .Define(sp)
                                                     .WithNewApplication("http://" + sp)
                                                     .Create();

                IActiveDirectoryUser user = graphManager.Users
                                            .Define(us)
                                            .WithEmailAlias(us)
                                            .WithPassword("P@$$w0rd")
                                            .Create();
                //var spnCredentialsClientId = HttpMockServer.Variables[ConnectionStringKeys.ServicePrincipalKey];

                try
                {
                    IVault vault = manager.Vaults
                                   .Define(vaultName1)
                                   .WithRegion(Region.USWest)
                                   .WithNewResourceGroup(rgName)
                                   .DefineAccessPolicy()
                                   .ForServicePrincipal("http://" + sp)
                                   .AllowKeyPermissions(KeyPermissions.List)
                                   .AllowSecretAllPermissions()
                                   .AllowCertificatePermissions(CertificatePermissions.Get)
                                   .Attach()
                                   .DefineAccessPolicy()
                                   .ForUser(us)
                                   .AllowKeyAllPermissions()
                                   .AllowSecretAllPermissions()
                                   .AllowCertificatePermissions(CertificatePermissions.Get, CertificatePermissions.List, CertificatePermissions.Create)
                                   .Attach()
                                   .Create();
                    Assert.NotNull(vault);
                    Assert.Equal(vaultName1, vault.Name);
                    foreach (IAccessPolicy policy in vault.AccessPolicies)
                    {
                        if (policy.ObjectId.Equals(servicePrincipal.Id))
                        {
                            Assert.Equal(1, policy.Permissions.Keys.Count);
                            Assert.Equal(KeyPermissions.List.Value, policy.Permissions.Keys[0]);
                            Assert.Equal(8, policy.Permissions.Secrets.Count);
                            Assert.Equal(1, policy.Permissions.Certificates.Count);
                            Assert.Equal(CertificatePermissions.Get.Value, policy.Permissions.Certificates[0]);
                        }
                        if (policy.ObjectId.Equals(user.Id))
                        {
                            Assert.Equal(16, policy.Permissions.Keys.Count);
                            Assert.Equal(8, policy.Permissions.Secrets.Count);
                            Assert.Equal(3, policy.Permissions.Certificates.Count);
                        }
                    }

                    vault = vault.Update()
                            .UpdateAccessPolicy(servicePrincipal.Id)
                            .AllowKeyAllPermissions()
                            .DisallowSecretAllPermissions()
                            .AllowCertificateAllPermissions()
                            .Parent()
                            .Apply();

                    foreach (IAccessPolicy policy in vault.AccessPolicies)
                    {
                        if (policy.ObjectId.Equals(servicePrincipal.Id))
                        {
                            Assert.Equal(16, policy.Permissions.Keys.Count);
                            Assert.Equal(0, policy.Permissions.Secrets.Count);
                            Assert.Equal(14, policy.Permissions.Certificates.Count);
                        }
                    }
                }
                finally
                {
                    try
                    {
                        TestHelper.CreateResourceManager().ResourceGroups.DeleteByName(rgName);
                    }
                    catch { }
                }
            }
        }
Ejemplo n.º 11
0
        public void CanCRUDGroup()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                IGraphRbacManager manager = TestHelper.CreateGraphRbacManager();
                var userName                           = SdkContext.RandomResourceName("user", 16);
                var spName                             = SdkContext.RandomResourceName("sp", 16);
                var group1Name                         = SdkContext.RandomResourceName("group", 16);
                var group2Name                         = SdkContext.RandomResourceName("group", 16);
                IActiveDirectoryUser  user             = null;
                IServicePrincipal     servicePrincipal = null;
                IActiveDirectoryGroup group1           = null;
                IActiveDirectoryGroup group2           = null;
                try
                {
                    user = manager.Users.Define(userName)
                           .WithEmailAlias(userName)
                           .WithPassword("StrongPass!123")
                           .Create();
                    servicePrincipal = manager.ServicePrincipals.Define(spName)
                                       .WithNewApplication("https://" + spName)
                                       .Create();
                    group1 = manager.Groups.Define(group1Name)
                             .WithEmailAlias(group1Name)
                             .Create();
                    SdkContext.DelayProvider.Delay(15000);
                    group2 = manager.Groups.Define(group2Name)
                             .WithEmailAlias(group2Name)
                             .WithMember(user.Id)
                             .WithMember(servicePrincipal.Id)
                             .WithMember(group1.Id)
                             .Create();

                    Assert.NotNull(group2);
                    Assert.NotNull(group2.Id);
                    var members = group2.ListMembers();
                    Assert.Equal(3, members.Count());
                    var enumerator = members.GetEnumerator();
                    Assert.True(enumerator.MoveNext());
                    Assert.NotNull(enumerator.Current.Id);
                    Assert.True(enumerator.MoveNext());
                    Assert.NotNull(enumerator.Current.Id);
                    Assert.True(enumerator.MoveNext());
                    Assert.NotNull(enumerator.Current.Id);
                    Assert.False(enumerator.MoveNext());
                }
                finally
                {
                    if (servicePrincipal != null)
                    {
                        manager.ServicePrincipals.DeleteById(servicePrincipal.Id);
                    }
                    // cannot delete users or groups from service principal
                    // if (user != null) {
                    //     manager.Users.DeleteById(user.Id);
                    // }
                    // if (group != null) {
                    //     manager.Groups.DeleteById(group.Id);
                    // }
                }
            }
        }
Ejemplo n.º 12
0
        public void CanCRUDServicePrincipalWithRole()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                IGraphRbacManager manager          = TestHelper.CreateGraphRbacManager();
                IServicePrincipal servicePrincipal = null;
                string            subscriptionId   = TestHelper.CreateResourceManager().SubscriptionId;
                string            authFile         = "mytest.azureauth";
                string            name             = SdkContext.RandomResourceName("javasdksp", 20);
                string            rgName           = SdkContext.RandomResourceName("rg", 20);
                try
                {
                    servicePrincipal = manager.ServicePrincipals.Define(name)
                                       .WithNewApplication("http://easycreate.azure.com/" + name)
                                       .DefinePasswordCredential("sppass")
                                       .WithPasswordValue("StrongPass!12")
                                       .Attach()
                                       .DefineCertificateCredential("spcert")
                                       .WithAsymmetricX509Certificate()
                                       .WithPublicKey(File.ReadAllBytes("Assets/myTest.cer"))
                                       .WithDuration(TimeSpan.FromDays(100))
                                       .WithAuthFileToExport(new StreamWriter(new FileStream(authFile, FileMode.OpenOrCreate)))
                                       .WithPrivateKeyFile("Assets/myTest._pfx")
                                       .WithPrivateKeyPassword("Abc123")
                                       .Attach()
                                       .WithNewRoleInSubscription(BuiltInRole.Contributor, subscriptionId)
                                       .Create();
                    Console.WriteLine(servicePrincipal.Id + " - " + string.Join(", ", servicePrincipal.ServicePrincipalNames));
                    Assert.NotNull(servicePrincipal.Id);
                    Assert.NotNull(servicePrincipal.ApplicationId);
                    Assert.Equal(2, servicePrincipal.ServicePrincipalNames.Count);
                    Assert.Equal(1, servicePrincipal.PasswordCredentials.Count);
                    Assert.Equal(1, servicePrincipal.CertificateCredentials.Count);

                    SdkContext.DelayProvider.Delay(10000);
                    IResourceManager resourceManager = Microsoft.Azure.Management.ResourceManager.Fluent.ResourceManager.Authenticate(
                        new AzureCredentialsFactory().FromFile(authFile)).WithSubscription(subscriptionId);
                    var group = resourceManager.ResourceGroups.Define(rgName).WithRegion(Region.USWest).Create();

                    // Update
                    IRoleAssignment ra = servicePrincipal.RoleAssignments.First();
                    servicePrincipal.Update()
                    .WithoutRole(ra)
                    .WithNewRoleInResourceGroup(BuiltInRole.Contributor, group)
                    .Apply();

                    SdkContext.DelayProvider.Delay(120000);
                    Assert.NotNull(resourceManager.ResourceGroups.GetByName(group.Name));
                    try
                    {
                        resourceManager.ResourceGroups.Define(rgName + "2")
                        .WithRegion(Region.USWest).Create();
                    }
                    catch (Exception)
                    {
                        // expected
                    }
                }
                finally
                {
                    if (servicePrincipal != null)
                    {
                        manager.ServicePrincipals.DeleteById(servicePrincipal.Id);
                        manager.Applications.DeleteById(manager.Applications.GetByName(servicePrincipal.ApplicationId).Id);
                    }
                }
            }
        }
 /// <summary>
 /// Specifies the Active Directory service principal this access policy is for.
 /// </summary>
 /// <param name="servicePrincipal">The AD service principal object.</param>
 /// <return>The next stage of access policy definition.</return>
 Microsoft.Azure.Management.KeyVault.Fluent.AccessPolicy.Definition.IWithAttach <Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithCreate> Microsoft.Azure.Management.KeyVault.Fluent.AccessPolicy.Definition.IWithIdentity <Microsoft.Azure.Management.KeyVault.Fluent.Vault.Definition.IWithCreate> .ForServicePrincipal(IServicePrincipal servicePrincipal)
 {
     return(this.ForServicePrincipal(servicePrincipal));
 }
 public ActiveDirectoryGroupImpl WithMember(IServicePrincipal servicePrincipal)
 {
     return(WithMember(servicePrincipal.Id));
 }
        /**
         * Azure Users, Groups and Roles sample.
         * - Create a user
         * - Assign role to AD user
         * - Revoke role from AD user
         * - Get role by scope and role name
         * - Create service principal
         * - Assign role to service principal
         * - Create 2 Active Directory groups
         * - Add the user, the service principal, and the 1st group as members of the 2nd group
         */
        public static void RunSample(Azure.IAuthenticated authenticated)
        {
            string userEmail   = Utilities.CreateRandomName("test");
            string userName    = userEmail.Replace("test", "Test ");
            string spName      = Utilities.CreateRandomName("sp");
            string raName1     = SdkContext.RandomGuid();
            string raName2     = SdkContext.RandomGuid();
            string groupEmail1 = Utilities.CreateRandomName("group1");
            string groupEmail2 = Utilities.CreateRandomName("group2");
            string groupName1  = groupEmail1.Replace("group1", "Group ");
            string groupName2  = groupEmail2.Replace("group2", "Group ");
            String spId        = "";

            string subscriptionId = authenticated.Subscriptions.List().First().SubscriptionId;

            Utilities.Log("Selected subscription: " + subscriptionId);

            // ============================================================
            // Create a user

            Utilities.Log("Creating an Active Directory user " + userName + "...");

            var user = authenticated.ActiveDirectoryUsers
                       .Define(userName)
                       .WithEmailAlias(userEmail)
                       .WithPassword("StrongPass!12")
                       .Create();

            Utilities.Log("Created Active Directory user " + userName);
            Utilities.Print(user);

            // ============================================================
            // Assign role to AD user

            IRoleAssignment roleAssignment1 = authenticated.RoleAssignments
                                              .Define(raName1)
                                              .ForUser(user)
                                              .WithBuiltInRole(BuiltInRole.DnsZoneContributor)
                                              .WithSubscriptionScope(subscriptionId)
                                              .Create();

            Utilities.Log("Created Role Assignment:");
            Utilities.Print(roleAssignment1);

            // ============================================================
            // Revoke role from AD user

            authenticated.RoleAssignments.DeleteById(roleAssignment1.Id);
            Utilities.Log("Revoked Role Assignment: " + roleAssignment1.Id);

            // ============================================================
            // Get role by scope and role name

            IRoleDefinition roleDefinition = authenticated.RoleDefinitions
                                             .GetByScopeAndRoleName("subscriptions/" + subscriptionId, "Contributor");

            Utilities.Print(roleDefinition);

            // ============================================================
            // Create Service Principal

            IServicePrincipal sp = authenticated.ServicePrincipals.Define(spName)
                                   .WithNewApplication("http://" + spName)
                                   .Create();

            // wait till service principal created and propagated
            SdkContext.DelayProvider.Delay(15000);
            Utilities.Log("Created Service Principal:");
            Utilities.Print(sp);
            spId = sp.Id;

            // ============================================================
            // Assign role to Service Principal

            string defaultSubscription = authenticated.Subscriptions.List().First().SubscriptionId;

            IRoleAssignment roleAssignment2 = authenticated.RoleAssignments
                                              .Define(raName2)
                                              .ForServicePrincipal(sp)
                                              .WithBuiltInRole(BuiltInRole.Contributor)
                                              .WithSubscriptionScope(defaultSubscription)
                                              .Create();

            Utilities.Log("Created Role Assignment:");
            Utilities.Print(roleAssignment2);

            // ============================================================
            // Create Active Directory groups

            Utilities.Log("Creating Active Directory group " + groupName1 + "...");
            var group1 = authenticated.ActiveDirectoryGroups
                         .Define(groupName1)
                         .WithEmailAlias(groupEmail1)
                         .Create();

            Utilities.Log("Created Active Directory group " + groupName1);
            Utilities.Print(group1);

            var group2 = authenticated.ActiveDirectoryGroups
                         .Define(groupName2)
                         .WithEmailAlias(groupEmail2)
                         .Create();

            Utilities.Log("Created Active Directory group " + groupName2);
            Utilities.Print(group2);

            Utilities.Log("Adding group members to group " + groupName2 + "...");
            group2.Update()
            .WithMember(user)
            .WithMember(sp)
            .WithMember(group1)
            .Apply();

            Utilities.Log("Group members added to group " + groupName2);
            Utilities.Print(group2);
        }
        /// <summary>
        /// Creates a RBAC role assignment (using role or role definition) for the given service principal.
        /// </summary>
        /// <param name="servicePrincipal">The service principal.</param>
        /// <param name="roleOrRoleDefinition">The role or role definition.</param>
        /// <param name="scope">The scope for the role assignment.</param>
        /// <return>An observable that emits the role assignment if it is created, null if assignment already exists.</return>
        ///GENMHASH:85AA7846D5642A1F7125332B46A901BE:A2437532CFAD0C7032A34C1FD573957E
        private async Task <Microsoft.Azure.Management.Graph.RBAC.Fluent.IRoleAssignment> CreateRbacRoleAssignmentIfNotExistsAsync(IServicePrincipal servicePrincipal, string roleOrRoleDefinition, string scope, bool isRole, CancellationToken cancellationToken = default(CancellationToken))
        {
            string roleAssignmentName = SdkContext.RandomGuid();

            try
            {
                if (isRole)
                {
                    return(await rbacManager
                           .RoleAssignments
                           .Define(roleAssignmentName)
                           .ForServicePrincipal(servicePrincipal)
                           .WithBuiltInRole(BuiltInRole.Parse(roleOrRoleDefinition))
                           .WithScope(scope)
                           .CreateAsync(cancellationToken));
                }
                else
                {
                    return(await rbacManager
                           .RoleAssignments
                           .Define(roleAssignmentName)
                           .ForServicePrincipal(servicePrincipal)
                           .WithRoleDefinition(roleOrRoleDefinition)
                           .WithScope(scope)
                           .CreateAsync(cancellationToken));
                }
            }
            catch (CloudException cloudException)
            {
                if (cloudException.Body != null && cloudException.Body.Code != null && cloudException.Body.Code.Equals("RoleAssignmentExists", StringComparison.OrdinalIgnoreCase))
                {
                    // NOTE: We are unable to lookup the role assignment from principal.RoleAssignments() list
                    // because role assignment object does not contain 'role' name (the roleDefinitionId refer
                    // 'role' using id with GUID).
                    return(null);
                }
                throw cloudException;
            }
        }
Ejemplo n.º 17
0
 public RoleAssignmentImpl ForServicePrincipal(IServicePrincipal servicePrincipal)
 {
     this.objectId = servicePrincipal.Id;
     return(this);
 }
Ejemplo n.º 18
0
        static async Task CreateOrUpdateResourceGroup(IServicePrincipal serverApplication)
        {
            Console.WriteLine("Add or update Key Vault Resource Group (required once)? [y/N] to continue: ");
            var key = Console.ReadLine()
                      .ToUpperInvariant()
                      .Trim();

            if (key != "Y")
            {
                return;
            }

            Console.Write("SubscriptionId: ");
            var subscriptionId = Console.ReadLine();

            Console.Write("Resource Group Name (blank for default 'SignService-KeyVaults'): ");
            var name = Console.ReadLine();

            if (string.IsNullOrWhiteSpace(name))
            {
                name = "SignService-KeyVaults";
            }

            Console.WriteLine("Location (eastus, westus, etc): ");
            var location = Console.ReadLine();

            var accessToken = await authContext.AcquireTokenSilentAsync(azureRmResourceId, ClientId);

            using var rgc = new ResourceManagementClient(new TokenCredentials(accessToken.AccessToken))
                  {
                      SubscriptionId = subscriptionId,
                      BaseUri        = new Uri(configuration["AzureRM:Instance"])
                  };
            var rg = new ResourceGroup(location, name: name);

            rg = await rgc.ResourceGroups.CreateOrUpdateAsync(name, rg);

            using var ac = new AuthorizationManagementClient(new TokenCredentials(accessToken.AccessToken))
                  {
                      SubscriptionId = subscriptionId,
                      BaseUri        = new Uri(configuration["AzureRM:Instance"])
                  };


            // See if the resource group has the reader role
            // Get the reader role
            var roleFilter = new ODataQuery <RoleDefinitionFilter>(f => f.RoleName == "Reader");

            var roleDefinitions = await ac.RoleDefinitions.ListAsync(rg.Id, roleFilter);

            var roleDefinition = roleDefinitions.First();
            var roleId         = roleDefinition.Id;

            var spid = serverApplication.ObjectId;

            var raps = await ac.RoleAssignments.ListForScopeAsync(rg.Id, new ODataQuery <RoleAssignmentFilter>(f => f.PrincipalId == spid));

            if (raps.All(ra => ra.RoleDefinitionId != roleId))
            {
                // none found, add one
                var rap = new RoleAssignmentCreateParameters
                {
                    PrincipalId      = spid,
                    RoleDefinitionId = roleId
                };
                var ra = await ac.RoleAssignments.CreateAsync(rg.Id, Guid.NewGuid().ToString(), rap);
            }
        }
 /// <summary>
 /// Removes a service principal as a member in the group.
 /// </summary>
 /// <param name="servicePrincipal">The service principal to remove.</param>
 /// <return>The next AD group update stage.</return>
 ActiveDirectoryGroup.Update.IUpdate ActiveDirectoryGroup.Update.IWithMemberBeta.WithoutMember(IServicePrincipal servicePrincipal)
 {
     return(this.WithoutMember(servicePrincipal));
 }
 /// <summary>
 /// Adds a service principal as a member in the group.
 /// </summary>
 /// <param name="servicePrincipal">The service principal to add.</param>
 /// <return>The next AD group definition stage.</return>
 ActiveDirectoryGroup.Definition.IWithCreate ActiveDirectoryGroup.Definition.IWithMemberBeta.WithMember(IServicePrincipal servicePrincipal)
 {
     return(this.WithMember(servicePrincipal));
 }
Ejemplo n.º 21
0
 public AzureRestClient(IServicePrincipal principal)
 {
     this.principal = principal;
     httpClient     = new HttpClient();
 }
        /**
         * Azure Service Principal sample for managing Service Principal -
         *  - Create an Active Directory application
         *  - Create a Service Principal for the application and assign a role
         *  - Export the Service Principal to an authentication file
         *  - Use the file to list subcription virtual machines
         *  - Update the application
         *  - Delete the application and Service Principal.
         */
        public static void RunSample(Azure.IAuthenticated authenticated, AzureEnvironment environment)
        {
            string spName             = Utilities.CreateRandomName("sp");
            string appName            = SdkContext.RandomResourceName("app", 20);
            string appUrl             = "https://" + appName;
            string passwordName1      = SdkContext.RandomResourceName("password", 20);
            string password1          = "P@ssw0rd";
            string passwordName2      = SdkContext.RandomResourceName("password", 20);
            string password2          = "StrongP@ss!12";
            string certName1          = SdkContext.RandomResourceName("cert", 20);
            string raName             = SdkContext.RandomGuid();
            string servicePrincipalId = "";

            try
            {
                // ============================================================
                // Create application

                Utilities.Log("Creating a service principal " + spName + "...");

                IServicePrincipal servicePrincipal = authenticated.ServicePrincipals
                                                     .Define(appName)
                                                     .WithNewApplication(appUrl)
                                                     .DefinePasswordCredential(passwordName1)
                                                     .WithPasswordValue(password1)
                                                     .Attach()
                                                     .DefinePasswordCredential(passwordName2)
                                                     .WithPasswordValue(password2)
                                                     .Attach()
                                                     .DefineCertificateCredential(certName1)
                                                     .WithAsymmetricX509Certificate()
                                                     .WithPublicKey(File.ReadAllBytes(Path.Combine(Utilities.ProjectPath, "Asset", "NetworkTestCertificate1.cer")))
                                                     .WithDuration(TimeSpan.FromDays(1))
                                                     .Attach()
                                                     .Create();

                Utilities.Log("Created service principal " + spName + ".");
                Utilities.Print(servicePrincipal);

                servicePrincipalId = servicePrincipal.Id;

                // ============================================================
                // Create role assignment

                Utilities.Log("Creating a Contributor role assignment " + raName + " for the service principal...");

                SdkContext.DelayProvider.Delay(15000);

                IRoleAssignment roleAssignment = authenticated.RoleAssignments
                                                 .Define(raName)
                                                 .ForServicePrincipal(servicePrincipal)
                                                 .WithBuiltInRole(BuiltInRole.Contributor)
                                                 .WithSubscriptionScope(authenticated.Subscriptions.List().First <ISubscription>().SubscriptionId)
                                                 .Create();

                Utilities.Log("Created role assignment " + raName + ".");
                Utilities.Print(roleAssignment);

                // ============================================================
                // Verify the credentials are valid

                Utilities.Log("Verifying password credential " + passwordName1 + " is valid...");

                AzureCredentials testCredential = new AzureCredentialsFactory().FromServicePrincipal(
                    servicePrincipal.ApplicationId, password1, authenticated.TenantId, environment);
                try
                {
                    Azure.Authenticate(testCredential).WithDefaultSubscription();

                    Utilities.Log("Verified " + passwordName1 + " is valid.");
                }
                catch (Exception e)
                {
                    Utilities.Log("Failed to verify " + passwordName1 + " is valid. Exception: " + e.Message);
                }

                Utilities.Log("Verifying password credential " + passwordName2 + " is valid...");

                testCredential = new AzureCredentialsFactory().FromServicePrincipal(
                    servicePrincipal.ApplicationId, password2, authenticated.TenantId, environment);
                try
                {
                    Azure.Authenticate(testCredential).WithDefaultSubscription();

                    Utilities.Log("Verified " + passwordName2 + " is valid.");
                }
                catch (Exception e)
                {
                    Utilities.Log("Failed to verify " + passwordName2 + " is valid. Exception: " + e.Message);
                }

                Utilities.Log("Verifying certificate credential " + certName1 + " is valid...");

                testCredential = new AzureCredentialsFactory().FromServicePrincipal(
                    servicePrincipal.ApplicationId,
                    Path.Combine(Utilities.ProjectPath, "Asset", "NetworkTestCertificate1.pfx"),
                    "Abc123",
                    authenticated.TenantId,
                    environment);
                try
                {
                    Azure.Authenticate(testCredential).WithDefaultSubscription();

                    Utilities.Log("Verified " + certName1 + " is valid.");
                }
                catch (Exception e)
                {
                    Utilities.Log("Failed to verify " + certName1 + " is valid. Exception: " + e.Message);
                }

                // ============================================================
                // Revoke access of the 1st password credential
                Utilities.Log("Revoking access for password credential " + passwordName1 + "...");

                servicePrincipal.Update()
                .WithoutCredential(passwordName1)
                .Apply();

                SdkContext.DelayProvider.Delay(15000);

                Utilities.Log("Credential revoked.");

                // ============================================================
                // Verify the revoked password credential is no longer valid

                Utilities.Log("Verifying password credential " + passwordName1 + " is revoked...");

                testCredential = new AzureCredentialsFactory().FromServicePrincipal(
                    servicePrincipal.ApplicationId, password1, authenticated.TenantId, environment);
                try
                {
                    Azure.Authenticate(testCredential).WithDefaultSubscription();

                    Utilities.Log("Failed to verify " + passwordName1 + " is revoked.");
                }
                catch (Exception e)
                {
                    Utilities.Log("Verified " + passwordName1 + " is revoked. Exception: " + e.Message);
                }

                // ============================================================
                // Revoke the role assignment

                Utilities.Log("Revoking role assignment " + raName + "...");

                authenticated.RoleAssignments.DeleteById(roleAssignment.Id);

                SdkContext.DelayProvider.Delay(5000);

                // ============================================================
                // Verify the revoked password credential is no longer valid

                Utilities.Log("Verifying password credential " + passwordName2 + " has no access to subscription...");

                testCredential = new AzureCredentialsFactory().FromServicePrincipal(
                    servicePrincipal.ApplicationId, password2, authenticated.TenantId, environment);
                try
                {
                    Azure.Authenticate(testCredential).WithDefaultSubscription()
                    .ResourceGroups.List();

                    Utilities.Log("Failed to verify " + passwordName2 + " has no access to subscription.");
                }
                catch (Exception e)
                {
                    Utilities.Log("Verified " + passwordName2 + " has no access to subscription. Exception: " + e.Message);
                }
            }
            catch (Exception f)
            {
                Utilities.Log(f.Message);
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting application: " + appName);
                    authenticated.ServicePrincipals.DeleteById(servicePrincipalId);
                    Utilities.Log("Deleted application: " + appName);
                }
                catch (Exception e)
                {
                    Utilities.Log("Did not create applications in Azure. No clean up is necessary. Exception: " + e.Message);
                }
            }
        }
 /// <summary>
 /// Specifies the assignee of the role assignment to be a service principal.
 /// </summary>
 /// <param name="servicePrincipal">The service principal object.</param>
 /// <return>The next stage in role assignment definition.</return>
 RoleAssignment.Definition.IWithRole RoleAssignment.Definition.IWithAssignee.ForServicePrincipal(IServicePrincipal servicePrincipal)
 {
     return(this.ForServicePrincipal(servicePrincipal) as RoleAssignment.Definition.IWithRole);
 }
 private static void UpdateServicePrincipal(Azure.IAuthenticated authenticated, IServicePrincipal servicePrincipal)
 {
     Utilities.Log("Updating Service Principal...");
     servicePrincipal.Update()
     // add another password credentials
     .WithoutCredential("ServicePrincipalAzureSample")
     .WithoutRole(servicePrincipal.RoleAssignments.First())
     .Apply();
 }
Ejemplo n.º 25
0
        public void CanSetMSIOnNewVMWithMultipleRoleAssignments()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var    groupName          = TestUtilities.GenerateName("rgmsi");
                var    storageAccountName = TestUtilities.GenerateName("ja");
                var    region             = Region.USSouthCentral;
                var    vmName             = "javavm";
                IAzure azure = null;
                try
                {
                    azure = TestHelper.CreateRollupClient();


                    IStorageAccount storageAccount = azure.StorageAccounts
                                                     .Define(storageAccountName)
                                                     .WithRegion(region)
                                                     .WithNewResourceGroup(groupName)
                                                     .Create();

                    var resourceGroup = azure.ResourceGroups.GetByName(storageAccount.ResourceGroupName);

                    IVirtualMachine virtualMachine = azure.VirtualMachines
                                                     .Define(vmName)
                                                     .WithRegion(region)
                                                     .WithExistingResourceGroup(groupName)
                                                     .WithNewPrimaryNetwork("10.0.0.0/28")
                                                     .WithPrimaryPrivateIPAddressDynamic()
                                                     .WithoutPrimaryPublicIPAddress()
                                                     .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                                     .WithRootUsername("Foo12")
                                                     .WithRootPassword("abc!@#F0orL")
                                                     .WithSize(VirtualMachineSizeTypes.StandardDS2V2)
                                                     .WithOSDiskCaching(CachingTypes.ReadWrite)
                                                     .WithSystemAssignedManagedServiceIdentity()
                                                     .WithSystemAssignedIdentityBasedAccessTo(resourceGroup.Id, BuiltInRole.Contributor)
                                                     .WithSystemAssignedIdentityBasedAccessTo(storageAccount.Id, BuiltInRole.Contributor)
                                                     .Create();

                    var authenticatedClient = TestHelper.CreateAuthenticatedClient();
                    // Validate service created service principal
                    //
                    IServicePrincipal servicePrincipal = authenticatedClient
                                                         .ServicePrincipals
                                                         .GetById(virtualMachine.SystemAssignedManagedServiceIdentityPrincipalId);

                    Assert.NotNull(servicePrincipal);
                    Assert.NotNull(servicePrincipal.Inner);

                    // Ensure the MSI extension is set
                    //
                    var  extensions     = virtualMachine.ListExtensions();
                    bool extensionFound = false;
                    foreach (var extension in extensions.Values)
                    {
                        if (extension.PublisherName.Equals("Microsoft.ManagedIdentity", StringComparison.OrdinalIgnoreCase) &&
                            extension.TypeName.Equals("ManagedIdentityExtensionForLinux", StringComparison.OrdinalIgnoreCase))
                        {
                            extensionFound = true;
                            break;
                        }
                    }
                    Assert.True(extensionFound);


                    // Ensure role assigned for resource group
                    //

                    var rgRoleAssignments = authenticatedClient.RoleAssignments.ListByScope(resourceGroup.Id);
                    Assert.NotNull(rgRoleAssignments);
                    bool found = false;
                    foreach (var roleAssignment in rgRoleAssignments)
                    {
                        if (roleAssignment.PrincipalId != null && roleAssignment.PrincipalId.Equals(virtualMachine.SystemAssignedManagedServiceIdentityPrincipalId, StringComparison.OrdinalIgnoreCase))
                        {
                            found = true;
                            break;
                        }
                    }
                    Assert.True(found, "Resource group should have a role assignment with virtual machine MSI principal");

                    // Ensure role assigned for storage account
                    //
                    var stgRoleAssignments = authenticatedClient.RoleAssignments.ListByScope(storageAccount.Id);
                    Assert.NotNull(stgRoleAssignments);
                    found = false;
                    foreach (var roleAssignment in stgRoleAssignments)
                    {
                        if (roleAssignment.PrincipalId != null && roleAssignment.PrincipalId.Equals(virtualMachine.SystemAssignedManagedServiceIdentityPrincipalId, StringComparison.OrdinalIgnoreCase))
                        {
                            found = true;
                            break;
                        }
                    }
                    Assert.True(found, "Storage account should have a role assignment with virtual machine MSI principal");
                }
                finally
                {
                    try
                    {
                        if (azure != null)
                        {
                            azure.ResourceGroups.BeginDeleteByName(groupName);
                        }
                    }
                    catch { }
                }
            }
        }
 ///GENMHASH:7B10596856964977EC5E018A031EE6E9:E17FF884EE021904E2BD4F8BD9BDB6FC
 public AccessPolicyImpl ForServicePrincipal(IServicePrincipal servicePrincipal)
 {
     Inner.ObjectId = servicePrincipal.Id;
     return(this);
 }