Azure Fluent Management v 0.4 Released

If you haven’t tried Fluent Management yet try it now! It’s beginning to shape up into quite a powerful library. There are several features which are on cards for the lib between v0.4 and v0.5 most of which revolve around ServiceSystemWatchers and Upgrades but the deployment side of things is done now. We’re also going to update the Service Bus side of things to create multiple service identities with new queue creation. There are a few updates which need to be done to support rdp, ssl enablements across multiple roles instead of a single one as well as an error router which will deal with common web exceptions through a notification interface but on the whole it can do some pretty good things in a very easy to understand manner. We’ve had 187 downloads so hopefully people are using it even though we haven’t had that much feedback.

A common scenario we’re using it for now are as follows:

  • Upload a package to Blob storage
  • Auto-update the configs (.cscfg, .csdef on the fly using business rules)
  • Deploy the package with 3 roles, rdp support and an autgenerated self-signed SSL/RD certificate in the name of the role
  • Create a SQL Azure instance, logins, firewall rules, single database, new admin user and populate the database
  • Add a storage account and return the keys

Of course the beauty around these scenarios is that this is an all or nothing thing so we’ll have a rollback occur if there is a failure at any point. The logging support is okay at the moment to help determine the failure scenarios but it will be much better by the next v0.5 release.

Hope you enjoy using this. Remember this is beta and it was released to try and get feedback from the community so if you have any comments or suggestions let us know.

UPDATE: Added the framework this morning for watching things. It should be really easy now to drop in a watcher to keep an eye on whether someone deletes your database, database server, storage account, hosted service, deployment in staging or production etc. can lead to some very useful scenarios.

The only one I’ve implemented is the one that Michael Collier from Neudesic requested since I think it may be useful for a number of people but when I get time I’ll add the others because it would be nice to have a simple monitoring and supporting reference service off the back of the lib.

Anyway, the code from my test looks like this (it will poll every 15 seconds by default) – if you haven’t got it Azure Fluent Management from nuget:


var man = new ManualResetEvent(false);

var subscriptionManager = new SubscriptionManager(TestConstants.LwaugSubscriptionId); var manager = subscriptionManager.GetRoleStatusChangedWatcher(TestConstants.LwaugServiceName, TestConstants.LwaugRoleName,                  DeploymentSlot.Staging, TestConstants.LwaugThumbprint);

manager.RoleStatusChangeHandler += (status, oldStatus) =>  {

Assert.AreNotEqual(oldStatus, status);

man.Set();

};

man.WaitOne(10000);

Azure Fluent Management v0.3.9.9: New stuff really!!

One thing that recurs with me is that I always make mistakes with my deployments. Then I have to do them again time and time over. I’ve got used to deleting parts of the deployments which generally because we put together bespoke HPC implementations entail several SQL Azure instances, several storage account instances, ACS and Service Bus Queues. Of course that’s on top tens of cores in use by the deployment over three roles. The tedium of doing these things manually drove me to build in a transaction scope for deployments for Fluent Management. v0.4 will make the coming of age of Fluent Management. We’ve just uploaded v0.3.9.9 – yes we’re running out of numbers! This is now downloadable from nuget and can be used in an application preferably not production until we come out of beta but use it at your own risk.

Speaking of beta. We will be coming out beta by the end of June which should hopefully mark v0.5. This beautiful piece of software will be a lot more resilient and we’ll tying down the interface as much as we can going forward but probably won’t standardise it completely until v1. v0.3.9.9 is missing a transaction scope for deployments but includes it for storage and databases. You can couple as many creates as you want for these two types of service and if there is a failure at any point it will rollback. There are several other things that we’ve included as well such as low level control over config and support for plugins to name a couple. Some of the interfaces have changed and we’ve added some more commands which haven’t yet been wired into the fluent API. v 4 will see two things which ae absolutely mandatory, the first is error routing which will enable certain types of WebException to be handled. Polling asynchronously sometimes generates things like 404′s when resources have been deleted and yet the polls continue indefinitely. The other thing is the completion of the transaction scope for deployments. These two things will be like a coming of age for the library. After that it will be down to streamlining the interface. It’s a little too text oriented so we’ll be adding some Actions<> to help out.

To recap here is how you create a Sql Azure database:


