Disclaimer

Any opinions expressed here are my own and not necessarily those of my employer (I'm self-employed).

Jul 29, 2012

Generating secure Guids

Guids are used extensively throughout Microsoft systems and developers tend to turn to Guid.NewGuid() whenever they need to create a value to uniquely identify something. Guids might also be used as keys or identifiers in security critical operations — under the assumption that they are hard to guess for an attacker. I've been looking around the Internet to see if I could find some guidance on Guid security along with details on how they are generated in the .NET framework. I couldn't find much information, but I did find that Eric Lippert from the C# team recently raised some concerns about the Guids on his blog. So I started digging around to see what more I could find out.

First of all a quick background. Microsoft's Guid is their implementation of the Universally Unique IDentifier (UUID) outlined in RFC 4122. UUIDs are 128 bits, and the Guid class generates version 4 UUIDs, meaning that all bits except those defining the version and variant of the UUID are "random." Please note that 4 bits are used for the version number, and two bits are used for the variant — so it's not a 128 bit random number, it's a 122 bit random number.

I looked into how these Guids are created in the .NET framework. Turns out Guid.NewGuid() simply calls the CoCreateGuid  function on the native ole32.dll, which in turn calls the RPC function UuidCreate. And from its remarks:
The UuidCreate function generates a UUID that cannot be traced to the ethernet address of the computer on which it was generated. It also cannot be associated with other UUIDs created on the same computer. 
Some care has been taken when generating these Guids, but the documentation is far from fullfilling. It's still unclear how easy they are to predict. So, assuming that we cannot trust Guids to be all that "secure", what to do? I've looked around for code that generates a Guid based on the output of a cryptographically strong RNG but couldn't find a good example — so I wrote my own generator that uses the RngCryptoServiceProvider. That way, we know where the bits are coming from. Since it generates proper Guid instances it should be fairly easy to plug it into existing code, e.g. replacing Guid.NewGuid() with SecureGuid.NewGuid(). Also remember to look out for Guids created by constructor: new Guid().

The code

Here's what the code could look like if you wanted to generate a GUID using random bytes from the frameworks's cryptograpically strong RNG. Note the first four bits of the time_hi_and_ver variable is set to version number four, and the first two bits of byte number eight is set according to the variant. Have a look at  RFC 4122  for more details. Apart from that, the code should be straightforward to understand.

using System;
using System.Security.Cryptography;

namespace SecureGuidDemo
{
    class SecureGuid
    {

        public static Guid NewGuid()
        {
            byte[] bytes = { 0x00, 0x00, 0x00, 0x00,
                               0x00, 0x00, 0x00, 0x00,
                               0x00, 0x00, 0x00, 0x00,
                               0x00, 0x00, 0x00, 0x00 };

            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(bytes);
                
            }
            var time = BitConverter.ToUInt32(bytes,0);
            var time_mid = BitConverter.ToUInt16(bytes,4);
            var  time_hi_and_ver = BitConverter.ToUInt16(bytes,6);
            time_hi_and_ver = (ushort)((time_hi_and_ver | 0x4000) & 0x4FFF);
            
            bytes[8] = (byte)((bytes[8] | 0x80) & 0xBF);
            
            return new Guid(time,time_mid,time_hi_and_ver,
                bytes[8],bytes[9],bytes[10],bytes[11],bytes[12],bytes[13],
                bytes[14],bytes[15]);
        }
    }
}

You might look at the code and find it funny that I used the constructor that takes an int, short, short, and byte's. The reason is that I found a bug when creating Guids based on byte arrays. The above code does not trigger the bug, so it should work now and should also work after the bug is fixed (if they decide to do so). I'm in the process of verifying the bug with Microsoft, I'll probably put something up on my blog about it when that's settled.

