Example #1
0
	// source: http://blogs.msdn.com/shawnfa/archive/2004/10/25/247379.aspx
	static AppDomain CreateRestrictedDomain (string filename)
	{
		PermissionSet emptySet = new PermissionSet (PermissionState.None);
		PolicyStatement emptyPolicy = new PolicyStatement (emptySet);
		UnionCodeGroup root = new UnionCodeGroup (new AllMembershipCondition (), emptyPolicy);

		PermissionSet userSet = null;
		if (filename [0] == '@')
			userSet = GetNamedPermissionSet (filename.Substring (1));
		else
			userSet = LoadFromFile (filename);

		PolicyStatement userPolicy = new PolicyStatement (userSet);
		root.AddChild (new UnionCodeGroup (new AllMembershipCondition (), userPolicy));

		PolicyLevel pl = PolicyLevel.CreateAppDomainLevel ();
		pl.RootCodeGroup = root;

		AppDomain ad = AppDomain.CreateDomain ("Restricted");
		ad.SetAppDomainPolicy (pl);
		return ad;
	}
Example #2
0
    // Add file permission to restrict write access to all files
    // on the local machine.
    private static void addPolicy(ref FirstMatchCodeGroup codeGroup)
    {
        // Set the PolicyStatement property to a policy with read access to
        // the root directory on drive C.
        //<Snippet6>
        FileIOPermission rootFilePermissions =
            new FileIOPermission(PermissionState.None);

        rootFilePermissions.AllLocalFiles = FileIOPermissionAccess.Read;
        rootFilePermissions.SetPathList(FileIOPermissionAccess.Read, "C:\\");

        NamedPermissionSet namedPermissions =
            new NamedPermissionSet("RootPermissions");

        namedPermissions.AddPermission(rootFilePermissions);

        // Create a PolicyStatement with exclusive rights to the policy.
        PolicyStatement policy = new PolicyStatement(
            namedPermissions,
            PolicyStatementAttribute.Exclusive);

        codeGroup.PolicyStatement = policy;
        //</Snippet6>
    }
Example #3
0
        public void Resolve_ZoneMembershipCondition_Internet()
        {
            IMembershipCondition mc   = new ZoneMembershipCondition(SecurityZone.Internet);
            PermissionSet        pset = new PermissionSet(PermissionState.Unrestricted);
            UnionCodeGroup       cg   = new UnionCodeGroup(mc, new PolicyStatement(pset, PolicyStatementAttribute.Nothing));

            Evidence e = new Evidence();

            e.AddHost(new Zone(SecurityZone.Internet));
            PolicyStatement result = cg.Resolve(e);

            Assert.AreEqual(PolicyStatementAttribute.Nothing, result.Attributes, "Internet-Attributes");
            Assert.AreEqual(String.Empty, result.AttributeString, "Internet-AttributeString");
            Assert.IsTrue(result.PermissionSet.IsUnrestricted(), "Internet-IsUnrestricted");
            Assert.AreEqual(0, result.PermissionSet.Count, "Internet-Count");

            e = new Evidence();
            e.AddHost(new Zone(SecurityZone.Intranet));
            Assert.IsNull(cg.Resolve(e), "Intranet");

            e = new Evidence();
            e.AddHost(new Zone(SecurityZone.MyComputer));
            Assert.IsNull(cg.Resolve(e), "MyComputer");

            e = new Evidence();
            e.AddHost(new Zone(SecurityZone.NoZone));
            Assert.IsNull(cg.Resolve(e), "NoZone");

            e = new Evidence();
            e.AddHost(new Zone(SecurityZone.Trusted));
            Assert.IsNull(cg.Resolve(e), "Trusted");

            e = new Evidence();
            e.AddHost(new Zone(SecurityZone.Untrusted));
            Assert.IsNull(cg.Resolve(e), "Untrusted");
        }
        public void ToFromXmlRoundtrip_WithChildren()
        {
            PolicyStatement ps = new PolicyStatement(new NamedPermissionSet(ps_Name));

            MyCodeGroup cgChild = new MyCodeGroup(new ApplicationDirectoryMembershipCondition(), ps);

            cgChild.Name        = "ChildName";
            cgChild.Description = "Child Descripiton";

            MyCodeGroup cg = new MyCodeGroup(new AllMembershipCondition(), ps);

            cg.Name        = "SomeName";
            cg.Description = "Some Description";
            cg.AddChild(cgChild);
            cg.AddChild(cgChild);
            Assert.IsTrue(cg.Equals(cg), "Equals (itself)");
            SecurityElement se = cg.ToXml();

            MyCodeGroup cg2 = (MyCodeGroup)cg.Copy();

            cg2.FromXml(se);
            // MissingMethodException down here (stangely not up here ?!? delayed ?)
            Assert.IsTrue(cg.Equals(cg2, true), "Equals (FromXml)");
        }
Example #5
0
        //-----------------------------------------------------------------------------------------------
        // private methods
        //-----------------------------------------------------------------------------------------------

        /// <summary>
        /// Written by Abhishek Kumar on March 05, 2007
        /// purpose: to initiate the central Application Domain that
        /// all Grid Threads will be run on.
        ///
        /// Police and permissions will also be set.
        /// ADV: a crash in this App Domain(because of poor code in GThread)
        /// does not affect eduGRID's Framework i.e. the Alchemi executor is maintained steady even in error
        ///
        /// initially Alchemi created separate app domains for each Gthread it received.
        /// now, instead, we create 1 appdomain and run all gthreads on it
        /// the Bot Logic resides in this app domain.
        /// (this saves the overhead of initializing bot logic for every Gthread (or every query))
        /// </summary>
        private void initialize_GridThreadExecutor()
        {
            if (GridThreadExecutor == null)
            {
                string         appDir = GetApplicationDirectory(_CurTi.ApplicationId);
                AppDomainSetup info   = new AppDomainSetup();
                info.PrivateBinPath         = appDir;
                GridThreadApplicationDomain = AppDomain.CreateDomain("Central_AppDomain", null, info);

                // ***
                // http://www.dotnetthis.com/Articles/DynamicSandboxing.htm
                PolicyLevel            domainPolicy = PolicyLevel.CreateAppDomainLevel();
                AllMembershipCondition allCodeMC    = new AllMembershipCondition();
                // TODO: 'FullTrust' in the following line needs to be replaced with something like 'AlchemiGridThread'
                //        This permission set needs to be defined and set automatically as part of the installation.
                PermissionSet   internetPermissionSet   = domainPolicy.GetNamedPermissionSet("FullTrust");
                PolicyStatement internetPolicyStatement = new PolicyStatement(internetPermissionSet);
                CodeGroup       allCodeInternetCG       = new UnionCodeGroup(allCodeMC, internetPolicyStatement);
                domainPolicy.RootCodeGroup = allCodeInternetCG;
                GridThreadApplicationDomain.SetAppDomainPolicy(domainPolicy);

                GridThreadExecutor = (AppDomainExecutor)GridThreadApplicationDomain.CreateInstanceFromAndUnwrap(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Alchemi.Executor.dll"), "Alchemi.Executor.AppDomainExecutor");
            }

            if (!GridThreadExecutor.Initialized)
            {
                try
                {
                    GridThreadExecutor.initialize();
                }
                catch (Exception ex)
                {
                    throw new Exception("Error during initialization of GridThreadExecutor");
                }
            }
        }
Example #6
0
        public void Equals()
        {
            PolicyStatement empty1 = new PolicyStatement(null);
            PolicyStatement empty2 = new PolicyStatement(null);

            Assert.IsTrue(empty1.Equals(empty2), "empty1.Equals (empty2)");
            Assert.IsTrue(empty2.Equals(empty1), "empty2.Equals (empty1)");
            Assert.IsFalse(Object.ReferenceEquals(empty1, empty2), "!ReferenceEquals");

            PolicyStatement unr1 = new PolicyStatement(Unrestricted, PolicyStatementAttribute.All);

            Assert.IsFalse(unr1.Equals(empty1), "unr1.Equals (empty1)");
            Assert.IsFalse(empty1.Equals(unr1), "empty1.Equals (unr1)");

            PolicyStatement unr2 = new PolicyStatement(Unrestricted, PolicyStatementAttribute.Exclusive);

            Assert.IsFalse(unr1.Equals(unr2), "unr1.Equals (unr2)");
            Assert.IsFalse(unr2.Equals(unr1), "unr2.Equals (unr1)");

            PolicyStatement unr3 = unr2.Copy();

            Assert.IsTrue(unr3.Equals(unr2), "unr3.Equals (unr2)");
            Assert.IsTrue(unr2.Equals(unr3), "unr2.Equals (unr3)");
        }
        }// DoesCGHaveNetCodegroup

        internal static void PrepCodeGroupTree(CodeGroup root, PolicyLevel plSrc, PolicyLevel plDest)
        {
            SuperCodeGroupArrayList scal;

            ListifyCodeGroup(root, null, out scal);
            for (int i = 0; i < scal.Count; i++)
            {
                // make sure this codegroup name is not already used
                int    nCounter = 1;
                String sBase    = scal[i].cg.Name;
                while (Security.isCodeGroupNameUsed(plDest.RootCodeGroup, scal[i].cg.Name) ||
                       Security.isCodeGroupNameUsed(root, scal[i].cg))
                {
                    if (nCounter == 1)
                    {
                        scal[i].cg.Name = String.Format(CResourceStore.GetString("CSingleCodeGroup:NewDupCodegroup"), sBase);
                    }
                    else
                    {
                        scal[i].cg.Name = String.Format(CResourceStore.GetString("CSingleCodeGroup:NumNewDupCodegroup"), nCounter.ToString(), sBase);
                    }

                    nCounter++;
                }

                // Now check to see if we have its permission set in the policy
                if (plDest != plSrc)
                {
                    bool fAddPermissionSet = false;

                    if (!Security.isPermissionSetNameUsed(plDest, scal[i].cg.PermissionSetName))
                    {
                        // We're copying a codegroup from a different policy level to a new
                        // policy level. This new policy level does not contain the permission
                        // set that our codegroup uses... thus, we must also copy over a new
                        // permission set as well
                        fAddPermissionSet = true;
                    }
                    else
                    {
                        // The permission set name is used. Let's see if it's what we want
                        PermissionSet psSrc  = plSrc.GetNamedPermissionSet(scal[i].cg.PermissionSetName);
                        PermissionSet psDest = plDest.GetNamedPermissionSet(scal[i].cg.PermissionSetName);
                        // See if these permission sets are equal
                        try
                        {
                            if (!(psSrc.IsSubsetOf(psDest) && psDest.IsSubsetOf(psSrc)))
                            {
                                // We're copying a codegroup from a different policy level to a new
                                // policy level. This new policy level contains a permission
                                // set with the same name as the permission set the our codegroup uses...
                                // However, the permission set that the codegroup uses has different permissions
                                // than what the permission set that the new policy level has... therefore, we
                                // must copy over a new permission set.
                                // The copied permission set will have a different name (since we can't have two
                                // permission sets with the exact same name). We'll have to remember
                                // to change the name of the permission set that the codegroup uses.
                                fAddPermissionSet = true;
                            }
                        }
                        catch (Exception)
                        {
                            // When we're doing these IsSubSetOf things, RegEx classes will throw
                            // exceptions if things aren't quite right. If that's the case, then
                            // we want to add the permission set.
                            fAddPermissionSet = true;
                        }
                    }

                    if (fAddPermissionSet)
                    {
                        // See if this codegroup has a policy (i.e. a permission set)
                        if (scal[i].cg.PolicyStatement != null)
                        {
                            // We need to add this permission set from that policy level
                            String sPermissionSetName = AddPermissionSet(plDest, plSrc.GetNamedPermissionSet(scal[i].cg.PermissionSetName)).DisplayName;
                            // It's possible that we added a permission set and the name of our permission
                            // set was already used in the security policy. In that case, the permission set
                            // we tried to add was renamed. We should updated the codegroup to look at the
                            // permission set's new name
                            PermissionSet   ps   = plDest.GetNamedPermissionSet(sPermissionSetName);
                            PolicyStatement pols = scal[i].cg.PolicyStatement;
                            pols.PermissionSet         = ps;
                            scal[i].cg.PolicyStatement = pols;
                        }
                    }
                }

                if (i != 0)
                {
                    // Add the modified codegroup back into the tree
                    Security.RefreshCodeGroup(scal[scal[i].nParent].cg, scal[i].cg, scal[i].ChildNum);
                }
            }
        }// PrepCodeGroupTree