var trans1 = sqlAzureManager.AddNewServer(Constants.LocationWestEurope)

.AddCertificateFromStore(TestConstants.ManagementThumbprint)

.AddNewFirewallRule("myofficeip", "10.27.27.253", "10.27.27.254")

.AddNewFirewallRule("anotherip", "10.27.28.11", "10.27.28.254")

.AddNewFirewallRuleForWindowsAzureHostedService()

.AddNewFirewallRuleWithMyIp("myhomeip")

.WithSqlAzureCredentials("ukwaug", "<a href="mailto:M@cc0mputer">M@cc0mputer</a>")

.AddNewDatabase("test")

.AddNewDatabaseAdminUser("ukwaugdb", "<a href="mailto:M@cc0mputer">M@cc0mputer</a>")

.ExecuteScripts(@"C:\Projects\Tech Projects\Elastacloud")

.Go();

And a storage account:


var storage1 = storageManager1.CreateNew("elastadfg1")

.AddCertificateFromStore(TestConstants.ManagementThumbprint)

.WithDescription("my new storage")

.WithLocation(Constants.LocationWestEurope)

.Go();

To couple these together in a transaction we create a ServiceOrchestrator like so:


var orchestrator = new ServiceOrchestrator();

orchestrator.AddDeploymentStep(trans1);

orchestrator.AddDeploymentStep(storage1);

var success = orchestrator.Commit();

Take a simple scenario here where we create our database server and database and boom! Our account limit for storage is breached. In this instance we want to rollback our database because half an application is not that much better than no application.

Anyway, happy trails and all that.

Some updates to fluent management

Hi!

It’s been a while since I’ve done any posts on fluent management. This is taking place in the background and I’m using one of our projects to drive the development of this. I’ve back in a lot of changes and I realise now that if I’m going to get people to use this then I need to set up a wiki!

Recently I had a pingback from Michael Collier from Neudesic who looked at the library and saw that there was nothing in it to pick up state changes in roles. This is the kind of feedback I’d like. I have backed in a notification interface now and have a wrapper called ServiceSystemWatcher which will ping on the state change. As the lib gets more complicated now I’m forced to use config and defaults for many of the properties.

There have been a whole heap of changes which allow config to be injected in prior to deployment and that wrap up .cscfg files so have a nice way to add and remove settings. This proved mandatory for us on the current project we’re undertaking which needs the use config-driven settings for plugins we’re writing at runtime.

One of the key aspects which will be added in the next release is the idea of workflow. I want to be able to add a storage account, do something with it, add a database, add a hosted service, create a service bus namespace and queue etc. in a single transaction and rollback if this fails at any point. I’ve added some context interfaces to the lib which should enable this fairly easily now.  

Someone recently asked whether the lib was published under an open source license. Yes, it is under a GNU lesser license. Currently it’s in beta so we won’t take repsonsibility for it if you use it in production and it fails. We’re going to offer a manadatory support contract going forward if you turnover more than $5m/year. This is mainly because a lot of consultancies that we’ve worked with don’t put anything back in the ecosystem and we don’t want them to profit from our labour and maintenance if they’re not helping the community. This has been our general experience with the user group – not a lot of support from the “partner” “community” – two terms I use very loosely.

Happy trails and an update soon containing new stuff!

startups and Windows Azure

This month we ran a user group session on startups and windows azure. It was new thing for us. Ordinarily we’re chained to technology and developers seem to be most comfortable listening to this. I’ve been told that there is a entrepreneur in all of us but techies more than most seem to be affected by this characteristic. The reason for this is very simple – we have lots of ideas. We work in business areas where we can immediately see the value of a solution for cost-saving, optimisation, greater productivity etc. or simply as a pure enabler of something that hasn’t been possible to date.

I’ve had more startups than most. I seem to be most comfortable outside of the enterprise workplace. In 2001 I had my first taste of a startup after 6 years of contracting around the City. On Board Info Limited took me into the depths of “Hailstorm” or .NET My Services and we were firmly involved with Microsoft. I spoke at the PDC and decided and the autonomy I had was something I wanted to maintain. Unfortunately this all ended for the company prematurely and I went back to contracting for another 5 years. In 2006 I left the City again and decided I would setup up TemporalS with colleagues. It was my first struggle as a startup. We did pretty well but this ended prematurely as well. I set up Clarendon and got several clients and bits of pieces of consultancy under my belt and from 2009 built ShipTracker with my friend Phil in Omnecon, what followed was a myriad of startup ideas each great in their own right but all ahead of their time. Timing is everything with a startup when you don’t have the staying power of a big company.