31 comments:

  1. This is awesome!! really helpful for me. Thanks for sharing with us. Following links also helped me to complete my task.

    http://msdn.microsoft.com/en-IN/library/system.guid(v=vs.71).aspx
    http://www.mindstick.com/Articles/93446478-8ec4-4f1d-b87f-8248e0f7d6ad/?GUID%20in%20NET

    ReplyDelete
  2. how can i use this sample for 32 bit GUID

    ReplyDelete
  3. Replies
    1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru ASP.NET Essential Training Online . Nowadays Dot Net has tons of job opportunities on various vertical industry.
      or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

      Delete
  4. Get all necessary information about WebWatcher app here.

    ReplyDelete
  5. Very informative, keep posting such good articles, it really helps to know about things.

    ReplyDelete
  6. By reading this article I get a lot of lessons and this is very useful . cara menggugurkan kandungan

    ReplyDelete
  7. It's a great site .. Design looks very good .. Continue to work so!

    ReplyDelete
  8. • Assignments are often considered the burden on the mind of students not giving them ample time for any other activities. Lack of time denies students from performing their beloved hobbies, ceasing them from participating in any sports, cultural affairs. Hence, no overall growth for them. Online Assignment help

    ReplyDelete
  9. Get the best essay writing NZ services from the experts of Students Assignment Help and make your academic life easier. Send us your assignment request at info@studentsassignmenthelp.com or WhatsApp at +44-755-536-9184

    ReplyDelete
  10. Avail the best Australian Assignment Help services in Australia by top rated experts at cheapest prices at Myassignmenthelp.com. MyAssignmenthelp most trusted online assignment writing company provides the assignment writing help service for students in Australia of all levels, starting from high school till Ph.D. Our professional academic assignment helper prepares custom written assignment exclusively for you to achieve A+ grade

    ReplyDelete
  11. Students Assignment Help provides the write my essay NZ services to the students of various universities at a low price. Our highly-experienced writers are available 24x7 for guiding the students for any academic help.

    ReplyDelete
  12. Web Ocean Design is the best IT services provider for complete mobile and web application development. The young development company based in Bihar, India, owned and managed by Vicky who have a good amount of experience in Information Technology, Management and other related fields. We provide technical and creative services ranging from Internet Marketing to Communication maneuver. We are also skilled in website development which includes brand promotion, web designing and software development.

    website design company in patna
    website development company in patna
    website development in patna

    web design company in patna
    web development company in patna
    website design in patna

    website design patna
    seo company in patna
    seo company in bihar

    ReplyDelete
  13. Web Ocean Design is the best IT services provider for complete mobile and web application development. The young development company based in Bihar, India, owned and managed by Vicky who have a good amount of experience in Information Technology, Management and other related fields. We provide technical and creative services ranging from Internet Marketing to Communication maneuver. We are also skilled in website development which includes brand promotion, web designing and software development.

    best seo company in patna
    digital marketing company in patna
    best website design company in patna

    affordable seo service in patna
    website optimization in patna
    educational internet marketing company patna

    social media marketing company patna
    real estate seo company in patna
    ecommerce seo company patna

    ReplyDelete
  14. ac Market is a standout among the best outsider application stores which enable Android clients to ac market download broke applications, hacked diversions and numerous mods of recreations and applications for absolutely free of expense. Air conditioning Market is the best option in contrast to the Google Play Store.

    ReplyDelete
  15. Our assignment help experts could address students' academic topics quite well. Thus, they can opt for our service if they have difficulty in writing the academic task.
    assignment help

    ReplyDelete
  16. My Assignment Services is your first and last destination for every query you have related to ‘assignment help’ because we guarantee you the low-cost possible price of Assignment Writers Australia with the unmatched quality of assignments in Australia.

    ReplyDelete
  17. Loss of time denies college students from appearing their loved hobbies, ceasing them from collaborating in any sports, cultural affairs. Control and other associated fields. We offer Best Dissertation Writing Services UK technical and creative offerings ranging from net advertising to conversation maneuver.

    ReplyDelete
  18. Generating secure Guids is entirely a different stuff for me. Nice presentation. Thanks for sharing. Essay Writing Service

    ReplyDelete
  19. 90minup ข่าวกีฬา ฟุตบอล ผลบอล วิเคราะห์บอล พรีเมียร์ลีก ฟุตบอลไทย
    ข่าวกีฬา
    ตารางคะแนน
    ฟุตบอลไทย
    ไฮไลท์ฟุตบอล
    ดูบอลออนไลน์
    ผลบอลสด
    90minup

    ReplyDelete

Copyright notice

© André N. Klingsheim and www.dotnetnoob.com, 2009-2018. Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and/or owner is strictly prohibited. Excerpts and links may be used, provided that full and clear credit is given to André N. Klingsheim and www.dotnetnoob.com with appropriate and specific direction to the original content.

Read other popular posts