Ejemplo n.º 1
0
        public void Decode(string sasIdentifier)
        {
            ASCIIEncoding   aSCIIEncoding   = new ASCIIEncoding();
            UnicodeEncoding unicodeEncoding = new UnicodeEncoding();

            SASUtilities.ValidateACIIEncoding(sasIdentifier);
            NameValueCollection nameValueCollection = new NameValueCollection();

            MetadataEncoding.Decode(aSCIIEncoding.GetBytes(sasIdentifier), nameValueCollection);
            string item  = nameValueCollection[SASIdentifier.IdName];
            string str   = nameValueCollection[SASAccessPolicy.SignedStartName];
            string item1 = nameValueCollection[SASAccessPolicy.SignedExpiryName];
            string str1  = nameValueCollection[SASAccessPolicy.SignedPermissionName];

            if (!string.IsNullOrEmpty(item))
            {
                this.Id = unicodeEncoding.GetString(Convert.FromBase64String(item));
            }
            if (!string.IsNullOrEmpty(str))
            {
                this.AccessPolicy.SignedStart = new DateTime?(SASUtilities.ParseTime(str));
            }
            if (!string.IsNullOrEmpty(item1))
            {
                this.AccessPolicy.SignedExpiry = new DateTime?(SASUtilities.ParseTime(item1));
            }
            if (!string.IsNullOrEmpty(str1))
            {
                this.AccessPolicy.SignedPermission = new SASPermission?(SASUtilities.ParseSASPermission(str1));
            }
        }
Ejemplo n.º 2
0
        public byte[] Encode()
        {
            ASCIIEncoding       aSCIIEncoding       = new ASCIIEncoding();
            UnicodeEncoding     unicodeEncoding     = new UnicodeEncoding();
            NameValueCollection nameValueCollection = new NameValueCollection();

            nameValueCollection[SASIdentifier.IdName] = Convert.ToBase64String(unicodeEncoding.GetBytes(this.Id));
            if (this.AccessPolicy.SignedStart.HasValue)
            {
                string   signedStartName = SASAccessPolicy.SignedStartName;
                DateTime?signedStart     = this.AccessPolicy.SignedStart;
                nameValueCollection[signedStartName] = SASUtilities.EncodeTime(signedStart.Value);
            }
            if (this.AccessPolicy.SignedExpiry.HasValue)
            {
                string   signedExpiryName = SASAccessPolicy.SignedExpiryName;
                DateTime?signedExpiry     = this.AccessPolicy.SignedExpiry;
                nameValueCollection[signedExpiryName] = SASUtilities.EncodeTime(signedExpiry.Value);
            }
            if (this.AccessPolicy.SignedPermission.HasValue)
            {
                string        signedPermissionName = SASAccessPolicy.SignedPermissionName;
                SASPermission?signedPermission     = this.AccessPolicy.SignedPermission;
                nameValueCollection[signedPermissionName] = SASUtilities.EncodeSASPermission(signedPermission.Value);
            }
            return(MetadataEncoding.Encode(nameValueCollection));
        }
Ejemplo n.º 3
0
        public static AuthDataEntry SignedKeyAuthenticate(string stringToSign, string requestSignature, AuthenticationInformation authInfo)
        {
            AuthDataEntry authDataEntry;

            NephosAssertionException.Assert(!string.IsNullOrEmpty(stringToSign));
            NephosAssertionException.Assert(!string.IsNullOrEmpty(requestSignature));
            NephosAssertionException.Assert(authInfo != null);
            RequestContext      requestContext  = authInfo.RequestContext;
            NephosUriComponents uriComponents   = authInfo.UriComponents;
            NameValueCollection queryParameters = requestContext.QueryParameters;
            string item = queryParameters["sv"];

            byte[] sign = BlobSignedAccessHelper.ComputeUrlDecodedUtf8EncodedStringToSign(queryParameters, uriComponents);
            using (IEnumerator <AuthDataEntry> enumerator = SharedKeyAuthInfoHelper.GetSharedKeys(authInfo).GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    AuthDataEntry current  = enumerator.Current;
                    byte[]        numArray = SASUtilities.ComputeSignedKey(sign, current.AuthValue);
                    if (!SASUtilities.ComputeSignatureAndCompare((new UTF8Encoding()).GetBytes(stringToSign), numArray, requestSignature))
                    {
                        continue;
                    }
                    authDataEntry = current;
                    return(authDataEntry);
                }
                CultureInfo invariantCulture = CultureInfo.InvariantCulture;
                object[]    objArray         = new object[] { requestSignature, stringToSign };
                throw new AuthenticationFailureException(string.Format(invariantCulture, "The MAC signature found in the HTTP request '{0}' is not the same as any computed signature. Server used following string to sign: '{1}'.", objArray));
            }
            return(authDataEntry);
        }