Elastacloud is my latest venture with Andy Cross. We haven’t talked much about it because virtually everything is a trade secret now. Andy and I have spent a year becoming experts in HPC on Azure and by extension Hadoop. And by experts I don’t mean the single project that most big consultants do (mainly badly in my experience!) but we have spent months and months understanding every line of code through decompilation of our peers products and testing to know exactly how to build our solution. This is what you need to be successful – a complete understanding of what your technology is and does.

In our foray through this jungle we built Fluent Diagnostics and Fluent Management for the community. Both have recent releases which could be very valuable to other developers. The open source libraries themselves are not important but the low level knowledge you have to accumulate to get something to work properly is. This is why we’re happy these to stand in front of crowd and proclaim that we’re experts in azure management, deployment, diagnostics, HPC and Hadoop – because we are – because we took time away from earning and invested in these skills.

I meet a lot of people in this business that think they’re going to be the next Bill Gates with the next biggest idea from experience with their respective line of businesses. I don’t give people who talk without taking the plunge (and leaving their job and getting on with it) any time anymore because they are just talkers. Ideas mean nothing. I’ve found that the only thing that matters is getting on with it, taking the risk and taking each day as it comes. This approach is not for everybody and most people in life turn out to be not cut from this cloth which precludes them from doing nothing other than deluding themselves they’ll be the next biggest thing if they’re not content with their lot. People that build startups will eventually succeed in something because that’s their makeup they just get on with it and don’t waste time on talking.

It’s for this reason that I felt this user group meeting was a resounding success. Our first speaker Bindi Karia has a deep insight into what makes a startup tick. You can tell with Bindi when she speaks that her attachment to Bizspark and helping startups is more than just a job. She’s made links into the industry with VC’s and incubators that she’s fed back into the Bizspark program to nurse Bizspark startups into achieving sales and necessary expansion capital. It really showed me that Bizspark was not just a fire and forget registration process with some free software but a genuinely great program to foster a rich ecosystem of new companies. From everything Bindi was saying we have some great times ahead of us in the UK which looks to be a formidable software hub.

Mark Bower, CTO of CubeSocial, is a prime example of exactly what I wrote about above. Everybody in the audience really delved into Mark’s knowledge to see where the spark comes from in the aptly named Bizspark. I think the one thing that I understood very clearly from Mark is that there was not an area of the business and decision-making process over the last 18 months that he couldn’t recite verbatim. No question either technical or on the business was an effort for him because he has lived the evolution of CubeSocial and has been tied to every decision. A great speaker and startup. I look forward to inviting Mark back to the group in a couple of years when the offers start rolling in on their company and he can give us a true end-to-end perspective on the path to success!

Thanks to both of our speakers for the inspiration they gave to a bunch of geeks.

Update: Automating the generation of service certificates

I missed a key part out of a post I did week ago on automating the generation of service certificates. In order to do this using Bouncy Castle you have to create #Pkcs12 store which is a security wrapper around the private key. It’s worth pointing out that a certificate doesn’t contain a private key. It’s just linked to a private key through a higher level structure. This structure can be a pfx or pkcs#12. The terms can be mutually exclusive for our usage. Anyway, I couldn’t see this code anywhere online so I thought I’d post it to save anyone the trouble of doing this on their own.

// build the key parameter and the certificate entry
var keyEntry = new AsymmetricKeyEntry(privateKey);
var entry = new X509CertificateEntry(certificate);
// build the PKCS#12 store to encapsulate the certificate
var builder = new Pkcs12StoreBuilder();
builder.SetUseDerEncoding(true);
builder.SetCertAlgorithm(PkcsObjectIdentifiers.Sha1WithRsaEncryption);
builder.SetKeyAlgorithm(PkcsObjectIdentifiers.Sha1WithRsaEncryption);
builder.Build();
// create a memorystream to hold the output 
var stream = new MemoryStream(2000);
// create the individual store and set two entries for cert and key
var store = new Pkcs12Store();
store.SetCertificateEntry("Elastacloud Test Certificate", entry);
store.SetKeyEntry("Elastacloud Test Certificate", keyEntry, new[] { entry });
store.Save(stream, userPassword.ToCharArray(), new SecureRandom());