Example #8
0
        /// <summary>
        /// Create an AppDomain that contains policy restricting code to execute
        /// with only the permissions granted by a named permission set
        /// </summary>
        /// <param name="permissionSetName">name of the permission set to restrict to</param>
        /// <param name="appDomainName">'friendly' name of the appdomain to be created</param>
        /// <exception cref="ArgumentNullException">
        /// if <paramref name="permissionSetName"/> is null
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// if <paramref name="permissionSetName"/> is empty
        /// </exception>
        /// <returns>AppDomain with a restricted security policy</returns>
        /// <remarks>Substantial portions of this function from: http://blogs.msdn.com/shawnfa/archive/2004/10/25/247379.aspx
        /// Valid permissionSetName values are:
        /// * FullTrust
        /// * SkipVerification
        /// * Execution
        /// * Nothing
        /// * LocalIntranet
        /// * Internet
        /// * Everything
        /// </remarks>
#pragma warning disable 0618
        public static AppDomain CreateRestrictedDomain(string permissionSetName, string appDomainName)
        {
            if (permissionSetName == null)
            {
                throw new ArgumentNullException("permissionSetName");
            }
            if (permissionSetName.Length == 0)
            {
                throw new ArgumentOutOfRangeException("permissionSetName", permissionSetName,
                                                      "Cannot have an empty permission set name");
            }

            // Default to all code getting nothing
            PolicyStatement emptyPolicy = new PolicyStatement(new PermissionSet(PermissionState.None));
            UnionCodeGroup  policyRoot  = new UnionCodeGroup(new AllMembershipCondition(), emptyPolicy);

            bool          foundName       = false;
            PermissionSet setIntersection = new PermissionSet(PermissionState.Unrestricted);

            // iterate over each policy level
            IEnumerator levelEnumerator = SecurityManager.PolicyHierarchy();

            while (levelEnumerator.MoveNext())
            {
                PolicyLevel level = levelEnumerator.Current as PolicyLevel;

                // if this level has defined a named permission set with the
                // given name, then intersect it with what we've retrieved
                // from all the previous levels
                if (level != null)
                {
                    PermissionSet levelSet = level.GetNamedPermissionSet(permissionSetName);
                    if (levelSet != null)
                    {
                        foundName = true;
                        if (setIntersection != null)
                        {
                            setIntersection = setIntersection.Intersect(levelSet);
                        }
                    }
                }
            }

            // Intersect() can return null for an empty set, so convert that
            // to an empty set object. Also return an empty set if we didn't find
            // the named permission set we were looking for
            if (setIntersection == null || !foundName)
            {
                setIntersection = new PermissionSet(PermissionState.None);
            }
            else
            {
                setIntersection = new NamedPermissionSet(permissionSetName, setIntersection);
            }

            // if no named permission sets were found, return an empty set,
            // otherwise return the set that was found
            PolicyStatement permissions = new PolicyStatement(setIntersection);

            policyRoot.AddChild(new UnionCodeGroup(new AllMembershipCondition(), permissions));

            // create an AppDomain policy level for the policy tree
            PolicyLevel appDomainLevel = PolicyLevel.CreateAppDomainLevel();

            appDomainLevel.RootCodeGroup = policyRoot;

            // create an AppDomain where this policy will be in effect
            string    domainName       = appDomainName;
            AppDomain restrictedDomain = AppDomain.CreateDomain(domainName);

            restrictedDomain.SetAppDomainPolicy(appDomainLevel);

            return(restrictedDomain);
        }
        /// From MRMModule.cs by Adam Frisby
        /// <summary>
        ///     Create an AppDomain that contains policy restricting code to execute
        ///     with only the permissions granted by a named permission set
        /// </summary>
        /// <param name="permissionSetName">name of the permission set to restrict to</param>
        /// <param name="appDomainName">'friendly' name of the appdomain to be created</param>
        /// <param name="ads"></param>
        /// <exception cref="ArgumentNullException">
        ///     if <paramref name="permissionSetName" /> is null
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        ///     if <paramref name="permissionSetName" /> is empty
        /// </exception>
        /// <returns>AppDomain with a restricted security policy</returns>
        /// <remarks>
        ///     Substantial portions of this function from: http://blogs.msdn.com/shawnfa/archive/2004/10/25/247379.aspx
        ///     Valid permissionSetName values are:
        ///     * FullTrust
        ///     * SkipVerification
        ///     * Execution
        ///     * Nothing
        ///     * LocalIntranet
        ///     * Internet
        ///     * Everything
        /// </remarks>
        public AppDomain CreateRestrictedDomain(string permissionSetName, string appDomainName, AppDomainSetup ads)
        {
            if (permissionSetName == null)
            {
                throw new ArgumentNullException("permissionSetName");
            }
            if (permissionSetName.Length == 0)
            {
                throw new ArgumentOutOfRangeException("permissionSetName", permissionSetName,
                                                      "Cannot have an empty permission set name");
            }

            // Default to all code getting everything
            PermissionSet setIntersection  = new PermissionSet(PermissionState.Unrestricted);
            AppDomain     restrictedDomain = null;

#if LINUX
        #pragma warning disable 612, 618
            PolicyStatement emptyPolicy = new PolicyStatement(new PermissionSet(PermissionState.None));
            UnionCodeGroup  policyRoot  = new UnionCodeGroup(new AllMembershipCondition(), emptyPolicy);

            bool foundName = false;
            // iterate over each policy level
            IEnumerator levelEnumerator = SecurityManager.PolicyHierarchy();
            while (levelEnumerator.MoveNext())
            {
                PolicyLevel level = levelEnumerator.Current as PolicyLevel;

                // if this level has defined a named permission set with the
                // given name, then intersect it with what we've retrieved
                // from all the previous levels
                if (level != null)
                {
                    PermissionSet levelSet = level.GetNamedPermissionSet(permissionSetName);
                    if (levelSet != null)
                    {
                        foundName = true;
                        if (setIntersection != null)
                        {
                            setIntersection = setIntersection.Intersect(levelSet);
                        }
                    }
                }
            }

            // Intersect() can return null for an empty set, so convert that
            // to an empty set object. Also return an empty set if we didn't find
            // the named permission set we were looking for
            if (setIntersection == null || !foundName)
            {
                setIntersection = new PermissionSet(PermissionState.None);
            }
            else
            {
                setIntersection = new NamedPermissionSet(permissionSetName, setIntersection);
            }

            // if no named permission sets were found, return an empty set,
            // otherwise return the set that was found
            setIntersection.AddPermission(new SocketPermission(PermissionState.Unrestricted));
            setIntersection.AddPermission(new WebPermission(PermissionState.Unrestricted));
            setIntersection.AddPermission(new SecurityPermission(PermissionState.Unrestricted));

            PolicyStatement permissions = new PolicyStatement(setIntersection);
            policyRoot.AddChild(new UnionCodeGroup(new AllMembershipCondition(), permissions));

            // create an AppDomain policy level for the policy tree
            PolicyLevel appDomainLevel = PolicyLevel.CreateAppDomainLevel();
            appDomainLevel.RootCodeGroup = policyRoot;

            // create an AppDomain where this policy will be in effect
            restrictedDomain = AppDomain.CreateDomain(appDomainName, null, ads);
            restrictedDomain.SetAppDomainPolicy(appDomainLevel);
        #pragma warning restore 612, 618
#else
            SecurityZone zone = SecurityZone.MyComputer;
            try
            {
                zone = (SecurityZone)Enum.Parse(typeof(SecurityZone), permissionSetName);
            }
            catch
            {
                zone = SecurityZone.MyComputer;
            }

            Evidence ev = new Evidence();
            ev.AddHostEvidence(new Zone(zone));
            setIntersection = SecurityManager.GetStandardSandbox(ev);
            setIntersection.AddPermission(new System.Net.SocketPermission(PermissionState.Unrestricted));
            setIntersection.AddPermission(new System.Net.WebPermission(PermissionState.Unrestricted));
            setIntersection.AddPermission(
                new System.Security.Permissions.SecurityPermission(PermissionState.Unrestricted));

            // create an AppDomain where this policy will be in effect
            restrictedDomain = AppDomain.CreateDomain(appDomainName, ev, ads, setIntersection, null);
#endif

            return(restrictedDomain);
        }
 public static PolicyStatement WithEffect(this PolicyStatement statement, Effect effect)
 {
     statement.Effect = effect;
     return(statement);
 }
 public static PolicyStatement WithResources(this PolicyStatement statement, params string[] resources)
 {
     statement.AddResources(0 < resources.Length ? resources : new string[] { "*" });
     return(statement);
 }
        public void FromXml_BadSecurityElement()
        {
            PolicyStatement ps = new PolicyStatement(null);

            ps.FromXml(new SecurityElement("Bad"));
        }
 // Constructors
 public FirstMatchCodeGroup(IMembershipCondition membershipCondition, PolicyStatement policy)
 {
 }
        public void FromXml_Null()
        {
            PolicyStatement ps = new PolicyStatement(null);

            ps.FromXml(null);
        }
	// Constructors
	public FirstMatchCodeGroup(IMembershipCondition membershipCondition, PolicyStatement policy) {}
