Пример #1
0
// step3-4
func (s socks5Handler) readRequest() (string, bool) {
	var (
		buf            = make([]byte, 262) // 4+(1+255)+2
		host           string
		ofs            int
		ver, cmd, atyp byte
	)
	var msg = []byte{5, 0, 0, 1, 0, 0, 0, 0, 0, 0}
	setRTimeout(s.conn)
	_, err := s.conn.Read(buf)
	if err != nil {
		exception.Spawn(&err, "socks: read request")
		goto errLogging
	}
	ver, cmd, atyp = buf[0], buf[1], buf[3]
	if ver != S5_VER || cmd != 1 {
		exception.Spawn(&err, "socks: invalid request")
		goto errHandler
	}

	buf = buf[4:]
	switch atyp {
	case IPV4:
		host = net.IP(buf[:net.IPv4len]).String()
		ofs = net.IPv4len
	case IPV6:
		host = "[" + net.IP(buf[:net.IPv6len]).String() + "]"
		ofs = net.IPv6len
	case DOMAIN:
		dlen := int(buf[0])
		ofs = dlen + 1
		host = string(buf[1:ofs])
		// literal IPv6
		if strings.Count(host, ":") >= 2 && !strings.HasPrefix(host, "[") {
			host = "[" + host + "]"
		}
	default:
		exception.Spawn(&err, "socks: invalid request")
		goto errHandler
	}

	// accept
	_, err = s.conn.Write(msg)
	if err != nil {
		exception.Spawn(&err, "socks: write response")
		goto errLogging
	}

	host += ":" + strconv.Itoa(int(binary.BigEndian.Uint16(buf[ofs:])))
	return host, true

errHandler:
	msg[1] = 0x1 // general SOCKS server failure
	setWTimeout(s.conn)
	s.conn.Write(msg)
errLogging:
	log.Warningln(err)

	return NULL, false
}
Пример #2
0
// deserializeRoute decodes a binary netlink message into a Route struct
func deserializeRoute(m []byte) (Route, error) {
	route := Route{}
	msg := nl.DeserializeRtMsg(m)
	attrs, err := nl.ParseRouteAttr(m[msg.Len():])
	if err != nil {
		return route, err
	}
	route.Scope = Scope(msg.Scope)
	route.Flags = int(msg.Flags)

	native := nl.NativeEndian()
	for _, attr := range attrs {
		switch attr.Attr.Type {
		case syscall.RTA_GATEWAY:
			route.Gw = net.IP(attr.Value)
		case syscall.RTA_PREFSRC:
			route.Src = net.IP(attr.Value)
		case syscall.RTA_DST:
			route.Dst = &net.IPNet{
				IP:   attr.Value,
				Mask: net.CIDRMask(int(msg.Dst_len), 8*len(attr.Value)),
			}
		case syscall.RTA_OIF:
			routeIndex := int(native.Uint32(attr.Value[0:4]))
			route.LinkIndex = routeIndex
		}
	}
	return route, nil
}
Пример #3
0
func analyzeIpv4Header(ipv4 ethernetdecode.Ipv4Header) {
	src := net.IP(ipv4.Source[:4]).String()
	dst := net.IP(ipv4.Destination[:4]).String()
	size := uint64(ipv4.Len)

	updateCounters(src, dst, size)
}
Пример #4
0
func (m *BGP4MPHeader) decodeFromBytes(data []byte) ([]byte, error) {
	if m.isAS4 && len(data) < 8 {
		return nil, fmt.Errorf("Not all BGP4MPMessageAS4 bytes available")
	} else if !m.isAS4 && len(data) < 4 {
		return nil, fmt.Errorf("Not all BGP4MPMessageAS bytes available")
	}

	if m.isAS4 {
		m.PeerAS = binary.BigEndian.Uint32(data[:4])
		m.LocalAS = binary.BigEndian.Uint32(data[4:8])
		data = data[8:]
	} else {
		m.PeerAS = uint32(binary.BigEndian.Uint16(data[:2]))
		m.LocalAS = uint32(binary.BigEndian.Uint16(data[2:4]))
		data = data[4:]
	}
	m.InterfaceIndex = binary.BigEndian.Uint16(data[:2])
	m.AddressFamily = binary.BigEndian.Uint16(data[2:4])
	switch m.AddressFamily {
	case AFI_IP:
		m.PeerIpAddress = net.IP(data[4:8]).To4()
		m.LocalIpAddress = net.IP(data[8:12]).To4()
		data = data[12:]
	case AFI_IP6:
		m.PeerIpAddress = net.IP(data[4:20])
		m.LocalIpAddress = net.IP(data[20:36])
		data = data[36:]
	default:
		return nil, fmt.Errorf("unsupported address family: %d", m.AddressFamily)
	}
	return data, nil
}
Пример #5
0
//export consume
func consume(ctx *C.knot_layer_t, pkt *C.knot_pkt_t) C.int {
	req := (*C.struct_kr_request)(ctx.data)
	qry := req.current_query
	state := (C.int)(ctx.state)
	if qry.flags&C.QUERY_CACHED != 0 {
		return state
	}
	// Parse answer source address
	sa := (*C.struct_sockaddr)(unsafe.Pointer(&qry.ns.addr[0]))
	var ip net.IP
	if sa.sa_family == C.AF_INET {
		sa_v4 := (*C.struct_sockaddr_in)(unsafe.Pointer(sa))
		ip = net.IP(C.GoBytes(unsafe.Pointer(&sa_v4.sin_addr), 4))
	} else if sa.sa_family == C.AF_INET6 {
		sa_v6 := (*C.struct_sockaddr_in6)(unsafe.Pointer(sa))
		ip = net.IP(C.GoBytes(unsafe.Pointer(&sa_v6.sin6_addr), 16))
	}
	// Parse metadata
	qname := C.knot_dname_to_str_alloc(C.knot_pkt_qname(pkt))
	defer C.free(unsafe.Pointer(qname))
	qtype := C.knot_pkt_qtype(pkt)
	secure := (bool)(C.knot_pkt_has_dnssec(pkt))
	// Sample metric
	process_sample(C.GoString(qname), int(qtype), ip, secure)
	return state
}
Пример #6
0
func analyzeIpv6Header(ipv6 ethernetdecode.Ipv6Header) {
	src := net.IP(ipv6.Source[:16]).String()
	dst := net.IP(ipv6.Destination[:16]).String()
	size := uint64(ipv6.PayloadLength)

	updateCounters(src, dst, size)
}
Пример #7
0
func TestTransportNonsense(t *testing.T) {
	testString := `  sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout Inode
   0: 00000000:A6C0 00000000:0000 01 000000
broken line
`
	p := NewProcNet([]byte(testString), tcpEstablished)
	expected := []Connection{
		{
			LocalAddress:  net.IP([]byte{0, 0, 0, 0}),
			LocalPort:     0xa6c0,
			RemoteAddress: net.IP([]byte{0, 0, 0, 0}),
			RemotePort:    0x0,
		},
	}

	for i := 0; i < 1; i++ {
		have := p.Next()
		want := expected[i]
		if !reflect.DeepEqual(*have, want) {
			t.Errorf("Got\n%+v\nExpected\n%+v\n", *have, want)
		}
	}
	if got := p.Next(); got != nil {
		t.Errorf("p.Next() wasn't empty")
	}

}
func (s *S5Step1) parseSocks5Request() string {
	var buf = make([]byte, 262) // 4+(1+255)+2
	_, err := s.conn.Read(buf)
	ThrowErr(err)
	ver, cmd, atyp := buf[0], buf[1], buf[3]
	if ver != SOCKS5_VER || cmd != 1 {
		s.err = INVALID_SOCKS5_REQUEST
		return NULL
	}
	s.target = buf[3:]
	buf = buf[4:]
	var host string
	var ofs int
	switch atyp {
	case IPV4:
		host = net.IP(buf[:net.IPv4len]).String()
		ofs = net.IPv4len
	case IPV6:
		host = net.IP(buf[:net.IPv6len]).String()
		ofs = net.IPv6len
	case DOMAIN:
		dlen := int(buf[0])
		host = string(buf[1 : dlen+1])
		ofs = dlen + 1
	default:
		s.err = INVALID_SOCKS5_REQUEST
		return NULL
	}
	var dst_port = binary.BigEndian.Uint16(buf[ofs : ofs+2])
	return host + ":" + strconv.Itoa(int(dst_port))
}
Пример #9
0
func (i *IGMP) decodeIGMPv3MembershipReport(data []byte) error {
	if len(data) < 8 {
		return fmt.Errorf("IGMPv3 Membership Report too small #1")
	}

	i.Checksum = binary.BigEndian.Uint16(data[2:4])
	i.NumberOfGroupRecords = binary.BigEndian.Uint16(data[6:8])

	recordOffset := 8
	for j := 0; j < int(i.NumberOfGroupRecords); j++ {
		if len(data) < recordOffset+8 {
			return fmt.Errorf("IGMPv3 Membership Report too small #2")
		}

		var gr IGMPv3GroupRecord
		gr.Type = IGMPv3GroupRecordType(data[recordOffset])
		gr.AuxDataLen = data[recordOffset+1]
		gr.NumberOfSources = binary.BigEndian.Uint16(data[recordOffset+2 : recordOffset+4])
		gr.MulticastAddress = net.IP(data[recordOffset+4 : recordOffset+8])

		if len(data) < recordOffset+8+int(gr.NumberOfSources)*4 {
			return fmt.Errorf("IGMPv3 Membership Report too small #3")
		}

		// append source address records.
		for i := 0; i < int(gr.NumberOfSources); i++ {
			sourceAddr := net.IP(data[recordOffset+8+i*4 : recordOffset+12+i*4])
			gr.SourceAddresses = append(gr.SourceAddresses, sourceAddr)
		}

		i.GroupRecords = append(i.GroupRecords, gr)
		recordOffset += 8 + 4*int(gr.NumberOfSources)
	}
	return nil
}
Пример #10
0
func NewNodeReader(r io.Reader) (*Node, os.Error) {
	buf := make([]byte, maxSize)
	if _, err := r.Read(buf[0:1]); err != nil {
		return nil, err
	}
	nameLen := int(buf[0])
	if nameLen == 0 {
		return nil, NameTooShort
	}
	size := 1 + nameLen + sizeAddrs
	if _, err := r.Read(buf[1:size]); err != nil {
		return nil, err
	}
	pos := 1
	name := string(buf[pos : pos+nameLen])
	pos += nameLen
	extIP := net.IP(buf[pos : pos+sizeIP6])
	pos += sizeIP6
	intIP4 := net.IP(buf[pos : pos+sizeIP4])
	pos += sizeIP4
	intIP6 := net.IP(buf[pos : pos+sizeIP6])
	pos += sizeIP6

	return NewNode(name, extIP, intIP4, intIP6), nil
}
Пример #11
0
func unmarshalInet(info TypeInfo, data []byte, value interface{}) error {
	switch v := value.(type) {
	case Unmarshaler:
		return v.UnmarshalCQL(info, data)
	case *net.IP:
		if x := len(data); !(x == 4 || x == 16) {
			return unmarshalErrorf("cannot unmarshal %s into %T: invalid sized IP: got %d bytes not 4 or 16", info, value, x)
		}
		buf := copyBytes(data)
		ip := net.IP(buf)
		if v4 := ip.To4(); v4 != nil {
			*v = v4
			return nil
		}
		*v = ip
		return nil
	case *string:
		if len(data) == 0 {
			*v = ""
			return nil
		}
		ip := net.IP(data)
		if v4 := ip.To4(); v4 != nil {
			*v = v4.String()
			return nil
		}
		*v = ip.String()
		return nil
	}
	return unmarshalErrorf("cannot unmarshal %s into %T", info, value)
}
Пример #12
0
func unmarshalInet(info TypeInfo, data []byte, value interface{}) error {
	switch v := value.(type) {
	case Unmarshaler:
		return v.UnmarshalCQL(info, data)
	case *net.IP:
		ip := net.IP(data)
		if v4 := ip.To4(); v4 != nil {
			*v = v4
			return nil
		}
		*v = ip
		return nil
	case *string:
		if len(data) == 0 {
			*v = ""
			return nil
		}
		ip := net.IP(data)
		if v4 := ip.To4(); v4 != nil {
			*v = v4.String()
			return nil
		}
		*v = ip.String()
		return nil
	}
	return unmarshalErrorf("cannot unmarshal %s into %T", info, value)
}
Пример #13
0
func parseGretapData(link Link, data []syscall.NetlinkRouteAttr) {
	gre := link.(*Gretap)
	for _, datum := range data {
		switch datum.Attr.Type {
		case nl.IFLA_GRE_OKEY:
			gre.IKey = ntohl(datum.Value[0:4])
		case nl.IFLA_GRE_IKEY:
			gre.OKey = ntohl(datum.Value[0:4])
		case nl.IFLA_GRE_LOCAL:
			gre.Local = net.IP(datum.Value[0:4])
		case nl.IFLA_GRE_REMOTE:
			gre.Remote = net.IP(datum.Value[0:4])
		case nl.IFLA_GRE_ENCAP_SPORT:
			gre.EncapSport = ntohs(datum.Value[0:2])
		case nl.IFLA_GRE_ENCAP_DPORT:
			gre.EncapDport = ntohs(datum.Value[0:2])
		case nl.IFLA_GRE_IFLAGS:
			gre.IFlags = ntohs(datum.Value[0:2])
		case nl.IFLA_GRE_OFLAGS:
			gre.OFlags = ntohs(datum.Value[0:2])

		case nl.IFLA_GRE_TTL:
			gre.Ttl = uint8(datum.Value[0])
		case nl.IFLA_GRE_TOS:
			gre.Tos = uint8(datum.Value[0])
		case nl.IFLA_GRE_PMTUDISC:
			gre.PMtuDisc = uint8(datum.Value[0])
		case nl.IFLA_GRE_ENCAP_TYPE:
			gre.EncapType = native.Uint16(datum.Value[0:2])
		case nl.IFLA_GRE_ENCAP_FLAGS:
			gre.EncapFlags = native.Uint16(datum.Value[0:2])
		}
	}
}
Пример #14
0
//Process the incomming request message and create a responce packet.
func (dhcpServer *DHCPServer) processDHCPRequest(p Packet, msgType MessageType, options Options) (d Packet, e error) {

	dhcpServer.Logger.Debug("Received a DHCP request packet. " + dhcpServer.packetToString(p))

	serverIP := net.IP{192, 168, 182, 1}
	leaseDuration := 2 * time.Hour

	staticOptions := Options{
		OptionSubnetMask:       []byte{255, 255, 255, 0},
		OptionRouter:           []byte(serverIP), // Presuming Server is also your router
		OptionDomainNameServer: []byte(serverIP), // Presuming Server is also your DNS server
	}

	if server, ok := options[OptionServerIdentifier]; ok && !net.IP(server).Equal(serverIP) {
		return nil, nil // Message not for this dhcp server
	}

	if reqIP := net.IP(options[OptionRequestedIPAddress]); len(reqIP) == 4 {

		retPacket := ReplyPacket(p, ACK, serverIP, net.IP(options[OptionRequestedIPAddress]), leaseDuration, staticOptions.SelectOrderOrAll(options[OptionParameterRequestList]))

		retPacket.SetFile([]byte("keith.txt"))
		retPacket.SetSIAddr([]byte(net.IP{192, 168, 182, 100}))

		dhcpServer.Logger.Debug("Sending responce packet to a DHCP request. " + dhcpServer.packetToString(retPacket))

		return retPacket, nil

	}

	retPacket := ReplyPacket(p, NAK, serverIP, nil, 0, nil)
	dhcpServer.Logger.Debug("Sending responce packet to a DHCP request. " + dhcpServer.packetToString(retPacket))

	return retPacket, nil
}
Пример #15
0
// step2
func (s *s5Handler) parseRequest() string {
	var (
		buf  = make([]byte, 262) // 4+(1+255)+2
		host string
		ofs  int
	)

	setRTimeout(s.conn)
	_, err := s.conn.Read(buf)
	ThrowErr(err)
	ver, cmd, atyp := buf[0], buf[1], buf[3]
	if ver != S5_VER || cmd != 1 {
		s.err = INVALID_SOCKS5_REQUEST
		return NULL
	}

	buf = buf[4:]
	switch atyp {
	case IPV4:
		host = net.IP(buf[:net.IPv4len]).String()
		ofs = net.IPv4len
	case IPV6:
		host = "[" + net.IP(buf[:net.IPv6len]).String() + "]"
		ofs = net.IPv6len
	case DOMAIN:
		dlen := int(buf[0])
		host = string(buf[1 : dlen+1])
		ofs = dlen + 1
	default:
		s.err = INVALID_SOCKS5_REQUEST
		return NULL
	}
	var dst_port = binary.BigEndian.Uint16(buf[ofs : ofs+2])
	return host + ":" + strconv.Itoa(int(dst_port))
}
Пример #16
0
func (p *Packet) Unpack(buf *packet.Buffer) error {
	var versihl uint8
	buf.ReadN(&versihl)

	p.Version = versihl >> 4
	p.IHL = versihl & 0x0F

	buf.ReadN(&p.TOS)
	buf.ReadN(&p.Length)
	buf.ReadN(&p.Id)

	var flagsfrag uint16
	buf.ReadN(&flagsfrag)
	p.Flags = Flags(flagsfrag >> 13)
	p.FragOff = flagsfrag & 0x1FFF

	buf.ReadN(&p.TTL)

	buf.ReadN(&p.Protocol)

	buf.ReadN(&p.Checksum)

	p.SrcAddr = net.IP(buf.Next(4))
	p.DstAddr = net.IP(buf.Next(4))

	/* TODO: Options */

	return nil
}
Пример #17
0
func (p *Packet) Unpack(buf *packet.Buffer) error {
	var versclass uint8
	buf.ReadN(&versclass)

	p.Version = versclass >> 4

	p.Class =
		uint8((binary.BigEndian.Uint16(buf.LayerBytes()[0:2]) >> 4) & 0x00FF)

	p.Label =
		binary.BigEndian.Uint32(buf.LayerBytes()[0:4]) & 0x000FFFFF

	buf.Next(3)

	buf.ReadN(&p.Length)
	buf.ReadN(&p.NextHdr)
	buf.ReadN(&p.HopLimit)

	p.SrcAddr = net.IP(buf.Next(16))
	p.DstAddr = net.IP(buf.Next(16))

	/* TODO: Options */

	return nil
}
Пример #18
0
func (i streamID) toStreamID() StreamID {
	return StreamID{
		SrcIP:   net.IP(i.srcIP),
		DstIP:   net.IP(i.dstIP),
		SrcPort: i.srcPort,
		DstPort: i.dstPort,
	}
}
Пример #19
0
func (receiver *receiver) request(conn net.Conn) ([]byte, string, bool, error) {
	buf := make([]byte, 263)
	//conn.SetReadDeadline(time.Now().Add(l.timeout))
	var n int
	var err error
	if n, err = io.ReadAtLeast(conn, buf, domainLen+1); err != nil {
		logger.Errorf("Socks5--->read data from client error %s\n", err)
		return nil, "", false, err
	}
	if buf[version] != socksV5 {
		return nil, "", false, errSocks
	}
	//cmd
	if buf[1] != socksCmdConnect {
		logger.Errorf("Socks5--->error socks cmd value is %v\n", buf[1])
		return nil, "", false, errCmd
	}
	var hstLen int
	//host item like ipv4,ipv6,domian and so on
	switch buf[3] {
	case ipv4:
		hstLen = ipv4Len
	case ipv6:
		hstLen = ipv6Len
	case domain:
		hstLen = int(buf[domainLen]) + domainTLen
	default:
		return nil, "", false, errAddr
	}
	if n < hstLen {
		if _, err := io.ReadFull(conn, buf[n:hstLen]); err != nil {
			logger.Errorf("Socks5--->read data error %s\n", err)
			return nil, "", false, err
		}
	} else if n > hstLen {
		logger.Errorf("Socks5--->some error")
		return nil, "", false, errors.New("error socks data export")
	}
	//id type is 3
	//ip start idex
	ipIndex := 4
	domian := false
	rawAddr := buf[3:hstLen]
	var hst string
	switch buf[3] {
	case ipv4:
		hst = net.IP(buf[ipIndex : ipIndex+net.IPv4len]).String()
	case ipv6:
		hst = net.IP(buf[ipIndex : ipIndex+net.IPv6len]).String()
	case domain:
		hst = string(buf[5 : 5+buf[domainLen]])
		domian = true
	}
	port := binary.BigEndian.Uint16(buf[hstLen-2 : hstLen])
	host := net.JoinHostPort(hst, strconv.Itoa(int(port)))
	return rawAddr, host, domian, nil
}
Пример #20
0
func addIP(a, b []byte) applyAddr {
	return func(f *FlowID) {
		if len(a) <= 4 {
			f.AddIPv4(net.IP(a), net.IP(b))
		} else {
			f.AddIPv6(net.IP(a), net.IP(b))
		}
	}
}
Пример #21
0
// Run runs the specified ProxyServer.  This should never exit.
func (s *ProxyServer) Run(_ []string) error {
	if err := util.ApplyOomScoreAdj(0, s.OOMScoreAdj); err != nil {
		glog.Info(err)
	}

	serviceConfig := config.NewServiceConfig()
	endpointsConfig := config.NewEndpointsConfig()

	protocol := iptables.ProtocolIpv4
	if net.IP(s.BindAddress).To4() == nil {
		protocol = iptables.ProtocolIpv6
	}
	loadBalancer := proxy.NewLoadBalancerRR()
	proxier := proxy.NewProxier(loadBalancer, net.IP(s.BindAddress), iptables.New(exec.New(), protocol))
	if proxier == nil {
		glog.Fatalf("failed to create proxier, aborting")
	}

	// Wire proxier to handle changes to services
	serviceConfig.RegisterHandler(proxier)
	// And wire loadBalancer to handle changes to endpoints to services
	endpointsConfig.RegisterHandler(loadBalancer)

	// Note: RegisterHandler() calls need to happen before creation of Sources because sources
	// only notify on changes, and the initial update (on process start) may be lost if no handlers
	// are registered yet.

	// define api config source
	if s.ClientConfig.Host != "" {
		glog.Infof("Using API calls to get config %v", s.ClientConfig.Host)
		client, err := client.New(&s.ClientConfig)
		if err != nil {
			glog.Fatalf("Invalid API configuration: %v", err)
		}
		config.NewSourceAPI(
			client.Services(api.NamespaceAll),
			client.Endpoints(api.NamespaceAll),
			30*time.Second,
			serviceConfig.Channel("api"),
			endpointsConfig.Channel("api"),
		)
	}

	if s.HealthzPort > 0 {
		go util.Forever(func() {
			err := http.ListenAndServe(s.BindAddress.String()+":"+strconv.Itoa(s.HealthzPort), nil)
			if err != nil {
				glog.Errorf("Starting health server failed: %v", err)
			}
		}, 5*time.Second)
	}

	// Just loop forever for now...
	proxier.SyncLoop()
	return nil
}
Пример #22
0
// RouteGet gets a route to a specific destination from the host system.
// Equivalent to: 'ip route get'.
func RouteGet(destination net.IP) ([]Route, error) {
	req := nl.NewNetlinkRequest(syscall.RTM_GETROUTE, syscall.NLM_F_REQUEST)
	family := nl.GetIPFamily(destination)
	var destinationData []byte
	var bitlen uint8
	if family == FAMILY_V4 {
		destinationData = destination.To4()
		bitlen = 32
	} else {
		destinationData = destination.To16()
		bitlen = 128
	}
	msg := &nl.RtMsg{}
	msg.Family = uint8(family)
	msg.Dst_len = bitlen
	req.AddData(msg)

	rtaDst := nl.NewRtAttr(syscall.RTA_DST, destinationData)
	req.AddData(rtaDst)

	msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWROUTE)
	if err != nil {
		return nil, err
	}

	native := nl.NativeEndian()
	res := make([]Route, 0)
	for _, m := range msgs {
		msg := nl.DeserializeRtMsg(m)
		attrs, err := nl.ParseRouteAttr(m[msg.Len():])
		if err != nil {
			return nil, err
		}

		route := Route{}
		for _, attr := range attrs {
			switch attr.Attr.Type {
			case syscall.RTA_GATEWAY:
				route.Gw = net.IP(attr.Value)
			case syscall.RTA_PREFSRC:
				route.Src = net.IP(attr.Value)
			case syscall.RTA_DST:
				route.Dst = &net.IPNet{
					IP:   attr.Value,
					Mask: net.CIDRMask(int(msg.Dst_len), 8*len(attr.Value)),
				}
			case syscall.RTA_OIF:
				routeIndex := int(native.Uint32(attr.Value[0:4]))
				route.LinkIndex = routeIndex
			}
		}
		res = append(res, route)
	}
	return res, nil

}
Пример #23
0
func sockaddrToString(sa syscall.Sockaddr) string {
	switch sa := sa.(type) {
	case *syscall.SockaddrInet4:
		return net.JoinHostPort(net.IP(sa.Addr[:]).String(), strconv.Itoa(sa.Port))
	case *syscall.SockaddrInet6:
		return net.JoinHostPort(net.IP(sa.Addr[:]).String(), strconv.Itoa(sa.Port))
	default:
		return fmt.Sprintf("(unknown - %T)", sa)
	}
}
Пример #24
0
func GenerateIPAddress(cidr *net.IPNet) (net.IP, error) {
	log.Printf("generate IP income: %v", cidr)
	randBytes := make([]byte, 4)
	_, err := rand.Read(randBytes)
	for i := 0; i < 4; i++ {
		randBytes[i] = randBytes[i]&^cidr.Mask[i] | cidr.IP[i]
	}
	log.Printf("generate IP out: %v", net.IP(randBytes).String())
	return net.IP(randBytes), err
}
Пример #25
0
func (c *UDPConn) handleUDPConnection(n int, src *net.UDPAddr, receive []byte) {
	var dstIP net.IP
	var reqLen int
	defer udpBuf.Put(receive)

	switch receive[idType] {
	case typeIPv4:
		reqLen = lenIPv4
		dstIP = net.IP(receive[idIP0 : idIP0+net.IPv4len])
	case typeIPv6:
		reqLen = lenIPv6
		dstIP = net.IP(receive[idIP0 : idIP0+net.IPv6len])
	case typeDm:
		reqLen = int(receive[idDmLen]) + lenDmBase
		dIP, err := net.ResolveIPAddr("ip", string(receive[idDm0:idDm0+receive[idDmLen]]))
		if err != nil {
			fmt.Sprintf("[udp]failed to resolve domain name: %s\n", string(receive[idDm0:idDm0+receive[idDmLen]]))
			return
		}
		dstIP = dIP.IP
	default:
		fmt.Sprintf("[udp]addr type %d not supported", receive[idType])
		return
	}
	dst := &net.UDPAddr{
		IP:   dstIP,
		Port: int(binary.BigEndian.Uint16(receive[reqLen-2 : reqLen])),
	}
	if _, ok := ReqList[dst.String()]; !ok {
		req := make([]byte, reqLen)
		for i := 0; i < reqLen; i++ {
			req[i] = receive[i]
		}
		ReqList[dst.String()] = &ReqNode{req, reqLen}
	}

	remote, _, err := nl.Get(src, c)
	if err != nil {
		return
	}
	remote.SetWriteDeadline(time.Now().Add(c.timeout))
	_, err = remote.WriteToUDP(receive[reqLen:n], dst)
	if err != nil {
		if ne, ok := err.(*net.OpError); ok && (ne.Err == syscall.EMFILE || ne.Err == syscall.ENFILE) {
			// log too many open file error
			// EMFILE is process reaches open file limits, ENFILE is system limit
			fmt.Println("[udp]write error:", err)
		} else {
			fmt.Println("[udp]error connecting to:", dst, err)
		}
		return
	}
	// Pipeloop
	return
}
Пример #26
0
func TestBadIP(t *testing.T) {
	for _, iplist := range []Ranger{
		New(nil),
		NewFromPacked([]byte("\x00\x00\x00\x00\x00\x00\x00\x00")),
	} {
		assert.Nil(t, iplist.Lookup(net.IP(make([]byte, 4))), "%v", iplist)
		assert.Nil(t, iplist.Lookup(net.IP(make([]byte, 16))))
		assert.Equal(t, iplist.Lookup(nil).Description, "bad IP")
		assert.NotNil(t, iplist.Lookup(net.IP(make([]byte, 5))))
	}
}
Пример #27
0
func InetNtop(family int, src unsafe.Pointer) string {
	switch family {
	case C.AF_INET:
		return net.IP((*(*[net.IPv4len]byte)(src))[:]).String()
	case C.AF_INET6:
		return net.IP((*(*[net.IPv6len]byte)(src))[:]).String()
	default:
		return "(unknown family)"
	}
	return "(unknown family)"
}
Пример #28
0
func main() {
	opened := 0
	closed := 0

	udpAddr, _ := net.ResolveUDPAddr("udp", ":6343")
	conn, err := net.ListenUDP("udp", udpAddr)

	fmt.Println(err)

	buf := make([]byte, 65535)

	for {
		n, _, err := conn.ReadFromUDP(buf)
		if err == nil {
			datagram := sflow.Decode(buf[0:n])
			for _, sample := range datagram.Samples {
				switch sample.SampleType() {
				case sflow.TypeFlowSample:
					fs := sample.(sflow.FlowSample)
					for _, record := range fs.Records {
						if record.RecordType() == sflow.TypeRawPacketFlow {
							r := record.(sflow.RawPacketFlowRecord)
							_, ipHdr, protoHdr := ethernetdecode.Decode(r.Header)
							if ipHdr != nil && ipHdr.IpVersion() == 4 {
								ipv4 := ipHdr.(ethernetdecode.Ipv4Header)
								switch protoHdr.Protocol() {
								case ethernetdecode.ProtocolTcp:
									tcp := protoHdr.(ethernetdecode.TcpHeader)

									// SYN+ACK flags
									if tcp.Flags&3 == 2 {
										opened++
									}

									// FIN+ACK flags
									if tcp.Flags&17 != 0 {
										closed++
									}
								case ethernetdecode.ProtocolUdp:

								}
								fmt.Printf("src: %v => dst: %v\n", net.IP(ipv4.Source[:]), net.IP(ipv4.Destination[:]))
								fmt.Printf("TCP connections opened: %d, closed: %d\n", opened, closed)
							}
						}
					}
				default:
				}
			}
		} else {
			fmt.Println(err)
		}
	}
}
Пример #29
0
func (nf *Netflow) process(n int, b []byte) (*Packet, error) {
	if int(b[1]) != 5 {
		return nil, fmt.Errorf("invalid netflow record version %v", int(b[1]))
	}
	if (n-NETFLOW_HEADER_LEN)%NETFLOW_RECORD_LEN != 0 {
		return nil, fmt.Errorf("invalid packet size %v", n)
	}
	numRecords := (n - NETFLOW_HEADER_LEN) / NETFLOW_RECORD_LEN

	p := &Packet{
		Header: &Header{
			Version:   int(b[1]), // skip the first byte
			Count:     int(b[3]),
			Sequence:  (int32(b[16]) << 24) + (int32(b[17]) << 16) + (int32(b[18]) << 8) + (int32(b[19])),
			Uptime:    (uint32(b[4]) << 24) + (uint32(b[5]) << 16) + (uint32(b[6]) << 8) + (uint32(b[7])),
			EpochSec:  (uint32(b[8]) << 24) + (uint32(b[9]) << 16) + (uint32(b[10]) << 8) + (uint32(b[11])),
			EpochNsec: (uint32(b[12]) << 24) + (uint32(b[13]) << 16) + (uint32(b[14]) << 8) + (uint32(b[15])),
		},
		Raw: b[:n-1],
	}

	for i := 0; i < numRecords; i++ {
		offset := (i * NETFLOW_RECORD_LEN) + NETFLOW_HEADER_LEN
		c := b[offset:]

		r := &Record{
			Src:        net.IP([]byte{c[0], c[1], c[2], c[3]}),
			Dst:        net.IP([]byte{c[4], c[5], c[6], c[7]}),
			Nexthop:    net.IP([]byte{c[8], c[9], c[10], c[11]}),
			Input:      (uint(c[12]) << 8) + uint(c[13]),
			Output:     (uint(c[14]) << 8) + uint(c[15]),
			NumPackets: (uint32(c[16]) << 24) + (uint32(c[17]) << 16) + (uint32(c[18]) << 8) + (uint32(c[19])),
			NumOctets:  (uint32(c[20]) << 24) + (uint32(c[21]) << 16) + (uint32(c[22]) << 8) + (uint32(c[23])),
			First:      (uint32(c[24]) << 24) + (uint32(c[25]) << 16) + (uint32(c[26]) << 8) + (uint32(c[27])),
			Last:       (uint32(c[28]) << 24) + (uint32(c[29]) << 16) + (uint32(c[30]) << 8) + (uint32(c[31])),
			SrcPort:    (int(c[32]) << 8) + int(c[33]),
			DstPort:    (int(c[34]) << 8) + int(c[35]),
			Protocol:   int(c[38]),
			ToS:        int(c[39]),
			SrcAS:      (int(c[40]) << 8) + int(c[41]),
			DstAS:      (int(c[42]) << 8) + int(c[43]),
		}
		p.Records = append(p.Records, r)

		nf.statBytes += uint64(r.NumOctets)
		nf.statPackets += uint64(r.NumPackets)
	}

	nf.statFlows += uint64(p.Header.Count)
	nf.statNFBytes += uint64(n)
	nf.statNFRecords += uint64(len(p.Records))

	return p, nil
}
Пример #30
0
func (rd *APAIR) Copy(dest dns.PrivateRdata) error {
	cp := make([]byte, rd.Len())
	_, err := rd.Pack(cp)
	if err != nil {
		return err
	}

	d := dest.(*APAIR)
	d.addr[0] = net.IP(cp[:3])
	d.addr[1] = net.IP(cp[4:])
	return nil
}