Anyway, once you have this you can use the MemoryStream in .NET with an X509Certificate2.

Hope this helps if anyone was struggling with my former post.

Service Bus, ACS and multiple service identities

As windows Azure becomes more prolific and people begin to use key features we’ve had several users of the service bus come to us at the user group showing us reasonably good implementations. They all have one key design flaw on production release which I wanted to write about here.

Good security for a website entails that you don’t send messages back to the client when they get their password wrong that tell that it was their password that was at fault. Whilst the lack of pintpoint feedback like this is not ideal one of the key considerations is not to give an attacker more information then they need to crack an account. Without precise feedback any random attack bot (is there such a term or is my star wars head just inventing stuff this morning?!) can learn details on credentials.

 

Service Bus management details
Service Bus management details

 

One of the problem with the Service Bus is that many people begin to use it without understanding how ACS is used to protect access to it. They key idea here is that ACS is like a lockbox. As part of the setup process it creates a single “identity” which contains the information needed for any client to participate in the service bus and send and receive messages. So this identity then becomes your most important asset.

The problem here is that most users still don’t effectively understand the coupling mechanism between the service bus and ACS so they keep the default identity with the name “owner”. So now we’re left with breaking our pattern of good security because 50% of the information we need to know is known to an attacker – it would still be pretty hard to guess the default 256-bit symettric key though!

Showing the default and owner and key

Showing the default and owner and key

 

As such you may want to predicate access on groups or corporations or something that would beget a good access policy and create at least one new or multiple identities so that at least you could track usage effectively as well as revoke access to a particular messaging client.

In order to do this you need to follow the link to the Management Endpoint in your browser which takes you straight to the ACS for the Service Bus. Then select Service Identities. You can add another identity very easily and choose either symettric key, password or certificate-based authentication.

 

Select Service Identities from the Menu

Select Service Identities from the Menu

Creating and editing a service identity

Creating and editing a service identity

 

I’ve now removed the owner, which is the default identity and set up a new identity which can be used with clients. Of course it’s possible to automate this process through the management REST layer. Maybe this is something we can look at doing in the fluent management API.

 

Managing Multiple Identities

Managing Multiple Identities

 

Anyway, should you now try and use these credentials you’ll get an UnauthorizedAccessException! The Service Bus uses a particular action to generate output claims for access to specific things you can do with the bus. These claims are Send, Listen and Manage. By default, the “owner”, has all 3 enabled. The first two are fine but the third could cause major disruption to your project which is all the more reason to change your management access – or disable programmatic access if you choose to and use the portal instead.

 

Bye-bye owner!

Bye-bye owner!

UnauthorizedAccessException

UnauthorizedAccessException

 

Send and Listen output claims should be sufficient for pretty much everything as long as you don’t ask the Service Bus to divulge any information (e.g. if you use QueueExists to check the validity of a queue or try and get metainformation about anything on the service bus then it will fail if you don’t have the Manage output claim).

Here is a screenshot showing the claims:

 

Editing and completing input -> output claims

Editing and completing input -> output claims

 

To add standard rule you would use the following format:

  • Input Claim Issuer: Access Control Service
  • Input Claim Type: (Select Type) namesidentifier
  • Input Claim Value: <your new identity name>
  • Output Claim Type: net.windows.servicebus.action
  • Output Claim Value: Send/Listen/Manage

Once you’ve created 1-3 rules depending on the rights of the identity, if you’ve created a new rule group and not added rules to the existing one then you’ll need to add this to the Relying Party Application as in the screenshot.

 

Adding a second rule group to a relying party application

Adding a second rule group to a relying party application

 

So the moral of the story here is that ACS offers a rich model of managing identities and claims. Use this and ensure that you adhere to good application design principles, get rid of default users and don’t send these credentials to clients. Ensure that each user of the service bus subscribes to the principle of least privilege so unless they need management access don’t give it to them. It means writing your applications in a certain way to ensure that no management checks are done prior to sending and/or receiving messages but better safe than sorry!