Example #16
0
        }// CreateGrantedPermissionSet

        private void CreateGrantedCodegroups()
        {
            CodeGroup[] cgs = new CodeGroup[] { new NotEvalCodegroup(),
                                                new NotEvalCodegroup(),
                                                new NotEvalCodegroup() };
            int nIndex = -1;

            try
            {
                if (Page1.PolicyLevel != ALL_CODEGROUPS)
                {
                    nIndex = Page1.PolicyLevel;
                    PolicyLevel pl = GetPolicyLevel(Page1.PolicyLevel);
                    cgs[nIndex] = pl.RootCodeGroup.ResolveMatchingCodeGroups(m_ev);
                }
                else
                {
                    // We need to run through all the levels

                    // The ordering of Enterprise, Machine, and User is very important.
                    //
                    // If this ordering gets changed, please update the constants located at
                    // the top of the file (ENTERPRISE_CODEGROUPS, MACHINE_CODEGROUPS, etc)

                    String[] sPolLevels = new String[] { "Enterprise", "Machine", "User" };
                    for (nIndex = 0; nIndex < sPolLevels.Length; nIndex++)
                    {
                        PolicyLevel pl = Security.GetPolicyLevelFromLabel(sPolLevels[nIndex]);
                        cgs[nIndex] = pl.RootCodeGroup.ResolveMatchingCodeGroups(m_ev);

                        // Now check to see if this codegroup tree has a level final...
                        if (cgs[nIndex] != null)
                        {
                            PolicyStatement ps = cgs[nIndex].Resolve(m_ev);
                            if (ps != null)
                            {
                                if ((ps.Attributes & PolicyStatementAttribute.LevelFinal) == PolicyStatementAttribute.LevelFinal)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
                // All done
                m_cgMatchingCodeGroups = cgs;
                m_fCGErrors            = false;
            }
            catch (PolicyException pe)
            {
                String[] sPolLevels = new String[] {
                    CResourceStore.GetString("Enterprise"),
                    CResourceStore.GetString("Machine"),
                    CResourceStore.GetString("User")
                };


                m_fCGErrors       = true;
                m_sCGErrorMessage = String.Format(CResourceStore.GetString("CEvalAssemWizard:ErrorEvaluate"),
                                                  sPolLevels[nIndex],
                                                  pe.Message);
                m_cgMatchingCodeGroups = null;
            }
        } // CreateGrantedCodegroups
        public void CreateLogConsumerResources()
        {
            //LambdaRole
            var firehoseLambdaRole = new Role(this, "FirehoseLambdaRole", new RoleProps
            {
                AssumedBy = new ServicePrincipal("lambda.amazonaws.com"),
                Path      = "/",
            });

            firehoseLambdaRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps
            {
                Effect    = Effect.ALLOW,
                Resources = new string[] { "arn:aws:logs:*:*:*" },
                Actions   = new string[] { "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" },
            }));

            //FirehoseDataProcessingFunction
            var handler = new Function(this, "FirehoseDataProcessorFunction", new FunctionProps
            {
                FunctionName = "data-processor-function",
                Runtime      = Runtime.NODEJS_12_X,
                Code         = Code.FromAsset("resources"),
                Handler      = "index.handler",
                Role         = firehoseLambdaRole,
                Timeout      = Duration.Minutes(2)
            });

            //FirehoseDeliveryRole & Policies
            var firehoseDeliveryRole = new Role(this, "FirehoseDeliveryRole", new RoleProps
            {
                AssumedBy = new ServicePrincipal("firehose.amazonaws.com"),
                Path      = "/"
            });

            //S3 permissions
            firehoseDeliveryRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps
            {
                Effect    = Effect.ALLOW,
                Resources = new string[] { _logsBucket.BucketArn, _logsBucket.BucketArn + "/*" },
                Actions   = new string[] { "s3:AbortMultipartUpload", "s3:GetBucketLocation", "s3:GetObject"
                                           , "s3:ListBucket", "s3:ListBucketMultipartUploads", "s3:PutObject" },
            }));

            //Lambda permissions
            firehoseDeliveryRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps
            {
                Effect    = Effect.ALLOW,
                Resources = new string[] { handler.FunctionArn },
                Actions   = new string[] { "lambda:GetFunctionConfiguration", "lambda:InvokeFunction" },
            }));

            //Log group for Firehose logs.
            var firehoseloggroup = new LogGroup(this, "firehoseloggroup", new LogGroupProps
            {
                LogGroupName = "central-logs-delivery-group"
            });
            var logstream = new LogStream(this, "logstream", new LogStreamProps
            {
                LogStreamName = "central-logs-delivery-stream",
                LogGroup      = firehoseloggroup
            });

            firehoseDeliveryRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps
            {
                Effect    = Effect.ALLOW,
                Resources = new string[] { firehoseloggroup.LogGroupArn },
                Actions   = new string[] { "logs:PutLogEvents" },
            }));

            //FirehoseLoggingDeliveryStream - Start
            CfnDeliveryStream.ExtendedS3DestinationConfigurationProperty s3config = new CfnDeliveryStream.ExtendedS3DestinationConfigurationProperty();
            s3config.BucketArn      = _logsBucket.BucketArn;
            s3config.BufferingHints = new CfnDeliveryStream.BufferingHintsProperty
            {
                SizeInMBs         = 50,
                IntervalInSeconds = 300
            };
            s3config.CompressionFormat = "UNCOMPRESSED";
            s3config.RoleArn           = firehoseDeliveryRole.RoleArn;
            s3config.Prefix            = "CentralLogs/AWSLogs/";
            s3config.ErrorOutputPrefix = "CentralLogs/AWSLogs/Error/";

            var parameters = new CfnDeliveryStream.ProcessorParameterProperty();

            parameters.ParameterName  = "LambdaArn";
            parameters.ParameterValue = handler.FunctionArn;

            var paramsArray1 = new CfnDeliveryStream.ProcessorParameterProperty[] { parameters };

            var processorProperty = new CfnDeliveryStream.ProcessorProperty();

            processorProperty.Parameters = paramsArray1;
            processorProperty.Type       = "Lambda";

            var paramsArray = new CfnDeliveryStream.ProcessorProperty[] { processorProperty };

            s3config.ProcessingConfiguration = new CfnDeliveryStream.ProcessingConfigurationProperty
            {
                Enabled    = true,
                Processors = paramsArray
            };

            s3config.CloudWatchLoggingOptions = new CfnDeliveryStream.CloudWatchLoggingOptionsProperty
            {
                Enabled       = true,
                LogGroupName  = firehoseloggroup.LogGroupName,
                LogStreamName = logstream.LogStreamName
            };


            CfnDeliveryStream firehoseDeliveryStream = new CfnDeliveryStream(this, "FirehoseLoggingDeliveryStream", new CfnDeliveryStreamProps
            {
                DeliveryStreamType = "DirectPut",
                ExtendedS3DestinationConfiguration = s3config
            });
            //FirehoseLoggingDeliveryStream - End

            //Policy Statements for LogDestination- start
            var policyStmt = new PolicyStatement(new PolicyStatementProps()
            {
                Actions   = new string[] { "firehose:PutRecord" },
                Resources = new string[] { "*" },
                Effect    = Effect.ALLOW
            });
            var policyDoc = new PolicyDocument();

            policyDoc.AddStatements(new PolicyStatement[] { policyStmt });

            var policyProp = new CfnRole.PolicyProperty();

            policyProp.PolicyName     = "logDestinationPolicy";
            policyProp.PolicyDocument = policyDoc;
            //Policy Statements - end

            //AssumeRolePolicyDocument for LogDestination - start
            var principal             = new ServicePrincipal("logs.amazonaws.com");
            var assumePolicyStatement = new PolicyStatement(new PolicyStatementProps
            {
                Actions    = new string[] { "sts:AssumeRole" },
                Effect     = Effect.ALLOW,
                Principals = new IPrincipal[] { principal }
            });
            var assumePolicyDoc = new PolicyDocument();

            assumePolicyDoc.AddStatements(new PolicyStatement[] { assumePolicyStatement });
            //AssumeRolePolicyDocument - end

            var roleProps = new CfnRoleProps {
                Path = "/",
                AssumeRolePolicyDocument = assumePolicyDoc,
                Policies = new CfnRole.PolicyProperty[] { policyProp }
            };

            CfnRole cfnRole = new CfnRole(this, "CfnRole", roleProps);

            CfnDestination logDestination = new CfnDestination(this, "LogDestination", new CfnDestinationProps
            {
                DestinationName   = "Central-Log-Destination",
                RoleArn           = cfnRole.AttrArn,
                TargetArn         = firehoseDeliveryStream.AttrArn,
                DestinationPolicy = "{\"Version\" : \"2012-10-17\",\"Statement\" : [{\"Effect\" : \"Allow\", \"Principal\" : {\"AWS\" :  [\"" + SourceLogAccountId + "\"]},\"Action\" : \"logs:PutSubscriptionFilter\", \"Resource\" : \"arn:aws:logs:" + this.Region + ":"
                                    + DestinationAccountId + ":destination:Central-Log-Destination\"}]}"
            });

            logDestination.AddDependsOn(firehoseDeliveryStream);
            logDestination.AddDependsOn(cfnRole);
            Console.WriteLine(logDestination.DestinationPolicy);

            LogDestinationArn = logDestination.AttrArn;

            CfnOutput output = new CfnOutput(this, "LogDestinationARN", new CfnOutputProps {
                Description = "LogDestination ARN",
                Value       = logDestination.AttrArn
            });
        }
