Exemplo n.º 1
0
        /// <summary>
        /// Extracts a list of all roles codes mentioned in a permit rule in a policy.
        /// </summary>
        /// <param name="policy">The policy</param>
        /// <returns>List of role codes</returns>
        public static List <string> GetRolesWithAccess(XacmlPolicy policy)
        {
            HashSet <string> roleCodes = new HashSet <string>();

            foreach (XacmlRule rule in policy.Rules)
            {
                if (rule.Effect.Equals(XacmlEffectType.Permit) && rule.Target != null)
                {
                    foreach (XacmlAnyOf anyOf in rule.Target.AnyOf)
                    {
                        foreach (XacmlAllOf allOf in anyOf.AllOf)
                        {
                            foreach (XacmlMatch xacmlMatch in allOf.Matches)
                            {
                                if (xacmlMatch.AttributeDesignator.AttributeId.Equals(AltinnXacmlConstants.MatchAttributeIdentifiers.RoleAttribute))
                                {
                                    roleCodes.Add(xacmlMatch.AttributeValue.Value);
                                }
                            }
                        }
                    }
                }
            }

            return(roleCodes.ToList());
        }
        private XacmlContextResponse SetuUpPolicyDecisionPoint(string testCase, bool contextRequstIsEnriched)
        {
            XacmlContextRequest contextRequest         = XacmlTestDataParser.ParseRequest(testCase + "Request.xml", GetConformancePath());
            XacmlContextRequest contextRequestEnriched = contextRequest;

            if (contextRequstIsEnriched)
            {
                contextRequestEnriched = XacmlTestDataParser.ParseRequest(testCase + "Request_Enriched.xml", GetConformancePath());
            }

            Moq.Mock <IContextHandler> moqContextHandler = new Mock <IContextHandler>();
            moqContextHandler.Setup(c => c.Enrich(It.IsAny <XacmlContextRequest>())).ReturnsAsync(contextRequestEnriched);

            Moq.Mock <IPolicyRetrievalPoint> moqPRP = new Mock <IPolicyRetrievalPoint>();

            XacmlPolicy policy = null;

            try
            {
                policy = XacmlTestDataParser.ParsePolicy(testCase + "Policy.xml", GetConformancePath());
                moqPRP.Setup(p => p.GetPolicyAsync(It.IsAny <XacmlContextRequest>())).ReturnsAsync(policy);
            }
            catch (XmlException ex)
            {
                moqPRP.Setup(p => p.GetPolicyAsync(It.IsAny <XacmlContextRequest>())).Throws(ex);
            }

            PolicyDecisionPoint pdp = new PolicyDecisionPoint();

            XacmlContextResponse xacmlResponse = pdp.Authorize(contextRequestEnriched, policy);

            return(xacmlResponse);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Gets the entire policy as a list of <see cref="ResourcePolicy"/>.
        /// </summary>
        /// <param name="policy">The policy</param>
        /// <param name="language">The language (not in use yet; exactly how is yet to be determined)</param>
        /// <returns>List of resource policies</returns>
        public static List <ResourcePolicy> GetResourcePoliciesFromXacmlPolicy(XacmlPolicy policy, string language)
        {
            Dictionary <string, ResourcePolicy> resourcePolicies = new Dictionary <string, ResourcePolicy>();

            foreach (XacmlRule rule in policy.Rules)
            {
                if (rule.Effect.Equals(XacmlEffectType.Permit) && rule.Target != null)
                {
                    List <RoleGrant> roles = GetRolesFromRule(rule);
                    if (roles.Count == 0)
                    {
                        continue;
                    }

                    List <string>         policyKeys = GetResourcePoliciesFromRule(resourcePolicies, rule);
                    List <ResourceAction> actions    = GetActionsFromRule(rule, roles);

                    foreach (string policyKey in policyKeys)
                    {
                        ResourcePolicy resourcePolicy = resourcePolicies.GetValueOrDefault(policyKey);

                        if (policy.Description != null && resourcePolicy.Description == null)
                        {
                            resourcePolicy.Description = policy.Description;
                        }

                        AddActionsToResourcePolicy(actions, resourcePolicy);
                    }
                }
            }

            return(resourcePolicies.Values.ToList());
        }
Exemplo n.º 4
0
        public async Task <XacmlJsonResponse> GetDecisionForRequest(XacmlJsonRequestRoot xacmlJsonRequest)
        {
            if (_pepSettings.DisablePEP)
            {
                return(new XacmlJsonResponse
                {
                    Response = new List <XacmlJsonResult>()
                    {
                        new XacmlJsonResult
                        {
                            Decision = XacmlContextDecision.Permit.ToString(),
                        }
                    },
                });
            }

            try
            {
                XacmlContextRequest decisionRequest = XacmlJsonXmlConverter.ConvertRequest(xacmlJsonRequest.Request);
                decisionRequest = await Enrich(decisionRequest);

                Altinn.Authorization.ABAC.PolicyDecisionPoint pdp = new Altinn.Authorization.ABAC.PolicyDecisionPoint();

                XacmlPolicy policy = await GetPolicyAsync(decisionRequest);

                XacmlContextResponse contextResponse = pdp.Authorize(decisionRequest, policy);

                return(XacmlJsonXmlConverter.ConvertResponse(contextResponse));
            }
            catch
            {
            }

            return(null);
        }
Exemplo n.º 5
0
        private async Task <XacmlContextResponse> Authorize(XacmlContextRequest decisionRequest)
        {
            decisionRequest = await this._contextHandler.Enrich(decisionRequest);

            _logger.LogInformation($"// DecisionController // Authorize // Roles // Enriched request: {JsonConvert.SerializeObject(decisionRequest)}.");
            XacmlPolicy policy = await this._prp.GetPolicyAsync(decisionRequest);

            XacmlContextResponse rolesContextResponse = _pdp.Authorize(decisionRequest, policy);

            _logger.LogInformation($"// DecisionController // Authorize // Roles // XACML ContextResponse: {JsonConvert.SerializeObject(rolesContextResponse)}.");

            XacmlContextResult roleResult = rolesContextResponse.Results.First();

            if (roleResult.Decision.Equals(XacmlContextDecision.NotApplicable))
            {
                try
                {
                    XacmlContextResponse delegationContextResponse = await AuthorizeBasedOnDelegations(decisionRequest, policy);

                    XacmlContextResult delegationResult = delegationContextResponse.Results.First();
                    if (delegationResult.Decision.Equals(XacmlContextDecision.Permit))
                    {
                        return(delegationContextResponse);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "// DecisionController // Authorize // Delegation // Unexpected Exception");
                }
            }

            return(rolesContextResponse);
        }
Exemplo n.º 6
0
        private async Task <XacmlContextResponse> AuthorizeBasedOnDelegations(XacmlContextRequest decisionRequest, List <DelegationChange> delegations, XacmlPolicy appPolicy)
        {
            XacmlContextResponse delegationContextResponse = new XacmlContextResponse(new XacmlContextResult(XacmlContextDecision.NotApplicable)
            {
                Status = new XacmlContextStatus(XacmlContextStatusCode.Success)
            });

            foreach (DelegationChange delegation in delegations.Where(d => d.DelegationChangeType != DelegationChangeType.RevokeLast))
            {
                XacmlPolicy delegationPolicy = await _prp.GetPolicyVersionAsync(delegation.BlobStoragePolicyPath, delegation.BlobStorageVersionId);

                foreach (XacmlObligationExpression obligationExpression in appPolicy.ObligationExpressions)
                {
                    delegationPolicy.ObligationExpressions.Add(obligationExpression);
                }

                delegationContextResponse = _pdp.Authorize(decisionRequest, delegationPolicy);

                string response = JsonConvert.SerializeObject(delegationContextResponse);
                _logger.LogInformation("// DecisionController // Authorize // Delegations // XACML ContextResponse\n{response}", response);

                if (delegationContextResponse.Results.Any(r => r.Decision == XacmlContextDecision.Permit))
                {
                    return(delegationContextResponse);
                }
            }

            return(delegationContextResponse);
        }
Exemplo n.º 7
0
        private void PutXacmlPolicyInCache(string policyPath, XacmlPolicy policy)
        {
            var cacheEntryOptions = new MemoryCacheEntryOptions()
                                    .SetPriority(CacheItemPriority.High)
                                    .SetAbsoluteExpiration(new TimeSpan(0, _generalSettings.PolicyCacheTimeout, 0));

            _memoryCache.Set(policyPath, policy, cacheEntryOptions);
        }
        private async Task <XacmlContextResponse> Authorize(XacmlContextRequest decisionRequest)
        {
            decisionRequest = await Enrich(decisionRequest);

            XacmlPolicy policy = await GetPolicyAsync(decisionRequest);

            PolicyDecisionPoint  pdp = new PolicyDecisionPoint();
            XacmlContextResponse xacmlContextResponse = pdp.Authorize(decisionRequest, policy);

            return(xacmlContextResponse);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Serializes the XacmlPolicy <see cref="XacmlPolicy"/> to Xml and returns it as a Memory stream
        /// </summary>
        /// <param name="policy">The XacmlPolicy model to serialize to a memory stream</param>
        /// <returns>MemoryStream of the Xml serialized policy</returns>
        public static MemoryStream GetXmlMemoryStreamFromXacmlPolicy(XacmlPolicy policy)
        {
            MemoryStream stream = new MemoryStream();
            XmlWriter    writer = XmlWriter.Create(stream);

            XacmlSerializer.WritePolicy(writer, policy);

            writer.Flush();
            stream.Position = 0;
            return(stream);
        }
Exemplo n.º 10
0
        public async Task GetPolicy_TC02()
        {
            // Arrange
            XacmlContextRequest request = new XacmlContextRequest(true, true, GetXacmlContextAttributesWithOrgAndApp(false));

            // Act
            XacmlPolicy xacmlPolicy = await _prp.GetPolicyAsync(request);

            // Assert
            Assert.Null(xacmlPolicy);
        }
Exemplo n.º 11
0
        public async void PolicyContainsMatchingRule_PolicyContainsRule_PolicyWithoutAppLevelResource_False()
        {
            // Arrange
            Rule        rule   = TestDataHelper.GetRuleModel(20001337, 50001337, "20001336", AltinnXacmlConstants.MatchAttributeIdentifiers.UserAttribute, "eat", "org1", "singlecomplexrule");
            XacmlPolicy policy = await _prpMock.GetPolicyAsync("org1", "singlecomplexrule");

            // Act
            bool actual = DelegationHelper.PolicyContainsMatchingRule(policy, rule);

            // Assert
            Assert.False(actual);
        }
Exemplo n.º 12
0
        public async void PolicyContainsMatchingRule_PolicyContainsRule_InvalidApp_False()
        {
            // Arrange
            Rule        rule   = TestDataHelper.GetRuleModel(20001337, 50001337, "20001336", AltinnXacmlConstants.MatchAttributeIdentifiers.UserAttribute, "read", "org2", "app1");
            XacmlPolicy policy = await _prpMock.GetPolicyAsync("org1", "app1");

            // Act
            bool actual = DelegationHelper.PolicyContainsMatchingRule(policy, rule);

            // Assert
            Assert.False(actual);
        }
Exemplo n.º 13
0
        /// <summary>
        /// public void WritePolicy
        /// </summary>
        /// <param name="writer">XmlWriter writer</param>
        /// <param name="data">XacmlPolicy data</param>
        public virtual void WritePolicy(XmlWriter writer, XacmlPolicy data)
        {
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer));
            }

            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            writer.WriteStartElement(XacmlConstants.Prefixes.Policy, XacmlConstants.ElementNames.Policy, this.Version.NamespacePolicy);
            writer.WriteAttributeString(XacmlConstants.AttributeNames.PolicyId, data.PolicyId.OriginalString);
            writer.WriteAttributeString(XacmlConstants.AttributeNames.RuleCombiningAlgId, data.RuleCombiningAlgId.OriginalString);

            // ?Description
            if (data.Description != null)
            {
                writer.WriteElementString(XacmlConstants.Prefixes.Policy, XacmlConstants.ElementNames.Description, this.Version.NamespacePolicy, data.Description);
            }

            // PolicyDefaults
            if (data.XPathVersion != null)
            {
                writer.WriteStartElement(XacmlConstants.Prefixes.Policy, XacmlConstants.ElementNames.PolicyDefaults, this.Version.NamespacePolicy);
                writer.WriteElementString(XacmlConstants.Prefixes.Policy, XacmlConstants.ElementNames.XPathVersion, this.Version.NamespacePolicy, data.XPathVersion.ToString());
                writer.WriteEndElement();
            }

            // Target
            this.WriteTarget(writer, data.Target);

            // Rule
            foreach (var rule in data.Rules)
            {
                this.WriteRule(writer, rule);
            }

            // Obligatoins
            if (data.Obligations.Count > 0)
            {
                writer.WriteStartElement(XacmlConstants.Prefixes.Policy, XacmlConstants.ElementNames.Obligations, this.Version.NamespacePolicy);
                foreach (var obligation in data.Obligations)
                {
                    this.WriteObligation(writer, obligation);
                }

                writer.WriteEndElement();
            }

            writer.WriteEndElement();
        }