And v0.3.7 Fluent Management was born!

Okay, so I know the naming convention is pretty pants but I wanted to make another release. Version 0.4 will include a hosted service delete feature, automatic checks of hosted lists and blob container existance checks, propogation of exceptions from WebExceptions (which are currently suppressed) and enablement of Remote Desktop.

The roadmap for v 0.5 is about a month away but will include an orchestration engine and addition of plugins and new config settings. Remember, this library is still in beta so don’t use this in a production release until we say so!

Firstly we’ll review the new read infosets. This will get the current subscription information:

 var subscriptionManager = new SubscriptionManager(TestConstants.SubscriptionId);
 var subscriptionInformation = subscriptionManager.GetSubscriptionDetailsManager()
                .AddCertificateFromStore(TestConstants.ManagementThumbprint)
                .GetSubscriptionInformation();

This will return the locations available under your subscription. Useful if your subscription is free and is pinned to a particular territory.

 var subscriptionInformation = subscriptionManager.GetSubscriptionDetailsManager()
                .AddCertificateFromStore(TestConstants.ManagementThumbprint)
                .GetSubscriberLocations();

To get a list of hosted services you can use the following:

 var hostedService = subscriptionManager.GetDeploymentManager()
                .ForServiceInformationQuery()
                .UseExistingBuild()
                .AddCertificateFromStore(TestConstants.ManagementThumbprint)
                .GetHostedServiceList();

However, by far the most useful feature is the automatic addition of SSL to package and config. I’m a little tired now but this was not an easy thing to do and required several steps some of which I’ll share over the next few months.

var subscriptionManager = new SubscriptionManager(TestConstants.SubscriptionId);

            var deploymentManager = subscriptionManager.GetDeploymentManager();
            ((DeploymentManager)deploymentManager).AzureTaskComplete += TestConstants.TaskComplete;

            deploymentManager.ForNewDeployment(TestConstants.DeploymentName)
                .SetBuildDirectoryRoot(TestConstants.ProjectBuildRoot)
                .Rebuild()
                .EnableSslForRole(TestConstants.RoleNameHellocloudWeb)
                .UploadExistingServiceCertificate(TestConstants.ManagementThumbprint, "xxxxxxx")
                .AddCertificateFromStore(TestConstants.ManagementThumbprint)
                .WithNewHostedService(TestConstants.HostedServiceName)
                .WithStorageConnectionStringName(TestConstants.ConnectionStringName)
                .AddDescription("My new hosted services")
                .AddEnvironment(DeploymentSlot.Production)
                .AddLocation(Constants.LocationNorthEurope)
                .AddParams(DeploymentParams.StartImmediately)
                .ForRole(TestConstants.RoleNameHellocloudWeb)
                .WithInstanceCount(2)
                .Go();

The above example would create a hosted service and deployment and add SSL to it. It would allow the uploading of a Service Certificate. In many ways, however, when testing the certificate might not be available so you can replace the UploadExistingServiceCertificate with this:

.GenerateAndAddServiceCertificate("helloelastacloud.cloudapp.net")
 

And this will generate the appropriate certificate. In order to actually do this the library needs to rebuild the package from source with new build definitions and cloud config. A lot of refactoring has gone on with the lib so I hope you enjoy the updates. It’s getting that time of night now where I’m sort of slumped over the keyboard and mistyping every third letter. Leave it another 10 minutes and my keyboard will be full of drool so just to say I’m happy that this is a semi-stable release and I’ll upload the new package to nuget tomorrow morning.

Lastly, there is some licensing information in the library which explains the terms of use. Contact us if there are any problems but it’s fairly open, commercial reditribution usage should get in touch as per the terms etc. etc.

Automating the generation of service certificates in Windows Azure

I was prompted to write this having seen some of the implementations of the generation of service certificates online. Some poor explanations so I though I’d plug the gap. First let us cover some definitions. We interact with our subscription through a management certificate.

The management certificate needs to be uploaded to the subscription through the portal. This is the only function that we can’t automate. Obvious why, everybody has probably seen the chicken and the egg here already. Anyway, Microsoft have provided a .publishsettings file and Uri which eases the pain of automating this process because the fabric will instamagically update your subscription when you use your live id to login and download a publishsettings file. Y voila you have management access.