Example #18
0
    // Create new code groups using the custom named permission sets previously created. 
    private static void CreateCodeGroups()
    {
        // Create instances of the named permission sets created earlier to establish the 
        // permissions for the new code groups.
        NamedPermissionSet companyCodeSet = new NamedPermissionSet("MyCompany",PermissionState.Unrestricted);
        NamedPermissionSet departmentCodeSet = new NamedPermissionSet("MyDepartment",PermissionState.Unrestricted);
        // Create new code groups using the named permission sets.
        PolicyStatement policyMyCompany = new PolicyStatement(companyCodeSet,PolicyStatementAttribute.LevelFinal);
        PolicyStatement policyMyDepartment = new PolicyStatement(departmentCodeSet,PolicyStatementAttribute.Exclusive);
        // Create new code groups using UnionCodeGroup.
        CodeGroup myCompanyZone = new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.Intranet), policyMyCompany);
        myCompanyZone.Name = "MyCompanyCodeGroup";

        byte[] b1 = { 0, 36, 0, 0, 4, 128, 0, 0, 148, 0, 0, 0, 6, 2, 0, 0, 0, 36, 0, 0, 82, 83, 65, 49, 0, 4, 0, 0, 1, 0, 1, 0, 237, 146, 145, 51, 34, 97, 123, 196, 90, 174, 41, 170, 173, 221, 41, 193, 175, 39, 7, 151, 178, 0, 230, 152, 218, 8, 206, 206, 170,84, 111, 145, 26, 208, 158, 240, 246, 219, 228, 34, 31, 163, 11, 130, 16, 199, 111, 224, 4, 112, 46, 84, 0, 104, 229, 38, 39, 63, 53, 189, 0, 157, 32, 38, 34, 109, 0, 171, 114, 244, 34, 59, 9, 232, 150, 192, 247, 175, 104, 143, 171, 42, 219, 66, 66, 194, 191, 218, 121, 59, 92, 42, 37, 158, 13, 108, 210, 189, 9, 203, 204, 32, 48, 91, 212, 101, 193, 19, 227, 107, 25, 133, 70, 2, 220, 83, 206, 71, 102, 245, 104, 252, 87, 109, 190, 56, 34, 180};
        StrongNamePublicKeyBlob blob = new StrongNamePublicKeyBlob(b1);

        CodeGroup myDepartmentZone = new UnionCodeGroup(new StrongNameMembershipCondition(blob, null, null), policyMyDepartment);
        myDepartmentZone.Name = "MyDepartmentCodeGroup";

        // Move through the policy levels looking for the Machine policy level. 
        // Create two new code groups at that level.
        IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy();
        while(policyEnumerator.MoveNext())
        {
            // At the Machine level delete already existing copies of the custom code groups, 
            // then create the new code groups.
            PolicyLevel currentLevel = (PolicyLevel)policyEnumerator.Current;
            if (currentLevel.Label == "Machine")
            {

                // Remove old instances of the custom groups.
                DeleteCustomCodeGroups();
                // Add the new code groups. 
                //******************************************************* 
                // To add a child code group, add the child to the parent prior to adding 
                // the parent to the root.
                myCompanyZone.AddChild(myDepartmentZone);
                // Add the parent to the root code group.
                currentLevel.RootCodeGroup.AddChild(myCompanyZone);
                SecurityManager.SavePolicy();
            }
        }
        // Save the security policy.
        SecurityManager.SavePolicy();
        Console.WriteLine("Security policy modified.");
        Console.WriteLine("New code groups added at the Machine policy level.");
    }
 public static PolicyStatement Deny(this PolicyStatement statement)
 {
     return(statement.WithEffect(Effect.DENY));
 }
        public void Attribute_Invalid()
        {
            PolicyStatement ps = new PolicyStatement(null);

            ps.Attributes = (PolicyStatementAttribute)Int32.MinValue;
        }
        internal PipelineStack(Construct scope, string id, Configuration configuration, IStackProps props = null) : base(scope, id, props)
        {
            var repository = Repository.FromRepositoryArn(this, "Repository", configuration.Source.RepositoryArn);

            var sourceArtifact = new Artifact_();
            var outputArtifact = new Artifact_();
            var ecrPolicy      = new PolicyStatement(new PolicyStatementProps
            {
                Effect    = Effect.ALLOW,
                Actions   = new[] { "ecr:*" },
                Resources = new[] { "*" }
            });


            // Setup CodeCommit cross account role access policies if required
            IRole codeCommitRole = null;

            if (!string.IsNullOrWhiteSpace(configuration.Source.CrossAccountRoleArn))
            {
                codeCommitRole = Role.FromRoleArn(this, "CodeCommitRole", configuration.Source.CrossAccountRoleArn, new FromRoleArnOptions()
                {
                    Mutable = false // Flag to indicate CDK to not modify the role
                });
            }


            // Self mutation
            var pipeline = new CdkPipeline(this, "Pipeline", new CdkPipelineProps
            {
                PipelineName          = Configuration.ProjectName,
                CloudAssemblyArtifact = outputArtifact,

                SourceAction = new CodeCommitSourceAction(new CodeCommitSourceActionProps
                {
                    ActionName = "CodeCommit",
                    Output     = sourceArtifact,
                    Repository = repository,
                    Branch     = configuration.Source.BranchName,
                    Role       = codeCommitRole,
                    Trigger    = CodeCommitTrigger.POLL
                }),

                // It synthesizes CDK code to cdk.out directory which is picked by SelfMutate stage to mutate the pipeline
                SynthAction = new SimpleSynthAction(new SimpleSynthActionProps
                {
                    SourceArtifact        = sourceArtifact,
                    CloudAssemblyArtifact = outputArtifact,
                    Subdirectory          = "LambdaRuntimeDockerfiles/dotnet5/Infrastructure",
                    InstallCommands       = new[]
                    {
                        "npm install -g aws-cdk",
                    },
                    BuildCommands            = new[] { "dotnet build" },
                    SynthCommand             = "cdk synth",
                    CopyEnvironmentVariables = new[]
                    {
                        "SOURCE_REPOSITORY_ARN",
                        "SOURCE_BRANCH_NAME",
                        "SOURCE_CROSS_ACCOUNT_ROLE_ARN",
                        "BASE_ECRS",
                        "STAGE_ECR",
                        "BETA_ECRS",
                        "PROD_ECRS",
                        "ECR_REPOSITORY_NAME",
                    }
                })
            });


            // Stage
            var dockerBuild = new Project(this, "DockerBuild", new ProjectProps()
            {
                BuildSpec   = BuildSpec.FromSourceFilename($"{Configuration.ProjectRoot}/DockerBuild/buildspec.yml"),
                Description = $"Builds and pushes image to {configuration.Ecrs.Stage}",
                Environment = new BuildEnvironment()
                {
                    BuildImage = LinuxBuildImage.AMAZON_LINUX_2_3,
                    Privileged = true
                },
                Source = Amazon.CDK.AWS.CodeBuild.Source.CodeCommit(new CodeCommitSourceProps()
                {
                    Repository  = repository,
                    BranchOrRef = configuration.Source.BranchName
                }),
                EnvironmentVariables = new Dictionary <string, IBuildEnvironmentVariable>
                {
                    { "BASE_ECRS", new BuildEnvironmentVariable()
                      {
                          Value = configuration.Ecrs.Base
                      } },
                    { "STAGE_ECR", new BuildEnvironmentVariable {
                          Value = configuration.Ecrs.Stage
                      } },
                    { "ECR_REPOSITORY_NAME", new BuildEnvironmentVariable {
                          Value = configuration.EcrRepositoryName
                      } }
                }
            });

            dockerBuild.AddToRolePolicy(ecrPolicy);

            var dockerBuildStage = pipeline.AddStage("Stage-DockerBuild");

            dockerBuildStage.AddActions(new CodeBuildAction(new CodeBuildActionProps()
            {
                Input      = sourceArtifact,
                Project    = dockerBuild,
                ActionName = "DockerBuild"
            }));


            // Beta
            var betaDockerPush = new Project(this, "Beta-DockerPush", new ProjectProps()
            {
                BuildSpec   = BuildSpec.FromSourceFilename($"{Configuration.ProjectRoot}/DockerPush/buildspec.yml"),
                Description = $"Pushes staged image to {configuration.Ecrs.Beta}",
                Environment = new BuildEnvironment()
                {
                    BuildImage = LinuxBuildImage.AMAZON_LINUX_2_3,
                    Privileged = true
                },
                Source = Amazon.CDK.AWS.CodeBuild.Source.CodeCommit(new CodeCommitSourceProps()
                {
                    Repository  = repository,
                    BranchOrRef = configuration.Source.BranchName
                }),
                EnvironmentVariables = new Dictionary <string, IBuildEnvironmentVariable>
                {
                    { "SOURCE_ECR", new BuildEnvironmentVariable {
                          Value = configuration.Ecrs.Stage
                      } },
                    { "ECR_REPOSITORY_NAME", new BuildEnvironmentVariable {
                          Value = configuration.EcrRepositoryName
                      } },
                    { "DESTINATION_ECRS", new BuildEnvironmentVariable {
                          Value = configuration.Ecrs.Beta
                      } },
                    { "DESTINATION_IMAGE_TAG", new BuildEnvironmentVariable {
                          Value = "beta"
                      } },
                }
            });

            betaDockerPush.AddToRolePolicy(ecrPolicy);

            var betaDockerPushStage = pipeline.AddStage("Beta-DockerPush");

            betaDockerPushStage.AddActions(new CodeBuildAction(new CodeBuildActionProps()
            {
                Input      = sourceArtifact,
                Project    = betaDockerPush,
                ActionName = "DockerPush"
            }));


            // Manual Approval
            var manualApprovalStage = pipeline.AddStage("Prod-ManualApproval");

            manualApprovalStage.AddActions(new ManualApprovalAction(new ManualApprovalActionProps()
            {
                ActionName = "ManualApproval"
            }));


            // Prod
            var prodDockerPush = new Project(this, "Prod-DockerPush", new ProjectProps()
            {
                BuildSpec   = BuildSpec.FromSourceFilename($"{Configuration.ProjectRoot}/DockerPush/buildspec.yml"),
                Description = $"Pushes staged image to {configuration.Ecrs.Prod}",
                Environment = new BuildEnvironment()
                {
                    BuildImage = LinuxBuildImage.AMAZON_LINUX_2_3,
                    Privileged = true
                },
                Source = Amazon.CDK.AWS.CodeBuild.Source.CodeCommit(new CodeCommitSourceProps()
                {
                    Repository  = repository,
                    BranchOrRef = "dotnet5/cdk"
                }),
                EnvironmentVariables = new Dictionary <string, IBuildEnvironmentVariable>
                {
                    { "SOURCE_ECR", new BuildEnvironmentVariable {
                          Value = configuration.Ecrs.Stage
                      } },
                    { "ECR_REPOSITORY_NAME", new BuildEnvironmentVariable {
                          Value = configuration.EcrRepositoryName
                      } },
                    { "DESTINATION_ECRS", new BuildEnvironmentVariable {
                          Value = configuration.Ecrs.Prod
                      } },
                    { "DESTINATION_IMAGE_TAG", new BuildEnvironmentVariable {
                          Value = "beta"
                      } },                                                                    // Prod images are also tagged as beta
                }
            });

            prodDockerPush.AddToRolePolicy(ecrPolicy);

            var prodDockerPushStage = pipeline.AddStage("Prod-DockerPush");

            prodDockerPushStage.AddActions(new CodeBuildAction(new CodeBuildActionProps()
            {
                Input      = sourceArtifact,
                Project    = prodDockerPush,
                ActionName = "DockerPush"
            }));
        }
        public void FromXml_SecurityElementNull()
        {
            PolicyStatement ps = new PolicyStatement(null);

            ps.FromXml(null, PolicyLevel.CreateAppDomainLevel());
        }
