Creating Azure Traffic Manager through REST API - unexpected behaviour - azure

I created Traffic Manager throught its REST API using 2011-10-01 MS verion.
Resources I followed -
Create Profile -
http://msdn.microsoft.com/en-us/library/windowsazure/hh758254.aspx
Create Definition -
http://msdn.microsoft.com/en-us/library/windowsazure/hh758257.aspx
Traffic Manager got created successfully. All happies.
But after 30mins of time, traffic manager is going to INACTIVE status and all its endpoints are GONE. It shows there are no endpoints associated with it.
I am not sure what is happening around. Is it Azure problem? or is it REST API problem? or is it my way of creating Traffic manager problem.
PS - I followed this sample for making REST API calls - http://msdn.microsoft.com/en-us/library/windowsazure/gg651127.aspx
Any help would be highly appreciated.
UPDATE1
Parameters
SubscriptionID - a Valid GUID from publishsettings
Certificate - I cross checked a valid certificate present in the local cert store
endpoint1 domain name - JASH13.CLOUDAPP.NET
endpoint2 domain name - JASH23.CLOUDAPP.NET
There is no error at REST API calls level. Everything worked seamlessly.
Profile Creation -
// X.509 certificate variables.
X509Store certStore = null;
X509Certificate2Collection certCollection = null;
X509Certificate2 certificate = null;
// Request and response variables.
HttpWebRequest httpWebRequest = null;
HttpWebResponse httpWebResponse = null;
// Stream variables.
Stream responseStream = null;
StreamReader reader = null;
// URI variable.
Uri requestUri = null;
// The thumbprint for the certificate. This certificate would have been
// previously added as a management certificate within the Windows Azure management portal.
string thumbPrint = CertificateThumbprint;
// Open the certificate store for the current user.
certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certStore.Open(OpenFlags.ReadOnly);
// Find the certificate with the specified thumbprint.
certCollection = certStore.Certificates.Find(
X509FindType.FindByThumbprint,
thumbPrint,
false);
// Close the certificate store.
certStore.Close();
// Check to see if a matching certificate was found.
if (0 == certCollection.Count)
{
throw new Exception("No certificate found containing thumbprint " + thumbPrint);
}
// A matching certificate was found.
certificate = certCollection[0];
// Create the request.
requestUri = new Uri("https://management.core.windows.net/"
+ SubscriptionId
+ "/services/WATM/profiles");
httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(requestUri);
// Add the certificate to the request.
httpWebRequest.ClientCertificates.Add(certificate);
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("x-ms-version", "2011-10-01");
string str = #"<Profile xmlns=""http://schemas.microsoft.com/windowsazure""><DomainName>" + ProfileDomain + "</DomainName><Name>" + ProfileName + "</Name></Profile>";
byte[] bodyStart = System.Text.Encoding.UTF8.GetBytes(str.ToString());
Stream dataStream = httpWebRequest.GetRequestStream();
dataStream.Write(bodyStart, 0, str.ToString().Length);
// Make the call using the web request.
httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
// Parse the web response.
responseStream = httpWebResponse.GetResponseStream();
reader = new StreamReader(responseStream);
// Close the resources no longer needed.
httpWebResponse.Close();
responseStream.Close();
reader.Close();
Definition Creation-
// X.509 certificate variables.
X509Store certStore = null;
X509Certificate2Collection certCollection = null;
X509Certificate2 certificate = null;
// Request and response variables.
HttpWebRequest httpWebRequest = null;
HttpWebResponse httpWebResponse = null;
// Stream variables.
Stream responseStream = null;
StreamReader reader = null;
// URI variable.
Uri requestUri = null;
// The thumbprint for the certificate. This certificate would have been
// previously added as a management certificate within the Windows Azure management portal.
string thumbPrint = CertificateThumbprint;
// Open the certificate store for the current user.
certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certStore.Open(OpenFlags.ReadOnly);
// Find the certificate with the specified thumbprint.
certCollection = certStore.Certificates.Find(
X509FindType.FindByThumbprint,
thumbPrint,
false);
// Close the certificate store.
certStore.Close();
// Check to see if a matching certificate was found.
if (0 == certCollection.Count)
{
throw new Exception("No certificate found containing thumbprint " + thumbPrint);
}
// A matching certificate was found.
certificate = certCollection[0];
// Create the request.
requestUri = new Uri("https://management.core.windows.net/"
+ SubscriptionId
+ "/services/WATM/profiles/" + ProfileName + "/definitions");
httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(requestUri);
// Add the certificate to the request.
httpWebRequest.ClientCertificates.Add(certificate);
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("x-ms-version", "2011-10-01");
string str = #"<Definition xmlns=""http://schemas.microsoft.com/windowsazure""><DnsOptions><TimeToLiveInSeconds>300</TimeToLiveInSeconds></DnsOptions><Monitors><Monitor><IntervalInSeconds>30</IntervalInSeconds><TimeoutInSeconds>10</TimeoutInSeconds><ToleratedNumberOfFailures>3</ToleratedNumberOfFailures><Protocol>HTTP</Protocol><Port>80</Port><HttpOptions><Verb>GET</Verb><RelativePath>/</RelativePath><ExpectedStatusCode>200</ExpectedStatusCode></HttpOptions></Monitor></Monitors><Policy><LoadBalancingMethod>RoundRobin</LoadBalancingMethod><Endpoints><Endpoint><DomainName>" + PrimaryService + "</DomainName><Status>Enabled</Status></Endpoint><Endpoint><DomainName>" + SecondaryService + "</DomainName><Status>Enabled</Status></Endpoint></Endpoints></Policy></Definition>";
byte[] bodyStart = System.Text.Encoding.UTF8.GetBytes(str.ToString());
Stream dataStream = httpWebRequest.GetRequestStream();
dataStream.Write(bodyStart, 0, str.ToString().Length);
// Make the call using the web request.
httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
// Parse the web response.
responseStream = httpWebResponse.GetResponseStream();
reader = new StreamReader(responseStream);
// Close the resources no longer needed.
httpWebResponse.Close();
responseStream.Close();
reader.Close();
UPDATE2
Once the TM went into Inactive State, I checked the profile definition using REST API. In there I was not able to find any endpoints. They are missing.
<Definitions xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Definition>
<DnsOptions>
<TimeToLiveInSeconds>300</TimeToLiveInSeconds>
</DnsOptions>
<Status>Enabled</Status>
<Version>1</Version>
<Monitors>
<Monitor>
<IntervalInSeconds>30</IntervalInSeconds>
<TimeoutInSeconds>10</TimeoutInSeconds>
<ToleratedNumberOfFailures>3</ToleratedNumberOfFailures>
<Protocol>HTTP</Protocol>
<Port>80</Port>
<HttpOptions>
<Verb>GET</Verb>
<RelativePath>/</RelativePath>
<ExpectedStatusCode>200</ExpectedStatusCode>
</HttpOptions>
</Monitor>
</Monitors>
<Policy>
<LoadBalancingMethod>Performance</LoadBalancingMethod>
<Endpoints/>
<MonitorStatus>Inactive</MonitorStatus>
</Policy>
</Definition>
</Definitions>
UPDATE3
This sporadic behavior is ONLY happening with the specific cloud services and TM profile/definitiona. When I create new set of cloud services and TM profile, then everything seems to be working fine. I tested this multiple times. So the only problem is with following parameters.
endpoint1 domain name - JASH13.CLOUDAPP.NET
endpoint2 domain name -JASH23.CLOUDAPP.NET
TM Domain - ramitm.trafficmanager.net
TM profilename - ramitm