A service certificate is something different though. Service certificates are bound to an individual hosted service and don’t entail management of anything. They actually allow you to perform any operation which involves a certificate for that particular hosted service. Under the seams that certificate is being added to the Personal store on each of the role instances within that service.

Service certificates are immensely important for two essential functions:  SSL and Remote Desktop.

Management Portal Showing Service Certificates

Management Portal Showing Service Certificates

SSL is intrinsic to the role instance since it is part of IIS which is present on each of the web roles. Remote Desktop requires a plugin but equally uses the service certificate for authentication purposes.

I wanted to highlight one great way of generating service certificates. There are several ways to do this but we’ll focus on a single one although we can use makecert, powershell and Microsoft provide a test app called CertificateGenerator (essentially a COM Callable Wrapper) amongst others. This way uses Bouncy Castle, a great library which is available through nuget. Simply:

Bouncy Castle from Nuget

Bouncy Castle from Nuget

> Install-Package BouncyCastle

at the Package Manager Console prompt and it is installed.

Let’s start by determining all of our using statements:

using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Prng;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;

And then our method signature:

public static X509Certificate2 Create(string name, DateTime start, DateTime end, string userPassword, bool addtoStore = false)

In order to create our certificate as a minimum we need a name, a validity period and as we are protecting a private key we need a private key password (more on this later!). Additionally we may want to add this to a local certificate store which the System.Cryptography assembly allows us to do fairly easily.

We always start any asymmetric cryptographic operation with the a private-public key pair. To generate keys we can use the following:

// generate a key pair using RSA
var generator = new RsaKeyPairGenerator();
// keys have to be a minimum of 2048 bits for Azure
generator.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 2048));
var cerKp = generator.GenerateKeyPair();

Two properties that an X509v3 certificate has are a serial number and a subject name (and issuer name). The representation of what this looks like is canonical so we use terms such as “Common Name” (CN) or “Organisational Unit” (OU) to define details about the party the certificate represents and who the authority is that is vouching for them.

To create a subject name we use the X509Name as below and to generate a serial number which is a unique reference to our certificate we generate a large random prime:

// create the CN using the name passed in and create a unique serial number for the cert
var certName = new X509Name("CN=" + name);
var serialNo = BigInteger.ProbablePrime(120, new Random());

After doing this we can create an X509v3CertificateGenerator object which will encapsulate and create the certificate for us:

// start the generator and set CN/DN and serial number and valid period
var x509Generator = new X509V3CertificateGenerator();
x509Generator.SetSerialNumber(serialNo);
x509Generator.SetSubjectDN(certName);
x509Generator.SetIssuerDN(certName);
x509Generator.SetNotBefore(start);
x509Generator.SetNotAfter(end);

Once we’ve set the basic and essential properties we can focus on what the cert actually does:

// add the server authentication key usage
var keyUsage = new KeyUsage(KeyUsage.KeyEncipherment);
x509Generator.AddExtension(X509Extensions.KeyUsage, false, keyUsage.ToAsn1Object());
var extendedKeyUsage = new ExtendedKeyUsage(new[] {KeyPurposeID.IdKPServerAuth});
x509Generator.AddExtension(X509Extensions.ExtendedKeyUsage, true, extendedKeyUsage.ToAsn1Object());

Two types of property that the certificate has are Key Usage and Extended Key Usage which tell us all about its purpose to life. It’s rasion D’etre (it’s getting that time of night where I think I can actually speak French!)

In this case the certificate we create will need to be able to do two things.

  1. Prove to a client that it has authority to verify the server and
  2. Encrypt a key during a key exchange process
X509 Certificate with KU/EKU properties

X509 Certificate with KU/EKU properties

Both of these are common to SSL (TLS).

The rest is fairly straightforward. We can set a signature algorithm. Note the use of Sha1 which by extension is the thumbprint algorithm in our certificate which is an integrity check to prove that the cert hasn’t been tampered with. It’s important to be aware that Azure will only support this thumbprint algorithm.

// algorithm can only be SHA1 ??
x509Generator.SetSignatureAlgorithm("sha1WithRSA");
// Set the key pair
x509Generator.SetPublicKey(cerKp.Public);
Org.BouncyCastle.X509.X509Certificate certificate = x509Generator.Generate(cerKp.Private);