Ejemplo n.º 4
0
        public static List <SASIdentifier> DecodeSASIdentifiers(string sasIdentifiersValue)
        {
            ASCIIEncoding aSCIIEncoding = new ASCIIEncoding();

            if (sasIdentifiersValue == null)
            {
                throw new ArgumentNullException("sasIdentifiersValue");
            }
            SASUtilities.ValidateACIIEncoding(sasIdentifiersValue);
            sasIdentifiersValue = aSCIIEncoding.GetString(Convert.FromBase64String(sasIdentifiersValue));
            List <SASIdentifier> sASIdentifiers = new List <SASIdentifier>();

            using (StringReader stringReader = new StringReader(sasIdentifiersValue))
            {
                string str = null;
                while (true)
                {
                    string str1 = stringReader.ReadLine();
                    str = str1;
                    if (str1 == null)
                    {
                        break;
                    }
                    str = str.Trim();
                    if (str.Length != 0)
                    {
                        string        str2          = aSCIIEncoding.GetString(Convert.FromBase64String(str));
                        SASIdentifier sASIdentifier = new SASIdentifier();
                        sASIdentifier.Decode(str2);
                        sASIdentifiers.Add(sASIdentifier);
                    }
                }
            }
            return(sASIdentifiers);
        }
Ejemplo n.º 5
0
        public virtual void ParseAccessPolicyFields(bool isDoubleSigned)
        {
            string item = this.QueryParams["st"];

            this.ValidateOptionalField(item, "st");
            if (item != null)
            {
                this.SignedStart = new DateTime?(SASUtilities.ParseTime(item));
            }
            string str = this.QueryParams["se"];

            if (!this.IsRevocableAccess)
            {
                this.ValidateMandatoryField(str, "se");
                this.SignedExpiry = new DateTime?(SASUtilities.ParseTime(str));
            }
            else
            {
                this.ValidateOptionalField(str, "se");
                if (str != null)
                {
                    this.SignedExpiry = new DateTime?(SASUtilities.ParseTime(str));
                }
            }
            if (!VersioningHelper.IsPreApril15OrInvalidVersion(this.SignedVersion))
            {
                string item1 = this.QueryParams["sip"];
                this.ValidateOptionalField(item1, "sip");
                if (item1 != null)
                {
                    try
                    {
                        this.SignedIP = SASUtilities.ParseSip(item1);
                    }
                    catch (ArgumentOutOfRangeException argumentOutOfRangeException)
                    {
                        throw new FormatException("Invalid sip format", argumentOutOfRangeException);
                    }
                }
                string str1 = this.QueryParams["spr"];
                this.ValidateOptionalField(str1, "spr");
                if (str1 != null)
                {
                    this.SignedProtocol = SASUtilities.ParseSignedProtocol(str1);
                }
            }
            string item2 = this.QueryParams["sep"];

            this.ValidateOptionalField(item2, "sep");
            if (item2 != null)
            {
                this.SignedExtraPermission = SASUtilities.ParseExtraPermission(item2);
            }
        }
