Azure App Service: using PerformanceCounters - azure

I am trying to setup my Azure Web App to include the use of a third party software, which seems to require access to PerformanceCounters. Locally this works fine, but when I run it in Azure I get the following error:
[UnauthorizedAccessException: Access to the registry key 'Global' is denied.]
Microsoft.Win32.RegistryKey.Win32Error(Int32 errorCode, String str) +5230217
Microsoft.Win32.RegistryKey.InternalGetValue(String name, Object defaultValue, Boolean doNotExpand, Boolean checkSecurity) +11769029
Microsoft.Win32.RegistryKey.GetValue(String name) +40
System.Diagnostics.PerformanceMonitor.GetData(String item) +102
System.Diagnostics.PerformanceCounterLib.GetPerformanceData(String item) +186
System.Diagnostics.PerformanceCounterLib.get_CategoryTable() +105
System.Diagnostics.PerformanceCounterLib.GetCategorySample(String category) +17
System.Diagnostics.PerformanceCounterLib.GetCategorySample(String machine, String category) +61
System.Diagnostics.PerformanceCounterCategory.GetCounterInstances(String categoryName, String machineName) +70
System.Diagnostics.PerformanceCounterCategory.GetInstanceNames() +25
According to this answer, I should configure IIS to allow access to the app pool/user, but I don't think that is possible for a Azure Web App. Is there a way to get performance counters working in my situation?

On Windows, Performance Counters are accessible through WMI:
https://msdn.microsoft.com/en-us/library/aa392397(v=vs.85).aspx
WMI is restricted in the App Service sandbox.
From https://github.com/projectkudu/kudu/wiki/Azure-Web-App-sandbox#access-to-out-of-process-com-servers:
Access to out-of-process COM servers
Windows Servers have a bunch of COM servers configured and available for consumption by default; however the sandbox prevents access to all out-of-proc COM servers. For example, a sandboxed application cannot call into WMI, or into MSIServer.
From Kudu:
PS D:\home> Get-Counter -Counter "\processor(_total)\% processor time"
Get-Counter : The specified object was not found on the computer.
PS D:\home> Get-WmiObject -Class WIN32_OperatingSystem
Get-WmiObject : Access is denied. (Exception from HRESULT: 0x80070005
(E_ACCESSDENIED))
If you absolutely have to use the 3rd party software, look at Azure Cloud Services (with a Web Role). You have full control over the OS there while still being PaaS.

Related

Azure Traffic Manager errors when adding 2nd App Service as endpoint

We have added an app service as an endpoint to Azure Traffic Manager, and everything is working fine. However, when trying to add a second app service it fails with the following error:
Some of the provided Azure Website endpoints are not valid: Traffic manager configuration unexpectedly failed in region 'uksouth' with exception: Microsoft.Web.Hosting.Administration.Client.GeomasterClientException: Call to geomaster failed!, HttpStatusCode=BadRequest, RequestId='cae63ca1-0a3d-4f87-bd8e-9b881186e114', Uri=https://ln1.geomaster.azurewebsites.windows.net:444/subscriptions/fe12301c-5b6f-45f7-a038-ce2d4dbeec94/providers/Microsoft.Web/verifyTrafficManagerConfiguration?api-version=2018-02-01, CorrelationId=06de79f7-a67a-4a0e-ac5f-f6db24d5f908 at Microsoft.Web.Hosting.Administration.Client.InterGeomasterClient.Send[P,R](HttpMethod verb, String path, String queryString, P payload, Boolean throwOnError) at Microsoft.Web.Hosting.Administration.Client.InterGeomasterClient.<>c__DisplayClass22_0`2.<Post>b__0() at Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling.RetryPolicy.ExecuteAction[TResult](Func`1 func) at Microsoft.Web.Hosting.Administration.Client.RegionalToRegionalClient.VerifyAndRegisterTrafficManagerConfiguration(String subscriptionName, CsmTrafficManagerConfiguration csmTrafficManagerConfiguration) at Microsoft.Web.Hosting.Administration.GeoScale.Sql.SubscriptionController.ForwardVerifyAndRegisterApiCallToRegionalGeomaster(RESTApiMetricsTracker tracker, String location, String subscriptionName, String trafficManagerDomainName, String[] hostNamesForsitesInRegion, Boolean registerTrafficManagerDomainName, Boolean failIneligibleSites)
We seem to be able to add two different app services without error, even this particular one with a different app service without error. It seems to be this particular combination of app services that fails as if they are somehow incompatible?
Not sure if it's significant but it seems combinations with an old app service (i.e. created a couple of years ago doesn't work with a recently created app service) but adding two app services that have been created recently works OK.
This error could be because of using the free tier of Traffic Management. If you are using the free tier of the old app, then change the tier plan.
Alternatively:
If the two apps are running on standard tier and still the issue occurs, then it must be the location error mentioned in the exception. That is South. Make sure the regions of the apps running are compatible with all the services you want to use. Some of the services may not be enabled in all the availability zones.

Remote WMI query failing with 'A security package specific error occurred' when using Azure Active Directory user

