// ParseRejectAdmitCIDRRules calculates a blacklist and whitelist from a list of string CIDR rules (treating
// a leading ! as a negation). Returns an error if any rule is invalid.
181437
func ParseRejectAdmitCIDRRules(rules []string) (reject, admit []*net.IPNet, err error) {
	for _, s := range rules {
		negate := false
		if strings.HasPrefix(s, "!") {
			negate = true
			s = s[1:]
		}
		_, cidr, err := net.ParseCIDR(s)
		if err != nil {
			return nil, nil, err
		}
		if negate {
			reject = append(reject, cidr)
		} else {
			admit = append(admit, cidr)
		}
	}
	return reject, admit, nil
}
818663
func ValidateCIDRListSlice(cidrBlocks []string) (bool, error) {
	if len(cidrBlocks) == 0 {
		return false, fmt.Errorf("missing CIDR blocks that needs validation")
	}

	for _, block := range cidrBlocks {
		if _, _, err := net.ParseCIDR(strings.TrimSpace(block)); err != nil {
			return false, err
		}
	}

	return true, nil
}
278843
func (f *aclFilter) filterCheckServiceNodes(nodes *structs.CheckServiceNodes) {
	csn := *nodes
	for i := 0; i < len(csn); i++ {
		node := csn[i]
		if f.allowNode(node.Node.Node) && f.allowService(node.Service.Service) {
			continue
		}
		f.logger.Printf("[DEBUG] consul: dropping node %q from result due to ACLs", node.Node.Node)
		csn = append(csn[:i], csn[i+1:]...)
		i--
	}
	*nodes = csn
}
1198377
func ParseIngressRules(r io.Reader) ([]network.IngressRule, error) {
	var rules []network.IngressRule
	scanner := bufio.NewScanner(r)
	for scanner.Scan() {
		line := scanner.Text()
		rule, ok, err := parseIngressRule(strings.TrimSpace(line))
		if err != nil {
			logger.Warningf("failed to parse iptables line %q: %v", line, err)
			continue
		}
		if !ok {
			continue
		}
		rules = append(rules, rule)
	}
	if err := scanner.Err(); err != nil {
		return nil, errors.Annotate(err, "reading iptables output")
	}
	return rules, nil
}
265925
func (p *PacketFilter) AddICMPRule(sourceNetwork string, description string, isAllow bool) (*PacketFilterExpression, error) {

	exp := p.createICMPRule(sourceNetwork, description, isAllow)
	p.Expression = append(p.Expression, exp)
	return exp, nil
}
80477
func ParseIfAddrs(input string, ifAddrs sockaddr.IfAddrs) (string, error) {
	return ParseIfAddrsTemplate(input, ifAddrs, template.New("sockaddr.Parse"))
}
569505
func parseMultiaddrs(maddrs []ma.Multiaddr) (iaddrs []iaddr.IPFSAddr, err error) {
	iaddrs = make([]iaddr.IPFSAddr, len(maddrs))
	for i, maddr := range maddrs {
		iaddrs[i], err = iaddr.ParseMultiaddr(maddr)
		if err != nil {
			return nil, cmds.ClientError("invalid peer address: " + err.Error())
		}
	}
	return
}
316639
func CheckIPWhitelist(remoteAddr string, ipRange string) (bool, error) {
	// Extract IP address from remote address.

	ip := remoteAddr

	if strings.LastIndex(remoteAddr, ":") != -1 {
		ip = remoteAddr[0:strings.LastIndex(remoteAddr, ":")]
	}

	ip = strings.TrimSpace(ip)

	// IPv6 addresses will likely be surrounded by [], so don't forget to remove those.

	if strings.HasPrefix(ip, "[") && strings.HasSuffix(ip, "]") {
		ip = ip[1 : len(ip)-1]
	}

	parsedIP := net.ParseIP(strings.TrimSpace(ip))

	if parsedIP == nil {
		return false, fmt.Errorf("invalid IP address found in remote address '%s'", remoteAddr)
	}

	// Extract IP range in CIDR form.  If a single IP address is provided, turn it into CIDR form.

	ipRange = strings.TrimSpace(ipRange)

	if !strings.Contains(ipRange, "/") {
		ipRange = ipRange + "/32"
	}

	_, cidr, err := net.ParseCIDR(ipRange)

	if err != nil {
		return false, err
	}

	return cidr.Contains(parsedIP), nil
}
299642
func injectToCIDRSetRules(rule *api.Rule, cache *DNSCache, reMap *regexpmap.RegexpMap) (emittedIPs map[string][]net.IP, namesMissingIPs []string) {
	missing := make(map[string]struct{}) // a set to dedup missing dnsNames
	emitted := make(map[string][]net.IP) // name -> IPs we wrote out

	// Add CIDR rules
	// we need to edit Egress[*] in-place
	for egressIdx := range rule.Egress {
		egressRule := &rule.Egress[egressIdx]

		// Build an IP collection to remove all duplicates
		allIPs := []net.IP{}

		// Generate CIDR rules for each FQDN
		for _, ToFQDN := range egressRule.ToFQDNs {
			// lookup matching DNS names
			if len(ToFQDN.MatchName) > 0 {
				dnsName := prepareMatchName(ToFQDN.MatchName)
				lookupIPs := cache.Lookup(dnsName)

				// Mark this name missing; it will be unmarked in the loop below
				if len(lookupIPs) == 0 {
					missing[ToFQDN.MatchName] = struct{}{}
				}

				// Accumulate toCIDRSet rules
				log.WithFields(logrus.Fields{
					"DNSName":   dnsName,
					"IPs":       lookupIPs,
					"matchName": ToFQDN.MatchName,
				}).Debug("Emitting matching DNS Name -> IPs for ToFQDNs Rule")
				emitted[dnsName] = append(emitted[dnsName], lookupIPs...)
				allIPs = append(allIPs, lookupIPs...)
			}

			if len(ToFQDN.MatchPattern) > 0 {
				// lookup matching DNS names
				dnsPattern := matchpattern.Sanitize(ToFQDN.MatchPattern)
				patternREStr := matchpattern.ToRegexp(dnsPattern)
				patternRE := reMap.GetPrecompiledRegexp(patternREStr)
				var err error
				if patternRE == nil {
					if patternRE, err = regexp.Compile(patternREStr); err != nil {
						log.WithError(err).Error("Error compiling matchPattern")
					}
				}
				lookupIPs := cache.LookupByRegexp(patternRE)

				// Mark this pattern missing; it will be unmarked in the loop below
				missing[ToFQDN.MatchPattern] = struct{}{}

				// Accumulate toCIDRSet rules
				for name, ips := range lookupIPs {
					log.WithFields(logrus.Fields{
						"DNSName":      name,
						"IPs":          ips,
						"matchPattern": ToFQDN.MatchPattern,
					}).Debug("Emitting matching DNS Name -> IPs for ToFQDNs Rule")
					delete(missing, ToFQDN.MatchPattern)
					emitted[name] = append(emitted[name], ips...)
					allIPs = append(allIPs, ips...)
				}
			}

			// Always set the ToCIDRSet, in case that there are no IPs will be
			// empty to clean old entries in case of TTL expires.
			egressRule.ToCIDRSet = api.IPsToCIDRRules(ip.KeepUniqueIPs(allIPs))
		}
		egressRule.SetAggregatedSelectors()

	}

	for dnsName := range missing {
		namesMissingIPs = append(namesMissingIPs, dnsName)
	}

	return emitted, namesMissingIPs
}
627320
func validateAwsSecurityGroupRule(d *schema.ResourceData) error {
	blocks, blocksOk := d.GetOk("cidr_blocks")
	self, selfOk := d.GetOk("self")
	if blocksOk && self.(bool) {
		return fmt.Errorf("'self': conflicts with 'cidr_blocks' (%#v)", blocks)
	}

	_, ipv6Ok := d.GetOk("ipv6_cidr_blocks")
	_, sourceOk := d.GetOk("source_security_group_id")
	_, prefixOk := d.GetOk("prefix_list_ids")
	if !blocksOk && !sourceOk && !selfOk && !prefixOk && !ipv6Ok {
		return fmt.Errorf(
			"One of ['cidr_blocks', 'ipv6_cidr_blocks', 'self', 'source_security_group_id', 'prefix_list_ids'] must be set to create an AWS Security Group Rule")
	}
	return nil
}
444230
func (ncc *SeesawNCC) LBInterfaceAddVserver(lbVserver *ncctypes.LBInterfaceVserver, out *int) error {
	return iptablesAddRules(lbVserver.Vserver, lbVserver.Iface.ClusterVIP, lbVserver.AF)
}
716942
func (api *API) ListFirewallRules() (params.ListFirewallRulesResults, error) {
	var listResults params.ListFirewallRulesResults
	if err := api.checkCanRead(); err != nil {
		return listResults, errors.Trace(err)
	}
	rules, err := api.backend.ListFirewallRules()
	if err != nil {
		return listResults, errors.Trace(err)
	}
	listResults.Rules = make([]params.FirewallRule, len(rules))
	for i, r := range rules {
		listResults.Rules[i] = params.FirewallRule{
			KnownService:   params.KnownServiceValue(r.WellKnownService),
			WhitelistCIDRS: r.WhitelistCIDRs,
		}
	}
	return listResults, nil
}
1075730
func (b blacklist) IsValid(value string) bool {
	return !b.rule.IsValid(value)
}
1340287
func (f Firewall) convertFromSecRules(rules ...response.SecRule) (map[string][]network.IngressRule, error) {
	applications, err := f.getAllApplicationsAsMap()
	if err != nil {
		return nil, errors.Trace(err)
	}

	iplists, err := f.getAllIPListsAsMap()
	if err != nil {
		return nil, errors.Trace(err)
	}

	ret := map[string][]network.IngressRule{}
	for _, val := range rules {
		app := val.Application
		srcList := strings.TrimPrefix(val.Src_list, "seciplist:")
		dstList := strings.TrimPrefix(val.Dst_list, "seclist:")
		portRange := f.convertApplicationToPortRange(applications[app])
		if _, ok := ret[dstList]; !ok {
			ret[dstList] = []network.IngressRule{
				{
					PortRange:   portRange,
					SourceCIDRs: iplists[srcList].Secipentries,
				},
			}
		} else {
			toAdd := network.IngressRule{
				PortRange:   portRange,
				SourceCIDRs: iplists[srcList].Secipentries,
			}
			ret[dstList] = append(ret[dstList], toAdd)
		}
	}
	return ret, nil
}
320264
func (c *Client) ListIpForwardingRules(p *ListIpForwardingRulesParameter) ([]*IpForwardingRule, error) {
	obj, err := c.Request("listIpForwardingRules", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.([]*IpForwardingRule), err
}
1336386
func (i *Instance) trapRules(cfg *ACLInfo, isHostPU bool) [][]string {

	tmpl := template.Must(template.New(packetCaptureTemplate).Funcs(template.FuncMap{
		"needDnsRules": func() bool {
			return i.mode == constants.Sidecar || isHostPU || i.isLegacyKernel
		},
		"isUIDProcess": func() bool {
			return cfg.UID != ""
		},
	}).Parse(packetCaptureTemplate))

	rules, err := extractRulesFromTemplate(tmpl, cfg)
	if err != nil {
		zap.L().Warn("unable to extract rules", zap.Error(err))
	}

	return rules
}
302970
func ValidateCIDR(cidr string) (*net.IPNet, error) {
	_, net, err := net.ParseCIDR(cidr)
	if err != nil {
		return nil, err
	}
	return net, nil
}