Exemplo n.º 14
0
        public async Task GetPolicy_ByOrgApp_NullWhenPolicyNotExists()
        {
            // Arrange
            string org = "1";
            string app = "2";

            // Act
            XacmlPolicy xacmlPolicy = await _prp.GetPolicyAsync(org, app);

            // Assert
            Assert.Null(xacmlPolicy);
        }
Exemplo n.º 15
0
        public async void PolicyContainsMatchingRule_PolicyContainsRule_PolicyResourcesOutOfOrder_True()
        {
            // Arrange
            Rule        rule   = TestDataHelper.GetRuleModel(20001337, 50001337, "20001336", AltinnXacmlConstants.MatchAttributeIdentifiers.UserAttribute, "read", "org1", "unorderedresources");
            XacmlPolicy policy = await _prpMock.GetPolicyAsync("org1", "unorderedresources");

            // Act
            bool actual = DelegationHelper.PolicyContainsMatchingRule(policy, rule);

            // Assert
            Assert.True(actual);
        }
Exemplo n.º 16
0
        public async Task GetPolicy_ByOrgApp_ReturnsPolicy()
        {
            // Arrange
            string org = "ttd";
            string app = "repository-test-app";

            // Act
            XacmlPolicy xacmlPolicy = await _prp.GetPolicyAsync(org, app);

            // Assert
            Assert.NotNull(xacmlPolicy);
        }
        public async Task GetPolicy_TC01()
        {
            // Arrange
            await PopulateBlobStorage();

            XacmlContextRequest request = new XacmlContextRequest(true, true, GetXacmlContextAttributesWithOrgAndApp());

            // Act
            XacmlPolicy xacmlPolicy = await _prp.GetPolicyAsync(request);

            // Assert
            Assert.NotNull(xacmlPolicy);
        }
