public string GetCannedSignedURL(string fileName)
        {
            var cacheKey = $"s3url_{fileName}";
            var url      = _distributedCache.GetString(cacheKey);

            if (string.IsNullOrEmpty(url))
            {
                url = "";
                using (var textReader = File.OpenText(_cloudFrontOptions.PrivateKeyPath))
                {
                    url = AmazonCloudFrontUrlSigner.GetCannedSignedURL(
                        AmazonCloudFrontUrlSigner.Protocol.https,
                        _cloudFrontOptions.Domain,
                        textReader,
                        fileName,
                        _cloudFrontOptions.KeypairId,
                        DateTime.Now.AddSeconds(_cloudFrontOptions.ExpiredInSecond));
                }

                var options = new DistributedCacheEntryOptions
                {
                    AbsoluteExpiration = DateTime.Now.AddSeconds(_cloudFrontOptions.ExpiredInSecond)
                };
                _distributedCache.SetString(cacheKey, url, options);
            }

            return(url);
        }
        public void SignURLValidation()
        {
            string expectedSignedURL = @"http://awesome.dot.com/amazing/uri/?Policy=U2VjcmV0UG9saWN5"
                                       + @"&Signature=nmwKvD6cFoniNsMZeuxrzooEt73MtzS78g3u0Pym835Ty1cfV0sWK1sGnPpafaMw95kGNv7eHE3eivEosdXenrYMnz8EtobPOLyx4SQ4RvDrBfrjiNTGGgAowORLYc6sztZ8AKEQiQ9KVaOVNJ8DR5e2TQ7S~bNU91c0PEfrrcA_"
                                       + @"&Key-Pair-Id=amazingKeyPairId";
            string signedURL = AmazonCloudFrontUrlSigner.SignUrl("http://awesome.dot.com/amazing/uri/", "amazingKeyPairId", privateRSAKeyStreamReader, "SecretPolicy");

            Assert.Equal(expectedSignedURL, signedURL);
        }
Esempio n. 3
0
        public void SignURLCannedValidation()
        {
            string expectedSignedURL = @"http://awesome.dot.com/amazing/uri/?Expires=-6106035600"
                                       + @"&Signature=RezrUdl1C4O4LiHnK2orurG-KjuAoPb3wcJr7R0wrvaERJ7H4FVv4OtNxT2QcY~m7KmAXOJEL6aR6Xs3CujxAb2rMOeIev6yy6C~YVkMQQucBDof6HiFdfCZD-aZr7IQxiap6Kd9uqwR9tTp9rKBENzvI3hHyKtCY8Rn~SzwpGU_"
                                       + @"&Key-Pair-Id=amazingKeyPairId";
            string signedURL = AmazonCloudFrontUrlSigner.SignUrlCanned("http://awesome.dot.com/amazing/uri/", "amazingKeyPairId", privateRSAKeyStreamReader, new DateTime(1776, 7, 4));

            Assert.AreEqual(signedURL, expectedSignedURL);
        }
        public void SignURLCannedValidation()
        {
            string expectedSignedURL = @"http://awesome.dot.com/amazing/uri/?Expires=1492153200" +
                                       @"&Signature=XSFtfQPkZ3SgEulXvGpBH7L~Bfh3wv4kPtrYHkFA2yubVZ9tibq0Cz4HDaA-TVkuPOw0ipC4AmzOX8tjrtoD1U1N" +
                                       @"MsnnA3H4SQJI4Pe9AXjJwARrbFegGmCLoMmun2FxbOZqo2zb1ltBMOx7HtXBF5lQVkdukQsam4B6g3Mm9ec_&Key-Pair-Id=amazingKeyPairId";

            string signedURL = AmazonCloudFrontUrlSigner.SignUrlCanned("http://awesome.dot.com/amazing/uri/",
                                                                       "amazingKeyPairId", privateRSAKeyStreamReader, new DateTime(2017, 4, 14, 7, 0, 0, DateTimeKind.Utc));

            Assert.Equal(expectedSignedURL, signedURL);
        }
