基于gopacket的极简http抓包

代码修改来自 gopacket 的example

// Copyright 2012 Google, Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree.

// This binary provides sample code for using the gopacket TCP assembler and TCP
// stream reader.  It reads packets off the wire and reconstructs HTTP requests
// it sees, logging them.
package main

import (
    "bufio"
    "flag"
    "io"
    "log"
    "net/http"
    "time"
    "fmt"

    "github.com/google/gopacket"
    "github.com/google/gopacket/examples/util"
    "github.com/google/gopacket/layers"
    "github.com/google/gopacket/pcap"
    "github.com/google/gopacket/tcpassembly"
    "github.com/google/gopacket/tcpassembly/tcpreader"
)

var iface = flag.String("i", "en0", "Interface to get packets from")
var fname = flag.String("r", "", "Filename to read from, overrides -i")
var snaplen = flag.Int("s", 1600, "SnapLen for pcap packet capture")
var filter = flag.String("f", "tcp and port 80", "BPF filter for pcap")
var logAllPackets = flag.Bool("v", false, "Logs every packet in great detail")

// Build a simple HTTP request parser using tcpassembly.StreamFactory and tcpassembly.Stream interfaces

// httpStreamFactory implements tcpassembly.StreamFactory
type httpStreamFactory struct{}

// httpStream will handle the actual decoding of http requests.
type httpStream struct {
    net, transport gopacket.Flow
    r              tcpreader.ReaderStream
}

func (h *httpStreamFactory) New(net, transport gopacket.Flow) tcpassembly.Stream {
    hstream := &httpStream{
        net:       net,
        transport: transport,
        r:         tcpreader.NewReaderStream(),
    }


    src,_ := transport.Endpoints()  
    if fmt.Sprintf("%v",src) == "80" {
        go hstream.runResponse() // Important... we must guarantee that data from the reader stream is read.
    } else {
        go hstream.runRequest() // Important... we must guarantee that data from the reader stream is read.
    }

    // ReaderStream implements tcpassembly.Stream, so we can return a pointer to it.
    return &hstream.r
}

func (h *httpStream) runResponse() {

    buf := bufio.NewReader(&h.r)
    defer tcpreader.DiscardBytesToEOF(buf)
    for {
        resp, err := http.ReadResponse(buf,nil)
        if err == io.EOF || err == io.ErrUnexpectedEOF {
            // We must read until we see an EOF... very important!
            return
        } else if err != nil {
            log.Println("Error reading stream", h.net, h.transport, ":", err)
            return 
        } else {
            bodyBytes := tcpreader.DiscardBytesToEOF(resp.Body)
            resp.Body.Close()
            printResponse(resp,h,bodyBytes)
            // log.Println("Received response from stream", h.net, h.transport, ":", resp, "with", bodyBytes, "bytes in response body")
        }
    }
}
func (h *httpStream) runRequest() {

    buf := bufio.NewReader(&h.r)
    defer tcpreader.DiscardBytesToEOF(buf)
    for {
        req, err := http.ReadRequest(buf)
        if err == io.EOF || err == io.ErrUnexpectedEOF {
            // We must read until we see an EOF... very important!
            return
        } else if err != nil {
            log.Println("Error reading stream", h.net, h.transport, ":", err)
        } else {
            bodyBytes := tcpreader.DiscardBytesToEOF(req.Body)
            req.Body.Close()
            printRequest(req,h,bodyBytes)
            // log.Println("Received request from stream", h.net, h.transport, ":", req, "with", bodyBytes, "bytes in request body")
        }
    }
}

func printHeader(h http.Header){
    for k,v := range h{
        fmt.Println(k,v)
    }
}

func printRequest(req *http.Request,h *httpStream,bodyBytes int){

    fmt.Println("\n\r\n\r")
    fmt.Println(h.net,h.transport)
    fmt.Println("\n\r")
    fmt.Println(req.Method, req.RequestURI, req.Proto)
    printHeader(req.Header)

}

func printResponse(resp *http.Response,h *httpStream,bodyBytes int){

    fmt.Println("\n\r")
    fmt.Println(resp.Proto, resp.Status)
    printHeader(resp.Header)
}


func main() {
    defer util.Run()()
    var handle *pcap.Handle
    var err error

    // Set up pcap packet capture
    if *fname != "" {
        log.Printf("Reading from pcap dump %q", *fname)
        handle, err = pcap.OpenOffline(*fname)
    } else {
        log.Printf("Starting capture on interface %q", *iface)
        handle, err = pcap.OpenLive(*iface, int32(*snaplen), true, pcap.BlockForever)
    }
    if err != nil {
        log.Fatal(err)
    }

    if err := handle.SetBPFFilter(*filter); err != nil {
        log.Fatal(err)
    }

    // Set up assembly
    streamFactory := &httpStreamFactory{}
    streamPool := tcpassembly.NewStreamPool(streamFactory)
    assembler := tcpassembly.NewAssembler(streamPool)

    log.Println("reading in packets")
    // Read in packets, pass to assembler.
    packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
    packets := packetSource.Packets()
    ticker := time.Tick(time.Minute)
    for {
        select {
        case packet := <-packets:
            // A nil packet indicates the end of a pcap file.
            if packet == nil {
                return
            }
            if *logAllPackets {
                log.Println(packet)
            }
            if packet.NetworkLayer() == nil || packet.TransportLayer() == nil || packet.TransportLayer().LayerType() != layers.LayerTypeTCP {
                log.Println("Unusable packet")
                continue
            }
            tcp := packet.TransportLayer().(*layers.TCP)
            assembler.AssembleWithTimestamp(packet.NetworkLayer().NetworkFlow(), tcp, packet.Metadata().Timestamp)
        case <-ticker:
            // Every minute, flush connections that haven't seen activity in the past 2 minutes.
            assembler.FlushOlderThan(time.Now().Add(time.Minute * -2))
        }
    }
}