Ejemplo n.º 6
0
 public override void ParseAccessPolicyFields(bool isDoubleSigned)
 {
     try
     {
         if (isDoubleSigned)
         {
             string str = base.ExtractSignedAuthorization(base.RequestContext);
             base.ValidateMandatoryField(str, "SignedKey");
             base.ValidateSignedAuthorizationFormat(str);
         }
         else
         {
             string item = base.QueryParams["sig"];
             base.ValidateMandatoryField(item, "sig");
             base.ValidateSignatureFormat(item);
             base.Signature = item;
         }
         string item1 = base.QueryParams["si"];
         base.ValidateOptionalField(item1, "si");
         base.SignedIdentifier = item1;
         string str1 = base.QueryParams["sv"];
         base.ValidateMandatoryField(str1, "sv");
         this.ValidateSASVersion(str1);
         base.ParseAccessPolicyFields(isDoubleSigned);
         string item2 = base.QueryParams["sp"];
         if (!base.IsRevocableAccess)
         {
             base.ValidateMandatoryField(item2, "sp");
             SASUtilities.ValidatePermissionOrdering(item2, SASPermission.Queue);
             base.SignedPermission = new SASPermission?(SASUtilities.ParseSASPermission(item2));
         }
         else
         {
             base.ValidateOptionalField(item2, "sp");
             if (item2 != null)
             {
                 SASUtilities.ValidatePermissionOrdering(item2, SASPermission.Queue);
                 base.SignedPermission = new SASPermission?(SASUtilities.ParseSASPermission(item2));
             }
         }
         string str2 = AuthenticationManagerHelper.ExtractKeyNameFromParamsWithConversion(base.QueryParams);
         base.ValidateOptionalField(str2, "sk");
         if (str2 != null)
         {
             base.KeyName = str2.Trim();
             Logger <IRestProtocolHeadLogger> .Instance.Verbose.Log("Using secret key with KeyName '{0}' to authenticate SAS request.", new object[] { base.KeyName });
         }
     }
     catch (FormatException formatException)
     {
         throw new AuthenticationFailureException("Signature fields not well formed.", formatException);
     }
 }
Ejemplo n.º 7
0
 public SASAccessPolicy(string signedStart, string signedExpiry, string signedPermission)
 {
     if (!string.IsNullOrEmpty(signedStart))
     {
         this.SignedStart = new DateTime?(SASUtilities.ParseTime(signedStart));
     }
     if (!string.IsNullOrEmpty(signedExpiry))
     {
         this.SignedExpiry = new DateTime?(SASUtilities.ParseTime(signedExpiry));
     }
     if (!string.IsNullOrEmpty(signedPermission))
     {
         this.SignedPermission = new SASPermission?(SASUtilities.ParseSASPermission(signedPermission));
     }
 }
Ejemplo n.º 8
0
        public static SASExtraPermission?ParseExtraPermission(string extraPermission)
        {
            SASExtraPermission?nullable = null;

            if (string.IsNullOrEmpty(extraPermission))
            {
                return(nullable);
            }
            for (int i = 0; i < extraPermission.Length; i++)
            {
                if (extraPermission[i] != 'b')
                {
                    throw new FormatException(string.Concat("Unexpected character ", extraPermission[i], " in extra permission"));
                }
                nullable = SASUtilities.ValidateAndAddExtraPermission(nullable, SASExtraPermission.BypassAccountNetworkAcls, i);
            }
            return(nullable);
        }