I'm attempting to query a remote machine with the PowerShell cmdlet: Get-WmiObject and using credentials for a user in Azure AD that has the Azure AD joined device local administrator role and the IAM role assignment of Virtual Machine Administrator Login on the remote machine.
When I run the following command:
Get-WmiObject -Class Win32_Process -Namespace "root/cimv2" -ComputerName <remote_computer_local_ip> -Impersonation Impersonate -Credential AzureAD\<username>
I receive the following error message:
Get-WmiObject : A security package specific error occurred. (Exception from HRESULT: 0x80070721)
Is the ability to run remote WMI queries supported when using an Azure AD user?
Remote machine specs:
Windows Server 2019 Datacenter
10.0.17763 Build 17763
Other troubleshooting notes:
I'm able to sign to the remote machine with the same user and have followed the steps in the https://learn.microsoft.com/en-us/azure/active-directory/devices/howto-vm-sign-in-azure-ad-windows document
When running the same command on the remote machine locally it properly returns the Win32_Process data
If I use the local administrator credentials on the remote command it also works which suggests that remote WMI is working
Both computers are Azure AD joined and show AzureAdJoined : YES from the dsregcmd /status command
I've attempted to use the Computer Name, Local IP, and FQDN and they all yield the same result
After talking with Microsoft support about this issue, it seems that the error stems from the different authentication methods between a local user account and an Azure AD account.
It seems it is not supported as they are using different authentication protocols.
Azure AD user uses OAuth and the security error is due to Kerberos.
Here is the reference article for more details: Authentication protocols in Azure Active Directory B2C | Microsoft Docs
They have also mentioned that there is no current information on whether or not this will be supported in the future and have recommend checking Azure updates for future product updates.
It could happen for number of reasons. Please check if any of these in your case is the one.
When You try to setup a WMI session when:
a. There are more than one computer accounts with the same name in play and one of those stale computer accounts resides in the same domain as your user account
b. Or when servers operating reside in the same AD DS forest but in different domains.
When server is not able to find the user object due to password credentials that may be stored as cache from previous login.
Incorrect time on machines/server that doesn’t match.
If firewalls are enabled for server which may restrict the access.
possible work arounds
Try azuread\user#mydomain.com or user#mydomain.com or domainame\username format to login or Try taking out the domain and adding it back again.
The local PC and remote PC must be in the same Azure AD tenant.
Run AAD delta Sync to make sure everything is Synced and make sure of internet connectivity and network.
Try if you can turn off firewall.
References:
remote access - AAD- Server Fault
rdp -Azure AD Joined - Server Fault
«0x80070721 | exchange12rocks.org)
A security package specific error occurred | Microsoft Docs

Azure Service Bus 1.1 Failing to Start