Esempio n. 5
0
 private string CreateSignedUrlForCannedPolicy()
 {
     // coreclr StreamReader does not have ctor that takes filename
     using (var fs = File.OpenRead(PrivateKeyFile))
         using (var reader = new StreamReader(fs))
         {
             var signedUrl = AmazonCloudFrontUrlSigner.GetCannedSignedURL(ResourceUri.ToString(),
                                                                          reader,
                                                                          KeyPairId,
                                                                          ExpiresOn);
             return(signedUrl);
         }
 }
Esempio n. 6
0
        private static string GetSignedURL(string resourceUrl, string KeyFileName, string KEYPAIR_ID, int ExP)
        {
            string   pathtokey    = SiteConfig.Environment.ContentRootPath + "/wwwroot/security/aws/cloudfront/" + KeyFileName;
            FileInfo privateKey   = new FileInfo(pathtokey);
            string   file         = new Uri(resourceUrl).PathAndQuery.Trim('/');
            string   distribution = new Uri(resourceUrl).Host.TrimEnd('/');

            return(AmazonCloudFrontUrlSigner.GetCannedSignedURL(
                       AmazonCloudFrontUrlSigner.Protocol.http,
                       distribution,
                       privateKey,
                       file,
                       KEYPAIR_ID,
                       DateTime.Now.AddSeconds((double)ExP)));
        }
Esempio n. 7
0
        public void PolicyStatementWithNoAddress()
        {
            var resourcePath          = "http://d111111abcdef8.cloudfront.net/game_download.zip";
            var dateTime              = new DateTime(2013, 1, 1, 10, 00, 0, DateTimeKind.Utc);
            var policyWithEmptyString = AmazonCloudFrontUrlSigner.BuildPolicyForSignedUrl(
                resourcePath,
                dateTime,
                "");

            var policyWithNull = AmazonCloudFrontUrlSigner.BuildPolicyForSignedUrl(
                resourcePath,
                dateTime,
                null);

            Assert.AreEqual(policyWithEmptyString, policyWithNull);

            foreach (var policy in new List <string> {
                policyWithEmptyString, policyWithNull
            })
            {
                var jsonObject = JsonMapper.ToObject(policy);

                var statementList = jsonObject["Statement"];
                Assert.IsTrue(statementList.IsArray);

                var statement = statementList[0];
                Assert.IsNotNull(statement);

                var resource = statement["Resource"];
                Assert.AreEqual(resource.ToString(), resourcePath);

                var condition = statement["Condition"];
                Assert.IsNotNull(condition);
                Assert.IsTrue(condition.IsObject);

                var IpAddress = condition["IpAddress"];
                Assert.IsNull(IpAddress);

                var epochTime = condition["DateLessThan"]["AWS:EpochTime"];
                Assert.AreEqual(1357034400, long.Parse(epochTime.ToString()));
            }
        }
Esempio n. 8
0
        public static string ToCloudfrontSignedUrl(this string url)
        {
            var cloudFrontKeyPairID = Utils.GetKeyValue("CloudFrontPairID");
            var pathtokey           = HttpContext.Current.Request.MapPath("~/Secure/cert/pk-cf.pem");
            var privateKey          = new FileInfo(pathtokey);

            string expirationEpoch = GetUnixTime(DateTime.UtcNow.AddDays(2)).ToString();

            string policy =
                @"{""Statement"":[{""Resource"":""<url>"",""Condition"":{""DateLessThan"":{""AWS:EpochTime"":<expiration>}}}]}".
                Replace("<url>", url).
                Replace("<expiration>", expirationEpoch);

            var signedUrl = AmazonCloudFrontUrlSigner.SignUrl(
                url,
                cloudFrontKeyPairID,
                privateKey,
                policy);

            return(signedUrl);
        }