Ejemplo n.º 9
0
 public override void ParseAccessPolicyFields(bool isDoubleSigned)
 {
     try
     {
         if (isDoubleSigned)
         {
             string str = base.ExtractSignedAuthorization(base.RequestContext);
             base.ValidateMandatoryField(str, "SignedKey");
             base.ValidateSignedAuthorizationFormat(str);
         }
         else
         {
             string item = base.QueryParams["sig"];
             base.ValidateMandatoryField(item, "sig");
             base.ValidateSignatureFormat(item);
             base.Signature = item;
         }
         string item1 = base.QueryParams["si"];
         base.ValidateOptionalField(item1, "si");
         base.SignedIdentifier = item1;
         string str1 = base.QueryParams["tn"];
         base.ValidateMandatoryField(str1, "tn");
         this.TableName = str1.ToLower();
         string item2 = base.QueryParams["spk"];
         this.StartingPartitionKey = item2;
         string str2 = base.QueryParams["srk"];
         if (item2 == null && str2 != null)
         {
             throw new AuthenticationFailureException(string.Format("{0} is required when {1} is provided.", "srk", "spk"));
         }
         this.StartingRowKey = str2;
         string item3 = base.QueryParams["epk"];
         this.EndingPartitionKey = item3;
         string str3 = base.QueryParams["erk"];
         if (item3 == null && str3 != null)
         {
             throw new AuthenticationFailureException(string.Format("{0} is required when {1} is provided.", "erk", "epk"));
         }
         this.EndingRowKey = str3;
         string item4 = base.QueryParams["sv"];
         base.ValidateMandatoryField(item4, "sv");
         this.ValidateSASVersion(item4);
         base.ParseAccessPolicyFields(isDoubleSigned);
         string str4 = base.QueryParams["sp"];
         if (!base.IsRevocableAccess)
         {
             base.ValidateMandatoryField(str4, "sp");
             SASUtilities.ValidatePermissionOrdering(str4, SASPermission.Table);
             base.SignedPermission = new SASPermission?(SASUtilities.ParseSASPermission(str4));
         }
         else
         {
             base.ValidateOptionalField(str4, "sp");
             if (str4 != null)
             {
                 SASUtilities.ValidatePermissionOrdering(str4, SASPermission.Table);
                 base.SignedPermission = new SASPermission?(SASUtilities.ParseSASPermission(str4));
             }
         }
         string str5 = AuthenticationManagerHelper.ExtractKeyNameFromParamsWithConversion(base.QueryParams);
         base.ValidateOptionalField(str5, "sk");
         if (str5 != null)
         {
             base.KeyName = str5.Trim();
             Logger <IRestProtocolHeadLogger> .Instance.Verbose.Log("Using secret key with KeyName '{0}' to authenticate SAS request.", new object[] { base.KeyName });
         }
     }
     catch (FormatException formatException)
     {
         throw new AuthenticationFailureException("Signature fields not well formed.", formatException);
     }
 }
Ejemplo n.º 10
0
        public bool ComputeSignatureAndCompare(byte[] stringToSign, SecretKeyListV3 keys)
        {
            bool flag;

            NephosAssertionException.Assert(stringToSign != null);
            NephosAssertionException.Assert(keys != null);
            if (keys.Count == 0)
            {
                throw new ArgumentException("Invalid number of keys");
            }
            bool flag1 = string.IsNullOrEmpty(this.KeyName);

            List <SecretKeyV3> .Enumerator enumerator = keys.GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    SecretKeyV3 current = enumerator.Current;
                    if ((!flag1 || !current.IsDefault()) && !string.Equals(current.Name, this.KeyName) || !SASUtilities.ComputeSignatureAndCompare(stringToSign, current.Value, this.Signature))
                    {
                        continue;
                    }
                    this.KeyUsedForSigning = current;
                    flag = true;
                    return(flag);
                }
                return(false);
            }
            finally
            {
                ((IDisposable)enumerator).Dispose();
            }
            return(flag);
        }
Ejemplo n.º 11
0
        public static string GenerateBlobSasUrl(string accountName, string containerName, string blobName, string blobSnapshot, IStorageAccount storageAccount, string requestUrlBase, bool includeWritePermission)
        {
            if (string.IsNullOrEmpty(accountName) || string.IsNullOrEmpty(containerName) || string.IsNullOrEmpty(blobName) || string.IsNullOrEmpty(requestUrlBase))
            {
                IStringDataEventStream error = Logger <IRestProtocolHeadLogger> .Instance.Error;
                object[] objArray            = new object[] { accountName, containerName, blobName, requestUrlBase };
                error.Log("Source blob account, container, blob name or requestUrl should not be empty. sourceUnversionedAccountName: {0} sourceUnversionedContainerName: {1} sourceBlobName: {2} requestUrlBase: {3}", objArray);
                return(string.Empty);
            }
            NameValueCollection nameValueCollection = new NameValueCollection();

            if (!includeWritePermission)
            {
                nameValueCollection.Add("sp", "r");
            }
            else
            {
                nameValueCollection.Add("sp", "rw");
            }
            nameValueCollection.Add("se", SASUtilities.EncodeTime(DateTime.MaxValue));
            nameValueCollection.Add("sv", "2016-02-19");
            nameValueCollection.Add("sr", "b");
            byte[] sign = BlobSignedAccessHelper.ComputeUrlDecodedUtf8EncodedStringToSign(nameValueCollection, new NephosUriComponents(accountName, containerName, HttpUtility.UrlDecode(blobName)));
            string str  = (new UTF8Encoding()).GetString(sign);

            str = str.Replace('\n', '.');
            SecretKeyV3 secretKeyV3 = null;

            if (secretKeyV3 == null)
            {
                Logger <IRestProtocolHeadLogger> .Instance.Error.Log("GenerateBlobSasUrl: could not find a system key for the account");

                return(string.Empty);
            }
            string str1 = BlobSignedAccessHelper.ComputeHMACSHA256(secretKeyV3.Value, sign);

            if (string.IsNullOrEmpty(str1))
            {
                Logger <IRestProtocolHeadLogger> .Instance.Error.Log("GenerateBlobSasUrl: could not get HMACSHA256");

                return(string.Empty);
            }
            nameValueCollection.Add("sig", str1);
            if (!string.IsNullOrEmpty(blobSnapshot))
            {
                nameValueCollection.Add("snapshot", blobSnapshot);
            }
            UriBuilder    uriBuilder    = new UriBuilder(requestUrlBase);
            StringBuilder stringBuilder = new StringBuilder();

            string[] allKeys = nameValueCollection.AllKeys;
            for (int i = 0; i < (int)allKeys.Length; i++)
            {
                string str2 = allKeys[i];
                stringBuilder.Append(HttpUtilities.PathEncode(str2));
                stringBuilder.Append("=");
                stringBuilder.Append(HttpUtilities.PathEncode(nameValueCollection[str2]));
                stringBuilder.Append("&");
            }
            if (stringBuilder.Length > 0)
            {
                stringBuilder.Remove(stringBuilder.Length - 1, 1);
            }
            uriBuilder.Query = stringBuilder.ToString();
            return(uriBuilder.ToString());
        }