Service Bus Gateway is not starting.
First of all I have tried completely uninstalling all Azure/Fabric/Service Bus type SDKs and installations. I have installed both Windows Azure Pack: Service Bus 1.1 and Windows Azure Pack: Security Update for Service Bus 1.1 (KB2972621) from scratch.
After deleting all service bus related databases I start the Service Bus Configuration wizard and begin starting a new farm with custom settings.
I leave everything default except adding my own certificates, and of course entering my password.
After clicking go the the service bus configuration wizard eventually gets stuck in progress:
Starting
Created and configured Service Bus farm management database.
Created and configured Service Bus gateway database.
Creating default container.
Processing completed
Validating input and configuration parameters.
Granting 'Log on as Service' privilege to the run as account.
Windows Fabric configuration started.
Running Windows Fabric deployment.
Windows Fabric starting.
Service Bus configuration started.
Updating database.
Service Bus services starting.
The event viewer logs for Microsoft-Service Bus > Operational has the following errors. Top error received first...
Exception during fabric service creation for container 1, Exception System.ArgumentException: At least one address must be provided if hostEndpoints is non-null
Parameter name: hostEndpoints
at System.Fabric.FabricClient.InitializeFabricClient(SecurityCredentials credential, TimeSpan keepAliveInterval, String[] hostEndpoints)
at System.Fabric.FabricClient..ctor(SecurityCredentials credential, String[] hostEndpoints)
at Microsoft.ServiceBus.Commands.ServiceBusGetCommands.CreateFabricClient()
at Microsoft.ServiceBus.Commands.ServiceBusCommandBase.RegisterWinFabricService(Int64 containerId)
And then:
Service Bus Gateway service failed to start, retry count 1. Exception message: An error occurred creating the configuration section handler for namespacePolicyDataStoreFactory: Could not load file or assembly 'Microsoft.Cloud.Common.AzureStorage, Version=2.1.0.0, Culture=neutral, PublicKeyToken=4fe77f22fa8374f3' or one of its dependencies. The system cannot find the file specified.. Stack Trace: at System.Configuration.BaseConfigurationRecord.CallCreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader, String filename, Int32 line)
at System.Configuration.BaseConfigurationRecord.CreateSectionDefault(String configKey, Boolean getRuntimeObject, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at Microsoft.Cloud.ServiceBus.ServiceRegistryManagerContext.CreateNamespacePolicyDataManager(IComponentSite site)
at Microsoft.Cloud.ServiceBus.ServiceRegistryManagerContext.LoadServices(IComponentSite site)
at Microsoft.Cloud.ServiceBus.Common.Components.ComponentFactoryBase`1.CreateComponent()
at Microsoft.Cloud.HostingModel.ComponentHost.CreateComponent(IComponentFactory componentFactory)
at Microsoft.Cloud.HostingModel.ComponentHost.CreateComponents()
at Microsoft.Cloud.HostingModel.ComponentHost.Open()
at Microsoft.ServiceBus.Gateway.Gateway.OnStart(String[] args)
In Services the relevant services have the following statuses:
Service Bus Gateway: Starting
Service Bus Message Broker: Stopped
Service Bus Resource Provider: Stopped
Thanks
If you received this error after updating to NET framework v4.6+ then
Microsoft have a fix for this now, download this Update for Service Bus Server 1.1 (KB3086798) http://www.microsoft.com/en-us/download/details.aspx?id=49496
TL;DR;
Download dropbox.com/s/cb5fro1rv... - thanks Arash Rahimi
Navigate to your SDK tools
sn -Vr Microsoft.Cloud.Common.AzureStorage.dll
gacutil /i Microsoft.Cloud.Common.AzureStorage.dll
This issue was caused by installing the Visual Studio 2015 RC. Thankfully someone else has already experienced this and an answer has been posted.
Please see this answer on How do I report a bug in Windows Server Service Bus?
For whatever reason if the Dropbox link becomes obsolete. I have added it to Github.
Make sure any/all RabbitMQ service(s) are all stopped. (Or anything that uses the AMQP protocol)

Can a Worker Role process call Antimalware for Azure Cloud Services programmatically?

I'm trying to find a solution that I can use to perform virus scanning on files that have been uploaded to Azure blob storage. I wanted to know if it is possible to copy the file to local storage on a Worker Role instance, call Antimalware for Azure Cloud Services to perform the scan on that specific file, and then depending on whether the file is clean, process the file accordingly.
If the Worker Role cannot call the scan programmatically, is there a definitive way to check if a file has been scanned and whether it is clean or not once it has been copied to local storage (I don't know if the service does a real-time scan when new files are added, or only runs on a schedule)?
There isn't a direct API that we've found, but the anti-malware services conform to the standards used by Windows desktop virus checkers in that they implement the IAttachmentExecute COM API.
So we ended up implementing a file upload service that writes the uploaded file to a Quarantine local resource, then calling the IAttachmentExecute API. If the file is infected then, depending on the anti-malware service in use, it will either throw an exception, silently delete the file or mark it as inaccessible. So by attempting to read the first byte of the file, we can test if the file remains accessible.
var type = Type.GetTypeFromCLSID(new Guid("4125DD96-E03A-4103-8F70-E0597D803B9C"));
var svc = (IAttachmentExecute)Activator.CreateInstance(type);
try {
svc.SetClientGuid(ref clientGuid);
svc.SetLocalPath(path);
svc.Save();
}
finally
{
svc.ClearClientState();
}
using (var fileStream = File.OpenRead(path))
{
fileStream.ReadByte();
}
[Guid("73DB1241-1E85-4581-8E4F-A81E1D0F8C57")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IAttachmentExecute
{
void SetClientGuid(ref Guid guid);
void SetLocalPath(string pszLocalPath);
void Save();
void ClearClientState();
}
I think the best way for you to know is simply take an Azure VM (IaaS) and activate Microsoft Antimalware extension. Then you may log into it and do all the necessary check and tests against the service.
Later, you will apply all this into the Worker Role (there is a similar PaaS extension available for that, calles PaaSAntimalware).
See the next excerpt from https://msdn.microsoft.com/en-us/library/azure/dn832621.aspx:
"In PaaS, the VM agent is called GuestAgent, and is always available on Web and Worker Role VMs. (For more information, see Azure Role Architecture.) The VM agent for Role VMs can now add extensions to the cloud service VMs in the same way that it does for persistent Virtual Machines.
The biggest difference between VM Extensions on role VMs and persistent VMs is that with role VMs, extensions are added to the cloud service first and then to the deployments within that cloud service.
Use the Get-AzureServiceAvailableExtension cmdlet to list all available role VM extensions."

Accessing OnPremises Active Directory from WebRole running in Azure

I am trying to access the onpremises active directory from the web application running on Azure. We have selected Azure Connect as it best fits our requirement (authenticate user as well as fetch user information from Active Directory).
I have followed the steps provided in this link1 and link2, but still failing to achieve the goal.
Below is the method, I a trying to test if the onpremises Active Directory is reachable from Azure: DirectoryEntry.Exists("LDAP Path")
Below is the error I am encountering:
System.Runtime.InteropServices.COMException (0x8007054B): The
specified domain either does not exist or could not be contacted.
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Exists(String path) at
WebRole1.MyLogInPage.btnSubmit_Click(Object sender, EventArgs e)
I can see the connect endpoint software is running fine without any connectivity issue, on the server running Active Directory and the endpoint group is properly setup.

Resources