Example #23
0
        public void ResolveWithChildren()
        {
            PermissionSet pset1 = new PermissionSet(PermissionState.None);
            PermissionSet pset2 = new PermissionSet(PermissionState.None);
            PermissionSet pset3 = new PermissionSet(PermissionState.None);
            PermissionSet pset4 = new PermissionSet(PermissionState.None);
            PermissionSet pset5 = new PermissionSet(PermissionState.None);
            PermissionSet pset6 = new PermissionSet(PermissionState.None);

            IPermission perm1 = new UIPermission(PermissionState.Unrestricted);
            IPermission perm2 = new EnvironmentPermission(PermissionState.Unrestricted);
            IPermission perm3 = new FileDialogPermission(PermissionState.Unrestricted);
            IPermission perm4 = new ReflectionPermission(PermissionState.Unrestricted);
            IPermission perm5 = new RegistryPermission(PermissionState.Unrestricted);
            IPermission perm6 = new FileIOPermission(PermissionState.Unrestricted);

            pset1.AddPermission(perm1);
            PolicyStatement policy1 = new PolicyStatement(pset1);

            pset2.AddPermission(perm2);
            PolicyStatement policy2 = new PolicyStatement(pset2);

            pset3.AddPermission(perm3);
            PolicyStatement policy3 = new PolicyStatement(pset3);

            pset4.AddPermission(perm4);
            PolicyStatement policy4 = new PolicyStatement(pset4);

            pset5.AddPermission(perm5);
            PolicyStatement policy5 = new PolicyStatement(pset5);

            pset6.AddPermission(perm6);
            PolicyStatement policy6 = new PolicyStatement(pset6);

            UnionCodeGroup root = new UnionCodeGroup(new AllMembershipCondition(), policy1);

            UnionCodeGroup child1        = new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.Internet), policy2);
            UnionCodeGroup child2        = new UnionCodeGroup(new AllMembershipCondition(), policy3);
            UnionCodeGroup child3        = new UnionCodeGroup(new AllMembershipCondition(), policy4);
            UnionCodeGroup childofchild1 = new UnionCodeGroup(new AllMembershipCondition(), policy5);
            UnionCodeGroup childofchild3 = new UnionCodeGroup(new AllMembershipCondition(), policy6);

            child1.AddChild(childofchild1);
            child3.AddChild(childofchild3);

            root.AddChild(child1);
            root.AddChild(child2);
            root.AddChild(child3);

            PolicyStatement result = root.Resolve(new Evidence());

            PermissionSet correctset = new PermissionSet(PermissionState.None);

            correctset.AddPermission(perm1);
            correctset.AddPermission(perm3);
            correctset.AddPermission(perm4);
            correctset.AddPermission(perm6);

            Assert.AreEqual(correctset.Count, result.PermissionSet.Count, "PermissionSet.Count");
            foreach (IPermission p in correctset)
            {
                IPermission r = result.PermissionSet.GetPermission(p.GetType());
                Assert.IsNotNull(r, "PermissionSet.GetPermission");
            }
        }
 public static PolicyStatement Allow(this PolicyStatement statement)
 {
     return(statement.WithEffect(Effect.ALLOW));
 }