Exemplo n.º 18
0
        private async Task <XacmlContextResponse> Authorize(XacmlContextRequest decisionRequest)
        {
            decisionRequest = await this._contextHandler.Enrich(decisionRequest);

            _logger.LogInformation($"// DecisionController // Authorize // Enriched request: {JsonConvert.SerializeObject(decisionRequest)}.");
            XacmlPolicy policy = await this._prp.GetPolicyAsync(decisionRequest);

            PolicyDecisionPoint  pdp = new PolicyDecisionPoint();
            XacmlContextResponse xacmlContextResponse = pdp.Authorize(decisionRequest, policy);

            _logger.LogInformation($"// DecisionController // Authorize // XACML ContextResponse: {JsonConvert.SerializeObject(xacmlContextResponse)}.");
            return(xacmlContextResponse);
        }
        public void WritePolicy_11()
        {
            var subject = new XacmlSubject(
                new XacmlSubjectMatch[]
            {
                new XacmlSubjectMatch(
                    new Uri("http://www.MatchId.www"),
                    new XacmlAttributeValue(new Uri("http://www.DataType.www")),
                    new XacmlSubjectAttributeDesignator(new Uri("http://www.AttributeId.www"), new Uri("http://www.DataType.www"))
                {
                    Issuer = "String", MustBePresent = false, Category = new Uri("http://www.subjectCategory.www")
                })
            });

            var            target         = new XacmlTarget(subject, null, null);
            XacmlPolicySet xacmlPolicySet = new XacmlPolicySet(new Uri("http://www.PolicySetId.www"), new Uri("http://www.PolicyCombiningAlgId.www"), target);

            xacmlPolicySet.Description  = "description string";
            xacmlPolicySet.XPathVersion = Xacml10Constants.XPathVersions.Xpath10;

            XacmlPolicy xacmlPolicy = new XacmlPolicy(new Uri("http://www.PolicyId.www"), new Uri("http://www.RuleCombiningAlgId.www"), new XacmlTarget())
            {
                Description  = "description string",
                XPathVersion = Xacml10Constants.XPathVersions.Xpath10,
            };

            XacmlRule xacmlRule = new XacmlRule("http://www.RuleId.www", XacmlEffectType.Permit)
            {
                Description = "xacmlRule description"
            };

            xacmlPolicy.Rules.Add(xacmlRule);
            XacmlAttributeAssignment xacmlAttributeAssignment = new XacmlAttributeAssignment(new Uri("http://www.AttributeId.www"), new Uri("http://www.DataType.www"));
            XacmlObligation          xacmlObligation          = new XacmlObligation(new Uri("http://www.ObligationId.www"), XacmlEffectType.Permit, new XacmlAttributeAssignment[] { xacmlAttributeAssignment });

            xacmlPolicy.Obligations.Add(xacmlObligation);

            xacmlPolicySet.Policies.Add(xacmlPolicy);

            StringBuilder builder = new StringBuilder();

            using (XmlWriter writer = XmlWriter.Create(builder)) {
                var serializer = new Xacml10ProtocolSerializer();
                serializer.WritePolicySet(writer, xacmlPolicySet);
            }

            string xml = builder.ToString();

            ValidateMessage(xml, Path.Combine(TestCasePath, "cs-xacml-schema-context-01.xsd"));
        }
