基于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))
        }
    }
}

源代碼可以編譯執(zhí)行樟氢。

結(jié)果:

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 分析包,每一個包處理后,將調(diào)用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函數(shù)里面国夜,通過src判斷是request還是response。
request是指client給server發(fā)送請求短绸。
response是指server返回數(shù)據(jù)給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庫分析包,
分析的結(jié)果通過 printRequest,printReponse打印出來醋闭。

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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末窄驹,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子证逻,更是在濱河造成了極大的恐慌乐埠,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,290評論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件囚企,死亡現(xiàn)場離奇詭異丈咐,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)龙宏,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,107評論 2 385
  • 文/潘曉璐 我一進(jìn)店門棵逊,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人银酗,你說我怎么就攤上這事辆影⊥较瘢” “怎么了?”我有些...
    開封第一講書人閱讀 156,872評論 0 347
  • 文/不壞的土叔 我叫張陵蛙讥,是天一觀的道長锯蛀。 經(jīng)常有香客問我,道長次慢,這世上最難降的妖魔是什么谬墙? 我笑而不...
    開封第一講書人閱讀 56,415評論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮经备,結(jié)果婚禮上拭抬,老公的妹妹穿的比我還像新娘。我一直安慰自己侵蒙,他們只是感情好造虎,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,453評論 6 385
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著纷闺,像睡著了一般算凿。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上犁功,一...
    開封第一講書人閱讀 49,784評論 1 290
  • 那天氓轰,我揣著相機(jī)與錄音,去河邊找鬼浸卦。 笑死署鸡,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的限嫌。 我是一名探鬼主播靴庆,決...
    沈念sama閱讀 38,927評論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼怒医!你這毒婦竟也來了炉抒?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,691評論 0 266
  • 序言:老撾萬榮一對情侶失蹤稚叹,失蹤者是張志新(化名)和其女友劉穎焰薄,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體扒袖,經(jīng)...
    沈念sama閱讀 44,137評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡塞茅,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,472評論 2 326
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了僚稿。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片凡桥。...
    茶點(diǎn)故事閱讀 38,622評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖蚀同,靈堂內(nèi)的尸體忽然破棺而出缅刽,到底是詐尸還是另有隱情啊掏,我是刑警寧澤,帶...
    沈念sama閱讀 34,289評論 4 329
  • 正文 年R本政府宣布衰猛,位于F島的核電站迟蜜,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏啡省。R本人自食惡果不足惜娜睛,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,887評論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望卦睹。 院中可真熱鬧畦戒,春花似錦、人聲如沸结序。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,741評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽徐鹤。三九已至垃环,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間返敬,已是汗流浹背遂庄。 一陣腳步聲響...
    開封第一講書人閱讀 31,977評論 1 265
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留劲赠,地道東北人涛目。 一個月前我還...
    沈念sama閱讀 46,316評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像经磅,于是被迫代替她去往敵國和親泌绣。 傳聞我的和親對象是個殘疾皇子钮追,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,490評論 2 348

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理预厌,服務(wù)發(fā)現(xiàn),斷路器元媚,智...
    卡卡羅2017閱讀 134,629評論 18 139
  • 國家電網(wǎng)公司企業(yè)標(biāo)準(zhǔn)(Q/GDW)- 面向?qū)ο蟮挠秒娦畔?shù)據(jù)交換協(xié)議 - 報批稿:20170802 前言: 排版 ...
    庭說閱讀 10,926評論 6 13
  • 原文https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html...
    梁行之閱讀 1,088評論 0 0
  • 比如將原來托管在github上面的倉庫同時托管到osc(碼云)上面 1轧叽,首先在osc上面創(chuàng)建一個新的空倉庫,但是不...
    ArleyDu閱讀 909評論 1 0
  • 2018.5.20日貼 有一種喜悅刊棕,就是休憶春風(fēng)說舊事炭晒,緣花而坐,逢了知己甥角! ——麥琪的禮物
    迷鹿mirror閱讀 159評論 0 0