func ruleMatchPacket()

in pkg/skoop/network/aliyun/assertion.go [729:799]


func ruleMatchPacket(pkt *model.Packet, rule *ecs.DescribeSecurityGroupAttributeResponseBodyPermissionsPermission) (bool, error) {
	if rule.DestCidrIp != nil && *rule.DestCidrIp != "" {
		_, dstCidrIP, err := parseIPOrCIDR(*rule.DestCidrIp)
		if err != nil {
			return false, err
		}

		if dstCidrIP.Contains(pkt.Dst) {
			if *rule.IpProtocol == "ALL" || strings.EqualFold(string(pkt.Protocol), *rule.IpProtocol) {
				if pkt.Dport == 0 {
					return true, nil
				}

				portRange := strings.Split(*rule.PortRange, "/")
				// assert len(portRange) == 2
				if portRange[0] == "-1" && portRange[1] == "-1" {
					return true, nil
				}

				pStart, err := strconv.Atoi(portRange[0])
				if err != nil {
					return false, err
				}
				pEnd, err := strconv.Atoi(portRange[1])
				if err != nil {
					return false, nil
				}

				if pStart <= int(pkt.Dport) && pEnd >= int(pkt.Dport) {
					return true, nil
				}
			}
		}
	}

	if rule.SourceCidrIp != nil && *rule.SourceCidrIp != "" {
		_, srcCidrIP, err := parseIPOrCIDR(*rule.SourceCidrIp)
		if err != nil {
			return false, err
		}

		if srcCidrIP.Contains(pkt.Src) {
			if *rule.IpProtocol == "ALL" || strings.EqualFold(string(pkt.Protocol), *rule.IpProtocol) {
				if pkt.Dport == 0 {
					return true, nil
				}

				portRange := strings.Split(*rule.PortRange, "/")
				// assert len(portRange) == 2
				if portRange[0] == "-1" && portRange[1] == "-1" {
					return true, nil
				}

				pStart, err := strconv.Atoi(portRange[0])
				if err != nil {
					return false, err
				}
				pEnd, err := strconv.Atoi(portRange[1])
				if err != nil {
					return false, err
				}

				if pStart <= int(pkt.Dport) && pEnd >= int(pkt.Dport) {
					return true, nil
				}
			}
		}
	}

	return false, nil
}