Compare commits

...
Author SHA1 Message Date
Brandon b64aa19d61 Added more boundary tests for scanners mod.rs 2020-10-03 02:36:25 +01:00
Brandon 81ad00dc29 1.10.0 release 2020-09-29 00:29:58 +01:00
Bee 64cac6e0fa Added DNS lookup using Google DNS, refactored IP code (#246)
* Added DNS lookup using Google DNS, refactored IP code

* fixed comments & cargo fmt

* Fixed code review comments, added tests, removed unwrap() panics

* Added assertion to test
2020-09-28 21:19:55 +01:00
dependabot-preview[bot] 739e9716fc Bump structopt from 0.3.17 to 0.3.18 (#243)
Bumps [structopt](https://github.com/TeXitoi/structopt) from 0.3.17 to 0.3.18.
- [Release notes](https://github.com/TeXitoi/structopt/releases)
- [Changelog](https://github.com/TeXitoi/structopt/blob/master/CHANGELOG.md)
- [Commits](https://github.com/TeXitoi/structopt/compare/v0.3.17...v0.3.18)

Signed-off-by: dependabot-preview[bot] <[email protected]>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2020-09-24 13:38:47 +01:00
Bee 6bf70f0f9a Fixed output error, Warning! ran when file opened (#237)
Take file of addresses as input
2020-09-23 12:42:13 +01:00
Ben (CMNatic) 57dfb15852 Update Dockerfile to encourage layer caching (#241)
At the moment the Dockerfile brings the entire current directory in as a context for the building container. We can encourage some caching here by only bringing forward the essentials:
`cargo.tml`, `cargo.lock` and the `src`

+ Added a maintainer label
2020-09-23 12:40:51 +01:00
allcontributors[bot]andBee 282065752c docs: add dmitris as a contributor (#232)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
Co-authored-by: Bee <[email protected]>
2020-09-22 12:55:29 +01:00
Brandon 982ae0d926 README updates 2020-09-21 23:19:29 +01:00
Brandon 53f8a15e16 Merge branch 'master' of github.com:RustScan/RustScan into master 2020-09-21 23:19:19 +01:00
Bee fc214a78b4 Increase code coverage (#236)
* Updated code coverage
2020-09-21 17:36:40 +01:00
Brandon 0ae289c25f Merge branch 'master' of github.com:RustScan/RustScan into master 2020-09-21 14:17:52 +01:00
bergabman 9326fc4a0f Refactored test, intorduced default() in test context for structs for easier test writing, Scanner struct quiet changed to greppable. (#235) 2020-09-21 00:00:11 +01:00
Brandon c05ebaf857 Merge branch 'master' of github.com:RustScan/RustScan into master 2020-09-20 15:58:39 +01:00
Ben (CMNatic) 6f8df7e77e Merge pull request #234 from CMNatic/master
Fix version tag (v1.9.0) typo in docker usage
2020-09-20 13:11:35 +01:00
Ben (CMNatic) 488853f40e Merge branch 'master' into master 2020-09-20 13:09:52 +01:00
Ben (CMNatic) 57c1e33650 typo in docker instructions 2020-09-20 13:02:17 +01:00
Ben (CMNatic) 699b578ade Update README for v1.9.0 release (#233)
DockerHub tag for v1.9.0 release has been pushed too
2020-09-20 13:00:30 +01:00
Ben (CMNatic) ebe5a326a8 Update README for v1.9.0 release
DockerHub tag for v1.9.0 release has been pushed too
2020-09-20 12:55:47 +01:00
Brandon abb7a3872c releasing 2020-09-20 12:27:51 +01:00
Dmitry SavintsevandBee f74cb456b1 socket_iterator: use itertools.iproducts for ip x ports set (#231)
Replace the current manual iterator-like implementation
with the call to the itertools.iproduct macro
to generate the cartesian product of the IPs and ports.

stdlib reference:
https://docs.rs/itertools/0.9.0/itertools/macro.iproduct.html

Co-authored-by: Bee <[email protected]>
2020-09-20 12:15:46 +01:00
Brandon 492d2fb3b3 fixed accessible issues 2020-09-20 01:25:41 +01:00
bergabmanandBee af53591ccb Added top ports, fixed accessibility. (#230)
* Refactored scanner struct for accessibility, fixed macros

Co-authored-by: Bee <[email protected]>
2020-09-19 18:24:08 +01:00
Bee 6405b43f5a Merge pull request #229 from dmitris/patch-1
fix typo
2020-09-19 00:54:24 +01:00
Dmitry Savintsev 9a71253697 fix typo 2020-09-18 22:13:33 +02:00
Bee 4d6d57fe2c Merge pull request #226 from RustScan/dependabot/cargo/async-std-1.6.4
Bump async-std from 1.6.3 to 1.6.4
2020-09-18 15:38:36 +01:00
Bee a040ab5521 Merge branch 'master' into dependabot/cargo/async-std-1.6.4 2020-09-18 15:38:29 +01:00
Bee a546aa2ac0 Merge pull request #228 from RustScan/all-contributors/add-bergabman
docs: add bergabman as a contributor
2020-09-18 15:38:04 +01:00
Bee 868e61bb2e Merge branch 'master' into all-contributors/add-bergabman 2020-09-18 15:37:57 +01:00
allcontributors[bot] c4f8ceb336 docs: update .all-contributorsrc [skip ci] 2020-09-18 14:37:46 +00:00
allcontributors[bot] 9d80fb4fa7 docs: update README.md [skip ci] 2020-09-18 14:37:45 +00:00
Bee e659d51976 Merge pull request #225 from bergabman/benchmark
Runtime measurement implementation, better debugging, and better error handling for unreachable hosts.
2020-09-18 15:37:44 +01:00
bergabman 64f4aecacd Runtime measurement implementation, better debugging, and better error handling for unreachable hosts. 2020-09-18 16:14:26 +02:00
dependabot-preview[bot] afe2a9452f Bump async-std from 1.6.3 to 1.6.4
Bumps [async-std](https://github.com/async-rs/async-std) from 1.6.3 to 1.6.4.
- [Release notes](https://github.com/async-rs/async-std/releases)
- [Changelog](https://github.com/async-rs/async-std/blob/master/CHANGELOG.md)
- [Commits](https://github.com/async-rs/async-std/compare/v1.6.3...v1.6.4)

Signed-off-by: dependabot-preview[bot] <[email protected]>
2020-09-18 06:51:32 +00:00
Bernardo Araujo 4a6e74d507 Merge pull request #224 from CMNatic/cmn-v1.80-docker-instructions
Updated README to reflect v1.8.0 DockerHub tag
2020-09-15 22:12:28 -04:00
Ben (CMNatic) eb905f7e7a Update README.md
Small typos after initial commit to #224
2020-09-16 02:41:11 +01:00
Ben (CMNatic) 561e7fb2f0 Updated README to reflect v1.8.0 DockerHub tag
v1.8.0 is the most recent published version of RustScan, the alpine tag quickly became depreciated - meaning people had to rely on `latest` to get any features made within the last month.

Version tags will build as per major realease i.e. `v1.9.0`
2020-09-16 01:55:12 +01:00
Bee e5d22a0421 Merge pull request #221 from RustScan/ba-fix-no-nmap
Fix behaviour of --no-nmap flag
2020-09-15 00:51:52 +01:00
Bernardo Chaves 33c9388586 Fix behaviour of --no-nmap flag
At some point we forgot to check for this flag before actually running
our post scanning tasks. I've also adjusted some of our messages for
reporting.
2020-09-14 19:30:30 -04:00
Bee 4dfe76737b Merge pull request #216 from RustScan/dependabot/cargo/serde_derive-1.0.116
Bump serde_derive from 1.0.115 to 1.0.116
2020-09-14 14:01:52 +01:00
Bee cc0b344232 Merge branch 'master' into dependabot/cargo/serde_derive-1.0.116 2020-09-14 13:58:43 +01:00
Bee abaf100da9 Merge pull request #217 from RustScan/bee-fix-debug-output
fixed debug log
2020-09-14 13:58:29 +01:00
Bee 43602793e0 Merge branch 'master' into bee-fix-debug-output 2020-09-14 12:23:28 +01:00
Brandon 7b827991c1 cargo fmt 2020-09-14 12:23:09 +01:00
Brandon f4555ecb98 fixed debug log 2020-09-14 12:20:48 +01:00
dependabot-preview[bot] 2fb8a399a7 Bump serde_derive from 1.0.115 to 1.0.116
Bumps [serde_derive](https://github.com/serde-rs/serde) from 1.0.115 to 1.0.116.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.115...v1.0.116)

Signed-off-by: dependabot-preview[bot] <[email protected]>
2020-09-14 11:05:24 +00:00
Bee e612ddc4e6 Merge pull request #215 from RustScan/dependabot/cargo/serde-1.0.116
Bump serde from 1.0.115 to 1.0.116
2020-09-14 12:04:08 +01:00
dependabot-preview[bot] 8bf75846d3 Bump serde from 1.0.115 to 1.0.116
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.115 to 1.0.116.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.115...v1.0.116)

Signed-off-by: dependabot-preview[bot] <[email protected]>
2020-09-14 06:57:46 +00:00
Bee bf1cb3a5d0 Merge pull request #208 from RustScan/ba-socket-iterator
Introduce SocketIterator
2020-09-13 00:22:49 +01:00
Bernardo Chaves 01975d7238 Introduce SocketIterator
The goal of this iterator is to generate sockets based on combinations
of IPs and ports in a memory-bounded way, we only consume the next item
of this iterator when a socket has been processed by our scanner.

Before this change we were generating every combination of IP and port
and storing it in a VecDeque, and while this is fine for a small subset
of IPs and ports it can quickly get out of hand with multiple IPs and
a big port range.
2020-09-12 12:24:30 -04:00
Bee 8c4cc77e6b Merge pull request #206 from bergabman/master
Bugfixes
2020-09-11 23:35:23 +01:00
bergabman b0c1ab3177 Logic at adding targets to the FuturesUnordered rolled back to the initial.
In case of batchsize higher than all sockets to scan, we could end up in an infinite loop. Fixed with breaking out of the loop if that's the case.
2020-09-11 19:21:21 +02:00
Bee 6812cc3051 Merge pull request #205 from Martin005/patch-1
Fix incorrect timeout option in README
2020-09-11 13:00:50 +01:00
Martin Chrástek 2800adec34 Fix incorrect timeout option 2020-09-11 13:22:11 +02:00
Bee cf1aa67a21 Merge pull request #204 from RustScan/all-contributors/add-bergabman
docs: add bergabman as a contributor
2020-09-11 01:16:28 +01:00
Bee c9708671e8 Merge branch 'master' into all-contributors/add-bergabman 2020-09-11 01:13:27 +01:00
Bee 461f9aaa6d Merge pull request #203 from bergabman/master
Small improvement in the scanning engine.
2020-09-11 01:12:51 +01:00
allcontributors[bot] 01a74b72df docs: update .all-contributorsrc [skip ci] 2020-09-11 00:01:53 +00:00
allcontributors[bot] d301cf3b20 docs: update README.md [skip ci] 2020-09-11 00:01:52 +00:00
Bee 5e8d45bf01 Merge branch 'master' into master 2020-09-11 01:00:47 +01:00
Brandon bc5b2eea7e added release drafter 2020-09-11 00:59:55 +01:00
bergabman c8a8915682 Remove unnecessary comment.
Fix mistake at adding futures to the initial stream.
2020-09-11 01:48:35 +02:00
bergabman d786e24186 Fix format. 2020-09-11 00:48:23 +02:00
Bee 5b536621e6 Merge branch 'master' into master 2020-09-10 23:45:46 +01:00
bergabman c05f40ae70 Small improvement at an if. 2020-09-10 23:29:07 +02:00
bergabman 24b9f8d8d3 Improved scanner engine to work more efficient and consistent with scanning. 2020-09-10 23:27:28 +02:00
Bee bda392c9a7 Merge pull request #200 from RustScan/ba-add-cidr-support
Add CIDR support
2020-09-10 00:46:19 +01:00
Bernardo Chaves 3836480486 Add CIDR support
Add CIDR support for ips_or_hosts argument. This will allow our users to
specify multiple IPs within a network at once which is pretty
convenient.
2020-09-09 19:21:43 -04:00
Bee 2291ba73d2 Update FUNDING.yml 2020-09-07 23:00:14 +01:00
Bee e0af8a306a Merge pull request #198 from RustScan/all-contributors/add-buermarc
docs: add buermarc as a contributor
2020-09-07 22:22:52 +01:00
Bee cb0f4f7a92 Merge branch 'master' into all-contributors/add-buermarc 2020-09-07 22:17:59 +01:00
Bee 402bea4b06 Merge pull request #195 from buermarc/master
Check '.config/rustscan/config.toml' for config
2020-09-07 22:15:47 +01:00
allcontributors[bot] f44dda0360 docs: update .all-contributorsrc [skip ci] 2020-09-07 21:15:35 +00:00
allcontributors[bot] 965a173032 docs: update README.md [skip ci] 2020-09-07 21:15:34 +00:00
Bee d95cae6677 Merge branch 'master' into master 2020-09-07 21:41:27 +01:00
Bee 2f92d5583a Merge pull request #197 from RustScan/ba-no-nmap-option
Introduce the -no-nmap option
2020-09-07 21:41:09 +01:00
Bee 8d8da79640 Merge branch 'master' into ba-no-nmap-option 2020-09-07 21:29:23 +01:00
Bee e5b4a2f443 Merge branch 'master' into master 2020-09-07 21:23:18 +01:00
Bernardo Araujo a0b877729e Merge pull request #194 from usrGabriel/patch-1
Update README.md
2020-09-07 11:20:25 -04:00
Bernardo Chaves 743fa1cad6 Introduce the -no-nmap option
As the name implies this will allow RustScan to to run the scan without
starting an nmap scan with ports that are found.
2020-09-06 22:22:17 -04:00
mulc a0561d4728 Check '.config/rustscan/config.toml' for config
When reading the config file '$CONFIG_DIR/.config/rustscan/config.toml'
should also be checked. If both '~/.rustscan.toml' and
'$CONFIG_DIR/.config/rustscan/config.toml' exist, then later will be
used.
2020-09-05 18:32:08 +02:00
Gabriel b2a1bd2e7a Update README.md
Typo fix in the Debian / Kali install section.
2020-09-05 12:23:18 -04:00
Brandon 87de96c3c4 Merge pull request #185 from RustScan/ba-add-config-file
Add configuration file
2020-08-30 14:00:07 +01:00
Bernardo Chaves 8e21f3bf8c Add configuration file
This configuration file will be read from the home directory of the
user. Options set within this file will have priority over arguments
from the command line unless the `--no-config` option is passed to the
program.
2020-08-29 18:01:44 -04:00
Brandon 4019d1ff3a Merge pull request #182 from RustScan/all-contributors/add-tim77
docs: add tim77 as a contributor
2020-08-29 12:15:07 +01:00
Brandon c004bd0527 Merge pull request #181 from tim77/tim77-patch-1
Add Fedora/CentOS installation instructions
2020-08-29 11:53:44 +01:00
allcontributors[bot] cdc5bbd924 docs: update .all-contributorsrc [skip ci] 2020-08-29 10:53:35 +00:00
allcontributors[bot] f41213047a docs: update README.md [skip ci] 2020-08-29 10:53:34 +00:00
Artem Polishchuk 2315ef2417 Add Fedora/CentOS installation instructions 2020-08-28 23:33:42 +03:00
Brandon cb87d5b9ce Update README.md 2020-08-28 16:14:10 +01:00
Brandon 92800678cd Merge branch 'master' of github.com:brandonskerritt/RustScan into master 2020-08-28 15:59:05 +01:00
Brandon 8e76a71a4c updated logo 2020-08-28 15:58:42 +01:00
Brandon 07fdea8471 Merge pull request #176 from niklasmohrin/improve-readme
README.md tweaks
2020-08-28 13:50:38 +01:00
Niklas Mohrin 8670bcc35f Move "rustscan -h" and output together 2020-08-28 14:43:50 +02:00
Niklas Mohrin fbba9d16ca Mark code blocks as bash commands in README 2020-08-28 14:43:50 +02:00
Niklas Mohrin 309d1ad660 Remove argument placeholders in docker alias 2020-08-28 14:43:47 +02:00
Brandon ed48161bea added travis token 2020-08-28 11:22:23 +01:00
Brandon f0d1aa2b9a Merge pull request #180 from RustScan/all-contributors/add-SuperSandro2000
docs: add SuperSandro2000 as a contributor
2020-08-28 11:12:35 +01:00
Brandon ac93feddb5 Merge pull request #178 from SuperSandro2000/optimize-docker
Optimize Dockerfile
2020-08-28 11:12:17 +01:00
allcontributors[bot] 1280fa1b47 docs: update .all-contributorsrc [skip ci] 2020-08-28 10:12:08 +00:00
Brandon 6e731aaf93 Merge branch 'master' into optimize-docker 2020-08-28 11:12:08 +01:00
allcontributors[bot] 9230165f8f docs: update README.md [skip ci] 2020-08-28 10:12:07 +00:00
Brandon 818c80041b Merge pull request #177 from RustScan/all-contributors/add-niklasmohrin
docs: add niklasmohrin as a contributor
2020-08-28 11:11:38 +01:00
allcontributors[bot] bce955212a docs: update .all-contributorsrc [skip ci] 2020-08-28 10:11:34 +00:00
allcontributors[bot] 41e0e8905f docs: update README.md [skip ci] 2020-08-28 10:11:33 +00:00
Sandro Jäckel 85f1699724 Prevent cache bustages 2020-08-28 01:31:54 +02:00
Sandro Jäckel bafd0141df Pin Alpine 3.12 to prevent breakages in the future 2020-08-28 01:31:26 +02:00
Sandro Jäckel aba0f3c38c Cleanup Dockerfile 2020-08-28 01:31:08 +02:00
allcontributors[bot] 9e161d4f79 docs: update .all-contributorsrc [skip ci] 2020-08-27 23:12:10 +00:00
allcontributors[bot] 731b4079cf docs: update README.md [skip ci] 2020-08-27 23:12:09 +00:00
Brandon b4edc6cca6 1.8.0 publish 2020-08-28 00:03:02 +01:00
Brandon 4a7cbd701b Merge pull request #175 from RustScan/all-contributors/add-caass
docs: add caass as a contributor
2020-08-27 20:39:46 +01:00
allcontributors[bot] f34ee8f5ef docs: update .all-contributorsrc [skip ci] 2020-08-27 19:36:22 +00:00
allcontributors[bot] 89c763789f docs: update README.md [skip ci] 2020-08-27 19:36:21 +00:00
Brandon 5c48f1173a Merge pull request #140 from remigourdon/docs-pages
Add Travis configuration to publish doc to GitHub pages
2020-08-27 14:02:46 +01:00
Brandon 8d8ca1d4a0 Merge branch 'master' into docs-pages 2020-08-27 14:01:29 +01:00
Brandon 8d8acd61e8 Merge pull request #173 from RustScan/bee-add-submodule
added submodule
2020-08-27 13:33:16 +01:00
Brandon 0ab3e53034 Merge branch 'master' into bee-add-submodule 2020-08-27 13:05:19 +01:00
Brandon 56493859cb added submodule 2020-08-27 12:36:56 +01:00
Brandon 2ef723ed96 Merge branch 'master' into docs-pages 2020-08-27 12:30:33 +01:00
Brandon e9288302ba Merge pull request #172 from RustScan/all-contributors/add-caass
docs: add caass as a contributor
2020-08-27 11:39:35 +01:00
remigourdon 8179511527 Add Travis configuration to publish doc to GitHub pages 2020-08-26 23:22:13 -04:00
allcontributors[bot] fbab4a4020 docs: update .all-contributorsrc [skip ci] 2020-08-26 23:22:13 -04:00
allcontributors[bot] b425d15a98 docs: update README.md [skip ci] 2020-08-26 23:22:13 -04:00
allcontributors[bot] fddda34465 docs: update .all-contributorsrc [skip ci] 2020-08-26 23:39:11 +00:00
allcontributors[bot] 125df4a2ed docs: update README.md [skip ci] 2020-08-26 23:39:10 +00:00
Brandon e670d11223 Merge pull request #170 from RustScan/all-contributors/add-SuperSandro2000
docs: add SuperSandro2000 as a contributor
2020-08-27 00:36:42 +01:00
Brandon 8453320586 Merge pull request #169 from SuperSandro2000/fix-timeout-arg
Convert -T to -t
2020-08-26 17:27:15 +01:00
allcontributors[bot] 99e9c834a9 docs: update .all-contributorsrc [skip ci] 2020-08-26 15:54:45 +00:00
allcontributors[bot] dfbce6a636 docs: update README.md [skip ci] 2020-08-26 15:54:44 +00:00
Sandro Jäckel 916be1e4a2 Convert -T to -t 2020-08-26 17:38:58 +02:00
Brandon 90b4328fb6 Merge pull request #167 from RustScan/all-contributors/add-Phenomite
docs: add Phenomite as a contributor
2020-08-26 16:08:25 +01:00
Brandon 76035d3379 Merge branch 'master' into all-contributors/add-Phenomite 2020-08-26 15:50:08 +01:00
Brandon 4de31ecede Merge pull request #163 from Phenomite/patch-1
2000 milliseconds not seconds
2020-08-26 15:47:50 +01:00
allcontributors[bot] ce9befaa1a docs: update .all-contributorsrc [skip ci] 2020-08-26 14:47:28 +00:00
Brandon 5f6457ed7e Merge branch 'master' into patch-1 2020-08-26 15:47:27 +01:00
allcontributors[bot] 12d3c91983 docs: update README.md [skip ci] 2020-08-26 14:47:27 +00:00
Brandon e0fd7a39dc Merge pull request #164 from RustScan/dependabot/cargo/structopt-0.3.17
Bump structopt from 0.3.16 to 0.3.17
2020-08-26 14:59:31 +01:00
Brandon ff0787e332 Merge branch 'master' into dependabot/cargo/structopt-0.3.17 2020-08-26 14:02:08 +01:00
Brandon 6ce6c0ce9e Merge pull request #166 from RustScan/all-contributors/add-Ferryistaken
docs: add Ferryistaken as a contributor
2020-08-26 14:01:48 +01:00
Brandon edf989ad5d Merge branch 'master' into all-contributors/add-Ferryistaken 2020-08-26 13:35:08 +01:00
Brandon 3fede4c6db Merge pull request #165 from Ferryistaken/fix-message
Fixed small typo in a warning message
2020-08-26 13:34:46 +01:00
allcontributors[bot] 75b310f227 docs: update .all-contributorsrc [skip ci] 2020-08-26 12:34:40 +00:00
allcontributors[bot] 72c6ef1f1d docs: update README.md [skip ci] 2020-08-26 12:34:39 +00:00
Ferry 83b23da32b Fixed small typo in a warning message 2020-08-26 11:00:54 +02:00
dependabot-preview[bot] 3886a07775 Bump structopt from 0.3.16 to 0.3.17
Bumps [structopt](https://github.com/TeXitoi/structopt) from 0.3.16 to 0.3.17.
- [Release notes](https://github.com/TeXitoi/structopt/releases)
- [Changelog](https://github.com/TeXitoi/structopt/blob/master/CHANGELOG.md)
- [Commits](https://github.com/TeXitoi/structopt/compare/v0.3.16...v0.3.17)

Signed-off-by: dependabot-preview[bot] <[email protected]>
2020-08-26 06:52:53 +00:00
Phenomite f5064d3d5c 2000 milliseconds not seconds 2020-08-25 18:42:59 -04:00
Brandon 22cbfc5826 Merge pull request #159 from RustScan/bee-add-nmap-ports
updated config file to feature nmap top 1k ports
2020-08-24 16:49:13 +01:00
Brandon a9d729300c Merge branch 'master' into bee-add-nmap-ports 2020-08-24 13:49:10 +01:00
Brandon 4f5dd20e85 Merge pull request #162 from RustScan/ba-reduce-binary-size
Reduce binary size from 2.4MB to 1.9MB
2020-08-24 12:48:45 +01:00
Bernardo Chaves 499ff66f36 Reduce binary size from 2.4MB to 1.9MB
By default, Cargo instructs compilation units to be compiled and optimized
in isolation. LTO instructs the linker to optimize at the link stage.
This can, for example, remove dead code and often times reduces binary size.

By default, when Rust code encounters a situation when it must call panic!(),
it unwinds the stack and produces a helpful backtrace. The unwinding code,
however, does require extra binary size. rustc can be instructed to abort
immediately rather than unwind, which removes the need for this extra unwinding code.

For more information see: https://github.com/johnthagen/min-sized-rust
2020-08-23 18:10:53 -04:00
Brandon 61b87243d9 Merge pull request #161 from RustScan/ba-refactor-port-strategy
Allow randomized order for manual ports
2020-08-22 22:27:37 +01:00
Bernardo Chaves e069991c8d Allow randomized order for manual ports
Before this change we would always scan manually specified ports in
sequential way, this is not the case anymore. This is an important
change since we are planning to introduce a config file with the top 1K
ports and we would like to scan those in a randomized way.
2020-08-21 13:09:41 -04:00
Brandon 85c1cbf445 Merge pull request #160 from RustScan/bee-remove-A
removed -A from nmap
2020-08-20 22:58:39 +01:00
Brandon e609b3617c updated config file to feature nmap top 1k ports 2020-08-20 00:05:45 +01:00
24 changed files with 3125 additions and 561 deletions

No files matched your search

+87
View File
@@ -115,6 +115,93 @@
"doc",
"design"
]
},
{
"login": "Ferryistaken",
"name": "Alessandro Ferrari",
"avatar_url": "https://avatars3.githubusercontent.com/u/47927670?v=4",
"profile": "https://github.com/Ferryistaken",
"contributions": [
"content"
]
},
{
"login": "Phenomite",
"name": "Phenomite",
"avatar_url": "https://avatars2.githubusercontent.com/u/8285537?v=4",
"profile": "https://github.com/Phenomite",
"contributions": [
"content"
]
},
{
"login": "SuperSandro2000",
"name": "Sandro",
"avatar_url": "https://avatars2.githubusercontent.com/u/7258858?v=4",
"profile": "https://supersandro.de/",
"contributions": [
"content",
"bug",
"code"
]
},
{
"login": "caass",
"name": "Cass",
"avatar_url": "https://avatars2.githubusercontent.com/u/25358963?v=4",
"profile": "https://swag.lgbt",
"contributions": [
"platform",
"code",
"bug"
]
},
{
"login": "niklasmohrin",
"name": "Niklas Mohrin",
"avatar_url": "https://avatars0.githubusercontent.com/u/47574893?v=4",
"profile": "https://github.com/niklasmohrin",
"contributions": [
"doc"
]
},
{
"login": "tim77",
"name": "Artem Polishchuk",
"avatar_url": "https://avatars0.githubusercontent.com/u/5614476?v=4",
"profile": "https://liberapay.com/Artem4/",
"contributions": [
"platform"
]
},
{
"login": "buermarc",
"name": "buermarc",
"avatar_url": "https://avatars2.githubusercontent.com/u/44375277?v=4",
"profile": "https://github.com/buermarc",
"contributions": [
"code"
]
},
{
"login": "bergabman",
"name": "bergabman",
"avatar_url": "https://avatars1.githubusercontent.com/u/44554109?v=4",
"profile": "https://github.com/bergabman",
"contributions": [
"code",
"bug",
"design"
]
},
{
"login": "dmitris",
"name": "Dmitry Savintsev",
"avatar_url": "https://avatars0.githubusercontent.com/u/31205?v=4",
"profile": "https://github.com/dmitris",
"contributions": [
"code"
]
}
],
"contributorsPerLine": 7,
+2
View File
@@ -0,0 +1,2 @@
.git
Dockerfile
+1 -1
View File
@@ -1,4 +1,4 @@
github: brandonskerritt
github: bee-san
patreon: brandonskerritt
ko_fi: hacker
custom: ["https://monzo.me/bee", "https://paypal.me/brandonskerritt"]
+4
View File
@@ -0,0 +1,4 @@
template: |
## What’s Changed
$CHANGES
+77
View File
@@ -43,3 +43,80 @@ pkg/
# End of https://www.toptal.com/developers/gitignore/api/rust,archlinuxpackages
*.deb
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
.idea/*
.idea
.idea*
+3
View File
@@ -0,0 +1,3 @@
[submodule "src/rustscan_scripting_engine"]
path = src/rustscan_scripting_engine
url = https://github.com/RustScan/rustscan_scripting_engine
+23 -42
View File
@@ -1,56 +1,37 @@
language: rust
os:
- linux
- osx
# - windows
- linux
- osx
arch:
- amd64
- arm64
- amd64
- arm64
services:
- docker
- docker
before_install:
- rustup component add rustfmt
# cargo test
rust:
- stable
- beta
- stable
- beta
jobs:
fast_finish: true
# Cargo fmt
script:
- cargo build
- cargo test
- cargo fmt -- --check
# automatic deployment to cargo on release
# deploy:
# provider: releases
# api_key: "GITHUB OAUTH TOKEN"
# file: "FILE TO UPLOAD"
# skip_cleanup: true
# on:
# tags: true
# after_success:
# - wget https://raw.githubusercontent.com/DiscordHooks/travis-ci-discord-webhook/master/send.sh
# - chmod +x send.sh
# - ./send.sh success $WEBHOOK_URL
# only deploy on master branch
# on:
# branch: master
# provider: cargo
# token: $crates
after_failure:
- wget https://raw.githubusercontent.com/DiscordHooks/travis-ci-discord-webhook/master/send.sh
- chmod +x send.sh
- ./send.sh failure $WEBHOOK_URL
- wget https://raw.githubusercontent.com/DiscordHooks/travis-ci-discord-webhook/master/send.sh
- chmod +x send.sh
- "./send.sh failure $WEBHOOK_URL"
after_success: |
if [ -n "${GITHUB_TOKEN}" ]; then
[ "${TRAVIS_BRANCH} " = master ] &&
[ "${TRAVIS_PULL_REQUEST}" = false ] &&
cargo doc &&
echo "<meta http-equiv=refresh content=0;url=rustscan/index.html>" > target/doc/index.html &&
sudo pip install ghp-import &&
ghp-import -n target/doc &&
git push -fq https://${GITHUB_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages
fi
env:
global:
secure: Gf24LG7Hr3Q0drWyPrvISTL35Z57DxdS/wIOo7v+ZdauzY3Qjvv3Lh4TY//C4sdN0g1CLj4yjg7LQOqF4XRdh2Qah7JZPv/i2B5uz9nwjTsoRzmmMWML9VtfT1u53nSFqsNeXbvpmoNG9rfMXcoiyd+Lv+EgniHphDEBlXvS9n9KMcpOi1F2x7bsH0EK37wQYKMTpCCd5TPUPdZou7BJNiZS3ikRLpTRFF7uIN4gYtRH9kU5uBSphWgnJ6eBm2ItzZcUPOgrjAoF4RkmZAzGG4idDh1Qkf3No3nZwT3U5NSk8h7owtJ4oADlRgYqYKCB4YcC9cAKCJgDsyMlKKMkEyagvw1seFnBLCY3ljsW4EklpVEZ0rVqZOx4pTkIaxIxytLTC9pHmdDSnhdhFknOcVAQQWjg+nAZfD07QUeAqUdr0i/vxQoZitvbNY0znzEarycE1waKvwlkiB4gt385U1CBfYldydnOnRKkdtLNrCLClu13HU0djmSXMhojQJhTuNxTHtZAf5fKcWIWwkVbNZ5MNKYjQh4rKufqW3o1iHphB8dfAGsDEPv0RQMtVbu6H4+clCouLkFlxHOIrrOJ5SXQ8cIATPhnJR7y4cSDdRaN0DRLRjeLAIKlbOGBtNuFC+BftocaTY5qN42aKAMqQcT30ycfiLuRVJNiQJ5pkto=
+16 -16
View File
@@ -14,22 +14,22 @@ appearance, race, religion, or sexual identity and orientation.
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
- The use of sexualized language or imagery and unwelcome sexual attention or
advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic
address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
@@ -55,7 +55,7 @@ further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at brandon@skerritt.blog. All
reported by contacting the project team at our discord via a private message to any of the owners. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
@@ -67,10 +67,10 @@ members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
This Code of Conduct is adapted from the Contributor Covenant homepage, version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
homepage: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
Generated
+840 -56
View File
File diff suppressed because it is too large. Load diff
+18 -5
View File
@@ -1,6 +1,6 @@
[package]
name = "rustscan"
version = "1.7.1"
version = "1.10.0"
authors = ["Bee <[email protected]>"]
edition = "2018"
description = "Faster Nmap Scanning with Rust"
@@ -16,12 +16,10 @@ exclude = [
"rustscan-debbuilder/*",
]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
colored = "2.0.0"
structopt = "0.3.16"
async-std = "1.6.3"
structopt = "0.3.18"
async-std = "1.6.4"
futures = "0.3"
rlimit = "0.4.0"
shell-words = "1.0.0"
@@ -32,7 +30,22 @@ gcd = "2.0.1"
rand = "0.7.3"
colorful = "0.2.1"
ansi_term = "0.12.1"
toml = "0.5.6"
serde = "1.0.116"
serde_derive = "1.0.116"
cidr-utils = "0.5.0"
itertools = "0.9.0"
trust-dns-resolver = { version = "0.19.5"}
criterion = "0.3"
[package.metadata.deb]
depends = "$auto, nmap"
section = "rust"
[profile.release]
lto = true
panic = 'abort'
[[bench]]
name = "main"
harness = false
+11 -14
View File
@@ -1,22 +1,19 @@
FROM rust:alpine as builder
RUN apk update && \
apk add build-base && \
rm -rf /var/cache/apk/*
LABEL maintainer="CMNatic <https://github.com/CMNatic">
RUN apk add --no-cache build-base
# Encourage some layer caching here rather then copying entire directory that includes docs to builder container ~CMN
WORKDIR /usr/src/rustscan
COPY . .
COPY Cargo.toml Cargo.lock ./
COPY src src
RUN cargo install --path .
FROM alpine
FROM alpine:3.12
LABEL author="Hydragyrum <https://github.com/Hydragyrum>"
RUN ulimit -n 100000 && \
apk update && \
apk add \
nmap nmap-scripts wget \
&& \
rm -rf /var/cache/apk/*
COPY --from=builder /usr/local/cargo/bin/rustscan /usr/local/bin/rustscan
RUN addgroup -S rustscan && \
adduser -S -G rustscan rustscan
adduser -S -G rustscan rustscan && \
ulimit -n 100000 && \
apk add --no-cache nmap nmap-scripts wget
COPY --from=builder /usr/local/cargo/bin/rustscan /usr/local/bin/rustscan
USER rustscan
ENTRYPOINT ["/usr/local/bin/rustscan"]
ENTRYPOINT [ "/usr/local/bin/rustscan" ]
+140 -84
View File
@@ -5,7 +5,7 @@
<a href="https://github.com/RustScan/RustScan#-usage">Usage Guide</a>
⬅️
<br>
<img src="https://github.com/RustScan/RustScan/blob/master/pictures/rustscan.png?raw=true">
<img src="pictures/rustscan.png" height=400px width=400px>
</p>
<p align="center">
<u><b> Turns a 17 minutes Nmap scan into 19 seconds. </b></u><br> Find all open ports <b>fast</b> with RustScan, automatically pipe them into Nmap.
@@ -13,7 +13,7 @@
<p align="center">
<img alt="AUR version" src="https://img.shields.io/aur/version/rustscan">
<img src="https://img.shields.io/badge/Built%20with-Rust-Purple">
<img alt="GitHub commit activity" src="https://img.shields.io/github/commit-activity/w/brandonskerritt/rustscan">
<img alt="GitHub commit activity" src="https://img.shields.io/github/commit-activity/w/Rustscan/Rustscan">
<img alt="GitHub All Releases" src="https://img.shields.io/github/downloads/rustscan/rustscan/total?label=GitHub%20Downloads">
<img alt="Crates.io" src="https://img.shields.io/crates/d/rustscan?label=Cargo%20Downloads">
<img alt="Discord" src="https://img.shields.io/discord/736614461313515576">
@@ -21,14 +21,15 @@
</p>
<hr>
| <p align="center"><a href="https://hub.docker.com/r/cmnatic/rustscan">🐋 Docker (Recommended) </a></p> | <p align="center"><a href="https://github.com/RustScan/RustScan/releases">👩‍💻 Kali / Debian </p> | <p align="center"><a href="https://aur.archlinux.org/packages/rustscan/">🏗️ Arch </a></p> | <p align="center"><a href="https://crates.io/crates/rustscan">🔧 Cargo (Universal) </a></p> |
| ---- | ---- | ---- | --- |
| <p align="center"><img src="https://github.com/RustScan/RustScan/blob/master/pictures/docker.png?raw=true" /></p> | <p align="center"><img src="https://github.com/RustScan/RustScan/blob/master/pictures/kali.png?raw=true" /></p> | <p align="center"><img src="https://github.com/RustScan/RustScan/blob/master/pictures/arch.png?raw=true" /></p> | <p align="center"><img src="https://github.com/RustScan/RustScan/blob/master/pictures/rust.png?raw=true" /></p>
| `docker pull rustscan/rustscan:alpine` <p>[Usage](https://github.com/RustScan/RustScan#docker-whale) | [Read the install guide](https://github.com/brandonskerritt/RustScan/blob/master/README.md#%EF%B8%8F-debian--kali) | `yay -S rustscan` | `cargo install rustscan`
| <p align="center"><a href="https://hub.docker.com/r/cmnatic/rustscan">🐋 Docker (Recommended) </a></p> | <p align="center"><a href="https://github.com/RustScan/RustScan/releases">👩‍💻 Kali / Debian </p> | <p align="center"><a href="https://aur.archlinux.org/packages/rustscan/">🏗️ Arch </a></p> | <p align="center"><a href="https://crates.io/crates/rustscan">🔧 Cargo (Universal) </a></p> |
| ----------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| <p align="center"><img src="https://github.com/RustScan/RustScan/blob/master/pictures/docker.png?raw=true" /></p> | <p align="center"><img src="https://github.com/RustScan/RustScan/blob/master/pictures/kali.png?raw=true" /></p> | <p align="center"><img src="https://github.com/RustScan/RustScan/blob/master/pictures/arch.png?raw=true" /></p> | <p align="center"><img src="https://github.com/RustScan/RustScan/blob/master/pictures/rust.png?raw=true" /></p> |
| `docker pull rustscan/rustscan:v1.9.0` <p>[Usage](https://github.com/RustScan/RustScan#docker-whale) | [Read the install guide](https://github.com/Rustscan/RustScan/blob/master/README.md#%EF%B8%8F-debian--kali) | `yay -S rustscan` | `cargo install rustscan` |
<hr>
# 🤔 What is this?
1. Find ports quickly using Rustscan (**3 seconds at its fastest**).
2. Automatically runs `nmap` on those ports.
3. ???
@@ -57,26 +58,29 @@
RustScans **only** job is to reduce the friction between finding open ports and inputting them into nmap.
# ✨ Features
* Scans all 65k ports in **8 seconds** (on 10k batch size).
* Saves you time by automatically piping it into Nmap. No more manual copying and pasting!
* Does one thing and does it well. **Only** purpose is to improve Nmap, not replace it!
* Let's you choose what Nmap commands to run, or uses the default.
* IPv6 Support
- Scans all 65k ports in **8 seconds** (on 10k batch size).
- Saves you time by automatically piping it into Nmap. No more manual copying and pasting!
- Does one thing and does it well. **Only** purpose is to improve Nmap, not replace it!
- Let's you choose what Nmap commands to run, or uses the default.
- IPv6 Support
## ‼️ Important Links
| Installation Guide | Documentation | Discord |
| ------------------ | ------------- | ------- |
| 📖 [Installation Guide](https://github.com/RustScan/RustScan#-full-installation-guide) | 📚 [Documentation](https://github.com/RustScan/RustScan/issues/89) | 🦜 [Discord](https://discord.gg/GFrQsGy)
| Installation Guide | Documentation | Discord |
| -------------------------------------------------------------------------------------- | -------------------------------------------------------- | ---------------------------------------- |
| 📖 [Installation Guide](https://github.com/RustScan/RustScan#-full-installation-guide) | 📚 [Documentation](https://rustscan.github.io/RustScan/) | 🦜 [Discord](https://discord.gg/GFrQsGy) |
## 🙋 Table of Contents
* 📖 [Installation Guide](https://github.com/RustScan/RustScan#-full-installation-guide)
* 🐋 [Docker Usage](https://github.com/RustScan/RustScan#docker-whale)
* 🦜 [Discord](https://discord.gg/GFrQsGy)
* 🤸 [Usage](https://github.com/RustScan/RustScan#-usage)
* 🎪 [Community](https://github.com/RustScan/RustScan#-community)
- 📖 [Installation Guide](https://github.com/RustScan/RustScan#-full-installation-guide)
- 🐋 [Docker Usage](https://github.com/RustScan/RustScan#docker-whale)
- 🦜 [Discord](https://discord.gg/GFrQsGy)
- 🤸 [Usage](https://github.com/RustScan/RustScan#-usage)
- 🎪 [Community](https://github.com/RustScan/RustScan#-community)
# 🔭 Why RustScan?
Why spend time running fast scans and manually copying the ports, or waiting for a 20 minute scan to finish when you can just do all 65k ports in less than a minute?
![gif](https://github.com/RustScan/RustScan/blob/master/pictures/8seconds.gif?raw=true)
@@ -87,11 +91,12 @@ Why spend time running fast scans and manually copying the ports, or waiting for
| **Name** | RustScan | Nmap | Masscan |
| ------------------------------------------------------------------------------------------ | -------- | ---- | ------- |
| Fast | ✅ | ❌ | ✅ |
| Actually useful | ❌ | ✅ | ❌ |
| Realises it's not useful, and pipes the only useful data into the only useful port scanner | ✅ | ❌ | ❌ |
| Fast | ✅ | ❌ | ✅ |
| Actually useful | ❌ | ✅ | ❌ |
| Realises it's not useful, and pipes the only useful data into the only useful port scanner | ✅ | ❌ | ❌ |
# 📖 Full Installation Guide
**You need Nmap**. If you have Kali Linux or Parrot OS installed, you already have Nmap. If not, [follow the nmap install guide](https://nmap.org/download.html).
The easiest way to install RustScan is to use one of the packages provided for your system, such as HomeBrew or Yay for Arch Linux.
@@ -106,38 +111,41 @@ Note: sometimes Rust doesn't add Cargo to the path. Please see [this issue](http
Download the .deb file from the releases page:
[https://github.com/brandonskerritt/RustScan/releases](https://github.com/brandonskerritt/RustScan/releases)
[https://github.com/RustScan/RustScan/releases](https://github.com/RustScan/RustScan/releases)
Run the commpand `dpkg -i` on the file.
Run the command `dpkg -i` on the file.
Note: sometimes you can double click the file to achieve the same result.
## Docker :whale:
Docker is the recommended way of installing RustScan. This is because:
* It has a high open file descriptor limit, which is one of the [main problems](https://github.com/RustScan/RustScan/issues/40) with RustScan. Now you don't have to fiddle around trying to understand your OS.
* It works on all systems, regardless of OS. Even Windows, which we don't officially support.
* The Docker image uses the latest build from Cargo, our main source-of-truth package. This means that you will always be using the latest version.
* No need to install Rust, Cargo, or Nmap.
- It has a high open file descriptor limit, which is one of the [main problems](https://github.com/RustScan/RustScan/issues/40) with RustScan. Now you don't have to fiddle around trying to understand your OS.
- It works on all systems, regardless of OS. Even Windows, which we don't officially support.
- The Docker image uses the latest build from Cargo, our main source-of-truth package. This means that you will always be using the latest version.
- No need to install Rust, Cargo, or Nmap.
To install Docker, [follow their guide](https://docs.docker.com/engine/install/).
**Once Docker is installed, you can either build your own image using the `Dockerfile` (alpine) provided in the repo, or alternatively, use the published Docker image like below (most convenient)**
Please see our [DockerHub](https://hub.docker.com/repository/docker/rustscan/rustscan) for further info, however, note that we have two Docker images:
```
rustscan/rustscan:alpine
Please see our [DockerHub](https://hub.docker.com/repository/docker/rustscan/rustscan) for further our published versions. However, we recommend using our latest release [v1.9.0](https://github.com/RustScan/RustScan/releases/tag/1.9.0)
rustscan/rustscan:latest
```
We strongly recommend using the `alpine` tag, as this is the latest major - stable - release of RustScan. This READMDE uses the `alpine` image by default, however, note that the`latest` image is considered experimental.
Stable and supported: rustscan/rustscan:v1.9.0
Bleeding edge (run at your own risk!): rustscan/rustscan:latest
```
We strongly recommend using the `v1.9.0` tag, as this is the latest major - stable - release of RustScan. This README uses the `v1.9.0` image by default, however, note that the `latest` image is considered experimental.
#### To get started:
Simply run this command against the IP you want to target:
```
docker run -it --rm --name rustscan rustscan/rustscan:alpine <rustscan arguments here> <ip address to scan>
```bash
docker run -it --rm --name rustscan rustscan/rustscan:v1.9.0 <rustscan arguments here> <ip address to scan>
```
Note: this will scan the Docker's localhost, not your own.
@@ -146,30 +154,33 @@ Once done, you will no longer need to re-download the image (except when RustSca
You will have to run this command every time, so we suggest aliasing it to something memorable.
```
alias rustscan='docker run -it --rm --name rustscan rustscan/rustscan:alpine <rustscan arguments here> <ip address to scan>'
```bash
alias rustscan='docker run -it --rm --name rustscan rustscan/rustscan:v1.9.0'
```
Then we can:
Then we can scan:
```
rustscan 127.0.0.1 -t 500 -b 1500 -- -A
```bash
rustscan 192.168.1.0/24 -t 500 -b 1500 -- -A
```
#### To build your own image:
Download the repo:
```
```bash
git clone https://github.com/RustScan/RustScan.git
```
Ensure you navigate to the download location of the repo:
```
```bash
cd /path/to/download/RustScan
```
Build away!
```
```bash
docker build -t <yourimagename> .
```
@@ -177,14 +188,6 @@ docker build -t <yourimagename> .
**Note for Mac users** Mac OS has a very, very small ulimit size. This will negatively impact RustScan by a significant amount. Please use the Docker container, or tell RustScan to up the ulimit size on every run.
Tap the brew:
```
brew tap brandonskerritt/rustscan
```
Install it:
```
brew install rustscan
```
@@ -198,31 +201,33 @@ brew install rustscan
5. Symlink to the binary or something. Whatever you want!
## 🦊 Community Distributions
Here are all of RustScan's community distributions.
If you maintain a community distribution and want it listed here, leave an issue / pull request / Discord message or however you want to let us know.
* [OpenSuse](https://software.opensuse.org/package/rustscan?search_term=rustscan)
- [OpenSuse](https://software.opensuse.org/package/rustscan?search_term=rustscan)
- [Fedora/CentOS](https://copr.fedorainfracloud.org/coprs/atim/rustscan/)
[![Packaging status](https://repology.org/badge/vertical-allrepos/rustscan.svg)](https://repology.org/project/rustscan/versions)
# 🤸 Usage
```
rustscan -h
```
```console
$ rustscan -h
```
Fast Port Scanner built in Rust. WARNING Do not use this program against sensitive infrastructure since the specified
server may not be able to handle this many socket connections at once. - Discord https://discord.gg/GFrQsGy - GitHub
https://github.com/RustScan/RustScan
USAGE:
rustscan [FLAGS] [OPTIONS] <ips-or-hosts>... [-- <command>...]
rustscan [FLAGS] [OPTIONS] [addresses]... [-- <command>...]
FLAGS:
-a, --accessible
--accessible Accessible mode. Turns off features which negatively affect screen readers
-h, --help Prints help information
-n, --no-config Whether to ignore the configuration file or not
--no-nmap Turns off Nmap
-q, --quiet Quiet mode. Only output the ports. No Nmap. Useful for grep or outputting to a file
-V, --version Prints version information
@@ -230,8 +235,7 @@ OPTIONS:
-b, --batch-size <batch-size> The batch size for port scanning, it increases or slows the speed of scanning.
Depends on the open file limit of your OS. If you do 65535 it will do every port
at the same time. Although, your OS may not support this [default: 4500]
-p, --ports <ports>... A list of comma separed ports to be scanned. Example: 80,443,8080. These ports will
be scanned sequentially
-p, --ports <ports>... A list of comma separed ports to be scanned. Example: 80,443,8080
-r, --range <range> A range of ports with format start-end. Example: 1-1000
--scan-order <scan-order> The order of scanning to be performed. The "serial" option will scan ports in
ascending order while the "random" option will scan ports randomly [default:
@@ -240,36 +244,71 @@ OPTIONS:
-u, --ulimit <ulimit> Automatically ups the ULIMIT with the value you provided
ARGS:
<ips-or-hosts>... A list of comma separated IP addresses or hosts to be scanned
<command>... The Nmap arguments to run. To use the argument -A, end RustScan's args with '-- -A'.
Example: 'rustscan -T 1500 127.0.0.1 -- -A -sC'. This command adds -Pn -vvv -p $PORTS
automatically to nmap. For things like --script '(safe and vuln)' enclose it in quotations
marks \"'(safe and vuln)'\"")
<addresses>... A list of comma separated CIDRs, IPs, or hosts to be scanned
<command>... The Nmap arguments to run. To use the argument -A, end RustScan's args with '-- -A'. Example:
'rustscan -t 1500 127.0.0.1 -- -A -sC'. This command adds -Pn -vvv -p $PORTS automatically to
nmap. For things like --script '(safe and vuln)' enclose it in quotations marks \"'(safe and
vuln)'\"")
```
The format is `rustscan -b 500 -T 1500 192.168.0.1` to scan 192.168.0.1 with 500 batch size with a timeout of 1500ms. The timeout is how long RustScan waits for a response until it assumes the port is closed.
The format is `rustscan -b 500 -t 1500 192.168.0.1` to scan 192.168.0.1 with 500 batch size with a timeout of 1500ms. The timeout is how long RustScan waits for a response until it assumes the port is closed.
The batch size determines how fast RustScan is. Set it to 65k, and it will scan all 65k ports at the same time. This means at at 65k batch size, RustScan will take TIMEOUT long to scan all ports. Essentially, if timeout is 1000ms, **RustScan can scan in 1 second**.
Your operating system may not support this, but it is worth it to play around and see where your open file limit is. Shortly I will be releasing a dockerised version with a much larger open file limit, so this will be possible.
## Configuration file
This binary accepts a configuration file that is read from the home directory of the user. It follows the TOML format
and accepts the following fields:
- `addresses`
- `ports`
- `range`
- `scan_order`
- `command`
- `accessible`
- `quiet`
- `batch-size`
- `timeout`
- `ulimit`
### Format example
```toml
addresses = ["127.0.0.1", "192.168.0.0/30", "www.google.com"]
command = ["-A"]
ports = [80, 443, 8080]
range = { start = 1, end = 10 }
quiet = false
accessible = true
scan_order = "Serial"
batch_size = 1000
timeout = 1000
ulimit = 1000
```
## ⚠️ WARNING
This program, by default, scans 5000 ports at a time (5000 per second).
This may cause damage to a server, or may make it incredibly obvious you are scanning the server.
Servers as well as individual services can block your IP completely after a huge amount of simultaneous connections/tries, Possibly causing you to see false positives. False positives are open ports at the initial scanning process later found closed when you want to do further scanning, or connect to it.
There are 2 ways to deal with this;
1. Decrease batch size
`rustscan -b 10` will run 10 port scans for 1 second, and then another 10 for 1 second and so on.
`rustscan -b 10` will run 10 port scans for 1 second, and then another 10 for 1 second and so on.
2. Increase timeout
`rustscan -T 5000` will mean RustScan waits 5 seconds until it scans the next ports.
`rustscan -T 5000` will mean RustScan waits 5 seconds until it scans the next ports.
You can also use both of these at the same time, to make it as slow or as fast as you want. A fun favourite is 65535 batch size with 1 second timeout. Theoretically, this scans all 65535 ports in 1 second.
**Please** do not use this tool against sensitive servers. It is designed mainly for Capture the Flag events, not real world servers with sensitive data.
## 🚨 Thread Panicked at Main: Too Many Open Files
This is the most common error found in RustScan.
The open file limit is how many open sockets you can have at any given time.
@@ -281,6 +320,7 @@ RustScan does not automatically create defaults (other than 5000) like Nmap does
By figuring out for yourself the optimal batch size, you will know that RustScan is the most optimised port scanner for your system.
There are 2 things you can do:
1. Decrease batch size
2. Increase open file limit
@@ -288,7 +328,7 @@ Decreasing batch size slows down the program, so as long as it isn't too drastic
Run these 3 commands:
```
```bash
ulimit -a
ulimit -Hn
ulimit -Sn
@@ -302,7 +342,7 @@ Increasing the open file limit increases speed, but poses danger. Although, **op
To open more, set the ulimit to a higher number:
```
```bash
ulimit -n 5000
```
@@ -319,9 +359,10 @@ Windows Subsystem for Linux does not support ulimit (see issue #39).
The best way is to use it on a host computer, in Docker, or in a VM that isn't WSL.
**Automatic Ulimit updating**
We are currently working on automatic Ulimit updating. If it is too high, it will lower itself. If it is too low, it will suggest a higher Ulimit. Watch [this issue](https://github.com/brandonskerritt/RustScan/issues/25) for more.
We are currently working on automatic Ulimit updating. If it is too high, it will lower itself. If it is too low, it will suggest a higher Ulimit. Watch [this issue](https://github.com/RustScan/RustScan/issues/25) for more.
## 🔌 Nmap Custom Flags
To run your own nmap commands, end the RustScan command with `-- -A` where `--` indicates "end of RustScan flags, please do not parse anything further" and any flags after that will be entered into nmap.
RustScan automatically runs `nmap -vvv -p $PORTS $IP`. To make it run `-A`, execute the command `rustscan 127.0.0.1 -- -A`.
@@ -329,13 +370,14 @@ RustScan automatically runs `nmap -vvv -p $PORTS $IP`. To make it run `-A`, exec
If you want to run commands such as `--script (vuln and safe)`, you will need to enclose it in quotations like so `--script '"(vuln and safe) or default"'`.
## 🎯 Increasing speed / accuracy
* Batch size
- Batch size
This increases speed, by allowing us to process more at once. Something experimental I am working on is changing the open file limit. You can do this manually with `ulimit -n 70000` and then running rustscan with `-b 65535`. This _should_ scan all 65535 ports at the exact same time. But this is extremely experimental.
For non-experimental speed increases, slowly increase the batch size until it no longer gets open ports, or it breaks.
* Accuracy (and some speed)
- Accuracy (and some speed)
To increase accuracy, the easiest way is to increase the timeout. The default is 1.5 seconds, by setting it to 4 seconds (4000) we are telling RustScan "if we do not hear back from a port in 4 seconds, assume it is closed".
@@ -352,19 +394,21 @@ Before contributing, read our [code of conduct](https://github.com/RustScan/Rust
TL;DR if you abuse members of our community you will be **perma-banned** 🤗
RustScan has 2 major labels for GitHub issues you should look at:
* Good First issue
These are issues for newcomers to open source!
[https://github.com/RustScan/RustScan/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22](https://github.com/RustScan/RustScan/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)
* Help wanted
These are issues that aren't really for newcomers, but we could still do wiht help!
[https://github.com/RustScan/RustScan/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22+label%3A%22help+wanted%22](https://github.com/RustScan/RustScan/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22+label%3A%22help+wanted%22)
- Good First issue
These are issues for newcomers to open source!
[https://github.com/RustScan/RustScan/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22](https://github.com/RustScan/RustScan/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)
- Help wanted
These are issues that aren't really for newcomers, but we could still do wiht help!
[https://github.com/RustScan/RustScan/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22+label%3A%22help+wanted%22](https://github.com/RustScan/RustScan/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22+label%3A%22help+wanted%22)
If you want to, solve the issue or comment on the issue for help.
The flow for contributing to open source software is:
* Fork the repo
* Make changes
* Pull request to the repo
- Fork the repo
- Make changes
- Pull request to the repo
And then comment on the issue that you've done.
@@ -375,14 +419,15 @@ If you have any feature suggestions or bugs, leave a GitHub issue. We welcome an
We communicate over Discord. [Click here](https://discord.gg/GFrQsGy) to join our Discord community!
## Rewarding you
I cannot pay you :-( But, I can place your GitHub profile on the README under `#Contributors` as a thank you! :)
I cannot pay you :-( But, I can place your GitHub profile on the README under `#Contributors` as a thank you! :)
Please read the [contributing.md file](contributing.md)
## Contributors ✨
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-11-orange.svg?style=flat-square)](#contributors-)
[![All Contributors](https://img.shields.io/badge/all_contributors-20-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
@@ -405,6 +450,17 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
<td align="center"><a href="https://tgotwig.me"><img src="https://avatars0.githubusercontent.com/u/30773779?v=4" width="100px;" alt=""/><br /><sub><b>Thomas Gotwig</b></sub></a><br /><a href="#platform-TGotwig" title="Packaging/porting to new platform">📦</a></td>
<td align="center"><a href="https://github.com/remigourdon"><img src="https://avatars3.githubusercontent.com/u/2874133?v=4" width="100px;" alt=""/><br /><sub><b>Rémi Gourdon</b></sub></a><br /><a href="https://github.com/RustScan/RustScan/commits?author=remigourdon" title="Documentation">📖</a> <a href="https://github.com/RustScan/RustScan/commits?author=remigourdon" title="Code">💻</a></td>
<td align="center"><a href="https://cmnatic.co.uk"><img src="https://avatars3.githubusercontent.com/u/4163116?v=4" width="100px;" alt=""/><br /><sub><b>Ben (CMNatic)</b></sub></a><br /><a href="https://github.com/RustScan/RustScan/commits?author=cmnatic" title="Code">💻</a> <a href="https://github.com/RustScan/RustScan/commits?author=cmnatic" title="Documentation">📖</a> <a href="#design-cmnatic" title="Design">🎨</a></td>
<td align="center"><a href="https://github.com/Ferryistaken"><img src="https://avatars3.githubusercontent.com/u/47927670?v=4" width="100px;" alt=""/><br /><sub><b>Alessandro Ferrari</b></sub></a><br /><a href="#content-Ferryistaken" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/Phenomite"><img src="https://avatars2.githubusercontent.com/u/8285537?v=4" width="100px;" alt=""/><br /><sub><b>Phenomite</b></sub></a><br /><a href="#content-Phenomite" title="Content">🖋</a></td>
<td align="center"><a href="https://supersandro.de/"><img src="https://avatars2.githubusercontent.com/u/7258858?v=4" width="100px;" alt=""/><br /><sub><b>Sandro</b></sub></a><br /><a href="#content-SuperSandro2000" title="Content">🖋</a> <a href="https://github.com/RustScan/RustScan/issues?q=author%3ASuperSandro2000" title="Bug reports">🐛</a> <a href="https://github.com/RustScan/RustScan/commits?author=SuperSandro2000" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://swag.lgbt"><img src="https://avatars2.githubusercontent.com/u/25358963?v=4" width="100px;" alt=""/><br /><sub><b>Cass</b></sub></a><br /><a href="#platform-caass" title="Packaging/porting to new platform">📦</a> <a href="https://github.com/RustScan/RustScan/commits?author=caass" title="Code">💻</a> <a href="https://github.com/RustScan/RustScan/issues?q=author%3Acaass" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/niklasmohrin"><img src="https://avatars0.githubusercontent.com/u/47574893?v=4" width="100px;" alt=""/><br /><sub><b>Niklas Mohrin</b></sub></a><br /><a href="https://github.com/RustScan/RustScan/commits?author=niklasmohrin" title="Documentation">📖</a></td>
<td align="center"><a href="https://liberapay.com/Artem4/"><img src="https://avatars0.githubusercontent.com/u/5614476?v=4" width="100px;" alt=""/><br /><sub><b>Artem Polishchuk</b></sub></a><br /><a href="#platform-tim77" title="Packaging/porting to new platform">📦</a></td>
<td align="center"><a href="https://github.com/buermarc"><img src="https://avatars2.githubusercontent.com/u/44375277?v=4" width="100px;" alt=""/><br /><sub><b>buermarc</b></sub></a><br /><a href="https://github.com/RustScan/RustScan/commits?author=buermarc" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/bergabman"><img src="https://avatars1.githubusercontent.com/u/44554109?v=4" width="100px;" alt=""/><br /><sub><b>bergabman</b></sub></a><br /><a href="https://github.com/RustScan/RustScan/commits?author=bergabman" title="Code">💻</a> <a href="https://github.com/RustScan/RustScan/issues?q=author%3Abergabman" title="Bug reports">🐛</a> <a href="#design-bergabman" title="Design">🎨</a></td>
<td align="center"><a href="https://github.com/dmitris"><img src="https://avatars0.githubusercontent.com/u/31205?v=4" width="100px;" alt=""/><br /><sub><b>Dmitry Savintsev</b></sub></a><br /><a href="https://github.com/RustScan/RustScan/commits?author=dmitris" title="Code">💻</a></td>
</tr>
</table>
+9
View File
@@ -0,0 +1,9 @@
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use rustscan::*;
pub fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("fib 20", |b| b.iter(|| fibonacci(black_box(20))));
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
+1004
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -11,7 +11,7 @@ RustScan has 2 major labels for GitHub issues you should look at:
These are issues for newcomers to open source!
[https://github.com/RustScan/RustScan/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22](https://github.com/RustScan/RustScan/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)
* Help wanted
These are issues that aren't really for newcomers, but we could still do wiht help!
These are issues that aren't really for newcomers, but we could still do with help!
[https://github.com/RustScan/RustScan/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22+label%3A%22help+wanted%22](https://github.com/RustScan/RustScan/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22+label%3A%22help+wanted%22)
If you want to, solve the issue or comment on the issue for help.
+6
View File
@@ -0,0 +1,6 @@
127.0.0.1
google.com
example.com
66666666666666.666666666666666666.66666666666666666.6666666666
....
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.radiatorFixtures
Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 29 KiB

+89
View File
@@ -0,0 +1,89 @@
//! # Usage
//! ```
//! // Initiate Benchmark vector
//! let mut bm = Benchmark::init();
//! // Start named timer with name
//! let mut example_bench = NamedTimer::start("Example Bench");
//! // Stop named timer
//! example_bench.stop();
//! // Add named timer to Benchmarks
//! bm.push(example_bench);
//! // Print Benchmark Summary
//! info!({}, bm.summary());
//! ```
use std::time::Instant;
/// A Benchmark struct to hold NamedTimers with name, start and end Instants,
#[derive(Debug)]
pub struct Benchmark {
named_timers: Vec<NamedTimer>,
}
impl Benchmark {
pub fn init() -> Self {
Self {
named_timers: Vec::new(),
}
}
pub fn push(&mut self, timer: NamedTimer) {
self.named_timers.push(timer);
}
/// Summary of the benchmarks will destruct the vector,
/// formats every element the same way and return
/// a single String with all the available information
/// for easy printing
pub fn summary(&self) -> String {
let mut summary = String::from("\nRustScan Benchmark Summary");
for timer in &self.named_timers {
if timer.start.is_some() && timer.end.is_some() {
let runtime_secs = timer
.end
.unwrap()
.saturating_duration_since(timer.start.unwrap())
.as_secs_f32();
summary.push_str(&format!("\n{0: <10} | {1: <10}s", timer.name, runtime_secs))
}
}
summary
}
}
/// The purpose of NamedTimer is to hold a name,
/// start Instant and end Instant for a specific timer.
/// The given name will be presented in the benchmark summary,
/// start and end Instants will be used for calculating runtime.
#[derive(Debug)]
pub struct NamedTimer {
name: &'static str,
start: Option<Instant>,
end: Option<Instant>,
}
impl NamedTimer {
pub fn start(name: &'static str) -> Self {
Self {
name: name,
start: Some(Instant::now()),
end: None,
}
}
pub fn end(&mut self) {
self.end = Some(Instant::now());
}
}
#[test]
fn benchmark() {
let mut benchmarks = Benchmark::init();
let mut test_timer = NamedTimer::start("test");
std::thread::sleep(std::time::Duration::from_millis(100));
test_timer.end();
benchmarks.push(test_timer);
benchmarks.push(NamedTimer::start("only_start"));
assert!(benchmarks
.summary()
.contains("\nRustScan Benchmark Summary\ntest | 0."));
assert_ne!(benchmarks.summary().contains("only_start"), true);
}
+329
View File
@@ -0,0 +1,329 @@
use serde_derive::Deserialize;
use std::collections::HashMap;
use std::fs;
use structopt::{clap::arg_enum, StructOpt};
const LOWEST_PORT_NUMBER: u16 = 1;
const TOP_PORT_NUMBER: u16 = 65535;
arg_enum! {
/// Represents the strategy in which the port scanning will run.
/// - Serial will run from start to end, for example 1 to 1_000.
/// - Random will randomize the order in which ports will be scanned.
#[derive(Deserialize, Debug, StructOpt, Clone, PartialEq)]
pub enum ScanOrder {
Serial,
Random,
}
}
/// Represents the range of ports to be scanned.
#[derive(Deserialize, Debug, Clone, PartialEq)]
pub struct PortRange {
pub start: u16,
pub end: u16,
}
#[cfg(not(tarpaulin_include))]
fn parse_range(input: &str) -> Result<PortRange, String> {
let range = input
.split("-")
.map(|x| x.parse::<u16>())
.collect::<Result<Vec<u16>, std::num::ParseIntError>>();
if range.is_err() {
return Err(String::from(
"the range format must be 'start-end'. Example: 1-1000.",
));
}
match range.unwrap().as_slice() {
[start, end] => Ok(PortRange {
start: *start,
end: *end,
}),
_ => Err(String::from(
"the range format must be 'start-end'. Example: 1-1000.",
)),
}
}
#[derive(StructOpt, Debug)]
#[structopt(name = "rustscan", setting = structopt::clap::AppSettings::TrailingVarArg)]
/// Fast Port Scanner built in Rust.
/// WARNING Do not use this program against sensitive infrastructure since the
/// specified server may not be able to handle this many socket connections at once.
/// - Discord https://discord.gg/GFrQsGy
/// - GitHub https://github.com/RustScan/RustScan
pub struct Opts {
/// A list of comma separated CIDRs, IPs, or hosts to be scanned.
#[structopt(use_delimiter = true)]
pub addresses: Vec<String>,
/// A list of comma separed ports to be scanned. Example: 80,443,8080.
#[structopt(short, long, use_delimiter = true)]
pub ports: Option<Vec<u16>>,
/// A range of ports with format start-end. Example: 1-1000.
#[structopt(short, long, conflicts_with = "ports", parse(try_from_str = parse_range))]
pub range: Option<PortRange>,
/// Whether to ignore the configuration file or not.
#[structopt(short, long)]
pub no_config: bool,
/// Greppable mode. Only output the ports. No Nmap. Useful for grep or outputting to a file.
#[structopt(short, long)]
pub greppable: bool,
/// Accessible mode. Turns off features which negatively affect screen readers.
#[structopt(long)]
pub accessible: bool,
/// Turns off Nmap.
#[structopt(long)]
pub no_nmap: bool,
/// The batch size for port scanning, it increases or slows the speed of
/// scanning. Depends on the open file limit of your OS. If you do 65535
/// it will do every port at the same time. Although, your OS may not
/// support this.
#[structopt(short, long, default_value = "4500")]
pub batch_size: u16,
/// The timeout in milliseconds before a port is assumed to be closed.
#[structopt(short, long, default_value = "1500")]
pub timeout: u32,
/// Automatically ups the ULIMIT with the value you provided.
#[structopt(short, long)]
pub ulimit: Option<rlimit::rlim>,
/// The order of scanning to be performed. The "serial" option will
/// scan ports in ascending order while the "random" option will scan
/// ports randomly.
#[structopt(long, possible_values = &ScanOrder::variants(), case_insensitive = true, default_value = "serial")]
pub scan_order: ScanOrder,
/// The Nmap arguments to run.
/// To use the argument -A, end RustScan's args with '-- -A'.
/// Example: 'rustscan -T 1500 127.0.0.1 -- -A -sC'.
/// This command adds -Pn -vvv -p $PORTS automatically to nmap.
/// For things like --script '(safe and vuln)' enclose it in quotations marks \"'(safe and vuln)'\"")
#[structopt(last = true)]
pub command: Vec<String>,
/// Use the top 1000 ports.
#[structopt(long)]
pub top: bool,
}
#[cfg(not(tarpaulin_include))]
impl Opts {
pub fn read() -> Self {
let mut opts = Opts::from_args();
if opts.ports.is_none() && opts.range.is_none() {
opts.range = Some(PortRange {
start: LOWEST_PORT_NUMBER,
end: TOP_PORT_NUMBER,
});
}
opts
}
/// Reads the command line arguments into an Opts struct and merge
/// values found within the user configuration file.
pub fn merge(&mut self, config: &Config) {
if !self.no_config {
self.merge_required(&config);
self.merge_optional(&config);
}
}
fn merge_required(&mut self, config: &Config) {
macro_rules! merge_required {
($($field: ident),+) => {
$(
if let Some(e) = &config.$field {
self.$field = e.clone();
}
)+
}
}
merge_required!(addresses, greppable, accessible, batch_size, timeout, scan_order, command);
}
fn merge_optional(&mut self, config: &Config) {
macro_rules! merge_optional {
($($field: ident),+) => {
$(
if config.$field.is_some() {
self.$field = config.$field.clone();
}
)+
}
}
// Only use top ports when the user asks for them
if self.top {
if config.ports.is_some() {
let mut ports: Vec<u16> = Vec::with_capacity(config.ports.clone().unwrap().len());
for entry in config.ports.clone().unwrap().keys() {
ports.push(entry.parse().unwrap())
}
self.ports = Some(ports);
}
}
merge_optional!(range, ulimit);
}
}
/// Struct used to deserialize the options specified within our config file.
/// These will be further merged with our command line arguments in order to
/// generate the final Opts struct.
#[cfg(not(tarpaulin_include))]
#[derive(Debug, Deserialize)]
pub struct Config {
addresses: Option<Vec<String>>,
ports: Option<HashMap<String, u16>>,
range: Option<PortRange>,
greppable: Option<bool>,
accessible: Option<bool>,
batch_size: Option<u16>,
timeout: Option<u32>,
no_nmap: Option<bool>,
ulimit: Option<rlimit::rlim>,
scan_order: Option<ScanOrder>,
command: Option<Vec<String>>,
}
#[cfg(not(tarpaulin_include))]
impl Config {
/// Reads the configuration file with TOML format and parses it into a
/// Config struct.
///
/// # Format
///
/// addresses = ["127.0.0.1", "127.0.0.1"]
/// ports = [80, 443, 8080]
/// quiet = true
/// scan_order: "Serial"
///
pub fn read() -> Self {
let mut home_dir = match dirs::home_dir() {
Some(dir) => dir,
None => panic!("Could not infer config file path."),
};
home_dir.push(".rustscan.toml");
let mut content = String::new();
if home_dir.exists() {
content = match fs::read_to_string(home_dir) {
Ok(content) => content,
Err(_) => String::new(),
}
}
let config: Config = match toml::from_str(&content) {
Ok(config) => config,
Err(e) => {
println!("Found {} in configuration file.\nAborting scan.\n", e);
std::process::exit(1);
}
};
config
}
}
#[cfg(test)]
mod tests {
use super::{Config, Opts, PortRange, ScanOrder};
impl Config {
fn default() -> Self {
Self {
addresses: Some(vec!["127.0.0.1".to_owned()]),
ports: None,
range: None,
greppable: Some(true),
batch_size: Some(25_000),
timeout: Some(1_000),
ulimit: None,
no_nmap: Some(false),
command: Some(vec!["-A".to_owned()]),
accessible: Some(true),
scan_order: Some(ScanOrder::Random),
}
}
}
impl Opts {
pub fn default() -> Self {
Self {
addresses: vec![],
ports: None,
range: None,
greppable: true,
batch_size: 0,
timeout: 0,
ulimit: None,
command: vec![],
accessible: false,
no_nmap: false,
scan_order: ScanOrder::Serial,
no_config: true,
top: false,
}
}
}
#[test]
fn opts_no_merge_when_config_is_ignored() {
let mut opts = Opts::default();
let config = Config::default();
opts.merge(&config);
assert_eq!(opts.addresses, vec![] as Vec<String>);
assert_eq!(opts.greppable, true);
assert_eq!(opts.accessible, false);
assert_eq!(opts.timeout, 0);
assert_eq!(opts.command, vec![] as Vec<String>);
assert_eq!(opts.scan_order, ScanOrder::Serial);
}
#[test]
fn opts_merge_required_arguments() {
let mut opts = Opts::default();
let config = Config::default();
opts.merge_required(&config);
assert_eq!(opts.addresses, config.addresses.unwrap());
assert_eq!(opts.greppable, config.greppable.unwrap());
assert_eq!(opts.timeout, config.timeout.unwrap());
assert_eq!(opts.command, config.command.unwrap());
assert_eq!(opts.accessible, config.accessible.unwrap());
assert_eq!(opts.scan_order, config.scan_order.unwrap());
}
#[test]
fn opts_merge_optional_arguments() {
let mut opts = Opts::default();
let mut config = Config::default();
config.range = Some(PortRange {
start: 1,
end: 1_000,
});
config.ulimit = Some(1_000);
opts.merge_optional(&config);
assert_eq!(opts.range, config.range);
assert_eq!(opts.ulimit, config.ulimit);
}
}
+227 -273
View File
@@ -2,28 +2,37 @@ extern crate shell_words;
mod tui;
mod input;
use input::{Config, Opts, PortRange, ScanOrder};
mod scanner;
use scanner::Scanner;
mod port_strategy;
use port_strategy::PortStrategy;
mod benchmark;
use benchmark::{Benchmark, NamedTimer};
use cidr_utils::cidr::IpCidr;
use colorful::Color;
use colorful::Colorful;
use futures::executor::block_on;
use rlimit::Resource;
use rlimit::{getrlimit, setrlimit};
use std::collections::HashMap;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::net::ToSocketAddrs;
use std::process::Command;
use std::str::FromStr;
use std::{net::IpAddr, net::ToSocketAddrs, time::Duration};
use structopt::{clap::arg_enum, StructOpt};
use std::{net::IpAddr, time::Duration};
use trust_dns_resolver::config::*;
use trust_dns_resolver::Resolver;
extern crate colorful;
extern crate dirs;
const LOWEST_PORT_NUMBER: u16 = 1;
const TOP_PORT_NUMBER: u16 = 65535;
// Average value for Ubuntu
const DEFAULT_FILE_DESCRIPTORS_LIMIT: rlimit::rlim = 8000;
// Safest batch size based on experimentation
@@ -32,128 +41,32 @@ const AVERAGE_BATCH_SIZE: rlimit::rlim = 3000;
#[macro_use]
extern crate log;
arg_enum! {
#[derive(Debug, StructOpt)]
pub enum ScanOrder {
Serial,
Random,
}
}
#[derive(Debug)]
pub struct PortRange {
start: u16,
end: u16,
}
fn parse_range(input: &str) -> Result<PortRange, String> {
let range = input
.split("-")
.map(|x| x.parse::<u16>())
.collect::<Result<Vec<u16>, std::num::ParseIntError>>();
if range.is_err() {
return Err(String::from(
"the range format must be 'start-end'. Example: 1-1000.",
));
}
match range.unwrap().as_slice() {
[start, end] => Ok(PortRange {
start: *start,
end: *end,
}),
_ => Err(String::from(
"the range format must be 'start-end'. Example: 1-1000.",
)),
}
}
#[derive(StructOpt, Debug)]
#[structopt(name = "rustscan", setting = structopt::clap::AppSettings::TrailingVarArg)]
/// Fast Port Scanner built in Rust.
/// WARNING Do not use this program against sensitive infrastructure since the
/// specified server may not be able to handle this many socket connections at once.
/// - Discord https://discord.gg/GFrQsGy
/// - GitHub https://github.com/RustScan/RustScan
struct Opts {
/// A list of comma separated IP addresses or hosts to be scanned.
#[structopt(use_delimiter = true, required = true)]
ips_or_hosts: Vec<String>,
/// A list of comma separed ports to be scanned. Example: 80,443,8080.
/// These ports will be scanned sequentially.
#[structopt(short, long, use_delimiter = true)]
ports: Option<Vec<u16>>,
/// A range of ports with format start-end. Example: 1-1000.
#[structopt(short, long, conflicts_with = "ports", parse(try_from_str = parse_range))]
range: Option<PortRange>,
///Quiet mode. Only output the ports. No Nmap. Useful for grep or outputting to a file.
#[structopt(short, long)]
quiet: bool,
//Accessible mode. Turns off features which negatively affect screen readers.
#[structopt(short, long)]
accessible: bool,
/// The batch size for port scanning, it increases or slows the speed of
/// scanning. Depends on the open file limit of your OS. If you do 65535
/// it will do every port at the same time. Although, your OS may not
/// support this.
#[structopt(short, long, default_value = "4500")]
batch_size: u16,
/// The timeout in milliseconds before a port is assumed to be closed.
#[structopt(short, long, default_value = "1500")]
timeout: u32,
/// Automatically ups the ULIMIT with the value you provided.
#[structopt(short, long)]
ulimit: Option<rlimit::rlim>,
/// The order of scanning to be performed. The "serial" option will
/// scan ports in ascending order while the "random" option will scan
/// ports randomly.
#[structopt(long, possible_values = &ScanOrder::variants(), case_insensitive = true, default_value = "serial")]
scan_order: ScanOrder,
/// The Nmap arguments to run.
/// To use the argument -A, end RustScan's args with '-- -A'.
/// Example: 'rustscan -T 1500 127.0.0.1 -- -A -sC'.
/// This command adds -Pn -vvv -p $PORTS automatically to nmap.
/// For things like --script '(safe and vuln)' enclose it in quotations marks \"'(safe and vuln)'\"")
#[structopt(last = true)]
command: Vec<String>,
}
#[cfg(not(tarpaulin_include))]
/// Faster Nmap scanning with Rust
/// If you're looking for the actual scanning, check out the module Scanner
fn main() {
env_logger::init();
let mut benchmarks = Benchmark::init();
let mut rustscan_bench = NamedTimer::start("RustScan");
info!("Starting up");
let mut opts = Opts::from_args();
let mut opts: Opts = Opts::read();
let config = Config::read();
opts.merge(&config);
if opts.ports.is_none() && opts.range.is_none() {
opts.range = Some(PortRange {
start: LOWEST_PORT_NUMBER,
end: TOP_PORT_NUMBER,
});
debug!("Main() `opts` arguments are {:?}", opts);
if !opts.greppable && !opts.accessible {
print_opening(&opts);
}
info!("Mains() `opts` arguments are {:?}", opts);
if !opts.quiet && !opts.accessible {
print_opening();
}
let ips: Vec<IpAddr> = parse_ips(&opts);
let ips: Vec<IpAddr> = parse_addresses(&opts);
if ips.is_empty() {
warning!("No IPs could be resolved, aborting scan.", false);
warning!(
"No IPs could be resolved, aborting scan.",
opts.greppable,
opts.accessible
);
std::process::exit(1);
}
@@ -164,11 +77,17 @@ fn main() {
&ips,
batch_size,
Duration::from_millis(opts.timeout.into()),
opts.quiet,
opts.greppable,
PortStrategy::pick(opts.range, opts.ports, opts.scan_order),
opts.accessible,
);
debug!("Scanner finished building: {:?}", scanner);
let mut portscan_bench = NamedTimer::start("Portscan");
let scan_result = block_on(scanner.run());
portscan_bench.end();
benchmarks.push(portscan_bench);
let mut ports_per_ip = HashMap::new();
for socket in scan_result {
@@ -186,40 +105,42 @@ fn main() {
// If we got here it means the IP was not found within the HashMap, this
// means the scan couldn't find any open ports for it.
let x = format!("{} Looks like I didn't find any open ports for {:?}. This is usually caused by a high batch size.
\n*I used {} batch size, consider lowering to {} with {} or a comfortable number for your system.
\n Alternatively, increase the timeout if your ping is high. Rustscan -t 2000 for 2000 second timeout.\n",
"ERROR",
let x = format!("Looks like I didn't find any open ports for {:?}. This is usually caused by a high batch size.
\n*I used {} batch size, consider lowering it with {} or a comfortable number for your system.
\n Alternatively, increase the timeout if your ping is high. Rustscan -t 2000 for 2000 milliseconds (2s) timeout.\n",
ip,
opts.batch_size,
(opts.batch_size / 2).to_string(),
"'rustscan -b <batch_size> <ip address>'");
warning!(x, opts.quiet);
warning!(x, opts.greppable, opts.accessible);
}
let mut nmap_bench = NamedTimer::start("Nmap");
for (ip, ports) in ports_per_ip.iter_mut() {
let nmap_str_ports: Vec<String> = ports.into_iter().map(|port| port.to_string()).collect();
detail!("Starting Nmap", opts.quiet);
// nmap port style is 80,443. Comma separated with no spaces.
let ports_str = nmap_str_ports.join(",");
// if quiet mode is on nmap should not be spawned
if opts.quiet {
println!("{}", ports_str);
if opts.greppable || opts.no_nmap {
println!("{} -> [{}]", &ip, ports_str);
continue;
}
detail!("Starting Nmap", opts.greppable, opts.accessible);
let addr = ip.to_string();
let user_nmap_args =
shell_words::split(&opts.command.join(" ")).expect("failed to parse nmap arguments");
let nmap_args = build_nmap_arguments(&addr, &ports_str, &user_nmap_args, ip.is_ipv6());
output!(format!(
"The Nmap command to be run is nmap {}\n",
&nmap_args.join(" ")
));
output!(
format!(
"The Nmap command to be run is nmap {}\n",
&nmap_args.join(" ")
),
opts.greppable.clone(),
opts.accessible.clone()
);
// Runs the nmap command and spawns it as a process.
let mut child = Command::new("nmap")
@@ -229,11 +150,19 @@ fn main() {
child.wait().expect("failed to wait on nmap process");
}
// To use the runtime benchmark, run the process as: RUST_LOG=info ./rustscan
nmap_bench.end();
benchmarks.push(nmap_bench);
rustscan_bench.end();
benchmarks.push(rustscan_bench);
debug!("Benchmarks raw {:?}", benchmarks);
info!("{}", benchmarks.summary());
}
/// Prints the opening title of RustScan
fn print_opening() {
info!("Printing opening");
fn print_opening(opts: &Opts) {
debug!("Printing opening");
let s = r#".----. .-. .-. .----..---. .----. .---. .--. .-. .-.
| {} }| { } |{ {__ {_ _}{ {__ / ___} / {} \ | `| |
| .-. \| {_} |.-._} } | | .-._} }\ }/ /\ \| |\ |
@@ -247,19 +176,17 @@ Faster Nmap scanning with Rust."#;
println!("{}", info.gradient(Color::Yellow).bold());
funny_opening!();
let config_path = match dirs::config_dir() {
Some(mut path) => {
path.push("rustscan");
path.push("config.toml");
path
}
None => panic!("Couldn't find config dir."),
let mut home_dir = match dirs::home_dir() {
Some(dir) => dir,
None => panic!("Could not infer config file path."),
};
home_dir.push(".rustscan.toml");
detail!(format!(
"{} {:?}",
"The config file is expected to be at", config_path
));
detail!(
format!("The config file is expected to be at {:?}", home_dir),
opts.greppable,
opts.accessible
);
}
#[cfg(not(tarpaulin_include))]
fn build_nmap_arguments<'a>(
@@ -282,25 +209,96 @@ fn build_nmap_arguments<'a>(
arguments
}
fn parse_ips(opts: &Opts) -> Vec<IpAddr> {
/// Goes through all possible IP inputs (files or via argparsing)
/// Parses the string(s) into IPs
fn parse_addresses(opts: &Opts) -> Vec<IpAddr> {
let mut ips: Vec<IpAddr> = Vec::new();
let resolver = &Resolver::new(ResolverConfig::default(), ResolverOpts::default()).unwrap();
for ip_or_host in &opts.ips_or_hosts {
match IpAddr::from_str(ip_or_host) {
Ok(ip) => ips.push(ip),
_ => match format!("{}:{}", &ip_or_host, 80).to_socket_addrs() {
Ok(mut iter) => ips.push(iter.nth(0).unwrap().ip()),
for ip_or_host in &opts.addresses {
match read_ips_from_file(ip_or_host.to_owned(), &resolver) {
Ok(x) => ips.extend(x),
_ => match parse_to_ip(ip_or_host.to_owned(), &resolver) {
Ok(x) => ips.extend(x),
_ => {
let failed_to_resolve = format!("Host {:?} could not be resolved.", ip_or_host);
warning!(failed_to_resolve, opts.quiet);
warning!(
format!("Host {:?} could not be resolved.", ip_or_host),
opts.greppable,
opts.accessible
);
}
},
}
}
ips
}
/// Uses DNS to get the IPS assiocated with host
fn resolve_ips_from_host(
source: &String,
resolver: &Resolver,
) -> Result<Vec<IpAddr>, std::io::Error> {
let mut ips: Vec<std::net::IpAddr> = Vec::new();
match resolver.lookup_ip(&source) {
Ok(x) => {
for ip in x.iter() {
ips.push(ip);
}
}
_ => (),
};
return Ok(ips);
}
#[cfg(not(tarpaulin_include))]
/// Parses an input file of IPs and uses those
fn read_ips_from_file(
ips: String,
resolver: &Resolver,
) -> Result<Vec<std::net::IpAddr>, std::io::Error> {
// if we cannot open it as a file, it is not a file so move on
let file = File::open(ips)?;
let reader = BufReader::new(file);
let mut ips: Vec<std::net::IpAddr> = Vec::new();
for str_ip in reader.lines() {
match str_ip {
Ok(x) => match parse_to_ip(x, resolver) {
Ok(result) => ips.extend(result),
Err(e) => {
debug!("{} is not a valid IP or host", e);
}
},
Err(_) => {
debug!("Line in file is not valid");
}
}
}
Ok(ips)
}
/// Given a string, parse it as an host, IP address, or CIDR.
/// This allows us to pass files as hosts or cidr or IPs easily
/// Call this everytime you have a possible IP_or_host
fn parse_to_ip(address: String, resolver: &Resolver) -> Result<Vec<IpAddr>, std::io::Error> {
let mut ips: Vec<IpAddr> = Vec::new();
match IpCidr::from_str(&address) {
Ok(cidr) => cidr.iter().for_each(|ip| ips.push(ip)),
_ => match format!("{}:{}", &address, 80).to_socket_addrs() {
Ok(mut iter) => ips.push(iter.nth(0).unwrap().ip()),
_ => match resolve_ips_from_host(&address, resolver) {
Ok(hosts) => ips.extend(hosts),
_ => (),
},
},
};
Ok(ips)
}
fn adjust_ulimit_size(opts: &Opts) -> rlimit::rlim {
if opts.ulimit.is_some() {
let limit: rlimit::rlim = opts.ulimit.unwrap();
@@ -309,10 +307,17 @@ fn adjust_ulimit_size(opts: &Opts) -> rlimit::rlim {
Ok(_) => {
detail!(
format!("Automatically increasing ulimit value to {}.", limit),
opts.quiet
opts.greppable,
opts.accessible
);
}
Err(_) => {
warning!(
"ERROR. Failed to set ulimit value.",
opts.greppable,
opts.accessible
);
}
Err(_) => println!("{}", "ERROR. Failed to set ulimit value."),
}
}
@@ -326,8 +331,8 @@ fn infer_batch_size(opts: &Opts, ulimit: rlimit::rlim) -> u16 {
// Adjust the batch size when the ulimit value is lower than the desired batch size
if ulimit < batch_size {
warning!("File limit is lower than default batch size. Consider upping with --ulimt. May cause harm to sensitive servers",
opts.quiet
warning!("File limit is lower than default batch size. Consider upping with --ulimit. May cause harm to sensitive servers",
opts.greppable, opts.accessible
);
// When the OS supports high file limits like 8000, but the user
@@ -337,7 +342,7 @@ fn infer_batch_size(opts: &Opts, ulimit: rlimit::rlim) -> u16 {
// ulimit is smaller than aveage batch size
// user must have very small ulimit
// decrease batch size to half of ulimit
warning!("Your file limit is very small, which negatively impacts RustScan's speed. Use the Docker image, or up the Ulimit with '--ulimit 5000'. ");
warning!("Your file limit is very small, which negatively impacts RustScan's speed. Use the Docker image, or up the Ulimit with '--ulimit 5000'. ", opts.greppable, opts.accessible);
info!("Halving batch_size because ulimit is smaller than average batch size");
batch_size = ulimit / 2
} else if ulimit > DEFAULT_FILE_DESCRIPTORS_LIMIT {
@@ -350,10 +355,8 @@ fn infer_batch_size(opts: &Opts, ulimit: rlimit::rlim) -> u16 {
// When the ulimit is higher than the batch size let the user know that the
// batch size can be increased unless they specified the ulimit themselves.
else if ulimit + 2 > batch_size && (opts.ulimit.is_none()) {
detail!(format!(
"File limit higher than batch size. Can increase speed by increasing batch size '-b {}'.",
ulimit - 100
), opts.quiet);
detail!(format!("File limit higher than batch size. Can increase speed by increasing batch size '-b {}'.", ulimit - 100),
opts.greppable, opts.accessible);
}
batch_size as u16
@@ -361,41 +364,22 @@ fn infer_batch_size(opts: &Opts, ulimit: rlimit::rlim) -> u16 {
#[cfg(test)]
mod tests {
use crate::{adjust_ulimit_size, infer_batch_size, parse_ips, print_opening, Opts, ScanOrder};
use crate::{adjust_ulimit_size, infer_batch_size, parse_addresses, print_opening, Opts};
use std::net::Ipv4Addr;
#[test]
fn batch_size_lowered() {
let opts = Opts {
ips_or_hosts: vec!["127.0.0.1".to_owned()],
ports: None,
range: None,
quiet: true,
batch_size: 50_000,
timeout: 1_000,
ulimit: Some(2_000),
command: Vec::new(),
accessible: false,
scan_order: ScanOrder::Serial,
};
let mut opts = Opts::default();
opts.batch_size = 50_000;
let batch_size = infer_batch_size(&opts, 120);
assert!(batch_size < 50_000);
assert!(batch_size < opts.batch_size);
}
#[test]
fn batch_size_lowered_average_size() {
let opts = Opts {
ips_or_hosts: vec!["127.0.0.1".to_owned()],
ports: None,
range: None,
quiet: true,
batch_size: 50_000,
timeout: 1_000,
ulimit: Some(2_000),
command: Vec::new(),
accessible: false,
scan_order: ScanOrder::Serial,
};
let mut opts = Opts::default();
opts.batch_size = 50_000;
let batch_size = infer_batch_size(&opts, 9_000);
assert!(batch_size == 3_000);
@@ -404,18 +388,8 @@ mod tests {
fn batch_size_equals_ulimit_lowered() {
// because ulimit and batch size are same size, batch size is lowered
// to ULIMIT - 100
let opts = Opts {
ips_or_hosts: vec!["127.0.0.1".to_owned()],
ports: None,
range: None,
quiet: true,
batch_size: 50_000,
timeout: 1_000,
ulimit: Some(2_000),
command: Vec::new(),
accessible: false,
scan_order: ScanOrder::Serial,
};
let mut opts = Opts::default();
opts.batch_size = 50_000;
let batch_size = infer_batch_size(&opts, 5_000);
assert!(batch_size == 4_900);
@@ -423,102 +397,82 @@ mod tests {
#[test]
fn batch_size_adjusted_2000() {
// ulimit == batch_size
let opts = Opts {
ips_or_hosts: vec!["127.0.0.1".to_owned()],
ports: None,
range: None,
quiet: true,
batch_size: 50_000,
timeout: 1_000,
ulimit: Some(2_000),
command: Vec::new(),
accessible: false,
scan_order: ScanOrder::Serial,
};
let mut opts = Opts::default();
opts.batch_size = 50_000;
opts.ulimit = Some(2_000);
let batch_size = adjust_ulimit_size(&opts);
assert!(batch_size == 2_000);
}
#[test]
fn test_print_opening_no_panic() {
let mut opts = Opts::default();
opts.ulimit = Some(2_000);
// print opening should not panic
print_opening();
print_opening(&opts);
assert!(1 == 1);
}
#[test]
fn test_high_ulimit_no_quiet_mode() {
let opts = Opts {
ips_or_hosts: vec!["127.0.0.1".to_owned()],
ports: None,
range: None,
quiet: false,
batch_size: 10,
timeout: 1_000,
ulimit: None,
command: Vec::new(),
accessible: true,
scan_order: ScanOrder::Serial,
};
fn test_high_ulimit_no_greppable_mode() {
let mut opts = Opts::default();
opts.batch_size = 10;
opts.greppable = false;
infer_batch_size(&opts, 1_000_000);
let batch_size = infer_batch_size(&opts, 1_000_000);
assert!(1 == 1);
assert!(batch_size == opts.batch_size);
}
#[test]
fn parse_correct_ips_or_hosts() {
let opts = Opts {
ips_or_hosts: vec!["127.0.0.1".to_owned(), "google.com".to_owned()],
ports: None,
range: None,
quiet: true,
batch_size: 10,
timeout: 1_000,
ulimit: Some(2_000),
command: Vec::new(),
accessible: false,
scan_order: ScanOrder::Serial,
};
let ips = parse_ips(&opts);
fn parse_correct_addresses() {
let mut opts = Opts::default();
opts.addresses = vec!["127.0.0.1".to_owned(), "192.168.0.0/30".to_owned()];
let ips = parse_addresses(&opts);
assert_eq!(2, ips.len());
assert_eq!(
ips,
[
Ipv4Addr::new(127, 0, 0, 1),
Ipv4Addr::new(192, 168, 0, 0),
Ipv4Addr::new(192, 168, 0, 1),
Ipv4Addr::new(192, 168, 0, 2),
Ipv4Addr::new(192, 168, 0, 3)
]
);
}
#[test]
fn parse_correct_and_incorrect_ips_or_hosts() {
let opts = Opts {
ips_or_hosts: vec!["127.0.0.1".to_owned(), "im_wrong".to_owned()],
ports: None,
range: None,
quiet: true,
batch_size: 10,
timeout: 1_000,
ulimit: Some(2_000),
command: Vec::new(),
accessible: false,
scan_order: ScanOrder::Serial,
};
let ips = parse_ips(&opts);
fn parse_correct_host_addresses() {
let mut opts = Opts::default();
opts.addresses = vec!["google.com".to_owned()];
let ips = parse_addresses(&opts);
assert_eq!(1, ips.len());
assert_eq!(ips.len(), 1);
}
#[test]
fn parse_incorrect_ips_or_hosts() {
let opts = Opts {
ips_or_hosts: vec!["im_wrong".to_owned(), "300.10.1.1".to_owned()],
ports: None,
range: None,
quiet: true,
batch_size: 10,
timeout: 1_000,
ulimit: Some(2_000),
command: Vec::new(),
accessible: false,
scan_order: ScanOrder::Serial,
};
let ips = parse_ips(&opts);
fn parse_correct_and_incorrect_addresses() {
let mut opts = Opts::default();
opts.addresses = vec!["127.0.0.1".to_owned(), "im_wrong".to_owned()];
let ips = parse_addresses(&opts);
assert_eq!(0, ips.len());
assert_eq!(ips, [Ipv4Addr::new(127, 0, 0, 1),]);
}
#[test]
fn parse_incorrect_addresses() {
let mut opts = Opts::default();
opts.addresses = vec!["im_wrong".to_owned(), "300.10.1.1".to_owned()];
let ips = parse_addresses(&opts);
assert_eq!(ips.is_empty(), true);
}
#[test]
fn parse_hosts_file_and_incorrect_hosts() {
// Host file contains IP, Hosts, incorrect IPs, incorrect hosts
let mut opts = Opts::default();
opts.addresses = vec!["fixtures/hosts.txt".to_owned()];
let ips = parse_addresses(&opts);
assert_eq!(ips.len(), 3);
}
}
+34 -24
View File
@@ -1,11 +1,14 @@
mod range_iterator;
use super::{PortRange, ScanOrder};
use rand::seq::SliceRandom;
use rand::thread_rng;
use range_iterator::RangeIterator;
/// Represents options of port scanning.
///
/// Right now all these options involve ranges, but in the future
/// it will also contain custom lists of ports.
#[derive(Debug)]
pub enum PortStrategy {
Manual(Vec<u16>),
Serial(SerialRange),
@@ -15,26 +18,27 @@ pub enum PortStrategy {
impl PortStrategy {
pub fn pick(range: Option<PortRange>, ports: Option<Vec<u16>>, order: ScanOrder) -> Self {
match order {
ScanOrder::Serial => match ports.is_none() {
true => {
let range = range.as_ref().unwrap();
PortStrategy::Serial(SerialRange {
start: range.start,
end: range.end,
})
}
false => PortStrategy::Manual(ports.unwrap()),
},
ScanOrder::Random => match ports.is_none() {
true => {
let range = range.as_ref().unwrap();
PortStrategy::Random(RandomRange {
start: range.start,
end: range.end,
})
}
false => PortStrategy::Manual(ports.unwrap()),
},
ScanOrder::Serial if ports.is_none() => {
let range = range.as_ref().unwrap();
PortStrategy::Serial(SerialRange {
start: range.start,
end: range.end,
})
}
ScanOrder::Random if ports.is_none() => {
let range = range.as_ref().unwrap();
PortStrategy::Random(RandomRange {
start: range.start,
end: range.end,
})
}
ScanOrder::Serial => PortStrategy::Manual(ports.unwrap()),
ScanOrder::Random => {
let mut rng = thread_rng();
let mut ports = ports.unwrap();
ports.shuffle(&mut rng);
PortStrategy::Manual(ports)
}
}
}
@@ -55,6 +59,7 @@ trait RangeOrder {
/// As the name implies SerialRange will always generate a vector in
/// ascending order.
#[derive(Debug)]
pub struct SerialRange {
start: u16,
end: u16,
@@ -68,6 +73,7 @@ impl RangeOrder for SerialRange {
/// As the name implies RandomRange will always generate a vector with
/// a random order. This vector is built following the LCG algorithm.
#[derive(Debug)]
pub struct RandomRange {
start: u16,
end: u16,
@@ -121,9 +127,13 @@ mod tests {
}
#[test]
fn random_strategy_with_ports_does_not_randomize_ports() {
let strategy = PortStrategy::pick(None, Some(vec![80, 443]), ScanOrder::Random);
let result = strategy.order();
assert_eq!(vec![80, 443], result);
fn random_strategy_with_ports() {
let strategy = PortStrategy::pick(None, Some((1..10).collect()), ScanOrder::Random);
let mut result = strategy.order();
let expected_range = (1..10).into_iter().collect::<Vec<u16>>();
assert_ne!(expected_range, result);
result.sort();
assert_eq!(expected_range, result);
}
}
+99 -32
View File
@@ -1,14 +1,17 @@
use super::PortStrategy;
mod socket_iterator;
use socket_iterator::SocketIterator;
use async_std::io;
use async_std::net::TcpStream;
use async_std::prelude::*;
use colored::*;
use futures::stream::FuturesUnordered;
use std::time::Duration;
use std::{
io::ErrorKind,
net::{IpAddr, Shutdown, SocketAddr},
time::Duration,
};
/// The class for the scanner
@@ -18,12 +21,14 @@ use std::{
/// Timeout is the time RustScan should wait before declaring a port closed. As datatype Duration.
/// Quiet is whether or not RustScan should print things, or wait until the end to print only open ports.
#[cfg(not(tarpaulin_include))]
#[derive(Debug)]
pub struct Scanner {
ips: Vec<IpAddr>,
batch_size: u16,
timeout: Duration,
quiet: bool,
greppable: bool,
port_strategy: PortStrategy,
accessible: bool,
}
impl Scanner {
@@ -31,15 +36,17 @@ impl Scanner {
ips: &[IpAddr],
batch_size: u16,
timeout: Duration,
quiet: bool,
greppable: bool,
port_strategy: PortStrategy,
accessible: bool,
) -> Self {
Self {
batch_size,
timeout,
quiet,
greppable,
port_strategy,
ips: ips.iter().map(|ip| ip.to_owned()).collect(),
accessible,
}
}
@@ -48,35 +55,35 @@ impl Scanner {
/// Returns all open ports as Vec<u16>
pub async fn run(&self) -> Vec<SocketAddr> {
let ports: Vec<u16> = self.port_strategy.order();
let batch_per_ip: usize = self.batch_size as usize / self.ips.len();
let mut socket_iterator: SocketIterator = SocketIterator::new(&self.ips, &ports);
let mut open_sockets: Vec<SocketAddr> = Vec::new();
for batch in ports.chunks(batch_per_ip) {
let mut sockets = self.scan_ports(batch).await;
open_sockets.append(&mut sockets);
}
open_sockets
}
/// Given a slice of sockets, scan them all.
/// Returns a vector of open sockets.
async fn scan_ports(&self, ports: &[u16]) -> Vec<SocketAddr> {
let mut ftrs = FuturesUnordered::new();
for port in ports {
for ip in &self.ips {
ftrs.push(self.scan_socket(SocketAddr::new(*ip, *port)));
for _ in 0..self.batch_size {
if let Some(socket) = socket_iterator.next() {
ftrs.push(self.scan_socket(socket));
} else {
break;
}
}
let mut open_sockets: Vec<SocketAddr> = Vec::new();
debug!("Start scanning sockets. \nBatch size {}\nNumber of ip-s {}\nNumber of ports {}\nTargets all together {} ",
self.batch_size,
self.ips.len(),
&ports.len(),
(self.ips.len() * &ports.len()));
while let Some(result) = ftrs.next().await {
if let Some(socket) = socket_iterator.next() {
ftrs.push(self.scan_socket(socket));
}
match result {
Ok(socket) => open_sockets.push(socket),
_ => {}
}
}
debug!("Open Sockets found: {:?}", &open_sockets);
open_sockets
}
@@ -95,20 +102,35 @@ impl Scanner {
async fn scan_socket(&self, socket: SocketAddr) -> io::Result<SocketAddr> {
match self.connect(socket).await {
Ok(x) => {
// match stream_result.shutdown(Shutdown::Both)
info!("Shutting down stream");
debug!(
"Connection was successful, shutting down stream {}",
&socket
);
match x.shutdown(Shutdown::Both) {
Err(e) => debug!("Shutdown stream error {}", &e),
_ => {}
}
if !self.quiet {
println!("Open {}", socket.to_string().purple());
if !self.greppable {
if self.accessible {
println!("Open {}", socket.to_string());
} else {
println!("Open {}", socket.to_string().purple());
}
}
Ok(socket)
}
Err(e) => match e.kind() {
ErrorKind::Other => {
panic!("Too many open files. Please reduce batch size. The default is 5000. Try -b 2500.");
if e.to_string().contains("No route to host")
|| e.to_string().contains("Network is unreachable")
{
debug!("Socket connect error: {} {}", &e.to_string(), &socket);
Err(io::Error::new(io::ErrorKind::Other, e.to_string()))
} else {
debug!("Socket connect error: {} {}", &e.to_string(), &socket);
panic!("Too many open files. Please reduce batch size. The default is 5000. Try -b 2500.");
}
}
_ => Err(io::Error::new(io::ErrorKind::Other, e.to_string())),
},
@@ -152,7 +174,7 @@ mod tests {
end: 1_000,
};
let strategy = PortStrategy::pick(Some(range), None, ScanOrder::Random);
let scanner = Scanner::new(&addrs, 10, Duration::from_millis(100), true, strategy);
let scanner = Scanner::new(&addrs, 10, Duration::from_millis(100), true, strategy, true);
block_on(scanner.run());
// if the scan fails, it wouldn't be able to assert_eq! as it panicked!
assert_eq!(1, 1);
@@ -166,7 +188,7 @@ mod tests {
end: 1_000,
};
let strategy = PortStrategy::pick(Some(range), None, ScanOrder::Random);
let scanner = Scanner::new(&addrs, 10, Duration::from_millis(100), true, strategy);
let scanner = Scanner::new(&addrs, 10, Duration::from_millis(100), true, strategy, true);
block_on(scanner.run());
// if the scan fails, it wouldn't be able to assert_eq! as it panicked!
assert_eq!(1, 1);
@@ -179,7 +201,7 @@ mod tests {
end: 1_000,
};
let strategy = PortStrategy::pick(Some(range), None, ScanOrder::Random);
let scanner = Scanner::new(&addrs, 10, Duration::from_millis(100), true, strategy);
let scanner = Scanner::new(&addrs, 10, Duration::from_millis(100), true, strategy, true);
block_on(scanner.run());
assert_eq!(1, 1);
}
@@ -191,7 +213,7 @@ mod tests {
end: 445,
};
let strategy = PortStrategy::pick(Some(range), None, ScanOrder::Random);
let scanner = Scanner::new(&addrs, 10, Duration::from_millis(100), true, strategy);
let scanner = Scanner::new(&addrs, 10, Duration::from_millis(100), true, strategy, true);
block_on(scanner.run());
assert_eq!(1, 1);
}
@@ -206,7 +228,52 @@ mod tests {
end: 600,
};
let strategy = PortStrategy::pick(Some(range), None, ScanOrder::Random);
let scanner = Scanner::new(&addrs, 10, Duration::from_millis(100), true, strategy);
let scanner = Scanner::new(&addrs, 10, Duration::from_millis(100), true, strategy, true);
block_on(scanner.run());
assert_eq!(1, 1);
}
#[test]
fn scanner_runs_serial() {
let addrs = vec!["8.8.8.8".parse::<IpAddr>().unwrap()];
let range = PortRange {
start: 400,
end: 600,
};
let strategy = PortStrategy::pick(Some(range), None, ScanOrder::Serial);
let scanner = Scanner::new(&addrs, 10, Duration::from_millis(100), true, strategy, true);
block_on(scanner.run());
assert_eq!(1, 1);
}
#[test]
fn scanner_doesnt_run_no_range() {
let addrs = vec!["8.8.8.8".parse::<IpAddr>().unwrap()];
let range = PortRange { start: 0, end: 0 };
let strategy = PortStrategy::pick(Some(range), None, ScanOrder::Serial);
let scanner = Scanner::new(&addrs, 10, Duration::from_millis(100), true, strategy, true);
block_on(scanner.run());
assert_eq!(1, 1);
}
#[test]
fn scanner_doesnt_run_high_range() {
let addrs = vec!["127.0.0.1".parse::<IpAddr>().unwrap()];
let range = PortRange {
start: 1,
end: 65535,
};
let strategy = PortStrategy::pick(Some(range), None, ScanOrder::Serial);
let scanner = Scanner::new(&addrs, 10, Duration::from_millis(100), true, strategy, true);
block_on(scanner.run());
assert_eq!(1, 1);
}
#[test]
fn scanner_doesnt_run_backwards_range() {
let addrs = vec!["127.0.0.1".parse::<IpAddr>().unwrap()];
let range = PortRange { start: 10, end: 1 };
let strategy = PortStrategy::pick(Some(range), None, ScanOrder::Serial);
let scanner = Scanner::new(&addrs, 10, Duration::from_millis(100), true, strategy, true);
block_on(scanner.run());
assert_eq!(1, 1);
}
+75
View File
@@ -0,0 +1,75 @@
use itertools::{iproduct, Product};
use std::net::{IpAddr, SocketAddr};
pub struct SocketIterator<'s> {
// product_it is a cartesian product iterator over
// the slices of ports and IP addresses.
//
// The IP/port order is intentionally reversed here since we want
// the itertools::iproduct! macro below to generate the pairs with
// all the IPs for one port before moving on to the next one
// ("hold the port, go through all the IPs, then advance the port...").
// See also the comments in the iterator implementation for an example.
product_it:
Product<Box<std::slice::Iter<'s, u16>>, Box<std::slice::Iter<'s, std::net::IpAddr>>>,
}
/// An iterator that receives a slice of IPs and ports and returns a Socket
/// for each IP and port pair until all of these combinations are exhausted.
/// The goal of this iterator is to go over every IP and port combination
/// wihout generating a big memory footprint. The alternative would be
/// generating a vector containing all these combinations.
impl<'s> SocketIterator<'s> {
pub fn new(ips: &'s [IpAddr], ports: &'s [u16]) -> Self {
let ports_it = Box::new(ports.into_iter());
let ips_it = Box::new(ips.into_iter());
Self {
product_it: iproduct!(ports_it, ips_it),
}
}
}
impl<'s> Iterator for SocketIterator<'s> {
type Item = SocketAddr;
/// Returns a socket based on the combination of one of the provided
/// IPs and ports or None when these combinations are exhausted. Every
/// IP will have the same port until a port is incremented.
///
/// let it = SocketIterator::new(&["127.0.0.1", "192.168.0.1"], &[80, 443]);
/// it.next(); // 127.0.0.1:80
/// it.next(); // 192.168.0.1:80
/// it.next(); // 127.0.0.1:443
/// it.next(); // 192.168.0.1:443
/// it.next(); // None
fn next(&mut self) -> Option<Self::Item> {
match self.product_it.next() {
None => None,
Some((port, ip)) => Some(SocketAddr::new(*ip, *port)),
}
}
}
#[cfg(test)]
mod tests {
use super::SocketIterator;
use std::net::{IpAddr, SocketAddr};
#[test]
fn goes_through_every_ip_port_combination() {
let addrs = vec![
"127.0.0.1".parse::<IpAddr>().unwrap(),
"192.168.0.1".parse::<IpAddr>().unwrap(),
];
let ports: Vec<u16> = vec![22, 80, 443];
let mut it = SocketIterator::new(&addrs, &ports);
assert_eq!(Some(SocketAddr::new(addrs[0], ports[0])), it.next());
assert_eq!(Some(SocketAddr::new(addrs[1], ports[0])), it.next());
assert_eq!(Some(SocketAddr::new(addrs[0], ports[1])), it.next());
assert_eq!(Some(SocketAddr::new(addrs[1], ports[1])), it.next());
assert_eq!(Some(SocketAddr::new(addrs[0], ports[2])), it.next());
assert_eq!(Some(SocketAddr::new(addrs[1], ports[2])), it.next());
assert_eq!(None, it.next());
}
}
+30 -13
View File
@@ -7,11 +7,16 @@ macro_rules! warning {
use ansi_term::Colour::Red;
println!("{} {}", Red.bold().paint("[!]"), $name);
};
// quiet mode
($name:expr, $quiet:expr) => {
($name:expr, $greppable:expr, $accessible:expr) => {
use ansi_term::Colour::Red;
if !$quiet {
println!("{} {}", Red.bold().paint("[!]"), $name);
// if not greppable then print, otherwise no else statement so do not print.
if !$greppable {
if $accessible {
// Don't print the ascii art
println!("{}", $name);
} else {
println!("{} {}", Red.bold().paint("[!]"), $name);
}
}
};
}
@@ -22,26 +27,38 @@ macro_rules! detail {
use ansi_term::Colour::Blue;
println!("{} {}", Blue.bold().paint("[~]"), $name);
};
($name:expr, $quiet:expr) => {
($name:expr, $greppable:expr, $accessible:expr) => {
use ansi_term::Colour::Blue;
if !$quiet {
println!("{} {}", Blue.bold().paint("[~]"), $name);
// if not greppable then print, otherwise no else statement so do not print.
if !$greppable {
if $accessible {
// Don't print the ascii art
println!("{}", $name);
} else {
println!("{} {}", Blue.bold().paint("[~]"), $name);
}
}
};
}
#[macro_export]
macro_rules! output {
($name:expr, $quiet:expr) => {
use ansi_term::Colour::RGB;
if !$quiet {
println!("{} {}", RGB(0, 255, 9).bold().paint("[>]"), $name);
}
};
($name:expr) => {
use ansi_term::Colour::RGB;
println!("{} {}", RGB(0, 255, 9).bold().paint("[>]"), $name);
};
($name:expr, $greppable:expr, $accessible:expr) => {
use ansi_term::Colour::RGB;
// if not greppable then print, otherwise no else statement so do not print.
if !$greppable {
if $accessible {
// Don't print the ascii art
println!("{}", $name);
} else {
println!("{} {}", RGB(0, 255, 9).bold().paint("[>]"), $name);
}
}
};
}
#[macro_export]