Example #25
0
        }// AddMenuItems

        internal override void MenuCommand(int nCommandID)
        {
            if (nCommandID == COMMANDS.CREATE_CODEGROUP)
            {
                CNewCodeGroupWizard wiz = new CNewCodeGroupWizard(m_pl);
                wiz.LaunchWizard(Cookie);
                // Ok, let's see what goodies we have...
                String sPermSetName = null;
                if (wiz.CreatedPermissionSet != null)
                {
                    sPermSetName = AddPermissionSet(wiz.CreatedPermissionSet).DisplayName;
                    SecurityPolicyChanged();
                }
                if (wiz.CreatedCodeGroup != null)
                {
                    try
                    {
                        CodeGroup cg = wiz.CreatedCodeGroup;
                        if (sPermSetName != null)
                        {
                            PermissionSet   ps   = m_pl.GetNamedPermissionSet(sPermSetName);
                            PolicyStatement pols = cg.PolicyStatement;
                            pols.PermissionSet = ps;
                            cg.PolicyStatement = pols;
                        }
                        CSingleCodeGroup node = AddCodeGroup(wiz.CreatedCodeGroup);
                        // Put the focus on the newly created codegroup
                        CNodeManager.SelectScopeItem(node.HScopeItem);
                    }
                    catch (Exception)
                    {
                        MessageBox(CResourceStore.GetString("CSingleCodeGroup:ErrorCreatingCodegroup"),
                                   CResourceStore.GetString("CSingleCodeGroup:ErrorCreatingCodegroupTitle"),
                                   MB.ICONEXCLAMATION);
                    }
                }
            }
            else if (nCommandID == COMMANDS.DUPLICATE_CODEGROUP)
            {
                CNode node;

                CodeGroup newcg = m_cg.Copy();

                // Change this code group's name

                String sBaseName = newcg.Name;
                newcg.Name = String.Format(CResourceStore.GetString("CSingleCodeGroup:PrependtoDupCodegroups"), newcg.Name);
                int nCounter = 1;
                // make sure it's not already used
                while (Security.isCodeGroupNameUsed(m_pl.RootCodeGroup, newcg.Name))
                {
                    nCounter++;
                    newcg.Name = String.Format(CResourceStore.GetString("CSingleCodeGroup:NumPrependtoDupCodegroups"), nCounter.ToString(), sBaseName);
                }

                CNode newCodeGroup = null;
                // If we are the root codegroup, then we'll add this as a child
                if (Security.GetRootCodeGroupNode(m_pl) == this)
                {
                    newCodeGroup = AddCodeGroup(newcg);
                    node         = this;
                }
                else
                {
                    node         = CNodeManager.GetNodeByHScope(ParentHScopeItem);
                    newCodeGroup = ((CSingleCodeGroup)node).AddCodeGroup(newcg);
                }

                // Select the new item
                CNodeManager.SelectScopeItem(newCodeGroup.HScopeItem);
            }
        }// MenuCommand
 public static PolicyStatement WithNotActions(this PolicyStatement statement, params string[] actions)
 {
     statement.AddNotActions(actions);
     return(statement);
 }
Example #27
0
        public KinesisFirehoseStack(Construct parent, string id, KinesisFirehoseStackProps props) : base(parent, id,
                                                                                                         props)
        {
            var clicksDestinationBucket = new Bucket(this, "Bucket", new BucketProps
            {
                Versioned = true
            });

            var firehoseDeliveryRole = new Role(this, "FirehoseDeliveryRole", new RoleProps
            {
                RoleName    = "FirehoseDeliveryRole",
                AssumedBy   = new ServicePrincipal("firehose.amazonaws.com"),
                ExternalIds = new string[]
                {
                    Aws.ACCOUNT_ID
                }
            });

            var firehoseDeliveryPolicyS3Stm = new PolicyStatement();

            firehoseDeliveryPolicyS3Stm.AddActions("s3:AbortMultipartUpload",
                                                   "s3:GetBucketLocation",
                                                   "s3:GetObject",
                                                   "s3:ListBucket",
                                                   "s3:ListBucketMultipartUploads",
                                                   "s3:PutObject");
            firehoseDeliveryPolicyS3Stm.AddResources(clicksDestinationBucket.BucketArn);
            firehoseDeliveryPolicyS3Stm.AddResources(clicksDestinationBucket.ArnForObjects("*"));

            var lambdaFunctionPolicy = new PolicyStatement();

            lambdaFunctionPolicy.AddActions("dynamodb:GetItem");
            lambdaFunctionPolicy.AddResources(props.TableArn);
            var LambdaFunctionPolicyStmXRay = new PolicyStatement();

            LambdaFunctionPolicyStmXRay.AddActions(
                //  Allows the Lambda function to interact with X-Ray
                "xray:PutTraceSegments",
                "xray:PutTelemetryRecords",
                "xray:GetSamplingRules",
                "xray:GetSamplingTargets",
                "xray:GetSamplingStatisticSummaries"
                );
            LambdaFunctionPolicyStmXRay.AddAllResources();
            var mysfitsClicksProcessor = new Function(this, "Function", new FunctionProps
            {
                Handler     = "streaming_lambda::streaming_lambda.function::FunctionHandlerAsync",
                Runtime     = Runtime.DOTNET_CORE_2_1,
                Description = "An Amazon Kinesis Firehose stream processor that enriches click records" +
                              " to not just include a mysfitId, but also other attributes that can be analyzed later.",
                MemorySize    = 128,
                Code          = Code.FromAsset("../lambda/stream/bin/Debug/netcoreapp2.1/Publish"),
                Timeout       = Duration.Seconds(30),
                Tracing       = Tracing.ACTIVE,
                InitialPolicy = new PolicyStatement[]
                {
                    lambdaFunctionPolicy,
                    LambdaFunctionPolicyStmXRay
                },
                Environment = new Dictionary <string, string>()
                {
                    {
                        "mysfits_api_url",
                        string.Format($"https://${props.APIid}.execute-api.{Amazon.CDK.Aws.REGION}.amazonaws.com/prod/")
                    }
                }
            });

            var firehoseDeliveryPolicyLambdaStm = new PolicyStatement();

            firehoseDeliveryPolicyLambdaStm.AddActions("lambda:InvokeFunction");
            firehoseDeliveryPolicyLambdaStm.AddResources(mysfitsClicksProcessor.FunctionArn);
            firehoseDeliveryRole.AddToPolicy(firehoseDeliveryPolicyS3Stm);
            firehoseDeliveryRole.AddToPolicy(firehoseDeliveryPolicyLambdaStm);

            var mysfitsFireHoseToS3 = new CfnDeliveryStream(this, "DeliveryStream", new CfnDeliveryStreamProps
            {
                ExtendedS3DestinationConfiguration = new CfnDeliveryStream.ExtendedS3DestinationConfigurationProperty()
                {
                    BucketArn      = clicksDestinationBucket.BucketArn,
                    BufferingHints = new CfnDeliveryStream.BufferingHintsProperty
                    {
                        IntervalInSeconds = 60,
                        SizeInMBs         = 50
                    },
                    CompressionFormat       = "UNCOMPRESSED",
                    Prefix                  = "firehose/",
                    RoleArn                 = firehoseDeliveryRole.RoleArn,
                    ProcessingConfiguration = new CfnDeliveryStream.ProcessingConfigurationProperty
                    {
                        Enabled    = true,
                        Processors = new CfnDeliveryStream.ProcessorProperty[]
                        {
                            new CfnDeliveryStream.ProcessorProperty()
                            {
                                Type       = "Lambda",
                                Parameters = new CfnDeliveryStream.ProcessorParameterProperty
                                {
                                    ParameterName  = "LambdaArn",
                                    ParameterValue = mysfitsClicksProcessor.FunctionArn
                                }
                            }
                        }
                    }
                }
            });

            new CfnPermission(this, "Permission", new CfnPermissionProps
            {
                Action        = "lambda:InvokeFunction",
                FunctionName  = mysfitsClicksProcessor.FunctionArn,
                Principal     = "firehose.amazonaws.com",
                SourceAccount = Amazon.CDK.Aws.ACCOUNT_ID,
                SourceArn     = mysfitsFireHoseToS3.AttrArn
            });

            var clickProcessingApiRole = new Role(this, "ClickProcessingApiRole", new RoleProps
            {
                AssumedBy = new ServicePrincipal("apigateway.amazonaws.com")
            });

            var apiPolicy = new PolicyStatement();

            apiPolicy.AddActions("firehose:PutRecord");
            apiPolicy.AddResources(mysfitsFireHoseToS3.AttrArn);
            new Policy(this, "ClickProcessingApiPolicy", new PolicyProps
            {
                PolicyName = "api_gateway_firehose_proxy_role",
                Statements = new PolicyStatement[]
                {
                    apiPolicy
                },
                Roles = new[] { clickProcessingApiRole }
            });

            var api = new RestApi(this, "APIEndpoint", new RestApiProps
            {
                RestApiName    = "ClickProcessing API Service",
                CloudWatchRole = false,
                EndpointTypes  = new EndpointType[]
                {
                    EndpointType.REGIONAL
                }
            });

            var clicks = api.Root.AddResource("clicks");

            clicks.AddMethod("PUT", new AwsIntegration(new AwsIntegrationProps
            {
                Service = "firehose",
                IntegrationHttpMethod = "POST",
                Action  = "PutRecord",
                Options = new IntegrationOptions
                {
                    ConnectionType       = ConnectionType.INTERNET,
                    CredentialsRole      = clickProcessingApiRole,
                    IntegrationResponses = new IntegrationResponse[]
                    {
                        new IntegrationResponse()
                        {
                            StatusCode        = "200",
                            ResponseTemplates =
                            {
                                { "application/json", "{\"status\":\"OK\"}" }
                            },
                            ResponseParameters =
                            {
                                { "method.response.header.Access-Control-Allow-Headers", "'Content-Type'" },
                                { "method.response.header.Access-Control-Allow-Methods", "'OPTIONS,PUT'"  },
                                { "method.response.header.Access-Control-Allow-Origin",  "'*'"            }
                            }
                        }
                    },
                    RequestParameters =
                    {
                        { "integration.request.header.Content-Type", "'application/x-amz-json-1.1'" }
                    },
                    RequestTemplates =
                    {
                        {
                            "application/json",
                            "{\"DeliveryStreamName\":\"" + mysfitsFireHoseToS3.Ref +
                            "\", \"Record\": { \"Data\": \"$util.base64Encode($input.json('$'))\"}"
                        }
                    }
                }
            }),
                             new MethodOptions
            {
                MethodResponses = new MethodResponse[]
                {
                    new MethodResponse
                    {
                        StatusCode         = "200",
                        ResponseParameters =
                        {
                            { "method.response.header.Access-Control-Allow-Headers", true },
                            { "method.response.header.Access-Control-Allow-Methods", true },
                            { "method.response.header.Access-Control-Allow-Origin",  true }
                        }
                    }
                }
            });

            clicks.AddMethod("OPTIONS", new MockIntegration(new IntegrationOptions
            {
                IntegrationResponses = new IntegrationResponse[]
                {
                    new IntegrationResponse
                    {
                        StatusCode         = "200",
                        ResponseParameters = new Dictionary <string, string>
                        {
                            {
                                "method.response.header.Access-Control-Allow-Headers",
                                "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'"
                            },
                            { "method.response.header.Access-Control-Allow-Origin", "'*'" },
                            { "method.response.header.Access-Control-Allow-Credentials", "'false'" },
                            { "method.response.header.Access-Control-Allow-Methods", "'OPTIONS,GET,PUT,POST,DELETE'" }
                        }
                    }
                },
                PassthroughBehavior = PassthroughBehavior.NEVER,
                RequestTemplates    = new Dictionary <string, string>
                {
                    { "application/json", "{\"statusCode\": 200}" }
                }
            }),
                             new MethodOptions
            {
                MethodResponses = new MethodResponse[]
                {
                    new MethodResponse
                    {
                        StatusCode         = "200",
                        ResponseParameters = new Dictionary <string, bool>
                        {
                            { "method.response.header.Access-Control-Allow-Headers", true },
                            { "method.response.header.Access-Control-Allow-Methods", true },
                            { "method.response.header.Access-Control-Allow-Credentials", true },
                            { "method.response.header.Access-Control-Allow-Origin", true }
                        }
                    }
                }
            });
        }
 public static PolicyStatement WithNotResources(this PolicyStatement statement, params string[] resources)
 {
     statement.AddNotResources(resources);
     return(statement);
 }
