// IngressRules implements instances.Instance.IngressRules.
421437
func (kvm *kvmInstance) IngressRules(ctx context.ProviderCallContext, machineId string) ([]network.IngressRule, error) {
	return nil, fmt.Errorf("not implemented")
}
388692
func secGroupMatchesIngressRule(secGroupRule neutron.SecurityGroupRuleV2, rule network.IngressRule) bool {
	if secGroupRule.IPProtocol == nil ||
		secGroupRule.PortRangeMax == nil || *secGroupRule.PortRangeMax == 0 ||
		secGroupRule.PortRangeMin == nil || *secGroupRule.PortRangeMin == 0 {
		return false
	}
	portsMatch := *secGroupRule.IPProtocol == rule.Protocol &&
		*secGroupRule.PortRangeMin == rule.FromPort &&
		*secGroupRule.PortRangeMax == rule.ToPort
	if !portsMatch {
		return false
	}
	// The ports match, so if the security group RemoteIPPrefix matches *any* of the
	// rule's source ranges, then that's a match.
	if len(rule.SourceCIDRs) == 0 {
		return secGroupRule.RemoteIPPrefix == "" || secGroupRule.RemoteIPPrefix == "0.0.0.0/0"
	}
	for _, r := range rule.SourceCIDRs {
		if r == secGroupRule.RemoteIPPrefix {
			return true
		}
	}
	return false
}
1096871
func (*environ) IngressRules() ([]network.IngressRule, error) {
	return nil, errors.Trace(errors.NotSupportedf("Ports"))
}
35047
func (c *rackspaceFirewaller) InstanceIngressRules(ctx context.ProviderCallContext, inst instances.Instance, machineId string) ([]network.IngressRule, error) {
	_, configurator, err := c.getInstanceConfigurator(ctx, inst)
	if err != nil {
		return nil, errors.Trace(err)
	}
	rules, err := configurator.FindIngressRules()
	if err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
	}
	return rules, err
}
1371310
func (c *ingressRoutes) List(opts v1.ListOptions) (result *v1alpha1.IngressRouteList, err error) {
	result = &v1alpha1.IngressRouteList{}
	err = c.client.Get().
		Namespace(c.ns).
		Resource("ingressroutes").
		VersionedParams(&opts, scheme.ParameterCodec).
		Do().
		Into(result)
	return
}
1185165
func (c *neutronFirewaller) IngressRules(ctx context.ProviderCallContext) ([]network.IngressRule, error) {
	rules, err := c.ingressRules(ctx, c.ingressRulesInGroup)
	if err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
		return rules, errors.Trace(err)
	}
	return rules, nil
}
256499
func (api *API) FirewallRules(zoneID string, pageOpts PaginationOptions) ([]FirewallRule, error) {
	uri := fmt.Sprintf("/zones/%s/firewall/rules", zoneID)
	v := url.Values{}

	if pageOpts.PerPage > 0 {
		v.Set("per_page", strconv.Itoa(pageOpts.PerPage))
	}

	if pageOpts.Page > 0 {
		v.Set("page", strconv.Itoa(pageOpts.Page))
	}

	if len(v) > 0 {
		uri = uri + "?" + v.Encode()
	}

	res, err := api.makeRequest("GET", uri, nil)
	if err != nil {
		return []FirewallRule{}, errors.Wrap(err, errMakeRequestError)
	}

	var firewallDetailResponse FirewallRulesDetailResponse
	err = json.Unmarshal(res, &firewallDetailResponse)
	if err != nil {
		return []FirewallRule{}, errors.Wrap(err, errUnmarshalError)
	}

	return firewallDetailResponse.Result, nil
}
718162
func (fw *Firewaller) gatherIngressRules(machines ...*machineData) ([]network.IngressRule, error) {
	var want []network.IngressRule
	for _, machined := range machines {
		for unitTag, portRanges := range machined.definedPorts {
			unitd, known := machined.unitds[unitTag]
			if !known {
				logger.Debugf("no ingress rules for unknown %v on %v", unitTag, machined.tag)
				continue
			}

			cidrs := set.NewStrings()
			// If the unit is exposed, allow access from everywhere.
			if unitd.applicationd.exposed {
				cidrs.Add("0.0.0.0/0")
			} else {
				// Not exposed, so add any ingress rules required by remote relations.
				if err := fw.updateForRemoteRelationIngress(unitd.applicationd.application.Tag(), cidrs); err != nil {
					return nil, errors.Trace(err)
				}
				logger.Debugf("CIDRS for %v: %v", unitTag, cidrs.Values())
			}
			if cidrs.Size() > 0 {
				for portRange := range portRanges {
					sourceCidrs := cidrs.SortedValues()
					rule, err := network.NewIngressRule(portRange.Protocol, portRange.FromPort, portRange.ToPort, sourceCidrs...)
					if err != nil {
						return nil, errors.Trace(err)
					}
					want = append(want, rule)
				}
			}
		}
	}
	return want, nil
}
323976
func (f Firewall) GlobalIngressRules(ctx context.ProviderCallContext) ([]network.IngressRule, error) {
	seclist := f.globalGroupName()
	return f.getIngressRules(ctx, f.client.ComposeName(seclist))
}
1338250
func Convert_networking_IngressRuleValue_To_v1beta1_IngressRuleValue(in *networking.IngressRuleValue, out *v1beta1.IngressRuleValue, s conversion.Scope) error {
	return autoConvert_networking_IngressRuleValue_To_v1beta1_IngressRuleValue(in, out, s)
}
237127
func (p *Repository) computePolicyEnforcementAndRules(securityIdentity *identity.Identity) (ingress bool, egress bool, matchingRules ruleSlice) {

	lbls := securityIdentity.LabelArray
	// Check if policy enforcement should be enabled at the daemon level.
	switch GetPolicyEnabled() {
	case option.AlwaysEnforce:
		_, _, matchingRules = p.getMatchingRules(securityIdentity)
		// If policy enforcement is enabled for the daemon, then it has to be
		// enabled for the endpoint.
		return true, true, matchingRules
	case option.DefaultEnforcement:
		ingress, egress, matchingRules = p.getMatchingRules(securityIdentity)
		// If the endpoint has the reserved:init label, i.e. if it has not yet
		// received any labels, always enforce policy (default deny).
		if lbls.Has(labels.IDNameInit) {
			return true, true, matchingRules
		}

		// Default mode means that if rules contain labels that match this
		// endpoint, then enable policy enforcement for this endpoint.
		return ingress, egress, matchingRules
	default:
		// If policy enforcement isn't enabled, we do not enable policy
		// enforcement for the endpoint. We don't care about returning any
		// rules that match.
		return false, false, nil
	}
}
753395
func (r *Rules) MatchingRules(c context.Context, serviceAccount string) ([]*Rule, error) {
	// TODO(vadimsh): This will not scale when the number of rules becomes large.
	// At some point we'll have to give up the perfect consistency and start
	// caching the results.

	// Set of rules that match the service account. If the service account matches
	// some rule via multiple different groups, this is NOT an error, since
	// there's no ambiguity in this case.
	matchingRules := make(map[*Rule]struct{}, 1)

	// Query all groups mentioned in the config to figure out which ones the
	// account belongs to and then pick the corresponding rules.
	if len(r.groups) != 0 {
		ident := identity.Identity("user:" + serviceAccount)
		groups, err := auth.GetState(c).DB().CheckMembership(c, ident, r.groups)
		if err != nil {
			return nil, errors.Annotate(err, "failed to check membership of %s", serviceAccount).Err()
		}
		for _, g := range groups {
			matchingRules[r.rulesPerGroup[g]] = struct{}{}
		}
	}

	// Try rules with explicitly mentioned accounts too.
	if rule := r.rulesPerAcc[serviceAccount]; rule != nil {
		matchingRules[rule] = struct{}{}
	}

	// Convert to an array and sort for deterministic error messages.
	out := make([]*Rule, 0, len(matchingRules))
	for rule := range matchingRules {
		out = append(out, rule)
	}
	sort.Slice(out, func(i, j int) bool { return out[i].Rule.Name < out[j].Rule.Name })
	return out, nil
}
306440
func (inst *azureInstance) IngressRules(ctx context.ProviderCallContext, machineId string) (rules []jujunetwork.IngressRule, err error) {
	nsgClient := network.SecurityGroupsClient{inst.env.network}
	securityGroupName := internalSecurityGroupName
	nsg, err := nsgClient.Get(stdcontext.Background(), inst.env.resourceGroup, securityGroupName, "")
	if err != nil {
		return nil, errorutils.HandleCredentialError(errors.Annotate(err, "querying network security group"), ctx)
	}
	if nsg.SecurityRules == nil {
		return nil, nil
	}

	vmName := resourceName(names.NewMachineTag(machineId))
	prefix := instanceNetworkSecurityRulePrefix(instance.Id(vmName))

	// Keep track of all the SourceAddressPrefixes for each port range.
	portSourceCIDRs := make(map[corenetwork.PortRange]*[]string)
	for _, rule := range *nsg.SecurityRules {
		if rule.Direction != network.SecurityRuleDirectionInbound {
			continue
		}
		if rule.Access != network.SecurityRuleAccessAllow {
			continue
		}
		if to.Int32(rule.Priority) <= securityRuleInternalMax {
			continue
		}
		if !strings.HasPrefix(to.String(rule.Name), prefix) {
			continue
		}

		var portRange corenetwork.PortRange
		if *rule.DestinationPortRange == "*" {
			portRange.FromPort = 0
			portRange.ToPort = 65535
		} else {
			portRange, err = corenetwork.ParsePortRange(
				*rule.DestinationPortRange,
			)
			if err != nil {
				return nil, errors.Annotatef(
					err, "parsing port range for security rule %q",
					to.String(rule.Name),
				)
			}
		}

		var protocols []string
		switch rule.Protocol {
		case network.SecurityRuleProtocolTCP:
			protocols = []string{"tcp"}
		case network.SecurityRuleProtocolUDP:
			protocols = []string{"udp"}
		default:
			protocols = []string{"tcp", "udp"}
		}

		// Record the SourceAddressPrefix for the port range.
		remotePrefix := to.String(rule.SourceAddressPrefix)
		if remotePrefix == "" || remotePrefix == "*" {
			remotePrefix = "0.0.0.0/0"
		}
		for _, protocol := range protocols {
			portRange.Protocol = protocol
			sourceCIDRs, ok := portSourceCIDRs[portRange]
			if !ok {
				sourceCIDRs = &[]string{}
				portSourceCIDRs[portRange] = sourceCIDRs
			}
			*sourceCIDRs = append(*sourceCIDRs, remotePrefix)
		}
	}
	// Combine all the port ranges and remote prefixes.
	for portRange, sourceCIDRs := range portSourceCIDRs {
		rule, err := jujunetwork.NewIngressRule(
			portRange.Protocol,
			portRange.FromPort,
			portRange.ToPort,
			*sourceCIDRs...)
		if err != nil {
			return nil, errors.Trace(err)
		}
		rules = append(rules, rule)
	}
	jujunetwork.SortIngressRules(rules)
	return rules, nil
}
191785
func (c *neutronFirewaller) InstanceIngressRules(ctx context.ProviderCallContext, inst instances.Instance, machineId string) ([]network.IngressRule, error) {
	if c.environ.Config().FirewallMode() != config.FwInstance {
		return nil, errors.Errorf("invalid firewall mode %q for retrieving ingress rules from instance",
			c.environ.Config().FirewallMode())
	}
	// For bug 1680787
	// No security groups exist if the network used to boot the instance has
	// PortSecurityEnabled set to false.  To avoid filling up the log files,
	// skip trying to open ports in this cases.
	if securityGroups := inst.(*openstackInstance).getServerDetail().Groups; securityGroups == nil {
		return []network.IngressRule{}, nil
	}
	rules, err := c.instanceIngressRules(ctx, c.ingressRulesInGroup, machineId)
	if err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
		return rules, errors.Trace(err)
	}
	return rules, err
}
112051
func (f Firewall) getSecRules(seclist string) ([]response.SecRule, error) {
	// we only care about ingress rules
	name := fmt.Sprintf("seclist:%s", seclist)
	rulesFilter := []api.Filter{
		{
			Arg:   "dst_list",
			Value: name,
		},
	}
	rules, err := f.client.AllSecRules(rulesFilter)
	if err != nil {
		return nil, errors.Trace(err)
	}
	// gsamfira: the oracle compute API does not allow filtering by action
	ret := []response.SecRule{}
	for _, val := range rules.Result {
		// gsamfira: We set a default policy of DENY. No use in worrying about
		// DENY rules (if by any chance someone add one manually for some reason)
		if val.Action != common.SecRulePermit {
			continue
		}
		// We only care about rules that have a destination set
		// to a security list. Those lists get attached to VMs
		// NOTE: someone decided, when writing the oracle API
		// that some fields should be bool, some should be string.
		// never mind they both are boolean values...but hey.
		// I swear...some people like to watch the world burn
		if val.Dst_is_ip == "true" {
			continue
		}
		// We only care about rules that have an IP list as source
		if val.Src_is_ip == "false" {
			continue
		}
		ret = append(ret, val)
	}
	return ret, nil
}
934557
func (o *Gateway) IngressProfiles(info *bambou.FetchingInfo) (IngressProfilesList, *bambou.Error) {

	var list IngressProfilesList
	err := bambou.CurrentSession().FetchChildren(o, IngressProfileIdentity, &list, info)
	return list, err
}
263377
func (f Firewall) MachineIngressRules(ctx context.ProviderCallContext, machineId string) ([]network.IngressRule, error) {
	seclist := f.machineGroupName(machineId)
	return f.getIngressRules(ctx, f.client.ComposeName(seclist))
}