顯示具有 Network 標籤的文章。 顯示所有文章
顯示具有 Network 標籤的文章。 顯示所有文章

2022年9月23日 星期五

IPv6

Fragment

IPv6 基本上不做 Fragment,先透過 Path MTU Discovery 讓傳送端依照 MTU 送,就不需要 Fragment,所以標準 IPv6 封頭沒有 Fragmentation 支援。

透過 extension header,仍可以包含 fragmentation 資訊。

https://lirobo.blogspot.com/2022/09/internet-protocol.html

IPv4

16-bit Identification (ID)

  • 規定在特定來源位址、目的位址、和協定下,每個 datagram 要有不同值,但實際只用在 Fragmentation 和 Reassembly,Fragment 後沿用同樣 ID。其它有些實作並不改變 ID。
  • 在 maximum datagram lifetime (MDL) 內會有唯一的值,和建議的 reassembly timeout 有關,典型 MDL 是 2 分鐘 [RFC791] [RFC1122]。這樣限制了兩點間單一協定在典型 MTU 1500 時的速度上限為 6.4 Mbps [RFC4963],在高速裝置常會違反而變得沒有意義。
  • RFC1122 提到的 datagram de-duplication 用途,仍可以如同 IPv6 unfragmented datagrams 用 hash-based duplicate detection 達成 [RFC6621]。
  • 不改變 ID 導致如 RObust Header Compression (ROHC) [RFC5225] 支援。
  • 參考 RFC6864

3-bit Flags (0DM)

  • 0-bit:保留,沒用。
  • D-bit 表示 Do not Fragment (DF),不進行 Fragment。可用做 path MTU discovery。
  • M-bit 表示 More Fragments (MF)。Fragment 後沿用同樣 ID,除了最後封包外都設 M-bit。

13-bit Fragment Offset

  • IP Payload 的 Offset,採 8 的倍數。

IPv4 位址

https://lirobo.blogspot.com/2022/09/internet-protocol.html

https://lirobo.blogspot.com/2018/08/ipv4-and-ipv6-identification-and.html

https://lirobo.blogspot.com/2010/03/ipv4-link-local-addressing.html

https://lirobo.blogspot.com/2014/09/ether-type.html

2022年9月16日 星期五

Internet Protocol

IPv4

IPv6

https://lirobo.blogspot.com/2018/08/simple-history-of-ip-protocol_23.html

https://lirobo.blogspot.com/2018/08/ipv4-and-ipv6-identification-and.html

https://lirobo.blogspot.com/2020/03/ip-multicast.html

https://lirobo.blogspot.com/2010/10/ipsec.html

2020年12月5日 星期六

Linux Network Block Devices

Network block devices (NBD) 是 client/server 架構,server 提供遠端儲存裝置或檔案,給 client 對應為本地裝置檔,可開機等。也可以格式化、modify or copy 整個分割,這在 NFS 是不行的,因為這些動作需要 unmount 才能進行,而 unmount 就失去連線了。 

問題:NFS 似乎可以提供給多個 client 使用,而 NBD 似乎只能給一個 client 使用。

Server
apt-get install nbd-server
modprobe nbd
nbd-server 9999 /dev/sda # export a device on port 9999
nbd-server 9998 vmdisk.img # export image file on port 9998
Client
apt-get install nbd-client
modprobe nbd-client
# map remote NBD as local device
nbd-client 192.168.1.100 9999 /dev/nbd0 
nbd-client 192.168.1.100 9998 /dev/nbd1

然後可以 format it、可以 resize partitions、可以建立檔案系統...

問題:Server export 後,Server 可以使用嗎?

https://medium.com/@aysadx/linux-nbd-introduction-to-linux-network-block-devices-143365f1901b

https://www.kernel.org/doc/html/latest/admin-guide/blockdev/nbd.html

https://nbd.sourceforge.io/

2020年11月14日 星期六

dnsmasq

dnsmasq (Wikipedia) 是輕量級的 DNS forwarder 加 DHCP Server:

  • DNS server,包括轉送查詢和查詢 /etc/hosts
  • DNS cache
  • DHCP server 支援 DHCPv4、DHCPv6、BOOTP 和 PXE
  • 唯讀的 TFTP server

設定