Esempio n. 9
0
        public static string GetCloudFrontSignedPlayer(string filePath, string cloudFrontDomain)
        {
            filePath = filePath ?? "133321-75943878-651C-45C8-B53D-D47961B89DF3.mp4";

            string cloudFrontKeyPairID = "APKAJE56ZD4LJIRRJC6A"; //"APKAINOEJFZ5JOR7RPUQ"; //

            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);

            writer.Write(Constants.CLOUDFRONT_PRIVATEKEY);
            writer.Flush();
            stream.Position = 0;

            var url = AmazonCloudFrontUrlSigner.GetCannedSignedURL(
                AmazonCloudFrontUrlSigner.Protocol.http,
                cloudFrontDomain, //"dpa1gnaivadn.cloudfront.net",
                new StreamReader(stream),
                filePath,
                cloudFrontKeyPairID,
                DateTime.Now.AddDays(2));

            return(url);
        }
Esempio n. 10
0
        public string Sign(string url, DateTime expiry = default)
        {
            if (expiry == default)
            {
                expiry = DateTime.Now.AddHours(6);
            }
            using var privateKeyReader = new StringReader(_privateKey);
            Uri uri;

            if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
            {
                throw new ApplicationException("url is not valid: " + url);
            }
            var tempUrl = AmazonCloudFrontUrlSigner.GetCustomSignedURL(
                AmazonCloudFrontUrlSigner.Protocol.https,
                uri.Host.ToLower(),
                privateKeyReader,
                "*",
                _keyPairId,
                expiry,
                null);

            var queryParams    = tempUrl[(tempUrl.IndexOf("?") + 1)..];
Esempio n. 11
0
        public void PolicyStatementWithAddress()
        {
            var resourcePath = "http://*";
            var dateTime     = new DateTime(2013, 1, 1, 10, 00, 0, DateTimeKind.Utc);
            var ipRange      = "192.0.2.0/24";
            var cookies      = AmazonCloudFrontUrlSigner.BuildPolicyForSignedUrl(
                resourcePath,
                dateTime,
                ipRange);

            var jsonObject = JsonMapper.ToObject(cookies);

            var statementList = jsonObject["Statement"];

            Assert.IsTrue(statementList.IsArray);

            var statement = statementList[0];

            Assert.IsNotNull(statement);

            var resource = statement["Resource"];

            Assert.AreEqual(resource.ToString(), resourcePath);

            var condition = statement["Condition"];

            Assert.IsNotNull(condition);
            Assert.IsTrue(condition.IsObject);

            var sourceIp = condition["IpAddress"]["AWS:SourceIp"];

            Assert.AreEqual(ipRange, sourceIp.ToString());

            var epochTime = condition["DateLessThan"]["AWS:EpochTime"];

            Assert.AreEqual(1357034400, long.Parse(epochTime.ToString()));
        }
Esempio n. 12
0
        /// <summary>
        /// Get signed CloudFront URL
        /// </summary>
        /// <param name="photoPath"></param>
        /// <param name="distributionDomain"></param>
        /// <returns></returns>
        public static string GetCannedSignedURLContactBase(string photoPath, string distributionDomain)
        {
            const string keyPairId = "APKAJYLNBTJQ44EXZHTQ";
            const string rsaKey    = @"-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAh/8nUGHs5EK5bDFzDKT/LuS2Jy5px2FCNSb6+SDP8j8tDLSe
DS10J/8W0rgK8YoKgqbSwHc7nqkQwaFK3dBhtRZWOeLvr7uCZEr1D0MFzb00lUqK
f4ph9n/A1kgsdOA/6qVeIeaA5xskQhFSngQCMkeAuBXulF5iOZcYGEsBiH5AGsVr
Bo0AJrRqwAP9Kd/e9Vw6J7FFyjTdm7zEhDlcH1SsiM02Ys82d3XHDx0h4THFbYwR
dWt6DtiKmL82xiDsAoNgYGY0csL9nUtsZSWVI0Wz6tAUCxHhpXgm+381WyeJsv0Q
liKDdqOdPykSth0f3kjQ4E3tyVvKIRmDRvR1fwIDAQABAoIBAD3Ld76zsGOL2htK
YN+m/Xj+XbJyCYiaLe5e9v1KppKJmFvEmmicdcJSy7kV/YsBUYNKcEsaIpIWelGx
i4Y80JjrPGTzNDwitL4DvVSg/LsetQz9IO+RHrBWHnZ/twuodgKV/67hwULB93i5
zFOWuLTF/rwm4xCxzmoiuMUZF+o/4QQKaabwd+89h7+DeFQq91jY4XUgcvHyQPV3
P4WiDjPTbIJG31GrP9Cbw4eBswL9KbvhYHNtbu9zuxhI/pqbap1lIuYObnoimWdE
hdm00FIc8ZbmLKkDRiKdQEcYQr4mpIKN5ODheFhA1l3pqMUoZuEcN4ldyIZtkRLW
0NyZzFkCgYEA0ZX07nr5R4JQ7sI8Us8WLcIJ4M6hhui43iDT59dJ9I3RRtuySzYX
pfc+NsklsPgbtpmVGp8r5uFld1CwlFVzvdOfozDsGbIwNgIWsGVsxeOLyKyhf79z
YOFidvId6e0wSarGmZUz4mhbHFClKDJapFBup24jk2qD6uJdig01A3MCgYEAph02
XA4vYdF/+UmMjmAogkpDozOmTpRGqkOJZ5/YmVpKoWq+hnOXddo4GGqT6b1AEnsv
nziuXZZBGSTuMRIfIsbqRRsKNKzGS30isF/PR/AnPJPH6/Zo28nS73xSRxWu8k7W
5pCAgzXnVr3Ob0ZGX09GuTzAatKa6KeoUMdsesUCgYBp3aVrERL53AmlkNeHvLMn
SexTcgyFaOh4y3w+j7D7pucfM7pL43bujoUOh2xSiAD3q3x1hhFW/mOScV/Ajal5
KXxpojygfjF8FnH/iDv5eYcSRqENNlfBiBeEnagekYDitTC8Q3GB29Sp6NKEC2td
tIMwb6HoxNT9wHofUayFoQKBgFimWF9SVqkOZAyG2tMUsCmwNl5/bu6apQeymT7L
CI32qMNyMxGP2LHVboBhSGTCUdJLGYQQfMWHLWCc290mPaWSoG2W26B24DBjLMMR
ro5GtLnYaCYeT6GUGNUj9Mjo4n9/4aIUVfEwMDCThPrPdzjgFu8+Y7XehTtKVkId
21+9AoGABSlZsV1+5n4TKbi4LGAwnKiOE7vEyQz7jFJEzNH8eqK3GKSzJIP3zFEC
MwBDKvyz+WsuhjccRKncswJBFZY3HleBBmQ43zPkL6kOCJLzBdFslk/0bVq0m+dJ
jyweJ5gTWfNgFuk4vrrioGUW10P/yuNU6C2bPQKDJtc7tfkuD7o=
-----END RSA PRIVATE KEY-----";

            var rsaKeyText = new StringReader(rsaKey);

            try
            {
                if (string.IsNullOrWhiteSpace(photoPath))
                {
                    return("data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==");
                }

                if (photoPath.IndexOf("/") > -1)
                {
                    photoPath = HttpUtility.UrlEncode(photoPath);
                }

                TimeSpan expiry = TimeSpan.FromHours(6);

                var signedUrl = AmazonCloudFrontUrlSigner.GetCannedSignedURL(
                    string.Format("https://{0}/{1}", distributionDomain, photoPath),
                    rsaKeyText,
                    keyPairId,
                    DateTime.Now.AddSeconds((int)expiry.TotalSeconds));

                return(signedUrl);
            }
            catch (Exception ex)
            {
            }

            return(null);
        }