Example #29
0
 // Constructors
 public UnionCodeGroup(IMembershipCondition membershipCondition, PolicyStatement policy)
 {
 }
        public TheEventbridgeAtmStack(Construct scope, string id, IStackProps props = null)
            : base(scope, id, props)
        {
            //Producer Lambda
            var atmProducerLambda = new Function(this, "atmProducerLambda", new FunctionProps
            {
                Runtime = Runtime.NODEJS_12_X,
                Code    = Code.FromAsset("lambda-fns/atmProducer"),
                Handler = "handler.lambdaHandler"
            });

            var eventPolicy = new PolicyStatement(new PolicyStatementProps
            {
                Effect    = Effect.ALLOW,
                Resources = new[] { "*" },
                Actions   = new[] { "events:PutEvents" }
            });

            atmProducerLambda.AddToRolePolicy(eventPolicy);

            //Approved Transaction Consumer
            var atmConsumer1Lambda = new Function(this, "atmConsumer1Lambda", new FunctionProps
            {
                Runtime = Runtime.NODEJS_12_X,
                Code    = Code.FromAsset("lambda-fns/atmConsumer"),
                Handler = "handler.case1Handler"
            });

            var atmConsumer1LambdaRule = new Rule(this, "atmConsumer1LambdaRule", new RuleProps
            {
                Description  = "Approved transactions",
                EventPattern = new EventPattern
                {
                    Source     = new[] { "custom.myATMapp" },
                    DetailType = new[] { "transaction" },
                    Detail     = new Dictionary <string, object>
                    {
                        ["result"] = new[] { "approved" }
                    }
                }
            });

            atmConsumer1LambdaRule.AddTarget(new LambdaFunction(atmConsumer1Lambda));

            //NY Prefix Consumer
            var atmConsumer2Lambda = new Function(this, "atmConsumer2Lambda", new FunctionProps
            {
                Runtime = Runtime.NODEJS_12_X,
                Code    = Code.FromAsset("lambda-fns/atmConsumer"),
                Handler = "handler.case2Handler"
            });

            var atmConsumer2LambdaRule = new Rule(this, "atmConsumer2LambdaRule", new RuleProps
            {
                Description  = "Transactions with NY- prefix",
                EventPattern = new EventPattern
                {
                    Source     = new[] { "custom.myATMapp" },
                    DetailType = new[] { "transaction" },
                    Detail     = new Dictionary <string, object>
                    {
                        ["location"] = new []
                        {
                            new Dictionary <string, string>
                            {
                                ["prefix"] = "NY-"
                            }
                        }
                    }
                }
            });

            atmConsumer2LambdaRule.AddTarget(new LambdaFunction(atmConsumer2Lambda));

            //Not Approved Consumer
            var atmConsumer3Lambda = new Function(this, "atmConsumer3Lambda", new FunctionProps
            {
                Runtime = Runtime.NODEJS_12_X,
                Code    = Code.FromAsset("lambda-fns/atmConsumer"),
                Handler = "handler.case3Handler"
            });

            var atmConsumer3LambdaRule = new Rule(this, "atmConsumer3LambdaRule", new RuleProps
            {
                Description  = "Not approved transactions",
                EventPattern = new EventPattern
                {
                    Source     = new[] { "custom.myATMapp" },
                    DetailType = new[] { "transaction" },
                    Detail     = new Dictionary <string, object>
                    {
                        ["result"] = new[]
                        {
                            new Dictionary <string, object>
                            {
                                ["anything-but"] = "approved"
                            }
                        }
                    }
                }
            });

            atmConsumer3LambdaRule.AddTarget(new LambdaFunction(atmConsumer3Lambda));

            //API Gateway proxy integration
            // defines an API Gateway REST API resource backed by our "atmProducerLambda" function.
            new LambdaRestApi(this, "Endpoint", new LambdaRestApiProps
            {
                Handler = atmProducerLambda
            });
        }
 // Constructors
 public UnionCodeGroup(IMembershipCondition membershipCondition, PolicyStatement policy)
 {
 }
