Ejemplo n.º 1
1
func tcpdumpHandler(ws *websocket.Conn) {

	type TCPDUMPRequest struct {
		Interface string
		Count     float64
	}

	// receive JSON type T
	var data TCPDUMPRequest
	websocket.JSON.Receive(ws, &data)

	log.Printf("interface=%#v\n", data)

	h, err := pcap.OpenLive(data.Interface, 65535, true, 500)
	if h == nil {
		log.Print(err)
		return
	}
	defer h.Close()
	count := 0
	for pkt, r := h.NextEx(); r >= 0; pkt, r = h.NextEx() {
		if r == 0 {
			// timeout, continue
			continue
		}
		pkt.Decode()
		jsonHeaders := []interface{}{}
		data := map[string]interface{}{
			"string":      pkt.String(),
			"time":        pkt.Time.String(),
			"len":         pkt.Len,
			"type":        pkt.Type,
			"data":        pkt.Data,
			"src_mac":     formatMAC(pkt.SrcMac),
			"dest_mac":    formatMAC(pkt.DestMac),
			"raw_headers": pkt.Headers}

		for _, header := range pkt.Headers {
			var packet interface{}
			packet = header
			if iphdr, ok := header.(*pcap.Iphdr); ok {
				packet = map[string]interface{}{
					"type":       "ipv4",
					"version":    iphdr.Version,
					"ihl":        iphdr.Ihl,
					"tos":        iphdr.Tos,
					"len":        iphdr.Length,
					"id":         iphdr.Id,
					"flags":      iphdr.Flags,
					"fragoffset": iphdr.FragOffset,
					"ttl":        iphdr.Ttl,
					"protocol":   iphdr.Protocol,
					"checksum":   iphdr.Checksum,
					"src_ip":     iphdr.SrcAddr(),
					"dest_ip":    iphdr.DestAddr(),
				}
			}
			if ipv6Hdr, ok := header.(*pcap.Ip6hdr); ok {
				packet = map[string]interface{}{
					"type":          "ipv6",
					"version":       ipv6Hdr.Version,
					"traffic_class": ipv6Hdr.TrafficClass,
					"flow_label":    ipv6Hdr.FlowLabel,
					"length":        ipv6Hdr.Length,
					"next_header":   ipv6Hdr.NextHeader,
					"hop_limit":     ipv6Hdr.HopLimit,
					"src_ip":        ipv6Hdr.SrcAddr(),
					"dest_ip":       ipv6Hdr.DestAddr(),
				}
			}
			if tcpHdr, ok := header.(*pcap.Tcphdr); ok {
				packet = map[string]interface{}{
					"type":        "tcp",
					"src_port":    tcpHdr.SrcPort,
					"dest_port":   tcpHdr.DestPort,
					"seq":         tcpHdr.Seq,
					"ack":         tcpHdr.Ack,
					"data_offset": tcpHdr.DataOffset,
					"flags":       tcpHdr.FlagsString(),
					"window":      tcpHdr.Window,
					"checksum":    tcpHdr.Checksum,
					"urgent":      tcpHdr.Urgent,
					"data":        tcpHdr.Data,
				}
			}
			if udpHdr, ok := header.(*pcap.Udphdr); ok {
				packet = map[string]interface{}{
					"type":      "udp",
					"src_port":  udpHdr.SrcPort,
					"dest_port": udpHdr.DestPort,
					"length":    udpHdr.Length,
					"checksum":  udpHdr.Checksum,
				}
			}
			if icmpHdr, ok := header.(*pcap.Icmphdr); ok {
				packet = map[string]interface{}{
					"type":      "icmp",
					"icmp_type": icmpHdr.TypeString(),
					"id":        icmpHdr.Id,
					"seq":       icmpHdr.Seq,
					"data":      icmpHdr.Data,
				}
			}
			//TODO complete set
			if arpHdr, ok := header.(*pcap.Arphdr); ok {
				packet = map[string]interface{}{
					"type":      "arp",
					"addr_type": arpHdr.Addrtype,
					"protocol":  arpHdr.Protocol,
					"operation": arpHdr.Operation,
				}
			}
			jsonHeaders = append(jsonHeaders, packet)
		}
		data["headers"] = jsonHeaders
		err := websocket.JSON.Send(ws, data)
		if err != nil {
			log.Println(err)
			break
		}
		count++
	}
}
Ejemplo n.º 2
0
func main() {
	var (
		pc  *pcap.Pcap
		err error
	)
devloop:
	for _, device := range []string{"bond0", "eth2", "en0", "any"} {
		devs, errx := pcap.FindAllDevs()
		if errx != "" {
			log.Fatalf("%v", errx)
		}
		for _, dev := range devs {
			if dev.Name == device {
				pc, err = pcap.OpenLive(device, 8192, false, 1000)
				if err == nil {
					break devloop
				}
			}
		}
	}

	if err != nil {
		log.Fatalf("%v", err)
	}

	if err = pc.SetFilter("udp and dst port 53"); err != nil {
		log.Fatalf("%v", err)
	}

	lock := &sync.Mutex{}
	ss := &spacesaving.Rate{}
	ss.Init(4096, 60*time.Second)

	go Poller(lock, ss, pc)

	for pkt, r := pc.NextEx(); r >= 0; pkt, r = pc.NextEx() {
		if r == 0 {
			continue
		}
		pkt.Decode()
		var msg dns.Msg
		if err := safeParse(&msg, pkt.Payload); err != nil {
			fmt.Printf("err %v\n", err)
			continue
		}

		qname := strings.ToLower(msg.Question[0].Name)
		if len(qname) > 0 {
			qname = qname[:len(qname)-1]
		}

		lock.Lock()
		ss.Touch(qname, pkt.Time)
		lock.Unlock()
	}

	fmt.Printf("Done\n")
}
Ejemplo n.º 3
0
Archivo: cmd.go Proyecto: sebkl/CAT_TP
func main() {
	flag.Parse()
	args := flag.Args()

	if len(args) > 0 {
		cfg.command = args[0]
	}

	var handle *pcap.Pcap
	var err error

	Log = log.New(os.Stderr, "CATTP", log.Flags())

	// Set filter command for libpcap
	if len(args) > 1 {
		cfg.filter = args[1]
	}

	if len(cfg.device) > 0 {
		Log.Printf("Opening device: %s", cfg.device)
		handle, err = pcap.OpenLive(cfg.device, int32(cfg.snaplen), true, 1000)
	} else if len(cfg.infile) > 0 {
		handle, err = pcap.OpenOffline(cfg.infile)
	} else {
		printUsage("No source given.")
	}

	if len(cfg.filter) > 0 {
		handle.SetFilter(cfg.filter)
	}

	if err != nil {
		Log.Fatalf("Failed to open source: %s", err)
	}

	//TODO: Fix this ugly condition for file end detection.
	for x := handle.Next(); len(cfg.infile) > 0 && x != nil; x = handle.Next() {
		if x != nil {
			func(p *pcap.Packet) {
				defer func() {
					if r := recover(); r != nil {
						Log.Printf("Could not decode packet: %s \n %s", r, p)
					}
				}()

				p.Decode() // Decode pcap packet
				if cp, err := NewPacket(p); err == nil {
					fmt.Println(cp)
					if cfg.hexlog {
						fmt.Println(hex.Dump(cp.Raw()))
					}
				}
			}(x)
		}
	}
}
Ejemplo n.º 4
0
func main() {
	var device *string = flag.String("i", "", "interface")
	var snaplen *int = flag.Int("s", 65535, "snaplen")
	var hexdump *bool = flag.Bool("X", false, "hexdump")
	expr := ""

	out = bufio.NewWriter(os.Stdout)
	errout = bufio.NewWriter(os.Stderr)

	flag.Usage = func() {
		fmt.Fprintf(errout, "usage: %s [ -i interface ] [ -s snaplen ] [ -X ] [ expression ]\n", os.Args[0])
		os.Exit(1)
	}

	flag.Parse()

	if len(flag.Args()) > 0 {
		expr = flag.Arg(0)
	}

	if *device == "" {
		devs, err := pcap.FindAllDevs()
		if err != "" {
			fmt.Fprintf(errout, "tcpdump: couldn't find any devices: %s\n", err)
		}
		if 0 == len(devs) {
			flag.Usage()
		}
		*device = devs[0].Name
	}

	h, err := pcap.OpenLive(*device, int32(*snaplen), true, 1000)
	if h == nil {
		fmt.Fprintf(errout, "tcpdump: %s\n", err)
		errout.Flush()
		return
	}

	if expr != "" {
		ferr := h.SetFilter(expr)
		if ferr != nil {
			fmt.Fprintf(out, "tcpdump: %s\n", ferr)
			out.Flush()
		}
	}

	for pkt := h.Next(); pkt != nil; pkt = h.Next() {
		pkt.Decode()
		fmt.Fprintf(out, "%s\n", pkt.String())
		if *hexdump {
			Hexdump(pkt)
		}
		out.Flush()
	}
}
Ejemplo n.º 5
0
func main() {
	expr := ""

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "usage: %s [ -i interface ] [ -s snaplen ] [ -X ] [ expression ]\n", os.Args[0])
		os.Exit(1)
	}

	flag.Parse()

	if len(flag.Args()) > 0 {
		expr = flag.Arg(0)
	}

	if *device == "" {
		devs, err := pcap.FindAllDevs()
		if err != "" {
			fmt.Fprintln(os.Stderr, "tcpdump: couldn't find any devices:", err)
		}
		if 0 == len(devs) {
			flag.Usage()
		}
		*device = devs[0].Name
	}

	h, err := pcap.OpenLive(*device, int32(*snaplen), true, 500)
	if h == nil {
		fmt.Fprintf(os.Stderr, "tcpdump:", err)
		return
	}

	if expr != "" {
		fmt.Println("tcpdump: setting filter to", expr)
		ferr := h.SetFilter(expr)
		if ferr != nil {
			fmt.Println("tcpdump:", ferr)
		}
	}

	for pkt, r := h.NextEx(); r >= 0; pkt, r = h.NextEx() {
		if r == 0 {
			// timeout, continue
			continue
		}
		pkt.Decode()
		fmt.Println(pkt)
		if *hexdump {
			Hexdump(pkt)
		}

	}
	fmt.Fprintln(os.Stderr, "tcpdump:", h.Geterror())

}
Ejemplo n.º 6
0
func openDevice(device *string, port *string, sm SourceMap) {
	h, err := pcap.OpenLive(*device, 65535, true, 100)

	if h == nil {
		fmt.Printf("Failed to open %s : %s\n", *device, err)
	} else {
		h.SetFilter("not port " + *port)
		for pkt := h.Next(); ; pkt = h.Next() {
			if pkt != nil {
				sm.process(pkt)
			}
		}

		log.Println("timeout")
	}
}
Ejemplo n.º 7
0
func (cons *PcapHTTPConsumer) initPcap() {
	var err error

	// Start listening
	// device, snaplen, promisc, read timeout ms
	cons.handle, err = pcap.OpenLive(cons.netInterface, int32(1<<16), cons.promiscuous, 500)
	if err != nil {
		Log.Error.Print("PcapHTTPConsumer: ", err)
		return
	}

	err = cons.handle.SetFilter(cons.filter)
	if err != nil {
		cons.handle.Close()
		Log.Error.Print("PcapHTTPConsumer: ", err)
		return
	}
}
Ejemplo n.º 8
0
func main() {
	args, err := docopt.Parse(usage, nil, true, "cookiescan 1.0.0", false)
	if err != nil {
		log.Fatal("Error parsing usage. Error: ", err.Error())
	}
	host := args["<target>"].(string)
	ports, err := explode(args["-p"].(string))
	if err != nil {
		log.Fatal(err.Error())
	}

	var ip string
	if net.ParseIP(host) == nil {
		ips, err := net.LookupIP(host)
		if err != nil {
			log.Fatal("Could not resolve hostname. Error: ", err.Error())
		}
		ip = ips[0].String()
	} else {
		ip = host
	}

	minc, err := strconv.Atoi(args["-c"].(string))
	if err != nil {
		log.Fatal("Invalid argument for -c.")
	}
	concurrency, err := strconv.Atoi(args["-g"].(string))
	if err != nil {
		log.Fatal("Invalid argument for -g.")
	}
	ti, err := strconv.Atoi(args["-t"].(string))
	if err != nil {
		log.Fatal("Invalid argument for -t.")
	}
	timeout := time.Duration(ti) * time.Millisecond

	filter := fmt.Sprintf("src %s and ((tcp[13] == 0x11) or (tcp[13] == 0x10) or (tcp[13] == 0x18))", ip)
	var device string
	if args["-i"] != nil {
		device = args["-i"].(string)
	}
	if device == "" {
		devs, err := pcap.FindAllDevs()
		if err != nil {
			log.Fatal("Error finding interfaces. Error: ", err)
		}
		if len(devs) == 0 {
			log.Fatal("No interfaces found. Are you not running as root?")
		}
		device = devs[0].Name
	}

	h, err := pcap.OpenLive(device, int32(320), true, 500)
	if err != nil {
		log.Fatal(err.Error())
	}
	if err = h.SetFilter(filter); err != nil {
		log.Fatal(err.Error())
	}

	res := make(map[uint16][]string)
	tasks := make(chan int, concurrency)
	track := make(chan empty)

	go func() {
		for pkt, r := h.NextEx(); r >= 0; pkt, r = h.NextEx() {
			select {
			case <-track:
				break
			default:
				if r == 0 {
					continue
				}
				pkt.Decode()
				t := pkt.Headers[1].(*pcap.Tcphdr)
				f := t.FlagsString()
				res[t.SrcPort] = append(res[t.SrcPort], f)
			}
		}
	}()

	for i := 0; i < concurrency; i++ {
		go func() {
			for p := range tasks {
				c, err := net.DialTimeout("tcp", ip+":"+strconv.Itoa(p), timeout)
				if err != nil {
					continue
				}
				c.Close()
			}
		}()
	}

	log.Printf("Staring scan of %s.\n", ip)
	for _, p := range ports {
		tasks <- p
	}
	close(tasks)
	time.Sleep(time.Duration(2 * time.Second))
	track <- empty{}
	close(track)
	h.Close()
	log.Println("Scan complete.")

	services, _ := buildServices()
	results := cookiescan.Result{Host: ip}
	for k, v := range res {
		conf := len(v)
		if conf < minc {
			continue
		}
		service := "unknown"
		if s, ok := services[int(k)]; ok {
			service = s
		}
		p := cookiescan.Port{Port: int(k), Service: service, State: "open", Confidence: conf, Reason: v}
		results.Ports = append(results.Ports, p)
	}
	sort.Sort(results.Ports)

	if args["-j"].(bool) {
		j, _ := json.MarshalIndent(results, "", "    ")
		fmt.Println(string(j))
	} else {
		w := tabwriter.NewWriter(os.Stdout, 0, 8, 4, ' ', 0)
		fmt.Fprintln(w, "Port\tState\tService\tConfidence\tReason")
		for _, p := range results.Ports {
			fmt.Fprintf(w, "%d\t%s\t%s\t%d\t%s\n", p.Port, p.State, p.Service, p.Confidence, p.Reason)
		}
		w.Flush()
	}
}
Ejemplo n.º 9
0
func PingScan(CIDR, OUIFile, dev string, ch chan *PingScanResult) error {
	h, err := pcap.OpenLive(dev, 256, true, 500)
	if err != nil {
		return err
	}
	defer h.Close()
	err = h.SetFilter("icmp")
	if err != nil {
		return err
	}
	go func() {
		pingAll(CIDR, ch)
	}()
	ouiDB := make(map[string]string)
	ouiFileExists := true
	f, err := os.OpenFile(OUIFile, os.O_RDONLY, 0666)
	if err != nil {
		ouiFileExists = false
	}
	defer f.Close()
	if ouiFileExists {
		fc, err := ioutil.ReadFile(OUIFile)
		if err == nil {
			lines := strings.Split(string(fc), "\n")
			for _, line := range lines {
				if line == "" || strings.HasPrefix(line, "#") {
					continue
				}
				fields := strings.Fields(line)
				ouiDB[fields[0]] = strings.Join(fields[1:], " ")
			}
		}
	}
	sres := []ScanResult{}
	// REDFLAG: cannot put this loop in goroutine because of
	// runtime.sigpanic from pkg/runtime/os_linux.c:222
	for pkt, r := h.NextEx(); r >= 0; pkt, r = h.NextEx() {
		if r == 0 {
			continue
		}
		pkt.Decode()
		srcVend := "?"
		destVend := "?"
		if len(ouiDB) > 0 {
			srcVend = fmt.Sprintf("%02X%02X%02X",
				pkt.SrcMac&0xff0000000000>>40,
				pkt.SrcMac&0xff00000000>>32,
				pkt.SrcMac&0xff000000>>24)
			srcVend = ouiDB[srcVend]
			destVend = fmt.Sprintf("%02X%02X%02X",
				pkt.DestMac&0xff0000000000>>40,
				pkt.DestMac&0xff00000000>>32,
				pkt.DestMac&0xff000000>>24)
			destVend = ouiDB[destVend]
		}
		glog.V(2).Infof("pkt: ether[%02X:%012X(%s):%012X(%s)] %v",
			pkt.Type, pkt.DestMac, destVend, pkt.SrcMac, srcVend, pkt)
		sr := ScanResult{}
		sr.SrcMACAddr = fmt.Sprintf("%012X", pkt.SrcMac)
		sr.SrcVendor = srcVend
		sr.SrcIPAddr = ""
		var ip *pcap.Iphdr
		for _, h := range pkt.Headers {
			glog.Infof("%v", reflect.TypeOf(h))
			if reflect.TypeOf(h) == reflect.TypeOf(ip) {
				ip = h.(*pcap.Iphdr)
				sr.SrcIPAddr = ip.SrcAddr()
			}
		}
		sres = append(sres, sr)
		psRes := PingScanResult{}
		psRes.Type = "scan"
		psRes.Scan = sr
		ch <- &psRes
	}
	//not reached
	glog.V(2).Infof("exiting pcap capture. %v", h.Geterror())
	return nil
}
Ejemplo n.º 10
0
func main() {
	interf := flag.String("interface", "eth0", "What interface the device is attached to")
	debug := flag.Bool("debug", false, "Print loads of debug info")
	output_mkv := flag.Bool("mkv", true, "Spit out Audio + Video contained in MKV, else spit out raw MJPEG")
	audio := flag.Bool("audio", true, "Output audio into MKV as well")
	wakeup := flag.Bool("wakeups", true, "Send packets needed to start/keep the sender transmitting")
	sendermac := flag.String("sender-mac", "000b78006001", "The macaddress of the sender unit")
	flag.Parse()

	var videowriter *os.File
	pipename := randString(5)
	audiodis := make(chan []byte, 100)
	videodis := make(chan []byte, 100)

	if *wakeup {
		go BroadcastWakeups(*interf, *sendermac)
	}

	if *output_mkv {
		go WrapinMKV(fmt.Sprintf("/tmp/hdmi-Vfifo-%s", pipename), audiodis, *audio)

		err := syscall.Mkfifo(fmt.Sprintf("/tmp/hdmi-Vfifo-%s", pipename), 0664)
		if err != nil {
			log.Fatalf("Could not make a fifo in /tmp/hdmi-Vfifo-%s, %s", pipename, err.Error())
		}

		videowriter, err = os.OpenFile(fmt.Sprintf("/tmp/hdmi-Vfifo-%s", pipename), os.O_WRONLY, 0664)
		if err != nil {
			log.Fatalf("Could not open newly made fifo in /tmp/hdmi-Vfifo-%s, %s", pipename, err.Error())
		}
		go DumpChanToFile(videodis, videowriter)
	} else {
		videowriter = os.Stdout
	}

	MULTICAST_MAC := []byte{0x01, 0x00, 0x5e, 0x02, 0x02, 0x02}

	h, err := pcap.OpenLive(*interf, 1500, true, 500)
	if h == nil {
		fmt.Fprintf(os.Stderr, "de hdmi: %s\n", err)
		return
	}
	defer h.Close()

	droppedframes := 0
	desyncframes := 0
	totalframes := 0

	CurrentPacket := Frame{}
	CurrentPacket.Data = make([]byte, 0)

	videodis <- []byte("--myboundary\nContent-Type: image/jpeg\n\n")

	for pkt, r := h.NextEx(); r >= 0; pkt, r = h.NextEx() {
		if r == 0 {
			// Timeout, continue
			continue
		}

		MACADDR := pkt.Data[0:6]
		if bytes.Compare(MACADDR, MULTICAST_MAC) != 0 {
			// This isnt the multicast packet we are looking for
			continue
		}

		// Ethernet + IP + UDP = 50, Min packet size is 5 bytes, thus 55
		if len(pkt.Data) < 100 {
			continue
		}

		ApplicationData := pkt.Data[42:]

		// Maybe there is some audio data?
		if pkt.Data[34] == 0x08 && pkt.Data[35] == 0x12 && *output_mkv && *audio {
			select {
			case audiodis <- ApplicationData[16:]:
			default:
			}

			continue
		}

		// Check that the port is 2068
		if pkt.Data[34] != 0x08 || pkt.Data[35] != 0x14 {
			continue
		}

		FrameNumber := uint16(0)
		CurrentChunk := uint16(0)

		buf := bytes.NewBuffer(ApplicationData[:2])
		buf2 := bytes.NewBuffer(ApplicationData[2:4])
		binary.Read(buf, binary.BigEndian, &FrameNumber)
		binary.Read(buf2, binary.BigEndian, &CurrentChunk)

		if CurrentPacket.FrameID != FrameNumber && CurrentPacket.FrameID != 0 {
			// Did we drop a packet ?
			droppedframes++
			if CurrentPacket.FrameID < FrameNumber {
				CurrentPacket = Frame{}
				CurrentPacket.Data = make([]byte, 0)
				CurrentPacket.FrameID = CurrentPacket.FrameID
				CurrentPacket.LastChunk = 0
				log.Printf("Dropped packet because of non sane frame number (%d dropped so far)", droppedframes)
			}
			continue
		}

		if *debug {
			log.Printf("%d/%d - %d/%d - %d", FrameNumber, CurrentChunk, CurrentPacket.FrameID, CurrentPacket.LastChunk, len(ApplicationData))
		}

		if CurrentPacket.LastChunk != 0 && CurrentPacket.LastChunk != CurrentChunk-1 {
			if uint16(^(CurrentChunk << 15)) != 65534 {
				log.Printf("Dropped packet because of desync detected (%d dropped so far, %d because of desync)",
					droppedframes, desyncframes)

				log.Printf("You see; %d != %d-1",
					CurrentPacket.LastChunk, CurrentChunk)

				// Oh dear, we are out of sync, Drop the frame
				droppedframes++
				desyncframes++
				CurrentPacket = Frame{}
				CurrentPacket.Data = make([]byte, 0)
				CurrentPacket.FrameID = CurrentPacket.FrameID
				CurrentPacket.LastChunk = 0

				continue
			}
			CurrentPacket.LastChunk = CurrentChunk
		}

		for _, v := range ApplicationData[4:] {
			CurrentPacket.Data = append(CurrentPacket.Data, v)
		}

		if uint16(^(CurrentChunk >> 15)) == 65534 {
			// Flush the frame to output

			fin := []byte("\n--myboundary\nContent-Type: image/jpeg\n\n")
			fin = append(fin, CurrentPacket.Data...)
			select {
			case videodis <- fin:
			default:
			}

			totalframes++

			if *debug {
				log.Printf("Size: %d", len(CurrentPacket.Data))
			}

			CurrentPacket = Frame{}
			CurrentPacket.Data = make([]byte, 0)
			CurrentPacket.FrameID = 0
			CurrentPacket.LastChunk = 0
		}

	}
}
Ejemplo n.º 11
0
func main() {
	expr := ""

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "usage: %s [ -i interface ] [ -s snaplen ] [ -X hexdump ] [ -w file ] [ -h show usage] [ expression ] \n", os.Args[0])
		os.Exit(1)
	}

	flag.Parse()

	if len(flag.Args()) > 0 {
		expr = flag.Arg(0)
	}

	if *help {
		flag.Usage()
	}

	if *device == "" {
		devs, err := pcap.FindAllDevs()
		if err != nil {
			fmt.Fprintln(os.Stderr, "tcpdump: couldn't find any devices:", err)
		}
		if 0 == len(devs) {
			flag.Usage()
		}
		*device = devs[0].Name
	}

	h, err := pcap.OpenLive(*device, int32(*snaplen), true, 500)
	if h == nil {
		fmt.Fprintf(os.Stderr, "tcpdump:", err)
		return
	}
	defer h.Close()

	if expr != "" {
		fmt.Println("tcpdump: setting filter to", expr)
		ferr := h.SetFilter(expr)
		if ferr != nil {
			fmt.Println("tcpdump:", ferr)
		}
	}

	if *ofile != "" {
		dumper, oerr := h.DumpOpen(ofile)
		addHandler(h, dumper)
		if oerr != nil {
			fmt.Fprintln(os.Stderr, "tcpdump: couldn't write to file:", oerr)
		}
		_, lerr := h.PcapLoop(0, dumper)
		if lerr != nil {
			fmt.Fprintln(os.Stderr, "tcpdump: loop error:", lerr, h.Geterror())
		}
		defer h.PcapDumpClose(dumper)
		return
	}

	for pkt, r := h.NextEx(); r >= 0; pkt, r = h.NextEx() {
		if r == 0 {
			// timeout, continue
			continue
		}
		pkt.Decode()
		fmt.Println(pkt)
		if *hexdump {
			Hexdump(pkt)
		}

	}
	fmt.Fprintln(os.Stderr, "tcpdump:", h.Geterror())

}
Ejemplo n.º 12
0
func main() {
	var device *string = flag.String("d", "", "device")
	var file *string = flag.String("r", "", "file")
	var expr *string = flag.String("e", "", "filter expression")

	flag.Parse()

	var h *pcap.Pcap

	ifs, err := pcap.FindAllDevs()
	if len(ifs) == 0 {
		fmt.Printf("Warning: no devices found : %s\n", err)
	} else {
		for i := 0; i < len(ifs); i++ {
			fmt.Printf("dev %d: %s (%s)\n", i+1, ifs[i].Name, ifs[i].Description)
		}
	}

	if *device != "" {
		h, err = pcap.OpenLive(*device, 65535, true, 0)
		if h == nil {
			fmt.Printf("OpenLive(%s) failed: %s\n", *device, err)
			return
		}
	} else if *file != "" {
		h, err = pcap.OpenOffline(*file)
		if h == nil {
			fmt.Printf("Openoffline(%s) failed: %s\n", *file, err)
			return
		}
	} else {
		fmt.Printf("usage: pcaptest [-d <device> | -r <file>]\n")
		return
	}

	fmt.Printf("pcap version: %s\n", pcap.Version())

	if *expr != "" {
		fmt.Printf("Setting filter: %s\n", *expr)
		err := h.SetFilter(*expr)
		if err != nil {
			fmt.Printf("Warning: setting filter failed: %s\n", err)
		}
	}

	for pkt := h.Next(); pkt != nil; pkt = h.Next() {
		fmt.Printf("time: %d.%06d (%s) caplen: %d len: %d\nData:",
			int64(pkt.Time.Second()), int64(pkt.Time.Nanosecond()),
			time.Unix(int64(pkt.Time.Second()), 0).String(), int64(pkt.Caplen), int64(pkt.Len))
		for i := uint32(0); i < pkt.Caplen; i++ {
			if i%32 == 0 {
				fmt.Printf("\n")
			}
			if 32 <= pkt.Data[i] && pkt.Data[i] <= 126 {
				fmt.Printf("%c", pkt.Data[i])
			} else {
				fmt.Printf(".")
			}
		}
		fmt.Printf("\n\n")
	}

}