Exemplo n.º 20
0
        /// <summary>
        /// Checks whether the provided XacmlPolicy contains a rule having an identical Resource signature and contains the Action from the rule,
        /// to be used for checking for duplicate rules in delegation, or that the rule exists in the Apps Xacml policy.
        /// </summary>
        /// <returns>A bool</returns>
        public static bool PolicyContainsMatchingRule(XacmlPolicy policy, Rule rule)
        {
            string ruleResourceKey = GetAttributeMatchKey(rule.Resource);

            foreach (XacmlRule policyRule in policy.Rules)
            {
                if (!policyRule.Effect.Equals(XacmlEffectType.Permit) || policyRule.Target == null)
                {
                    continue;
                }

                List <List <AttributeMatch> > policyResourceMatches = new List <List <AttributeMatch> >();
                bool matchingActionFound = false;
                foreach (XacmlAnyOf anyOf in policyRule.Target.AnyOf)
                {
                    foreach (XacmlAllOf allOf in anyOf.AllOf)
                    {
                        List <AttributeMatch> resourceMatch = new List <AttributeMatch>();
                        foreach (XacmlMatch xacmlMatch in allOf.Matches)
                        {
                            if (xacmlMatch.AttributeDesignator.Category.Equals(XacmlConstants.MatchAttributeCategory.Resource))
                            {
                                resourceMatch.Add(new AttributeMatch {
                                    Id = xacmlMatch.AttributeDesignator.AttributeId.OriginalString, Value = xacmlMatch.AttributeValue.Value
                                });
                            }
                            else if (xacmlMatch.AttributeDesignator.Category.Equals(XacmlConstants.MatchAttributeCategory.Action) &&
                                     xacmlMatch.AttributeDesignator.AttributeId.OriginalString == rule.Action.Id &&
                                     xacmlMatch.AttributeValue.Value == rule.Action.Value)
                            {
                                matchingActionFound = true;
                            }
                        }

                        if (resourceMatch.Any())
                        {
                            policyResourceMatches.Add(resourceMatch);
                        }
                    }
                }

                if (policyResourceMatches.Any(resourceMatch => GetAttributeMatchKey(resourceMatch) == ruleResourceKey) && matchingActionFound)
                {
                    rule.RuleId = policyRule.RuleId;
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Method to serialize a XACML Policy.
        /// </summary>
        /// <param name="writer">XML Writer</param>
        /// <param name="xacmlPolicy">The XACML Policy to be serialized</param>
        public static void WritePolicy(XmlWriter writer, XacmlPolicy xacmlPolicy)
        {
            Guard.ArgumentNotNull(writer, nameof(writer));
            Guard.ArgumentNotNull(xacmlPolicy, nameof(xacmlPolicy));

            writer.WriteStartElement(XacmlConstants.Prefixes.Xacml, XacmlConstants.ElementNames.Policy, Xacml30Constants.NameSpaces.Policy);

            writer.WriteAttributeString(XacmlConstants.AttributeNames.PolicyId, xacmlPolicy.PolicyId.OriginalString);
            writer.WriteAttributeString(XacmlConstants.AttributeNames.Version, xacmlPolicy.Version);
            writer.WriteAttributeString(XacmlConstants.AttributeNames.RuleCombiningAlgId, xacmlPolicy.RuleCombiningAlgId.OriginalString);

            if (xacmlPolicy.MaxDelegationDepth != null)
            {
                writer.WriteAttributeString(XacmlConstants.AttributeNames.MaxDelegationDepth, xacmlPolicy.MaxDelegationDepth.ToString());
            }

            if (xacmlPolicy.PolicyIssuer != null)
            {
                WriteIssuer(writer, xacmlPolicy.PolicyIssuer);
            }

            if (xacmlPolicy.Description != null)
            {
                WriteDescription(writer, xacmlPolicy.Description);
            }

            if (xacmlPolicy.Target != null)
            {
                WriteTarget(writer, xacmlPolicy.Target);
            }

            foreach (XacmlRule rule in xacmlPolicy.Rules)
            {
                WriteRule(writer, rule);
            }

            if (xacmlPolicy.ObligationExpressions != null && xacmlPolicy.ObligationExpressions.Count > 0)
            {
                WriteObligationExpressions(writer, xacmlPolicy.ObligationExpressions);
            }

            if (xacmlPolicy.AdviceExpressions != null && xacmlPolicy.AdviceExpressions.Count > 0)
            {
                WriteAdviceExpressions(writer, xacmlPolicy.AdviceExpressions);
            }

            writer.WriteEndElement();
        }
Exemplo n.º 22
0
        public async Task <ActionResult> GetResourcePolicies([FromBody] List <List <AttributeMatch> > appIdList, [FromQuery] string language)
        {
            List <ResourcePolicyResponse> resourcePolicyResponses = new List <ResourcePolicyResponse>();

            foreach (var attributeMatches in appIdList)
            {
                ResourcePolicyResponse response = new ResourcePolicyResponse {
                    AppId = attributeMatches
                };
                resourcePolicyResponses.Add(response);
                string org = attributeMatches.FirstOrDefault(match => match.Id == XacmlRequestAttribute.OrgAttribute)?.Value;
                string app = attributeMatches.FirstOrDefault(match => match.Id == XacmlRequestAttribute.AppAttribute)?.Value;
                if (string.IsNullOrWhiteSpace(org))
                {
                    response.ErrorResponse = "Organisation must be defined in the path";
                    continue;
                }

                if (string.IsNullOrWhiteSpace(app))
                {
                    response.ErrorResponse = "App must be defined in the path";
                    continue;
                }

                XacmlPolicy policy = await _prp.GetPolicyAsync(org, app);

                if (policy == null)
                {
                    response.ErrorResponse = $"No valid policy found for org '{org}' and app '{app}'";
                    continue;
                }

                response.MinimumAuthenticationLevel = PolicyHelper.GetMinimumAuthenticationLevelFromXacmlPolicy(policy);
                response.ResourcePolicies           = new List <ResourcePolicy>();
                List <ResourcePolicy> list = PolicyHelper.GetResourcePoliciesFromXacmlPolicy(policy, language);
                foreach (ResourcePolicy resourcePolicy in list)
                {
                    if (resourcePolicy.Resource.First(a => a.Id == XacmlRequestAttribute.OrgAttribute).Value == org &&
                        resourcePolicy.Resource.First(a => a.Id == XacmlRequestAttribute.AppAttribute).Value == app)
                    {
                        response.ResourcePolicies.Add(resourcePolicy);
                    }
                }
            }

            return(Ok(resourcePolicyResponses));
        }
Exemplo n.º 23
0
        /// <summary>
        /// Gets the authentication level requirement from the obligation expression of the XacmlPolicy if specified
        /// </summary>
        /// <param name="policy">The policy</param>
        /// <returns>Minimum authentication level requirement</returns>
        public static int GetMinimumAuthenticationLevelFromXacmlPolicy(XacmlPolicy policy)
        {
            foreach (XacmlObligationExpression oblExpr in policy.ObligationExpressions)
            {
                foreach (XacmlAttributeAssignmentExpression attrExpr in oblExpr.AttributeAssignmentExpressions)
                {
                    if (attrExpr.Category.OriginalString == AltinnXacmlConstants.MatchAttributeCategory.MinimumAuthenticationLevel &&
                        attrExpr.Property is XacmlAttributeValue attrValue &&
                        int.TryParse(attrValue.Value, out int minAuthLevel))
                    {
                        return(minAuthLevel);
                    }
                }
            }

            return(0);
        }
Exemplo n.º 24
0
        /// <inheritdoc/>
        public async Task <List <Rule> > GetRulesAsync(List <string> appIds, List <int> offeredByPartyIds, List <int> coveredByPartyIds, List <int> coveredByUserIds)
        {
            List <Rule>             rules             = new List <Rule>();
            List <DelegationChange> delegationChanges = await _delegationRepository.GetAllCurrentDelegationChanges(offeredByPartyIds, appIds, coveredByPartyIds, coveredByUserIds);

            foreach (DelegationChange delegationChange in delegationChanges)
            {
                if (delegationChange.DelegationChangeType != DelegationChangeType.RevokeLast)
                {
                    XacmlPolicy policy = await _prp.GetPolicyVersionAsync(delegationChange.BlobStoragePolicyPath, delegationChange.BlobStorageVersionId);

                    rules.AddRange(GetRulesFromPolicyAndDelegationChange(policy.Rules, delegationChange));
                }
            }

            return(rules);
        }
Exemplo n.º 25
0
        public static void AssertPolicyEqual(XacmlPolicy expected, XacmlPolicy actual)
        {
            Assert.NotNull(actual);
            Assert.NotNull(expected);
            Assert.Equal(expected.PolicyId, actual.PolicyId);
            Assert.Equal(expected.Version, actual.Version);
            Assert.Equal(expected.MaxDelegationDepth, actual.MaxDelegationDepth);
            Assert.Equal(expected.Description, actual.Description);
            Assert.Equal(expected.RuleCombiningAlgId.OriginalString, actual.RuleCombiningAlgId.OriginalString);

            if (expected.XPathVersion != null)
            {
                Assert.Equal(expected.XPathVersion.OriginalString, actual.XPathVersion.OriginalString);
            }

            AssertTargetEqual(expected.Target, actual.Target);

            AssertCollections(expected.Rules, actual.Rules, AssertRuleEqual);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Builds a XacmlPolicy <see cref="XacmlPolicy"/> representation based on the DelegationPolicy input
        /// </summary>
        /// <param name="org">Unique identifier of the organisation responsible for the app.</param>
        /// <param name="app">Application identifier which is unique within an organisation.</param>
        /// <param name="offeredByPartyId">The party id of the entity offering the delegated the policy</param>
        /// <param name="coveredByPartyId">The party of the entity having received the delegated policy, if the receiving entity is an organization</param>
        /// <param name="coveredByUserId">The user id of the entity having received the delegated policy, if the receiving entity is a user</param>
        /// <param name="rules">The set of rules to be delegated</param>
        public static XacmlPolicy BuildDelegationPolicy(string org, string app, int offeredByPartyId, int?coveredByPartyId, int?coveredByUserId, IList <Rule> rules)
        {
            XacmlPolicy delegationPolicy = new XacmlPolicy(new Uri($"{AltinnXacmlConstants.Prefixes.PolicyId}{1}"), new Uri(XacmlConstants.CombiningAlgorithms.PolicyDenyOverrides), new XacmlTarget(new List <XacmlAnyOf>()));

            delegationPolicy.Version = "1.0";

            string coveredBy = coveredByPartyId.HasValue ? coveredByPartyId.Value.ToString() : coveredByUserId.Value.ToString();

            delegationPolicy.Description = $"Delegation policy containing all delegated rights/actions from {offeredByPartyId} to {coveredBy}, for resources on the app; {org}/{app}";

            foreach (Rule rule in rules)
            {
                if (!DelegationHelper.PolicyContainsMatchingRule(delegationPolicy, rule))
                {
                    delegationPolicy.Rules.Add(BuildDelegationRule(org, app, offeredByPartyId, coveredByPartyId, coveredByUserId, rule));
                }
            }

            return(delegationPolicy);
        }
        public async Task <XacmlJsonResponse> GetDecisionForRequest(XacmlJsonRequestRoot xacmlJsonRequest)
        {
            try
            {
                XacmlContextRequest decisionRequest = XacmlJsonXmlConverter.ConvertRequest(xacmlJsonRequest.Request);
                decisionRequest = await Enrich(decisionRequest);

                Altinn.Authorization.ABAC.PolicyDecisionPoint pdp = new Altinn.Authorization.ABAC.PolicyDecisionPoint();

                XacmlPolicy policy = await GetPolicyAsync(decisionRequest);

                XacmlContextResponse contextResponse = pdp.Authorize(decisionRequest, policy);

                return(XacmlJsonXmlConverter.ConvertResponse(contextResponse));
            }
            catch
            {
            }

            return(null);
        }
Exemplo n.º 28
0
        private XacmlContextResponse SetuUpPolicyDecisionPoint(string testCase, bool contextRequstIsEnriched)
        {
            XacmlContextRequest contextRequest         = XacmlTestDataParser.ParseRequest(testCase + "Request.xml", GetAltinnAppsPath());
            XacmlContextRequest contextRequestEnriched = contextRequest;

            if (contextRequstIsEnriched)
            {
                contextRequestEnriched = XacmlTestDataParser.ParseRequest(testCase + "Request_Enriched.xml", GetAltinnAppsPath());
            }

            XacmlPolicy policy = XacmlTestDataParser.ParsePolicy(testCase + "Policy.xml", GetAltinnAppsPath());

            Moq.Mock <IContextHandler> moqContextHandler = new Mock <IContextHandler>();
            moqContextHandler.Setup(c => c.Enrich(It.IsAny <XacmlContextRequest>())).ReturnsAsync(contextRequestEnriched);

            PolicyDecisionPoint pdp = new PolicyDecisionPoint();

            XacmlContextResponse xacmlResponse = pdp.Authorize(contextRequestEnriched, policy);

            return(xacmlResponse);
        }
Exemplo n.º 29
0
        public async Task <ActionResult> GetRolesWithAccess(string org, string app)
        {
            if (string.IsNullOrWhiteSpace(org))
            {
                return(BadRequest("Organisation must be defined in the path"));
            }

            if (string.IsNullOrWhiteSpace(app))
            {
                return(BadRequest("App must be defined in the path"));
            }

            XacmlPolicy policy = await _prp.GetPolicyAsync(org, app);

            if (policy == null)
            {
                return(NotFound($"No valid policy found for org '{org}' and app '{app}'"));
            }

            return(Ok(PolicyHelper.GetRolesWithAccess(policy)));
        }
Exemplo n.º 30
0
        private void AddObligations(XacmlPolicy policy, XacmlContextResult result)
        {
            if (result.Decision.Equals(XacmlContextDecision.Permit))
            {
                if (policy.ObligationExpressions.Count > 0)
                {
                    IEnumerable <XacmlObligationExpression> obligationsWithPermit = policy.ObligationExpressions.Where(o => o.FulfillOn == XacmlEffectType.Permit);
                    foreach (XacmlObligationExpression expression in obligationsWithPermit)
                    {
                        List <XacmlAttributeAssignment> attributeAssignments = new List <XacmlAttributeAssignment>();
                        foreach (XacmlAttributeAssignmentExpression ex in expression.AttributeAssignmentExpressions)
                        {
                            Type applyElemType = ex.Property.GetType();

                            if (applyElemType == typeof(XacmlAttributeValue))
                            {
                                XacmlAttributeValue attributeValue = ex.Property as XacmlAttributeValue;

                                XacmlAttributeAssignment attributeAssignment = new XacmlAttributeAssignment(ex.AttributeId, attributeValue.DataType, attributeValue.Value)
                                {
                                    Category = ex.Category,
                                    Issuer   = ex.Issuer,
                                };

                                attributeAssignments.Add(attributeAssignment);
                            }
                        }

                        XacmlObligation obligation = new XacmlObligation(expression.ObligationId, attributeAssignments)
                        {
                            FulfillOn = XacmlEffectType.Permit,
                        };

                        result.Obligations.Add(obligation);
                    }
                }
            }
        }