Ejemplo n.º 12
0
        public static byte[] ComputeUrlDecodedUtf8EncodedStringToSign(NameValueCollection queryParams, NephosUriComponents uriComponents)
        {
            string        item          = queryParams["st"];
            string        str           = queryParams["se"];
            string        item1         = queryParams["sp"];
            string        str1          = queryParams["sr"];
            string        item2         = queryParams["si"];
            string        str2          = queryParams["sip"];
            string        item3         = queryParams["spr"];
            string        str3          = queryParams["sv"];
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.Append(item1 ?? string.Empty);
            stringBuilder.Append("\n");
            stringBuilder.Append(item ?? string.Empty);
            stringBuilder.Append("\n");
            stringBuilder.Append(str ?? string.Empty);
            stringBuilder.Append("\n");
            stringBuilder.Append(BlobSignedAccessHelper.GetCanonicalizedResource(uriComponents, SASUtilities.ParseSasAccessLevel(str1), str3));
            stringBuilder.Append("\n");
            stringBuilder.Append(item2 ?? string.Empty);
            if (str3 != null)
            {
                if (VersioningHelper.CompareVersions(str3, "2015-04-05") >= 0)
                {
                    stringBuilder.Append("\n");
                    stringBuilder.Append(str2 ?? string.Empty);
                    stringBuilder.Append("\n");
                    stringBuilder.Append(item3 ?? string.Empty);
                }
                stringBuilder.Append("\n");
                stringBuilder.Append(queryParams["sv"]);
                if (VersioningHelper.CompareVersions(str3, "2014-02-14") >= 0)
                {
                    stringBuilder.Append("\n");
                    if (queryParams["rscc"] != null)
                    {
                        stringBuilder.Append(queryParams["rscc"]);
                    }
                    stringBuilder.Append("\n");
                    if (queryParams["rscd"] != null)
                    {
                        stringBuilder.Append(queryParams["rscd"]);
                    }
                    stringBuilder.Append("\n");
                    if (queryParams["rsce"] != null)
                    {
                        stringBuilder.Append(queryParams["rsce"]);
                    }
                    stringBuilder.Append("\n");
                    if (queryParams["rscl"] != null)
                    {
                        stringBuilder.Append(queryParams["rscl"]);
                    }
                    stringBuilder.Append("\n");
                    if (queryParams["rsct"] != null)
                    {
                        stringBuilder.Append(queryParams["rsct"]);
                    }
                }
            }
            if (queryParams["sep"] != null)
            {
                stringBuilder.Append("\n");
                stringBuilder.Append(queryParams["sep"]);
            }
            return((new UTF8Encoding()).GetBytes(stringBuilder.ToString()));
        }