--server=[/[domain]/[domain/]][ipaddr[#port]][@interface][@source-ip[#port]]

  • ipaddr 是指定的上游 server 網址,可有 port
  • domain 是指定使用的網域,前後有斜線。多個 domain 只需要後面加斜線。
  • @interface, @source-ip 可有 port

https://thekelleys.org.uk/dnsmasq/doc.html

resolv.conf

2020年10月2日 星期五

RADIUS 遠端用戶撥入驗證服務

Remote Authentication Dial-In User Service (RADIUS) 是主從式網路應用協定,提供用戶使用網路服務集中式認證、授權、和記帳 (Authentication, Authorization, and Accounting, AAA) 管理,定義在 RFC2865RFC2866

Network Access Server (NAS)

也就是 RADIUS Client,負責 passing 用戶認證和記帳資訊給 RADIUS Server 或 Accounting Server。
RADIUS 流程
                                        +---------+  +------------+
+------+                +-----+         | RADIUS  |  |   RADIUS   |
| User |                | NAS |         |  Server |  | Accounting |
+--+---+                +--+--+         +----+----+  +------+-----+
   | 連線請求 (用戶名、密碼)  |                 |              |
   |---------------------->| Access-Request  |              |
   |                       |---------------->|              |
   |                       | Access-Accept   |              |
   | 連線通知               |<----------------|              |
   |<----------------------|                                |
   |                       | Accounting-Request start       |
   |                       |------------------------------->|
   |                       | Accounting-Response            |
   |                       |<-------------------------------|
   /                       /                                /
   /                       /                                /
   | 斷線請求               |                                |
   |---------------------->| Accounting-Request stop        |
   |                       |------------------------------->|
   |                       | Accounting-Response            |
   | 斷線通知               |<-------------------------------|
   |<----------------------|                                |

RADIUS Server 使用 UDP port 1812。早期用 UDP port 1645 會和「datametrics」衝突。RADIUS Accounting Server 使用 UDP port 1813。早期用 UDP port 1646 會和「sa-msg-port」衝突。

封包格式
    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |     Code      |  Identifier   |            Length             |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   |                         Authenticator                         |
   |                           16 octets                           |
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |  Attributes ...
   +-+-+-+-+-+-+-+-+-+-+-+-+-
  • Code:type of RADIUS packet
    • 1= Access-Request
    • 2= Access-Accept
    • 3= Access-Reject
    • 4= Accounting-Request
    • 5= Accounting-Response:Server 收到 Accounting-Request 後成功紀錄後才回,不然不回應。
    • 11= Access-Challenge
    • 12= Status-Server, experimental
    • 13= Status-Server, experimental
    • invalid Code:silently discarded.
  • Identifier:辨別重傳,和回應配對請求。新 Access-Request 和 Accounting-Request 訊息用新的 Identifier,重傳用原本的 Identifier。Access-Accept、Access-Reject、和 Access-Challenge 用 Access-Request 的 Identifier。Accounting-Response 用 Accounting-Request 的 Identifier。
  • Length:從 Code 開始到所有 Attribute 的長度,20~4095,如果封包比 Length 短:silently discarded。
  • Authenticator:用來 authenticate Client 和 Server 間的訊息。
    • 在 Access-Request...
    • 在 Accounting-Request 是 Code、Identifier、Length、16 zero octets、attributes、加上 shared secret 的 MD5 checksum。The NAS and RADIUS accounting server share a secret.
    • 在回應是 Code、Identifier、Length、請求的 Authenticator、attributes、加上 shared secret 的 MD5 hash。
  • Attributes:Attributes may have multiple instances, in such a case the order of attributes of the same type SHOULD be preserved. The order of attributes of different types is not required to be preserved.
Attribute 格式
 0                   1                   2
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|     Type      |    Length     |  Value ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Length 值包含 Type、Length、和 Value,最小是 2。Value 的格式和長度由 Type 和 Length 決定,完整 Type 列表見 IANA。Value 的類型有:
  • string:1-253 octets 二進位資料 (0 ~ 255),未必有 NULL 結尾。注意:至少 1 octet。
  • text:1-253 octets UTF-8 encoded 的 10646 characters,未必有 NULL 結尾,是 string 的 subset。注意:至少 1 octet。
  • address:32-bit value, most significant octet first.
  • integer:32-bit unsigned value, most significant octet first.
  • time:32-bit unsigned value, most significant octet first。從 1970 UTC 開始妙數。
#typelenvalue說明
5NAS-Port6integer用戶使用的界面編號。
26Vendor-Specific≥7vsa4-byte Vender-Id + string。Vendor-Id 是 Vendor 的 SMI Network Management Private Enterprise Code。string 由 Vendor 自行定義,例如 1-octet vendor type + 1-octet length + value。
40Acct-Status-Type6enumAccounting-Request 記帳開始或結束:
1=Start
2=Stop
3=Interim-Update
7=Accounting-On
8=Accounting-Off
9-14=Reserved for Tunnel Accounting
15=Reserved for Failed
41Acct-Delay-Time6integer送這個紀錄時延遲的秒數。
42Acct-Input-Octets6integer
43Acct-Output-Octets6integer
44Acct-Session-Id≥3text方便
45Acct-Authentic6enumAccounting-Request 時表示認證方式
46Acct-Session-Time6integer服務秒數,Accounting-Request 的 Acct-Status-Type=Stop 時回報。
47Acct-Input-Packets6integer
48Acct-Output-Packets6integer
49Acct-Terminate-Cause6enum
50Acct-Multi-Session-Id≥3text
51Acct-Link-Count6integer
61NAS-Port-Type6enum用戶使用的界面類型:
0=Async
1=Sync
2=ISDN Sync
3=ISDN Async V.120
4=ISDN Async V.110
5=Virtual
6=PIAFS
7=HDLC Clear Channel
8=X.25
9=X.75
10=G.3 Fax
11=SDSL
12=ADSL-CAP
13=ADSL-DMT
14=IDSL
15=Ethernet
16=xDSL
17=Cable
18=Wireless - Other
19=Wireless - IEEE 802.11
87NAS-Port-Id≥3text描述用戶使用的界面。例如「ISDN 7/2:D:1」。

認證和授權

記帳

服務開始:送 Accounting Start (type of service being delivered and the user it is being delivered to) 給 RADIUS Accounting server 服務結束:送 Accounting Stop (type of service that was delivered and optionally statistics such as elapsed time, input and output octets, or input and output packets) 給 RADIUS Accounting server Accounting-Request (whether for Start or Stop) 成功的話 RADIUS Accounting server 回 Accounting-Response acknowledgment 建議 Client continue attempting to send the Accounting-Request 直到收到 acknowledgement, using some form of backoff. alternate server (after a number of tries to the primary server fail, or in a round-robin fashion)

Accounting-Request 的 Attribute
  • 必須放的:NAS-IP-Address 或 NAS-Identifier
  • 應該放的:NAS-Port or NAS- Port-Type attribute or both unless the service does not involve a port or the NAS does not distinguish among its ports
  • 如果有 Framed-IP-Address,必須含用戶的 IP address。可能是透過 Access-Accept 指定或協調的。
  • 不能放的:User-Password, CHAP-Password, Reply-Message, State。

如果 Accounting-Request 有 invalid Length,整個 request MUST be silently discarded。

參考

  1. https://en.wikipedia.org/wiki/RADIUS
  2. 802.1X
  3. RADIUS Server:FreeRadius
  4. CDR configuration with Radius Accounting:CISCO 設備只送 Accounting-Request stop 作為 CDR,可使用標準 RADIUS Attribute 或 CISCO VSA Attribute

2020年8月17日 星期一

Software Defined Networking

軟體定義網路 (Software-defined networking, SDN) 架構大略分為應用層、控制層以及基礎架構層三層。

應用層
北向 API
控制層
南向 API
基礎架構層

控制層由控制器 (Controller) 負責,集中管理眾多網路設備,讓網路設備專注於封包傳遞,網管人員能以高階軟體的方式調整網路的決策,提升網路資源管控和管理效率。對應用層界面是 Northbound API,對基礎架構層是 Southbound API。基礎架構層 (資料層、Data Layer、Forwarding Layer)由各種網路設備所組成,透過 Southbound API 將設備資訊送到控制器內做整合,並接受控制器的訊息對 flow table 等設備內的設定作調整。控制層內由許許多多模組組成一個可以應付各種需求的控制器。應用層由許多 Forwarding、Firewall 和 Security 等應用所組成,透過 Northbound API 取得整個 SDN 網路的相關資訊去做相對應處理。

例如有個應用想要建立一條從主機 A 到主機 B 的路線,只需要告訴控制器,控制器根據內部現有的網路拓樸計算出最佳的路徑並自動將設定部署到整個網路,不用對每一個交換機做獨立設定。

Controller 備援

參考:
  1. http://www.cc.ntu.edu.tw/chinese/epaper/0029/20140620_2908.html
  2. 可程式網路
  3. 網路功能虛擬化 (Network Virtualization Function,NFV)
  4. https://medium.com/@RiverChan/sdn與nfv的區別和關係-3a15692bb3f6
  5. http://speed.cis.nctu.edu.tw/~ydlin/miscpub/indep_wanghc.pdf:ONOS 有著較好的使用者體驗。測試分散式叢集 (distributed clustering) 功能,Opendaylight 效能較好,ONOS 在穩定性與高可用性上較好。
  6. 控制器:Ryu、NOX/POX、Beacon、Opendaylight、ONOS、...
  7. 北向協定:OpenDayLight 的 REST API,ONOS 的 intent framework API,...
  8. 南向協定:Open Network Foundation (ONF) 的 OpenFlow,SNMP、LISP、XMPP、PCEP、OF-Config、Net-Config、BGP-LS、OPFLEX...
  9. Software Driven Network

2020年6月24日 星期三

Berkeley Packet Filter and Linux Socket Filtering

隨著電腦網路連線發展,需要分析封包傳了什麼,一開始百家爭鳴,直到 Berkeley Packet Filter (BPF) 造成轟動而變成 de-facto 標準。

1992 《The BSD Packet Filter: A New Architecture for User-level Packet Capture》發表,用簡單的虛擬機器改進封包在 kernel 過濾效率。之後一直擴展移植到其它平台和作業系統,成為 Berkeley Packet Filter (BPF)。(1992 好早喔,我那時候左右才知道 TANET,也才在師或長帶領下小用一兩次)

1997 透過 socket 引入 Linux kernel v2.1.75,稱為 Linux Socket Filter (LSF),但還是常稱為 BPF,大部分實作放在 net/core/filter.c

沈寂一段時間後,BPF 持續改善效能,也應用在更多的地方。

2011 Linux v3.0 開始,進一步使用 BPF just-in-time (JIT) 編譯器將 BPF 程式碼轉成原生機器碼的來加速執行。Linux v3.4 用在 SECCOMP,Linux v3.14 新增除錯工具 bpf_asm()、bpf_dbg()。

隨著處理器的演進,BPF 虛擬機器離可運用的原生機器碼越來越遠,對於 BPF 的應用也有更開闊的想法。

2014 Linux v3.15 開始稱為 extended BPF (eBPF) 的全新設計,傳統 BPF 保留為 classical BPF (cBPF)。

在 v3.17 加到 kernel/bpf 下。

Linux 核心封包過濾機制 Linux Socket Filtering (LSF) 源自 Berkeley Packet Filter (BPF),讓 userspace 程式透過 socket SO_ATTACH_FILTER 選項附上過濾碼到任何 socket,給 kernel 過濾封包。此外,也用在 netfilter 的 xt_bpf、kernel qdisc layer 的 cls_bpf、SECCOMP-BPF、team driver、PTP code 等。

高階過濾指令如 `tcpdump -i em1 port 22`,加上參數 -ddd 可用 libpcap內部編譯器產生 SO_ATTACH_FILTER 用的過濾碼。但如果用到 BPF Linux 擴充,或者較為複雜或需要最佳化等,也可以用低階的 BPF 組合語言撰寫,用在 kernel tools/bpf/ 的工具 bpf_asm 編譯。BPF 組語 syntax 很接近原始的 BPF 論文。

BPF 引擎包括下列暫存器:
  • A:32-bit accumulator
  • X:32-bit X register
  • M[16]:16 x 32-bit 記憶體
在 #include <linux/filter.h> 可看到過濾指令的結構:
struct sock_filter { /* Filter block */
  __u16 code;   /* Actual filter code */
  __u8 jt;      /* Jump offset for true */
  __u8 jf;      /* Jump offset for false */
  __u32 k;      /* Generic multiuse field depends on code */
};
code定址模式說明
Load
ld1, 2, 3, 4, 10Load 32-bit into A
ldi4Load word into A
ldh1, 2Load half-word into A
ldb1, 2Load byte into A
ldx3, 4, 5, 10Load word into X
ldxi4Load word into X
ldxb5Load byte into X
Store
st3Store A into M[]
stx3Store X into M[]
Branch
jmp6Jump to label
ja6Jump to label
jeq7, 8Jump on A == k
jneq8Jump on A != k
jne8Jump on A != k
jlt8Jump on A < k
jle8Jump on A <= k
jgt7, 8Jump on A > k
jge7, 8Jump on A >= k
jset7, 8Jump on A & k
ALU
add0, 4A + <x>
sub0, 4A - <x>
mul0, 4A * <x>
div0, 4A / <x>
mod0, 4A % <x>
neg!A
and0, 4A & <x>
or0, 4A | <x>
xor0, 4A ^ <x>
lsh0, 4A << <x>
rsh0, 4A >> <x>
Miscellaneous
taxCopy A into X
txaCopy X into A
Return
ret4, 9Return

定址模式Syntax說明
0x/%xRegister X
1[k]BHW at byte offset k in the packet
2[x + k]BHW at the offset X + k in the packet
3M[k]Word at offset k in M[]
4#kLiteral value stored in k
54*([k]&0xf)Lower nibble * 4 at byte offset k in the packet
6LJump label L
7#k,Lt,LfJump to Lt if true, otherwise jump to Lf
8#k,LtJump to Lt if predicate is true
9a/%aAccumulator A
10extensionBPF extension
Linux 還有 BPF 擴充對載入到 A 指令 "overloading" the k argument with a negative offset + a particular extension offset.
  len                      skb->len
  proto                    skb->protocol
  type                     skb->pkt_type
  poff                     Payload start offset
  ifidx                    skb->dev->ifindex
  nla                      Netlink attribute of type X with offset A
  nlan                     Nested Netlink attribute of type X with offset A
  mark                     skb->mark
  queue                    skb->queue_mapping
  hatype                   skb->dev->type
  rxhash                   skb->hash
  cpu                      raw_smp_processor_id()
  vlan_tci                 skb_vlan_tag_get(skb)
  vlan_avail               skb_vlan_tag_present(skb)
  vlan_tpid                skb->vlan_proto
  rand                     prandom_u32()
BPF 組合語言範例:
ARP 封包: (檔案 foo)
      ldh [12]         /* Load half word offset 12 into A */
      jne #0x806, drop /* Jump to drop if != 0x0806 */
      ret #-1
drop: ret #0
經過 bpf_asm 轉換成 bytecode:
$ ./bpf_asm foo
4,40 0 0 12,21 0 1 2054,6 0 0 4294967295,6 0 0 0,
C 語言格式輸出方便複製貼上:
$ ./bpf_asm -c foo
{ 0x28,  0,  0, 0x0000000c },
{ 0x15,  0,  1, 0x00000806 },
{ 0x06,  0,  0, 0xffffffff },
{ 0x06,  0,  0, 0000000000 },

IPv4 TCP packets:
      ldh [12]
      jne #0x800, drop
      ldb [23]
      jneq #6, drop
      ret #-1
drop: ret #0
(Accelerated) VLAN w/ id 10:
ld vlan_tci
jneq #10, drop
ret #-1
drop: ret #0
icmp random packet sampling, 1 in 4
ldh [12]
jne #0x800, drop
ldb [23]
jneq #1, drop
# get a random uint32 number
ld rand
mod #4
jneq #1, drop
ret #-1
drop: ret #0
SECCOMP filter example:
ld [4] /* offsetof(struct seccomp_data, arch) */
jne #0xc000003e, bad /* AUDIT_ARCH_X86_64 */
ld [0] /* offsetof(struct seccomp_data, nr) */
jeq #15, good /* __NR_rt_sigreturn */
jeq #231, good /* __NR_exit_group */
jeq #60, good /* __NR_exit */
jeq #0, good /* __NR_read */
jeq #1, good /* __NR_write */
jeq #5, good /* __NR_fstat */
jeq #9, good /* __NR_mmap */
jeq #14, good /* __NR_rt_sigprocmas
k */ jeq #13, good /* __NR_rt_sigaction */
jeq #35, good /* __NR_nanosleep */
bad: ret #0 /* SECCOMP_RET_KILL_THREAD */
good: ret #0x7fff0000 /* SECCOMP_RET_ALLOW */

參考

  1. BPF - the forgotten bytecode

wireshark packet dissection

就 encapsulated 協定,每個 dissector 負責解碼一部分協定,然後交給下個階段 dissector。整個 dissection 流程,一開始是 Frame dissector 解碼擷取檔封包本身 (例如 timestamps)。然後資料交給 lowest-level data dissector,例如解析 Ethernet header。payload 再交給下一個 dissector (例如 IP) 等等。

Dissection 實作有兩種方式:內建或 plugin。一開始發展可以用 plugin 減少編譯時間。

doc/README.dissector

proto_register_protocol()


https://www.wireshark.org/docs/wsdg_html_chunked/ChapterDissection.html

libpcap

libpcap 是封包擷取的 C/C++ 函式庫,可以過濾網路界面或 pcap 檔的封包,存成 pcap 檔

使用前都要開啟取得 pcap handle,此時可以設定過濾條件,然後才能讀取封包。封包讀取後可以作各種處理,包括存成 pcap 檔。

開啟

無論是網路界面或 pcap 檔,都需要開啟取得 pcap handle -- pcap_t。即使沒有者兩個來源,只是要產生過濾程式碼或寫 pcap 檔,也需要開啟一個「假」的。

  • 網路界面:pcap_create() → 設定選項 → pcap_activate()。
    • pcap_findalldevs() 列出界面,然後 pcap_freealldevs() 釋出。
    • pcap_lookupdev() 取得第一個非「loopback」的界面。
    • 讀取權限
  • pcap 檔案:pcap_open_offline() 或 pcap_fopen_offline()。
  • 「假」的:pcap_open_dead()

關閉 pcap_t 用 pcap_close()。

* pcap handle 設定
* 網路界面 link 信頭 type 及設定

讀取封包

讀取封包:pcap_dispatch(), pacp_loop(), pcap_next(), pcap_next_ex()。

過濾

讀取之前可以先過濾。如果可能的話,過濾網路界面的封包會在 kernel 裡進行,不需要的封包就不用從 kernel 複製出來。

過濾表示式是一個字串,由 pcap_compile() 編譯成虛擬機器程式碼,然後透過 pcap_setfilter() 設給 pcap_t,或者用 pcap_offline_filter() 套用在已讀取的封包看是否符合。

產生的虛擬機器程式碼用 pcap_freecode() 釋出。特定過濾表示式編譯時可能需要 network mask,pcap_lookupnet() 可用來網路界面的位址和 mask。

存封包

寫 pcap 檔:pcap_dump_open() -> pcap_dump() -> pcap_dump_close()。

統計

統計

送封包

pcap_inject() 或 pcap_sendpacket() 送封包到網路界面。兩者相同,只是前者回傳送出幾 byte,後者回傳 0 表成功。

回報錯誤

回報錯誤

取得版本資訊

取得版本資訊

使用 libpcap (或 windows 下 winpcap) 的程式

  • tcpdump:limited protocol decoding but 大多 *NIX 平台有。capture filter
  • wireshark:功能強大的網路分析程式。capture filter。可用 tcpdump 擷取,然後用 wireshark 分析。
  • tshark:wireshark 指令行版本。
  • dumpcap:wireshark 的一部分,只能擷取封包。
  • ettercap:用來 injecting traffic
  • OpenWrt

參考

  1. https://www.tcpdump.org/manpages/pcap.3pcap.html

udpdump

udpdump 是 wireshark 內部接收 UDP 封包的 server,由其它所在擷取的訊息裝載而成 。udpdump 接收後,把 UDP 進前的 Header 拿掉,轉著 EXPORTED_PDU 格式給 wireshark 解析。

EXPORTED_PDU 格式是訊息前面含有一些 TLV 格式的 meta 資訊
  0                   1                   2                   3
  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 |      Option Code              |         Option Length         |
 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 /                       Option Value                            /
 /             variable length, aligned to 32 bits               /
 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 /                                                               /
 /                 . . . other options . . .                     /
 /                                                               /
 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 |   Option Code == opt_endofopt  |  Option Length == 0          |
 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

依據 udpdump 原始碼,meta 資訊包含協定名稱 (在啟用時設定,預設 data)、實際來源 IP 和port、目的 IP (固定為 127.0.0.1)、實際目的 port (預設 5555)。

wireshark 依據協定名稱對訊息解析。

問題:協定如果是網路封包

參考來源
  • https://www.wireshark.org/docs/man-pages/udpdump.html 
  • https://code.wireshark.org/review/gitweb?p=wireshark.git;a=blob;f=epan/exported_pdu.h;hb=refs/heads/master
  •  https://www.wireshark.org/docs/wsdg_html_chunked/
  • https://www.wireshark.org/docs/wsdg_html_chunked/PartDevelopment.html

wireshark

wireshark 是功能強大的圖形界面網路分析程式。用 libpcap 或 winpcap 擷取封包

擷取過濾

顯示過濾

2020年6月13日 星期六

inet_pton() and inet_ntop()

IPv4 或 IPv6 位址表示字串,如:
  • 204.152.189.116 (dotted-decimal 的 IPv4 位址)
  • ::1 (colon-separated hexadecimal 的 IPv6 位址)
  • ::FFFF:204.152.189.116 (IPv4-mapped 的 IPv6 位址)
inet_pton() 可轉換成為二進位格式 (struct in_addr 或 strut in6_addr)。而 inet_ntop() 反之。 函數名稱中的 p 是「presentation」,指文字表示字串;n 是「network」。
#include <arpa/inet.h>

// 轉換 IPv4 或 IPv6 數字位址 (表示字串) src_str 為二進位格式 addrptr
int inet_pton(
    int family, // AF_INET 或 AF_INET6
    const char *src_str,
    void *addrptr);
// 回傳 1:成功、0:src_str 格式不是表示字串、–1 on error

// 轉換二進位格式 addrptr 為表示字串 dst_str
const char *inet_ntop(
    int family,
    const void *addrptr,
    char *dst_str,
    size_t len);
// 回傳 指向 dst_str 的文字字串: 成功, NULL: 錯誤
  • family 可以是 AF_INET 或 AF_INET6。擴充並捨棄 inet_aton() 與 inet_ntoa() (只能用在 IPv4)。問題:程式如何判斷位址是 IPv4 或 IPv6?
  • addrptr 依據 family 可指到 struct in_addr 或 struct in6_addr。
  • 呼叫 inet_ntop() 需提供長度 len 的 dst_str buffer,適當的長度是 INET_ADDRSTRLEN (16) 或 INET6_ADDRSTRLEN (46)。

參考來源

TLPI §59.6 §59.13.1

2020年3月13日 星期五

IP Multicast

有些應用需要進行一對多或多對多的封包傳送,例如網路廣播電台、網路電視廣播。如果封包使用 unicast 單點傳送的方式,傳送端需要先知道所有傳送的對象,一個一個傳送,對傳送端負擔較大,也需要很多倍的網路頻寬。封包的 broadcast 廣播通常會侷限在本地區域網路內,如果開放到網際網路容易造成網路雍塞而癱瘓。最適當的方式是用 multicast 多點傳送,傳送端負擔變少只需要傳送一次,由網路設備 (router 或 switch) 負責複製給每個需要的接收者,大大減少傳送端所需要的網路頻寬。

由於是由網路設備複製,網路設備需要知道那些網路埠有接收者,傳送者並不需要知道每個接收者是誰,只要知道有接收者並負責把風包丟出來即可。

IPv4 multicast 位址
  • 224.0.0.0/4,開頭為二進位的 1110,範圍為 224.0.0.0 ~ 239.255.255.255。
  • 對應的 Ethernet MAC 位址為 01:00:5e:xx:xx:xx,後 23-bit 來自 IP 位址後面 23 bits。可能 IP 位址不同,但 MAC 位址相同,此時 Switch 需要 multicast 它們的聯集。
  • 224.0.0/24:local link 區塊,由 IANA 個別指定。對應的 MAC 位址是 01:00:5e:00:00:xx,通常 L2 switch 會 broadcast 處理,不出 router。
    • 224.0.0.1:all hosts
    • 224.0.0.2:all routers
    • 224.0.0.18:VRRP
    • 224.0.0.22:IGMPv3 report
    • 224.0.0.251:mDNS
    • 224.0.0.252:LLMNR
  • 224.0.1/24:internetwork 區塊,由 IANA 個別指定
    • 224.0.1.1:NTP
    • 224.0.1.129 ~ 132:PTP 
    • 224.0.1.75:SIP
  • 224.0.2/24,224.4/15,233.252/14:Ad Hoc
  • 224.2/16:SDP/SAP
  • 232.0.0.0/8:Source Specific Multicast
  • 233.0.0.0/8:GLOP,16-bit ASN
  • 234.0.0.0/8:Unicast-Prefix-Based IPv4 Multicast addresses
  • 239.0.0.0/8:Administratively Scoped IP Multicast,由網管使用,封包不跨網管,位址在不同網管可重複使用。通常會再切割成較小區塊來限制特定 multicast 應用的範圍,避免小區塊間不必要的資料量。
    • 239.192/14:Organization local scope
    • 239.255/16:Local scope,不能再分割,可以往下擴充
    • Scope Relative addresses:相對於每個小區塊最後一個位址。每個小區塊預留最後 256 個位址
      • -0 (239.255.255.255):
      • -5 (239.255.255.250):SSDP
其他說明
  • 主要概念是一個 multicast IP 位址及由接收者驅動而建立的 multicast distribution tree
    • 接收者透過協定加入 multicast 群組,在 LAN 使用 IGMP (IPv4) 或 MLD (IPv6),在 routing domain 內用 PIM, MOSPF,domain 外用 MBGP
  • Protocol Independent Multicast
  • 封包傳送要遠離 source IP,跟 unicast 要接近 destination IP 不同。
  • IPv6 multicast 位址使用 Ethernet MAC 位址 33:33:xx:xx:xx:xx,後 32-bit 來自 IPv6 位址後面 4 bytes。
  • switch 監聽 IGMP 來維護其 multicast 表格稱為 IGMP snooping,如果有 L3 功能則可作為 IGMP querier。如果網路沒有 multicast router,有 IGMP snooping 能力的 switch 可用來產生需要的 IGMP 訊息給用戶加入 multicast 群組。如果 switch 沒這些功能,就只能 broadcast 處理這些 multicast 封包。
  • 無線網路原本就是 boardcast 環境,行為跟 Ethernet 有些不同。如果用戶都不在省電模式,multicast 封包會馬上送。如果有用戶在省電模式,AP 只在每個 DTIM interval 後送,且只在一個支援的速率送。無線網路有 ACK 來避免高遺失率,但 multicast 封包並不用 ACK 而可能有高遺失率。現在有一些方法處理這個問題,例如改用 unicast 一個一個傳 (只需改 AP)、或要求每個用戶 ACK (需要 AP 跟用戶都改)。
  • RTP、RSVP、mDNS
  • multicast 本質比較不適合 connection-oriented 這種有重傳的協定,但也有 TCP 例子 -- Pragmatic General Multicast
應用
  • Multicast Paging
參考來源
  1. CISCO:GUIDELINES FOR ENTERPRISE IP MULTICAST ADDRESS ALLOCATION (2004)
  2. https://en.wikipedia.org/wiki/IP_multicast
  3. https://en.wikipedia.org/wiki/Multicast_address 

2019年10月18日 星期五

iproute2

傳統上 Linux 使用 net-tools 工具程式 arp、ifconfig、和 route 來設定或查看網路,但這些功能有所限制。Linux kernel 2.2 之後使用重新設計的網路子系統,也需要新的工具程式。

iproute2 是 Linux 上管理 TCP/IP 網路的一套工具程式,包括網路界面、routing、tunnels、traffic control、和網路相關 device drivers,通常以套件 iproute 或 iproute2 發行。iproute2 工具程式使用 netlink 協定跟 Linux kernel 溝通。

net-toolsiproute2說明
ifconfig if[:n] ip[/len| netmask nm]ip addr add ip[/len] dev if界面 if 設定或新增 (有 :n) IPv4 位址 ip。netmask nmnm 需轉換成 prefix 長度 len
ifconfig if add ip/len界面 if 新增 IPv6 位址 ip,prefix 長度為 len
ifconfigip addr, ip link, ip -s其它 Address and link 設定
routeip routeRouting tables
arpip neighNeighbors
iptunnelip tunnelTunnels
nameififrename, ip link set name網路界面改名
ipmaddrip maddr群播
netstatip -s, ss, ip route顯示網路統計

除了 ip 指令,還有 ss, bridge, rtacct, rtmon, tc, ctstat, lnstat, nstat, routef, routel, rtstat, tipc, arpd 和 devlink。

參考
  1. https://en.wikipedia.org/wiki/Iproute2 
  2. https://wiki.linuxfoundation.org/networking/iproute2
  3. https://lartc.org/howto

2019年8月24日 星期六

OSI Reference Model

OSI (Open-data System Interface Reference Model) 把網路通訊的各種功能分為七個層級,由上而下分別為:
LayerOSIInternet Protocol Suit
7Application應用層ApplicationHTTP, FTP, ...
6Presentation表現層 (表達層)
5Session會談層 (會議層)
4Transport傳輸層 (傳送層)TransportTCP, UDP
3Network網路層NetworkIP, ICMP
2Data Link資料連結層LinkEthernet, ARP, Serial, ATM
1Physical實體層
作用:
  • 將網路功能模組化,便於說明以及元件開發。
  • 其它
Physical Layer:
Data Link Layer:
Network Layer:
Transport Layer:
Session Layer:
Presentation Layer:
Application Layer:
參考
  1. http://www.wunan.com.tw/www2/download/2S63_2版1刷_試閱_100.11.8.PDF 
  2. https://www.pcnet.idv.tw/pcnet/network/network_ip_model.htm 
  3. http://linux.vbird.org/linux_server/0110network_basic.php
  4. TCP/IP 分層協定參考 RFC-791 和 RFC-817  
  5. List of IP protocol numbers

2019年1月19日 星期六

pcap 封包擷取過濾式

pcap 封包擷取過濾式 (filter expression) 用在 tcpdumpWireshark (TShark)、Dumpcap 等程式,在擷取階段就篩選封包。其基本表示式 (primitive) 至少會有一個以上前置限定詞 (qualifier),然後可能會有一個數字或名稱的 id。

限定詞可大致分類成通訊協定 (proto)、傳送方向 (dir)、類型 (type) 三種:
  • type:說明 id 是指什麼,未指明預設是 host
    • host host:位址或主機名稱,如果沒指明 proto 是指 IPv4 或 IPv6 的位址或主機名稱。
    • net net [mask netmask] 或 net net/len:IPv4 或 IPv6 位址、subnet,可指明 netmask。
    • port port:TCP 或 UDP 的通訊埠。
    • portrange port1-port2:TCP 或 UDP 通訊埠的範圍。
  • dir:限定方向
    • srcdstsrc or dst (預設)、和 src and dst
    • proto wlan 限定:rataaddr1addr2addr3addr4dir
  • proto:限定協定,有 etheripip6arprarptcpudp 等,未指明則預設所有跟 type 能一致的協定。
此外還有其它特殊 keyword gatewaybroadcast 等,以及算術運算。較複雜的過濾表示用邏輯 and (&&)、or (||)、not (!)、以及「( )」來組合基本表示式。

範例

Ethernet 信頭
  • ether dst|src|host ehost:Ethernet 目的或來源位址是 ehostehost 可以是來自 /etc/ethers 的名稱或十六進位數字表示的 MAC 位址 (會忽略中間參雜的「:」、「.」、和「-」)。
  • ether ehost:錯誤。
  • [ether] broadcast:Ethernet 廣播封包。ether 可省略。
  • [ether] multicast:Ethernet 群播封包。ether 可省略。相當於 ether[0] & 1 != 0
  • [ether protoprotocol:Ethernet 的 Ether Type 是 protocolprotocol 可以是數字或名稱 ipip6arprarpatalkaarpdecnetscalatmopdlmoprcisostpipx、或 netbeui。註:由於這些名稱也是保留字,所以需要 backslash (\) 跳脫。
  • vlan [vlan_id]:
  • pppoed
  • pppoes [session_id]:
  • wlan ra|ta|addr1|addr2|addr3|addr4 ehost
  • [type wlan_type] [subtyp wlan_subtype]:
  • dir dir:
IP 位址或主機名稱
  • [ip|arp|rarp|ipv6] [dst|src] host hosthost 是 IPv4/IPv6 位址或主機名稱。前面可加協定限制、方向限制。ip host host 相當於 ether proto \ip and host host
  • gateway host:使用 host 作為 gateway 的封包,也就是使用 host 的 Ethernet 位址,但不是 host 的 IP 位址。host 的 IP 位址和 MAC 位址需要查得到。相當於 ether host ehost and not host host。
  • [dst|src] net net [mask netmask]:
  • [dst|src] net net[/len]:
  • ip broadcast
  • [ip|ip6] multicast
  • [[ip|ip6] proto] tcp|udp|icmp:協定是 tcp、ucp、或 icmp 封包。註:tcp, udp, and icmp 也是 keyword,所以需要 backslash (\) 跳脫。註:不能 chase the protocol header chain。
  • [ip|ip6] proto protocol:IPv4 或 IPv6 protocol type 是 protocol。protocol 可以是數字或名稱 icmp6, igmp, igrp, pim, ah, esp, or vrrp。註:不能 chase the protocol header chain.
  • [ip|ip6] protochain protocol:IPv4 或 IPv6 protocol chain 中含有 protocol。產生的 BPF 程式碼較複雜,且 kernel 不支援。
  • [tcp|udp] [dst|srcport port
  • [tcp|udp] [dst|srcportrange port1-port2
算術
  • expr relop exprrelop 是比大小 ><>=<==!= 之一。expr 可能是某個值、封包長度 len、或封包資料和正整數的 +-*/&|<<>>%^ 運算。(註:Linux 3.7 以後在 kernel 才能算 %^。) 封包資料用 proto[expr[:size]] 表示,指特定 proto 協定的 expr byte offset 的 size byte。size 可以是 1、2、4,預設是 1。特定 offset 或欄位可以用名稱表示,例如 tcp[tcpflags]。特定值可以用名稱表示,例如 tcp-syntcp-fin 等。
  • less|greater length:封包長度。相當於 len <= length 和 len >= length
其它

這些過濾描述會先編譯成 BPF 虛擬機器的指令碼,才給 BPF 執行。

參考來源

  1. Manpage of PCAP-FILTER
延伸閱讀
  • 顯示過濾式

2018年9月1日 星期六

pcapng file format

一般存放擷取封包的 pcap 檔案有一些限制,所以發展下一代的格式 -- The PCAP Next Generation Dump File Format (pcapng)。

檔案內容分成如下的區塊串接起來,前後有相同的長度欄位 (Block Total Length),限定出每個區塊的範圍,方便往後、或往前跳過不需要或不認得的 Block Type,容易擴展新定義的區塊。
32-bit Block Type
32-bit Block Total Length
Block Body
variable length, padded to 32 bits
32-bit Block Total Length
  • Block Total Length:整個區塊 byte 數。
  • Block Type:決定區塊內容 (Block Body) 的格式,區塊內容都會補齊 32-bit,所以區塊長度也會是 4 的倍數。
  • Block Body:依據 Block Type,除了必要欄位外,可放多個 TLV 選項。都 32-bit 對齊。

區塊雖然是一維線性串起來的,但有邏輯上的階層,最頂層一定是叫 Section Header Block 的區塊,一個檔案可以有多個頂層的 Section Header Block。

例如傳統 pcap 檔案轉成 pcapng 的區塊樹狀階層架構會是這樣:
Section Header Block
+- Interface Description Block
   +- Enhanced Packet Block
   +- Enhanced Packet Block
   +- ...
   +- Enhanced Packet Block

選項表

每個選項有 Type、Length、Value 三個欄位,可依 Length 跳過不需要或不認得的選項。
  • Option Type (2-byte):Option Type 的編碼。Most Significant Bit 為 1 保留為內部使用。
  • Option Length (2-byte):Option Value 不含補齊 32-bit 的實際長度。
  • Option Value (variable length):Option 的值,補到 32-bit 對齊。如果是字串,不能假設是以 0 結束。Option Length 為 0 則無此項。
有些 Option Type 可以重複,有些不行。選項表最後應該要有選項 'End of Option' (opt_endofopt)。

 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|      Option Code              |         Option Length         |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/                       Option Value                            /
/              variable length, padded to 32 bits               /
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/                                                               /
/                 . . . other options . . .                     /
/                                                               /
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|   Option Code == opt_endofopt  |  Option Length == 0          |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

名稱Code長度可多個?說明
opt_endofopt00no選項表結束。
opt_comment1可變utf-8 編碼的註解,字串沒有結束的 0。換行用「\r\n」或「\n」。
opt_custom
客訂選項
0x0BAC可變utf-8 編碼的字串,沒有結束的 0。複製到新檔案。
0x0BAD可變二進位資料。複製到新檔案。
0x4BAC可變utf-8 編碼的字串,沒有結束的 0。不複製到新檔案。
0x4BAD可變二進位資料。不複製到新檔案。

客訂選項有 4 種,選項值開頭放登記在 IANA 的 32-bit Private Enterprise Number (PEN) 來避免衝突。

 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|     Custom Option Code        |         Option Length         |
+---------------------------------------------------------------+
|                Private Enterprise Number (PEN)                |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/                        Custom Data                            /
/              variable length, padded to 32 bits               /
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

Section Header Block (SHB)

最頂層階層的區塊
   0                   1                   2                   3
   0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +---------------------------------------------------------------+
 0 |           Section Header Block Type = 0x0A0D0D0A              |
   +---------------------------------------------------------------+
 4 |                      Block Total Length                       |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 8 |                Byte-Order Magic = 0x1A2B3C4D                  |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
12 |        Major Version = 1      |       Minor Version = 0       |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
16 |                                                               |
   |                          Section Length                       |
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
24 /                                                               /
   /                      Options (variable)                       /
   /                                                               /
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                      Block Total Length                       |
   +---------------------------------------------------------------+
  • Block Type 0x0A0D0D0A (字串 "\n\r\r\n"):無論位元組順序怎樣都一樣都可以辨認到。透過 FTP 或 HTTP 傳送時,用來偵測不適當的 ASCII 轉換。
  • Byte-Order Magic 0x1A2B3C4D:用來偵測位元組順序 (byte order)。
  • Major Version 和 Minor Version:格式版本,目前 1.0。
  • Section Length (signed 64-bit value):不含 Section Header Block 自己的 section 長度。可用來快速跳過 section。-1 代表未知。4 的倍數。
  • Options:選項表。區塊特有選項有擷取機器的機型、作業系統、應用程式等。

Interface Description Block (IDB)

描述擷取封包的界面資訊。處理檔案的工具程式,會將每個 Section 的 IDB,獨立從 0 開始編號,稱為 Interface ID。Section 內其它有 Interface ID 欄位的區塊,就要有對應的 IDB。Simple Packet Block 沒有 Interface ID 欄位隱含 Interface ID 0。

    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +---------------------------------------------------------------+
 0 |                    Block Type = 0x00000001                    |
   +---------------------------------------------------------------+
 4 |                      Block Total Length                       |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 8 |           LinkType            |         Reserved = 0          |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
12 |                            SnapLen                            |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
16 /                                                               /
   /                      Options (variable)                       /
   /                                                               /
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                      Block Total Length                       |
   +---------------------------------------------------------------+
  • LinkType: 跟 pcap 的 header type 一樣。
  • SnapLen:每個封包最多擷取前面的 byte 數。0 表示不限制。
特有的選項有:
Name Code Length 可多個? 說明
if_name 2 Variable no
if_description 3 Variable no
if_IPv4addr 4 8 yes
if_IPv6addr 5 17 yes
if_MACaddr 6 6 no
if_EUIaddr 7 8 no
if_speed 8 8 no
if_tsresol91no時間精度。MSB 0:剩下是 10 的 negative power。MSB 1:剩下是 2 的 negative power。預設是 10-6,跟 pcap 預設的微秒一致。
if_tzone 10 4 no
if_filter 11 variable no
if_os 12 variable no
if_fcslen 13 1 no
if_tsoffset 14 8 no

Enhanced Packet Block (EPB)

標準放封包的區塊。另外封包也可以放在 Simple Packet Block,用來加速擷取檔案的產生。
   0                   1                   2                   3
   0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +---------------------------------------------------------------+
 0 |            Enhanced Packet Block Type = 0x00000006            |
   +---------------------------------------------------------------+
 4 |                      Block Total Length                       |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 8 |                         Interface ID                          |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
12 |                        Timestamp (High)                       |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
16 |                        Timestamp (Low)                        |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
20 |                    Captured Packet Length                     |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
24 |                    Original Packet Length                     |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
28 /                                                               /
   /                          Packet Data                          /
   /              variable length, padded to 32 bits               /
   /                                                               /
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   /                                                               /
   /                      Options (variable)                       /
   /                                                               /
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                      Block Total Length                       |
   +---------------------------------------------------------------+
  • Interface ID (32-bit):對應的 IDB。原本 Packet Block 只有 16-bit,另外 16-bit Drops Count 改移到 option。
  • Timestamp (High) and Timestamp (Low): 64-bit 的 epoch 時間,單位在 IDB 的 'if_tsresol' 選項,預設是微秒。在 pcap 是分成 32-bit 秒和 32-bit 微秒。
  • Captured Packet Length:Packet Data 的封包長度,不含補齊。會是 Original Packet Length 和 IDB 的 SnapLen 比較,值較小的。
  • Original Packet Length:在網路實際傳送的封包長度。
  • Packet Data:擷取的封包加上補到 32-bit 對齊。封包格式依據 IDB 的 LinkType 欄位。

Simple Packet Block (SPB)

SPB 簡化 EPB,只保留 Original Packet Length,只有 16-byte overhead,不需要取得 timestamp 和計算,適合有效能或空間瓶頸的情況。EPB 和 SPB 可以交錯使用。
    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +---------------------------------------------------------------+
 0 |                Simple Block Type = 0x00000003                 |
   +---------------------------------------------------------------+
 4 |                      Block Total Length                       |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 8 |                    Original Packet Length                     |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
12 /                                                               /
   /                          Packet Data                          /
   /              variable length, padded to 32 bits               /
   /                                                               /
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                      Block Total Length                       |
   +---------------------------------------------------------------+
  • Original Packet Length: 在網路實際傳送的封包長度。和 IDB 的 SnapLen 比較,較小的就是實際擷取的封包長度。
  • Packet Data:擷取的封包和 padding。封包格式依據 IDB 的 LinkType 欄位。

其它區塊

有 Name Resolution Block、Interface Statistics Block、Custom Block、及一些實驗性的區塊。 32-bit Block Type 的 Most Significant Bit (MSB) 為 1,保留為內部使用。

參考

  1. https://github.com/pcapng/pcapng

2018年8月25日 星期六

IPv4 與 IPv6 辨識和位址

項目IPv4IPv6說明
EtherType0x08000x86DD
header 版本46
header 長度2040不含 options
位址 bit 數32128
位址 byte 數416
familyAF_INETAF_INET6
data typestruct in_addr
(unsigned long)
struct in6_addr
字串表示逗點隔開的 4 個十進位數字
dotted-decimal
255.255.255.255
分號隔開的 8 組 4 位十六進位數字
 colon-separated hexadecimal
ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
IPv6 有簡寫規則
字串最長長度INET_ADDRSTRLEN
16
INET6_ADDRSTRLEN
46 (40)
含結尾 0。IPv6 位址 40-byte,但IPv4 tunneling 有 46-byte。

IPv6 簡寫規則:
  • 每組開頭的 0 可省略,若全為 0 ,則可簡寫為 0
  • 若連續好幾組全為 0,可全省略,只留下「::」,但以一次為限。
IPv4 tunneling (IPv4-mapped IPv6 位址)
  • 文字位址最長 46-byte:ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255
struct sockaddr_in {
    sa_family_t    sin_family; /* address family: AF_INET */
    in_port_t      sin_port;   /* port in network byte order */
    struct in_addr sin_addr;   /* internet address */
};

struct sockaddr_in6 {
    sa_family_t     sin6_family;   /* AF_INET6 */
    in_port_t       sin6_port;     /* port number */
    uint32_t        sin6_flowinfo; /* IPv6 flow information */
    struct in6_addr sin6_addr;     /* IPv6 address */
    uint32_t        sin6_scope_id; /* Scope ID */
};

flowinfo 作用?sin6_scope_id 只用在 link-local。

Kamailio 使用的 IP 位址

typedef struct ip_addr {
        unsigned int af;        /* address family: AF_INET6 or AF_INET */
        unsigned int len;       /* address len, 16 or 4 */

        /* 64 bits aligned address */
        union {
                unsigned long  addrl[16/sizeof(long)]; /* long format*/
                unsigned int   addr32[4];
                unsigned short addr16[8];
                unsigned char  addr[16];
        }u;
} ip_addr_t;

IPv4 位址

IPv6 位址

IPv6 位址分成三類
  • unicast:單一網路界面的位址。
  • anycast:多個網路界面共用的位址,只需要送給一個最近的成員。位址格式和 unicast 相同,通常用在 router,例如 gateway。
  • multicast: 群播給所有成員
    • IPv4 的廣播相當於定址給 link-local all-nodes multicast group ff02::1。
IPv6 沒有廣播位址,由 multicast 位址取代。

IPv6 位址 128-bit,一般前面 64-bit 為 Network ID 作 routing 使用,又可分成 Global Routing Prefix 跟 Subnet ID。後面 64-bit 為 Interface ID 用來識別主機界面,可能來自介面卡的 MAC address (使用 modified EUI-64 格式)、DHCPv6 伺服器、亂數產生、或手動指定。
  • ::/128:位址未指定,例如用在來源位址還不知道的時候,實作上或許作為任何位址使用。相當於 IPv4 的 0.0.0.0/32。
  • ::/96:IPv4-compatible address,剩下 32-bit 放 IPv4 位址。(捨棄)
  • ::/0:default route,相當於 IPv4 的 0.0.0.0/0。
  • ::1/128:localhost,相當於 IPv4 的 127.0.0.1/8。
  • ::ffff:0:0/96:IPv4-mapped IPv6 address
    • ::ffff:192.0.2.128
  • ::ffff:0:0:0/96:IPv4-translated address
  • 64:ff9b::/96:IPv4-Embedded IPv6 Address [RFC 6052]
  • 0100::/64:discarding
  • 2001::/32:Teredo tunneling (IPv6 transition mechanism)
  • 2001:2::/48:benchmarking IPv6,相當於 IPv4 的 192.18.0.0/15。
  • 2001:20::/28:ORCHIDv2
  • 2001:db8::/32:文件範例使用,相當於 IPv4 的 192.0.2.0/24、198.51.100.0/24、和 203.0.113.0/24。
  • 2002::/16:6to4
  • fc00::/7:Unique local address,相當於 IPv4 的 private 位址 10.0.0.0/8、172.16.0.0/12、和 192.168.0.0/16。
  • fe80::/64:link-local address,不跨 link 使用。後面 64-bit 通常使用 modified EUI-64 格式的介面卡 MAC 位址。相當於 IPv4 的 169.254.0.0/16。48-bit MAC 轉成 modified EUI-64 是 OUI 後插入 0xfffe,並將 universal/local bit 相反。
    • fe80::1
  • fec0::/10:Site-local address 不跨 site 使用。(捨棄 [RFC3879])
  • ffFS::/16: multicast address
    • F:4-bit 分別為 rRPT
      • r (reserved)
      • R (Rendezvous)
      • P (Prefix)
      • T (Traniet)。T = 1 表示 non-permanently-assigned ("transient"),T = 0 表示 IANA 有登記的 well-known multicast address
    • S (scope):有 14 種 scope
      • 1 = interface-local,不能跨界面,只能作為 multicast 回送,例如 IPC。不像 unicast loopback,可以指定給任何界面。
      • 2 = link-local,不能跨 link。
      • 4 = admin-local
      • 8 = organization-local
      • e = global
    • ff02::1:all link-local nodes
    • ff02::2:all link-local routers
    • ff02::1:ff00:0/104:Solicited-Node multicast address,後面 24-bit 來自 unicast/anycast 位址。
大位址空間
階層式位址配置 (prefix 依據網路拓樸分配,可縮小主幹路由表來提昇效率)

參考

  1. RFC3513 IPv6 Addressing Architecture
  2. IPv6 簡介
  3. IP 協定沿革
  4. RFC4213 Basic Transition Mechanisms for IPv6 Hosts and Routers
  5. https://en.wikipedia.org/wiki/IPv4
  6. RFC8200 IPv6 Specification
  7. RFC4007 IPv6 Scoped Address Architecture
    • 除了「::」,每個 IPv6 位址都隱含 scope 資訊。
    • scope zone
    • 同一種 scope 的 zone 不會重疊。因為非 global 位址會重複使用,所以 node 內部對每種 scope 的 zone 作 index,表示為 address%zone_id。
    • scope global 的 zone 是全世界,只有一個。
    • scope interface-local 的 zone 是每個界面一個。
    • zone 是靜態的,即使因斷線分成多個區塊,仍屬於同一 zone。
  8. link、interface、node、host、router

2018年8月23日 星期四

IP 協定沿革

  • IP 協定出現之前就有 TCP,TCP v1 在 1973 (RFC 675),TCP v2 在 1977。後來 Jon Postel 發現 TCP 同時作為 end to end 協定,以及封包包裝 和路由的協定,違反網路階層原則的發展方向,TCP 跟 IP 才分家,並同時使用版本 v3 (1978)。
  • v4 是第一個 IP 穩定版本。RFC 760 (1980) -> RFC 791 (1981)
  • v5 被 Internet Stream Protocol 用掉
  • v6:RFC 1883 (1995) -> RFC 2460 (1998) -> RFC 8200 (2017)

SIP header Via

所有 SIP 訊息 都要有 Via,縮寫 v。一開始的 UAC 和後續途經的每個 proxy 都會疊加一個 Via 放傳送的位址,依序作為回應的路徑。 格式 sent-protocol sent-by [ ;branch= branch ][ ; 參數 ...] s...