Packet.hpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #ifndef ZT_N_PACKET_HPP
  28. #define ZT_N_PACKET_HPP
  29. #include <stdint.h>
  30. #include <string.h>
  31. #include <stdio.h>
  32. #include <string>
  33. #include <iostream>
  34. #include "Constants.hpp"
  35. #include "Address.hpp"
  36. #include "Poly1305.hpp"
  37. #include "Salsa20.hpp"
  38. #include "Utils.hpp"
  39. #include "Buffer.hpp"
  40. #include "../ext/lz4/lz4.h"
  41. /**
  42. * Protocol version -- incremented only for MAJOR changes
  43. *
  44. * 1 - 0.2.0 ... 0.2.5
  45. * 2 - 0.3.0 ... 0.4.5
  46. * * Added signature and originating peer to multicast frame
  47. * * Double size of multicast frame bloom filter
  48. * 3 - 0.5.0 ... 0.6.0
  49. * * Yet another multicast redesign
  50. * * New crypto completely changes key agreement cipher
  51. * 4 - 0.6.0 ... CURRENT
  52. * * New identity format based on hashcash design
  53. *
  54. * This isn't going to change again for a long time unless your
  55. * author wakes up again at 4am with another great idea. :P
  56. */
  57. #define ZT_PROTO_VERSION 4
  58. /**
  59. * Minimum supported protocol version
  60. */
  61. #define ZT_PROTO_VERSION_MIN 4
  62. /**
  63. * Maximum hop count allowed by packet structure (3 bits, 0-7)
  64. *
  65. * This is not necessarily the maximum hop counter after which
  66. * relaying is no longer performed.
  67. */
  68. #define ZT_PROTO_MAX_HOPS 7
  69. /**
  70. * Cipher suite: Curve25519/Poly1305/Salsa20/12 without payload encryption
  71. *
  72. * This specifies Poly1305 MAC using a 32-bit key derived from the first
  73. * 32 bytes of a Salsa20/12 keystream as in the Salsa20/12 cipher suite,
  74. * but the payload is not encrypted. This is currently only used to send
  75. * HELLO since that's the public key specification packet and must be
  76. * sent in the clear. Key agreement is performed using Curve25519 elliptic
  77. * curve Diffie-Hellman.
  78. */
  79. #define ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE 0
  80. /**
  81. * Cipher suite: Curve25519/Poly1305/Salsa20/12
  82. *
  83. * This specifies Poly1305 using the first 32 bytes of a Salsa20/12 key
  84. * stream as its one-time-use key followed by payload encryption with
  85. * the remaining Salsa20/12 key stream. Key agreement is performed using
  86. * Curve25519 elliptic curve Diffie-Hellman.
  87. */
  88. #define ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012 1
  89. /**
  90. * Cipher suite: Curve25519/AES256-GCM
  91. *
  92. * This specifies AES256 in GCM mode using GCM's built-in authentication
  93. * with Curve25519 elliptic curve Diffie-Hellman.
  94. *
  95. * (Not implemented yet in client but reserved for future use.)
  96. */
  97. #define ZT_PROTO_CIPHER_SUITE__C25519_AES256_GCM 2
  98. /**
  99. * Header flag indicating that a packet is fragmented
  100. *
  101. * If this flag is set, the receiver knows to expect more than one fragment.
  102. * See Packet::Fragment for details.
  103. */
  104. #define ZT_PROTO_FLAG_FRAGMENTED 0x40
  105. /**
  106. * Verb flag indicating payload is compressed with LZ4
  107. */
  108. #define ZT_PROTO_VERB_FLAG_COMPRESSED 0x80
  109. /**
  110. * Rounds used for Salsa20 encryption in ZT
  111. */
  112. #define ZT_PROTO_SALSA20_ROUNDS 12
  113. // Indices of fields in normal packet header -- do not change as this
  114. // might require both code rework and will break compatibility.
  115. #define ZT_PACKET_IDX_IV 0
  116. #define ZT_PACKET_IDX_DEST 8
  117. #define ZT_PACKET_IDX_SOURCE 13
  118. #define ZT_PACKET_IDX_FLAGS 18
  119. #define ZT_PACKET_IDX_MAC 19
  120. #define ZT_PACKET_IDX_VERB 27
  121. #define ZT_PACKET_IDX_PAYLOAD 28
  122. /**
  123. * Packet buffer size (can be changed)
  124. */
  125. #define ZT_PROTO_MAX_PACKET_LENGTH (ZT_MAX_PACKET_FRAGMENTS * ZT_UDP_DEFAULT_PAYLOAD_MTU)
  126. /**
  127. * Minimum viable packet length (also length of header)
  128. */
  129. #define ZT_PROTO_MIN_PACKET_LENGTH ZT_PACKET_IDX_PAYLOAD
  130. // Indexes of fields in fragment header -- also can't be changed without
  131. // breaking compatibility.
  132. #define ZT_PACKET_FRAGMENT_IDX_PACKET_ID 0
  133. #define ZT_PACKET_FRAGMENT_IDX_DEST 8
  134. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR 13
  135. #define ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO 14
  136. #define ZT_PACKET_FRAGMENT_IDX_HOPS 15
  137. #define ZT_PACKET_FRAGMENT_IDX_PAYLOAD 16
  138. /**
  139. * Value found at ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR in fragments
  140. */
  141. #define ZT_PACKET_FRAGMENT_INDICATOR ZT_ADDRESS_RESERVED_PREFIX
  142. /**
  143. * Minimum viable fragment length
  144. */
  145. #define ZT_PROTO_MIN_FRAGMENT_LENGTH ZT_PACKET_FRAGMENT_IDX_PAYLOAD
  146. /**
  147. * Length of LAN beacon packets
  148. */
  149. #define ZT_PROTO_BEACON_LENGTH 13
  150. /**
  151. * Index of address in a LAN beacon
  152. */
  153. #define ZT_PROTO_BEACON_IDX_ADDRESS 8
  154. // Field incides for parsing verbs -------------------------------------------
  155. // Some verbs have variable-length fields. Those aren't fully defined here
  156. // yet-- instead they are parsed using relative indexes in IncomingPacket.
  157. // See their respective handler functions.
  158. #define ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION (ZT_PACKET_IDX_PAYLOAD)
  159. #define ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_PROTOCOL_VERSION + 1)
  160. #define ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO_IDX_MAJOR_VERSION + 1)
  161. #define ZT_PROTO_VERB_HELLO_IDX_REVISION (ZT_PROTO_VERB_HELLO_IDX_MINOR_VERSION + 1)
  162. #define ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP (ZT_PROTO_VERB_HELLO_IDX_REVISION + 2)
  163. #define ZT_PROTO_VERB_HELLO_IDX_IDENTITY (ZT_PROTO_VERB_HELLO_IDX_TIMESTAMP + 8)
  164. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  165. #define ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB + 1)
  166. #define ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE (ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID + 8)
  167. #define ZT_PROTO_VERB_ERROR_IDX_PAYLOAD (ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE + 1)
  168. #define ZT_PROTO_VERB_OK_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
  169. #define ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_OK_IDX_IN_RE_VERB + 1)
  170. #define ZT_PROTO_VERB_OK_IDX_PAYLOAD (ZT_PROTO_VERB_OK_IDX_IN_RE_PACKET_ID + 8)
  171. #define ZT_PROTO_VERB_WHOIS_IDX_ZTADDRESS (ZT_PACKET_IDX_PAYLOAD)
  172. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS (ZT_PACKET_IDX_PAYLOAD)
  173. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_FLAGS + 1)
  174. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT (ZT_PROTO_VERB_RENDEZVOUS_IDX_ZTADDRESS + 5)
  175. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN (ZT_PROTO_VERB_RENDEZVOUS_IDX_PORT + 2)
  176. #define ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRESS (ZT_PROTO_VERB_RENDEZVOUS_IDX_ADDRLEN + 1)
  177. #define ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  178. #define ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_FRAME_IDX_NETWORK_ID + 8)
  179. #define ZT_PROTO_VERB_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_FRAME_IDX_ETHERTYPE + 2)
  180. #define ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  181. #define ZT_PROTO_VERB_EXT_FRAME_LEN_NETWORK_ID 8
  182. #define ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS (ZT_PROTO_VERB_EXT_FRAME_IDX_NETWORK_ID + ZT_PROTO_VERB_EXT_FRAME_LEN_NETWORK_ID)
  183. #define ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS 1
  184. #define ZT_PROTO_VERB_EXT_FRAME_IDX_COM (ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS + ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS)
  185. #define ZT_PROTO_VERB_EXT_FRAME_IDX_TO (ZT_PROTO_VERB_EXT_FRAME_IDX_FLAGS + ZT_PROTO_VERB_EXT_FRAME_LEN_FLAGS)
  186. #define ZT_PROTO_VERB_EXT_FRAME_LEN_TO 6
  187. #define ZT_PROTO_VERB_EXT_FRAME_IDX_FROM (ZT_PROTO_VERB_EXT_FRAME_IDX_TO + ZT_PROTO_VERB_EXT_FRAME_LEN_TO)
  188. #define ZT_PROTO_VERB_EXT_FRAME_LEN_FROM 6
  189. #define ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_EXT_FRAME_IDX_FROM + ZT_PROTO_VERB_EXT_FRAME_LEN_FROM)
  190. #define ZT_PROTO_VERB_EXT_FRAME_LEN_ETHERTYPE 2
  191. #define ZT_PROTO_VERB_EXT_FRAME_IDX_PAYLOAD (ZT_PROTO_VERB_EXT_FRAME_IDX_ETHERTYPE + ZT_PROTO_VERB_EXT_FRAME_LEN_ETHERTYPE)
  192. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  193. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_NETWORK_ID + 8)
  194. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST_IDX_DICT_LEN + 2)
  195. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  196. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_NETWORK_ID + 8)
  197. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_FLAGS + 1)
  198. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_MAC + 6)
  199. #define ZT_PROTO_VERB_MULTICAST_GATHER_IDX_GATHER_LIMIT (ZT_PROTO_VERB_MULTICAST_GATHER_IDX_ADI + 4)
  200. // Note: COM, GATHER_LIMIT, and SOURCE_MAC are optional, and so are specified without size
  201. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID (ZT_PACKET_IDX_PAYLOAD)
  202. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_NETWORK_ID + 8)
  203. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_COM (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  204. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_GATHER_LIMIT (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  205. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_SOURCE_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  206. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FLAGS + 1)
  207. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_MAC + 6)
  208. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_DEST_ADI + 4)
  209. #define ZT_PROTO_VERB_MULTICAST_FRAME_IDX_FRAME (ZT_PROTO_VERB_MULTICAST_FRAME_IDX_ETHERTYPE + 2)
  210. #define ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  211. #define ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_TIMESTAMP + 8)
  212. #define ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_PROTOCOL_VERSION + 1)
  213. #define ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION (ZT_PROTO_VERB_HELLO__OK__IDX_MAJOR_VERSION + 1)
  214. #define ZT_PROTO_VERB_HELLO__OK__IDX_REVISION (ZT_PROTO_VERB_HELLO__OK__IDX_MINOR_VERSION + 1)
  215. #define ZT_PROTO_VERB_WHOIS__OK__IDX_IDENTITY (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  216. #define ZT_PROTO_VERB_WHOIS__ERROR__IDX_ZTADDRESS (ZT_PROTO_VERB_ERROR_IDX_PAYLOAD)
  217. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  218. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_NETWORK_ID + 8)
  219. #define ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT (ZT_PROTO_VERB_NETWORK_CONFIG_REQUEST__OK__IDX_DICT_LEN + 2)
  220. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  221. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_NETWORK_ID + 8)
  222. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_MAC + 6)
  223. #define ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_GATHER_RESULTS (ZT_PROTO_VERB_MULTICAST_GATHER__OK__IDX_ADI + 4)
  224. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID (ZT_PROTO_VERB_OK_IDX_PAYLOAD)
  225. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_NETWORK_ID + 8)
  226. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_MAC + 6)
  227. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_ADI + 4)
  228. #define ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_COM_AND_GATHER_RESULTS (ZT_PROTO_VERB_MULTICAST_FRAME__OK__IDX_FLAGS + 1)
  229. // ---------------------------------------------------------------------------
  230. namespace ZeroTier {
  231. /**
  232. * ZeroTier packet
  233. *
  234. * Packet format:
  235. * <[8] random initialization vector (doubles as 64-bit packet ID)>
  236. * <[5] destination ZT address>
  237. * <[5] source ZT address>
  238. * <[1] flags/cipher (top 5 bits) and ZT hop count (last 3 bits)>
  239. * <[8] 8-bit MAC (currently first 8 bytes of poly1305 tag)>
  240. * [... -- begin encryption envelope -- ...]
  241. * <[1] encrypted flags (top 3 bits) and verb (last 5 bits)>
  242. * [... verb-specific payload ...]
  243. *
  244. * Packets smaller than 28 bytes are invalid and silently discarded.
  245. *
  246. * The flags/cipher/hops bit field is: FFCCCHHH where C is a 3-bit cipher
  247. * selection allowing up to 8 cipher suites, F is flags (reserved, currently
  248. * all zero), and H is hop count.
  249. *
  250. * The three-bit hop count is the only part of a packet that is mutable in
  251. * transit without invalidating the MAC. All other bits in the packet are
  252. * immutable. This is because intermediate nodes can increment the hop
  253. * count up to 7 (protocol max).
  254. *
  255. * http://tonyarcieri.com/all-the-crypto-code-youve-ever-written-is-probably-broken
  256. *
  257. * For unencrypted packets, MAC is computed on plaintext. Only HELLO is ever
  258. * sent in the clear, as it's the "here is my public key" message.
  259. *
  260. * Beacon format and beacon packets:
  261. * <[8] 8 random bytes>
  262. * <[5] sender ZT address>
  263. *
  264. * A beacon is a 13-byte packet containing only the address of the sender.
  265. * Receiving peers may or may not respond to beacons with a HELLO or other
  266. * message to initiate direct communication.
  267. *
  268. * Beacons may be used for direct LAN announcement or NAT traversal.
  269. */
  270. class Packet : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  271. {
  272. public:
  273. /**
  274. * A packet fragment
  275. *
  276. * Fragments are sent if a packet is larger than UDP MTU. The first fragment
  277. * is sent with its normal header with the fragmented flag set. Remaining
  278. * fragments are sent this way.
  279. *
  280. * The fragmented bit indicates that there is at least one fragment. Fragments
  281. * themselves contain the total, so the receiver must "learn" this from the
  282. * first fragment it receives.
  283. *
  284. * Fragments are sent with the following format:
  285. * <[8] packet ID of packet whose fragment this belongs to>
  286. * <[5] destination ZT address>
  287. * <[1] 0xff, a reserved address, signals that this isn't a normal packet>
  288. * <[1] total fragments (most significant 4 bits), fragment no (LS 4 bits)>
  289. * <[1] ZT hop count (top 5 bits unused and must be zero)>
  290. * <[...] fragment data>
  291. *
  292. * The protocol supports a maximum of 16 fragments. If a fragment is received
  293. * before its main packet header, it should be cached for a brief period of
  294. * time to see if its parent arrives. Loss of any fragment constitutes packet
  295. * loss; there is no retransmission mechanism. The receiver must wait for full
  296. * receipt to authenticate and decrypt; there is no per-fragment MAC. (But if
  297. * fragments are corrupt, the MAC will fail for the whole assembled packet.)
  298. */
  299. class Fragment : public Buffer<ZT_PROTO_MAX_PACKET_LENGTH>
  300. {
  301. public:
  302. Fragment() :
  303. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>()
  304. {
  305. }
  306. template<unsigned int C2>
  307. Fragment(const Buffer<C2> &b)
  308. throw(std::out_of_range) :
  309. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  310. {
  311. }
  312. /**
  313. * Initialize from a packet
  314. *
  315. * @param p Original assembled packet
  316. * @param fragStart Start of fragment (raw index in packet data)
  317. * @param fragLen Length of fragment in bytes
  318. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  319. * @param fragTotal Total number of fragments (including 0)
  320. * @throws std::out_of_range Packet size would exceed buffer
  321. */
  322. Fragment(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  323. throw(std::out_of_range)
  324. {
  325. init(p,fragStart,fragLen,fragNo,fragTotal);
  326. }
  327. /**
  328. * Initialize from a packet
  329. *
  330. * @param p Original assembled packet
  331. * @param fragStart Start of fragment (raw index in packet data)
  332. * @param fragLen Length of fragment in bytes
  333. * @param fragNo Which fragment (>= 1, since 0 is Packet with end chopped off)
  334. * @param fragTotal Total number of fragments (including 0)
  335. * @throws std::out_of_range Packet size would exceed buffer
  336. */
  337. inline void init(const Packet &p,unsigned int fragStart,unsigned int fragLen,unsigned int fragNo,unsigned int fragTotal)
  338. throw(std::out_of_range)
  339. {
  340. if ((fragStart + fragLen) > p.size())
  341. throw std::out_of_range("Packet::Fragment: tried to construct fragment of packet past its length");
  342. setSize(fragLen + ZT_PROTO_MIN_FRAGMENT_LENGTH);
  343. // NOTE: this copies both the IV/packet ID and the destination address.
  344. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PACKET_ID,13),p.field(ZT_PACKET_IDX_IV,13),13);
  345. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] = ZT_PACKET_FRAGMENT_INDICATOR;
  346. (*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO] = (char)(((fragTotal & 0xf) << 4) | (fragNo & 0xf));
  347. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = 0;
  348. memcpy(field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,fragLen),p.field(fragStart,fragLen),fragLen);
  349. }
  350. /**
  351. * Get this fragment's destination
  352. *
  353. * @return Destination ZT address
  354. */
  355. inline Address destination() const { return Address(field(ZT_PACKET_FRAGMENT_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  356. /**
  357. * @return True if fragment is of a valid length
  358. */
  359. inline bool lengthValid() const { return (size() >= ZT_PACKET_FRAGMENT_IDX_PAYLOAD); }
  360. /**
  361. * @return ID of packet this is a fragment of
  362. */
  363. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_FRAGMENT_IDX_PACKET_ID); }
  364. /**
  365. * @return Total number of fragments in packet
  366. */
  367. inline unsigned int totalFragments() const { return (((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) >> 4) & 0xf); }
  368. /**
  369. * @return Fragment number of this fragment
  370. */
  371. inline unsigned int fragmentNumber() const { return ((unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_NO]) & 0xf); }
  372. /**
  373. * @return Fragment ZT hop count
  374. */
  375. inline unsigned int hops() const { return (unsigned int)((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]); }
  376. /**
  377. * Increment this packet's hop count
  378. */
  379. inline void incrementHops()
  380. {
  381. (*this)[ZT_PACKET_FRAGMENT_IDX_HOPS] = (((*this)[ZT_PACKET_FRAGMENT_IDX_HOPS]) + 1) & ZT_PROTO_MAX_HOPS;
  382. }
  383. /**
  384. * @return Length of payload in bytes
  385. */
  386. inline unsigned int payloadLength() const { return ((size() > ZT_PACKET_FRAGMENT_IDX_PAYLOAD) ? (size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD) : 0); }
  387. /**
  388. * @return Raw packet payload
  389. */
  390. inline const unsigned char *payload() const
  391. {
  392. return field(ZT_PACKET_FRAGMENT_IDX_PAYLOAD,size() - ZT_PACKET_FRAGMENT_IDX_PAYLOAD);
  393. }
  394. };
  395. /**
  396. * ZeroTier protocol verbs
  397. */
  398. enum Verb /* Max value: 32 (5 bits) */
  399. {
  400. /* No operation, payload ignored, no reply */
  401. VERB_NOP = 0,
  402. /* Announcement of a node's existence:
  403. * <[1] protocol version>
  404. * <[1] software major version>
  405. * <[1] software minor version>
  406. * <[2] software revision>
  407. * <[8] timestamp (ms since epoch)>
  408. * <[...] binary serialized identity (see Identity)>
  409. *
  410. * OK payload:
  411. * <[8] timestamp (echoed from original HELLO)>
  412. * <[1] protocol version (of responder)>
  413. * <[1] software major version (of responder)>
  414. * <[1] software minor version (of responder)>
  415. * <[2] software revision (of responder)>
  416. *
  417. * ERROR has no payload.
  418. */
  419. VERB_HELLO = 1,
  420. /* Error response:
  421. * <[1] in-re verb>
  422. * <[8] in-re packet ID>
  423. * <[1] error code>
  424. * <[...] error-dependent payload>
  425. */
  426. VERB_ERROR = 2,
  427. /* Success response:
  428. * <[1] in-re verb>
  429. * <[8] in-re packet ID>
  430. * <[...] request-specific payload>
  431. */
  432. VERB_OK = 3,
  433. /* Query an identity by address:
  434. * <[5] address to look up>
  435. *
  436. * OK response payload:
  437. * <[...] binary serialized identity>
  438. *
  439. * ERROR response payload:
  440. * <[5] address>
  441. */
  442. VERB_WHOIS = 4,
  443. /* Meet another node at a given protocol address:
  444. * <[1] flags (unused, currently 0)>
  445. * <[5] ZeroTier address of peer that might be found at this address>
  446. * <[2] 16-bit protocol address port>
  447. * <[1] protocol address length (4 for IPv4, 16 for IPv6)>
  448. * <[...] protocol address (network byte order)>
  449. *
  450. * This is sent by a relaying node to initiate NAT traversal between two
  451. * peers that are communicating by way of indirect relay. The relay will
  452. * send this to both peers at the same time on a periodic basis, telling
  453. * each where it might find the other on the network.
  454. *
  455. * Upon receipt a peer sends HELLO to establish a direct link.
  456. *
  457. * Nodes should implement rate control, limiting the rate at which they
  458. * respond to these packets to prevent their use in DDOS attacks. Nodes
  459. * may also ignore these messages if a peer is not known or is not being
  460. * actively communicated with.
  461. *
  462. * No OK or ERROR is generated.
  463. */
  464. VERB_RENDEZVOUS = 5,
  465. /* ZT-to-ZT unicast ethernet frame (shortened EXT_FRAME):
  466. * <[8] 64-bit network ID>
  467. * <[2] 16-bit ethertype>
  468. * <[...] ethernet payload>
  469. *
  470. * MAC addresses are derived from the packet's source and destination
  471. * ZeroTier addresses. This is a shortened EXT_FRAME that elides full
  472. * Ethernet framing and other optional flags and features when they
  473. * are not necessary.
  474. *
  475. * ERROR may be generated if a membership certificate is needed for a
  476. * closed network. Payload will be network ID.
  477. */
  478. VERB_FRAME = 6,
  479. /* Full Ethernet frame with MAC addressing and optional fields:
  480. * <[8] 64-bit network ID>
  481. * <[1] flags>
  482. * [<[...] certificate of network membership>]
  483. * <[6] destination MAC or all zero for destination node>
  484. * <[6] source MAC or all zero for node of origin>
  485. * <[2] 16-bit ethertype>
  486. * <[...] ethernet payload>
  487. *
  488. * Flags:
  489. * 0x01 - Certificate of network membership is attached
  490. *
  491. * An extended frame carries full MAC addressing, making them a
  492. * superset of VERB_FRAME. They're used for bridging or when we
  493. * want to attach a certificate since FRAME does not support that.
  494. *
  495. * Multicast frames may not be sent as EXT_FRAME.
  496. *
  497. * ERROR may be generated if a membership certificate is needed for a
  498. * closed network. Payload will be network ID.
  499. */
  500. VERB_EXT_FRAME = 7,
  501. /* DEPRECATED */
  502. VERB_P5_MULTICAST_FRAME = 8,
  503. /* Announce interest in multicast group(s):
  504. * <[8] 64-bit network ID>
  505. * <[6] multicast Ethernet address>
  506. * <[4] multicast additional distinguishing information (ADI)>
  507. * [... additional tuples of network/address/adi ...]
  508. *
  509. * LIKEs are sent to peers with whom you have a direct peer to peer
  510. * connection, and always including supernodes.
  511. *
  512. * OK/ERROR are not generated.
  513. */
  514. VERB_MULTICAST_LIKE = 9,
  515. /* Network member certificate replication/push:
  516. * <[...] serialized certificate of membership>
  517. * [ ... additional certificates may follow ...]
  518. *
  519. * Certificate contains network ID, peer it was issued for, etc.
  520. *
  521. * OK/ERROR are not generated.
  522. */
  523. VERB_NETWORK_MEMBERSHIP_CERTIFICATE = 10,
  524. /* Network configuration request:
  525. * <[8] 64-bit network ID>
  526. * <[2] 16-bit length of request meta-data dictionary>
  527. * <[...] string-serialized request meta-data>
  528. * [<[8] 64-bit timestamp of netconf we currently have>]
  529. *
  530. * This message requests network configuration from a node capable of
  531. * providing it. If the optional timestamp is included, a response is
  532. * only generated if there is a newer network configuration available.
  533. *
  534. * OK response payload:
  535. * <[8] 64-bit network ID>
  536. * <[2] 16-bit length of network configuration dictionary>
  537. * <[...] network configuration dictionary>
  538. *
  539. * OK returns a Dictionary (string serialized) containing the network's
  540. * configuration and IP address assignment information for the querying
  541. * node. It also contains a membership certificate that the querying
  542. * node can push to other peers to demonstrate its right to speak on
  543. * a given network.
  544. *
  545. * When a new network configuration is received, another config request
  546. * should be sent with the new netconf's timestamp. This confirms receipt
  547. * and also causes any subsequent changes to rapidly propagate as this
  548. * cycle will repeat until there are no changes. This is optional but
  549. * recommended behavior.
  550. *
  551. * ERROR response payload:
  552. * <[8] 64-bit network ID>
  553. *
  554. * UNSUPPORTED_OPERATION is returned if this service is not supported,
  555. * and OBJ_NOT_FOUND if the queried network ID was not found.
  556. */
  557. VERB_NETWORK_CONFIG_REQUEST = 11,
  558. /* Network configuration refresh request:
  559. * <[...] array of 64-bit network IDs>
  560. *
  561. * This message can be sent by the network configuration master node
  562. * to request that nodes refresh their network configuration. It can
  563. * thus be used to "push" updates so that network config changes will
  564. * take effect quickly.
  565. *
  566. * It does not generate an OK or ERROR message, and is treated only as
  567. * a hint to refresh now.
  568. */
  569. VERB_NETWORK_CONFIG_REFRESH = 12,
  570. /* Request endpoints for multicast distribution:
  571. * <[8] 64-bit network ID>
  572. * <[1] flags>
  573. * <[6] MAC address of multicast group being queried>
  574. * <[4] 32-bit ADI for multicast group being queried>
  575. * <[4] 32-bit requested max number of multicast peers>
  576. * [<[...] network certificate of membership>]
  577. *
  578. * Flags:
  579. * 0x01 - Network certificate of membership is attached
  580. *
  581. * This message asks a peer for additional known endpoints that have
  582. * LIKEd a given multicast group. It's sent when the sender wishes
  583. * to send multicast but does not have the desired number of recipient
  584. * peers.
  585. *
  586. * OK response payload:
  587. * <[8] 64-bit network ID>
  588. * <[6] MAC address of multicast group being queried>
  589. * <[4] 32-bit ADI for multicast group being queried>
  590. * [begin gather results -- these same fields can be in OK(MULTICAST_FRAME)]
  591. * <[4] 32-bit total number of known members in this multicast group>
  592. * <[2] 16-bit number of members enumerated in this packet>
  593. * <[...] series of 5-byte ZeroTier addresses of enumerated members>
  594. *
  595. * If no endpoints are known, OK and ERROR are both optional. It's okay
  596. * to return nothing in that case since gathering is "lazy."
  597. *
  598. * ERROR response payload:
  599. * <[8] 64-bit network ID>
  600. * <[6] MAC address of multicast group being queried>
  601. * <[4] 32-bit ADI for multicast group being queried>
  602. *
  603. * ERRORs are optional and are only generated if permission is denied,
  604. * certificate of membership is out of date, etc.
  605. */
  606. VERB_MULTICAST_GATHER = 13,
  607. /* Multicast frame:
  608. * <[8] 64-bit network ID>
  609. * <[1] flags>
  610. * [<[...] network certificate of membership>]
  611. * [<[4] 32-bit implicit gather limit>]
  612. * [<[6] source MAC>]
  613. * <[6] destination MAC (multicast address)>
  614. * <[4] 32-bit multicast ADI (multicast address extension)>
  615. * <[2] 16-bit ethertype>
  616. * <[...] ethernet payload>
  617. *
  618. * Flags:
  619. * 0x01 - Network certificate of membership is attached
  620. * 0x02 - Implicit gather limit field is present
  621. * 0x04 - Source MAC is specified -- otherwise it's computed from sender
  622. *
  623. * OK and ERROR responses are optional. OK may be generated if there are
  624. * implicit gather results or if the recipient wants to send its own
  625. * updated certificate of network membership to the sender. ERROR may be
  626. * generated if a certificate is needed or if multicasts to this group
  627. * are no longer wanted (multicast unsubscribe).
  628. *
  629. * OK response payload:
  630. * <[8] 64-bit network ID>
  631. * <[6] MAC address of multicast group>
  632. * <[4] 32-bit ADI for multicast group>
  633. * <[1] flags>
  634. * [<[...] network certficate of membership>]
  635. * [<[...] implicit gather results if flag 0x01 is set>]
  636. *
  637. * OK flags (same bits as request flags):
  638. * 0x01 - OK includes certificate of network membership
  639. * 0x02 - OK includes implicit gather results
  640. *
  641. * ERROR response payload:
  642. * <[8] 64-bit network ID>
  643. * <[6] multicast group MAC>
  644. * <[4] 32-bit multicast group ADI>
  645. */
  646. VERB_MULTICAST_FRAME = 14,
  647. /* Message sent to notify of a change in underlying address:
  648. * <[1] flags>
  649. * <[1] address type>
  650. * <[2] 16-bit length of address>
  651. * <[...] new address>
  652. *
  653. * Flags:
  654. * 0x01 - Address was confirmed (if unset no confirmation was done)
  655. *
  656. * Address types:
  657. * 0x01 - IPv4/UDP
  658. * 0x02 - IPv6/UDP
  659. * 0x03 - IPv4/TCP
  660. * 0x04 - IPv6/TCP
  661. * 0x05 - Ethernet MAC (raw framing address)
  662. * 0x06 - Bluetooth MAC
  663. * 0x07 - HTTP URL
  664. * (other values are reserved)
  665. *
  666. * Address formats:
  667. * IPv4: 32-bit address, 16-bit port in network byte order
  668. * IPv6: 128-bit address, 16-bit port in network byte order
  669. * Ethernet: 48-bit / 6-byte MAC
  670. * Bluetooth: 48-bit / 6-byte Bluetooth MAC
  671. * HTTP URL: ASCII string containing endpoint URL
  672. *
  673. * This should be sent by peers when a new remote address is detected by
  674. * way of a new packet from a previously unknown underlying physical
  675. * address. It may also be sent with flag 0x01 set once a new address is
  676. * confirmed via a bi-directional transaction, indicating a higher
  677. * confidence level.
  678. *
  679. * Peers can use this message to trigger reconnection semantics when
  680. * mobility, DHCP reassignment, VM migration, or other factors lead to
  681. * a change in physical address.
  682. */
  683. VERB_PHYSICAL_ADDRESS_CHANGED = 15
  684. };
  685. /**
  686. * Error codes for VERB_ERROR
  687. */
  688. enum ErrorCode
  689. {
  690. /* No error, not actually used in transit */
  691. ERROR_NONE = 0,
  692. /* Invalid request */
  693. ERROR_INVALID_REQUEST = 1,
  694. /* Bad/unsupported protocol version */
  695. ERROR_BAD_PROTOCOL_VERSION = 2,
  696. /* Unknown object queried (e.g. with WHOIS) */
  697. ERROR_OBJ_NOT_FOUND = 3,
  698. /* HELLO pushed an identity whose address is already claimed */
  699. ERROR_IDENTITY_COLLISION = 4,
  700. /* Verb or use case not supported/enabled by this node */
  701. ERROR_UNSUPPORTED_OPERATION = 5,
  702. /* Message to private network rejected -- no unexpired certificate on file */
  703. ERROR_NEED_MEMBERSHIP_CERTIFICATE = 6,
  704. /* Tried to join network, but you're not a member */
  705. ERROR_NETWORK_ACCESS_DENIED_ = 7, /* extra _ to avoid Windows name conflict */
  706. /* Multicasts to this group are not wanted */
  707. ERROR_UNWANTED_MULTICAST = 8
  708. };
  709. /**
  710. * @param v Verb
  711. * @return String representation (e.g. HELLO, OK)
  712. */
  713. static const char *verbString(Verb v)
  714. throw();
  715. /**
  716. * @param e Error code
  717. * @return String error name
  718. */
  719. static const char *errorString(ErrorCode e)
  720. throw();
  721. template<unsigned int C2>
  722. Packet(const Buffer<C2> &b)
  723. throw(std::out_of_range) :
  724. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(b)
  725. {
  726. }
  727. /**
  728. * Construct a new empty packet with a unique random packet ID
  729. *
  730. * Flags and hops will be zero. Other fields and data region are undefined.
  731. * Use the header access methods (setDestination() and friends) to fill out
  732. * the header. Payload should be appended; initial size is header size.
  733. */
  734. Packet() :
  735. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  736. {
  737. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  738. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  739. }
  740. /**
  741. * Make a copy of a packet with a new initialization vector and destination address
  742. *
  743. * This can be used to take one draft prototype packet and quickly make copies to
  744. * encrypt for different destinations.
  745. *
  746. * @param prototype Prototype packet
  747. * @param dest Destination ZeroTier address for new packet
  748. */
  749. Packet(const Packet &prototype,const Address &dest) :
  750. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(prototype)
  751. {
  752. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  753. setDestination(dest);
  754. }
  755. /**
  756. * Construct a new empty packet with a unique random packet ID
  757. *
  758. * @param dest Destination ZT address
  759. * @param source Source ZT address
  760. * @param v Verb
  761. */
  762. Packet(const Address &dest,const Address &source,const Verb v) :
  763. Buffer<ZT_PROTO_MAX_PACKET_LENGTH>(ZT_PROTO_MIN_PACKET_LENGTH)
  764. {
  765. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  766. setDestination(dest);
  767. setSource(source);
  768. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  769. setVerb(v);
  770. }
  771. /**
  772. * Reset this packet structure for reuse in place
  773. *
  774. * @param dest Destination ZT address
  775. * @param source Source ZT address
  776. * @param v Verb
  777. */
  778. inline void reset(const Address &dest,const Address &source,const Verb v)
  779. {
  780. setSize(ZT_PROTO_MIN_PACKET_LENGTH);
  781. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  782. setDestination(dest);
  783. setSource(source);
  784. (*this)[ZT_PACKET_IDX_FLAGS] = 0; // zero flags and hops
  785. setVerb(v);
  786. }
  787. /**
  788. * Generate a new IV / packet ID in place
  789. *
  790. * This can be used to re-use a packet buffer multiple times to send
  791. * technically different but otherwise identical copies of the same
  792. * packet.
  793. */
  794. inline void newInitializationVector()
  795. {
  796. Utils::getSecureRandom(field(ZT_PACKET_IDX_IV,8),8);
  797. }
  798. /**
  799. * Set this packet's destination
  800. *
  801. * @param dest ZeroTier address of destination
  802. */
  803. inline void setDestination(const Address &dest)
  804. {
  805. unsigned char *d = field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH);
  806. for(unsigned int i=0;i<ZT_ADDRESS_LENGTH;++i)
  807. d[i] = dest[i];
  808. }
  809. /**
  810. * Set this packet's source
  811. *
  812. * @param source ZeroTier address of source
  813. */
  814. inline void setSource(const Address &source)
  815. {
  816. unsigned char *s = field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH);
  817. for(unsigned int i=0;i<ZT_ADDRESS_LENGTH;++i)
  818. s[i] = source[i];
  819. }
  820. /**
  821. * Get this packet's destination
  822. *
  823. * @return Destination ZT address
  824. */
  825. inline Address destination() const { return Address(field(ZT_PACKET_IDX_DEST,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  826. /**
  827. * Get this packet's source
  828. *
  829. * @return Source ZT address
  830. */
  831. inline Address source() const { return Address(field(ZT_PACKET_IDX_SOURCE,ZT_ADDRESS_LENGTH),ZT_ADDRESS_LENGTH); }
  832. /**
  833. * @return True if packet is of valid length
  834. */
  835. inline bool lengthValid() const { return (size() >= ZT_PROTO_MIN_PACKET_LENGTH); }
  836. /**
  837. * @return True if packet is fragmented (expect fragments)
  838. */
  839. inline bool fragmented() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_FRAGMENTED) != 0); }
  840. /**
  841. * Set this packet's fragmented flag
  842. *
  843. * @param f Fragmented flag value
  844. */
  845. inline void setFragmented(bool f)
  846. {
  847. if (f)
  848. (*this)[ZT_PACKET_IDX_FLAGS] |= (char)ZT_PROTO_FLAG_FRAGMENTED;
  849. else (*this)[ZT_PACKET_IDX_FLAGS] &= (char)(~ZT_PROTO_FLAG_FRAGMENTED);
  850. }
  851. /**
  852. * @return True if compressed (result only valid if unencrypted)
  853. */
  854. inline bool compressed() const { return (((unsigned char)(*this)[ZT_PACKET_IDX_VERB] & ZT_PROTO_VERB_FLAG_COMPRESSED) != 0); }
  855. /**
  856. * @return ZeroTier forwarding hops (0 to 7)
  857. */
  858. inline unsigned int hops() const { return ((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x07); }
  859. /**
  860. * Increment this packet's hop count
  861. */
  862. inline void incrementHops()
  863. {
  864. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  865. b = (b & 0xf8) | ((b + 1) & 0x07);
  866. }
  867. /**
  868. * @return Cipher suite selector: 0 - 7 (see #defines)
  869. */
  870. inline unsigned int cipher() const
  871. {
  872. //return (((unsigned int)(*this)[ZT_PACKET_IDX_FLAGS] & 0x38) >> 3);
  873. // Use DEPRECATED 0x80 "encrypted" flag -- this will go away once there are no more <1.0.0 peers on the net
  874. return (((*this)[ZT_PACKET_IDX_FLAGS] & 0x80) == 0) ? ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE : ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012;
  875. }
  876. /**
  877. * Set this packet's cipher suite
  878. *
  879. * This normally shouldn't be called directly as armor() will set it after
  880. * encrypting and MACing the packet.
  881. */
  882. inline void setCipher(unsigned int c)
  883. {
  884. unsigned char &b = (*this)[ZT_PACKET_IDX_FLAGS];
  885. b = (b & 0xc7) | (unsigned char)((c << 3) & 0x38);
  886. // Set both the new cipher suite spec field and the old DEPRECATED "encrypted" flag as long as there's <1.0.0 peers online
  887. if (c == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)
  888. b |= 0x80;
  889. else b &= 0x7f;
  890. }
  891. /**
  892. * Get this packet's unique ID (the IV field interpreted as uint64_t)
  893. *
  894. * @return Packet ID
  895. */
  896. inline uint64_t packetId() const { return at<uint64_t>(ZT_PACKET_IDX_IV); }
  897. /**
  898. * Set packet verb
  899. *
  900. * This also has the side-effect of clearing any verb flags, such as
  901. * compressed, and so must only be done during packet composition.
  902. *
  903. * @param v New packet verb
  904. */
  905. inline void setVerb(Verb v) { (*this)[ZT_PACKET_IDX_VERB] = (char)v; }
  906. /**
  907. * @return Packet verb (not including flag bits)
  908. */
  909. inline Verb verb() const { return (Verb)((*this)[ZT_PACKET_IDX_VERB] & 0x1f); }
  910. /**
  911. * @return Length of packet payload
  912. */
  913. inline unsigned int payloadLength() const { return ((size() < ZT_PROTO_MIN_PACKET_LENGTH) ? 0 : (size() - ZT_PROTO_MIN_PACKET_LENGTH)); }
  914. /**
  915. * @return Raw packet payload
  916. */
  917. inline const unsigned char *payload() const
  918. {
  919. return field(ZT_PACKET_IDX_PAYLOAD,size() - ZT_PACKET_IDX_PAYLOAD);
  920. }
  921. /**
  922. * Armor packet for transport
  923. *
  924. * @param key 32-byte key
  925. * @param encryptPayload If true, encrypt packet payload, else just MAC
  926. */
  927. inline void armor(const void *key,bool encryptPayload)
  928. {
  929. unsigned char mangledKey[32];
  930. unsigned char macKey[32];
  931. unsigned char mac[16];
  932. const unsigned int payloadLen = size() - ZT_PACKET_IDX_VERB;
  933. unsigned char *const payload = field(ZT_PACKET_IDX_VERB,payloadLen);
  934. // Set flag now, since it affects key mangle function
  935. setCipher(encryptPayload ? ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012 : ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE);
  936. _salsa20MangleKey((const unsigned char *)key,mangledKey);
  937. Salsa20 s20(mangledKey,256,field(ZT_PACKET_IDX_IV,8),ZT_PROTO_SALSA20_ROUNDS);
  938. // MAC key is always the first 32 bytes of the Salsa20 key stream
  939. // This is the same construction DJB's NaCl library uses
  940. s20.encrypt(ZERO_KEY,macKey,sizeof(macKey));
  941. if (encryptPayload)
  942. s20.encrypt(payload,payload,payloadLen);
  943. Poly1305::compute(mac,payload,payloadLen,macKey);
  944. memcpy(field(ZT_PACKET_IDX_MAC,8),mac,8);
  945. }
  946. /**
  947. * Verify and (if encrypted) decrypt packet
  948. *
  949. * @param key 32-byte key
  950. * @return False if packet is invalid or failed MAC authenticity check
  951. */
  952. inline bool dearmor(const void *key)
  953. {
  954. unsigned char mangledKey[32];
  955. unsigned char macKey[32];
  956. unsigned char mac[16];
  957. const unsigned int payloadLen = size() - ZT_PACKET_IDX_VERB;
  958. unsigned char *const payload = field(ZT_PACKET_IDX_VERB,payloadLen);
  959. unsigned int cs = cipher();
  960. if ((cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE)||(cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)) {
  961. _salsa20MangleKey((const unsigned char *)key,mangledKey);
  962. Salsa20 s20(mangledKey,256,field(ZT_PACKET_IDX_IV,8),ZT_PROTO_SALSA20_ROUNDS);
  963. s20.encrypt(ZERO_KEY,macKey,sizeof(macKey));
  964. Poly1305::compute(mac,payload,payloadLen,macKey);
  965. if (!Utils::secureEq(mac,field(ZT_PACKET_IDX_MAC,8),8))
  966. return false;
  967. if (cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)
  968. s20.decrypt(payload,payload,payloadLen);
  969. return true;
  970. } else if (cs == ZT_PROTO_CIPHER_SUITE__C25519_AES256_GCM) {
  971. return false; // not implemented yet
  972. } else return false; // unrecognized cipher suite
  973. }
  974. /**
  975. * Attempt to compress payload if not already (must be unencrypted)
  976. *
  977. * This requires that the payload at least contain the verb byte already
  978. * set. The compressed flag in the verb is set if compression successfully
  979. * results in a size reduction. If no size reduction occurs, compression
  980. * is not done and the flag is left cleared.
  981. *
  982. * @return True if compression occurred
  983. */
  984. inline bool compress()
  985. {
  986. unsigned char buf[ZT_PROTO_MAX_PACKET_LENGTH * 2];
  987. if ((!compressed())&&(size() > (ZT_PACKET_IDX_PAYLOAD + 32))) {
  988. int pl = (int)(size() - ZT_PACKET_IDX_PAYLOAD);
  989. int cl = LZ4_compress((const char *)field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)pl),(char *)buf,pl);
  990. if ((cl > 0)&&(cl < pl)) {
  991. (*this)[ZT_PACKET_IDX_VERB] |= (char)ZT_PROTO_VERB_FLAG_COMPRESSED;
  992. setSize((unsigned int)cl + ZT_PACKET_IDX_PAYLOAD);
  993. memcpy(field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)cl),buf,cl);
  994. return true;
  995. }
  996. }
  997. (*this)[ZT_PACKET_IDX_VERB] &= (char)(~ZT_PROTO_VERB_FLAG_COMPRESSED);
  998. return false;
  999. }
  1000. /**
  1001. * Attempt to decompress payload if it is compressed (must be unencrypted)
  1002. *
  1003. * If payload is compressed, it is decompressed and the compressed verb
  1004. * flag is cleared. Otherwise nothing is done and true is returned.
  1005. *
  1006. * @return True if data is now decompressed and valid, false on error
  1007. */
  1008. inline bool uncompress()
  1009. {
  1010. unsigned char buf[ZT_PROTO_MAX_PACKET_LENGTH];
  1011. if ((compressed())&&(size() >= ZT_PROTO_MIN_PACKET_LENGTH)) {
  1012. if (size() > ZT_PACKET_IDX_PAYLOAD) {
  1013. unsigned int compLen = size() - ZT_PACKET_IDX_PAYLOAD;
  1014. int ucl = LZ4_decompress_safe((const char *)field(ZT_PACKET_IDX_PAYLOAD,compLen),(char *)buf,compLen,sizeof(buf));
  1015. if ((ucl > 0)&&(ucl <= (int)(capacity() - ZT_PACKET_IDX_PAYLOAD))) {
  1016. setSize((unsigned int)ucl + ZT_PACKET_IDX_PAYLOAD);
  1017. memcpy(field(ZT_PACKET_IDX_PAYLOAD,(unsigned int)ucl),buf,ucl);
  1018. } else return false;
  1019. }
  1020. (*this)[ZT_PACKET_IDX_VERB] &= (char)(~ZT_PROTO_VERB_FLAG_COMPRESSED);
  1021. }
  1022. return true;
  1023. }
  1024. private:
  1025. static const unsigned char ZERO_KEY[32];
  1026. /**
  1027. * Deterministically mangle a 256-bit crypto key based on packet
  1028. *
  1029. * This uses extra data from the packet to mangle the secret, giving us an
  1030. * effective IV that is somewhat more than 64 bits. This is "free" for
  1031. * Salsa20 since it has negligible key setup time so using a different
  1032. * key each time is fine.
  1033. *
  1034. * @param in Input key (32 bytes)
  1035. * @param out Output buffer (32 bytes)
  1036. */
  1037. inline void _salsa20MangleKey(const unsigned char *in,unsigned char *out) const
  1038. {
  1039. const unsigned char *d = (const unsigned char *)data();
  1040. // IV and source/destination addresses. Using the addresses divides the
  1041. // key space into two halves-- A->B and B->A (since order will change).
  1042. for(unsigned int i=0;i<18;++i) // 8 + (ZT_ADDRESS_LENGTH * 2) == 18
  1043. out[i] = in[i] ^ d[i];
  1044. // Flags, but with hop count masked off. Hop count is altered by forwarding
  1045. // nodes. It's one of the only parts of a packet modifiable by people
  1046. // without the key.
  1047. out[18] = in[18] ^ (d[ZT_PACKET_IDX_FLAGS] & 0xf8);
  1048. // Raw packet size in bytes -- thus each packet size defines a new
  1049. // key space.
  1050. out[19] = in[19] ^ (unsigned char)(size() & 0xff);
  1051. out[20] = in[20] ^ (unsigned char)((size() >> 8) & 0xff); // little endian
  1052. // Rest of raw key is used unchanged
  1053. for(unsigned int i=21;i<32;++i)
  1054. out[i] = in[i];
  1055. }
  1056. };
  1057. } // namespace ZeroTier
  1058. #endif