Example #32
0
 public FirstMatchCodeGroup(IMembershipCondition membershipCondition, PolicyStatement policy)
     : base(default(IMembershipCondition), default(PolicyStatement))
 {
 }
        public XRayStack(Construct parent, string id) : base(parent, id)
        {
            var table = new Table(this, "Table", new TableProps()
            {
                TableName    = "MysfitsQuestionsTable",
                PartitionKey = new Attribute
                {
                    Name = "QuestionId",
                    Type = AttributeType.STRING
                },
                Stream = StreamViewType.NEW_IMAGE
            });

            var postQuestionLambdaFunctionPolicyStmDDB = new PolicyStatement();

            postQuestionLambdaFunctionPolicyStmDDB.AddActions("dynamodb:PutItem");
            postQuestionLambdaFunctionPolicyStmDDB.AddResources(table.TableArn);

            var LambdaFunctionPolicyStmXRay = new PolicyStatement();

            LambdaFunctionPolicyStmXRay.AddActions(
                //  Allows the Lambda function to interact with X-Ray
                "xray:PutTraceSegments",
                "xray:PutTelemetryRecords",
                "xray:GetSamplingRules",
                "xray:GetSamplingTargets",
                "xray:GetSamplingStatisticSummaries"
                );
            LambdaFunctionPolicyStmXRay.AddAllResources();

            var mysfitsPostQuestion = new Function(this, "PostQuestionFunction", new FunctionProps
            {
                Handler     = "mysfitsPostQuestion.postQuestion",
                Runtime     = Runtime.PYTHON_3_6,
                Description =
                    "A microservice Lambda function that receives a new question submitted to the MythicalMysfits website from a user and inserts it into a DynamoDB database table.",
                MemorySize    = 128,
                Code          = Code.FromAsset("../../lambda-questions/PostQuestionsService"),
                Timeout       = Duration.Seconds(30),
                InitialPolicy = new[]
                {
                    postQuestionLambdaFunctionPolicyStmDDB,
                    LambdaFunctionPolicyStmXRay
                },
                Tracing = Tracing.ACTIVE
            });

            var topic = new Topic(this, "Topic", new TopicProps
            {
                DisplayName = "MythicalMysfitsQuestionsTopic",
                TopicName   = "MythicalMysfitsQuestionsTopic"
            });

            topic.AddSubscription(new EmailSubscription("REPLACE@EMAIL_ADDRESS"));

            var postQuestionLambdaFunctionPolicyStmSNS = new PolicyStatement();

            postQuestionLambdaFunctionPolicyStmSNS.AddActions("sns:Publish");
            postQuestionLambdaFunctionPolicyStmSNS.AddResources(topic.TopicArn);

            var mysfitsProcessQuestionStream = new Function(this, "ProcessQuestionStreamFunction", new FunctionProps
            {
                Handler     = "mysfitsProcessStream.processStream",
                Runtime     = Runtime.PYTHON_3_6,
                Description =
                    "An AWS Lambda function that will process all new questions posted to mythical mysfits" +
                    " and notify the site administrator of the question that was asked.",
                MemorySize    = 128,
                Code          = Code.FromAsset("../../lambda-questions/ProcessQuestionsStream"),
                Timeout       = Duration.Seconds(30),
                InitialPolicy = new[]
                {
                    postQuestionLambdaFunctionPolicyStmSNS,
                    LambdaFunctionPolicyStmXRay
                },
                Tracing     = Tracing.ACTIVE,
                Environment = new Dictionary <string, string>()
                {
                    { "SNS_TOPIC_ARN", topic.TopicArn }
                },
                Events = new IEventSource[]
                {
                    new DynamoEventSource(table, new DynamoEventSourceProps
                    {
                        StartingPosition = StartingPosition.TRIM_HORIZON,
                        BatchSize        = 1
                    })
                }
            });

            var questionsApiRole = new Role(this, "QuestionsApiRole", new RoleProps
            {
                AssumedBy = new ServicePrincipal("apigateway.amazonaws.com")
            });

            var apiPolicy = new PolicyStatement();

            apiPolicy.AddActions("lambda:InvokeFunction");
            apiPolicy.AddResources(mysfitsPostQuestion.FunctionArn);
            new Policy(this, "QuestionsApiPolicy", new PolicyProps
            {
                PolicyName = "questions_api_policy",
                Statements = new[]
                {
                    apiPolicy
                },
                Roles = new IRole[]
                {
                    questionsApiRole
                }
            });

            var questionsIntegration = new LambdaIntegration(mysfitsPostQuestion, new LambdaIntegrationOptions
            {
                CredentialsRole      = questionsApiRole,
                IntegrationResponses = new IntegrationResponse[]
                {
                    new IntegrationResponse()
                    {
                        StatusCode        = "200",
                        ResponseTemplates = new Dictionary <string, string>
                        {
                            { "application/json", "{\"status\":\"OK\"}" }
                        }
                    }
                }
            });

            var api = new LambdaRestApi(this, "APIEndpoint", new LambdaRestApiProps
            {
                Handler       = mysfitsPostQuestion,
                RestApiName   = "Questions API Service",
                DeployOptions = new StageOptions
                {
                    TracingEnabled = true
                },
                Proxy = false
            });

            var questionsMethod = api.Root.AddResource("questions");

            questionsMethod.AddMethod("POST", questionsIntegration, new MethodOptions
            {
                MethodResponses = new MethodResponse[]
                {
                    new MethodResponse
                    {
                        StatusCode         = "200",
                        ResponseParameters = new Dictionary <string, bool>()
                        {
                            { "method.response.header.Access-Control-Allow-Headers", true },
                            { "method.response.header.Access-Control-Allow-Methods", true },
                            { "method.response.header.Access-Control-Allow-Origin", true },
                        }
                    }
                },
                AuthorizationType = AuthorizationType.NONE
            });

            questionsMethod.AddMethod("OPTIONS", new MockIntegration(new IntegrationOptions
            {
                IntegrationResponses = new IntegrationResponse[]
                {
                    new IntegrationResponse
                    {
                        StatusCode         = "200",
                        ResponseParameters = new Dictionary <string, string>
                        {
                            {
                                "method.response.header.Access-Control-Allow-Headers",
                                "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'"
                            },
                            { "method.response.header.Access-Control-Allow-Origin", "'*'" },
                            { "method.response.header.Access-Control-Allow-Credentials", "'false'" },
                            { "method.response.header.Access-Control-Allow-Methods", "'OPTIONS,GET,PUT,POST,DELETE'" }
                        }
                    }
                },
                PassthroughBehavior = PassthroughBehavior.NEVER,
                RequestTemplates    = new Dictionary <string, string>
                {
                    { "application/json", "{\"statusCode\": 200}" }
                }
            }),
                                      new MethodOptions
            {
                MethodResponses = new MethodResponse[]
                {
                    new MethodResponse
                    {
                        StatusCode         = "200",
                        ResponseParameters = new Dictionary <string, bool>
                        {
                            { "method.response.header.Access-Control-Allow-Headers", true },
                            { "method.response.header.Access-Control-Allow-Methods", true },
                            { "method.response.header.Access-Control-Allow-Credentials", true },
                            { "method.response.header.Access-Control-Allow-Origin", true }
                        }
                    }
                }
            }
                                      );
        }
 public UnionCodeGroup(IMembershipCondition membershipCondition, PolicyStatement policy) : base(default(IMembershipCondition), default(PolicyStatement))
 {
 }
        public EcsStack(Construct parent, string id, EcsStackProps props) : base(parent, id)
        {
            this.ecsCluster = new Cluster(this, "Cluster", new ClusterProps
            {
                Vpc = props.Vpc,
            });
            this.ecsCluster.Connections.AllowFromAnyIpv4(Port.Tcp(8080));
            Console.Write(props.ecrRepository.RepositoryArn);
            this.ecsService = new NetworkLoadBalancedFargateService(this, "Service", new NetworkLoadBalancedFargateServiceProps()
            {
                Cluster            = this.ecsCluster,
                DesiredCount       = 1,
                PublicLoadBalancer = true,
                TaskImageOptions   = new NetworkLoadBalancedTaskImageOptions
                {
                    EnableLogging = true,
                    ContainerPort = 8080,
                    Image         = ContainerImage.FromEcrRepository(props.ecrRepository),
                }
            }
                                                                    );
            this.ecsService.Service.Connections.AllowFrom(Peer.Ipv4(props.Vpc.VpcCidrBlock), Port.Tcp(8080));

            var taskDefinitionPolicy = new PolicyStatement();

            taskDefinitionPolicy.AddActions(
                // Rules which allow ECS to attach network interfaces to instances
                // on your behalf in order for awsvpc networking mode to work right
                "ec2:AttachNetworkInterface",
                "ec2:CreateNetworkInterface",
                "ec2:CreateNetworkInterfacePermission",
                "ec2:DeleteNetworkInterface",
                "ec2:DeleteNetworkInterfacePermission",
                "ec2:Describe*",
                "ec2:DetachNetworkInterface",

                // Rules which allow ECS to update load balancers on your behalf
                //  with the information sabout how to send traffic to your containers
                "elasticloadbalancing:DeregisterInstancesFromLoadBalancer",
                "elasticloadbalancing:DeregisterTargets",
                "elasticloadbalancing:Describe*",
                "elasticloadbalancing:RegisterInstancesWithLoadBalancer",
                "elasticloadbalancing:RegisterTargets",

                //  Rules which allow ECS to run tasks that have IAM roles assigned to them.
                "iam:PassRole",

                //  Rules that let ECS create and push logs to CloudWatch.
                "logs:DescribeLogStreams",
                "logs:CreateLogGroup");
            taskDefinitionPolicy.AddAllResources();

            this.ecsService.Service.TaskDefinition.AddToExecutionRolePolicy(
                taskDefinitionPolicy
                );

            var taskRolePolicy = new PolicyStatement();

            taskRolePolicy.AddActions(
                // Allow the ECS Tasks to download images from ECR
                "ecr:GetAuthorizationToken",
                "ecr:BatchCheckLayerAvailability",
                "ecr:GetDownloadUrlForLayer",
                "ecr:BatchGetImage",
                // Allow the ECS tasks to upload logs to CloudWatch
                "logs:CreateLogStream",
                "logs:CreateLogGroup",
                "logs:PutLogEvents"
                );
            taskRolePolicy.AddAllResources();

            this.ecsService.Service.TaskDefinition.AddToTaskRolePolicy(
                taskRolePolicy
                );
        }