This seems like some DNS Problems for very fast REST API Operations. I was not able to get the crux of the problem, but this is how I solved it.
Previously I was getting this problem for this patter - Create -> Delete -> Re-Create
Now I made it this way - Create -> Delete -> Delay -> Re-Create
I think by introducing delay component, I am giving enough time for Azure to settle down all the DNS and infrastructure and there by update them. So after introducing delay, I was not experiencing the problem. Delay can be 5 - 10 mins.

Related

Two way SSL X509 Certificate location for secure service request in .Net Core MVC - Azure Services Hosted application

I've being working with x509 certificates in order to make secure requests to some data services. They require Two way SSL auth, so I've converted my "Sandbox" certificate (.crt) w/ my Private Key to a Password protected .p12 file.
Here's the first question: Where should I place this .p12 file so that it's readable by my application after deploying to Azure (Using DevOps) but still stored securely? Can I use an my Azure Key Vault?
The second issue is that in my Dev environment I haven't been able to establish the SSL binding after making the request (With a .p12 absolute path):
Here's the code I'm using:
void GetATMs()
{
string requestURL = "https://sandbox.api.visa.com/globalatmlocator/v1/localatms/atmsinquiry";
string userId = "MyUserId";
string password = "MyPassword";
string p12certificatePath = "C:\\Code\\projects\\project\\\\Clients\\PaymentGateways\\Visa\\Certs\\TC_keyAndCertBundle.p12";
string p12certificatePassword = "CertPassword";
string postData = #"{""wsRequestHeaderV2"": { ""requestTs"": ""2018-11-06T03:16:18.000Z"", ""applicationId"": ""VATMLOC"", ""requestMessageId"": ""ICE01-001"", ""userId"": ""CDISIUserID"", ""userBid"": ""10000108"", ""correlationId"": ""909420141104053819418"" }, ""requestData"": { ""culture"": ""en-US"", ""distance"": ""20"", ""distanceUnit"": ""mi"", ""metaDataOptions"": 0, ""location"": { ""address"": null, ""placeName"": ""700 Arch St, Pittsburgh, PA 15212"", ""geocodes"": null }, ""options"": { ""range"": { ""start"": 10, ""count"": 20 }, ""sort"": { ""primary"": ""city"", ""direction"": ""asc"" }, ""operationName"": ""or"", ""findFilters"": [ { ""filterName"": ""OPER_HRS"", ""filterValue"": ""C"" } ], ""useFirstAmbiguous"": true } } }";
HttpWebRequest request = WebRequest.Create(requestURL) as HttpWebRequest;
request.Method = "POST";
// Add headers
string authString = userId + ":" + password;
var authStringBytes = System.Text.Encoding.UTF8.GetBytes(authString);
string authHeaderString = Convert.ToBase64String(authStringBytes);
request.Headers["Authorization"] = "Basic " + authHeaderString;
// Add certificate
var certificate = new X509Certificate2(p12certificatePath, p12certificatePassword);
request.ClientCertificates.Add(certificate);
request.Accept = "application/json";
var data = Encoding.ASCII.GetBytes(postData);
request.ContentLength = data.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(data, 0, data.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
What am I missing here?
It fails the following way:
An unhandled exception occurred while processing the request.
Win32Exception: The credentials supplied to the package were not recognized
System.Net.SSPIWrapper.AcquireCredentialsHandle(SSPIInterface secModule, string package, CredentialUse intent, SCHANNEL_CRED scc)
HttpRequestException: The SSL connection could not be established, see inner exception.
System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
WebException: The SSL connection could not be established, see inner exception. The credentials supplied to the package were not recognized
System.Net.HttpWebRequest.GetResponse()
We have a Wildcard SSL for our domain. Are they different? Can it be registered in the Visa dashboard and used for make secure request as it is signed by a trusted CA authority?
Well, yes. As per, #dagope Recommendation, I've uploaded my certificate to key-management on Azure and access it through the SDK. This is also a best practice for key/certificate management on Azure.

Programmatically getting the list of azure virtual machine sizes

I am new to Azure management libraries for .net. How can we enumerate VM instance sizes available with respect to subscription or in general using Azure Management libraries for .Net or Rest APIs?
Please suggest.
You can get a list of VM sizes for a region by calling
https://management.azure.com/subscriptions/{subscription-id}/providers/Microsoft.Compute/locations/{location}/vmSizes?api-version={api-version}
As documented here - List all available virtual machine sizes in a region
There is also a .Net Class for the same, but I've not found any examples of it being used - documented here - VirtualMachineSizeOperationsExtensions.List
You can get list of VM sizes by region fillter
AuthenticationContext authenticationContext = new AuthenticationContext("https://login.windows.net/tenantdomainname.onmicrosoft.com"]);
UserCredential uc = new UserCredential(authusername,authpassword);
token = authenticationContext.AcquireToken("https://management.core.windows.net/", nativetenantid, uc);
var credentials = new TokenCredentials(token);
var computeClient = new ComputeManagementClient(credentials) { SubscriptionId = subscriptionid};
var virtualMachineSize = computeClient.VirtualMachineSizes.List(region_name).ToList();
you must need create one native client api on Azure Active Directory for token base authentication otherwise you can also use certification base authentication for client authorization.
i am using Microsoft.Azure.Management.Compute.dll, v10.0.0.0 for compute resources.
you can download here: https://www.nuget.org/packages/Microsoft.Azure.Management.Compute/13.0.4-prerelease
You can get list of VM Size by using Certificate Base Authentication
Get Certificate method
private static X509Certificate2 GetStoreCertificate(string subscriptionId, string thumbprint)
{
List<StoreLocation> locations = new List<StoreLocation>
{
StoreLocation.CurrentUser,
StoreLocation.LocalMachine
};
foreach (var location in locations)
{
X509Store store = new X509Store(StoreName.My, location);
try
{
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2Collection certificates = store.Certificates.Find(
X509FindType.FindByThumbprint, thumbprint, false);
if (certificates.Count == 1)
{
return certificates[0];
}
}
finally
{
store.Close();
}
}
throw new ArgumentException(string.Format("A Certificate with Thumbprint '{0}' could not be located.",thumbprint));
}
here i describe same way to get VM size
private static X509Certificate2 Certificate = GetStoreCertificate(Your-subscriptionid,Your-thumbprint);
Microsoft.Azure.CertificateCloudCredentials credentials = new Microsoft.Azure.CertificateCloudCredentials(Your-subscriptionid, Certificate);
var computeClient = new ComputeManagementClient(credentials) { SubscriptionId = Your-subscriptionid};
var virtualMachineSize = computeClient.VirtualMachineSizes.List(Your-region_name).ToList();

Add PFX Certificate to Azure WebApp using ARM (not for ssl)

Using Rest Management APIS that are backed by Azure Resource Manager the following code adds a certificate from keyvault to ARM.
var secret = keyvaultClient.GetSecretAsync(vaultUri, options.CertificateName).GetAwaiter().GetResult();
var certUploaded = client.Certificates.CreateOrUpdateCertificateWithHttpMessagesAsync(
options.ResourceGroupName, options.CertificateName,
new Certificate {
PfxBlob = secret.Value,
Location = app.Body.Location
}).GetAwaiter().GetResult();
var appSettings = client.Sites.ListSiteAppSettingsWithHttpMessagesAsync(options.ResourceGroupName, options.WebAppName).GetAwaiter().GetResult();
var existing = (appSettings.Body.Properties["WEBSITE_LOAD_CERTIFICATES"] ?? "").Split(',').ToList();
if (!existing.Contains(certUploaded.Body.Thumbprint))
existing.Add(certUploaded.Body.Thumbprint);
appSettings.Body.Properties["WEBSITE_LOAD_CERTIFICATES"] = string.Join(",",existing);
appSettings.Body.Properties[$"CN_{options.CertificateName}"] = certUploaded.Body.Thumbprint;
var result = client.Sites.UpdateSiteAppSettingsWithHttpMessagesAsync(options.ResourceGroupName, options.WebAppName, appSettings.Body).GetAwaiter().GetResult();
the problem is that when loading it in the webapp
X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCollection = certStore.Certificates.Find(
X509FindType.FindByThumbprint,
// Replace below with your cert's thumbprint
"0CE28C6246317AEB00B88C88934700865C71CBE0",
false);
Trace.TraceError($"{certCollection.Count}");
Console.WriteLine($"{certCollection.Count}");
// Get the first cert with the thumbprint
if (certCollection.Count > 0)
{
X509Certificate2 cert = certCollection[0];
// Use certificate
Console.WriteLine(cert.FriendlyName);
}
certStore.Close();
it is not loaded.
If I instead upload it using the portal, everything works as expected.
I also noticed that the certificates uploaded in the portal do not exist in ARM, only the certs added with the code in the start of the post exists.:
So what do we need to do to make a certificate available to webapp that do not involve manual uploading to portal?
The problem was that the certificates should be added to the resource group of the serverfarm that the webapp is hosted within and not the resourcegroup of the webapp.
Changing the code to deploy to the correct resourcegroup solved everything.
For reference my updated code is here:
var vaultUri = $"https://{options.VaultName}.vault.azure.net";
var keyvaultClient = new KeyVaultClient((_, b, c) => Task.FromResult(options.VaultAccessToken));
using (var client = new WebSiteManagementClient(
new TokenCredentials(cred.AccessToken)))
{
client.SubscriptionId = cred.SubscriptionId;
var app = client.Sites.GetSite(options.ResourceGroupName, options.WebAppName);
var serverFarmRG = Regex.Match(app.ServerFarmId, "resourceGroups/(.*?)/").Groups[1];
var secret = keyvaultClient.GetSecretAsync(vaultUri, options.CertificateName).GetAwaiter().GetResult();
var certUploaded = client.Certificates.CreateOrUpdateCertificate(
serverFarmRG.Value, options.CertificateName,
new Certificate
{
PfxBlob = secret.Value,
Location = app.Location
});
var appSettings = client.Sites.ListSiteAppSettings(options.ResourceGroupName, options.WebAppName);
appSettings.Properties["WEBSITE_LOAD_CERTIFICATES"] = string.Join(",", client.Certificates.GetCertificates(serverFarmRG.Value).Value.Select(k => k.Thumbprint));
appSettings.Properties[$"CN_{options.CertificateName}"] = certUploaded.Thumbprint;
var result = client.Sites.UpdateSiteAppSettings(options.ResourceGroupName, options.WebAppName, appSettings);

Connect to a SharePoint site when IIS requires client certificates

I currently have an application developed in C# that helps me in managing permissions on our Share-point 2013 site. Recently, I learned we may be loosing our local instance and moving to another instance that's behind a cac enforced IIS. I have converted one of my test sites to require certificates and have tried several way to send the cert to the IIS server but I still get
"The remote server returned and error: (403) Forbidden.
Below is a few things I have tried.
var handler = new WebRequestHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
handler.ClientCertificates.Add(pki.GetClientCertificate());
handler.UseProxy = false;
using (var client = new HttpClient(handler))
{
context connection code here
}
the pki.GetClientCertificate is a method, I made that returns a selected certificate in this case my cac cert. Its funny that SharePoint designer connects without issue or prompt. Any help on this matter would be much appreciated.
Just to add some more things I have tried
context.Credentials = new SharePointOnlineCredentials(uli.username, uli.password);
the uli username is the certificate converted to username I have a class that dose the conversion. the password is the pin converted to a secure string. I get the same message even when adding the credentials to the context.
I found a workable but slow solution here:
http://sharepoint.findincity.net/view/635399286724222582121618/ssl-certificate-error-when-using-client-object-model
The only issue with this is every time I call the context I have to send the certificate chain. One thing I changed from this users code is the following.
static void context_ExecutingWebRequest(object sender, WebRequestEventArgs e)
{
IntPtr ptr = IntPtr.Zero;
X509Certificate2 certificate = null;
X509Certificate t = null;
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
// Nothing to do if no cert found.
HttpWebRequest webReq = e.WebRequestExecutor.WebRequest;
//webReq.Proxy = new WebProxy("http://[ProxyAddress]");
//Specify a proxy address if you need to
// X509Certificate cert = pki.GetClientCertificate();
foreach (X509Certificate c in store.Certificates)
{
webReq.ClientCertificates.Add(c);
}
}
I just dumped all my certificates into the request because I didn't want to have a prompt every time I clicked something. So if anyone has a more efficient way to do this let me know.
The code below shows the use of the clientcontext and how it validates your cert
using (context = new ClientContext(siteurl))
{
ServicePointManager.ServerCertificateValidationCallback = delegate(object sender1, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
bool validationResult = true;
return validationResult;
};
context.ExecutingWebRequest += new EventHandler<WebRequestEventArgs>(context_ExecutingWebRequest);
//add all your context commands below this line
}

Azure Management Service API gives deployment configuration in some Encrypted format

I am using this code to get the deployment configurations.
X509Store certificateStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
certificateStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certs = certificateStore.Certificates.Find(
X509FindType.FindByThumbprint, certThumb, false);
if (certs.Count == 0)
{
Console.WriteLine("Couldn't find the certificate with thumbprint:" + certThumb);
return;
}
certificateStore.Close();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(
new Uri("https://management.core.windows.net/" + subID +
"/services/hostedservices/" + hostedServiceName +
"/deploymentslots/" + deploymentType));
request.Method = "GET";
request.ClientCertificates.Add(certs[0]);
request.ContentType = "application/xml";
request.Headers.Add("x-ms-version", "2009-10-01");
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// Parse the web response.
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
// Display the raw response.
Console.WriteLine("Deployment Details:");
string deployment = reader.ReadToEnd();
// Close the resources no longer needed.
responseStream.Close();
}
But I am getting configuration in encrypted format.
But if run azure powershell it gives me the configuration in plain text.
$deployment = Get-AzureDeployment -ServiceName $serviceName -Slot $slot
$deployedConfig = $deployment.Configuration
Since I have to use service management API how can I do it?
This is the expected behavior. REST API returns the data in Base64 encoded format. Since Windows Azure PowerShell consumes the same REST API, they convert the data from Base64 format and present it in humanly readable format. This is what you would also need to do.
So in your code you would do something like this:
string clearText = System.Text.Encoding.UTF8.GetString(
Convert.FromBase64String(reader.ReadToEnd()));

Resources