├── .github └── workflows │ ├── build.yml │ └── test.yml ├── .gitignore ├── CHANGELOG.md ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── cmd ├── eve2filter.go ├── exampleConfig.go ├── extract.go ├── filter.go ├── map.go ├── replay.go ├── root.go ├── tarExtract.go └── version.go ├── configs └── gophercap.yml ├── go.mod ├── go.sum ├── main.go └── pkg ├── dedup ├── dedup.go └── dedup_test.go ├── extract ├── filter.go ├── functions.go └── pcapfiles.go ├── filter ├── condition.go ├── config.go ├── filter.go ├── generate.go └── packet.go ├── models └── models.go └── replay ├── magic.go ├── map.go ├── map_pcap.go ├── map_set.go └── replay.go /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | 3 | on: 4 | push: 5 | tags: 6 | - '*' 7 | 8 | jobs: 9 | 10 | build: 11 | name: Build binary 12 | runs-on: ubuntu-20.04 13 | steps: 14 | 15 | - name: Set up Go 1.x 16 | uses: actions/setup-go@v2 17 | with: 18 | go-version: 1.21 19 | 20 | - name: Check out code into the Go module directory 21 | uses: actions/checkout@v2 22 | 23 | - name: Install libpcap 24 | run: sudo apt install -y libpcap-dev --install-suggests 25 | 26 | - name: Get dependencies 27 | run: go get -v 28 | working-directory: "." 29 | 30 | - name: Install govulncheck 31 | run: go install golang.org/x/vuln/cmd/govulncheck@latest 32 | 33 | - name: Check for vulnerabilities 34 | run: govulncheck ./... 35 | 36 | - name: Build 37 | run: go build -ldflags="-X 'gopherCap/cmd.Version=${{ github.ref_name }}'" -o gopherCap . 38 | working-directory: "." 39 | 40 | - name: Execute binary for testing 41 | run: ./gopherCap --help 42 | working-directory: "." 43 | 44 | - name: Compress the binary 45 | run: gzip gopherCap 46 | working-directory: "." 47 | 48 | - uses: actions/upload-artifact@v2 49 | with: 50 | name: gopherCap.gz 51 | path: ./gopherCap.gz 52 | 53 | - name: Upload Linux binary to release 54 | uses: svenstaro/upload-release-action@v2 55 | with: 56 | repo_token: ${{ secrets.GITHUB_TOKEN }} 57 | file: ./gopherCap.gz 58 | asset_name: gopherCap.gz 59 | tag: ${{ github.ref }} 60 | overwrite: true 61 | body: | 62 | ## Install 63 | 64 | Simply decompress the binary and make it executable. All documentation can be found using `--help`. 65 | * Ensure that **libpcap** is installed; 66 | * Requires amd64 platform, we do not provide arm builds because we build against libpcap; 67 | * Only tested on recent ubuntu / debian, binary will likely crash on rolling-release distros such as arch or fedora because build is linked to `libc` and `libpcap`; 68 | 69 | ``` 70 | gunzip gopherCap.gz 71 | chmod u+x gopherCap 72 | ./gopherCap --help 73 | ``` 74 | 75 | Full configuration dictionary can be generated with `exampleConfig` command. 76 | 77 | ``` 78 | ./gopherCap --config example.yml exampleConfig 79 | ``` 80 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test go code 2 | 3 | on: 4 | push: 5 | branches: [ master, next-* ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | 11 | build: 12 | runs-on: ubuntu-20.04 13 | steps: 14 | - uses: actions/checkout@v2 15 | 16 | - name: Install libpcap 17 | run: sudo apt install -y libpcap-dev --install-suggests 18 | 19 | - name: Set up Go 1.x 20 | uses: actions/setup-go@v2 21 | with: 22 | go-version: 1.21 23 | 24 | - name: Build 25 | run: go build -v ./... 26 | 27 | - name: Test 28 | run: go test -v ./... 29 | 30 | - name: Install govulncheck 31 | run: go install golang.org/x/vuln/cmd/govulncheck@latest 32 | 33 | - name: Check for vulnerabilities 34 | run: govulncheck ./... 35 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/StamusNetworks/gophercap/fbe41dfcb5d115c13f7b8efdf2215a8428665465/.gitignore -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 0.3.2 2 | 3 | ## Release highlights 4 | 5 | * dependency updates and go 1.21 build 6 | * filter: fix mismatch pkt lenght and capture lenght after decap 7 | 8 | # 0.3.1 9 | 10 | ## Release highlights 11 | 12 | * ci: pipeline improvements 13 | * mod: dependency updates 14 | * filter: usability improvements and optimizations 15 | * filter: support for packet deduplication 16 | 17 | # 0.3.0 18 | 19 | ## Release highlights 20 | 21 | * extract: PCAP folder discovery from EVE 22 | * filter: combined match logic 23 | * eve2filter: generate filters from alerts 24 | * filter: filter packets by ASN 25 | * replay: refactors and general improvements 26 | * make: Debian build using docker 27 | * ci: improvements and move to github actions 28 | * mod: bump to Go 1.19 and update dependencies 29 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.19-buster AS Builder 2 | 3 | ARG var_version=devel 4 | ENV VERSION=$var_version 5 | 6 | RUN mkdir -p /src 7 | COPY . /src/gopherCap 8 | WORKDIR /src/gopherCap 9 | 10 | RUN apt-get update && apt-get install -y libpcap-dev 11 | RUN go build -ldflags="-X 'gopherCap/cmd.Version=${VERSION}'" -o /tmp/gopherCap ./ 12 | 13 | FROM debian:buster 14 | RUN apt-get update && apt-get install -y libpcap0.8 && apt-get -y autoremove && apt-get -y autoclean && apt-get clean 15 | COPY --from=Builder /tmp/gopherCap /usr/local/bin/ 16 | ENTRYPOINT [ "/usr/local/bin/gopherCap" ] 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | GIT_VERSION = $(shell git log -1 --pretty=format:"%h") 2 | GO_LDFLAGS = "-X 'gopherCap/cmd.Version=$(GIT_VERSION)'" 3 | 4 | all: 5 | @$(MAKE) build 6 | build: 7 | go build -ldflags=$(GO_LDFLAGS) -o ./gopherCap ./ 8 | build-debian: 9 | @$(MAKE) clean-docker-builder 10 | @$(MAKE) build-docker-debian 11 | @$(MAKE) clean-docker-builder 12 | build-docker-debian: 13 | docker build -t stamus/gophercap . 14 | docker run --name gophercap-builder --entrypoint bash -d stamus/gophercap 15 | docker cp gophercap-builder:/usr/local/bin/gopherCap . 16 | clean-docker-builder: 17 | docker rm gophercap-builder || echo "container not running" 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GopherCap 2 | 3 | > Accurate, modular, scalable PCAP manipulation tool written in Go. 4 | 5 | GoperCap uses [gopacket](https://github.com/google/gopacket) and [cobra](https://github.com/spf13/cobra) to build a CLI tool for PCAP manipulation. First implemented feature being the ability to concurrently replay offline PCAP files on live network interface. While preserving timestamps between each packet. 6 | 7 | It can also calculate metadata for PCAP files and extract files from compressed tarballs (with no intermediate storage requirements). 8 | 9 | # Background 10 | 11 | Stamus Networks develops [Scirius Security Platform](https://www.stamus-networks.com/scirius-platform) and open-source [Scirius CE](https://github.com/StamusNetworks/scirius), network security platforms. We specialize in network detection and response solutions which include signature ruleset management, network threat hunting, advanced threat intelligence and data analytics. All leveraging the Suricata network IDS/IPS/NSM engine. 12 | 13 | Historically, we have used [tcpreplay](https://tcpreplay.appneta.com/) with predetermined PPS options. When setting up replay for a particular bigger-than-average PCAP set, we initially tried the typical bash rocket approach. Just read PCAP metadata using capinfos, extract average packet rate and then replay the file at that extracted average rate. Not ideal for developing algorithmic threat detection, but the result should be close enough, right? 14 | 15 | ```bash 16 | avg_pps=$(capinfos ${pcap} | grep 'Average packet rate' | awk '{print $4}' | tr -d ',') 17 | tcpreplay-edit --pps=$avg_pps --mtu-trunc -i $iface ${pcap} 18 | ``` 19 | 20 | After four days, our replay had only gone through about 10-15% of all PCAP files. Given that entire dataset only spans for three days, we were understandably puzzled. Sure, we were aware that replaying with average rate would flatten out all bursts, but that still seemed too much. But we quickly figured out what happened. 21 | 22 | That set was written using [Moloch](https://github.com/aol/moloch) full packet capture. Like Suricata, it reconstructs sessions from the ground up. All the way to the application layer. And like Suricata, it’s multi-threaded. Flow reconstruction 101 - all packets in a flow need to pass through the same worker. No information exchange happens between workers due to the extreme throughput they need to handle, and each worker can write those packets out to a separate PCAP file. But not all flows are created equal. Some workers will see more traffic volume than others, even if the flow balancer is able to distribute roughly the same number of sessions to each thread. One thread would therefore receive a large HTTP file download while another gets a lot of small DNS queries. The first PCAP file will simply rotate faster. 23 | 24 | In other words, our script relied on having sequential PCAP files. But the dataset was not sequential at all. Rather, it consisted of N sequential PCAP subsets, where N corresponds to the number of workers configured in Moloch. All in one folder and without worker ID configured as part of the PCAP naming scheme. Not knowing how many workers were used. And we needed to reconstruct it as well as we could, as the dataset was full of sweet simulated attacks, perfect for exercising the algorithmic threat detection we are developing. To put it bluntly, it sucked to be us. 25 | 26 | But... 27 | 28 | We can check when a PCAP file begins and ends by simply parsing the first and last packet. [Gopacket](https://github.com/google/gopacket) is pretty cool. It works well, we have have good experience using it. Even better, golang is actually built from ground up for concurrency, and spinning up IO readers that produce to single IO writer via thread-safe channel is a breeze. So, why not just sleep each reader for a duration calculated between global dataset and PCAP start timestamps. We can easily calculate diffs between each packet with `time.Sub()`, and sleep before pushing to writer. [Gopacket even had an example on that (albeit too basic to outright solve our problem)](https://github.com/google/gopacket/blob/master/examples/pcaplay/main.go). And finally, we could implement this feature as subcommand to bigger binary and build our own swiss army knife for all kinds of funky PCAP operations. 29 | 30 | Two working days later, we had a prototype replay tool. And after a month of bugfixes and usage in lab we decided to give it to community. 31 | 32 | You can read more in [this Stamus Networks blog post](https://www.stamus-networks.com/blog/gophercap), detailing the design more thoroughly. 33 | 34 | # Getting started 35 | 36 | ## Binary packages 37 | 38 | Version tagged binaries for GopherCap can be found under **releases** section in github. We currently provide Ubuntu 20.04 and Debian Buster CI builds. Note that very little is different between the builds. We simply separated them to ensure that libpcap version is locked in per platform. Following bash commands can be used to pull latest version download url. 39 | 40 | ### Ubuntu 41 | 42 | ``` 43 | GOPHER_URL=$(curl --silent "https://api.github.com/repos/StamusNetworks/gophercap/releases/latest" | jq -r '.assets[] | select(.name|startswith("gopherCap-ubuntu-2004-")) | .browser_download_url') 44 | wget $GOPHER_URL 45 | ``` 46 | 47 | ### Debian 48 | 49 | ``` 50 | GOPHER_URL=$(curl --silent "https://api.github.com/repos/StamusNetworks/gophercap/releases/latest" | jq -r '.assets[] | select(.name|startswith("gopherCap-debian-buster-")) | .browser_download_url') 51 | wget $GOPHER_URL 52 | ``` 53 | 54 | ## Community packages 55 | 56 | ### Arch linux 57 | 58 | Arch User Repository (AUR) package was contributed by a community member. It is not maintained by Stamus Networks. It can be installed with AUR helper like `yay`. 59 | 60 | ``` 61 | yay -Sy gophercap 62 | ``` 63 | 64 | Or by invoking `makepkg`. 65 | 66 | ``` 67 | git clone https://aur.archlinux.org/gophercap.git 68 | cd gophercap 69 | makepkg -si 70 | ``` 71 | 72 | ## Build 73 | 74 | Building GopherCap is quite easy, assuming some familiarity with Go build system. Currently it only has one Cgo dependency - libpcap. GoperCap needs libpcap to write packets into network interface. Development headers must be present for installing and regular library must be installed for execution. 75 | 76 | Ubuntu and Debian: 77 | 78 | ``` 79 | apt-get update && apt-get install -y libpcap-dev libpcap0.8 80 | ``` 81 | 82 | Arch Linux: 83 | 84 | ``` 85 | pacman -Sy libpcap 86 | ``` 87 | 88 | Then proceed as normal for building a go binary. Get project dependencies. 89 | 90 | ``` 91 | go get -u ./ 92 | ``` 93 | 94 | And build the binary. 95 | 96 | ``` 97 | go build -o ./gopherCap ./ 98 | ``` 99 | 100 | Or install it to `$GOPATH`. 101 | 102 | ``` 103 | go install 104 | which gopherCap 105 | ``` 106 | 107 | Binary can then be executed directly. 108 | 109 | ``` 110 | gopherCap --help 111 | ``` 112 | 113 | ## Basic usage 114 | 115 | Each subcommand has embedded usage examples. Refer to those for up to date and more extensive information. 116 | 117 | ``` 118 | gopherCap map --help 119 | ``` 120 | ``` 121 | gopherCap replay --help 122 | ``` 123 | ``` 124 | gopherCap tarExtract --help 125 | ``` 126 | 127 | Replay functionality requires PCAP files to be mapped first. This will collect metadata, such as first and last timestamp, total number of packets, PPS, etc. Most importantly, timestamp information is needed to calculate global dataset start and delay before reading each PCAP. 128 | 129 | ``` 130 | gopherCap map \ 131 | --dir-src /mnt/pcap \ 132 | --file-suffix "pcap" \ 133 | --dump-json /mnt/pcap/meta.json 134 | ``` 135 | 136 | Note that current implementation needs to iterate over entire PCAP file, for all files in dataset. Thus, mapping can take long. But it only needs to be done once. Afterwards, the `replay` subcommand will simply load the JSON metadata. This needs to be considered when moving or remounting PCAP storage. 137 | 138 | ``` 139 | gopherCap replay \ 140 | --out-interface veth0 \ 141 | --dump-json /mnt/pcap/meta.json 142 | ``` 143 | 144 | ### Configuring virtual NIC for testing 145 | 146 | Virtual ethernet interface pair can be created with following command. Packets replayed to one interface can be read from another. 147 | 148 | ``` 149 | sudo ip link add veth0 type veth peer name veth1 150 | ``` 151 | 152 | After creation, make sure to activate them. 153 | 154 | ``` 155 | sudo ip link set veth0 up 156 | sudo ip link set veth1 up 157 | ``` 158 | 159 | Use tcpdump to validate replay. 160 | 161 | ``` 162 | sudo tcpdump -i veth1 -n 163 | ``` 164 | 165 | Replay command might crash with following error: 166 | 167 | ``` 168 | FATA[0005] send: Message too long 169 | ``` 170 | 171 | This means packet was bigger than interface MTU. Maximum packet size can be found in metadata JSON. But 9000 is usually a safe MTU size, corresponding to common jumbo packet feature in many network switches. 172 | 173 | ``` 174 | sudo ip link set dev veth0 mtu 9000 175 | sudo ip link set dev veth1 mtu 9000 176 | ``` 177 | 178 | ## Docker 179 | 180 | Alternatively, you can also build and run gophercap as a docker container. 181 | 182 | ``` 183 | docker build -t stamus/gophercap . 184 | ``` 185 | 186 | Subcommands can then be executed through the image. 187 | 188 | ``` 189 | docker run -ti --rm stamus/gophercap --help 190 | ``` 191 | 192 | You will want to mount PCAP directory as volume. 193 | 194 | ``` 195 | docker run -ti --rm -v /mnt/pcap:/pcaps stamus/gophercap map \ 196 | --dir-src /pcaps \ 197 | --dump-json /pcaps/meta.json 198 | ``` 199 | 200 | For replay, you need to use *host network* rather than default docker bridge. Also, make sure that mapped PCAP paths correspond to in-container mount point, rather than host folder. 201 | 202 | ``` 203 | docker run -ti --rm --network host -v /mnt/pcap:/pcaps stamus/gophercap replay \ 204 | --dump-json /pcaps/meta.json \ 205 | --out-interface veth0 206 | ``` 207 | 208 | ## YAML config 209 | 210 | All CLI flags can be defined as configuration dictionary in YAML file. See [example configuration](/config/gophercap.yml) for layout. We also provide a subcommand for generating a clean template with default values. However, note that `--config` global flag needs to be used. 211 | 212 | ``` 213 | gopherCap --config 214 | ``` 215 | 216 | Configuration dictionary is organized by subcommand. With options used by multiple subcommands under `global` section. For example, location of mapping JSON file must be synced between `map` and `replay` commands, and thus both use the same config option. However, your mileage might vary with other parameters. You might want to map all PCAP files, but only replay a subset. In that case, you need two configuration files, or you need to override `global.file.regexp` via CLI flag. 217 | 218 | # Subcommands 219 | 220 | GoperCap uses *cobra* and *viper* libraries to implement a single binary with many subcommands. Similar to many other tools built in Go. Here's overview of currently supported features. 221 | 222 | ## Map 223 | 224 | PCAP metadata mapper. Collects timestamp information needed by replay command, along with other useful information. Such as largest packet size, total packet size, packet count, PPS, etc. Can take a lot of time to complete on bigger datasets, as it needs to iterate over all PCAP files. Thus reason for making this a separate subcommand, rather than wasting time before each replay sequence. PCAPs are processed concurrently on workers. So, the time needed depends on system IO throughput and CPU performance. 225 | 226 | ``` 227 | Usage: 228 | gopherCap map [flags] 229 | 230 | Flags: 231 | --dir-src string Source folder for recursive pcap search. 232 | --file-suffix string Suffix suffix used for file discovery. (default "pcap") 233 | --file-workers int Number of concurrent workers for scanning pcap files. Value less than 1 will map all pcap files concurrently. (default 4) 234 | -h, --help help for map 235 | 236 | Global Flags: 237 | --config string config file (default is $HOME/.go-replay.yaml) 238 | --dump-json string Full or relative path for storing pcap metadata in JSON format. (default "/tmp/mapped-files.json") 239 | --file-regexp string Regex pattern to filter files. 240 | ``` 241 | 242 | ## Replay 243 | 244 | Replay PCAP files to network interface while preserving time difference between packets. Requires files to be mapped beforehand, as the command relies entirely on metadata dump and no file discovery or mapping is performed. 245 | 246 | PCAP replay can be sped up or slowed down using timescaling parameters. BPF filter can be applied to written packets. 247 | 248 | ``` 249 | Usage: 250 | gopherCap replay [flags] 251 | 252 | Flags: 253 | -h, --help help for replay 254 | --loop-count int Number of iterations over pcap set. Will run infinitely if 0 or negative value is given. (default 1) 255 | --loop-infinite Loop over pcap files infinitely. Will override --loop-count 256 | --out-bpf string BPF filter to exclude some packets. 257 | --out-interface string Network interface to replay to. (default "eth0") 258 | --time-from string Start replay from this time. 259 | --time-modifier float Modifier for speeding up or slowing down the replay by a factor of X. (default 1) 260 | --time-scale-duration duration Duration for time scaling. (default 1h0m0s) 261 | --time-scale-enabled Enable time scaling. When enabled, will automatically calculate replay.time.modifier value to replay pcap in specified time window. Overrides replay.time.modifier value. Actual replay is not guaranteed to complete in defined time, As overhead from sleep calculations causes a natural drift. 262 | --time-to string End replay from this time. 263 | --wait-disable Disable initial wait before each PCAP file read. Useful when PCAPs are part of same logical set but not from same capture period. 264 | 265 | Global Flags: 266 | --config string config file (default is $HOME/.go-replay.yaml) 267 | --dump-json string Full or relative path for storing pcap metadata in JSON format. (default "/tmp/mapped-files.json") 268 | --file-regexp string Regex pattern to filter files. 269 | ``` 270 | 271 | ## Tar extract 272 | 273 | While attempting to use gopherCap in offline dev environment, we ran into a little problem. PCAPs were in 1 terabyte gzipped tarball that took 4 terabytes fully uncompressed. More than what was available on hand at the time. And only 1 terabyte subset (300GB compressed) was actually relevant for replay. 274 | 275 | This subcommand was written to extract selection of files from tarballs, optionally directly to gzipped file handles. No temporary storage or advanced filesystem level compression needed. 276 | 277 | ``` 278 | Usage: 279 | gopherCap tarExtract [flags] 280 | 281 | Flags: 282 | --dryrun Only list files in tarball for regex validation, do not extract. 283 | -h, --help help for tarExtract 284 | --in-tarball string Input gzipped tarball. 285 | --out-dir string Output directory for pcap files. 286 | --out-gzip Compress extracted files with gzip. 287 | 288 | Global Flags: 289 | --config string config file (default is $HOME/.go-replay.yaml) 290 | --dump-json string Full or relative path for storing pcap metadata in JSON format. (default "/tmp/mapped-files.json") 291 | --file-regexp string Regex pattern to filter files. 292 | ``` 293 | 294 | ## Example config 295 | 296 | GopherCap uses viper library to build a configuration dictionary. In other words, all CLI flags can be defined in YAML config file. CLI arguments would simply override the config file settings. 297 | 298 | ``` 299 | gopherCap --config ./config.yml exampleConfig 300 | ``` 301 | 302 | ## Version 303 | 304 | Prints GopherCap version tag. For integrating with CI builds and automated deploy systems, to check if local binary needs to be updated. Default value is `development`. 305 | 306 | ``` 307 | gopherCap version 308 | ``` 309 | 310 | Custom version can be embedded with following build command. 311 | 312 | ``` 313 | export VERSION= 314 | go build -ldflags="-X 'gopherCap/cmd.Version=$VERSION'" -o ./gopherCap ./ 315 | ``` 316 | 317 | # Contributing 318 | 319 | For all contributions please use a Pull Request on Github or open an issue. 320 | -------------------------------------------------------------------------------- /cmd/eve2filter.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2022 Stamus Networks oss@stamus-networks.com 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package cmd 18 | 19 | import ( 20 | "os" 21 | 22 | "github.com/StamusNetworks/gophercap/pkg/filter" 23 | 24 | "github.com/sirupsen/logrus" 25 | "github.com/spf13/cobra" 26 | "github.com/spf13/viper" 27 | "gopkg.in/yaml.v2" 28 | ) 29 | 30 | // eve2filterCmd represents the eve2filter command 31 | var eve2filterCmd = &cobra.Command{ 32 | Use: "eve2filter", 33 | Short: "Generate filter YAMLs from EVE events", 34 | Run: func(cmd *cobra.Command, args []string) { 35 | evePath := viper.GetString("eve2filter.path.eve") 36 | if evePath == "" { 37 | logrus.Fatal("EVE path missing") 38 | } 39 | filters, err := filter.Generate(evePath, func(err error) bool { 40 | logrus.Error(err) 41 | return true 42 | }) 43 | if err != nil { 44 | logrus.Fatal(err) 45 | } 46 | logrus.WithField("count", len(filters)).Info("Filters extracted") 47 | bin, err := yaml.Marshal(filters) 48 | if err != nil { 49 | logrus.Fatal(err) 50 | } 51 | logrus.WithField("path", viper.GetString("eve2filter.path.filter")).Info("Writing filters") 52 | f, err := os.Create(viper.GetString("eve2filter.path.filter")) 53 | if err != nil { 54 | logrus.Fatal(err) 55 | } 56 | defer f.Close() 57 | f.Write(bin) 58 | }, 59 | } 60 | 61 | func init() { 62 | rootCmd.AddCommand(eve2filterCmd) 63 | 64 | eve2filterCmd.PersistentFlags().String("path-eve", "", "Path to EVE JSON.") 65 | viper.BindPFlag("eve2filter.path.eve", eve2filterCmd.PersistentFlags().Lookup("path-eve")) 66 | 67 | eve2filterCmd.PersistentFlags().String( 68 | "path-filter", 69 | "./filter-generated.yaml", 70 | "Path to resulting filter YAML", 71 | ) 72 | viper.BindPFlag("eve2filter.path.filter", eve2filterCmd.PersistentFlags().Lookup("path-filter")) 73 | } 74 | -------------------------------------------------------------------------------- /cmd/exampleConfig.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "github.com/sirupsen/logrus" 5 | "github.com/spf13/cobra" 6 | "github.com/spf13/viper" 7 | ) 8 | 9 | // exampleConfigCmd represents the exampleConfig command 10 | var exampleConfigCmd = &cobra.Command{ 11 | Use: "exampleConfig", 12 | Short: "Generate example configuration file", 13 | Long: `Example usage: 14 | gopherCap --config example.yml exampleConfig`, 15 | Run: func(cmd *cobra.Command, args []string) { 16 | logrus.Infof("Writing config to %s", cfgFile) 17 | viper.WriteConfigAs(cfgFile) 18 | }, 19 | } 20 | 21 | func init() { 22 | rootCmd.AddCommand(exampleConfigCmd) 23 | } 24 | -------------------------------------------------------------------------------- /cmd/extract.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2021 Stamus Networks oss@stamus-networks.com 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package cmd 18 | 19 | import ( 20 | "github.com/StamusNetworks/gophercap/pkg/extract" 21 | 22 | "github.com/sirupsen/logrus" 23 | "github.com/spf13/cobra" 24 | "github.com/spf13/viper" 25 | ) 26 | 27 | // extractCmd represents the extract command 28 | var extractCmd = &cobra.Command{ 29 | Use: "extract", 30 | Short: "Extract data for a single flow from Suricata pcap directory.", 31 | Long: `Generate a pcap for a single flow specified in a Suricata event. 32 | 33 | Example usage: 34 | gopherCap extract \ 35 | --dir-pcap /var/log/suricata \ 36 | --event /tmp/event.json \ 37 | --dump-pcap /tmp/event.pcap \ 38 | --file-format log-%n-%t.pcap \ 39 | --skip-bpf 40 | `, 41 | Run: func(cmd *cobra.Command, args []string) { 42 | extractConfig := &extract.ExtractPcapConfig{ 43 | OutputName: viper.GetString("extract.dump.pcap"), 44 | EventPath: viper.GetString("extract.event"), 45 | SkipBpf: viper.GetBool("extract.skip.bpf"), 46 | FileFormat: viper.GetString("extract.file.format"), 47 | } 48 | if err := extract.ExtractPcapFile(*extractConfig); err != nil { 49 | logrus.Fatal(err) 50 | } 51 | }, 52 | } 53 | 54 | func init() { 55 | rootCmd.AddCommand(extractCmd) 56 | 57 | extractCmd.PersistentFlags().String("event", "", 58 | `Event to get flow info from.`) 59 | viper.BindPFlag("extract.event", extractCmd.PersistentFlags().Lookup("event")) 60 | extractCmd.PersistentFlags().String("dump-pcap", "", 61 | `Pcap file to extract data to.`) 62 | viper.BindPFlag("extract.dump.pcap", extractCmd.PersistentFlags().Lookup("dump-pcap")) 63 | extractCmd.PersistentFlags().Bool("skip-bpf", false, 64 | `Explicitely extract data with gopacket parsing. Slower but more accurate.`) 65 | viper.BindPFlag("extract.skip.bpf", extractCmd.PersistentFlags().Lookup("skip-bpf")) 66 | extractCmd.PersistentFlags().String("file-format", "pcap.%n.%t", 67 | `How pcap files are named by Suricata.`) 68 | viper.BindPFlag("extract.file.format", extractCmd.PersistentFlags().Lookup("file-format")) 69 | } 70 | -------------------------------------------------------------------------------- /cmd/filter.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2020 Stamus Networks oss@stamus-networks.com 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package cmd 18 | 19 | import ( 20 | "context" 21 | "errors" 22 | "os" 23 | "os/signal" 24 | "path/filepath" 25 | "time" 26 | 27 | "github.com/StamusNetworks/gophercap/pkg/dedup" 28 | "github.com/StamusNetworks/gophercap/pkg/filter" 29 | "github.com/StamusNetworks/gophercap/pkg/replay" 30 | "golang.org/x/sync/errgroup" 31 | 32 | "github.com/sirupsen/logrus" 33 | "github.com/spf13/cobra" 34 | "github.com/spf13/viper" 35 | "gopkg.in/yaml.v2" 36 | ) 37 | 38 | // filterCmd represents the filter command 39 | var filterCmd = &cobra.Command{ 40 | Use: "filter", 41 | Short: "Filter is for concurrent packet extraction with many PCAPs and many BPF filters", 42 | Long: ``, 43 | Run: func(cmd *cobra.Command, args []string) { 44 | workers := viper.GetInt("filter.workers") 45 | 46 | if workers < 1 { 47 | logrus.Fatalf("Invalid worker count: %d", workers) 48 | } 49 | 50 | input := viper.GetString("filter.input") 51 | if input == "" { 52 | logrus.Fatal(errors.New("Missing input folder")) 53 | } 54 | 55 | output := viper.GetString("filter.output") 56 | if output == "" { 57 | logrus.Fatal(errors.New("Missing output folder")) 58 | } 59 | 60 | filters := make(map[string]filter.Matcher) 61 | 62 | if configPath := viper.GetString("filter.yaml"); configPath != "" { 63 | var cfg filter.YAMLConfig 64 | data, err := os.ReadFile(viper.GetString("filter.yaml")) 65 | if err != nil { 66 | logrus.Fatalf("Filter input read: %s", err) 67 | } 68 | if err := yaml.Unmarshal(data, &cfg); err != nil { 69 | logrus.Fatal(err) 70 | } 71 | for name, config := range cfg { 72 | m, err := filter.NewCombinedMatcher(filter.MatcherConfig{ 73 | CombinedConfig: config, 74 | MaxMindASN: viper.GetString("filter.maxmind.asn"), 75 | }) 76 | if err != nil { 77 | logrus.Fatal(err) 78 | } 79 | filters[name] = m 80 | logrus.Infof("filter %s got %d conditions", name, len(m.Conditions)) 81 | } 82 | } else { 83 | logrus.Warn("Filter config missing, running with empty set") 84 | filters["raw"] = filter.DummyMatcher{} 85 | } 86 | 87 | tasks := make(chan filter.Task, workers) 88 | 89 | ctx, cancel := context.WithCancel(context.Background()) 90 | pool, ctx := errgroup.WithContext(ctx) 91 | for i := 0; i < workers; i++ { 92 | id := i 93 | pool.Go(func() error { 94 | logrus.Infof("Worker %d started", id) 95 | defer logrus.Infof("Worker %d done", id) 96 | loop: 97 | for { 98 | select { 99 | case <-ctx.Done(): 100 | logrus.WithField("worker", id).Warn("early exit called") 101 | break loop 102 | case task, ok := <-tasks: 103 | if !ok { 104 | break loop 105 | } 106 | logrus.WithFields(logrus.Fields{ 107 | "input": task.Input, 108 | "output": filepath.Dir(task.Output), 109 | "desc": task.Description, 110 | }).Info("Filtering file") 111 | result, err := filter.ReadAndFilter(&filter.Config{ 112 | File: struct { 113 | Input string 114 | Output string 115 | }{ 116 | Input: task.Input, 117 | Output: task.Output, 118 | }, 119 | Filter: task.Filter, 120 | Decapsulate: viper.GetBool("filter.decap.enabled"), 121 | DecapMaxDepth: viper.GetInt("filter.decap.depth"), 122 | Compress: viper.GetBool("filter.compress"), 123 | StatFunc: func(fr map[string]any) { 124 | logrus.WithField("worker", id).WithFields(fr).Debug("filter report") 125 | }, 126 | Ctx: ctx, 127 | Dedup: func() dedup.Dedupper { 128 | if viper.GetBool("filter.dedup") { 129 | return dedup.NewCircularDedup(3, 2*time.Second) 130 | } 131 | return nil 132 | }(), 133 | }) 134 | if err != nil { 135 | switch err.(type) { 136 | case filter.ErrEarlyExit: 137 | logrus.WithField("worker", id).Warn("early exit called") 138 | break loop 139 | default: 140 | logrus.Error(err) 141 | } 142 | } 143 | logrus.Infof("DONE: %+v", result) 144 | } 145 | } 146 | return nil 147 | }) 148 | } 149 | 150 | chSIG := make(chan os.Signal, 1) 151 | signal.Notify(chSIG, os.Interrupt) 152 | 153 | go func(ctx context.Context) { 154 | <-chSIG 155 | cancel() 156 | }(context.TODO()) 157 | 158 | files, err := replay.FindPcapFiles(input, viper.GetString("filter.suffix")) 159 | if err != nil { 160 | logrus.Fatalf("PCAP list gen: %s", err) 161 | } 162 | 163 | outer: 164 | for _, inFile := range files { 165 | inner: 166 | for name, matcher := range filters { 167 | outDir := filepath.Join(output, name) 168 | stat, err := os.Stat(outDir) 169 | if os.IsNotExist(err) { 170 | if err := os.Mkdir(outDir, 0750); err != nil { 171 | logrus.Fatal(err) 172 | } 173 | } else if !stat.IsDir() { 174 | logrus.Fatalf("Output path %s exists and is not a directory", output) 175 | } 176 | 177 | outFile := filter.ExtractBaseName(inFile) + ".pcap" 178 | outFile = filepath.Join(outDir, outFile) 179 | 180 | logrus.WithFields(logrus.Fields{ 181 | "filter": name, 182 | "path": outFile, 183 | }).Info("feeding file to matcher") 184 | 185 | select { 186 | case tasks <- filter.Task{ 187 | Input: inFile, 188 | Output: outFile, 189 | Filter: matcher, 190 | Description: name, 191 | }: 192 | case <-ctx.Done(): 193 | break outer 194 | break inner 195 | } 196 | } 197 | } 198 | close(tasks) 199 | if err := pool.Wait(); err != nil { 200 | logrus.Fatal(err) 201 | } 202 | }, 203 | } 204 | 205 | func init() { 206 | rootCmd.AddCommand(filterCmd) 207 | 208 | filterCmd.PersistentFlags().String("yaml", "", 209 | `Source file for BPF filters. `+ 210 | `Format is YAML. Key is name of the filter which also translates to output folder. `+ 211 | `Value is a list of networks. Packets matching those networks will be written to output file.`) 212 | viper.BindPFlag("filter.yaml", filterCmd.PersistentFlags().Lookup("yaml")) 213 | 214 | filterCmd.PersistentFlags().Int("workers", 4, `Number of PCAP files to be parsed at once.`) 215 | viper.BindPFlag("filter.workers", filterCmd.PersistentFlags().Lookup("workers")) 216 | 217 | filterCmd.PersistentFlags().String("input", "", `Input folder for filtered PCAP files.`) 218 | viper.BindPFlag("filter.input", filterCmd.PersistentFlags().Lookup("input")) 219 | 220 | filterCmd.PersistentFlags().String("output", "", `Output folder for filtered PCAP files.`) 221 | viper.BindPFlag("filter.output", filterCmd.PersistentFlags().Lookup("output")) 222 | 223 | filterCmd.PersistentFlags().Bool("decap", false, `Decapsulate GRE and ERSPAN headers.`) 224 | viper.BindPFlag("filter.decap.enabled", filterCmd.PersistentFlags().Lookup("decap")) 225 | 226 | filterCmd.PersistentFlags().Int("decap-depth", -1, `Max posterior packet layers to check for decap.`) 227 | viper.BindPFlag("filter.decap.depth", filterCmd.PersistentFlags().Lookup("decap-depth")) 228 | 229 | filterCmd.PersistentFlags().Bool("compress", false, `Write output packets directly to gzip stream.`) 230 | viper.BindPFlag("filter.compress", filterCmd.PersistentFlags().Lookup("compress")) 231 | 232 | filterCmd.PersistentFlags().Bool("dedup", false, `Apply best-effort software dedup.`) 233 | viper.BindPFlag("filter.dedup", filterCmd.PersistentFlags().Lookup("dedup")) 234 | 235 | filterCmd.PersistentFlags().String("maxmind-asn", "", `Path to maxmind ASN database. Only needed if ASN filter is used.`) 236 | viper.BindPFlag("filter.maxmind.asn", filterCmd.PersistentFlags().Lookup("maxmind-asn")) 237 | 238 | filterCmd.PersistentFlags().String("suffix", "pcap", "Find files with following suffix.") 239 | viper.BindPFlag("filter.suffix", filterCmd.PersistentFlags().Lookup("suffix")) 240 | } 241 | -------------------------------------------------------------------------------- /cmd/map.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2020 Stamus Networks oss@stamus-networks.com 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package cmd 18 | 19 | import ( 20 | "github.com/StamusNetworks/gophercap/pkg/replay" 21 | 22 | "github.com/sirupsen/logrus" 23 | "github.com/spf13/cobra" 24 | "github.com/spf13/viper" 25 | ) 26 | 27 | // mapCmd represents the map command 28 | var mapCmd = &cobra.Command{ 29 | Use: "map", 30 | Short: "Parse PCAP files for metadata mapping.", 31 | Long: `Recursively discovers all PCAP files in directory matching user-defined name pattern. First and last timestamp of each pcap file is parsed and stored in JSON dump. Also calculates additional metadata, such as data size in bytes, packets, PPS, etc. All files are processed in parallel, as we iterate over entire pcap file. Output dump is then loaded into replay step to save time. 32 | 33 | Example usage: 34 | gopherCap map \ 35 | --dir-src /mnt/pcap \ 36 | --file-suffix "pcap" \ 37 | --dump-json /mnt/pcap/meta.json 38 | `, 39 | Run: func(cmd *cobra.Command, args []string) { 40 | set, err := replay.NewPcapSet(replay.MapConfig{ 41 | Directory: viper.GetString("map.dir.src"), 42 | Suffix: viper.GetString("map.file.suffix"), 43 | Workers: viper.GetInt("map.file.workers"), 44 | Pattern: viper.GetString("global.file.regexp"), 45 | }) 46 | if err != nil { 47 | logrus.Fatal(err) 48 | } 49 | 50 | if err := replay.DumpSetJSON(viper.GetString("global.dump.json"), *set); err != nil { 51 | logrus.Fatal(err) 52 | } 53 | }, 54 | } 55 | 56 | func init() { 57 | rootCmd.AddCommand(mapCmd) 58 | 59 | mapCmd.PersistentFlags().String("dir-src", "", 60 | `Source folder for recursive pcap search.`) 61 | viper.BindPFlag("map.dir.src", mapCmd.PersistentFlags().Lookup("dir-src")) 62 | 63 | mapCmd.PersistentFlags().String("file-suffix", "pcap", 64 | `Suffix suffix used for file discovery.`) 65 | viper.BindPFlag("map.file.suffix", mapCmd.PersistentFlags().Lookup("file-suffix")) 66 | 67 | mapCmd.PersistentFlags().Int("file-workers", 4, 68 | `Number of concurrent workers for scanning pcap files. `+ 69 | `Value less than 1 will map all pcap files concurrently.`) 70 | viper.BindPFlag("map.file.workers", mapCmd.PersistentFlags().Lookup("file-workers")) 71 | } 72 | -------------------------------------------------------------------------------- /cmd/replay.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2020 Stamus Networks oss@stamus-networks.com 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package cmd 18 | 19 | import ( 20 | "context" 21 | "regexp" 22 | "time" 23 | 24 | "github.com/StamusNetworks/gophercap/pkg/replay" 25 | 26 | "github.com/sirupsen/logrus" 27 | "github.com/spf13/cobra" 28 | "github.com/spf13/viper" 29 | ) 30 | 31 | const argTsFormat = "2006-01-02 15:04:05" 32 | 33 | // replayCmd represents the replay command 34 | var replayCmd = &cobra.Command{ 35 | Use: "replay", 36 | Short: "Replay pcap files while preserving temporal properties.", 37 | Long: `Load metadata for PCAP dataset and replay them into a network interface 38 | while perserving time diffs between each packet. All readers are started in parallel, 39 | but each will sleep for a calculated duration between pcap start and global dataset 40 | start. Thus handling datasets where tool like Moloch wrote multiple pcap files in parallel, but not info exists any more on which thread corresponds to which pcap. 41 | 42 | Example usage: 43 | gopherCap replay \ 44 | --out-interface veth0 \ 45 | --dump-json /mnt/pcap/meta.json 46 | 47 | Usage with pcap timestamp and written packet filtering: 48 | gopherCap replay \ 49 | --out-interface veth0 \ 50 | --dump-json "db/mapped-files.json" 51 | --file-regexp '200928+-\d+' \ 52 | --time-from "2020-09-28 06:00:00" \ 53 | --time-to "2020-09-28 16:00:00" \ 54 | --out-bpf "not net 10.0.0.0/32" 55 | 56 | Usage timescaling to replay 1 day pcap set (approximately) in 4 hours: 57 | gopherCap replay \ 58 | --out-interface veth0 \ 59 | --dump-json "db/mapped-files.json" 60 | --file-regexp '200928+-\d+' \ 61 | --time-scale-enabled \ 62 | --time-scale-duration 4h 63 | 64 | Set up virtual ethernet interface for testing or local capture: 65 | sudo ip link add veth0 type veth peer name veth1 66 | 67 | sudo ip link set dev veth0 mtu 9000 68 | sudo ip link set dev veth1 mtu 9000 69 | 70 | sudo ip link set veth0 up 71 | sudo ip link set veth1 up 72 | 73 | Increase interface MTU if you get this error: 74 | FATA[0005] send: Message too long 75 | `, 76 | Run: func(cmd *cobra.Command, args []string) { 77 | set, err := replay.LoadSetJSON(viper.GetString("global.dump.json")) 78 | if err != nil { 79 | logrus.Fatal(err) 80 | } 81 | iterations := viper.GetInt("replay.loop.count") 82 | if iterations < 1 || viper.GetBool("replay.loop.infinite") { 83 | logrus.Infof("Negative iteration count or --loop-infinite called. Enabling infinite loop.") 84 | } 85 | var count int 86 | loop: 87 | for { 88 | count++ 89 | if !viper.GetBool("replay.loop.infinite") && count > iterations { 90 | if iterations > 1 { 91 | logrus.Infof("Max iteration count %d reached. Stopping loop.", iterations) 92 | } 93 | break loop 94 | } 95 | logrus.Infof("Starting iteration %d", count) 96 | handle, err := replay.NewHandle(replay.Config{ 97 | Set: *set, 98 | Ctx: context.Background(), 99 | WriteInterface: viper.GetString("replay.out.interface"), 100 | ScaleDuration: viper.GetDuration("replay.time.scale.duration"), 101 | ScaleEnabled: viper.GetBool("replay.time.scale.enabled"), 102 | ScalePerFile: viper.GetBool("replay.disable_wait"), 103 | OutBpf: viper.GetString("replay.out.bpf"), 104 | DisableWait: viper.GetBool("replay.disable_wait"), 105 | SkipOutOfOrder: viper.GetBool("replay.skip.out_of_order"), 106 | SkipMTU: viper.GetInt("replay.skip.mtu"), 107 | Reorder: viper.GetBool("replay.reorder.enabled"), 108 | FilterRegex: func() *regexp.Regexp { 109 | if pattern := viper.GetString("global.file.regexp"); pattern != "" { 110 | re, err := regexp.Compile(pattern) 111 | if err != nil { 112 | logrus.Fatal(err) 113 | } 114 | return re 115 | } 116 | return nil 117 | }(), 118 | TimeFrom: func() time.Time { 119 | if from := viper.GetString("replay.time.from"); from != "" { 120 | ts, err := time.Parse(argTsFormat, from) 121 | if err != nil { 122 | logrus.Fatalf("Invalid timestamp %s, please follow this format: %s", from, argTsFormat) 123 | } 124 | return ts.UTC() 125 | } 126 | return time.Time{} 127 | }(), 128 | TimeTo: func() time.Time { 129 | if from := viper.GetString("replay.time.to"); from != "" { 130 | ts, err := time.Parse(argTsFormat, from) 131 | if err != nil { 132 | logrus.Fatalf("Invalid timestamp %s, please follow this format: %s", from, argTsFormat) 133 | } 134 | return ts.UTC() 135 | } 136 | return time.Time{} 137 | }(), 138 | }) 139 | if err != nil { 140 | logrus.Fatal(err) 141 | } 142 | logrus.WithFields(logrus.Fields{ 143 | "beginning": handle.FileSet.Beginning, 144 | "end": handle.FileSet.End, 145 | }).Info("PCAP set loaded") 146 | start := time.Now() 147 | if err := handle.Play(); err != nil { 148 | logrus.Fatal(err) 149 | } 150 | logrus.Infof("Iteration %d done in %s.", count, time.Since(start)) 151 | } 152 | }, 153 | } 154 | 155 | func init() { 156 | rootCmd.AddCommand(replayCmd) 157 | 158 | replayCmd.PersistentFlags().String("out-interface", "eth0", 159 | `Network interface to replay to.`) 160 | viper.BindPFlag("replay.out.interface", replayCmd.PersistentFlags().Lookup("out-interface")) 161 | 162 | replayCmd.PersistentFlags().String("out-bpf", "", 163 | `BPF filter to exclude some packets.`) 164 | viper.BindPFlag("replay.out.bpf", replayCmd.PersistentFlags().Lookup("out-bpf")) 165 | 166 | replayCmd.PersistentFlags().Bool("loop-infinite", false, 167 | `Loop over pcap files infinitely. Will override --loop-count`) 168 | viper.BindPFlag("replay.loop.infinite", replayCmd.PersistentFlags().Lookup("loop-infinite")) 169 | 170 | replayCmd.PersistentFlags().Int("loop-count", 1, 171 | `Number of iterations over pcap set. Will run infinitely if 0 or negative value is given.`) 172 | viper.BindPFlag("replay.loop.count", replayCmd.PersistentFlags().Lookup("loop-count")) 173 | 174 | replayCmd.Flags().String( 175 | "time-from", "", `Start replay from this time.`) 176 | viper.BindPFlag("replay.time.from", replayCmd.Flags().Lookup("time-from")) 177 | 178 | replayCmd.Flags().String( 179 | "time-to", "", `End replay from this time.`) 180 | viper.BindPFlag("replay.time.to", replayCmd.Flags().Lookup("time-to")) 181 | 182 | replayCmd.PersistentFlags().Bool("time-scale-enabled", false, 183 | `Enable time scaling. `+ 184 | `Actual replay is not guaranteed to complete in defined time, `+ 185 | `As overhead from sleep calculations causes a natural drift.`) 186 | viper.BindPFlag("replay.time.scale.enabled", replayCmd.PersistentFlags().Lookup("time-scale-enabled")) 187 | 188 | replayCmd.PersistentFlags().Duration("time-scale-duration", 1*time.Hour, 189 | `Duration for time scaling.`) 190 | viper.BindPFlag("replay.time.scale.duration", replayCmd.PersistentFlags().Lookup("time-scale-duration")) 191 | 192 | replayCmd.PersistentFlags().Bool("wait-disable", false, 193 | `Disable initial wait before each PCAP file read. `+ 194 | `Useful when PCAPs are part of same logical set but not from same capture period.`) 195 | viper.BindPFlag("replay.disable_wait", replayCmd.PersistentFlags().Lookup("wait-disable")) 196 | 197 | replayCmd.PersistentFlags().Bool("skip-ooo", false, "Skip out of order packets. If disabled, out of order packets will be written with no delay.") 198 | viper.BindPFlag("replay.skip.out_of_order", replayCmd.PersistentFlags().Lookup("skip-ooo")) 199 | 200 | replayCmd.PersistentFlags().Int("skip-mtu", 1514, "Packets with total size in bytes bigger than this value will be dropped.") 201 | viper.BindPFlag("replay.skip.mtu", replayCmd.PersistentFlags().Lookup("skip-mtu")) 202 | 203 | replayCmd.PersistentFlags().Bool("reorder", false, "Enable packet reordering by timestamp. Adds overhead but is useful with out of order packets.") 204 | viper.BindPFlag("replay.reorder.enabled", replayCmd.PersistentFlags().Lookup("reorder")) 205 | } 206 | -------------------------------------------------------------------------------- /cmd/root.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2020 Stamus Networks oss@stamus-networks.com 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package cmd 18 | 19 | import ( 20 | "fmt" 21 | "os" 22 | 23 | "github.com/sirupsen/logrus" 24 | "github.com/spf13/cobra" 25 | 26 | homedir "github.com/mitchellh/go-homedir" 27 | "github.com/spf13/viper" 28 | ) 29 | 30 | var cfgFile string 31 | 32 | // rootCmd represents the base command when called without any subcommands 33 | var rootCmd = &cobra.Command{ 34 | Use: "gopherCap", 35 | Short: "Accurate, modular, scalable pcap manipulation tool written in Go.", 36 | Long: `Usage examples: 37 | 38 | Map metadata for all gzipped PCAP files in a folder: 39 | gopherCap map \ 40 | --dir-src /mnt/data/pcaps/<...> \ 41 | --file-suffix pcap.gz \ 42 | --dump-json dump.json 43 | 44 | Replay a subset of PCAP files from prevously mapped JSON dump to virtual interface: 45 | sudo gopherCap replay \ 46 | --dump-json dump.json \ 47 | --out-interface veth1 \ 48 | --file-regexp "190124-0000002\d+" 49 | 50 | Extract pcaps from tar.gz that match a pattern. Write them to a directory in gzip format. 51 | gopherCap tarExtract \ 52 | --in-tarball /mnt/ext/pcap/big.tar.gz \ 53 | --file-regexp 'owl-20012\d+-\d+\.pcap' \ 54 | --out-dir /mnt/pcap --out-gzip 55 | 56 | Each subcommand has separate --help. Please refer to that for more specific usage. 57 | `, 58 | } 59 | 60 | // Execute adds all child commands to the root command and sets flags appropriately. 61 | // This is called by main.main(). It only needs to happen once to the rootCmd. 62 | func Execute() { 63 | if err := rootCmd.Execute(); err != nil { 64 | fmt.Println(err) 65 | os.Exit(1) 66 | } 67 | } 68 | 69 | func init() { 70 | cobra.OnInitialize(initConfig) 71 | 72 | // Here you will define your flags and configuration settings. 73 | // Cobra supports persistent flags, which, if defined here, 74 | // will be global for your application. 75 | 76 | rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.go-replay.yaml)") 77 | 78 | rootCmd.PersistentFlags().String("dump-json", "/tmp/mapped-files.json", 79 | `Full or relative path for storing pcap metadata in JSON format.`) 80 | viper.BindPFlag("global.dump.json", rootCmd.PersistentFlags().Lookup("dump-json")) 81 | 82 | rootCmd.PersistentFlags().String("file-regexp", "", 83 | `Regex pattern to filter files.`) 84 | viper.BindPFlag("global.file.regexp", rootCmd.PersistentFlags().Lookup("file-regexp")) 85 | } 86 | 87 | // initConfig reads in config file and ENV variables if set. 88 | func initConfig() { 89 | if cfgFile != "" { 90 | // Use config file from the flag. 91 | viper.SetConfigFile(cfgFile) 92 | } else { 93 | // Find home directory. 94 | home, err := homedir.Dir() 95 | if err != nil { 96 | fmt.Println(err) 97 | os.Exit(1) 98 | } 99 | 100 | // Search config in home directory with name ".go-replay" (without extension). 101 | viper.AddConfigPath(home) 102 | viper.SetConfigName(".go-replay") 103 | } 104 | 105 | viper.AutomaticEnv() // read in environment variables that match 106 | 107 | // If a config file is found, read it in. 108 | if err := viper.ReadInConfig(); err == nil { 109 | fmt.Println("Using config file:", viper.ConfigFileUsed()) 110 | } 111 | logrus.SetLevel(logrus.DebugLevel) 112 | } 113 | -------------------------------------------------------------------------------- /cmd/tarExtract.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2020 Stamus Networks oss@stamus-networks.com 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package cmd 18 | 19 | import ( 20 | "archive/tar" 21 | "compress/gzip" 22 | "fmt" 23 | "io" 24 | "os" 25 | "path/filepath" 26 | "regexp" 27 | "strings" 28 | 29 | "github.com/StamusNetworks/gophercap/pkg/replay" 30 | 31 | "github.com/sirupsen/logrus" 32 | "github.com/spf13/cobra" 33 | "github.com/spf13/viper" 34 | ) 35 | 36 | // tarExtractCmd represents the tarExtract command 37 | var tarExtractCmd = &cobra.Command{ 38 | Use: "tarExtract", 39 | Short: "Extract selected pcap files from tar.gz", 40 | Long: `Got a huge tar.gz file with pcaps with no space to unpack it? Fear not, just iterate over the bytestream and unpack only the files you need. Directly to gzip if needed. 41 | 42 | Example usage: 43 | gopherCap tarExtract \ 44 | --in-tarball /mnt/ext/tarball.tar.gz \ 45 | --file-regexp "pcap-2020.+\.pcap" \ 46 | --out-dir /mnt/nfs/ \ 47 | --out-gzip 48 | 49 | List but don't extract anything: 50 | gopherCap tarExtract \ 51 | --in-tarball /mnt/ext/tarball.tar.gz \ 52 | --file-regexp "pcap-2020.+\.pcap" \ 53 | --dryrun 54 | `, 55 | Run: func(cmd *cobra.Command, args []string) { 56 | fileReader, err := replay.Open(viper.GetString("tarball.in.file")) 57 | if err != nil { 58 | logrus.Fatalf("Tarball read: %s", err) 59 | } 60 | defer fileReader.Close() 61 | reader := tar.NewReader(fileReader) 62 | pattern := func() *regexp.Regexp { 63 | if pattern := viper.GetString("global.file.regexp"); pattern != "" { 64 | re, err := regexp.Compile(pattern) 65 | if err != nil { 66 | logrus.Fatal(err) 67 | } 68 | return re 69 | } 70 | return nil 71 | }() 72 | outDir := viper.GetString("tarball.out.dir") 73 | if outDir == "" && !viper.GetBool("tarball.dryrun") { 74 | logrus.Fatal("Missing output dir.") 75 | } 76 | logrus.Infof("Starting reater for %s.", viper.GetString("tarball.in.tarball")) 77 | loop: 78 | for { 79 | header, err := reader.Next() 80 | if err == io.EOF { 81 | logrus.Debug("EOF, stopping reader.") 82 | break loop 83 | } 84 | if err != nil { 85 | logrus.Fatalf("Tarball read error: %s", err) 86 | } 87 | logrus.Debugf("Found %s", header.Name) 88 | info := header.FileInfo() 89 | if info.IsDir() { 90 | logrus.Debugf("%s is a folder, skipping", info.Name()) 91 | continue loop 92 | } 93 | if pattern == nil || (pattern != nil && pattern.MatchString(header.Name)) { 94 | logrus.Infof("%s matches file pattern", header.Name) 95 | outfile := filepath.Join( 96 | outDir, strings.ReplaceAll(strings.TrimPrefix(info.Name(), "./"), "/", "-"), 97 | ) 98 | if viper.GetBool("tarball.out.gzip") { 99 | outfile = fmt.Sprintf("%s.gz", outfile) 100 | } 101 | file, err := os.OpenFile(outfile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, info.Mode()) 102 | if err != nil { 103 | logrus.Fatal(err) 104 | } 105 | var writer io.WriteCloser = file 106 | if viper.GetBool("tarball.out.gzip") { 107 | writer = gzip.NewWriter(file) 108 | } 109 | _, err = io.Copy(writer, reader) 110 | if err != nil { 111 | logrus.Error(err) 112 | } 113 | writer.Close() 114 | } 115 | } 116 | }, 117 | } 118 | 119 | func init() { 120 | rootCmd.AddCommand(tarExtractCmd) 121 | 122 | tarExtractCmd.PersistentFlags().String("in-tarball", "", 123 | `Input gzipped tarball.`) 124 | viper.BindPFlag("tarball.in.file", tarExtractCmd.PersistentFlags().Lookup("in-tarball")) 125 | 126 | tarExtractCmd.PersistentFlags().String("out-dir", "", 127 | `Output directory for pcap files.`) 128 | viper.BindPFlag("tarball.out.dir", tarExtractCmd.PersistentFlags().Lookup("out-dir")) 129 | 130 | tarExtractCmd.PersistentFlags().Bool("dryrun", false, 131 | `Only list files in tarball for regex validation, do not extract.`) 132 | viper.BindPFlag("tarball.dryrun", tarExtractCmd.PersistentFlags().Lookup("dryrun")) 133 | 134 | tarExtractCmd.PersistentFlags().Bool("out-gzip", false, 135 | `Compress extracted files with gzip.`) 136 | viper.BindPFlag("tarball.out.gzip", tarExtractCmd.PersistentFlags().Lookup("out-gzip")) 137 | } 138 | -------------------------------------------------------------------------------- /cmd/version.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2020 Stamus Networks oss@stamus-networks.com 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package cmd 18 | 19 | import ( 20 | "fmt" 21 | 22 | "github.com/spf13/cobra" 23 | ) 24 | 25 | var Version = "development" 26 | 27 | // versionCmd represents the version command 28 | var versionCmd = &cobra.Command{ 29 | Use: "version", 30 | Short: "Shows gopherCap version.", 31 | Run: func(cmd *cobra.Command, args []string) { 32 | fmt.Println("gopherCap", Version) 33 | }, 34 | } 35 | 36 | func init() { 37 | rootCmd.AddCommand(versionCmd) 38 | } 39 | -------------------------------------------------------------------------------- /configs/gophercap.yml: -------------------------------------------------------------------------------- 1 | global: 2 | dump: 3 | json: /tmp/mapped-files.json 4 | file: 5 | regexp: "" 6 | map: 7 | dir: 8 | src: "" 9 | file: 10 | suffix: pcap 11 | workers: 4 12 | replay: 13 | disable_wait: false 14 | loop: 15 | count: 1 16 | infinite: false 17 | out: 18 | bpf: "" 19 | interface: eth0 20 | time: 21 | from: "" 22 | modifier: "1" 23 | scale: 24 | duration: 1h0m0s 25 | enabled: false 26 | to: "" 27 | tarball: 28 | dryrun: false 29 | in: 30 | file: "" 31 | out: 32 | dir: "" 33 | gzip: false 34 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/StamusNetworks/gophercap 2 | 3 | go 1.19 4 | 5 | require ( 6 | github.com/google/gopacket v1.1.19 7 | github.com/mitchellh/go-homedir v1.1.0 8 | github.com/oschwald/geoip2-golang v1.9.0 9 | github.com/sirupsen/logrus v1.9.3 10 | github.com/spf13/cobra v1.8.0 11 | github.com/spf13/viper v1.18.2 12 | golang.org/x/sync v0.6.0 13 | gopkg.in/yaml.v2 v2.4.0 14 | ) 15 | 16 | require ( 17 | github.com/fsnotify/fsnotify v1.7.0 // indirect 18 | github.com/hashicorp/hcl v1.0.0 // indirect 19 | github.com/inconshreveable/mousetrap v1.1.0 // indirect 20 | github.com/magiconair/properties v1.8.7 // indirect 21 | github.com/mitchellh/mapstructure v1.5.0 // indirect 22 | github.com/oschwald/maxminddb-golang v1.12.0 // indirect 23 | github.com/pelletier/go-toml/v2 v2.1.1 // indirect 24 | github.com/sagikazarmark/locafero v0.4.0 // indirect 25 | github.com/sagikazarmark/slog-shim v0.1.0 // indirect 26 | github.com/sourcegraph/conc v0.3.0 // indirect 27 | github.com/spf13/afero v1.11.0 // indirect 28 | github.com/spf13/cast v1.6.0 // indirect 29 | github.com/spf13/pflag v1.0.5 // indirect 30 | github.com/subosito/gotenv v1.6.0 // indirect 31 | go.uber.org/multierr v1.11.0 // indirect 32 | golang.org/x/exp v0.0.0-20240222234643-814bf88cf225 // indirect 33 | golang.org/x/net v0.21.0 // indirect 34 | golang.org/x/sys v0.17.0 // indirect 35 | golang.org/x/text v0.14.0 // indirect 36 | gopkg.in/ini.v1 v1.67.0 // indirect 37 | gopkg.in/yaml.v3 v3.0.1 // indirect 38 | ) 39 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= 2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 4 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= 5 | github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= 6 | github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= 7 | github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= 8 | github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= 9 | github.com/google/gopacket v1.1.19 h1:ves8RnFZPGiFnTS0uPQStjwru6uO6h+nlr9j6fL7kF8= 10 | github.com/google/gopacket v1.1.19/go.mod h1:iJ8V8n6KS+z2U1A8pUwu8bW5SyEMkXJB8Yo/Vo+TKTo= 11 | github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= 12 | github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= 13 | github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= 14 | github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= 15 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= 16 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 17 | github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= 18 | github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= 19 | github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= 20 | github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= 21 | github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= 22 | github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= 23 | github.com/oschwald/geoip2-golang v1.9.0 h1:uvD3O6fXAXs+usU+UGExshpdP13GAqp4GBrzN7IgKZc= 24 | github.com/oschwald/geoip2-golang v1.9.0/go.mod h1:BHK6TvDyATVQhKNbQBdrj9eAvuwOMi2zSFXizL3K81Y= 25 | github.com/oschwald/maxminddb-golang v1.12.0 h1:9FnTOD0YOhP7DGxGsq4glzpGy5+w7pq50AS6wALUMYs= 26 | github.com/oschwald/maxminddb-golang v1.12.0/go.mod h1:q0Nob5lTCqyQ8WT6FYgS1L7PXKVVbgiymefNwIjPzgY= 27 | github.com/pelletier/go-toml/v2 v2.1.1 h1:LWAJwfNvjQZCFIDKWYQaM62NcYeYViCmWIwmOStowAI= 28 | github.com/pelletier/go-toml/v2 v2.1.1/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= 29 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 30 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= 31 | github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= 32 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 33 | github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ= 34 | github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= 35 | github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= 36 | github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= 37 | github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= 38 | github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= 39 | github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= 40 | github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= 41 | github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= 42 | github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= 43 | github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0= 44 | github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= 45 | github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0= 46 | github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho= 47 | github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= 48 | github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 49 | github.com/spf13/viper v1.18.2 h1:LUXCnvUvSM6FXAsj6nnfc8Q2tp1dIgUfY9Kc8GsSOiQ= 50 | github.com/spf13/viper v1.18.2/go.mod h1:EKmWIqdnk5lOcmR72yw6hS+8OPYcwD0jteitLMVB+yk= 51 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 52 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 53 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 54 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 55 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 56 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 57 | github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= 58 | github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= 59 | github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= 60 | github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= 61 | go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= 62 | go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= 63 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 64 | golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 65 | golang.org/x/exp v0.0.0-20240222234643-814bf88cf225 h1:LfspQV/FYTatPTr/3HzIcmiUFH7PGP+OQ6mgDYo3yuQ= 66 | golang.org/x/exp v0.0.0-20240222234643-814bf88cf225/go.mod h1:CxmFvTBINI24O/j8iY7H1xHzx2i4OsyguNBmN/uPtqc= 67 | golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= 68 | golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= 69 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 70 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 71 | golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4= 72 | golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= 73 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 74 | golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ= 75 | golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= 76 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 77 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 78 | golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 79 | golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y= 80 | golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 81 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 82 | golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= 83 | golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= 84 | golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= 85 | golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 86 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 87 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= 88 | gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= 89 | gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= 90 | gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= 91 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= 92 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 93 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 94 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 95 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2020 Stamus Networks oss@stamus-networks.com 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package main 18 | 19 | import "github.com/StamusNetworks/gophercap/cmd" 20 | 21 | func main() { 22 | cmd.Execute() 23 | } 24 | -------------------------------------------------------------------------------- /pkg/dedup/dedup.go: -------------------------------------------------------------------------------- 1 | package dedup 2 | 3 | import ( 4 | "crypto/md5" 5 | "encoding/hex" 6 | "time" 7 | 8 | "github.com/google/gopacket" 9 | "github.com/google/gopacket/layers" 10 | ) 11 | 12 | // HashMD5 is inspired by packet deduplication in Arkime 13 | // https://github.com/arkime/arkime/blob/main/capture/dedup.c#L57 14 | func HashMD5(pkt gopacket.Packet) []byte { 15 | h := md5.New() 16 | for _, layer := range pkt.Layers() { 17 | switch layer.LayerType() { 18 | case layers.LayerTypeIPv4: 19 | data := layer.LayerContents() 20 | h.Write(data[0:7]) 21 | // skip TTL 22 | h.Write(data[9:9]) 23 | // skip checksum 24 | h.Write(data[13:]) 25 | case layers.LayerTypeIPv6: 26 | data := layer.LayerContents() 27 | h.Write(data[0:6]) 28 | // skip hop limit 29 | h.Write(data[8:]) 30 | case layers.LayerTypeTCP, layers.LayerTypeUDP: 31 | h.Write(layer.LayerContents()) 32 | // we only want TCP or UDP packets to be deduplicated 33 | // hashing every packet could cause problems with ICMP or more obscure protocols 34 | return h.Sum(nil) 35 | } 36 | } 37 | return nil 38 | } 39 | 40 | // Dedupper is a subsystem that accepts a gopacket type and reports if it has been already seen 41 | type Dedupper interface { 42 | // Drop implements Dedupper 43 | Drop(gopacket.Packet) bool 44 | } 45 | 46 | // TrivialDedup is only a minimal prototype for simple testing and SHOULD NOT BE USED 47 | // It will leak memory and will likely see a high hash collision rate 48 | type TrivialDedup struct { 49 | Set map[string]bool 50 | Hits uint64 51 | } 52 | 53 | // Drop implements Dedupper 54 | func (d *TrivialDedup) Drop(pkt gopacket.Packet) (found bool) { 55 | if d.Set == nil { 56 | // this object should not have a constructor 57 | d.Set = make(map[string]bool) 58 | } 59 | h := HashMD5(pkt) 60 | if h == nil { 61 | return false 62 | } 63 | key := hex.EncodeToString(h) 64 | if d.Set[key] { 65 | found = true 66 | d.Hits++ 67 | } 68 | d.Set[key] = true 69 | return found 70 | } 71 | 72 | // CircularDedup maintains N buckets of hash sets 73 | // hash lookup is done from all 74 | // if hash is not found, add to latest 75 | // rotate buckets if bucket duration has passed 76 | type CircularDedup struct { 77 | // circular array of hash sets 78 | Buckets []map[string]bool 79 | // max number of buckets to be kept 80 | MaxBuckets int 81 | // max duration of each bucket 82 | Duration time.Duration 83 | // timestamp of latest bucket 84 | Bucket time.Time 85 | } 86 | 87 | func (cd *CircularDedup) Drop(pkt gopacket.Packet) (found bool) { 88 | count := len(cd.Buckets) 89 | if count == 0 { 90 | cd.Buckets = make([]map[string]bool, 0, cd.MaxBuckets) 91 | cd.Buckets[0] = make(map[string]bool) 92 | } 93 | h := HashMD5(pkt) 94 | if h == nil { 95 | return false 96 | } 97 | key := hex.EncodeToString(h) 98 | for _, bucket := range cd.Buckets { 99 | if bucket[key] { 100 | found = true 101 | } 102 | } 103 | if !found { 104 | cd.Buckets[len(cd.Buckets)-1][key] = true 105 | } 106 | // check if new bucket needs to be added 107 | if time.Since(cd.Bucket) > cd.Duration { 108 | cd.Buckets = append(cd.Buckets, map[string]bool{}) 109 | cd.Bucket = time.Now().Truncate(cd.Duration) 110 | // drop last bucket if oversized 111 | if count+1 > cd.MaxBuckets { 112 | cd.Buckets = cd.Buckets[1:] 113 | } 114 | } 115 | return found 116 | } 117 | 118 | func NewCircularDedup(max int, duration time.Duration) *CircularDedup { 119 | cd := &CircularDedup{} 120 | if max < 2 { 121 | cd.MaxBuckets = 2 122 | } else { 123 | cd.MaxBuckets = max 124 | } 125 | if duration == 0 { 126 | cd.Duration = 2 * time.Second 127 | } else { 128 | cd.Duration = duration 129 | } 130 | cd.Buckets = make([]map[string]bool, 1, max) 131 | cd.Buckets[0] = make(map[string]bool) 132 | cd.Bucket = time.Now().Truncate(cd.Duration) 133 | return cd 134 | } 135 | -------------------------------------------------------------------------------- /pkg/dedup/dedup_test.go: -------------------------------------------------------------------------------- 1 | package dedup 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "net" 7 | "testing" 8 | 9 | "github.com/google/gopacket" 10 | "github.com/google/gopacket/layers" 11 | ) 12 | 13 | type pktParams struct { 14 | srcIP net.IP 15 | destIP net.IP 16 | srcMAC net.HardwareAddr 17 | destMac net.HardwareAddr 18 | srcPort uint16 19 | destPort uint16 20 | ttl uint8 21 | csum uint16 22 | } 23 | 24 | type v4params struct { 25 | pktParams 26 | } 27 | 28 | func buildPacketIPv4(p v4params) []byte { 29 | ethernetLayer := &layers.Ethernet{ 30 | SrcMAC: p.srcMAC, 31 | DstMAC: p.destMac, 32 | EthernetType: layers.EthernetTypeIPv4, 33 | } 34 | ipLayer := &layers.IPv4{ 35 | Version: 4, 36 | TTL: p.ttl, 37 | SrcIP: p.srcIP, 38 | DstIP: p.destIP, 39 | Checksum: p.csum, 40 | Protocol: layers.IPProtocolTCP, 41 | } 42 | tcpLayer := &layers.TCP{ 43 | SrcPort: layers.TCPPort(p.srcPort), 44 | DstPort: layers.TCPPort(p.destPort), 45 | } 46 | tcpLayer.SetNetworkLayerForChecksum(ipLayer) 47 | rawBytes := []byte{10, 20, 30} 48 | 49 | options := gopacket.SerializeOptions{ 50 | ComputeChecksums: true, 51 | FixLengths: true, 52 | } 53 | buffer := gopacket.NewSerializeBuffer() 54 | // And create the packet with the layers 55 | if err := gopacket.SerializeLayers(buffer, options, 56 | ethernetLayer, 57 | ipLayer, 58 | tcpLayer, 59 | gopacket.Payload(rawBytes), 60 | ); err != nil { 61 | // FIXME 62 | } 63 | return buffer.Bytes() 64 | } 65 | 66 | func TestHashV4(t *testing.T) { 67 | opts := gopacket.DecodeOptions{ 68 | Lazy: false, 69 | NoCopy: false, 70 | } 71 | firstLayer := layers.LayerTypeEthernet 72 | hashOrig := HashMD5(gopacket.NewPacket( 73 | buildPacketIPv4(v4params{ 74 | pktParams: pktParams{ 75 | srcIP: net.IP{127, 0, 0, 1}, 76 | destIP: net.IP{8, 8, 8, 8}, 77 | srcMAC: net.HardwareAddr{0xFF, 0xAA, 0xFA, 0xAA, 0xFF, 0xAA}, 78 | destMac: net.HardwareAddr{0xBD, 0xBD, 0xBD, 0xBD, 0xBD, 0xAA}, 79 | srcPort: 29999, 80 | destPort: 80, 81 | ttl: 13, 82 | csum: uint16(12379), 83 | }, 84 | }), 85 | firstLayer, 86 | opts)) 87 | // TTL and checksum should not affect hash result 88 | hashIdentical := HashMD5(gopacket.NewPacket( 89 | buildPacketIPv4(v4params{ 90 | pktParams: pktParams{ 91 | srcIP: net.IP{127, 0, 0, 1}, 92 | destIP: net.IP{8, 8, 8, 8}, 93 | srcMAC: net.HardwareAddr{0xFF, 0xAA, 0xFA, 0xAA, 0xFF, 0xBD}, 94 | destMac: net.HardwareAddr{0xBD, 0xBD, 0xBD, 0xBD, 0xBD, 0xBD}, 95 | srcPort: 29999, 96 | destPort: 80, 97 | ttl: 99, 98 | csum: uint16(7893), 99 | }, 100 | }), 101 | firstLayer, 102 | opts)) 103 | if !bytes.Equal(hashOrig, hashIdentical) { 104 | t.Fatal("TTL and checksum should not affect IPv4 packet results") 105 | } 106 | hashDiffIP := HashMD5(gopacket.NewPacket( 107 | buildPacketIPv4(v4params{ 108 | pktParams: pktParams{ 109 | srcIP: net.IP{127, 0, 0, 1}, 110 | destIP: net.IP{8, 8, 4, 4}, 111 | srcMAC: net.HardwareAddr{0xFF, 0xAA, 0xFA, 0xAA, 0xFF, 0xAA}, 112 | destMac: net.HardwareAddr{0xBD, 0xBD, 0xBD, 0xBD, 0xBD, 0xFF}, 113 | srcPort: 30000, 114 | destPort: 80, 115 | ttl: 99, 116 | csum: uint16(7893), 117 | }, 118 | }), 119 | firstLayer, 120 | opts)) 121 | if bytes.Equal(hashOrig, hashDiffIP) { 122 | fmt.Println(hashOrig) 123 | fmt.Println(hashDiffIP) 124 | t.Fatal("dest IP change should change hash result") 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /pkg/extract/filter.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2021 Stamus Networks oss@stamus-networks.com 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package extract 18 | 19 | import ( 20 | "errors" 21 | "fmt" 22 | 23 | "github.com/google/gopacket" 24 | "github.com/google/gopacket/layers" 25 | "github.com/sirupsen/logrus" 26 | ) 27 | 28 | // FlowPair holds IP and Transport layers for an event 29 | type FlowPair struct { 30 | // IP is the Flow containing data 31 | IP *gopacket.Flow 32 | // Transport is the Flow of the tunnel 33 | Transport *gopacket.Flow 34 | } 35 | 36 | func buildBPF(event Event) (string, error) { 37 | proto := event.Proto 38 | srcIp := event.SrcIP 39 | destIp := event.DestIP 40 | srcPort := event.SrcPort 41 | destPort := event.DestPort 42 | if event.Tunnel.Depth != 0 { 43 | proto = event.Tunnel.Proto 44 | srcIp = event.Tunnel.SrcIP 45 | destIp = event.Tunnel.DestIP 46 | srcPort = event.Tunnel.SrcPort 47 | destPort = event.Tunnel.DestPort 48 | } 49 | bpfFilter := "proto " + proto + " and " 50 | switch proto { 51 | case "TCP", "UDP": 52 | bpfFilter += "(" 53 | bpfFilter += fmt.Sprintf("(src host %s and src port %d and dst host %s and dst port %d)", srcIp, srcPort, destIp, destPort) 54 | bpfFilter += " or " 55 | bpfFilter += fmt.Sprintf("(src host %s and src port %d and dst host %s and dst port %d)", destIp, destPort, srcIp, srcPort) 56 | bpfFilter += ")" 57 | case "GRE": 58 | bpfFilter += "(" 59 | if event.Tunnel.Depth != 0 { 60 | bpfFilter += fmt.Sprintf("host %v and host %v", event.Tunnel.SrcIP, event.Tunnel.DestIP) 61 | } else { 62 | bpfFilter += fmt.Sprintf("host %v and host %v", event.SrcIP, event.DestIP) 63 | } 64 | bpfFilter += ")" 65 | default: 66 | return "", errors.New("Protocol not supported") 67 | } 68 | logrus.Debugln(bpfFilter) 69 | return bpfFilter, nil 70 | } 71 | 72 | func buildEndpoints(event Event) (*FlowPair, error) { 73 | srcIPEndpoint := layers.NewIPEndpoint(event.SrcIP.IP) 74 | destIPEndpoint := layers.NewIPEndpoint(event.DestIP.IP) 75 | IPFlow, err := gopacket.FlowFromEndpoints(srcIPEndpoint, destIPEndpoint) 76 | if err != nil { 77 | logrus.Error("Can not create IP Flow: ", err) 78 | } 79 | 80 | var srcEndpoint gopacket.Endpoint 81 | var destEndpoint gopacket.Endpoint 82 | switch event.Proto { 83 | case "TCP": 84 | srcEndpoint = layers.NewTCPPortEndpoint(layers.TCPPort(event.SrcPort)) 85 | destEndpoint = layers.NewTCPPortEndpoint(layers.TCPPort(event.DestPort)) 86 | case "UDP": 87 | srcEndpoint = layers.NewUDPPortEndpoint(layers.UDPPort(event.SrcPort)) 88 | destEndpoint = layers.NewUDPPortEndpoint(layers.UDPPort(event.DestPort)) 89 | case "SCTP": 90 | srcEndpoint = layers.NewSCTPPortEndpoint(layers.SCTPPort(event.SrcPort)) 91 | destEndpoint = layers.NewSCTPPortEndpoint(layers.SCTPPort(event.DestPort)) 92 | default: 93 | return &FlowPair{IP: &IPFlow, Transport: &gopacket.InvalidFlow}, errors.New("Unsupported protocol " + event.Proto) 94 | } 95 | 96 | transportFlow, err := gopacket.FlowFromEndpoints(srcEndpoint, destEndpoint) 97 | if err != nil { 98 | logrus.Error("Can not create transport Flow", err) 99 | } 100 | return &FlowPair{IP: &IPFlow, Transport: &transportFlow}, err 101 | } 102 | 103 | func filterTunnel(data []byte, eventFLowPair FlowPair, event Event) bool { 104 | packet := gopacket.NewPacket(data, layers.LayerTypeEthernet, gopacket.Lazy) 105 | switch event.Proto { 106 | case "TCP": 107 | tcpLayer := packet.Layer(layers.LayerTypeTCP) 108 | if tcpLayer != nil { 109 | tcp, _ := tcpLayer.(*layers.TCP) 110 | if tcp.TransportFlow() == *eventFLowPair.Transport || tcp.TransportFlow() == eventFLowPair.Transport.Reverse() { 111 | /* TODO handle depth > 1 */ 112 | networkLayer := packet.NetworkLayer() 113 | if event.Tunnel.Depth > 0 { 114 | var tLayer gopacket.Layer 115 | switch event.Tunnel.Proto { 116 | case "GRE": 117 | tLayer = packet.Layer(layers.LayerTypeGRE) 118 | case "VXLAN": 119 | tLayer = packet.Layer(layers.LayerTypeVXLAN) 120 | default: 121 | logrus.Error("Unsupported tunnel type: " + event.Tunnel.Proto) 122 | return false 123 | } 124 | actualPacket := gopacket.NewPacket(tLayer.LayerPayload(), layers.LayerTypeIPv4, gopacket.Lazy) 125 | networkLayer = actualPacket.NetworkLayer() 126 | } 127 | nFlow := networkLayer.NetworkFlow() 128 | if nFlow == *eventFLowPair.IP || nFlow == eventFLowPair.IP.Reverse() { 129 | return true 130 | } 131 | } 132 | } 133 | case "UDP": 134 | udpLayer := packet.Layer(layers.LayerTypeUDP) 135 | /* TODO handle tunnel in UDP */ 136 | if udpLayer != nil { 137 | udp, _ := udpLayer.(*layers.UDP) 138 | if udp.TransportFlow() == *eventFLowPair.Transport || udp.TransportFlow() == eventFLowPair.Transport.Reverse() { 139 | return true 140 | } 141 | } 142 | case "SCTP": 143 | sctpLayer := packet.Layer(layers.LayerTypeSCTP) 144 | /* TODO handle tunnel in SCTP */ 145 | if sctpLayer != nil { 146 | sctp, _ := sctpLayer.(*layers.SCTP) 147 | if sctp.TransportFlow() == *eventFLowPair.Transport || sctp.TransportFlow() == eventFLowPair.Transport.Reverse() { 148 | return true 149 | } 150 | } 151 | } 152 | return false 153 | } 154 | -------------------------------------------------------------------------------- /pkg/extract/functions.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2021 Stamus Networks oss@stamus-networks.com 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package extract 18 | 19 | import ( 20 | "errors" 21 | "fmt" 22 | "io" 23 | "io/ioutil" 24 | "net" 25 | "os" 26 | "path/filepath" 27 | "strconv" 28 | "time" 29 | 30 | "encoding/json" 31 | 32 | "github.com/google/gopacket/layers" 33 | "github.com/google/gopacket/pcap" 34 | "github.com/google/gopacket/pcapgo" 35 | "github.com/sirupsen/logrus" 36 | ) 37 | 38 | const FlowTimeout time.Duration = 600 * 1000000000 39 | 40 | func writePacket(handle *pcap.Handle, buf []byte) error { 41 | if err := handle.WritePacketData(buf); err != nil { 42 | logrus.Warningf("Failed to write packet: %s\n", err) 43 | return err 44 | } 45 | return nil 46 | } 47 | 48 | // IPAddr is for decoding IP values directly to IP objects during JSON decode. net.IP is a wrapper 49 | // around byte array, not integer, so it also handles IPv6 addresses. 50 | type IPAddr struct{ net.IP } 51 | 52 | // UnmarshalJSON implements json.Unmarshaler 53 | func (t *IPAddr) UnmarshalJSON(b []byte) error { 54 | str, err := strconv.Unquote(string(b)) 55 | if err != nil { 56 | return err 57 | } 58 | ip := net.ParseIP(str) 59 | if ip == nil { 60 | return fmt.Errorf("Invalid IP: %s", string(b)) 61 | } 62 | t.IP = ip 63 | return nil 64 | } 65 | 66 | type Tunnel struct { 67 | SrcIP IPAddr `json:"src_ip"` 68 | DestIP IPAddr `json:"dest_ip"` 69 | SrcPort uint16 `json:"src_port"` 70 | DestPort uint16 `json:"dest_port"` 71 | Proto string `json:"proto"` 72 | Depth uint8 `json:"depth"` 73 | } 74 | 75 | type Event struct { 76 | Timestamp string 77 | CaptureFile string `json:"capture_file"` 78 | SrcIP IPAddr `json:"src_ip"` 79 | DestIP IPAddr `json:"dest_ip"` 80 | SrcPort uint16 `json:"src_port"` 81 | DestPort uint16 `json:"dest_port"` 82 | AppProto string `json:"app_proto"` 83 | Proto string `json:"proto"` 84 | Tunnel Tunnel `json:"tunnel"` 85 | } 86 | 87 | func openPcapReaderHandle(fName string, bpfFilter string) (*pcap.Handle, error) { 88 | // Open PCAP file + handle potential BPF Filter 89 | // TODO maybe use a pcapgo reader 90 | handleRead, err := pcap.OpenOffline(fName) 91 | if err != nil { 92 | return handleRead, err 93 | } 94 | 95 | if err == nil { 96 | err = handleRead.SetBPFFilter(bpfFilter) 97 | if err != nil { 98 | logrus.Errorf("Invalid BPF Filter: %s", err) 99 | return handleRead, err 100 | } 101 | } 102 | return handleRead, nil 103 | } 104 | 105 | type ExtractPcapConfig struct { 106 | OutputName string 107 | EventPath string 108 | FileFormat string 109 | SkipBpf bool 110 | } 111 | 112 | /* 113 | Extract a pcap file for a given flow 114 | */ 115 | func ExtractPcapFile(config ExtractPcapConfig) error { 116 | /* open event file */ 117 | eventFile, err := os.Open(config.EventPath) 118 | if err != nil { 119 | return err 120 | } 121 | defer eventFile.Close() 122 | 123 | eventPathstring, err := ioutil.ReadAll(eventFile) 124 | if err != nil { 125 | return err 126 | } 127 | 128 | var event Event 129 | err = json.Unmarshal(eventPathstring, &event) 130 | if err != nil { 131 | return errors.New("Can't parse JSON in " + config.EventPath) 132 | } 133 | pcapDir := filepath.Dir(event.CaptureFile) 134 | 135 | if len(event.CaptureFile) > 0 { 136 | _, err := os.Stat(event.CaptureFile) 137 | if os.IsNotExist(err) { 138 | return err 139 | } 140 | logrus.Debugf("Starting from file %s", event.CaptureFile) 141 | } 142 | 143 | if event.Tunnel.Depth != 0 { 144 | logrus.Debugf("Tunnel: %s <-%s-> %s\n", event.Tunnel.SrcIP, event.Tunnel.Proto, event.Tunnel.DestIP) 145 | } 146 | logrus.Debugf("Flow: %s <-%s:%s-> %s\n", event.SrcIP, event.Proto, event.AppProto, event.DestIP) 147 | eventFlowPair, err := buildEndpoints(event) 148 | if err != nil { 149 | return err 150 | } 151 | 152 | pcapFileList := NewPcapFileList(pcapDir, event, config.FileFormat) 153 | if pcapFileList == nil { 154 | return errors.New("Problem when building pcap file list") 155 | } 156 | 157 | bpfFilter := "" 158 | if config.SkipBpf != true { 159 | bpfFilter, err = buildBPF(event) 160 | if err != nil { 161 | logrus.Warning(err) 162 | } 163 | } 164 | 165 | // Open up a second pcap handle for packet writes. 166 | outfile, err := os.Create(config.OutputName) 167 | if err != nil { 168 | logrus.Error("Can't open pcap output file: ", err) 169 | return err 170 | } 171 | defer outfile.Close() 172 | 173 | handleWrite := pcapgo.NewWriter(outfile) 174 | handleWrite.WriteFileHeader(65536, layers.LinkTypeEthernet) // new file, must do this. 175 | if err != nil { 176 | logrus.Error("Can't write to output file: ", err) 177 | return err 178 | } 179 | 180 | start := time.Now() 181 | var pktCount uint64 = 0 182 | /* FIXME we can do better here */ 183 | var lastTimestamp time.Time = time.Now() 184 | var firstTimestamp time.Time = time.Now() 185 | 186 | fName, err := pcapFileList.GetNext() 187 | if err != nil { 188 | switch err.(type) { 189 | case ErrOutOfFiles, *ErrOutOfFiles: 190 | logrus.Debugf("Expected at least one file: %s\n", err) 191 | return nil 192 | default: 193 | return err 194 | } 195 | } 196 | /* 197 | Loop over pcap file starting with the one specified in the event 198 | If timestamp of first packet > lastTimestamp of flow + flow_timeout then 199 | we can consider we are at the last pcap 200 | */ 201 | for len(event.CaptureFile) == 0 || firstTimestamp.Before(lastTimestamp.Add(FlowTimeout)) { 202 | filePkt := 0 203 | logrus.Debugf("Reading packets from %s", fName) 204 | handleRead, err := openPcapReaderHandle(fName, bpfFilter) 205 | defer handleRead.Close() 206 | if err != nil { 207 | logrus.Warningln("This was fast") 208 | break 209 | } 210 | 211 | // Loop over packets and write them 212 | for { 213 | data, ci, err := handleRead.ReadPacketData() 214 | 215 | switch { 216 | case err == io.EOF: 217 | logrus.Debugf("Extracted %d packet(s) from pcap file %s", filePkt, fName) 218 | goto NextFile 219 | case err != nil: 220 | logrus.Warningf("Failed to read packet %d: %s\n", pktCount, err) 221 | default: 222 | if config.SkipBpf == true || event.Tunnel.Depth > 0 { 223 | if filterTunnel(data, *eventFlowPair, event) { 224 | handleWrite.WritePacket(ci, data) 225 | pktCount++ 226 | lastTimestamp = ci.Timestamp 227 | } 228 | } else { 229 | handleWrite.WritePacket(ci, data) 230 | pktCount++ 231 | filePkt++ 232 | } 233 | } 234 | } 235 | NextFile: 236 | /* Open new pcap to see the beginning */ 237 | fName, err = pcapFileList.GetNext() 238 | if err != nil { 239 | logrus.Debugln(err) 240 | break 241 | } 242 | handleTest, err := openPcapReaderHandle(fName, bpfFilter) 243 | if err != nil { 244 | break 245 | } 246 | _, ci, err := handleRead.ReadPacketData() 247 | firstTimestamp = ci.Timestamp 248 | handleTest.Close() 249 | } 250 | logrus.Infof("Finished in %s\n", time.Since(start)) 251 | logrus.Infof("Written %d packet(s)\n", pktCount) 252 | 253 | return nil 254 | } 255 | -------------------------------------------------------------------------------- /pkg/extract/pcapfiles.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2021 Stamus Networks oss@stamus-networks.com 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package extract 18 | 19 | import ( 20 | "errors" 21 | "fmt" 22 | "io/ioutil" 23 | "path" 24 | "regexp" 25 | "strconv" 26 | "strings" 27 | "time" 28 | 29 | "github.com/sirupsen/logrus" 30 | ) 31 | 32 | type ErrOutOfFiles struct { 33 | } 34 | 35 | func (e ErrOutOfFiles) Error() string { 36 | return "No more files" 37 | } 38 | 39 | type PcapFileList struct { 40 | Files []string 41 | DirName string 42 | FileName string 43 | Index int 44 | FileParsing *regexp.Regexp 45 | ThreadIndex int 46 | TimestampIndex int 47 | } 48 | 49 | func NewPcapFileList(dname string, event Event, fileFormat string) *PcapFileList { 50 | pl := new(PcapFileList) 51 | pl.DirName = dname 52 | pl.buildPcapNameParsing(fileFormat) 53 | if len(event.CaptureFile) > 0 { 54 | pl.Files = append(pl.Files, event.CaptureFile) 55 | err := pl.buildPcapList() 56 | if err != nil { 57 | return nil 58 | } 59 | pl.FileName = event.CaptureFile 60 | } else { 61 | logrus.Debug("Scanning will start soon") 62 | err := pl.buildFullPcapList() 63 | if err != nil { 64 | return nil 65 | } 66 | } 67 | return pl 68 | } 69 | 70 | /* Suricata supports following expansion 71 | - %n -- thread number 72 | - %i -- thread id 73 | - %t -- timestamp 74 | */ 75 | func (pl *PcapFileList) buildPcapNameParsing(fileFormat string) { 76 | /* get each token */ 77 | threadIndex := strings.Index(fileFormat, "%n") 78 | if threadIndex == -1 { 79 | threadIndex = strings.Index(fileFormat, "%i") 80 | } 81 | timestampIndex := strings.Index(fileFormat, "%t") 82 | if threadIndex < timestampIndex { 83 | pl.ThreadIndex = 1 84 | pl.TimestampIndex = 2 85 | } else { 86 | pl.ThreadIndex = 2 87 | pl.TimestampIndex = 1 88 | } 89 | /* handle the case where just the timestamp is available */ 90 | if threadIndex == -1 { 91 | pl.ThreadIndex = -1 92 | pl.TimestampIndex = 1 93 | } 94 | regexpString := strings.Replace(fileFormat, "%n", `(\d+)`, 1) 95 | regexpString = strings.Replace(regexpString, "%i", `(\d+)`, 1) 96 | regexpString = strings.Replace(regexpString, "%t", `(\d+)`, 1) 97 | logrus.Debug("Using regexp: ", regexpString) 98 | /* build regular expression */ 99 | pl.FileParsing = regexp.MustCompile(regexpString) 100 | } 101 | 102 | func (pl *PcapFileList) GetNext() (string, error) { 103 | if pl.Index < len(pl.Files) { 104 | pfile := pl.Files[pl.Index] 105 | pl.Index += 1 106 | return pfile, nil 107 | } 108 | return "", &ErrOutOfFiles{} 109 | } 110 | 111 | func (pl *PcapFileList) buildPcapList() error { 112 | if pl.Files == nil || len(pl.Files) < 1 { 113 | return errors.New("No file available") 114 | } 115 | dName := path.Dir(pl.Files[0]) 116 | logrus.Debug("Scanning directory: ", dName) 117 | filePart := path.Base(pl.Files[0]) 118 | match := pl.FileParsing.FindStringSubmatch(filePart) 119 | if len(match) == 0 { 120 | logrus.Errorf("file %s does not match file format", filePart) 121 | return errors.New("Invalid file name in event") 122 | } 123 | var threadIndex int64 = -1 124 | if pl.ThreadIndex != -1 { 125 | var err error 126 | threadIndex, err = strconv.ParseInt(match[pl.ThreadIndex], 10, 64) 127 | if err != nil { 128 | logrus.Warning("Can't parse integer") 129 | } 130 | } 131 | timestampValue, err := strconv.ParseInt(match[pl.TimestampIndex], 10, 64) 132 | timestamp := time.Unix(timestampValue, 0) 133 | if err != nil { 134 | logrus.Warning("Can't parse integer") 135 | return errors.New("Invalid timestamp in file name") 136 | } 137 | files, err := ioutil.ReadDir(dName) 138 | if err != nil { 139 | logrus.Warningf("Can't open directory %s: %s", dName, err) 140 | } 141 | for _, file := range files { 142 | if file.Name() == filePart { 143 | continue 144 | } 145 | lMatch := pl.FileParsing.FindStringSubmatch(file.Name()) 146 | if lMatch == nil { 147 | continue 148 | } 149 | if pl.ThreadIndex != -1 { 150 | lThreadIndex, err := strconv.ParseInt(lMatch[pl.ThreadIndex], 10, 64) 151 | if err != nil { 152 | logrus.Warning("Can't parse integer") 153 | continue 154 | } 155 | if lThreadIndex != threadIndex { 156 | continue 157 | } 158 | } 159 | lTimestampValue, err := strconv.ParseInt(lMatch[pl.TimestampIndex], 10, 64) 160 | lTimestamp := time.Unix(lTimestampValue, 0) 161 | if err != nil { 162 | logrus.Warning("Can't parse integer") 163 | continue 164 | } 165 | if timestamp.Before(lTimestamp) { 166 | logrus.Infof("Adding file %s", file.Name()) 167 | pl.Files = append(pl.Files, path.Join(dName, file.Name())) 168 | } else { 169 | logrus.Debugf("Skipping file %s", file.Name()) 170 | } 171 | } 172 | return nil 173 | } 174 | 175 | func (pl *PcapFileList) buildFullPcapList() error { 176 | logrus.Debugf("Scanning directory: %s", pl.DirName) 177 | files, err := ioutil.ReadDir(pl.DirName) 178 | if err != nil { 179 | return fmt.Errorf("Can't open directory %s: %s", pl.DirName, err) 180 | } 181 | for _, file := range files { 182 | lMatch := pl.FileParsing.FindStringSubmatch(file.Name()) 183 | if lMatch == nil { 184 | continue 185 | } 186 | logrus.Infof("Adding file %s", file.Name()) 187 | pl.Files = append(pl.Files, path.Join(pl.DirName, file.Name())) 188 | } 189 | return nil 190 | } 191 | -------------------------------------------------------------------------------- /pkg/filter/condition.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2022 Stamus Networks oss@stamus-networks.com 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package filter 18 | 19 | import ( 20 | "errors" 21 | "fmt" 22 | "net" 23 | "strconv" 24 | "strings" 25 | 26 | "github.com/google/gopacket" 27 | "github.com/google/gopacket/layers" 28 | "github.com/oschwald/geoip2-golang" 29 | ) 30 | 31 | type FilterKind int 32 | 33 | const ( 34 | FilterKindUndefined FilterKind = iota 35 | FilterKindSubnet 36 | FilterKindEther 37 | FilterKindPort 38 | FilterKindASN 39 | FilterKindRaw 40 | ) 41 | 42 | func (k FilterKind) String() string { 43 | switch k { 44 | case FilterKindSubnet: 45 | return "subnet" 46 | case FilterKindEther: 47 | return "ether" 48 | case FilterKindPort: 49 | return "port" 50 | case FilterKindASN: 51 | return "asn" 52 | case FilterKindRaw: 53 | return "raw" 54 | default: 55 | return "undefined" 56 | } 57 | } 58 | 59 | var FilterKinds = []string{ 60 | FilterKindSubnet.String(), 61 | FilterKindEther.String(), 62 | FilterKindPort.String(), 63 | FilterKindASN.String(), 64 | FilterKindRaw.String(), 65 | } 66 | 67 | func NewFilterKind(raw string) FilterKind { 68 | switch raw { 69 | case FilterKindSubnet.String(): 70 | return FilterKindSubnet 71 | case FilterKindEther.String(): 72 | return FilterKindEther 73 | case FilterKindPort.String(): 74 | return FilterKindPort 75 | case FilterKindASN.String(): 76 | return FilterKindASN 77 | case FilterKindRaw.String(): 78 | return FilterKindRaw 79 | default: 80 | return FilterKindUndefined 81 | } 82 | } 83 | 84 | // Matcher is for filtering packets 85 | type Matcher interface { 86 | // Match should indicate if packet matches criteria 87 | Match(gopacket.Packet) bool 88 | } 89 | 90 | type DummyMatcher struct{} 91 | 92 | func (d DummyMatcher) Match(pkt gopacket.Packet) bool { 93 | return true 94 | } 95 | 96 | // CombinedMatcher allows us to use multiple match criteria 97 | type CombinedMatcher struct { 98 | Conditions []Matcher 99 | } 100 | 101 | func (cm CombinedMatcher) Match(pkt gopacket.Packet) bool { 102 | for _, matcher := range cm.Conditions { 103 | if !matcher.Match(pkt) { 104 | return false 105 | } 106 | } 107 | return true 108 | } 109 | 110 | func NewCombinedMatcher(c MatcherConfig) (*CombinedMatcher, error) { 111 | if len(c.Conditions) == 0 { 112 | return nil, errors.New("combined config condition missing") 113 | } 114 | conditions := make([]Matcher, 0, len(c.Conditions)) 115 | for i, condition := range c.Conditions { 116 | var m Matcher 117 | switch NewFilterKind(condition.Kind) { 118 | case FilterKindSubnet: 119 | sm, err := NewConditionalSubnet(condition.Match) 120 | if err != nil { 121 | return nil, err 122 | } 123 | m = sm 124 | case FilterKindEther: 125 | sm, err := NewConditionEther(condition.Match) 126 | if err != nil { 127 | return nil, err 128 | } 129 | m = sm 130 | case FilterKindPort: 131 | pm, err := NewPortMatcher(condition.Match) 132 | if err != nil { 133 | return nil, err 134 | } 135 | m = pm 136 | case FilterKindASN: 137 | if c.MaxMindASN == "" { 138 | return nil, errors.New("asn matcher needs maxmind ASN database") 139 | } 140 | fa, err := NewConditionASN(c.MaxMindASN, condition.Match) 141 | if err != nil { 142 | return nil, err 143 | } 144 | m = fa 145 | case FilterKindRaw: 146 | m = &DummyMatcher{} 147 | default: 148 | return nil, fmt.Errorf( 149 | "filtering condition %s unsupported for condition %d, use one of %s", 150 | condition.Kind, i, strings.Join(FilterKinds, ", "), 151 | ) 152 | } 153 | if m == nil { 154 | return nil, fmt.Errorf("unable to build matcher for item %d", i) 155 | } 156 | if condition.Negate { 157 | m = NegateMatcher{M: m} 158 | } 159 | conditions = append(conditions, m) 160 | } 161 | return &CombinedMatcher{ 162 | Conditions: conditions, 163 | }, nil 164 | } 165 | 166 | // NegateMatcher implements logical NOT 167 | type NegateMatcher struct { 168 | M Matcher 169 | } 170 | 171 | func (nm NegateMatcher) Match(pkt gopacket.Packet) bool { return !nm.M.Match(pkt) } 172 | 173 | // NewConditionalSubnet parses a list of textual network addrs into a Matcher 174 | func NewConditionalSubnet(nets []string) (ConditionSubnet, error) { 175 | if len(nets) == 0 { 176 | return nil, errors.New("no networks to parse into contition") 177 | } 178 | tx := make([]net.IPNet, 0, len(nets)) 179 | for _, n := range nets { 180 | _, parsed, err := net.ParseCIDR(n) 181 | if err != nil { 182 | return tx, err 183 | } 184 | tx = append(tx, *parsed) 185 | } 186 | return tx, nil 187 | } 188 | 189 | type ConditionSubnet []net.IPNet 190 | 191 | func (cs ConditionSubnet) Match(pkt gopacket.Packet) bool { 192 | if n := pkt.NetworkLayer(); n != nil { 193 | return cs.match(net.ParseIP(n.NetworkFlow().Src().String())) || 194 | cs.match(net.ParseIP(n.NetworkFlow().Dst().String())) 195 | } 196 | return false 197 | } 198 | 199 | func (cs ConditionSubnet) match(ip net.IP) bool { 200 | if ip == nil { 201 | return false 202 | } 203 | for _, net := range cs { 204 | if net.Contains(ip) { 205 | return true 206 | } 207 | } 208 | return false 209 | } 210 | 211 | type ConditionEther map[string]bool 212 | 213 | func (cs ConditionEther) Match(pkt gopacket.Packet) bool { 214 | fmt.Println(pkt.LinkLayer().LinkFlow().Src().String()) 215 | if n := pkt.LinkLayer(); n != nil { 216 | return cs[n.LinkFlow().Src().String()] || cs[n.LinkFlow().Dst().String()] 217 | } 218 | return false 219 | } 220 | 221 | func NewConditionEther(e []string) (ConditionEther, error) { 222 | ce := make(ConditionEther) 223 | for _, mac := range e { 224 | _, err := net.ParseMAC(mac) 225 | if err != nil { 226 | return ce, fmt.Errorf("invalid MAC %s", mac) 227 | } 228 | ce[mac] = true 229 | } 230 | return ce, nil 231 | } 232 | 233 | func NewPortMatcher(p []string) (ConditionEndpoint, error) { 234 | vals := make(map[gopacket.Endpoint]bool) 235 | for _, raw := range p { 236 | bits := strings.Split(raw, "/") 237 | if len(bits) != 2 { 238 | return nil, fmt.Errorf("%s not valid port format, should be /", raw) 239 | } 240 | port, err := strconv.Atoi(bits[0]) 241 | if err != nil { 242 | return nil, err 243 | } 244 | switch bits[1] { 245 | case "tcp": 246 | vals[layers.NewTCPPortEndpoint(layers.TCPPort(port))] = true 247 | case "udp": 248 | vals[layers.NewUDPPortEndpoint(layers.UDPPort(port))] = true 249 | default: 250 | return nil, fmt.Errorf( 251 | "protocol def invalid for %s, got %s, expected tcp or udp", 252 | raw, 253 | bits[1], 254 | ) 255 | } 256 | } 257 | return vals, nil 258 | } 259 | 260 | type ConditionEndpoint map[gopacket.Endpoint]bool 261 | 262 | func (cs ConditionEndpoint) Match(pkt gopacket.Packet) bool { 263 | if t := pkt.TransportLayer(); t != nil { 264 | tf := t.TransportFlow() 265 | return cs.match(tf.Src()) || cs.match(tf.Dst()) 266 | } 267 | return false 268 | } 269 | 270 | func (cs ConditionEndpoint) match(v gopacket.Endpoint) bool { 271 | return cs[v] 272 | } 273 | 274 | type ConditionASN struct { 275 | Values map[uint]bool 276 | DB *geoip2.Reader 277 | LookupErrs int 278 | IPParseErrs int 279 | } 280 | 281 | func (ca ConditionASN) Match(pkt gopacket.Packet) bool { 282 | if n := pkt.NetworkLayer(); n != nil { 283 | return ca.match(net.ParseIP(n.NetworkFlow().Src().String())) || 284 | ca.match(net.ParseIP(n.NetworkFlow().Dst().String())) 285 | } 286 | return false 287 | } 288 | 289 | func (ca *ConditionASN) match(ip net.IP) bool { 290 | if ip == nil { 291 | ca.IPParseErrs++ 292 | return false 293 | } 294 | resp, err := ca.DB.ASN(ip) 295 | if err != nil { 296 | ca.LookupErrs++ 297 | return false 298 | } 299 | return ca.Values[resp.AutonomousSystemNumber] 300 | } 301 | 302 | func NewConditionASN(path string, asn []string) (*ConditionASN, error) { 303 | db, err := geoip2.Open(path) 304 | if err != nil { 305 | return nil, err 306 | } 307 | conditions := make(map[uint]bool) 308 | for _, val := range asn { 309 | parsed, err := strconv.Atoi(val) 310 | if err != nil { 311 | return nil, err 312 | } 313 | conditions[uint(parsed)] = true 314 | } 315 | return &ConditionASN{ 316 | DB: db, 317 | Values: conditions, 318 | }, nil 319 | } 320 | -------------------------------------------------------------------------------- /pkg/filter/config.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2022 Stamus Networks oss@stamus-networks.com 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package filter 18 | 19 | type YAMLConfig map[string]CombinedConfig 20 | 21 | type CombinedConfig struct { 22 | Conditions []FilterItem `yaml:"conditions,omitempty"` 23 | } 24 | 25 | type FilterItem struct { 26 | Kind string `yaml:"kind,omitempty"` 27 | Negate bool `yaml:"negate,omitempty"` 28 | Match []string `yaml:"match,omitempty"` 29 | } 30 | 31 | type MatcherConfig struct { 32 | CombinedConfig 33 | MaxMindASN string 34 | } 35 | -------------------------------------------------------------------------------- /pkg/filter/filter.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2022 Stamus Networks oss@stamus-networks.com 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package filter 18 | 19 | import ( 20 | "bufio" 21 | "compress/gzip" 22 | "context" 23 | "fmt" 24 | "io" 25 | "os" 26 | "path/filepath" 27 | "strings" 28 | "time" 29 | 30 | "github.com/StamusNetworks/gophercap/pkg/dedup" 31 | "github.com/google/gopacket" 32 | "github.com/google/gopacket/pcapgo" 33 | ) 34 | 35 | type ErrEarlyExit struct{} 36 | 37 | func (e ErrEarlyExit) Error() string { return "early exit" } 38 | 39 | // Config holds params needed by ReadAndFilterNetworks 40 | type Config struct { 41 | ID int 42 | // Full path for input and otput PCAP files 43 | File struct { 44 | Input string 45 | Output string 46 | } 47 | // BPF filter object, only packets matching network list will be written to OutFile 48 | Filter Matcher 49 | // Enable GRE and ERSPAN packet decapsulation 50 | Decapsulate bool 51 | // How many layers should be checked for decapsulation 52 | DecapMaxDepth int 53 | 54 | Compress bool 55 | 56 | StatFunc func(map[string]any) 57 | 58 | Ctx context.Context 59 | 60 | Dedup dedup.Dedupper 61 | } 62 | 63 | type FilterResult struct { 64 | Count int 65 | Matched int 66 | Errors int 67 | DecapErrors int 68 | Skipped int 69 | Start time.Time 70 | Took time.Duration 71 | Rate string 72 | Deduplicated int 73 | DedupRatio float64 74 | } 75 | 76 | func (fr FilterResult) Map() map[string]any { 77 | return map[string]any{ 78 | "count": fr.Count, 79 | "matched": fr.Matched, 80 | "errors": fr.Errors, 81 | "decap_errors": fr.DecapErrors, 82 | "skipped": fr.Skipped, 83 | "start": fr.Start, 84 | "took": fr.Took, 85 | "rate": fr.Rate, 86 | "dedup": fr.Deduplicated, 87 | "dedup_ratio": fr.DedupRatio, 88 | } 89 | } 90 | 91 | /* 92 | ReadAndFilter processes a PCAP file, storing packets that match filtering 93 | criteria in output file 94 | */ 95 | func ReadAndFilter(c *Config) (*FilterResult, error) { 96 | f, err := os.Open(c.File.Input) 97 | if err != nil { 98 | return nil, err 99 | } 100 | defer f.Close() 101 | 102 | input, err := pcapgo.NewReader(bufio.NewReader(f)) 103 | if err != nil { 104 | return nil, fmt.Errorf("infile open: %s", err) 105 | } 106 | input.SetSnaplen(1024 * 64) 107 | 108 | var writer io.Writer 109 | fp := c.File.Output 110 | if c.Compress { 111 | fp += ".gz" 112 | } 113 | output, err := os.Create(fp) 114 | if err != nil { 115 | return nil, fmt.Errorf("outfile create: %s", err) 116 | } 117 | defer output.Close() 118 | 119 | bufWriter := bufio.NewWriterSize(output, 1024*64) 120 | defer bufWriter.Flush() 121 | 122 | if c.Compress { 123 | gw := gzip.NewWriter(bufWriter) 124 | defer gw.Close() 125 | writer = gw 126 | } else { 127 | writer = bufWriter 128 | } 129 | 130 | w := pcapgo.NewWriter(writer) 131 | if err := w.WriteFileHeader(uint32(input.Snaplen()), input.LinkType()); err != nil { 132 | return nil, err 133 | } 134 | 135 | report := time.NewTicker(5 * time.Second) 136 | 137 | res := &FilterResult{Start: time.Now()} 138 | 139 | var ctx context.Context 140 | if c.Ctx == nil { 141 | ctx = context.Background() 142 | } else { 143 | ctx = c.Ctx 144 | } 145 | 146 | loop: 147 | for { 148 | select { 149 | case <-ctx.Done(): 150 | return res, ErrEarlyExit{} 151 | case <-report.C: 152 | res.Took = time.Since(res.Start) 153 | res.Rate = fmt.Sprintf("%.2f pps", float64(res.Count)/res.Took.Seconds()) 154 | if c.StatFunc != nil { 155 | c.StatFunc(res.Map()) 156 | } 157 | default: 158 | } 159 | res.Count++ 160 | 161 | raw, ci, err := input.ReadPacketData() 162 | if err != nil && err == io.EOF { 163 | break loop 164 | } else if err != nil { 165 | res.Errors++ 166 | continue loop 167 | } 168 | pkt := gopacket.NewPacket(raw, input.LinkType(), gopacket.Default) 169 | if c.Decapsulate { 170 | pkt, err = DecapGREandERSPAN(pkt, c.DecapMaxDepth) 171 | if err != nil { 172 | res.DecapErrors++ 173 | continue loop 174 | } 175 | } 176 | if c.Dedup != nil { 177 | if c.Dedup.Drop(pkt) { 178 | res.Deduplicated++ 179 | res.DedupRatio = (float64(res.Deduplicated) / float64(res.Count)) * 100 180 | continue loop 181 | } 182 | } 183 | ci.CaptureLength = len(pkt.Data()) 184 | ci.Length = len(pkt.Data()) 185 | pkt.Metadata().CaptureInfo = ci 186 | if c.Filter.Match(pkt) { 187 | if err := w.WritePacket(pkt.Metadata().CaptureInfo, pkt.Data()); err != nil { 188 | return res, err 189 | } 190 | res.Matched++ 191 | } else { 192 | res.Skipped++ 193 | } 194 | } 195 | return res, nil 196 | } 197 | 198 | // Task is input file to be fed to filter reader, along with BPF filter used to extract packets 199 | type Task struct { 200 | Input, Output string 201 | 202 | Filter Matcher 203 | Description string 204 | } 205 | 206 | func ExtractBaseName(filename string) string { 207 | // only the base file name without path 208 | filename = filepath.Base(filename) 209 | // trim suffix because compressed filename might leave .gz 210 | // leading to filename.pcap.gz.gz when writing to compressed handle 211 | filename = strings.TrimSuffix(filename, filepath.Ext(filename)) 212 | // check if filename still contains a extention, strip recursively until only base remains 213 | if strings.Contains(filename, ".") { 214 | return ExtractBaseName(filename) 215 | } 216 | return filename 217 | } 218 | -------------------------------------------------------------------------------- /pkg/filter/generate.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2022 Stamus Networks oss@stamus-networks.com 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package filter 18 | 19 | import ( 20 | "bufio" 21 | "encoding/json" 22 | "io" 23 | "os" 24 | "strconv" 25 | 26 | "github.com/StamusNetworks/gophercap/pkg/models" 27 | ) 28 | 29 | /* 30 | Generate produces a filter YAML configurations from suricata alerts. 31 | */ 32 | func Generate(pth string, parseErrFunc func(error) bool) (YAMLConfig, error) { 33 | f, err := os.Open(pth) 34 | if err != nil { 35 | return nil, err 36 | } 37 | defer f.Close() 38 | scanner := bufio.NewScanner(f) 39 | tx := make(YAMLConfig) 40 | flowSet := make(map[int]bool) 41 | for scanner.Scan() { 42 | var obj models.EVE 43 | if err := json.Unmarshal(scanner.Bytes(), &obj); err != nil && !parseErrFunc(err) { 44 | return nil, err 45 | } 46 | if obj.EventType == "alert" && !flowSet[obj.FlowID] { 47 | tx[strconv.Itoa(obj.FlowID)] = *filterFromEVE(obj) 48 | flowSet[obj.FlowID] = true 49 | } 50 | } 51 | if scanner.Err() != nil && scanner.Err() != io.EOF { 52 | return tx, err 53 | } 54 | return tx, nil 55 | } 56 | 57 | func filterFromEVE(e models.EVE) *CombinedConfig { 58 | c := &CombinedConfig{Conditions: make([]FilterItem, 0, 4)} 59 | c.Conditions = append(c.Conditions, FilterItem{ 60 | Kind: FilterKindSubnet.String(), 61 | Match: []string{e.SrcIP.String()}, 62 | }) 63 | c.Conditions = append(c.Conditions, FilterItem{ 64 | Kind: FilterKindSubnet.String(), 65 | Match: []string{e.DestIP.String()}, 66 | }) 67 | c.Conditions = append(c.Conditions, FilterItem{ 68 | Kind: FilterKindPort.String(), 69 | Match: []string{strconv.Itoa(e.SrcPort)}, 70 | }) 71 | c.Conditions = append(c.Conditions, FilterItem{ 72 | Kind: FilterKindPort.String(), 73 | Match: []string{strconv.Itoa(e.DestPort)}, 74 | }) 75 | return c 76 | } 77 | -------------------------------------------------------------------------------- /pkg/filter/packet.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2022 Stamus Networks oss@stamus-networks.com 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package filter 18 | 19 | import ( 20 | "errors" 21 | 22 | "github.com/google/gopacket" 23 | "github.com/google/gopacket/layers" 24 | ) 25 | 26 | func DecapGREandERSPAN(pkt gopacket.Packet, maxdepth int) (gopacket.Packet, error) { 27 | var startLayer int 28 | loop: 29 | for i, layer := range pkt.Layers() { 30 | if maxdepth > 0 && i+1 == maxdepth { 31 | // this can be a good performance optimization to only loop over N posterior layers 32 | break loop 33 | } 34 | switch layer.LayerType() { 35 | case layers.LayerTypeGRE: 36 | startLayer = i 37 | case layers.LayerTypeERSPANII: 38 | startLayer = i 39 | } 40 | } 41 | // Did not find any tunnel layers, assume no decap nor custom filtering is needed 42 | if startLayer == 0 { 43 | return pkt, nil 44 | } 45 | if len(pkt.Layers()) <= startLayer { 46 | return pkt, errors.New("layer len mismatch") 47 | } 48 | inner := gopacket.NewPacket( 49 | pkt.Layers()[startLayer].LayerPayload(), 50 | pkt.Layers()[startLayer+1].LayerType(), 51 | gopacket.Lazy, 52 | ) 53 | 54 | if inner == nil || inner.NetworkLayer() == nil { 55 | return pkt, errors.New("unable to build inner packet") 56 | } 57 | return inner, nil 58 | } 59 | -------------------------------------------------------------------------------- /pkg/models/models.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2020 Stamus Networks oss@stamus-networks.com 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package models 18 | 19 | import ( 20 | "net" 21 | "time" 22 | ) 23 | 24 | type Period struct { 25 | Beginning time.Time `json:"beginning"` 26 | End time.Time `json:"end"` 27 | } 28 | 29 | func (p Period) Duration() time.Duration { 30 | return p.End.Sub(p.Beginning) 31 | } 32 | 33 | func (p Period) Delay(target time.Time) time.Duration { 34 | return p.Beginning.Sub(target) 35 | } 36 | 37 | type Counters struct { 38 | Packets int `json:"packets"` 39 | Size int `json:"size"` 40 | MaxPacketSize int `json:"max_packet_size"` 41 | OutOfOrder int `json:"out_of_order"` 42 | } 43 | 44 | func (c Counters) PPS(interval time.Duration) float64 { 45 | return float64(c.Packets) / interval.Seconds() 46 | } 47 | 48 | type Rates struct { 49 | PPS float64 `json:"pps"` 50 | Duration time.Duration `json:"duration"` 51 | DurationHuman string `json:"duration_human"` 52 | } 53 | 54 | type EVE struct { 55 | SrcIP net.IP `json:"src_ip,omitempty"` 56 | DestIP net.IP `json:"dest_ip,omitempty"` 57 | SrcPort int `json:"src_port,omitempty"` 58 | DestPort int `json:"dest_port,omitempty"` 59 | EventType string `json:"event_type,omitempty"` 60 | FlowID int `json:"flow_id,omitempty"` 61 | } 62 | 63 | type Alert struct { 64 | Signature string `json:"signature,omitempty"` 65 | SignatureID int `json:"signature_id,omitempty"` 66 | Category string `json:"category,omitempty"` 67 | } 68 | -------------------------------------------------------------------------------- /pkg/replay/magic.go: -------------------------------------------------------------------------------- 1 | package replay 2 | 3 | import ( 4 | "bufio" 5 | "io" 6 | "os" 7 | ) 8 | 9 | /* 10 | Content is enum signifying common file formats 11 | */ 12 | type Content int 13 | 14 | const ( 15 | Octet Content = iota 16 | Plaintext 17 | Gzip 18 | Xz 19 | Bzip 20 | Utf8 21 | Utf16 22 | ) 23 | 24 | /* 25 | Detect file magic without relying on http package 26 | */ 27 | 28 | func magic(path string) (Content, error) { 29 | var ( 30 | err error 31 | mag []byte 32 | in io.ReadCloser 33 | ) 34 | if in, err = os.Open(path); err != nil { 35 | return Octet, err 36 | } 37 | defer in.Close() 38 | 39 | if mag, err = bufio.NewReader(in).Peek(8); err != nil { 40 | return Octet, err 41 | } 42 | 43 | switch { 44 | case mag[0] == 31 && mag[1] == 139: 45 | return Gzip, nil 46 | case mag[0] == 253 && mag[1] == 55 && mag[2] == 122 && mag[3] == 88 && mag[4] == 90 && mag[5] == 0 && mag[6] == 0: 47 | return Xz, nil 48 | case mag[0] == 255 && mag[1] == 254: 49 | return Utf16, nil 50 | case mag[0] == 239 && mag[1] == 187 && mag[2] == 191: 51 | return Utf8, nil 52 | default: 53 | return Octet, nil 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /pkg/replay/map.go: -------------------------------------------------------------------------------- 1 | package replay 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "errors" 7 | "fmt" 8 | "io/ioutil" 9 | "os" 10 | "path/filepath" 11 | "regexp" 12 | "strings" 13 | "sync" 14 | "time" 15 | 16 | "github.com/StamusNetworks/gophercap/pkg/models" 17 | 18 | "github.com/sirupsen/logrus" 19 | ) 20 | 21 | type MapConfig struct { 22 | Directory string 23 | Suffix string 24 | Pattern string 25 | Workers int 26 | } 27 | 28 | /* 29 | NewPcapSetFromList instantiates a new Set object from a list of Pcaps from filesystem module. 30 | Used for initial metadata scan. 31 | */ 32 | func NewPcapSet(c MapConfig) (*PcapSet, error) { 33 | var ( 34 | fileRegexp *regexp.Regexp 35 | err error 36 | ) 37 | if c.Pattern != "" { 38 | fileRegexp, err = regexp.Compile(c.Pattern) 39 | if err != nil { 40 | return nil, fmt.Errorf("Invalid file regexp: %s", err) 41 | } 42 | } 43 | ch, err := concurrentScanPeriods( 44 | context.TODO(), 45 | c.Directory, 46 | c.Workers, 47 | fileRegexp, 48 | c.Suffix, 49 | ) 50 | if err != nil { 51 | return nil, err 52 | } 53 | s := &PcapSet{Files: make([]*Pcap, 0)} 54 | for f := range ch { 55 | s.Files = append(s.Files, f) 56 | } 57 | 58 | return s, s.UpdateDelay() 59 | } 60 | 61 | /* 62 | DumpSetJSON writes a Set object to user-defined JSON file 63 | */ 64 | func DumpSetJSON(path string, set PcapSet) error { 65 | f, err := os.Create(path) 66 | if err != nil { 67 | return err 68 | } 69 | defer f.Close() 70 | data, err := json.Marshal(set) 71 | if err != nil { 72 | return err 73 | } 74 | f.Write(data) 75 | return nil 76 | } 77 | 78 | /* 79 | LoadSetJSON loads Set object from filesystem JSON dump 80 | */ 81 | func LoadSetJSON(path string) (*PcapSet, error) { 82 | data, err := ioutil.ReadFile(path) 83 | if err != nil { 84 | return nil, err 85 | } 86 | var s PcapSet 87 | if err := json.Unmarshal(data, &s); err != nil { 88 | return nil, err 89 | } 90 | return &s, nil 91 | } 92 | 93 | func calculatePeriod(files []*Pcap) models.Period { 94 | p := &models.Period{} 95 | for _, f := range files { 96 | if p.Beginning.IsZero() || f.Beginning.Before(p.Beginning) { 97 | p.Beginning = f.Beginning 98 | } 99 | if p.End.IsZero() || f.End.After(p.End) { 100 | p.End = f.End 101 | } 102 | } 103 | return *p 104 | } 105 | 106 | func concurrentScanPeriods( 107 | ctx context.Context, 108 | dir string, 109 | workers int, 110 | pattern *regexp.Regexp, 111 | suffix string, 112 | ) (<-chan *Pcap, error) { 113 | if dir == "" { 114 | return nil, errors.New("missing source dir") 115 | } 116 | if workers < 1 { 117 | return nil, errors.New("Worker count should be > 0") 118 | } 119 | 120 | files, err := FindPcapFiles(dir, suffix) 121 | if err != nil { 122 | return nil, err 123 | } 124 | 125 | var wg sync.WaitGroup 126 | rx := make(chan string) 127 | tx := make(chan *Pcap) 128 | 129 | for i := 0; i < workers; i++ { 130 | wg.Add(1) 131 | go func(id int, ctx context.Context) { 132 | defer wg.Done() 133 | lctx := logrus.WithField("worker", id) 134 | lctx.Info("Mapper started") 135 | defer lctx.Info("Mapper stopped") 136 | 137 | loop: 138 | for fp := range rx { 139 | lctx. 140 | WithField("path", fp). 141 | Debug("scanning file") 142 | start := time.Now() 143 | pf, err := scan(fp, context.TODO()) 144 | if err != nil { 145 | logrus. 146 | WithField("file", fp). 147 | Error(err) 148 | continue loop 149 | } 150 | lctx. 151 | WithField("took", time.Since(start)). 152 | WithField("path", fp). 153 | Info("file mapped") 154 | tx <- pf 155 | } 156 | }(i, context.TODO()) 157 | } 158 | 159 | wg.Add(1) 160 | go func(fpth string, fsuff string) { 161 | defer wg.Done() 162 | defer close(rx) 163 | for _, f := range files { 164 | rx <- f 165 | } 166 | }(dir, suffix) 167 | 168 | go func() { 169 | defer close(tx) 170 | wg.Wait() 171 | }() 172 | 173 | return tx, nil 174 | } 175 | 176 | func FindPcapFiles(dir, suffix string) ([]string, error) { 177 | tx := make([]string, 0) 178 | err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { 179 | if !info.IsDir() && strings.HasSuffix(path, suffix) && err == nil { 180 | tx = append(tx, path) 181 | } 182 | return nil 183 | }) 184 | return tx, err 185 | } 186 | -------------------------------------------------------------------------------- /pkg/replay/map_pcap.go: -------------------------------------------------------------------------------- 1 | package replay 2 | 3 | import ( 4 | "compress/gzip" 5 | "context" 6 | "errors" 7 | "io" 8 | "os" 9 | "time" 10 | 11 | "github.com/StamusNetworks/gophercap/pkg/models" 12 | 13 | "github.com/google/gopacket/pcapgo" 14 | ) 15 | 16 | type Pcap struct { 17 | Path string `json:"path"` 18 | 19 | Snaplen uint32 `json:"snaplen"` 20 | 21 | models.Counters 22 | models.Period 23 | models.Rates 24 | 25 | Delay time.Duration `json:"delay"` 26 | DelayHuman string `json:"delay_human"` 27 | } 28 | 29 | func scan(path string, ctx context.Context) (*Pcap, error) { 30 | r, err := Open(path) 31 | if err != nil { 32 | return nil, err 33 | } 34 | defer r.Close() 35 | p := &Pcap{ 36 | Path: path, 37 | } 38 | h, err := pcapgo.NewReader(r) 39 | if err != nil { 40 | return nil, err 41 | } 42 | // Get first packet 43 | data, ci, err := h.ReadPacketData() 44 | if err != nil { 45 | return nil, err 46 | } 47 | p.Period.Beginning = ci.Timestamp 48 | p.Counters.Size = len(data) 49 | 50 | var last time.Time 51 | 52 | loop: 53 | for { 54 | data, ci, err = h.ReadPacketData() 55 | 56 | if err != nil { 57 | if err == io.EOF { 58 | break loop 59 | } else { 60 | return nil, err 61 | } 62 | } 63 | if !ci.Timestamp.After(last) { 64 | p.Counters.OutOfOrder++ 65 | } 66 | last = ci.Timestamp 67 | size := len(data) 68 | p.Counters.Packets++ 69 | p.Counters.Size += size 70 | if size > p.MaxPacketSize { 71 | p.MaxPacketSize = size 72 | } 73 | } 74 | p.Period.End = last 75 | p.Snaplen = h.Snaplen() 76 | p.Rates.Duration = p.Period.Duration() 77 | p.Rates.DurationHuman = p.Rates.Duration.String() 78 | p.Rates.PPS = p.Counters.PPS(p.Rates.Duration) 79 | return p, nil 80 | } 81 | 82 | /* 83 | open opens a file handle while accounting for compression extracted from file magic 84 | */ 85 | func Open(path string) (io.ReadCloser, error) { 86 | if path == "" { 87 | return nil, errors.New("Missing file path") 88 | } 89 | m, err := magic(path) 90 | if err != nil { 91 | return nil, err 92 | } 93 | handle, err := os.Open(path) 94 | if err != nil { 95 | return nil, err 96 | } 97 | if m == Gzip { 98 | gzipHandle, err := gzip.NewReader(handle) 99 | if err != nil { 100 | return nil, err 101 | } 102 | return gzipHandle, nil 103 | } 104 | return handle, nil 105 | } 106 | -------------------------------------------------------------------------------- /pkg/replay/map_set.go: -------------------------------------------------------------------------------- 1 | package replay 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "regexp" 7 | "time" 8 | 9 | "github.com/StamusNetworks/gophercap/pkg/models" 10 | ) 11 | 12 | type PcapSet struct { 13 | models.Period 14 | 15 | Files []*Pcap `json:"files"` 16 | } 17 | 18 | func (s *PcapSet) UpdateDelay() error { 19 | if len(s.Files) == 0 { 20 | return errors.New("unable to calculate period, no files") 21 | } 22 | s.Period = calculatePeriod(s.Files) 23 | 24 | if s.Beginning.IsZero() || s.End.IsZero() { 25 | return fmt.Errorf("set global period not initialized") 26 | } 27 | 28 | for _, item := range s.Files { 29 | if item.Beginning.IsZero() { 30 | return fmt.Errorf("missing beginning for %s", item.Path) 31 | } 32 | item.Delay = item.Beginning.Sub(s.Beginning) 33 | item.DelayHuman = item.Delay.String() 34 | } 35 | return nil 36 | } 37 | 38 | /* 39 | Validate implements a standard interface for checking config struct validity and setting 40 | sane default values. 41 | */ 42 | func (s PcapSet) Validate() error { 43 | if s.Files == nil || len(s.Files) == 0 { 44 | return errors.New("Missing pcap files") 45 | } 46 | if s.Beginning.IsZero() || s.End.IsZero() { 47 | return errors.New("Missing set start or end") 48 | } 49 | for i, f := range s.Files { 50 | if f.Beginning.IsZero() || f.End.IsZero() { 51 | return fmt.Errorf("index %d %+v missing beginning or end ts", i, f) 52 | } 53 | if f.Beginning.Before(s.Beginning) { 54 | return fmt.Errorf("element %d start ts is before global start %s", i, s.Beginning) 55 | } 56 | if f.End.After(s.End) { 57 | return fmt.Errorf("element %d end is after global end %s", i, s.End) 58 | } 59 | } 60 | return nil 61 | } 62 | 63 | /* 64 | FilterFilesByRegex subsets pcap Set by applying regexp pattern on file names. 65 | */ 66 | func (s *PcapSet) FilterFilesByRegex(pattern *regexp.Regexp) error { 67 | if pattern == nil { 68 | return errors.New("Missing regexp pattern for file filter") 69 | } 70 | files := make([]*Pcap, 0) 71 | for _, f := range s.Files { 72 | if pattern.MatchString(f.Path) { 73 | files = append(files, f) 74 | } 75 | } 76 | if len(files) == 0 { 77 | return errors.New("Regexp filter removed all files") 78 | } 79 | s.Files = files 80 | return s.UpdateDelay() 81 | } 82 | 83 | /* 84 | FilterFilesByTime subsets pcap Set by extracting only files where Period beginning is after or end 85 | is before user-provided timestamp value. 86 | */ 87 | func (s *PcapSet) FilterFilesByTime(ts time.Time, beginning bool) error { 88 | if ts.After(s.Period.End) { 89 | return fmt.Errorf("%s is after period end %s", ts, s.Period.End) 90 | } 91 | if ts.Before(s.Period.Beginning) { 92 | return fmt.Errorf("%s is before first period timestamp %s", ts, s.Period.Beginning) 93 | } 94 | files := make([]*Pcap, 0) 95 | for _, f := range s.Files { 96 | if (beginning && f.Beginning.After(ts)) || (!beginning && f.Beginning.Before(ts)) { 97 | files = append(files, f) 98 | } 99 | } 100 | if len(files) == 0 { 101 | return fmt.Errorf("No files that contain beginning ts %s", ts) 102 | } 103 | s.Files = files 104 | return s.UpdateDelay() 105 | } 106 | -------------------------------------------------------------------------------- /pkg/replay/replay.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2020 Stamus Networks oss@stamus-networks.com 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package replay 18 | 19 | import ( 20 | "context" 21 | "errors" 22 | "io" 23 | "regexp" 24 | "sort" 25 | "time" 26 | 27 | "github.com/StamusNetworks/gophercap/pkg/models" 28 | 29 | "github.com/google/gopacket/pcap" 30 | "github.com/google/gopacket/pcapgo" 31 | "github.com/sirupsen/logrus" 32 | "golang.org/x/sync/errgroup" 33 | ) 34 | 35 | var DelayGrace = 100 * time.Microsecond 36 | 37 | /* 38 | Config is used for passing Handle configurations when creating a new replay object 39 | */ 40 | type Config struct { 41 | Set PcapSet 42 | WriteInterface string 43 | FilterRegex *regexp.Regexp 44 | OutBpf string 45 | DisableWait bool 46 | Reorder bool 47 | 48 | ScaleDuration time.Duration 49 | ScaleEnabled bool 50 | ScalePerFile bool 51 | 52 | SkipOutOfOrder bool 53 | SkipMTU int 54 | 55 | TimeFrom, TimeTo time.Time 56 | Ctx context.Context 57 | } 58 | 59 | /* 60 | Validate implements a standard interface for checking config struct validity and setting 61 | sane default values. 62 | */ 63 | func (c Config) Validate() error { 64 | if c.Ctx == nil { 65 | return errors.New("missing replay stopper context") 66 | } 67 | if err := c.Set.Validate(); err != nil { 68 | return err 69 | } 70 | if c.ScaleEnabled && c.ScaleDuration == 0 { 71 | return errors.New("Time scaling enabled but duration not defined") 72 | } 73 | return nil 74 | } 75 | 76 | /* 77 | Handle is the core object managing replay state 78 | */ 79 | type Handle struct { 80 | FileSet PcapSet 81 | speedMod float64 82 | scale bool 83 | iface string 84 | disableWait bool 85 | skipOOO bool 86 | skipMTU int 87 | outBpf string 88 | reorder bool 89 | } 90 | 91 | /* 92 | NewHandle creates a new Handle object and conducts pre-flight setup for pcap replay 93 | */ 94 | func NewHandle(c Config) (*Handle, error) { 95 | if err := c.Validate(); err != nil { 96 | return nil, err 97 | } 98 | h := &Handle{ 99 | FileSet: c.Set, 100 | iface: c.WriteInterface, 101 | outBpf: c.OutBpf, 102 | disableWait: c.DisableWait, 103 | skipOOO: c.SkipOutOfOrder, 104 | skipMTU: c.SkipMTU, 105 | reorder: c.Reorder, 106 | } 107 | if c.FilterRegex != nil { 108 | logrus.Info("Filtering pcap files") 109 | if err := h.FileSet.FilterFilesByRegex(c.FilterRegex); err != nil { 110 | return h, err 111 | } 112 | } 113 | if !c.TimeFrom.IsZero() { 114 | logrus.Infof("Filtering pcap files to adjust replay beginning %s", c.TimeFrom) 115 | if err := h.FileSet.FilterFilesByTime(c.TimeFrom, true); err != nil { 116 | return h, err 117 | } 118 | } 119 | if !c.TimeTo.IsZero() { 120 | logrus.Infof("Filtering pcap files to adjust replay end %s", c.TimeTo) 121 | if err := h.FileSet.FilterFilesByTime(c.TimeTo, false); err != nil { 122 | return h, err 123 | } 124 | } 125 | if err := h.FileSet.UpdateDelay(); err != nil { 126 | return nil, err 127 | } 128 | if c.ScaleEnabled { 129 | h.scale = true 130 | h.speedMod = h.FileSet.Duration().Seconds() / c.ScaleDuration.Seconds() 131 | for _, item := range h.FileSet.Files { 132 | item.Delay = item.Delay / time.Duration(h.speedMod) 133 | item.DelayHuman = item.Delay.String() 134 | } 135 | logrus. 136 | WithField("value", h.speedMod). 137 | Info("scaling enabled, updated speed modifier") 138 | } else { 139 | h.speedMod = 1 140 | } 141 | 142 | return h, nil 143 | } 144 | 145 | // Play starts the replay sequence once Handle object has been constructed 146 | func (h *Handle) Play() error { 147 | packets := make(chan []byte) 148 | 149 | pool, ctx := errgroup.WithContext(context.Background()) 150 | for _, p := range h.FileSet.Files { 151 | type params struct { 152 | Path string 153 | Delay time.Duration 154 | models.Period 155 | } 156 | vals := params{ 157 | Path: p.Path, 158 | Delay: p.Delay, 159 | Period: models.Period{ 160 | Beginning: p.Beginning, 161 | End: p.End, 162 | }, 163 | } 164 | pool.Go(func() error { 165 | var outOfOrder, count int 166 | 167 | fh, err := Open(vals.Path) 168 | if err != nil { 169 | return err 170 | } 171 | defer fh.Close() 172 | reader, err := pcapgo.NewReader(fh) 173 | if err != nil { 174 | return err 175 | } 176 | 177 | actualGlobalDuration := h.FileSet.Duration() 178 | actualLocalDuration := vals.Duration() 179 | scaledGlobalDuration := actualGlobalDuration / time.Duration(h.speedMod) 180 | scaledLocalDuration := actualLocalDuration / time.Duration(h.speedMod) 181 | 182 | if h.scale { 183 | logrus.WithFields(logrus.Fields{ 184 | "actual_global_duration": actualGlobalDuration, 185 | "actual_local_duration": actualLocalDuration, 186 | "scaled_global_duration": scaledGlobalDuration, 187 | "scaled_local_duration": scaledLocalDuration, 188 | "actual_percentage": (actualLocalDuration.Seconds() / actualGlobalDuration.Seconds()) * 100, 189 | "scaled_percentage": (scaledLocalDuration.Seconds() / scaledGlobalDuration.Seconds()) * 100, 190 | "file": vals.Path, 191 | }).Debug("scaling pcap") 192 | } 193 | 194 | lctx := logrus.WithFields(logrus.Fields{ 195 | "delay_duration": vals.Delay, 196 | "delay": !h.disableWait, 197 | "pcap": vals.Path, 198 | "estimate": scaledLocalDuration, 199 | "batch_reorder": h.reorder, 200 | }) 201 | lctx.Info("starting replay worker") 202 | 203 | if !h.disableWait { 204 | time.Sleep(vals.Delay) 205 | if vals.Delay > 0 { 206 | lctx.Debug("delay done, playing pcap") 207 | } 208 | } 209 | 210 | start := time.Now() 211 | defer func() { 212 | logrus.WithFields(logrus.Fields{ 213 | "path": vals.Path, 214 | "took_actual": time.Since(start), 215 | "took_estimated": scaledLocalDuration, 216 | "out_of_order": outOfOrder, 217 | "sent_pkts": count, 218 | "delay": vals.Delay, 219 | }).Debug("file replay done") 220 | }() 221 | 222 | var fn pktSendFunc 223 | 224 | if h.reorder { 225 | fn = sendBatchReorder 226 | } else { 227 | fn = sendPerPacket 228 | } 229 | 230 | res, err := fn(vals.Beginning, reader, packets, *h) 231 | if err != nil { 232 | return err 233 | } 234 | count = res.count 235 | outOfOrder = res.outOfOrder 236 | 237 | return nil 238 | }) 239 | } 240 | 241 | writer, err := pcap.OpenLive(h.iface, 65536, true, pcap.BlockForever) 242 | if err != nil { 243 | return err 244 | } 245 | defer writer.Close() 246 | if h.outBpf != "" { 247 | if err := writer.SetBPFFilter(h.outBpf); err != nil { 248 | return err 249 | } 250 | } 251 | 252 | go func() { 253 | defer close(packets) 254 | 255 | var counter, oversize uint64 256 | ticker := time.NewTicker(5 * time.Second) 257 | start := time.Now() 258 | 259 | loop: 260 | for { 261 | select { 262 | case <-ctx.Done(): 263 | break loop 264 | case <-ticker.C: 265 | logrus.WithFields(logrus.Fields{ 266 | "written": counter, 267 | "pps": int(float64(counter) / time.Since(start).Seconds()), 268 | "oversize": oversize, 269 | }).Info("packets written") 270 | case packet, ok := <-packets: 271 | if !ok { 272 | break loop 273 | } 274 | if len(packet) > h.skipMTU { 275 | oversize++ 276 | continue loop 277 | } 278 | if err := writer.WritePacketData(packet); err != nil { 279 | logrus.Error(err) 280 | break loop 281 | } 282 | counter++ 283 | } 284 | } 285 | }() 286 | 287 | return pool.Wait() 288 | } 289 | 290 | type pktSendFunc func(time.Time, *pcapgo.Reader, chan<- []byte, Handle) (*result, error) 291 | 292 | type result struct { 293 | count int 294 | outOfOrder int 295 | } 296 | 297 | func sendPerPacket( 298 | last time.Time, 299 | reader *pcapgo.Reader, 300 | packets chan<- []byte, 301 | h Handle, 302 | ) (*result, error) { 303 | res := &result{} 304 | loop: 305 | for { 306 | data, ci, err := reader.ReadPacketData() 307 | 308 | if err != nil && err == io.EOF { 309 | break loop 310 | } else if err != nil { 311 | return res, err 312 | } 313 | 314 | if ci.Timestamp.Before(last) { 315 | res.outOfOrder++ 316 | if h.skipOOO { 317 | continue loop 318 | } 319 | } 320 | delay := ci.Timestamp.Sub(last) / time.Duration(h.speedMod) 321 | if delay > DelayGrace && !ci.Timestamp.Before(last) { 322 | time.Sleep(delay) 323 | } 324 | packets <- data 325 | last = ci.Timestamp 326 | res.count++ 327 | } 328 | return res, nil 329 | } 330 | 331 | func sendBatchReorder( 332 | last time.Time, 333 | reader *pcapgo.Reader, 334 | packets chan<- []byte, 335 | h Handle, 336 | ) (*result, error) { 337 | res := &result{} 338 | b := make(pBuf, 0, 100) 339 | 340 | loop: 341 | for { 342 | data, ci, err := reader.ReadPacketData() 343 | 344 | if err != nil && err == io.EOF { 345 | break loop 346 | } else if err != nil { 347 | return res, err 348 | } 349 | 350 | b = append(b, packet{ 351 | Timestamp: ci.Timestamp, 352 | Payload: data, 353 | }) 354 | 355 | if res.count%100 == 0 { 356 | last = sendPackets(b, packets, int64(h.speedMod), h.scale, last) 357 | b = make(pBuf, 0, 100) 358 | } 359 | res.count++ 360 | } 361 | return res, nil 362 | } 363 | 364 | type pBuf []packet 365 | 366 | type packet struct { 367 | Payload []byte 368 | Timestamp time.Time 369 | } 370 | 371 | func sendPackets( 372 | b pBuf, 373 | tx chan<- []byte, 374 | mod int64, 375 | scale bool, 376 | prevLast time.Time, 377 | ) (last time.Time) { 378 | sort.Slice(b, func(i, j int) bool { 379 | return b[i].Timestamp.Before(b[j].Timestamp) 380 | }) 381 | 382 | last = prevLast 383 | for _, pkt := range b { 384 | delay := pkt.Timestamp.Sub(last) / time.Duration(mod) 385 | if delay > DelayGrace { 386 | time.Sleep(delay) 387 | } 388 | tx <- pkt.Payload 389 | last = pkt.Timestamp 390 | } 391 | return last 392 | } 393 | --------------------------------------------------------------------------------