源代码可以编译执行。

结果:

192.168.1.104->198.13.57.90 65063->80


GET /http/ HTTP/1.1
Accept-Language [zh-CN,zh;q=0.9]
If-None-Match [W/"5ba2f652-c155"]
If-Modified-Since [Thu, 20 Sep 2018 01:22:26 GMT]
Upgrade-Insecure-Requests [1]
User-Agent [Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3528.4 Safari/537.36]
Accept [text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8]
Referer [http://go.xiulian.net.cn/url/]
Accept-Encoding [gzip, deflate]
Connection [keep-alive]


HTTP/1.1 304 Not Modified
Date [Thu, 20 Sep 2018 01:25:37 GMT]
Last-Modified [Thu, 20 Sep 2018 01:22:26 GMT]
Connection [keep-alive]
Etag ["5ba2f652-c155"]
Server [nginx/1.14.0 (Ubuntu)]

代码片段

    streamFactory := &httpStreamFactory{}
    streamPool := tcpassembly.NewStreamPool(streamFactory)
    assembler := tcpassembly.NewAssembler(streamPool)

这部分主要是,通过tcpassembly 分析包,每一个包处理后,将调用streamFactory.new

func (h *httpStreamFactory) New(net, transport gopacket.Flow) tcpassembly.Stream {
        hstream := &httpStream{
                net:       net,
                transport: transport,
                r:         tcpreader.NewReaderStream(),
        }


        src,_ := transport.Endpoints()
        if fmt.Sprintf("%v",src) == "80" {
                go hstream.runResponse() // Important... we must guarantee that data from the reader stream is read.
        } else {
                go hstream.runRequest() // Important... we must guarantee that data from the reader stream is read.
        }

        // ReaderStream implements tcpassembly.Stream, so we can return a pointer to it.
        return &hstream.r
}

在new函数里面,通过src判断是request还是response。
request是指client给server发送请求。
response是指server返回数据给client。

func (h *httpStream) runResponse() {

        buf := bufio.NewReader(&h.r)
        defer tcpreader.DiscardBytesToEOF(buf)
        for {
                resp, err := http.ReadResponse(buf,nil)
                if err == io.EOF || err == io.ErrUnexpectedEOF {
                        // We must read until we see an EOF... very important!
                        return
                } else if err != nil {
                        log.Println("Error reading stream", h.net, h.transport, ":", err)
                        return
                } else {
                        bodyBytes := tcpreader.DiscardBytesToEOF(resp.Body)
                        resp.Body.Close()
                        printResponse(resp,h,bodyBytes)
                        // log.Println("Received response from stream", h.net, h.transport, ":", resp, "with", bodyBytes, "bytes in response body")
                }
        }
}
func (h *httpStream) runRequest() {

        buf := bufio.NewReader(&h.r)
        defer tcpreader.DiscardBytesToEOF(buf)
        for {
                req, err := http.ReadRequest(buf)
                if err == io.EOF || err == io.ErrUnexpectedEOF {
                        // We must read until we see an EOF... very important!
                        return
                } else if err != nil {
                        log.Println("Error reading stream", h.net, h.transport, ":", err)
                } else {
                        bodyBytes := tcpreader.DiscardBytesToEOF(req.Body)
                        req.Body.Close()
                        printRequest(req,h,bodyBytes)
                        // log.Println("Received request from stream", h.net, h.transport, ":", req, "with", bodyBytes, "bytes in request body")
                }
        }
}

使用http库分析包,
分析的结果通过 printRequest,printReponse打印出来。

源代码在 https://github.com/asmcos/goexample/blob/master/examples/httpassembly.go

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,463评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,868评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,213评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,666评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,759评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,725评论 1 294
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,716评论 3 415
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,484评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,928评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,233评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,393评论 1 345
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,073评论 5 340
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,718评论 3 324
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,308评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,538评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,338评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,260评论 2 352

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,647评论 18 139
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 10,946评论 6 13
  • 原文https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html...
    梁行之阅读 1,103评论 0 0
  • 比如将原来托管在github上面的仓库同时托管到osc(码云)上面 1,首先在osc上面创建一个新的空仓库,但是不...
    ArleyDu阅读 909评论 1 0
  • 2018.5.20日贴 有一种喜悦,就是休忆春风说旧事,缘花而坐,逢了知己! ——麦琪的礼物
    迷鹿mirror阅读 160评论 0 0