When this is done we will want to do common tasks with this and generally end up with our familiar X509Certificate2 exposed by the System.Cryptography.X509Certificates namespace and used in all common crypto tasks. Well the means to do this are fairly easy and provided by Bouncy Castle.

// export the certificate bytes
byte[] certStream = DotNetUtilities.ToX509Certificate(certificate).Export(X509ContentType.Pkcs12, userPassword);

Also not the use of PKCS#12 (Public Key Cryptographic Standard) which defines the private and uses a form of password-based encryption (PBE) to ensure that only with the password can I access the private key. As we can just use our password and now treat the X509Certificate2 class as a container for our cert with private key.

var cert = new X509Certificate2(certStream, userPassword);

Adding the certificate to the store is fairly easy. You would first start by opening the store you want to engage:

///
<summary> /// Returns the My LocalMachine store
/// </summary>
private static X509Store ReturnStore()
{
  var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
  store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);
  return store;
}

After that all it takes is a bit addition using your X509Certificate2 object and then closing the store to release the handle.

One thing to note is that this certificate is self-signed. This doesn’t have to be the case; I could easily build a PKI here using this simple technique. Of course the code would like slightly differently (maybe we’ll cover this in a follow-up post) as would the issuer name.

I thought I’d write this post to offer readers another way to generate certificates. Six years ago when I was involved as the CTO in a startup that produced epassport software I would get immersed into the underlying details of these standards. Most of the time we would use OpenSSL which is an absolute gem of a library but Bouncy Castle comes a pretty close second in terms of functionality and upkeep. Have a play and enjoy!

The next generation of the Azure Fluent Management library uses the above code in order to automate the setup of SSL for a webrole and remote desktop. There has been a lot of refactoring on this recently to help us streamline deployments and we hope to release this in the coming week.

Happy trails!

Agile, Continuous Integration and Windows Azure

Recently our friends at Blush Packages raised the bar with a great implementation of TeamCity build for an Azure project they’re consulting on. We will be running an intermediate day course on Azure for the Enterprise which will comprise of how to make an enterprise ready application. The course will be delivered at the behest of Microsoft who are sponsors. It will probably take place within the next four weeks and we will have the following agenda:

  • Introduction to TFS Preview: Using TFS Preview to build an agile project in Azure
  • Development of a sample application using web/worker roles
  • Adding security using SQL Azure and Membership
  • Integration of Diagnostics capture for trace, exceptions and logs
  • Resilience and autoscaling with Enterprise Application Blocks
  • Automating common deployment tasks with Cerebrata Powershell CmdLets
  • Using mstest, msbuild and TFS to make a CI server

Remember this is not an advanced course; it’s simply addressing the problem of how to build and deploy a windows azure application and use enterprise methodologies and deployment and build processes to deliver cloud ready projects in the same way as you would traditional server projects.

Feel free to leave a comment here if you’re interested in attending. For updates on this follow @ukwaug or @azurecoder

Refactoring slowly

Okay so I’m finally getting around to refactoring the mess that is my library. Today I had to build some parsers for response xml and have explicitly decided from the start to use linq to xml as opposed to serialisation. Anyway, will probably do another package upload to nuget in about a week or so. No breaking interface changes and there probably won’t be from now on.

Anyway there are a couple of things on my list for the next month.

  1. Add support for adding name-value pairs for plugins for the .cscfg file
  2. Add support for msbuild so that the .csdef file can be modified to support multiple sites, update vmsizes and add certificates and other details only available at creation time
  3. Add support for a few more types of query such as deployments or sql azure servers or db instances

The fluent api will be tightened as well since the paths needs to be directed. The DeploymentManager code is getting a little unruly so I’ll refactor this and work out a flat class structure so that I can tidy up this code.  Anyway, regression testing everything so shouldn’t have any problems going forward.

var subscriptionManager = new SubscriptionManager("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");

var hostedService = subscriptionManager.GetDeploymentManager()
  .AddCertificateFromStore("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
  .GetHostedServiceList();

This call returns a HostedService generic List.

Follow

Get every new post delivered to your Inbox.

Join 141 other followers