mirror of
https://github.com/epi052/feroxbuster.git
synced 2026-05-22 12:11:13 -03:00
Compare commits
313 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b1f5ed507b | ||
|
|
79edc42b17 | ||
|
|
1b223b0867 | ||
|
|
0c6d5193a9 | ||
|
|
c637355796 | ||
|
|
a114cc8f85 | ||
|
|
c8503faf02 | ||
|
|
cbbd642510 | ||
|
|
2c8e9bace9 | ||
|
|
f4fe8c0544 | ||
|
|
73109483fe | ||
|
|
aee33012b1 | ||
|
|
eab95e0435 | ||
|
|
acb2f42f69 | ||
|
|
ac20b213ec | ||
|
|
201873d7ac | ||
|
|
9678b8f31c | ||
|
|
20a826fc0f | ||
|
|
56b78a4e04 | ||
|
|
4b6bf3645d | ||
|
|
6fd201b717 | ||
|
|
5f39d71fe8 | ||
|
|
c23850208b | ||
|
|
d5605efb08 | ||
|
|
5b8d3f5661 | ||
|
|
ce7f3b79b8 | ||
|
|
c9c63bebd0 | ||
|
|
1f60e06247 | ||
|
|
04e3ad69cc | ||
|
|
fd5b1f6f25 | ||
|
|
a9dde3f7e1 | ||
|
|
7a9ee39941 | ||
|
|
6befae1a93 | ||
|
|
e6b422b92a | ||
|
|
fb4bfa27fd | ||
|
|
2795ec4e72 | ||
|
|
e9d283bc59 | ||
|
|
3a128df2fc | ||
|
|
38f1b917c4 | ||
|
|
afa7d6804c | ||
|
|
28c3e25eeb | ||
|
|
55e22467ce | ||
|
|
bbfaddaedd | ||
|
|
53e3420efd | ||
|
|
d390bbc12d | ||
|
|
0c3b91855a | ||
|
|
48f5362f5f | ||
|
|
24514faf9e | ||
|
|
a424057166 | ||
|
|
7d483b6edd | ||
|
|
1a717e878d | ||
|
|
e35a6dda9f | ||
|
|
f3b2193b2f | ||
|
|
07a7ac652e | ||
|
|
f51993cde0 | ||
|
|
9093ffb92a | ||
|
|
d550448229 | ||
|
|
492665154e | ||
|
|
c14e617076 | ||
|
|
6bb748af17 | ||
|
|
863ea089cc | ||
|
|
ad3091a7db | ||
|
|
b2bdea71dd | ||
|
|
f478700b86 | ||
|
|
1f2aad5e52 | ||
|
|
3a6a61cc24 | ||
|
|
0311a846b3 | ||
|
|
3066efa848 | ||
|
|
a8fae65d63 | ||
|
|
970886a68b | ||
|
|
494eed81e8 | ||
|
|
c8a577b1e7 | ||
|
|
ccb10c1c68 | ||
|
|
20ab0aade3 | ||
|
|
02ad0b1d85 | ||
|
|
09aad922c1 | ||
|
|
697f947bfa | ||
|
|
d300d68737 | ||
|
|
c2c6854db4 | ||
|
|
63be575d89 | ||
|
|
0d25fda11e | ||
|
|
b0341c2432 | ||
|
|
62352db152 | ||
|
|
3090edc49c | ||
|
|
85d686d1aa | ||
|
|
17138f4ef7 | ||
|
|
1d30b7db31 | ||
|
|
4c0d3c91a0 | ||
|
|
96fc6b232a | ||
|
|
9b306aad34 | ||
|
|
10eee184d0 | ||
|
|
986161f05f | ||
|
|
4a19dbfd7d | ||
|
|
b8ceeaff0f | ||
|
|
d04e58036e | ||
|
|
d1a74207f4 | ||
|
|
03a36f0b60 | ||
|
|
f2d9269643 | ||
|
|
bba7cba02e | ||
|
|
fffd1e5c82 | ||
|
|
3c6da0f782 | ||
|
|
5ecd937c0e | ||
|
|
9f6221daf6 | ||
|
|
af49fd8e62 | ||
|
|
d1daefd8ba | ||
|
|
3e8255d5b7 | ||
|
|
5af18e83d8 | ||
|
|
d1d0757d56 | ||
|
|
f5f9344a81 | ||
|
|
fd52e39188 | ||
|
|
22377dc9a3 | ||
|
|
1cf7dff734 | ||
|
|
7c9eb900b7 | ||
|
|
8480b3cc2c | ||
|
|
9d29142046 | ||
|
|
38c194b222 | ||
|
|
72dc14bf3d | ||
|
|
9a7c690c17 | ||
|
|
de4514e381 | ||
|
|
2be8aaf2bf | ||
|
|
4db3a0b056 | ||
|
|
a9ef7f180f | ||
|
|
ac7cb5d6b6 | ||
|
|
f8e18abb48 | ||
|
|
1d805aca5a | ||
|
|
fa09266804 | ||
|
|
15592c3dfd | ||
|
|
53c171aeb5 | ||
|
|
5167d24c4b | ||
|
|
81ff62c53d | ||
|
|
433f68458e | ||
|
|
d32720a90a | ||
|
|
0ceef975e6 | ||
|
|
6d7d6c4e7b | ||
|
|
5f21953bc1 | ||
|
|
6906ac0ee8 | ||
|
|
cafe766d9e | ||
|
|
98d0d177df | ||
|
|
23e10833d0 | ||
|
|
7f51d0f7bf | ||
|
|
9515a5da99 | ||
|
|
b417ab41a5 | ||
|
|
b946565c2f | ||
|
|
714b054360 | ||
|
|
30544eaf7d | ||
|
|
99e2d46aa2 | ||
|
|
82a4f16252 | ||
|
|
6e0fe1eced | ||
|
|
1ffc93a337 | ||
|
|
7ab0453eb7 | ||
|
|
50b29a2b74 | ||
|
|
bf78fea926 | ||
|
|
56267726cc | ||
|
|
01844cffd8 | ||
|
|
2abc0b78ee | ||
|
|
fdb8774bfd | ||
|
|
8d3cd2471b | ||
|
|
da22371c87 | ||
|
|
ca494ca801 | ||
|
|
376804aa59 | ||
|
|
56a769c197 | ||
|
|
9922eb5124 | ||
|
|
7a58f8fcf8 | ||
|
|
8d1872fb3f | ||
|
|
e1e59e6e8e | ||
|
|
0c731c3639 | ||
|
|
b456215a00 | ||
|
|
d38c66f290 | ||
|
|
6ba32d926c | ||
|
|
86bcfd8fb1 | ||
|
|
4a101e4ae5 | ||
|
|
1ae1430a11 | ||
|
|
cca3163baf | ||
|
|
c9013edce8 | ||
|
|
7bdb137fd1 | ||
|
|
5f0eaf8885 | ||
|
|
2b7002d9cf | ||
|
|
86b17f226d | ||
|
|
cbbf9be6c9 | ||
|
|
f814c4b223 | ||
|
|
7839118379 | ||
|
|
8214a2a357 | ||
|
|
e06e194f77 | ||
|
|
1628ee86a3 | ||
|
|
53d2076176 | ||
|
|
304750fa3f | ||
|
|
6c5c812784 | ||
|
|
063e7b0420 | ||
|
|
eed59e1da5 | ||
|
|
ca4d8f0c52 | ||
|
|
c1132622cf | ||
|
|
2d5aeb444e | ||
|
|
53238a6e5e | ||
|
|
7b7eeeebfa | ||
|
|
aed0c41d8f | ||
|
|
5edd58a3f4 | ||
|
|
44693a3498 | ||
|
|
02448e9834 | ||
|
|
368035833c | ||
|
|
d13bce2261 | ||
|
|
88d451144c | ||
|
|
8d639a17e4 | ||
|
|
7f0dcb6b46 | ||
|
|
3230f9c276 | ||
|
|
b21ea9ce32 | ||
|
|
801413105d | ||
|
|
3030296d1c | ||
|
|
88a595fd82 | ||
|
|
9a84c5234f | ||
|
|
d0d99ebed6 | ||
|
|
7194326cd1 | ||
|
|
71885e7e56 | ||
|
|
13cfbe152e | ||
|
|
8b9d640090 | ||
|
|
007bc4a50d | ||
|
|
71c5b66eb6 | ||
|
|
1498122973 | ||
|
|
c0b4040743 | ||
|
|
3c474920bb | ||
|
|
079b8b2176 | ||
|
|
4a678ef65b | ||
|
|
e9fb9642a8 | ||
|
|
f25475ae4f | ||
|
|
194eec1867 | ||
|
|
d9088be54e | ||
|
|
c0ae120016 | ||
|
|
9d5b339708 | ||
|
|
b7e1876d87 | ||
|
|
4979946471 | ||
|
|
ef5d267500 | ||
|
|
a0208449cd | ||
|
|
bef48a8441 | ||
|
|
1bed84394a | ||
|
|
d66ba9c78a | ||
|
|
b4e8a63429 | ||
|
|
257352e22d | ||
|
|
ed521005b2 | ||
|
|
cbc4da53de | ||
|
|
920ce7ce23 | ||
|
|
1ef5bc288a | ||
|
|
97be0731d9 | ||
|
|
0b42c6a30e | ||
|
|
537d5c69dc | ||
|
|
194d00c073 | ||
|
|
f83195120a | ||
|
|
af2a4dbde0 | ||
|
|
c83a2d8ef2 | ||
|
|
ba96b686ea | ||
|
|
fddade6a11 | ||
|
|
8b97974728 | ||
|
|
ab1861ca2c | ||
|
|
5f241f6034 | ||
|
|
709a787613 | ||
|
|
21f0b95f15 | ||
|
|
36b6e49b87 | ||
|
|
327bdd6e03 | ||
|
|
b1e8023462 | ||
|
|
ae3a43db28 | ||
|
|
e8f4bbccf4 | ||
|
|
7cf834d000 | ||
|
|
1500e651fa | ||
|
|
e5048f0c8d | ||
|
|
d109608e2a | ||
|
|
3e373d1a50 | ||
|
|
46b3989df7 | ||
|
|
cc9467153b | ||
|
|
eb4b074454 | ||
|
|
a07c9432f2 | ||
|
|
1f4dbeaf65 | ||
|
|
1d45325c23 | ||
|
|
216e0e6595 | ||
|
|
dfa0664a16 | ||
|
|
54144dba89 | ||
|
|
18ad9ca733 | ||
|
|
2b58113a2c | ||
|
|
5ed43e8dbd | ||
|
|
82f65e58b7 | ||
|
|
b87836fb45 | ||
|
|
4db5835ea3 | ||
|
|
203108fc2d | ||
|
|
b040113115 | ||
|
|
6158d36279 | ||
|
|
215b76246c | ||
|
|
729c272964 | ||
|
|
43a8b7d7e7 | ||
|
|
94055ec504 | ||
|
|
76a1660329 | ||
|
|
d44ad9ca2d | ||
|
|
8712dee50c | ||
|
|
fc47a6e4e5 | ||
|
|
87c23b2cde | ||
|
|
e3fed0e6ac | ||
|
|
d43da01dab | ||
|
|
47726bc25a | ||
|
|
ec26321e42 | ||
|
|
21c0a7458b | ||
|
|
9950b1381d | ||
|
|
06460bf9da | ||
|
|
701701eea3 | ||
|
|
9a53053112 | ||
|
|
ee69c558a7 | ||
|
|
8f9b757e2d | ||
|
|
777e5628a5 | ||
|
|
4d49401a96 | ||
|
|
03e0d0092d | ||
|
|
21b29a693e | ||
|
|
857ac22266 | ||
|
|
06ca52a19c | ||
|
|
a1ab0b92c5 | ||
|
|
45c2285a65 | ||
|
|
3edab75966 | ||
|
|
2d0e64dec6 | ||
|
|
b8386b7e20 |
@@ -292,6 +292,182 @@
|
||||
"ideas",
|
||||
"code"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "narkopolo",
|
||||
"name": "narkopolo",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/16690056?v=4",
|
||||
"profile": "https://github.com/narkopolo",
|
||||
"contributions": [
|
||||
"ideas"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "justinsteven",
|
||||
"name": "Justin Steven",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/1893909?v=4",
|
||||
"profile": "https://ring0.lol",
|
||||
"contributions": [
|
||||
"ideas"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "7047payloads",
|
||||
"name": "7047payloads",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/95562424?v=4",
|
||||
"profile": "https://github.com/7047payloads",
|
||||
"contributions": [
|
||||
"code"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "unkn0wnsyst3m",
|
||||
"name": "unkn0wnsyst3m",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/21272239?v=4",
|
||||
"profile": "https://github.com/unkn0wnsyst3m",
|
||||
"contributions": [
|
||||
"ideas"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "its0x08",
|
||||
"name": "0x08",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/15280042?v=4",
|
||||
"profile": "https://ironwort.me/",
|
||||
"contributions": [
|
||||
"ideas"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "MD-Levitan",
|
||||
"name": "kusok",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/12116508?v=4",
|
||||
"profile": "https://github.com/MD-Levitan",
|
||||
"contributions": [
|
||||
"ideas",
|
||||
"code"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "godylockz",
|
||||
"name": "godylockz",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/81207744?v=4",
|
||||
"profile": "https://github.com/godylockz",
|
||||
"contributions": [
|
||||
"ideas",
|
||||
"code"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "0dayCTF",
|
||||
"name": "Ryan Montgomery",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/44453666?v=4",
|
||||
"profile": "http://ryanmontgomery.me",
|
||||
"contributions": [
|
||||
"ideas"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "ippsec",
|
||||
"name": "ippsec",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/24677271?v=4",
|
||||
"profile": "https://github.com/IppSec",
|
||||
"contributions": [
|
||||
"ideas"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "gtjamesa",
|
||||
"name": "James",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/2078364?v=4",
|
||||
"profile": "https://github.com/gtjamesa",
|
||||
"contributions": [
|
||||
"bug"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "jhaddix",
|
||||
"name": "Jason Haddix",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/3488554?v=4",
|
||||
"profile": "https://twitter.com/Jhaddix",
|
||||
"contributions": [
|
||||
"ideas",
|
||||
"bug"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "ThisLimn0",
|
||||
"name": "Limn0",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/67125885?v=4",
|
||||
"profile": "https://github.com/ThisLimn0",
|
||||
"contributions": [
|
||||
"bug"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "0xdf223",
|
||||
"name": "0xdf",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/76954092?v=4",
|
||||
"profile": "https://github.com/0xdf223",
|
||||
"contributions": [
|
||||
"bug",
|
||||
"ideas"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "Flangyver",
|
||||
"name": "Flangyver",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/59575870?v=4",
|
||||
"profile": "https://github.com/Flangyver",
|
||||
"contributions": [
|
||||
"ideas"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "DonatoReis",
|
||||
"name": "PeakyBlinder",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/93531354?v=4",
|
||||
"profile": "https://github.com/DonatoReis",
|
||||
"contributions": [
|
||||
"ideas"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "postmodern",
|
||||
"name": "Postmodern",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/12671?v=4",
|
||||
"profile": "https://postmodern.github.io/",
|
||||
"contributions": [
|
||||
"ideas"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "herrcykel",
|
||||
"name": "O",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/1936757?v=4",
|
||||
"profile": "https://github.com/herrcykel",
|
||||
"contributions": [
|
||||
"code"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "udoprog",
|
||||
"name": "John-John Tedro",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/111092?v=4",
|
||||
"profile": "http://udoprog.github.io/",
|
||||
"contributions": [
|
||||
"code"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "kmanc",
|
||||
"name": "kmanc",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/14863147?v=4",
|
||||
"profile": "https://github.com/kmanc",
|
||||
"contributions": [
|
||||
"bug",
|
||||
"code"
|
||||
]
|
||||
}
|
||||
],
|
||||
"contributorsPerLine": 7,
|
||||
@@ -299,5 +475,6 @@
|
||||
"projectOwner": "epi052",
|
||||
"repoType": "github",
|
||||
"repoHost": "https://github.com",
|
||||
"skipCi": true
|
||||
"skipCi": true,
|
||||
"commitConvention": "angular"
|
||||
}
|
||||
|
||||
6
.github/pull_request_template.md
vendored
6
.github/pull_request_template.md
vendored
@@ -16,7 +16,11 @@ Long form explanations of most of the items below can be found in the [CONTRIBUT
|
||||
|
||||
## Documentation
|
||||
- [ ] New code is documented using [doc comments](https://doc.rust-lang.org/stable/rust-by-example/meta/doc.html)
|
||||
- [ ] Documentation about your PR is included in the README, as needed
|
||||
- [ ] Documentation about your PR is included in the `docs`, as needed. The docs live in a [separate repository](https://epi052.github.io/feroxbuster-docs/docs/). Update the appropriate pages at the links below.
|
||||
- [ ] update [example config file section](https://epi052.github.io/feroxbuster-docs/docs/configuration/ferox-config-toml/)
|
||||
- [ ] update [help output section](https://epi052.github.io/feroxbuster-docs/docs/configuration/command-line/)
|
||||
- [ ] add an [example](https://epi052.github.io/feroxbuster-docs/docs/examples/)
|
||||
- [ ] update [comparison table](https://epi052.github.io/feroxbuster-docs/docs/compare/)
|
||||
|
||||
## Additional Tests
|
||||
- [ ] New code is unit tested
|
||||
|
||||
28
.github/workflows/build.yml
vendored
28
.github/workflows/build.yml
vendored
@@ -73,18 +73,22 @@ jobs:
|
||||
name: ${{ matrix.name }}.tar.gz
|
||||
path: ${{ matrix.name }}.tar.gz
|
||||
|
||||
build-deb:
|
||||
needs: [build-nix]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@master
|
||||
- name: Deb Build
|
||||
uses: ebbflow-io/cargo-deb-amd64-ubuntu@1.0
|
||||
- name: Upload Deb Artifact
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: feroxbuster_amd64.deb
|
||||
path: ./target/x86_64-unknown-linux-musl/debian/*
|
||||
# build-deb:
|
||||
# needs: [build-nix]
|
||||
# runs-on: ubuntu-latest
|
||||
# steps:
|
||||
# - uses: actions/checkout@master
|
||||
# - name: Install cargo-deb
|
||||
# run: cargo install -f cargo-deb
|
||||
# - name: Install musl toolchain
|
||||
# run: rustup target add x86_64-unknown-linux-musl
|
||||
# - name: Deb Build
|
||||
# run: cargo deb --target=x86_64-unknown-linux-musl
|
||||
# - name: Upload Deb Artifact
|
||||
# uses: actions/upload-artifact@v2
|
||||
# with:
|
||||
# name: feroxbuster_amd64.deb
|
||||
# path: ./target/x86_64-unknown-linux-musl/debian/*
|
||||
|
||||
build-macos:
|
||||
env:
|
||||
|
||||
32
.github/workflows/check.yml
vendored
32
.github/workflows/check.yml
vendored
@@ -8,11 +8,6 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
profile: minimal
|
||||
toolchain: stable
|
||||
override: true
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: check
|
||||
@@ -22,26 +17,19 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions-rs/toolchain@v1
|
||||
- name: Install latest nextest release
|
||||
uses: taiki-e/install-action@nextest
|
||||
- name: Test with latest nextest release
|
||||
uses: actions-rs/cargo@v1
|
||||
with:
|
||||
profile: minimal
|
||||
toolchain: stable
|
||||
override: true
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: test
|
||||
command: nextest
|
||||
args: run --all-features --all-targets --retries 10
|
||||
|
||||
fmt:
|
||||
name: Rust fmt
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
profile: minimal
|
||||
toolchain: stable
|
||||
override: true
|
||||
- run: rustup component add rustfmt
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: fmt
|
||||
@@ -52,13 +40,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
profile: minimal
|
||||
toolchain: stable
|
||||
override: true
|
||||
- run: rustup component add clippy
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: clippy
|
||||
args: --all-targets --all-features -- -D warnings -A clippy::deref_addrof -A clippy::mutex-atomic
|
||||
args: --all-targets --all-features -- -D warnings
|
||||
|
||||
48
.github/workflows/coverage.yml
vendored
48
.github/workflows/coverage.yml
vendored
@@ -3,42 +3,22 @@ on: [push]
|
||||
name: Code Coverage Pipeline
|
||||
|
||||
jobs:
|
||||
upload-coverage:
|
||||
coverage:
|
||||
name: LLVM Coverage
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: nightly
|
||||
override: true
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: clean
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: test
|
||||
args: --all-features --no-fail-fast
|
||||
env:
|
||||
CARGO_INCREMENTAL: '0'
|
||||
RUSTFLAGS: '-Zprofile -Ccodegen-units=1 -Copt-level=0 -Clink-dead-code -Coverflow-checks=off -Zpanic_abort_tests -Cpanic=abort'
|
||||
RUSTDOCFLAGS: '-Cpanic=abort'
|
||||
- uses: actions-rs/grcov@v0.1
|
||||
- uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: lcov.info
|
||||
path: lcov.info
|
||||
- name: Convert lcov to xml
|
||||
run: |
|
||||
curl -O https://raw.githubusercontent.com/epi052/lcov-to-cobertura-xml/master/lcov_cobertura/lcov_cobertura.py
|
||||
chmod +x lcov_cobertura.py
|
||||
./lcov_cobertura.py ./lcov.info
|
||||
- uses: codecov/codecov-action@v1
|
||||
- uses: actions/checkout@v2
|
||||
- name: Install llvm-tools-preview
|
||||
run: rustup toolchain install stable --component llvm-tools-preview
|
||||
- name: Install cargo-llvm-cov
|
||||
uses: taiki-e/install-action@cargo-llvm-cov
|
||||
- name: Install cargo-nextest
|
||||
uses: taiki-e/install-action@nextest
|
||||
- name: Generate code coverage
|
||||
run: cargo llvm-cov nextest --all-features --no-fail-fast --lcov --output-path lcov.info -- --retries 10
|
||||
- name: Upload coverage to Codecov
|
||||
uses: codecov/codecov-action@v1
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
file: ./coverage.xml
|
||||
name: codecov-umbrella
|
||||
files: lcov.info
|
||||
fail_ci_if_error: true
|
||||
- uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: coverage.xml
|
||||
path: ./coverage.xml
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -9,6 +9,9 @@ target/
|
||||
# jetbrains metadata folder
|
||||
.idea/
|
||||
|
||||
# vscode metadata folder
|
||||
.vscode/
|
||||
|
||||
# personal feroxbuster config for testing
|
||||
ferox-config.toml
|
||||
|
||||
|
||||
@@ -166,7 +166,7 @@ primarily related to continuous integration and release deployment.
|
||||
|
||||
feroxbuster uses the [`clippy`](https://rust-lang.github.io/rust-clippy/) code linter.
|
||||
|
||||
The command that will ultimately be used in the CI pipeline for linting is `cargo clippy --all-targets --all-features -- -D warnings -A clippy::unnecessary_unwrap`.
|
||||
The command that will ultimately be used in the CI pipeline for linting is `cargo clippy --all-targets --all-features -- -D warnings -A clippy::mutex-atomic`.
|
||||
|
||||
Before submitting a Pull Request, the above command should be run. Please do not ignore any linting errors in code you write or modify, as they are meant to **help** by ensuring a clean and simple code base.
|
||||
|
||||
|
||||
1508
Cargo.lock
generated
1508
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
109
Cargo.toml
109
Cargo.toml
@@ -1,14 +1,20 @@
|
||||
[package]
|
||||
name = "feroxbuster"
|
||||
version = "2.4.1"
|
||||
authors = ["Ben 'epi' Risher <epibar052@gmail.com>"]
|
||||
version = "2.7.3"
|
||||
authors = ["Ben 'epi' Risher (@epi052)"]
|
||||
license = "MIT"
|
||||
edition = "2018"
|
||||
edition = "2021"
|
||||
homepage = "https://github.com/epi052/feroxbuster"
|
||||
repository = "https://github.com/epi052/feroxbuster"
|
||||
description = "A fast, simple, recursive content discovery tool."
|
||||
categories = ["command-line-utilities"]
|
||||
keywords = ["pentest", "enumeration", "url-bruteforce", "content-discovery", "web"]
|
||||
keywords = [
|
||||
"pentest",
|
||||
"enumeration",
|
||||
"url-bruteforce",
|
||||
"content-discovery",
|
||||
"web",
|
||||
]
|
||||
exclude = [".github/*", "img/*", "check-coverage.sh"]
|
||||
build = "build.rs"
|
||||
|
||||
@@ -16,43 +22,46 @@ build = "build.rs"
|
||||
maintenance = { status = "actively-developed" }
|
||||
|
||||
[build-dependencies]
|
||||
clap = "2.33"
|
||||
regex = "1"
|
||||
lazy_static = "1.4"
|
||||
dirs = "4.0"
|
||||
clap = { version = "4.0.8", features = ["wrap_help", "cargo"] }
|
||||
clap_complete = "4.0.2"
|
||||
regex = "1.5.5"
|
||||
lazy_static = "1.4.0"
|
||||
dirs = "4.0.0"
|
||||
|
||||
[dependencies]
|
||||
futures = { version = "0.3"}
|
||||
tokio = { version = "1.15", features = ["full"] }
|
||||
tokio-util = {version = "0.6", features = ["codec"]}
|
||||
log = "0.4"
|
||||
env_logger = "0.9"
|
||||
reqwest = { version = "0.11", features = ["socks"] }
|
||||
url = { version = "2.2", features = ["serde"]} # uses feature unification to add 'serde' to reqwest::Url
|
||||
serde_regex = "1.1"
|
||||
clap = "2.34"
|
||||
lazy_static = "1.4"
|
||||
toml = "0.5"
|
||||
serde = { version = "1.0", features = ["derive", "rc"] }
|
||||
serde_json = "1.0"
|
||||
uuid = { version = "0.8", features = ["v4"] }
|
||||
scraper = "0.14.0"
|
||||
futures = "0.3.21"
|
||||
tokio = { version = "1.18.2", features = ["full"] }
|
||||
tokio-util = { version = "0.7.1", features = ["codec"] }
|
||||
log = "0.4.17"
|
||||
env_logger = "0.10.0"
|
||||
reqwest = { version = "0.11.10", features = ["socks"] }
|
||||
# uses feature unification to add 'serde' to reqwest::Url
|
||||
url = { version = "2.2.2", features = ["serde"] }
|
||||
serde_regex = "1.1.0"
|
||||
clap = { version = "4.0.8", features = ["wrap_help", "cargo"] }
|
||||
lazy_static = "1.4.0"
|
||||
toml = "0.5.9"
|
||||
serde = { version = "1.0.137", features = ["derive", "rc"] }
|
||||
serde_json = "1.0.81"
|
||||
uuid = { version = "1.0.0", features = ["v4"] }
|
||||
indicatif = "0.15"
|
||||
console = "0.15"
|
||||
openssl = { version = "0.10", features = ["vendored"] }
|
||||
dirs = "4.0"
|
||||
regex = "1"
|
||||
crossterm = "0.20"
|
||||
rlimit = "0.6"
|
||||
ctrlc = "3.2"
|
||||
console = "0.15.2"
|
||||
openssl = { version = "0.10.40", features = ["vendored"] }
|
||||
dirs = "4.0.0"
|
||||
regex = "1.5.5"
|
||||
crossterm = "0.25.0"
|
||||
rlimit = "0.9.0"
|
||||
ctrlc = "3.2.2"
|
||||
fuzzyhash = "0.2.1"
|
||||
anyhow = "1.0"
|
||||
leaky-bucket = "0.10.0"
|
||||
anyhow = "1.0.57"
|
||||
leaky-bucket = "0.12.1"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3.1"
|
||||
httpmock = "0.6"
|
||||
assert_cmd = "2.0"
|
||||
predicates = "2.1"
|
||||
tempfile = "3.3.0"
|
||||
httpmock = "0.6.6"
|
||||
assert_cmd = "2.0.4"
|
||||
predicates = "2.1.1"
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
@@ -64,9 +73,29 @@ section = "utility"
|
||||
license-file = ["LICENSE", "4"]
|
||||
conf-files = ["/etc/feroxbuster/ferox-config.toml"]
|
||||
assets = [
|
||||
["target/release/feroxbuster", "/usr/bin/", "755"],
|
||||
["ferox-config.toml.example", "/etc/feroxbuster/ferox-config.toml", "644"],
|
||||
["shell_completions/feroxbuster.bash", "/usr/share/bash-completion/completions/feroxbuster.bash", "644"],
|
||||
["shell_completions/feroxbuster.fish", "/usr/share/fish/completions/feroxbuster.fish", "644"],
|
||||
["shell_completions/_feroxbuster", "/usr/share/zsh/vendor-completions/_feroxbuster", "644"],
|
||||
[
|
||||
"target/release/feroxbuster",
|
||||
"/usr/bin/",
|
||||
"755",
|
||||
],
|
||||
[
|
||||
"ferox-config.toml.example",
|
||||
"/etc/feroxbuster/ferox-config.toml",
|
||||
"644",
|
||||
],
|
||||
[
|
||||
"shell_completions/feroxbuster.bash",
|
||||
"/usr/share/bash-completion/completions/feroxbuster.bash",
|
||||
"644",
|
||||
],
|
||||
[
|
||||
"shell_completions/feroxbuster.fish",
|
||||
"/usr/share/fish/completions/feroxbuster.fish",
|
||||
"644",
|
||||
],
|
||||
[
|
||||
"shell_completions/_feroxbuster",
|
||||
"/usr/share/zsh/vendor-completions/_feroxbuster",
|
||||
"644",
|
||||
],
|
||||
]
|
||||
|
||||
25
Makefile.toml
Normal file
25
Makefile.toml
Normal file
@@ -0,0 +1,25 @@
|
||||
# composite tasks
|
||||
[tasks.upgrade]
|
||||
dependencies = ["upgrade-deps", "update"]
|
||||
|
||||
# cleaning
|
||||
[tasks.clean-state]
|
||||
script = """
|
||||
rm ferox-*.state
|
||||
"""
|
||||
|
||||
# dependency management
|
||||
[tasks.upgrade-deps]
|
||||
command = "cargo"
|
||||
args = ["upgrade", "--exclude", "indicatif"]
|
||||
|
||||
[tasks.update]
|
||||
command = "cargo"
|
||||
args = ["update"]
|
||||
|
||||
# clippy / lint
|
||||
[tasks.clippy]
|
||||
clear = true
|
||||
script = """
|
||||
cargo clippy --all-targets --all-features -- -D warnings
|
||||
"""
|
||||
111
README.md
111
README.md
@@ -181,47 +181,74 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
|
||||
<!-- prettier-ignore-start -->
|
||||
<!-- markdownlint-disable -->
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center"><a href="https://io.fi"><img src="https://avatars.githubusercontent.com/u/5235109?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Joona Hoikkala</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/commits?author=joohoi" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/jsav0"><img src="https://avatars.githubusercontent.com/u/20546041?v=4?s=100" width="100px;" alt=""/><br /><sub><b>J Savage</b></sub></a><br /><a href="#infra-jsav0" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="https://github.com/epi052/feroxbuster/commits?author=jsav0" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="http://www.tgotwig.dev"><img src="https://avatars.githubusercontent.com/u/30773779?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Thomas Gotwig</b></sub></a><br /><a href="#infra-TGotwig" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="https://github.com/epi052/feroxbuster/commits?author=TGotwig" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/spikecodes"><img src="https://avatars.githubusercontent.com/u/19519553?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Spike</b></sub></a><br /><a href="#infra-spikecodes" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="https://github.com/epi052/feroxbuster/commits?author=spikecodes" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/evanrichter"><img src="https://avatars.githubusercontent.com/u/330292?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Evan Richter</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/commits?author=evanrichter" title="Code">💻</a> <a href="https://github.com/epi052/feroxbuster/commits?author=evanrichter" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/mzpqnxow"><img src="https://avatars.githubusercontent.com/u/8016228?v=4?s=100" width="100px;" alt=""/><br /><sub><b>AG</b></sub></a><br /><a href="#ideas-mzpqnxow" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/epi052/feroxbuster/commits?author=mzpqnxow" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://n-thumann.de/"><img src="https://avatars.githubusercontent.com/u/46975855?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Nicolas Thumann</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/commits?author=n-thumann" title="Code">💻</a> <a href="https://github.com/epi052/feroxbuster/commits?author=n-thumann" title="Documentation">📖</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://github.com/tomtastic"><img src="https://avatars.githubusercontent.com/u/302127?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Tom Matthews</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/commits?author=tomtastic" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/bsysop"><img src="https://avatars.githubusercontent.com/u/9998303?v=4?s=100" width="100px;" alt=""/><br /><sub><b>bsysop</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/commits?author=bsysop" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="http://bpsizemore.me"><img src="https://avatars.githubusercontent.com/u/11645898?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Brian Sizemore</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/commits?author=bpsizemore" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://pwn.by/noraj"><img src="https://avatars.githubusercontent.com/u/16578570?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Alexandre ZANNI</b></sub></a><br /><a href="#infra-noraj" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="https://github.com/epi052/feroxbuster/commits?author=noraj" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/craig"><img src="https://avatars.githubusercontent.com/u/99729?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Craig</b></sub></a><br /><a href="#infra-craig" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a></td>
|
||||
<td align="center"><a href="https://www.reddit.com/u/EONRaider"><img src="https://avatars.githubusercontent.com/u/15611424?v=4?s=100" width="100px;" alt=""/><br /><sub><b>EONRaider</b></sub></a><br /><a href="#infra-EONRaider" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a></td>
|
||||
<td align="center"><a href="https://github.com/wtwver"><img src="https://avatars.githubusercontent.com/u/53866088?v=4?s=100" width="100px;" alt=""/><br /><sub><b>wtwver</b></sub></a><br /><a href="#infra-wtwver" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://tib3rius.com"><img src="https://avatars.githubusercontent.com/u/48113936?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Tib3rius</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3ATib3rius" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="https://github.com/0xdf"><img src="https://avatars.githubusercontent.com/u/1489045?v=4?s=100" width="100px;" alt=""/><br /><sub><b>0xdf</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3A0xdf" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="http://secure77.de"><img src="https://avatars.githubusercontent.com/u/31564517?v=4?s=100" width="100px;" alt=""/><br /><sub><b>secure-77</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3Asecure-77" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="https://github.com/sbrun"><img src="https://avatars.githubusercontent.com/u/7712154?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Sophie Brun</b></sub></a><br /><a href="#infra-sbrun" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a></td>
|
||||
<td align="center"><a href="https://github.com/black-A"><img src="https://avatars.githubusercontent.com/u/30686803?v=4?s=100" width="100px;" alt=""/><br /><sub><b>black-A</b></sub></a><br /><a href="#ideas-black-A" title="Ideas, Planning, & Feedback">🤔</a></td>
|
||||
<td align="center"><a href="https://github.com/dinosn"><img src="https://avatars.githubusercontent.com/u/3851678?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Nicolas Krassas</b></sub></a><br /><a href="#ideas-dinosn" title="Ideas, Planning, & Feedback">🤔</a></td>
|
||||
<td align="center"><a href="https://github.com/N0ur5"><img src="https://avatars.githubusercontent.com/u/24260009?v=4?s=100" width="100px;" alt=""/><br /><sub><b>N0ur5</b></sub></a><br /><a href="#ideas-N0ur5" title="Ideas, Planning, & Feedback">🤔</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://github.com/moscowchill"><img src="https://avatars.githubusercontent.com/u/72578879?v=4?s=100" width="100px;" alt=""/><br /><sub><b>mchill</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3Amoscowchill" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="http://BitThr3at.github.io"><img src="https://avatars.githubusercontent.com/u/45028933?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Naman</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3ABitThr3at" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="https://github.com/Sicks3c"><img src="https://avatars.githubusercontent.com/u/32225186?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ayoub Elaich</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3Asicks3c" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="https://github.com/HenryHoggard"><img src="https://avatars.githubusercontent.com/u/1208121?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Henry</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3AHenryHoggard" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="https://github.com/SleepiPanda"><img src="https://avatars.githubusercontent.com/u/6428561?v=4?s=100" width="100px;" alt=""/><br /><sub><b>SleepiPanda</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3ASleepiPanda" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="https://github.com/uBadRequest"><img src="https://avatars.githubusercontent.com/u/47282747?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Bad Requests</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3AuBadRequest" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="https://home.dnaka91.rocks"><img src="https://avatars.githubusercontent.com/u/36804488?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Dominik Nakamura</b></sub></a><br /><a href="#infra-dnaka91" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://github.com/hunter0x8"><img src="https://avatars.githubusercontent.com/u/46222314?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Muhammad Ahsan</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3Ahunter0x8" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="https://github.com/cortantief"><img src="https://avatars.githubusercontent.com/u/34527333?v=4?s=100" width="100px;" alt=""/><br /><sub><b>cortantief</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3Acortantief" title="Bug reports">🐛</a> <a href="https://github.com/epi052/feroxbuster/commits?author=cortantief" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/dsaxton"><img src="https://avatars.githubusercontent.com/u/2658661?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Daniel Saxton</b></sub></a><br /><a href="#ideas-dsaxton" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/epi052/feroxbuster/commits?author=dsaxton" title="Code">💻</a></td>
|
||||
</tr>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td align="center"><a href="https://io.fi"><img src="https://avatars.githubusercontent.com/u/5235109?v=4?s=100" width="100px;" alt="Joona Hoikkala"/><br /><sub><b>Joona Hoikkala</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/commits?author=joohoi" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/jsav0"><img src="https://avatars.githubusercontent.com/u/20546041?v=4?s=100" width="100px;" alt="J Savage"/><br /><sub><b>J Savage</b></sub></a><br /><a href="#infra-jsav0" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="https://github.com/epi052/feroxbuster/commits?author=jsav0" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="http://www.tgotwig.dev"><img src="https://avatars.githubusercontent.com/u/30773779?v=4?s=100" width="100px;" alt="Thomas Gotwig"/><br /><sub><b>Thomas Gotwig</b></sub></a><br /><a href="#infra-TGotwig" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="https://github.com/epi052/feroxbuster/commits?author=TGotwig" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/spikecodes"><img src="https://avatars.githubusercontent.com/u/19519553?v=4?s=100" width="100px;" alt="Spike"/><br /><sub><b>Spike</b></sub></a><br /><a href="#infra-spikecodes" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="https://github.com/epi052/feroxbuster/commits?author=spikecodes" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/evanrichter"><img src="https://avatars.githubusercontent.com/u/330292?v=4?s=100" width="100px;" alt="Evan Richter"/><br /><sub><b>Evan Richter</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/commits?author=evanrichter" title="Code">💻</a> <a href="https://github.com/epi052/feroxbuster/commits?author=evanrichter" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/mzpqnxow"><img src="https://avatars.githubusercontent.com/u/8016228?v=4?s=100" width="100px;" alt="AG"/><br /><sub><b>AG</b></sub></a><br /><a href="#ideas-mzpqnxow" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/epi052/feroxbuster/commits?author=mzpqnxow" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://n-thumann.de/"><img src="https://avatars.githubusercontent.com/u/46975855?v=4?s=100" width="100px;" alt="Nicolas Thumann"/><br /><sub><b>Nicolas Thumann</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/commits?author=n-thumann" title="Code">💻</a> <a href="https://github.com/epi052/feroxbuster/commits?author=n-thumann" title="Documentation">📖</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://github.com/tomtastic"><img src="https://avatars.githubusercontent.com/u/302127?v=4?s=100" width="100px;" alt="Tom Matthews"/><br /><sub><b>Tom Matthews</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/commits?author=tomtastic" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/bsysop"><img src="https://avatars.githubusercontent.com/u/9998303?v=4?s=100" width="100px;" alt="bsysop"/><br /><sub><b>bsysop</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/commits?author=bsysop" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="http://bpsizemore.me"><img src="https://avatars.githubusercontent.com/u/11645898?v=4?s=100" width="100px;" alt="Brian Sizemore"/><br /><sub><b>Brian Sizemore</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/commits?author=bpsizemore" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://pwn.by/noraj"><img src="https://avatars.githubusercontent.com/u/16578570?v=4?s=100" width="100px;" alt="Alexandre ZANNI"/><br /><sub><b>Alexandre ZANNI</b></sub></a><br /><a href="#infra-noraj" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="https://github.com/epi052/feroxbuster/commits?author=noraj" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/craig"><img src="https://avatars.githubusercontent.com/u/99729?v=4?s=100" width="100px;" alt="Craig"/><br /><sub><b>Craig</b></sub></a><br /><a href="#infra-craig" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a></td>
|
||||
<td align="center"><a href="https://www.reddit.com/u/EONRaider"><img src="https://avatars.githubusercontent.com/u/15611424?v=4?s=100" width="100px;" alt="EONRaider"/><br /><sub><b>EONRaider</b></sub></a><br /><a href="#infra-EONRaider" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a></td>
|
||||
<td align="center"><a href="https://github.com/wtwver"><img src="https://avatars.githubusercontent.com/u/53866088?v=4?s=100" width="100px;" alt="wtwver"/><br /><sub><b>wtwver</b></sub></a><br /><a href="#infra-wtwver" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://tib3rius.com"><img src="https://avatars.githubusercontent.com/u/48113936?v=4?s=100" width="100px;" alt="Tib3rius"/><br /><sub><b>Tib3rius</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3ATib3rius" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="https://github.com/0xdf"><img src="https://avatars.githubusercontent.com/u/1489045?v=4?s=100" width="100px;" alt="0xdf"/><br /><sub><b>0xdf</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3A0xdf" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="http://secure77.de"><img src="https://avatars.githubusercontent.com/u/31564517?v=4?s=100" width="100px;" alt="secure-77"/><br /><sub><b>secure-77</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3Asecure-77" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="https://github.com/sbrun"><img src="https://avatars.githubusercontent.com/u/7712154?v=4?s=100" width="100px;" alt="Sophie Brun"/><br /><sub><b>Sophie Brun</b></sub></a><br /><a href="#infra-sbrun" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a></td>
|
||||
<td align="center"><a href="https://github.com/black-A"><img src="https://avatars.githubusercontent.com/u/30686803?v=4?s=100" width="100px;" alt="black-A"/><br /><sub><b>black-A</b></sub></a><br /><a href="#ideas-black-A" title="Ideas, Planning, & Feedback">🤔</a></td>
|
||||
<td align="center"><a href="https://github.com/dinosn"><img src="https://avatars.githubusercontent.com/u/3851678?v=4?s=100" width="100px;" alt="Nicolas Krassas"/><br /><sub><b>Nicolas Krassas</b></sub></a><br /><a href="#ideas-dinosn" title="Ideas, Planning, & Feedback">🤔</a></td>
|
||||
<td align="center"><a href="https://github.com/N0ur5"><img src="https://avatars.githubusercontent.com/u/24260009?v=4?s=100" width="100px;" alt="N0ur5"/><br /><sub><b>N0ur5</b></sub></a><br /><a href="#ideas-N0ur5" title="Ideas, Planning, & Feedback">🤔</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://github.com/moscowchill"><img src="https://avatars.githubusercontent.com/u/72578879?v=4?s=100" width="100px;" alt="mchill"/><br /><sub><b>mchill</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3Amoscowchill" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="http://BitThr3at.github.io"><img src="https://avatars.githubusercontent.com/u/45028933?v=4?s=100" width="100px;" alt="Naman"/><br /><sub><b>Naman</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3ABitThr3at" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="https://github.com/Sicks3c"><img src="https://avatars.githubusercontent.com/u/32225186?v=4?s=100" width="100px;" alt="Ayoub Elaich"/><br /><sub><b>Ayoub Elaich</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3Asicks3c" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="https://github.com/HenryHoggard"><img src="https://avatars.githubusercontent.com/u/1208121?v=4?s=100" width="100px;" alt="Henry"/><br /><sub><b>Henry</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3AHenryHoggard" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="https://github.com/SleepiPanda"><img src="https://avatars.githubusercontent.com/u/6428561?v=4?s=100" width="100px;" alt="SleepiPanda"/><br /><sub><b>SleepiPanda</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3ASleepiPanda" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="https://github.com/uBadRequest"><img src="https://avatars.githubusercontent.com/u/47282747?v=4?s=100" width="100px;" alt="Bad Requests"/><br /><sub><b>Bad Requests</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3AuBadRequest" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="https://home.dnaka91.rocks"><img src="https://avatars.githubusercontent.com/u/36804488?v=4?s=100" width="100px;" alt="Dominik Nakamura"/><br /><sub><b>Dominik Nakamura</b></sub></a><br /><a href="#infra-dnaka91" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://github.com/hunter0x8"><img src="https://avatars.githubusercontent.com/u/46222314?v=4?s=100" width="100px;" alt="Muhammad Ahsan"/><br /><sub><b>Muhammad Ahsan</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3Ahunter0x8" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="https://github.com/cortantief"><img src="https://avatars.githubusercontent.com/u/34527333?v=4?s=100" width="100px;" alt="cortantief"/><br /><sub><b>cortantief</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3Acortantief" title="Bug reports">🐛</a> <a href="https://github.com/epi052/feroxbuster/commits?author=cortantief" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/dsaxton"><img src="https://avatars.githubusercontent.com/u/2658661?v=4?s=100" width="100px;" alt="Daniel Saxton"/><br /><sub><b>Daniel Saxton</b></sub></a><br /><a href="#ideas-dsaxton" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/epi052/feroxbuster/commits?author=dsaxton" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/n0kovo"><img src="https://avatars.githubusercontent.com/u/16690056?v=4?s=100" width="100px;" alt="narkopolo"/><br /><sub><b>n0kovo</b></sub></a><br /><a href="#ideas-n0kovo" title="Ideas, Planning, & Feedback">🤔</a></td>
|
||||
<td align="center"><a href="https://ring0.lol"><img src="https://avatars.githubusercontent.com/u/1893909?v=4?s=100" width="100px;" alt="Justin Steven"/><br /><sub><b>Justin Steven</b></sub></a><br /><a href="#ideas-justinsteven" title="Ideas, Planning, & Feedback">🤔</a></td>
|
||||
<td align="center"><a href="https://github.com/7047payloads"><img src="https://avatars.githubusercontent.com/u/95562424?v=4?s=100" width="100px;" alt="7047payloads"/><br /><sub><b>7047payloads</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/commits?author=7047payloads" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/unkn0wnsyst3m"><img src="https://avatars.githubusercontent.com/u/21272239?v=4?s=100" width="100px;" alt="unkn0wnsyst3m"/><br /><sub><b>unkn0wnsyst3m</b></sub></a><br /><a href="#ideas-unkn0wnsyst3m" title="Ideas, Planning, & Feedback">🤔</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://ironwort.me/"><img src="https://avatars.githubusercontent.com/u/15280042?v=4?s=100" width="100px;" alt="0x08"/><br /><sub><b>0x08</b></sub></a><br /><a href="#ideas-its0x08" title="Ideas, Planning, & Feedback">🤔</a></td>
|
||||
<td align="center"><a href="https://github.com/MD-Levitan"><img src="https://avatars.githubusercontent.com/u/12116508?v=4?s=100" width="100px;" alt="kusok"/><br /><sub><b>kusok</b></sub></a><br /><a href="#ideas-MD-Levitan" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/epi052/feroxbuster/commits?author=MD-Levitan" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/godylockz"><img src="https://avatars.githubusercontent.com/u/81207744?v=4?s=100" width="100px;" alt="godylockz"/><br /><sub><b>godylockz</b></sub></a><br /><a href="#ideas-godylockz" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/epi052/feroxbuster/commits?author=godylockz" title="Code">💻</a></td>
|
||||
<td align="center"><a href="http://ryanmontgomery.me"><img src="https://avatars.githubusercontent.com/u/44453666?v=4?s=100" width="100px;" alt="Ryan Montgomery"/><br /><sub><b>Ryan Montgomery</b></sub></a><br /><a href="#ideas-0dayCTF" title="Ideas, Planning, & Feedback">🤔</a></td>
|
||||
<td align="center"><a href="https://github.com/IppSec"><img src="https://avatars.githubusercontent.com/u/24677271?v=4?s=100" width="100px;" alt="ippsec"/><br /><sub><b>ippsec</b></sub></a><br /><a href="#ideas-ippsec" title="Ideas, Planning, & Feedback">🤔</a></td>
|
||||
<td align="center"><a href="https://github.com/gtjamesa"><img src="https://avatars.githubusercontent.com/u/2078364?v=4?s=100" width="100px;" alt="James"/><br /><sub><b>James</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3Agtjamesa" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="https://twitter.com/Jhaddix"><img src="https://avatars.githubusercontent.com/u/3488554?v=4?s=100" width="100px;" alt="Jason Haddix"/><br /><sub><b>Jason Haddix</b></sub></a><br /><a href="#ideas-jhaddix" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/epi052/feroxbuster/issues?q=author%3Ajhaddix" title="Bug reports">🐛</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://github.com/ThisLimn0"><img src="https://avatars.githubusercontent.com/u/67125885?v=4?s=100" width="100px;" alt="Limn0"/><br /><sub><b>Limn0</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3AThisLimn0" title="Bug reports">🐛</a></td>
|
||||
<td align="center"><a href="https://github.com/0xdf223"><img src="https://avatars.githubusercontent.com/u/76954092?v=4?s=100" width="100px;" alt="0xdf"/><br /><sub><b>0xdf</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3A0xdf223" title="Bug reports">🐛</a> <a href="#ideas-0xdf223" title="Ideas, Planning, & Feedback">🤔</a></td>
|
||||
<td align="center"><a href="https://github.com/Flangyver"><img src="https://avatars.githubusercontent.com/u/59575870?v=4?s=100" width="100px;" alt="Flangyver"/><br /><sub><b>Flangyver</b></sub></a><br /><a href="#ideas-Flangyver" title="Ideas, Planning, & Feedback">🤔</a></td>
|
||||
<td align="center"><a href="https://github.com/DonatoReis"><img src="https://avatars.githubusercontent.com/u/93531354?v=4?s=100" width="100px;" alt="PeakyBlinder"/><br /><sub><b>PeakyBlinder</b></sub></a><br /><a href="#ideas-DonatoReis" title="Ideas, Planning, & Feedback">🤔</a></td>
|
||||
<td align="center"><a href="https://postmodern.github.io/"><img src="https://avatars.githubusercontent.com/u/12671?v=4?s=100" width="100px;" alt="Postmodern"/><br /><sub><b>Postmodern</b></sub></a><br /><a href="#ideas-postmodern" title="Ideas, Planning, & Feedback">🤔</a></td>
|
||||
<td align="center"><a href="https://github.com/herrcykel"><img src="https://avatars.githubusercontent.com/u/1936757?v=4?s=100" width="100px;" alt="O"/><br /><sub><b>O</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/commits?author=herrcykel" title="Code">💻</a></td>
|
||||
<td align="center"><a href="http://udoprog.github.io/"><img src="https://avatars.githubusercontent.com/u/111092?v=4?s=100" width="100px;" alt="John-John Tedro"/><br /><sub><b>John-John Tedro</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/commits?author=udoprog" title="Code">💻</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://github.com/kmanc"><img src="https://avatars.githubusercontent.com/u/14863147?v=4?s=100" width="100px;" alt="kmanc"/><br /><sub><b>kmanc</b></sub></a><br /><a href="https://github.com/epi052/feroxbuster/issues?q=author%3Akmanc" title="Bug reports">🐛</a> <a href="https://github.com/epi052/feroxbuster/commits?author=kmanc" title="Code">💻</a></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<!-- markdownlint-restore -->
|
||||
@@ -229,4 +256,4 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
|
||||
|
||||
<!-- ALL-CONTRIBUTORS-LIST:END -->
|
||||
|
||||
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
|
||||
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
|
||||
|
||||
28
build.rs
28
build.rs
@@ -1,9 +1,7 @@
|
||||
use std::fs::{copy, create_dir_all, OpenOptions};
|
||||
use std::io::{Read, Seek, SeekFrom, Write};
|
||||
extern crate clap;
|
||||
extern crate dirs;
|
||||
|
||||
use clap::Shell;
|
||||
use clap_complete::{generate_to, shells};
|
||||
|
||||
include!("src/parser.rs");
|
||||
|
||||
@@ -18,11 +16,11 @@ fn main() {
|
||||
|
||||
let mut app = initialize();
|
||||
|
||||
let shells: [Shell; 4] = [Shell::Bash, Shell::Fish, Shell::Zsh, Shell::PowerShell];
|
||||
|
||||
for shell in &shells {
|
||||
app.gen_completions("feroxbuster", *shell, outdir);
|
||||
}
|
||||
generate_to(shells::Bash, &mut app, "feroxbuster", outdir).unwrap();
|
||||
generate_to(shells::Zsh, &mut app, "feroxbuster", outdir).unwrap();
|
||||
generate_to(shells::Zsh, &mut app, "feroxbuster", outdir).unwrap();
|
||||
generate_to(shells::PowerShell, &mut app, "feroxbuster", outdir).unwrap();
|
||||
generate_to(shells::Elvish, &mut app, "feroxbuster", outdir).unwrap();
|
||||
|
||||
// 0xdf pointed out an oddity when tab-completing options that expect file paths, the fix we
|
||||
// landed on was to add -o plusdirs to the bash completion script. The following code aims to
|
||||
@@ -61,15 +59,11 @@ fn main() {
|
||||
if !config_dir.exists() {
|
||||
// recursively create the feroxbuster directory and all of its parent components if
|
||||
// they are missing
|
||||
if !config_dir.exists() {
|
||||
// recursively create the feroxbuster directory and all of its parent components if
|
||||
// they are missing
|
||||
if create_dir_all(&config_dir).is_err() {
|
||||
// only copy the config file when we're not running in the CI/CD pipeline
|
||||
// which fails with permission denied
|
||||
eprintln!("Couldn't create one or more directories needed to copy the config file");
|
||||
return;
|
||||
}
|
||||
if create_dir_all(&config_dir).is_err() {
|
||||
// only copy the config file when we're not running in the CI/CD pipeline
|
||||
// which fails with permission denied
|
||||
eprintln!("Couldn't create one or more directories needed to copy the config file");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -30,7 +30,13 @@
|
||||
# random_agent = false
|
||||
# redirects = true
|
||||
# insecure = true
|
||||
# collect_words = true
|
||||
# collect_backups = true
|
||||
# collect_extensions = true
|
||||
# extensions = ["php", "html"]
|
||||
# dont_collect = ["png", "gif", "jpg", "jpeg"]
|
||||
# methods = ["GET", "POST"]
|
||||
# data = [11, 12, 13, 14, 15]
|
||||
# url_denylist = ["http://dont-scan.me", "https://also-not.me"]
|
||||
# regex_denylist = ["/deny.*"]
|
||||
# no_recursion = true
|
||||
@@ -39,6 +45,7 @@
|
||||
# dont_filter = true
|
||||
# extract_links = true
|
||||
# depth = 1
|
||||
# force_recursion = true
|
||||
# filter_size = [5174]
|
||||
# filter_regex = ["^ignore me$"]
|
||||
# filter_similar = ["https://somesite.com/soft404"]
|
||||
|
||||
@@ -15,90 +15,106 @@ _feroxbuster() {
|
||||
|
||||
local context curcontext="$curcontext" state line
|
||||
_arguments "${_arguments_options[@]}" \
|
||||
'-w+[Path to the wordlist]' \
|
||||
'--wordlist=[Path to the wordlist]' \
|
||||
'*-u+[The target URL(s) (required, unless --stdin used)]' \
|
||||
'*--url=[The target URL(s) (required, unless --stdin used)]' \
|
||||
'-t+[Number of concurrent threads (default: 50)]' \
|
||||
'--threads=[Number of concurrent threads (default: 50)]' \
|
||||
'-d+[Maximum recursion depth, a depth of 0 is infinite recursion (default: 4)]' \
|
||||
'--depth=[Maximum recursion depth, a depth of 0 is infinite recursion (default: 4)]' \
|
||||
'-T+[Number of seconds before a request times out (default: 7)]' \
|
||||
'--timeout=[Number of seconds before a request times out (default: 7)]' \
|
||||
'-p+[Proxy to use for requests (ex: http(s)://host:port, socks5(h)://host:port)]' \
|
||||
'--proxy=[Proxy to use for requests (ex: http(s)://host:port, socks5(h)://host:port)]' \
|
||||
'-P+[Send only unfiltered requests through a Replay Proxy, instead of all requests]' \
|
||||
'--replay-proxy=[Send only unfiltered requests through a Replay Proxy, instead of all requests]' \
|
||||
'*-R+[Status Codes to send through a Replay Proxy when found (default: --status-codes value)]' \
|
||||
'*--replay-codes=[Status Codes to send through a Replay Proxy when found (default: --status-codes value)]' \
|
||||
'*-s+[Status Codes to include (allow list) (default: 200 204 301 302 307 308 401 403 405)]' \
|
||||
'*--status-codes=[Status Codes to include (allow list) (default: 200 204 301 302 307 308 401 403 405)]' \
|
||||
'-o+[Output file to write results to (use w/ --json for JSON entries)]' \
|
||||
'--output=[Output file to write results to (use w/ --json for JSON entries)]' \
|
||||
'(-u --url)--resume-from=[State file from which to resume a partially complete scan (ex. --resume-from ferox-1606586780.state)]' \
|
||||
'--debug-log=[Output file to write log entries (use w/ --json for JSON entries)]' \
|
||||
'-a+[Sets the User-Agent (default: feroxbuster/VERSION)]' \
|
||||
'--user-agent=[Sets the User-Agent (default: feroxbuster/VERSION)]' \
|
||||
'*-x+[File extension(s) to search for (ex: -x php -x pdf js)]' \
|
||||
'*--extensions=[File extension(s) to search for (ex: -x php -x pdf js)]' \
|
||||
'*--dont-scan=[URL(s) or Regex Pattern(s) to exclude from recursion/scans]' \
|
||||
'*-H+[Specify HTTP headers (ex: -H Header:val '\''stuff: things'\'')]' \
|
||||
'*--headers=[Specify HTTP headers (ex: -H Header:val '\''stuff: things'\'')]' \
|
||||
'*-Q+[Specify URL query parameters (ex: -Q token=stuff -Q secret=key)]' \
|
||||
'*--query=[Specify URL query parameters (ex: -Q token=stuff -Q secret=key)]' \
|
||||
'*-S+[Filter out messages of a particular size (ex: -S 5120 -S 4927,1970)]' \
|
||||
'*--filter-size=[Filter out messages of a particular size (ex: -S 5120 -S 4927,1970)]' \
|
||||
'*-X+[Filter out messages via regular expression matching on the response'\''s body (ex: -X '\''^ignore me$'\'')]' \
|
||||
'*--filter-regex=[Filter out messages via regular expression matching on the response'\''s body (ex: -X '\''^ignore me$'\'')]' \
|
||||
'*-W+[Filter out messages of a particular word count (ex: -W 312 -W 91,82)]' \
|
||||
'*--filter-words=[Filter out messages of a particular word count (ex: -W 312 -W 91,82)]' \
|
||||
'*-N+[Filter out messages of a particular line count (ex: -N 20 -N 31,30)]' \
|
||||
'*--filter-lines=[Filter out messages of a particular line count (ex: -N 20 -N 31,30)]' \
|
||||
'*-C+[Filter out status codes (deny list) (ex: -C 200 -C 401)]' \
|
||||
'*--filter-status=[Filter out status codes (deny list) (ex: -C 200 -C 401)]' \
|
||||
'*--filter-similar-to=[Filter out pages that are similar to the given page (ex. --filter-similar-to http://site.xyz/soft404)]' \
|
||||
'-L+[Limit total number of concurrent scans (default: 0, i.e. no limit)]' \
|
||||
'--scan-limit=[Limit total number of concurrent scans (default: 0, i.e. no limit)]' \
|
||||
'--parallel=[Run parallel feroxbuster instances (one child process per url passed via stdin)]' \
|
||||
'(--auto-tune)--rate-limit=[Limit number of requests per second (per directory) (default: 0, i.e. no limit)]' \
|
||||
'--time-limit=[Limit total run time of all scans (ex: --time-limit 10m)]' \
|
||||
'-u+[The target URL (required, unless \[--stdin || --resume-from\] used)]:URL:_urls' \
|
||||
'--url=[The target URL (required, unless \[--stdin || --resume-from\] used)]:URL:_urls' \
|
||||
'(-u --url)--resume-from=[State file from which to resume a partially complete scan (ex. --resume-from ferox-1606586780.state)]:STATE_FILE:_files' \
|
||||
'-p+[Proxy to use for requests (ex: http(s)://host:port, socks5(h)://host:port)]:PROXY:_urls' \
|
||||
'--proxy=[Proxy to use for requests (ex: http(s)://host:port, socks5(h)://host:port)]:PROXY:_urls' \
|
||||
'-P+[Send only unfiltered requests through a Replay Proxy, instead of all requests]:REPLAY_PROXY:_urls' \
|
||||
'--replay-proxy=[Send only unfiltered requests through a Replay Proxy, instead of all requests]:REPLAY_PROXY:_urls' \
|
||||
'*-R+[Status Codes to send through a Replay Proxy when found (default: --status-codes value)]:REPLAY_CODE: ' \
|
||||
'*--replay-codes=[Status Codes to send through a Replay Proxy when found (default: --status-codes value)]:REPLAY_CODE: ' \
|
||||
'-a+[Sets the User-Agent (default: feroxbuster/2.7.3)]:USER_AGENT: ' \
|
||||
'--user-agent=[Sets the User-Agent (default: feroxbuster/2.7.3)]:USER_AGENT: ' \
|
||||
'*-x+[File extension(s) to search for (ex: -x php -x pdf js)]:FILE_EXTENSION: ' \
|
||||
'*--extensions=[File extension(s) to search for (ex: -x php -x pdf js)]:FILE_EXTENSION: ' \
|
||||
'*-m+[Which HTTP request method(s) should be sent (default: GET)]:HTTP_METHODS: ' \
|
||||
'*--methods=[Which HTTP request method(s) should be sent (default: GET)]:HTTP_METHODS: ' \
|
||||
'--data=[Request'\''s Body; can read data from a file if input starts with an @ (ex: @post.bin)]:DATA: ' \
|
||||
'*-H+[Specify HTTP headers to be used in each request (ex: -H Header:val -H '\''stuff: things'\'')]:HEADER: ' \
|
||||
'*--headers=[Specify HTTP headers to be used in each request (ex: -H Header:val -H '\''stuff: things'\'')]:HEADER: ' \
|
||||
'*-b+[Specify HTTP cookies to be used in each request (ex: -b stuff=things)]:COOKIE: ' \
|
||||
'*--cookies=[Specify HTTP cookies to be used in each request (ex: -b stuff=things)]:COOKIE: ' \
|
||||
'*-Q+[Request'\''s URL query parameters (ex: -Q token=stuff -Q secret=key)]:QUERY: ' \
|
||||
'*--query=[Request'\''s URL query parameters (ex: -Q token=stuff -Q secret=key)]:QUERY: ' \
|
||||
'*--dont-scan=[URL(s) or Regex Pattern(s) to exclude from recursion/scans]:URL: ' \
|
||||
'*-S+[Filter out messages of a particular size (ex: -S 5120 -S 4927,1970)]:SIZE: ' \
|
||||
'*--filter-size=[Filter out messages of a particular size (ex: -S 5120 -S 4927,1970)]:SIZE: ' \
|
||||
'*-X+[Filter out messages via regular expression matching on the response'\''s body (ex: -X '\''^ignore me$'\'')]:REGEX: ' \
|
||||
'*--filter-regex=[Filter out messages via regular expression matching on the response'\''s body (ex: -X '\''^ignore me$'\'')]:REGEX: ' \
|
||||
'*-W+[Filter out messages of a particular word count (ex: -W 312 -W 91,82)]:WORDS: ' \
|
||||
'*--filter-words=[Filter out messages of a particular word count (ex: -W 312 -W 91,82)]:WORDS: ' \
|
||||
'*-N+[Filter out messages of a particular line count (ex: -N 20 -N 31,30)]:LINES: ' \
|
||||
'*--filter-lines=[Filter out messages of a particular line count (ex: -N 20 -N 31,30)]:LINES: ' \
|
||||
'(-s --status-codes)*-C+[Filter out status codes (deny list) (ex: -C 200 -C 401)]:STATUS_CODE: ' \
|
||||
'(-s --status-codes)*--filter-status=[Filter out status codes (deny list) (ex: -C 200 -C 401)]:STATUS_CODE: ' \
|
||||
'*--filter-similar-to=[Filter out pages that are similar to the given page (ex. --filter-similar-to http://site.xyz/soft404)]:UNWANTED_PAGE:_urls' \
|
||||
'*-s+[Status Codes to include (allow list) (default: 200 204 301 302 307 308 401 403 405)]:STATUS_CODE: ' \
|
||||
'*--status-codes=[Status Codes to include (allow list) (default: 200 204 301 302 307 308 401 403 405)]:STATUS_CODE: ' \
|
||||
'-T+[Number of seconds before a client'\''s request times out (default: 7)]:SECONDS: ' \
|
||||
'--timeout=[Number of seconds before a client'\''s request times out (default: 7)]:SECONDS: ' \
|
||||
'-t+[Number of concurrent threads (default: 50)]:THREADS: ' \
|
||||
'--threads=[Number of concurrent threads (default: 50)]:THREADS: ' \
|
||||
'-d+[Maximum recursion depth, a depth of 0 is infinite recursion (default: 4)]:RECURSION_DEPTH: ' \
|
||||
'--depth=[Maximum recursion depth, a depth of 0 is infinite recursion (default: 4)]:RECURSION_DEPTH: ' \
|
||||
'-L+[Limit total number of concurrent scans (default: 0, i.e. no limit)]:SCAN_LIMIT: ' \
|
||||
'--scan-limit=[Limit total number of concurrent scans (default: 0, i.e. no limit)]:SCAN_LIMIT: ' \
|
||||
'--parallel=[Run parallel feroxbuster instances (one child process per url passed via stdin)]:PARALLEL_SCANS: ' \
|
||||
'(--auto-tune)--rate-limit=[Limit number of requests per second (per directory) (default: 0, i.e. no limit)]:RATE_LIMIT: ' \
|
||||
'--time-limit=[Limit total run time of all scans (ex: --time-limit 10m)]:TIME_SPEC: ' \
|
||||
'-w+[Path to the wordlist]:FILE:_files' \
|
||||
'--wordlist=[Path to the wordlist]:FILE:_files' \
|
||||
'*-I+[File extension(s) to Ignore while collecting extensions (only used with --collect-extensions)]:FILE_EXTENSION: ' \
|
||||
'*--dont-collect=[File extension(s) to Ignore while collecting extensions (only used with --collect-extensions)]:FILE_EXTENSION: ' \
|
||||
'-o+[Output file to write results to (use w/ --json for JSON entries)]:FILE:_files' \
|
||||
'--output=[Output file to write results to (use w/ --json for JSON entries)]:FILE:_files' \
|
||||
'--debug-log=[Output file to write log entries (use w/ --json for JSON entries)]:FILE:_files' \
|
||||
'(-u --url)--stdin[Read url(s) from STDIN]' \
|
||||
'(-p --proxy -k --insecure --burp-replay)--burp[Set --proxy to http://127.0.0.1:8080 and set --insecure to true]' \
|
||||
'(-P --replay-proxy -k --insecure)--burp-replay[Set --replay-proxy to http://127.0.0.1:8080 and set --insecure to true]' \
|
||||
'--smart[Set --extract-links, --auto-tune, --collect-words, and --collect-backups to true]' \
|
||||
'--thorough[Use the same settings as --smart and set --collect-extensions to true]' \
|
||||
'-A[Use a random User-Agent]' \
|
||||
'--random-agent[Use a random User-Agent]' \
|
||||
'-f[Append / to each request'\''s URL]' \
|
||||
'--add-slash[Append / to each request'\''s URL]' \
|
||||
'-r[Allow client to follow redirects]' \
|
||||
'--redirects[Allow client to follow redirects]' \
|
||||
'-k[Disables TLS certificate validation in the client]' \
|
||||
'--insecure[Disables TLS certificate validation in the client]' \
|
||||
'-n[Do not scan recursively]' \
|
||||
'--no-recursion[Do not scan recursively]' \
|
||||
'(-n --no-recursion)--force-recursion[Force recursion attempts on all '\''found'\'' endpoints (still respects recursion depth)]' \
|
||||
'-e[Extract links from response body (html, javascript, etc...); make new requests based on findings]' \
|
||||
'--extract-links[Extract links from response body (html, javascript, etc...); make new requests based on findings]' \
|
||||
'(--auto-bail)--auto-tune[Automatically lower scan rate when an excessive amount of errors are encountered]' \
|
||||
'--auto-bail[Automatically stop scanning when an excessive amount of errors are encountered]' \
|
||||
'-D[Don'\''t auto-filter wildcard responses]' \
|
||||
'--dont-filter[Don'\''t auto-filter wildcard responses]' \
|
||||
'-E[Automatically discover extensions and add them to --extensions (unless they'\''re in --dont-collect)]' \
|
||||
'--collect-extensions[Automatically discover extensions and add them to --extensions (unless they'\''re in --dont-collect)]' \
|
||||
'-B[Automatically request likely backup extensions for "found" urls]' \
|
||||
'--collect-backups[Automatically request likely backup extensions for "found" urls]' \
|
||||
'-g[Automatically discover important words from within responses and add them to the wordlist]' \
|
||||
'--collect-words[Automatically discover important words from within responses and add them to the wordlist]' \
|
||||
'(--silent)*-v[Increase verbosity level (use -vv or more for greater effect. \[CAUTION\] 4 -v'\''s is probably too much)]' \
|
||||
'(--silent)*--verbosity[Increase verbosity level (use -vv or more for greater effect. \[CAUTION\] 4 -v'\''s is probably too much)]' \
|
||||
'(-q --quiet)--silent[Only print URLs + turn off logging (good for piping a list of urls to other commands)]' \
|
||||
'-q[Hide progress bars and banner (good for tmux windows w/ notifications)]' \
|
||||
'--quiet[Hide progress bars and banner (good for tmux windows w/ notifications)]' \
|
||||
'(--auto-bail)--auto-tune[Automatically lower scan rate when an excessive amount of errors are encountered]' \
|
||||
'--auto-bail[Automatically stop scanning when an excessive amount of errors are encountered]' \
|
||||
'--json[Emit JSON logs to --output and --debug-log instead of normal text]' \
|
||||
'-D[Don'\''t auto-filter wildcard responses]' \
|
||||
'--dont-filter[Don'\''t auto-filter wildcard responses]' \
|
||||
'-A[Use a random User-Agent]' \
|
||||
'--random-agent[Use a random User-Agent]' \
|
||||
'-r[Follow redirects]' \
|
||||
'--redirects[Follow redirects]' \
|
||||
'-k[Disables TLS certificate validation]' \
|
||||
'--insecure[Disables TLS certificate validation]' \
|
||||
'-n[Do not scan recursively]' \
|
||||
'--no-recursion[Do not scan recursively]' \
|
||||
'-f[Append / to each request]' \
|
||||
'--add-slash[Append / to each request]' \
|
||||
'(-u --url)--stdin[Read url(s) from STDIN]' \
|
||||
'-e[Extract links from response body (html, javascript, etc...); make new requests based on findings (default: false)]' \
|
||||
'--extract-links[Extract links from response body (html, javascript, etc...); make new requests based on findings (default: false)]' \
|
||||
'-h[Prints help information]' \
|
||||
'--help[Prints help information]' \
|
||||
'-V[Prints version information]' \
|
||||
'--version[Prints version information]' \
|
||||
'--no-state[Disable state output file (*.state)]' \
|
||||
'-h[Print help information (use `--help` for more detail)]' \
|
||||
'--help[Print help information (use `--help` for more detail)]' \
|
||||
'-V[Print version information]' \
|
||||
'--version[Print version information]' \
|
||||
&& ret=0
|
||||
|
||||
}
|
||||
|
||||
(( $+functions[_feroxbuster_commands] )) ||
|
||||
_feroxbuster_commands() {
|
||||
local commands; commands=(
|
||||
|
||||
)
|
||||
local commands; commands=()
|
||||
_describe -t commands 'feroxbuster commands' commands "$@"
|
||||
}
|
||||
|
||||
_feroxbuster "$@"
|
||||
_feroxbuster "$@"
|
||||
|
||||
@@ -12,7 +12,8 @@ Register-ArgumentCompleter -Native -CommandName 'feroxbuster' -ScriptBlock {
|
||||
$element = $commandElements[$i]
|
||||
if ($element -isnot [StringConstantExpressionAst] -or
|
||||
$element.StringConstantType -ne [StringConstantType]::BareWord -or
|
||||
$element.Value.StartsWith('-')) {
|
||||
$element.Value.StartsWith('-') -or
|
||||
$element.Value -eq $wordToComplete) {
|
||||
break
|
||||
}
|
||||
$element.Value
|
||||
@@ -20,37 +21,29 @@ Register-ArgumentCompleter -Native -CommandName 'feroxbuster' -ScriptBlock {
|
||||
|
||||
$completions = @(switch ($command) {
|
||||
'feroxbuster' {
|
||||
[CompletionResult]::new('-w', 'w', [CompletionResultType]::ParameterName, 'Path to the wordlist')
|
||||
[CompletionResult]::new('--wordlist', 'wordlist', [CompletionResultType]::ParameterName, 'Path to the wordlist')
|
||||
[CompletionResult]::new('-u', 'u', [CompletionResultType]::ParameterName, 'The target URL(s) (required, unless --stdin used)')
|
||||
[CompletionResult]::new('--url', 'url', [CompletionResultType]::ParameterName, 'The target URL(s) (required, unless --stdin used)')
|
||||
[CompletionResult]::new('-t', 't', [CompletionResultType]::ParameterName, 'Number of concurrent threads (default: 50)')
|
||||
[CompletionResult]::new('--threads', 'threads', [CompletionResultType]::ParameterName, 'Number of concurrent threads (default: 50)')
|
||||
[CompletionResult]::new('-d', 'd', [CompletionResultType]::ParameterName, 'Maximum recursion depth, a depth of 0 is infinite recursion (default: 4)')
|
||||
[CompletionResult]::new('--depth', 'depth', [CompletionResultType]::ParameterName, 'Maximum recursion depth, a depth of 0 is infinite recursion (default: 4)')
|
||||
[CompletionResult]::new('-T', 'T', [CompletionResultType]::ParameterName, 'Number of seconds before a request times out (default: 7)')
|
||||
[CompletionResult]::new('--timeout', 'timeout', [CompletionResultType]::ParameterName, 'Number of seconds before a request times out (default: 7)')
|
||||
[CompletionResult]::new('-u', 'u', [CompletionResultType]::ParameterName, 'The target URL (required, unless [--stdin || --resume-from] used)')
|
||||
[CompletionResult]::new('--url', 'url', [CompletionResultType]::ParameterName, 'The target URL (required, unless [--stdin || --resume-from] used)')
|
||||
[CompletionResult]::new('--resume-from', 'resume-from', [CompletionResultType]::ParameterName, 'State file from which to resume a partially complete scan (ex. --resume-from ferox-1606586780.state)')
|
||||
[CompletionResult]::new('-p', 'p', [CompletionResultType]::ParameterName, 'Proxy to use for requests (ex: http(s)://host:port, socks5(h)://host:port)')
|
||||
[CompletionResult]::new('--proxy', 'proxy', [CompletionResultType]::ParameterName, 'Proxy to use for requests (ex: http(s)://host:port, socks5(h)://host:port)')
|
||||
[CompletionResult]::new('-P', 'P', [CompletionResultType]::ParameterName, 'Send only unfiltered requests through a Replay Proxy, instead of all requests')
|
||||
[CompletionResult]::new('--replay-proxy', 'replay-proxy', [CompletionResultType]::ParameterName, 'Send only unfiltered requests through a Replay Proxy, instead of all requests')
|
||||
[CompletionResult]::new('-R', 'R', [CompletionResultType]::ParameterName, 'Status Codes to send through a Replay Proxy when found (default: --status-codes value)')
|
||||
[CompletionResult]::new('--replay-codes', 'replay-codes', [CompletionResultType]::ParameterName, 'Status Codes to send through a Replay Proxy when found (default: --status-codes value)')
|
||||
[CompletionResult]::new('-s', 's', [CompletionResultType]::ParameterName, 'Status Codes to include (allow list) (default: 200 204 301 302 307 308 401 403 405)')
|
||||
[CompletionResult]::new('--status-codes', 'status-codes', [CompletionResultType]::ParameterName, 'Status Codes to include (allow list) (default: 200 204 301 302 307 308 401 403 405)')
|
||||
[CompletionResult]::new('-o', 'o', [CompletionResultType]::ParameterName, 'Output file to write results to (use w/ --json for JSON entries)')
|
||||
[CompletionResult]::new('--output', 'output', [CompletionResultType]::ParameterName, 'Output file to write results to (use w/ --json for JSON entries)')
|
||||
[CompletionResult]::new('--resume-from', 'resume-from', [CompletionResultType]::ParameterName, 'State file from which to resume a partially complete scan (ex. --resume-from ferox-1606586780.state)')
|
||||
[CompletionResult]::new('--debug-log', 'debug-log', [CompletionResultType]::ParameterName, 'Output file to write log entries (use w/ --json for JSON entries)')
|
||||
[CompletionResult]::new('-a', 'a', [CompletionResultType]::ParameterName, 'Sets the User-Agent (default: feroxbuster/VERSION)')
|
||||
[CompletionResult]::new('--user-agent', 'user-agent', [CompletionResultType]::ParameterName, 'Sets the User-Agent (default: feroxbuster/VERSION)')
|
||||
[CompletionResult]::new('-a', 'a', [CompletionResultType]::ParameterName, 'Sets the User-Agent (default: feroxbuster/2.7.3)')
|
||||
[CompletionResult]::new('--user-agent', 'user-agent', [CompletionResultType]::ParameterName, 'Sets the User-Agent (default: feroxbuster/2.7.3)')
|
||||
[CompletionResult]::new('-x', 'x', [CompletionResultType]::ParameterName, 'File extension(s) to search for (ex: -x php -x pdf js)')
|
||||
[CompletionResult]::new('--extensions', 'extensions', [CompletionResultType]::ParameterName, 'File extension(s) to search for (ex: -x php -x pdf js)')
|
||||
[CompletionResult]::new('-m', 'm', [CompletionResultType]::ParameterName, 'Which HTTP request method(s) should be sent (default: GET)')
|
||||
[CompletionResult]::new('--methods', 'methods', [CompletionResultType]::ParameterName, 'Which HTTP request method(s) should be sent (default: GET)')
|
||||
[CompletionResult]::new('--data', 'data', [CompletionResultType]::ParameterName, 'Request''s Body; can read data from a file if input starts with an @ (ex: @post.bin)')
|
||||
[CompletionResult]::new('-H', 'H', [CompletionResultType]::ParameterName, 'Specify HTTP headers to be used in each request (ex: -H Header:val -H ''stuff: things'')')
|
||||
[CompletionResult]::new('--headers', 'headers', [CompletionResultType]::ParameterName, 'Specify HTTP headers to be used in each request (ex: -H Header:val -H ''stuff: things'')')
|
||||
[CompletionResult]::new('-b', 'b', [CompletionResultType]::ParameterName, 'Specify HTTP cookies to be used in each request (ex: -b stuff=things)')
|
||||
[CompletionResult]::new('--cookies', 'cookies', [CompletionResultType]::ParameterName, 'Specify HTTP cookies to be used in each request (ex: -b stuff=things)')
|
||||
[CompletionResult]::new('-Q', 'Q', [CompletionResultType]::ParameterName, 'Request''s URL query parameters (ex: -Q token=stuff -Q secret=key)')
|
||||
[CompletionResult]::new('--query', 'query', [CompletionResultType]::ParameterName, 'Request''s URL query parameters (ex: -Q token=stuff -Q secret=key)')
|
||||
[CompletionResult]::new('--dont-scan', 'dont-scan', [CompletionResultType]::ParameterName, 'URL(s) or Regex Pattern(s) to exclude from recursion/scans')
|
||||
[CompletionResult]::new('-H', 'H', [CompletionResultType]::ParameterName, 'Specify HTTP headers (ex: -H Header:val ''stuff: things'')')
|
||||
[CompletionResult]::new('--headers', 'headers', [CompletionResultType]::ParameterName, 'Specify HTTP headers (ex: -H Header:val ''stuff: things'')')
|
||||
[CompletionResult]::new('-Q', 'Q', [CompletionResultType]::ParameterName, 'Specify URL query parameters (ex: -Q token=stuff -Q secret=key)')
|
||||
[CompletionResult]::new('--query', 'query', [CompletionResultType]::ParameterName, 'Specify URL query parameters (ex: -Q token=stuff -Q secret=key)')
|
||||
[CompletionResult]::new('-S', 'S', [CompletionResultType]::ParameterName, 'Filter out messages of a particular size (ex: -S 5120 -S 4927,1970)')
|
||||
[CompletionResult]::new('--filter-size', 'filter-size', [CompletionResultType]::ParameterName, 'Filter out messages of a particular size (ex: -S 5120 -S 4927,1970)')
|
||||
[CompletionResult]::new('-X', 'X', [CompletionResultType]::ParameterName, 'Filter out messages via regular expression matching on the response''s body (ex: -X ''^ignore me$'')')
|
||||
@@ -62,38 +55,65 @@ Register-ArgumentCompleter -Native -CommandName 'feroxbuster' -ScriptBlock {
|
||||
[CompletionResult]::new('-C', 'C', [CompletionResultType]::ParameterName, 'Filter out status codes (deny list) (ex: -C 200 -C 401)')
|
||||
[CompletionResult]::new('--filter-status', 'filter-status', [CompletionResultType]::ParameterName, 'Filter out status codes (deny list) (ex: -C 200 -C 401)')
|
||||
[CompletionResult]::new('--filter-similar-to', 'filter-similar-to', [CompletionResultType]::ParameterName, 'Filter out pages that are similar to the given page (ex. --filter-similar-to http://site.xyz/soft404)')
|
||||
[CompletionResult]::new('-s', 's', [CompletionResultType]::ParameterName, 'Status Codes to include (allow list) (default: 200 204 301 302 307 308 401 403 405)')
|
||||
[CompletionResult]::new('--status-codes', 'status-codes', [CompletionResultType]::ParameterName, 'Status Codes to include (allow list) (default: 200 204 301 302 307 308 401 403 405)')
|
||||
[CompletionResult]::new('-T', 'T', [CompletionResultType]::ParameterName, 'Number of seconds before a client''s request times out (default: 7)')
|
||||
[CompletionResult]::new('--timeout', 'timeout', [CompletionResultType]::ParameterName, 'Number of seconds before a client''s request times out (default: 7)')
|
||||
[CompletionResult]::new('-t', 't', [CompletionResultType]::ParameterName, 'Number of concurrent threads (default: 50)')
|
||||
[CompletionResult]::new('--threads', 'threads', [CompletionResultType]::ParameterName, 'Number of concurrent threads (default: 50)')
|
||||
[CompletionResult]::new('-d', 'd', [CompletionResultType]::ParameterName, 'Maximum recursion depth, a depth of 0 is infinite recursion (default: 4)')
|
||||
[CompletionResult]::new('--depth', 'depth', [CompletionResultType]::ParameterName, 'Maximum recursion depth, a depth of 0 is infinite recursion (default: 4)')
|
||||
[CompletionResult]::new('-L', 'L', [CompletionResultType]::ParameterName, 'Limit total number of concurrent scans (default: 0, i.e. no limit)')
|
||||
[CompletionResult]::new('--scan-limit', 'scan-limit', [CompletionResultType]::ParameterName, 'Limit total number of concurrent scans (default: 0, i.e. no limit)')
|
||||
[CompletionResult]::new('--parallel', 'parallel', [CompletionResultType]::ParameterName, 'Run parallel feroxbuster instances (one child process per url passed via stdin)')
|
||||
[CompletionResult]::new('--rate-limit', 'rate-limit', [CompletionResultType]::ParameterName, 'Limit number of requests per second (per directory) (default: 0, i.e. no limit)')
|
||||
[CompletionResult]::new('--time-limit', 'time-limit', [CompletionResultType]::ParameterName, 'Limit total run time of all scans (ex: --time-limit 10m)')
|
||||
[CompletionResult]::new('-w', 'w', [CompletionResultType]::ParameterName, 'Path to the wordlist')
|
||||
[CompletionResult]::new('--wordlist', 'wordlist', [CompletionResultType]::ParameterName, 'Path to the wordlist')
|
||||
[CompletionResult]::new('-I', 'I', [CompletionResultType]::ParameterName, 'File extension(s) to Ignore while collecting extensions (only used with --collect-extensions)')
|
||||
[CompletionResult]::new('--dont-collect', 'dont-collect', [CompletionResultType]::ParameterName, 'File extension(s) to Ignore while collecting extensions (only used with --collect-extensions)')
|
||||
[CompletionResult]::new('-o', 'o', [CompletionResultType]::ParameterName, 'Output file to write results to (use w/ --json for JSON entries)')
|
||||
[CompletionResult]::new('--output', 'output', [CompletionResultType]::ParameterName, 'Output file to write results to (use w/ --json for JSON entries)')
|
||||
[CompletionResult]::new('--debug-log', 'debug-log', [CompletionResultType]::ParameterName, 'Output file to write log entries (use w/ --json for JSON entries)')
|
||||
[CompletionResult]::new('--stdin', 'stdin', [CompletionResultType]::ParameterName, 'Read url(s) from STDIN')
|
||||
[CompletionResult]::new('--burp', 'burp', [CompletionResultType]::ParameterName, 'Set --proxy to http://127.0.0.1:8080 and set --insecure to true')
|
||||
[CompletionResult]::new('--burp-replay', 'burp-replay', [CompletionResultType]::ParameterName, 'Set --replay-proxy to http://127.0.0.1:8080 and set --insecure to true')
|
||||
[CompletionResult]::new('--smart', 'smart', [CompletionResultType]::ParameterName, 'Set --extract-links, --auto-tune, --collect-words, and --collect-backups to true')
|
||||
[CompletionResult]::new('--thorough', 'thorough', [CompletionResultType]::ParameterName, 'Use the same settings as --smart and set --collect-extensions to true')
|
||||
[CompletionResult]::new('-A', 'A', [CompletionResultType]::ParameterName, 'Use a random User-Agent')
|
||||
[CompletionResult]::new('--random-agent', 'random-agent', [CompletionResultType]::ParameterName, 'Use a random User-Agent')
|
||||
[CompletionResult]::new('-f', 'f', [CompletionResultType]::ParameterName, 'Append / to each request''s URL')
|
||||
[CompletionResult]::new('--add-slash', 'add-slash', [CompletionResultType]::ParameterName, 'Append / to each request''s URL')
|
||||
[CompletionResult]::new('-r', 'r', [CompletionResultType]::ParameterName, 'Allow client to follow redirects')
|
||||
[CompletionResult]::new('--redirects', 'redirects', [CompletionResultType]::ParameterName, 'Allow client to follow redirects')
|
||||
[CompletionResult]::new('-k', 'k', [CompletionResultType]::ParameterName, 'Disables TLS certificate validation in the client')
|
||||
[CompletionResult]::new('--insecure', 'insecure', [CompletionResultType]::ParameterName, 'Disables TLS certificate validation in the client')
|
||||
[CompletionResult]::new('-n', 'n', [CompletionResultType]::ParameterName, 'Do not scan recursively')
|
||||
[CompletionResult]::new('--no-recursion', 'no-recursion', [CompletionResultType]::ParameterName, 'Do not scan recursively')
|
||||
[CompletionResult]::new('--force-recursion', 'force-recursion', [CompletionResultType]::ParameterName, 'Force recursion attempts on all ''found'' endpoints (still respects recursion depth)')
|
||||
[CompletionResult]::new('-e', 'e', [CompletionResultType]::ParameterName, 'Extract links from response body (html, javascript, etc...); make new requests based on findings')
|
||||
[CompletionResult]::new('--extract-links', 'extract-links', [CompletionResultType]::ParameterName, 'Extract links from response body (html, javascript, etc...); make new requests based on findings')
|
||||
[CompletionResult]::new('--auto-tune', 'auto-tune', [CompletionResultType]::ParameterName, 'Automatically lower scan rate when an excessive amount of errors are encountered')
|
||||
[CompletionResult]::new('--auto-bail', 'auto-bail', [CompletionResultType]::ParameterName, 'Automatically stop scanning when an excessive amount of errors are encountered')
|
||||
[CompletionResult]::new('-D', 'D', [CompletionResultType]::ParameterName, 'Don''t auto-filter wildcard responses')
|
||||
[CompletionResult]::new('--dont-filter', 'dont-filter', [CompletionResultType]::ParameterName, 'Don''t auto-filter wildcard responses')
|
||||
[CompletionResult]::new('-E', 'E', [CompletionResultType]::ParameterName, 'Automatically discover extensions and add them to --extensions (unless they''re in --dont-collect)')
|
||||
[CompletionResult]::new('--collect-extensions', 'collect-extensions', [CompletionResultType]::ParameterName, 'Automatically discover extensions and add them to --extensions (unless they''re in --dont-collect)')
|
||||
[CompletionResult]::new('-B', 'B', [CompletionResultType]::ParameterName, 'Automatically request likely backup extensions for "found" urls')
|
||||
[CompletionResult]::new('--collect-backups', 'collect-backups', [CompletionResultType]::ParameterName, 'Automatically request likely backup extensions for "found" urls')
|
||||
[CompletionResult]::new('-g', 'g', [CompletionResultType]::ParameterName, 'Automatically discover important words from within responses and add them to the wordlist')
|
||||
[CompletionResult]::new('--collect-words', 'collect-words', [CompletionResultType]::ParameterName, 'Automatically discover important words from within responses and add them to the wordlist')
|
||||
[CompletionResult]::new('-v', 'v', [CompletionResultType]::ParameterName, 'Increase verbosity level (use -vv or more for greater effect. [CAUTION] 4 -v''s is probably too much)')
|
||||
[CompletionResult]::new('--verbosity', 'verbosity', [CompletionResultType]::ParameterName, 'Increase verbosity level (use -vv or more for greater effect. [CAUTION] 4 -v''s is probably too much)')
|
||||
[CompletionResult]::new('--silent', 'silent', [CompletionResultType]::ParameterName, 'Only print URLs + turn off logging (good for piping a list of urls to other commands)')
|
||||
[CompletionResult]::new('-q', 'q', [CompletionResultType]::ParameterName, 'Hide progress bars and banner (good for tmux windows w/ notifications)')
|
||||
[CompletionResult]::new('--quiet', 'quiet', [CompletionResultType]::ParameterName, 'Hide progress bars and banner (good for tmux windows w/ notifications)')
|
||||
[CompletionResult]::new('--auto-tune', 'auto-tune', [CompletionResultType]::ParameterName, 'Automatically lower scan rate when an excessive amount of errors are encountered')
|
||||
[CompletionResult]::new('--auto-bail', 'auto-bail', [CompletionResultType]::ParameterName, 'Automatically stop scanning when an excessive amount of errors are encountered')
|
||||
[CompletionResult]::new('--json', 'json', [CompletionResultType]::ParameterName, 'Emit JSON logs to --output and --debug-log instead of normal text')
|
||||
[CompletionResult]::new('-D', 'D', [CompletionResultType]::ParameterName, 'Don''t auto-filter wildcard responses')
|
||||
[CompletionResult]::new('--dont-filter', 'dont-filter', [CompletionResultType]::ParameterName, 'Don''t auto-filter wildcard responses')
|
||||
[CompletionResult]::new('-A', 'A', [CompletionResultType]::ParameterName, 'Use a random User-Agent')
|
||||
[CompletionResult]::new('--random-agent', 'random-agent', [CompletionResultType]::ParameterName, 'Use a random User-Agent')
|
||||
[CompletionResult]::new('-r', 'r', [CompletionResultType]::ParameterName, 'Follow redirects')
|
||||
[CompletionResult]::new('--redirects', 'redirects', [CompletionResultType]::ParameterName, 'Follow redirects')
|
||||
[CompletionResult]::new('-k', 'k', [CompletionResultType]::ParameterName, 'Disables TLS certificate validation')
|
||||
[CompletionResult]::new('--insecure', 'insecure', [CompletionResultType]::ParameterName, 'Disables TLS certificate validation')
|
||||
[CompletionResult]::new('-n', 'n', [CompletionResultType]::ParameterName, 'Do not scan recursively')
|
||||
[CompletionResult]::new('--no-recursion', 'no-recursion', [CompletionResultType]::ParameterName, 'Do not scan recursively')
|
||||
[CompletionResult]::new('-f', 'f', [CompletionResultType]::ParameterName, 'Append / to each request')
|
||||
[CompletionResult]::new('--add-slash', 'add-slash', [CompletionResultType]::ParameterName, 'Append / to each request')
|
||||
[CompletionResult]::new('--stdin', 'stdin', [CompletionResultType]::ParameterName, 'Read url(s) from STDIN')
|
||||
[CompletionResult]::new('-e', 'e', [CompletionResultType]::ParameterName, 'Extract links from response body (html, javascript, etc...); make new requests based on findings (default: false)')
|
||||
[CompletionResult]::new('--extract-links', 'extract-links', [CompletionResultType]::ParameterName, 'Extract links from response body (html, javascript, etc...); make new requests based on findings (default: false)')
|
||||
[CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Prints help information')
|
||||
[CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Prints help information')
|
||||
[CompletionResult]::new('-V', 'V', [CompletionResultType]::ParameterName, 'Prints version information')
|
||||
[CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Prints version information')
|
||||
[CompletionResult]::new('--no-state', 'no-state', [CompletionResultType]::ParameterName, 'Disable state output file (*.state)')
|
||||
[CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help information (use `--help` for more detail)')
|
||||
[CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help information (use `--help` for more detail)')
|
||||
[CompletionResult]::new('-V', 'V', [CompletionResultType]::ParameterName, 'Print version information')
|
||||
[CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version information')
|
||||
break
|
||||
}
|
||||
})
|
||||
|
||||
@@ -8,11 +8,10 @@ _feroxbuster() {
|
||||
|
||||
for i in ${COMP_WORDS[@]}
|
||||
do
|
||||
case "${i}" in
|
||||
feroxbuster)
|
||||
case "${cmd},${i}" in
|
||||
",$1")
|
||||
cmd="feroxbuster"
|
||||
;;
|
||||
|
||||
*)
|
||||
;;
|
||||
esac
|
||||
@@ -20,90 +19,17 @@ _feroxbuster() {
|
||||
|
||||
case "${cmd}" in
|
||||
feroxbuster)
|
||||
opts=" -v -q -D -A -r -k -n -f -e -h -V -w -u -t -d -T -p -P -R -s -o -a -x -H -Q -S -X -W -N -C -L --verbosity --silent --quiet --auto-tune --auto-bail --json --dont-filter --random-agent --redirects --insecure --no-recursion --add-slash --stdin --extract-links --help --version --wordlist --url --threads --depth --timeout --proxy --replay-proxy --replay-codes --status-codes --output --resume-from --debug-log --user-agent --extensions --dont-scan --headers --query --filter-size --filter-regex --filter-words --filter-lines --filter-status --filter-similar-to --scan-limit --parallel --rate-limit --time-limit "
|
||||
opts="-u -p -P -R -a -A -x -m -H -b -Q -f -S -X -W -N -C -s -T -r -k -t -n -d -e -L -w -D -E -B -g -I -v -q -o -h -V --url --stdin --resume-from --burp --burp-replay --smart --thorough --proxy --replay-proxy --replay-codes --user-agent --random-agent --extensions --methods --data --headers --cookies --query --add-slash --dont-scan --filter-size --filter-regex --filter-words --filter-lines --filter-status --filter-similar-to --status-codes --timeout --redirects --insecure --threads --no-recursion --depth --force-recursion --extract-links --scan-limit --parallel --rate-limit --time-limit --wordlist --auto-tune --auto-bail --dont-filter --collect-extensions --collect-backups --collect-words --dont-collect --verbosity --silent --quiet --json --output --debug-log --no-state --help --version"
|
||||
if [[ ${cur} == -* || ${COMP_CWORD} -eq 1 ]] ; then
|
||||
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
|
||||
return 0
|
||||
fi
|
||||
case "${prev}" in
|
||||
|
||||
--wordlist)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-w)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--url)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-u)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--threads)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-t)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--depth)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-d)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--timeout)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-T)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--proxy)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-p)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--replay-proxy)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-P)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--replay-codes)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-R)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--status-codes)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-s)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--output)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-o)
|
||||
-u)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
@@ -111,7 +37,27 @@ _feroxbuster() {
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--debug-log)
|
||||
--proxy)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-p)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--replay-proxy)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-P)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--replay-codes)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-R)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
@@ -119,7 +65,7 @@ _feroxbuster() {
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-a)
|
||||
-a)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
@@ -127,11 +73,19 @@ _feroxbuster() {
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-x)
|
||||
-x)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--dont-scan)
|
||||
--methods)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-m)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--data)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
@@ -139,7 +93,15 @@ _feroxbuster() {
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-H)
|
||||
-H)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--cookies)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-b)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
@@ -147,7 +109,11 @@ _feroxbuster() {
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-Q)
|
||||
-Q)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--dont-scan)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
@@ -155,7 +121,7 @@ _feroxbuster() {
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-S)
|
||||
-S)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
@@ -163,7 +129,7 @@ _feroxbuster() {
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-X)
|
||||
-X)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
@@ -171,7 +137,7 @@ _feroxbuster() {
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-W)
|
||||
-W)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
@@ -179,7 +145,7 @@ _feroxbuster() {
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-N)
|
||||
-N)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
@@ -187,7 +153,7 @@ _feroxbuster() {
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-C)
|
||||
-C)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
@@ -195,11 +161,43 @@ _feroxbuster() {
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--status-codes)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-s)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--timeout)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-T)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--threads)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-t)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--depth)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-d)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--scan-limit)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-L)
|
||||
-L)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
@@ -215,6 +213,34 @@ _feroxbuster() {
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--wordlist)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-w)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--dont-collect)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-I)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--output)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
-o)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
--debug-log)
|
||||
COMPREPLY=($(compgen -f "${cur}"))
|
||||
return 0
|
||||
;;
|
||||
*)
|
||||
COMPREPLY=()
|
||||
;;
|
||||
@@ -222,7 +248,6 @@ _feroxbuster() {
|
||||
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
|
||||
return 0
|
||||
;;
|
||||
|
||||
esac
|
||||
}
|
||||
|
||||
|
||||
117
shell_completions/feroxbuster.elv
Normal file
117
shell_completions/feroxbuster.elv
Normal file
@@ -0,0 +1,117 @@
|
||||
|
||||
use builtin;
|
||||
use str;
|
||||
|
||||
set edit:completion:arg-completer[feroxbuster] = {|@words|
|
||||
fn spaces {|n|
|
||||
builtin:repeat $n ' ' | str:join ''
|
||||
}
|
||||
fn cand {|text desc|
|
||||
edit:complex-candidate $text &display=$text' '(spaces (- 14 (wcswidth $text)))$desc
|
||||
}
|
||||
var command = 'feroxbuster'
|
||||
for word $words[1..-1] {
|
||||
if (str:has-prefix $word '-') {
|
||||
break
|
||||
}
|
||||
set command = $command';'$word
|
||||
}
|
||||
var completions = [
|
||||
&'feroxbuster'= {
|
||||
cand -u 'The target URL (required, unless [--stdin || --resume-from] used)'
|
||||
cand --url 'The target URL (required, unless [--stdin || --resume-from] used)'
|
||||
cand --resume-from 'State file from which to resume a partially complete scan (ex. --resume-from ferox-1606586780.state)'
|
||||
cand -p 'Proxy to use for requests (ex: http(s)://host:port, socks5(h)://host:port)'
|
||||
cand --proxy 'Proxy to use for requests (ex: http(s)://host:port, socks5(h)://host:port)'
|
||||
cand -P 'Send only unfiltered requests through a Replay Proxy, instead of all requests'
|
||||
cand --replay-proxy 'Send only unfiltered requests through a Replay Proxy, instead of all requests'
|
||||
cand -R 'Status Codes to send through a Replay Proxy when found (default: --status-codes value)'
|
||||
cand --replay-codes 'Status Codes to send through a Replay Proxy when found (default: --status-codes value)'
|
||||
cand -a 'Sets the User-Agent (default: feroxbuster/2.7.3)'
|
||||
cand --user-agent 'Sets the User-Agent (default: feroxbuster/2.7.3)'
|
||||
cand -x 'File extension(s) to search for (ex: -x php -x pdf js)'
|
||||
cand --extensions 'File extension(s) to search for (ex: -x php -x pdf js)'
|
||||
cand -m 'Which HTTP request method(s) should be sent (default: GET)'
|
||||
cand --methods 'Which HTTP request method(s) should be sent (default: GET)'
|
||||
cand --data 'Request''s Body; can read data from a file if input starts with an @ (ex: @post.bin)'
|
||||
cand -H 'Specify HTTP headers to be used in each request (ex: -H Header:val -H ''stuff: things'')'
|
||||
cand --headers 'Specify HTTP headers to be used in each request (ex: -H Header:val -H ''stuff: things'')'
|
||||
cand -b 'Specify HTTP cookies to be used in each request (ex: -b stuff=things)'
|
||||
cand --cookies 'Specify HTTP cookies to be used in each request (ex: -b stuff=things)'
|
||||
cand -Q 'Request''s URL query parameters (ex: -Q token=stuff -Q secret=key)'
|
||||
cand --query 'Request''s URL query parameters (ex: -Q token=stuff -Q secret=key)'
|
||||
cand --dont-scan 'URL(s) or Regex Pattern(s) to exclude from recursion/scans'
|
||||
cand -S 'Filter out messages of a particular size (ex: -S 5120 -S 4927,1970)'
|
||||
cand --filter-size 'Filter out messages of a particular size (ex: -S 5120 -S 4927,1970)'
|
||||
cand -X 'Filter out messages via regular expression matching on the response''s body (ex: -X ''^ignore me$'')'
|
||||
cand --filter-regex 'Filter out messages via regular expression matching on the response''s body (ex: -X ''^ignore me$'')'
|
||||
cand -W 'Filter out messages of a particular word count (ex: -W 312 -W 91,82)'
|
||||
cand --filter-words 'Filter out messages of a particular word count (ex: -W 312 -W 91,82)'
|
||||
cand -N 'Filter out messages of a particular line count (ex: -N 20 -N 31,30)'
|
||||
cand --filter-lines 'Filter out messages of a particular line count (ex: -N 20 -N 31,30)'
|
||||
cand -C 'Filter out status codes (deny list) (ex: -C 200 -C 401)'
|
||||
cand --filter-status 'Filter out status codes (deny list) (ex: -C 200 -C 401)'
|
||||
cand --filter-similar-to 'Filter out pages that are similar to the given page (ex. --filter-similar-to http://site.xyz/soft404)'
|
||||
cand -s 'Status Codes to include (allow list) (default: 200 204 301 302 307 308 401 403 405)'
|
||||
cand --status-codes 'Status Codes to include (allow list) (default: 200 204 301 302 307 308 401 403 405)'
|
||||
cand -T 'Number of seconds before a client''s request times out (default: 7)'
|
||||
cand --timeout 'Number of seconds before a client''s request times out (default: 7)'
|
||||
cand -t 'Number of concurrent threads (default: 50)'
|
||||
cand --threads 'Number of concurrent threads (default: 50)'
|
||||
cand -d 'Maximum recursion depth, a depth of 0 is infinite recursion (default: 4)'
|
||||
cand --depth 'Maximum recursion depth, a depth of 0 is infinite recursion (default: 4)'
|
||||
cand -L 'Limit total number of concurrent scans (default: 0, i.e. no limit)'
|
||||
cand --scan-limit 'Limit total number of concurrent scans (default: 0, i.e. no limit)'
|
||||
cand --parallel 'Run parallel feroxbuster instances (one child process per url passed via stdin)'
|
||||
cand --rate-limit 'Limit number of requests per second (per directory) (default: 0, i.e. no limit)'
|
||||
cand --time-limit 'Limit total run time of all scans (ex: --time-limit 10m)'
|
||||
cand -w 'Path to the wordlist'
|
||||
cand --wordlist 'Path to the wordlist'
|
||||
cand -I 'File extension(s) to Ignore while collecting extensions (only used with --collect-extensions)'
|
||||
cand --dont-collect 'File extension(s) to Ignore while collecting extensions (only used with --collect-extensions)'
|
||||
cand -o 'Output file to write results to (use w/ --json for JSON entries)'
|
||||
cand --output 'Output file to write results to (use w/ --json for JSON entries)'
|
||||
cand --debug-log 'Output file to write log entries (use w/ --json for JSON entries)'
|
||||
cand --stdin 'Read url(s) from STDIN'
|
||||
cand --burp 'Set --proxy to http://127.0.0.1:8080 and set --insecure to true'
|
||||
cand --burp-replay 'Set --replay-proxy to http://127.0.0.1:8080 and set --insecure to true'
|
||||
cand --smart 'Set --extract-links, --auto-tune, --collect-words, and --collect-backups to true'
|
||||
cand --thorough 'Use the same settings as --smart and set --collect-extensions to true'
|
||||
cand -A 'Use a random User-Agent'
|
||||
cand --random-agent 'Use a random User-Agent'
|
||||
cand -f 'Append / to each request''s URL'
|
||||
cand --add-slash 'Append / to each request''s URL'
|
||||
cand -r 'Allow client to follow redirects'
|
||||
cand --redirects 'Allow client to follow redirects'
|
||||
cand -k 'Disables TLS certificate validation in the client'
|
||||
cand --insecure 'Disables TLS certificate validation in the client'
|
||||
cand -n 'Do not scan recursively'
|
||||
cand --no-recursion 'Do not scan recursively'
|
||||
cand --force-recursion 'Force recursion attempts on all ''found'' endpoints (still respects recursion depth)'
|
||||
cand -e 'Extract links from response body (html, javascript, etc...); make new requests based on findings'
|
||||
cand --extract-links 'Extract links from response body (html, javascript, etc...); make new requests based on findings'
|
||||
cand --auto-tune 'Automatically lower scan rate when an excessive amount of errors are encountered'
|
||||
cand --auto-bail 'Automatically stop scanning when an excessive amount of errors are encountered'
|
||||
cand -D 'Don''t auto-filter wildcard responses'
|
||||
cand --dont-filter 'Don''t auto-filter wildcard responses'
|
||||
cand -E 'Automatically discover extensions and add them to --extensions (unless they''re in --dont-collect)'
|
||||
cand --collect-extensions 'Automatically discover extensions and add them to --extensions (unless they''re in --dont-collect)'
|
||||
cand -B 'Automatically request likely backup extensions for "found" urls'
|
||||
cand --collect-backups 'Automatically request likely backup extensions for "found" urls'
|
||||
cand -g 'Automatically discover important words from within responses and add them to the wordlist'
|
||||
cand --collect-words 'Automatically discover important words from within responses and add them to the wordlist'
|
||||
cand -v 'Increase verbosity level (use -vv or more for greater effect. [CAUTION] 4 -v''s is probably too much)'
|
||||
cand --verbosity 'Increase verbosity level (use -vv or more for greater effect. [CAUTION] 4 -v''s is probably too much)'
|
||||
cand --silent 'Only print URLs + turn off logging (good for piping a list of urls to other commands)'
|
||||
cand -q 'Hide progress bars and banner (good for tmux windows w/ notifications)'
|
||||
cand --quiet 'Hide progress bars and banner (good for tmux windows w/ notifications)'
|
||||
cand --json 'Emit JSON logs to --output and --debug-log instead of normal text'
|
||||
cand --no-state 'Disable state output file (*.state)'
|
||||
cand -h 'Print help information (use `--help` for more detail)'
|
||||
cand --help 'Print help information (use `--help` for more detail)'
|
||||
cand -V 'Print version information'
|
||||
cand --version 'Print version information'
|
||||
}
|
||||
]
|
||||
$completions[$command]
|
||||
}
|
||||
@@ -12,8 +12,11 @@ complete -c feroxbuster -n "__fish_use_subcommand" -l resume-from -d 'State file
|
||||
complete -c feroxbuster -n "__fish_use_subcommand" -l debug-log -d 'Output file to write log entries (use w/ --json for JSON entries)'
|
||||
complete -c feroxbuster -n "__fish_use_subcommand" -s a -l user-agent -d 'Sets the User-Agent (default: feroxbuster/VERSION)'
|
||||
complete -c feroxbuster -n "__fish_use_subcommand" -s x -l extensions -d 'File extension(s) to search for (ex: -x php -x pdf js)'
|
||||
complete -c feroxbuster -n "__fish_use_subcommand" -s m -l methods -d 'HTTP request method(s) (default: GET)'
|
||||
complete -c feroxbuster -n "__fish_use_subcommand" -l data -d 'HTTP Body data; can read data from a file if input starts with an @ (ex: @post.bin)'
|
||||
complete -c feroxbuster -n "__fish_use_subcommand" -l dont-scan -d 'URL(s) or Regex Pattern(s) to exclude from recursion/scans'
|
||||
complete -c feroxbuster -n "__fish_use_subcommand" -s H -l headers -d 'Specify HTTP headers (ex: -H Header:val \'stuff: things\')'
|
||||
complete -c feroxbuster -n "__fish_use_subcommand" -s b -l cookies -d 'Specify HTTP cookies (ex: -b stuff=things)'
|
||||
complete -c feroxbuster -n "__fish_use_subcommand" -s Q -l query -d 'Specify URL query parameters (ex: -Q token=stuff -Q secret=key)'
|
||||
complete -c feroxbuster -n "__fish_use_subcommand" -s S -l filter-size -d 'Filter out messages of a particular size (ex: -S 5120 -S 4927,1970)'
|
||||
complete -c feroxbuster -n "__fish_use_subcommand" -s X -l filter-regex -d 'Filter out messages via regular expression matching on the response\'s body (ex: -X \'^ignore me$\')'
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::{
|
||||
config::Configuration,
|
||||
event_handlers::Handles,
|
||||
utils::{logged_request, status_colorizer},
|
||||
VERSION,
|
||||
DEFAULT_IGNORED_EXTENSIONS, DEFAULT_METHOD, VERSION,
|
||||
};
|
||||
use anyhow::{bail, Result};
|
||||
use console::{style, Emoji};
|
||||
@@ -98,6 +98,12 @@ pub struct Banner {
|
||||
/// represents Configuration.extensions
|
||||
extensions: BannerEntry,
|
||||
|
||||
/// represents Configuration.methods
|
||||
methods: BannerEntry,
|
||||
|
||||
/// represents Configuration.data
|
||||
data: BannerEntry,
|
||||
|
||||
/// represents Configuration.insecure
|
||||
insecure: BannerEntry,
|
||||
|
||||
@@ -145,6 +151,21 @@ pub struct Banner {
|
||||
|
||||
/// whether or not there is a known new version
|
||||
pub(super) update_status: UpdateStatus,
|
||||
|
||||
/// represents Configuration.collect_extensions
|
||||
collect_extensions: BannerEntry,
|
||||
|
||||
/// represents Configuration.dont_collect
|
||||
dont_collect: BannerEntry,
|
||||
|
||||
/// represents Configuration.collect_backups
|
||||
collect_backups: BannerEntry,
|
||||
|
||||
/// represents Configuration.collect_words
|
||||
collect_words: BannerEntry,
|
||||
|
||||
/// represents Configuration.collect_words
|
||||
force_recursion: BannerEntry,
|
||||
}
|
||||
|
||||
/// implementation of Banner
|
||||
@@ -282,6 +303,8 @@ impl Banner {
|
||||
&config.scan_limit.to_string(),
|
||||
);
|
||||
|
||||
let force_recursion =
|
||||
BannerEntry::new("🤘", "Force Recursion", &config.force_recursion.to_string());
|
||||
let replay_proxy = BannerEntry::new("🎥", "Replay Proxy", &config.replay_proxy);
|
||||
let auto_tune = BannerEntry::new("🎶", "Auto Tune", &config.auto_tune.to_string());
|
||||
let auto_bail = BannerEntry::new("🪣", "Auto Bail", &config.auto_bail.to_string());
|
||||
@@ -302,6 +325,38 @@ impl Banner {
|
||||
"Extensions",
|
||||
&format!("[{}]", config.extensions.join(", ")),
|
||||
);
|
||||
let methods = BannerEntry::new(
|
||||
"🏁",
|
||||
"HTTP methods",
|
||||
&format!("[{}]", config.methods.join(", ")),
|
||||
);
|
||||
|
||||
let dont_collect = if config.dont_collect == DEFAULT_IGNORED_EXTENSIONS {
|
||||
// default has 30+ extensions, just trim it up
|
||||
BannerEntry::new(
|
||||
"💸",
|
||||
"Ignored Extensions",
|
||||
"[Images, Movies, Audio, etc...]",
|
||||
)
|
||||
} else {
|
||||
BannerEntry::new(
|
||||
"💸",
|
||||
"Ignored Extensions",
|
||||
&format!("[{}]", config.dont_collect.join(", ")),
|
||||
)
|
||||
};
|
||||
|
||||
let offset = std::cmp::min(config.data.len(), 30);
|
||||
let data = String::from_utf8(config.data[..offset].to_vec())
|
||||
.unwrap_or_else(|_err| {
|
||||
format!(
|
||||
"{:x?} ...",
|
||||
&config.data[..std::cmp::min(config.data.len(), 13)]
|
||||
)
|
||||
})
|
||||
.replace('\n', " ")
|
||||
.replace('\r', "");
|
||||
let data = BannerEntry::new("💣", "HTTP Body", &data);
|
||||
let insecure = BannerEntry::new("🔓", "Insecure", &config.insecure.to_string());
|
||||
let redirects = BannerEntry::new("📍", "Follow Redirects", &config.redirects.to_string());
|
||||
let dont_filter =
|
||||
@@ -311,6 +366,16 @@ impl Banner {
|
||||
let parallel = BannerEntry::new("🛤", "Parallel Scans", &config.parallel.to_string());
|
||||
let rate_limit =
|
||||
BannerEntry::new("🚧", "Requests per Second", &config.rate_limit.to_string());
|
||||
let collect_extensions = BannerEntry::new(
|
||||
"💰",
|
||||
"Collect Extensions",
|
||||
&config.collect_extensions.to_string(),
|
||||
);
|
||||
let collect_backups =
|
||||
BannerEntry::new("🏦", "Collect Backups", &config.collect_backups.to_string());
|
||||
|
||||
let collect_words =
|
||||
BannerEntry::new("🤑", "Collect Words", &config.collect_words.to_string());
|
||||
|
||||
Self {
|
||||
targets,
|
||||
@@ -339,6 +404,8 @@ impl Banner {
|
||||
output,
|
||||
debug_log,
|
||||
extensions,
|
||||
methods,
|
||||
data,
|
||||
insecure,
|
||||
dont_filter,
|
||||
redirects,
|
||||
@@ -347,8 +414,13 @@ impl Banner {
|
||||
no_recursion,
|
||||
rate_limit,
|
||||
scan_limit,
|
||||
force_recursion,
|
||||
time_limit,
|
||||
url_denylist,
|
||||
collect_extensions,
|
||||
collect_backups,
|
||||
collect_words,
|
||||
dont_collect,
|
||||
config: cfg,
|
||||
version: VERSION.to_string(),
|
||||
update_status: UpdateStatus::Unknown,
|
||||
@@ -395,7 +467,7 @@ by Ben "epi" Risher {} ver: {}"#,
|
||||
|
||||
let api_url = Url::parse(url)?;
|
||||
|
||||
let result = logged_request(&api_url, handles.clone()).await?;
|
||||
let result = logged_request(&api_url, DEFAULT_METHOD, None, handles.clone()).await?;
|
||||
let body = result.text().await?;
|
||||
|
||||
let json_response: Value = serde_json::from_str(&body)?;
|
||||
@@ -445,11 +517,12 @@ by Ben "epi" Risher {} ver: {}"#,
|
||||
|
||||
writeln!(&mut writer, "{}", self.threads)?;
|
||||
writeln!(&mut writer, "{}", self.wordlist)?;
|
||||
writeln!(&mut writer, "{}", self.status_codes)?;
|
||||
|
||||
if !config.filter_status.is_empty() {
|
||||
// exception here for an optional print in the middle of always printed values is due
|
||||
// to me wanting the allows and denys to be printed one after the other
|
||||
if config.filter_status.is_empty() {
|
||||
// -C and -s are mutually exclusive, and -s meaning changes when -C is used
|
||||
// so only print one or the other
|
||||
writeln!(&mut writer, "{}", self.status_codes)?;
|
||||
} else {
|
||||
writeln!(&mut writer, "{}", self.filter_status)?;
|
||||
}
|
||||
|
||||
@@ -525,6 +598,28 @@ by Ben "epi" Risher {} ver: {}"#,
|
||||
writeln!(&mut writer, "{}", self.extensions)?;
|
||||
}
|
||||
|
||||
if config.collect_extensions {
|
||||
// dont-collect is active only when collect-extensions is used
|
||||
writeln!(&mut writer, "{}", self.collect_extensions)?;
|
||||
writeln!(&mut writer, "{}", self.dont_collect)?;
|
||||
}
|
||||
|
||||
if config.collect_backups {
|
||||
writeln!(&mut writer, "{}", self.collect_backups)?;
|
||||
}
|
||||
|
||||
if config.collect_words {
|
||||
writeln!(&mut writer, "{}", self.collect_words)?;
|
||||
}
|
||||
|
||||
if !config.methods.is_empty() {
|
||||
writeln!(&mut writer, "{}", self.methods)?;
|
||||
}
|
||||
|
||||
if !config.data.is_empty() {
|
||||
writeln!(&mut writer, "{}", self.data)?;
|
||||
}
|
||||
|
||||
if config.insecure {
|
||||
writeln!(&mut writer, "{}", self.insecure)?;
|
||||
}
|
||||
@@ -554,6 +649,10 @@ by Ben "epi" Risher {} ver: {}"#,
|
||||
|
||||
writeln!(&mut writer, "{}", self.no_recursion)?;
|
||||
|
||||
if config.force_recursion {
|
||||
writeln!(&mut writer, "{}", self.force_recursion)?;
|
||||
}
|
||||
|
||||
if config.scan_limit > 0 {
|
||||
writeln!(&mut writer, "{}", self.scan_limit)?;
|
||||
}
|
||||
|
||||
@@ -27,7 +27,8 @@ pub fn initialize(
|
||||
.user_agent(user_agent)
|
||||
.danger_accept_invalid_certs(insecure)
|
||||
.default_headers(header_map)
|
||||
.redirect(policy);
|
||||
.redirect(policy)
|
||||
.http1_title_case_headers();
|
||||
|
||||
if let Some(some_proxy) = proxy {
|
||||
if !some_proxy.is_empty() {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::utils::{
|
||||
depth, report_and_exit, save_state, serialized_type, status_codes, threads, timeout,
|
||||
user_agent, wordlist, OutputLevel, RequesterPolicy,
|
||||
depth, ignored_extensions, methods, report_and_exit, save_state, serialized_type, status_codes,
|
||||
threads, timeout, user_agent, wordlist, OutputLevel, RequesterPolicy,
|
||||
};
|
||||
use crate::config::determine_output_level;
|
||||
use crate::config::utils::determine_requester_policy;
|
||||
@@ -9,9 +9,9 @@ use crate::{
|
||||
DEFAULT_CONFIG_NAME,
|
||||
};
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use clap::{value_t, ArgMatches};
|
||||
use clap::{parser::ValueSource, ArgMatches};
|
||||
use regex::Regex;
|
||||
use reqwest::{Client, StatusCode, Url};
|
||||
use reqwest::{Client, Method, StatusCode, Url};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
@@ -22,17 +22,10 @@ use std::{
|
||||
|
||||
/// macro helper to abstract away repetitive configuration updates
|
||||
macro_rules! update_config_if_present {
|
||||
($c:expr, $m:ident, $v:expr, $t:ty) => {
|
||||
match value_t!($m, $v, $t) {
|
||||
Ok(value) => *$c = value, // Update value
|
||||
Err(clap::Error {
|
||||
kind: clap::ErrorKind::ArgumentNotFound,
|
||||
message: _,
|
||||
info: _,
|
||||
}) => {
|
||||
// Do nothing if argument not found
|
||||
}
|
||||
Err(e) => e.exit(), // Exit with error on parse error
|
||||
($conf_val:expr, $matches:ident, $arg_name:expr, $arg_type:ty) => {
|
||||
match $matches.get_one::<$arg_type>($arg_name) {
|
||||
Some(value) => *$conf_val = value.to_owned(), // Update value
|
||||
None => {}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -46,6 +39,35 @@ macro_rules! update_if_not_default {
|
||||
};
|
||||
}
|
||||
|
||||
/// macro helper to abstract away repetitive checks to see if the user has specified a value
|
||||
/// for a given argument from the commandline or if we just had a default value in the parser
|
||||
macro_rules! came_from_cli {
|
||||
($matches:ident, $arg_name:expr) => {
|
||||
matches!(
|
||||
$matches.value_source($arg_name),
|
||||
Some(ValueSource::CommandLine)
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
/// macro helper to abstract away repetitive if not default: update checks, specifically for
|
||||
/// values that are number types, i.e. usize, u64, etc
|
||||
macro_rules! update_config_with_num_type_if_present {
|
||||
($conf_val:expr, $matches:ident, $arg_name:expr, $arg_type:ty) => {
|
||||
if let Some(val) = $matches.get_one::<String>($arg_name) {
|
||||
match val.parse::<$arg_type>() {
|
||||
Ok(v) => *$conf_val = v,
|
||||
Err(_) => {
|
||||
report_and_exit(&format!(
|
||||
"Invalid value for --{}, must be a positive integer",
|
||||
$arg_name
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Represents the final, global configuration of the program.
|
||||
///
|
||||
/// This struct is the combination of the following:
|
||||
@@ -171,6 +193,14 @@ pub struct Configuration {
|
||||
#[serde(default)]
|
||||
pub extensions: Vec<String>,
|
||||
|
||||
/// HTTP requests methods(s) to search for
|
||||
#[serde(default = "methods")]
|
||||
pub methods: Vec<String>,
|
||||
|
||||
/// HTTP Body data to send during request
|
||||
#[serde(default)]
|
||||
pub data: Vec<u8>,
|
||||
|
||||
/// HTTP headers to be used in each request
|
||||
#[serde(default)]
|
||||
pub headers: HashMap<String, String>,
|
||||
@@ -240,8 +270,6 @@ pub struct Configuration {
|
||||
pub resume_from: String,
|
||||
|
||||
/// Whether or not a scan's current state should be saved when user presses Ctrl+C
|
||||
///
|
||||
/// Not configurable from CLI; can only be set from a config file
|
||||
#[serde(default = "save_state")]
|
||||
pub save_state: bool,
|
||||
|
||||
@@ -258,8 +286,29 @@ pub struct Configuration {
|
||||
#[serde(default)]
|
||||
pub url_denylist: Vec<Url>,
|
||||
|
||||
/// URLs that should never be scanned/recursed into based on a regular expression
|
||||
#[serde(with = "serde_regex", default)]
|
||||
pub regex_denylist: Vec<Regex>,
|
||||
|
||||
/// Automatically discover extensions and add them to --extensions (unless they're in --dont-collect)
|
||||
#[serde(default)]
|
||||
pub collect_extensions: bool,
|
||||
|
||||
/// don't collect any of these extensions when --collect-extensions is used
|
||||
#[serde(default = "ignored_extensions")]
|
||||
pub dont_collect: Vec<String>,
|
||||
|
||||
/// Automatically request likely backup extensions on "found" urls
|
||||
#[serde(default)]
|
||||
pub collect_backups: bool,
|
||||
|
||||
/// Automatically discover important words from within responses and add them to the wordlist
|
||||
#[serde(default)]
|
||||
pub collect_words: bool,
|
||||
|
||||
/// override recursion logic to always attempt recursion, still respects --depth
|
||||
#[serde(default)]
|
||||
pub force_recursion: bool,
|
||||
}
|
||||
|
||||
impl Default for Configuration {
|
||||
@@ -304,7 +353,11 @@ impl Default for Configuration {
|
||||
no_recursion: false,
|
||||
extract_links: false,
|
||||
random_agent: false,
|
||||
collect_extensions: false,
|
||||
collect_backups: false,
|
||||
collect_words: false,
|
||||
save_state: true,
|
||||
force_recursion: false,
|
||||
proxy: String::new(),
|
||||
config: String::new(),
|
||||
output: String::new(),
|
||||
@@ -315,6 +368,8 @@ impl Default for Configuration {
|
||||
replay_proxy: String::new(),
|
||||
queries: Vec::new(),
|
||||
extensions: Vec::new(),
|
||||
methods: methods(),
|
||||
data: Vec::new(),
|
||||
filter_size: Vec::new(),
|
||||
filter_regex: Vec::new(),
|
||||
url_denylist: Vec::new(),
|
||||
@@ -327,6 +382,7 @@ impl Default for Configuration {
|
||||
depth: depth(),
|
||||
threads: threads(),
|
||||
wordlist: wordlist(),
|
||||
dont_collect: ignored_extensions(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -357,6 +413,12 @@ impl Configuration {
|
||||
/// - **random_agent**: `false`
|
||||
/// - **insecure**: `false` (don't be insecure, i.e. don't allow invalid certs)
|
||||
/// - **extensions**: `None`
|
||||
/// - **collect_extensions**: `false`
|
||||
/// - **collect_backups**: `false`
|
||||
/// - **collect_words**: `false`
|
||||
/// - **dont_collect**: [`DEFAULT_IGNORED_EXTENSIONS`](constant.DEFAULT_RESPONSE_CODES.html)
|
||||
/// - **methods**: [`DEFAULT_METHOD`](constant.DEFAULT_METHOD.html)
|
||||
/// - **data**: `None`
|
||||
/// - **url_denylist**: `None`
|
||||
/// - **regex_denylist**: `None`
|
||||
/// - **filter_size**: `None`
|
||||
@@ -372,6 +434,7 @@ impl Configuration {
|
||||
/// - **json**: `false`
|
||||
/// - **dont_filter**: `false` (auto filter wildcard responses)
|
||||
/// - **depth**: `4` (maximum recursion depth)
|
||||
/// - **force_recursion**: `false` (still respects recursion depth)
|
||||
/// - **scan_limit**: `0` (no limit on concurrent scans imposed)
|
||||
/// - **parallel**: `0` (no limit on parallel scans imposed)
|
||||
/// - **rate_limit**: `0` (no limit on requests per second imposed)
|
||||
@@ -421,7 +484,7 @@ impl Configuration {
|
||||
|
||||
// --resume-from used, need to first read the Configuration from disk, and then
|
||||
// merge the cli_config into the resumed config
|
||||
if let Some(filename) = args.value_of("resume_from") {
|
||||
if let Some(filename) = args.get_one::<String>("resume_from") {
|
||||
// when resuming a scan, instead of normal configuration loading, we just
|
||||
// load the config from disk by calling resume_scan
|
||||
let mut previous_config = resume_scan(filename);
|
||||
@@ -507,18 +570,21 @@ impl Configuration {
|
||||
fn parse_cli_args(args: &ArgMatches) -> Self {
|
||||
let mut config = Configuration::default();
|
||||
|
||||
update_config_if_present!(&mut config.threads, args, "threads", usize);
|
||||
update_config_if_present!(&mut config.depth, args, "depth", usize);
|
||||
update_config_if_present!(&mut config.scan_limit, args, "scan_limit", usize);
|
||||
update_config_if_present!(&mut config.parallel, args, "parallel", usize);
|
||||
update_config_if_present!(&mut config.rate_limit, args, "rate_limit", usize);
|
||||
update_config_with_num_type_if_present!(&mut config.threads, args, "threads", usize);
|
||||
update_config_with_num_type_if_present!(&mut config.parallel, args, "parallel", usize);
|
||||
update_config_with_num_type_if_present!(&mut config.depth, args, "depth", usize);
|
||||
update_config_with_num_type_if_present!(&mut config.scan_limit, args, "scan_limit", usize);
|
||||
update_config_with_num_type_if_present!(&mut config.rate_limit, args, "rate_limit", usize);
|
||||
update_config_if_present!(&mut config.wordlist, args, "wordlist", String);
|
||||
update_config_if_present!(&mut config.output, args, "output", String);
|
||||
update_config_if_present!(&mut config.debug_log, args, "debug_log", String);
|
||||
update_config_if_present!(&mut config.time_limit, args, "time_limit", String);
|
||||
update_config_if_present!(&mut config.resume_from, args, "resume_from", String);
|
||||
|
||||
if let Some(arg) = args.values_of("status_codes") {
|
||||
if let Ok(Some(inner)) = args.try_get_one::<String>("time_limit") {
|
||||
config.time_limit = inner.to_owned();
|
||||
}
|
||||
|
||||
if let Some(arg) = args.get_many::<String>("status_codes") {
|
||||
config.status_codes = arg
|
||||
.map(|code| {
|
||||
StatusCode::from_bytes(code.as_bytes())
|
||||
@@ -528,7 +594,7 @@ impl Configuration {
|
||||
.collect();
|
||||
}
|
||||
|
||||
if let Some(arg) = args.values_of("replay_codes") {
|
||||
if let Some(arg) = args.get_many::<String>("replay_codes") {
|
||||
// replay codes passed in by the user
|
||||
config.replay_codes = arg
|
||||
.map(|code| {
|
||||
@@ -542,7 +608,7 @@ impl Configuration {
|
||||
config.replay_codes = config.status_codes.clone();
|
||||
}
|
||||
|
||||
if let Some(arg) = args.values_of("filter_status") {
|
||||
if let Some(arg) = args.get_many::<String>("filter_status") {
|
||||
config.filter_status = arg
|
||||
.map(|code| {
|
||||
StatusCode::from_bytes(code.as_bytes())
|
||||
@@ -552,24 +618,51 @@ impl Configuration {
|
||||
.collect();
|
||||
}
|
||||
|
||||
if let Some(arg) = args.values_of("extensions") {
|
||||
config.extensions = arg.map(|val| val.to_string()).collect();
|
||||
if let Some(arg) = args.get_many::<String>("extensions") {
|
||||
config.extensions = arg
|
||||
.map(|val| val.trim_start_matches('.').to_string())
|
||||
.collect();
|
||||
}
|
||||
|
||||
if args.is_present("stdin") {
|
||||
if let Some(arg) = args.get_many::<String>("dont_collect") {
|
||||
config.dont_collect = arg.map(|val| val.to_string()).collect();
|
||||
}
|
||||
|
||||
if let Some(arg) = args.get_many::<String>("methods") {
|
||||
config.methods = arg
|
||||
.map(|val| {
|
||||
// Check methods if they are correct
|
||||
Method::from_bytes(val.as_bytes())
|
||||
.unwrap_or_else(|e| report_and_exit(&e.to_string()))
|
||||
.as_str()
|
||||
.to_string()
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
if let Some(arg) = args.get_one::<String>("data") {
|
||||
if let Some(stripped) = arg.strip_prefix('@') {
|
||||
config.data =
|
||||
std::fs::read(stripped).unwrap_or_else(|e| report_and_exit(&e.to_string()));
|
||||
} else {
|
||||
config.data = arg.as_bytes().to_vec();
|
||||
}
|
||||
}
|
||||
|
||||
if came_from_cli!(args, "stdin") {
|
||||
config.stdin = true;
|
||||
} else if let Some(url) = args.value_of("url") {
|
||||
config.target_url = String::from(url);
|
||||
} else if let Some(url) = args.get_one::<String>("url") {
|
||||
config.target_url = url.into();
|
||||
}
|
||||
|
||||
if let Some(arg) = args.values_of("url_denylist") {
|
||||
if let Some(arg) = args.get_many::<String>("url_denylist") {
|
||||
// compile all regular expressions and absolute urls used for --dont-scan
|
||||
//
|
||||
// when --dont-scan is used, the should_deny_url function is called at least once per
|
||||
// url to be scanned. With the addition of regex support, I want to move parsing
|
||||
// out of should_deny_url and into here, so it's performed once instead of thousands
|
||||
// of times
|
||||
for denier in arg.into_iter() {
|
||||
for denier in arg {
|
||||
// could be an absolute url or a regex, need to determine which and populate the
|
||||
// appropriate vector
|
||||
match Url::parse(denier.trim_end_matches('/')) {
|
||||
@@ -606,15 +699,15 @@ impl Configuration {
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(arg) = args.values_of("filter_regex") {
|
||||
if let Some(arg) = args.get_many::<String>("filter_regex") {
|
||||
config.filter_regex = arg.map(|val| val.to_string()).collect();
|
||||
}
|
||||
|
||||
if let Some(arg) = args.values_of("filter_similar") {
|
||||
if let Some(arg) = args.get_many::<String>("filter_similar") {
|
||||
config.filter_similar = arg.map(|val| val.to_string()).collect();
|
||||
}
|
||||
|
||||
if let Some(arg) = args.values_of("filter_size") {
|
||||
if let Some(arg) = args.get_many::<String>("filter_size") {
|
||||
config.filter_size = arg
|
||||
.map(|size| {
|
||||
size.parse::<u64>()
|
||||
@@ -623,7 +716,7 @@ impl Configuration {
|
||||
.collect();
|
||||
}
|
||||
|
||||
if let Some(arg) = args.values_of("filter_words") {
|
||||
if let Some(arg) = args.get_many::<String>("filter_words") {
|
||||
config.filter_word_count = arg
|
||||
.map(|size| {
|
||||
size.parse::<usize>()
|
||||
@@ -632,7 +725,7 @@ impl Configuration {
|
||||
.collect();
|
||||
}
|
||||
|
||||
if let Some(arg) = args.values_of("filter_lines") {
|
||||
if let Some(arg) = args.get_many::<String>("filter_lines") {
|
||||
config.filter_line_count = arg
|
||||
.map(|size| {
|
||||
size.parse::<usize>()
|
||||
@@ -641,7 +734,7 @@ impl Configuration {
|
||||
.collect();
|
||||
}
|
||||
|
||||
if args.is_present("silent") {
|
||||
if came_from_cli!(args, "silent") {
|
||||
// the reason this is protected by an if statement:
|
||||
// consider a user specifying silent = true in ferox-config.toml
|
||||
// if the line below is outside of the if, we'd overwrite true with
|
||||
@@ -650,68 +743,111 @@ impl Configuration {
|
||||
config.output_level = OutputLevel::Silent;
|
||||
}
|
||||
|
||||
if args.is_present("quiet") {
|
||||
if came_from_cli!(args, "quiet") {
|
||||
config.quiet = true;
|
||||
config.output_level = OutputLevel::Quiet;
|
||||
}
|
||||
|
||||
if args.is_present("auto_tune") {
|
||||
if came_from_cli!(args, "auto_tune")
|
||||
|| came_from_cli!(args, "smart")
|
||||
|| came_from_cli!(args, "thorough")
|
||||
{
|
||||
config.auto_tune = true;
|
||||
config.requester_policy = RequesterPolicy::AutoTune;
|
||||
}
|
||||
|
||||
if args.is_present("auto_bail") {
|
||||
if came_from_cli!(args, "auto_bail") {
|
||||
config.auto_bail = true;
|
||||
config.requester_policy = RequesterPolicy::AutoBail;
|
||||
}
|
||||
|
||||
if args.is_present("dont_filter") {
|
||||
if came_from_cli!(args, "no_state") {
|
||||
config.save_state = false;
|
||||
}
|
||||
|
||||
if came_from_cli!(args, "dont_filter") {
|
||||
config.dont_filter = true;
|
||||
}
|
||||
|
||||
if args.occurrences_of("verbosity") > 0 {
|
||||
// occurrences_of returns 0 if none are found; this is protected in
|
||||
// an if block for the same reason as the quiet option
|
||||
config.verbosity = args.occurrences_of("verbosity") as u8;
|
||||
if came_from_cli!(args, "collect_extensions") || came_from_cli!(args, "thorough") {
|
||||
config.collect_extensions = true;
|
||||
}
|
||||
|
||||
if args.is_present("no_recursion") {
|
||||
if came_from_cli!(args, "collect_backups")
|
||||
|| came_from_cli!(args, "smart")
|
||||
|| came_from_cli!(args, "thorough")
|
||||
{
|
||||
config.collect_backups = true;
|
||||
}
|
||||
|
||||
if came_from_cli!(args, "collect_words")
|
||||
|| came_from_cli!(args, "smart")
|
||||
|| came_from_cli!(args, "thorough")
|
||||
{
|
||||
config.collect_words = true;
|
||||
}
|
||||
|
||||
if args.get_count("verbosity") > 0 {
|
||||
// occurrences_of returns 0 if none are found; this is protected in
|
||||
// an if block for the same reason as the quiet option
|
||||
config.verbosity = args.get_count("verbosity");
|
||||
}
|
||||
|
||||
if came_from_cli!(args, "no_recursion") {
|
||||
config.no_recursion = true;
|
||||
}
|
||||
|
||||
if args.is_present("add_slash") {
|
||||
if came_from_cli!(args, "add_slash") {
|
||||
config.add_slash = true;
|
||||
}
|
||||
|
||||
if args.is_present("extract_links") {
|
||||
if came_from_cli!(args, "extract_links")
|
||||
|| came_from_cli!(args, "smart")
|
||||
|| came_from_cli!(args, "thorough")
|
||||
{
|
||||
config.extract_links = true;
|
||||
}
|
||||
|
||||
if args.is_present("json") {
|
||||
if came_from_cli!(args, "json") {
|
||||
config.json = true;
|
||||
}
|
||||
|
||||
if came_from_cli!(args, "force_recursion") {
|
||||
config.force_recursion = true;
|
||||
}
|
||||
|
||||
////
|
||||
// organizational breakpoint; all options below alter the Client configuration
|
||||
////
|
||||
update_config_if_present!(&mut config.proxy, args, "proxy", String);
|
||||
update_config_if_present!(&mut config.replay_proxy, args, "replay_proxy", String);
|
||||
update_config_if_present!(&mut config.user_agent, args, "user_agent", String);
|
||||
update_config_if_present!(&mut config.timeout, args, "timeout", u64);
|
||||
update_config_with_num_type_if_present!(&mut config.timeout, args, "timeout", u64);
|
||||
|
||||
if args.is_present("random_agent") {
|
||||
if came_from_cli!(args, "burp") {
|
||||
config.proxy = String::from("http://127.0.0.1:8080");
|
||||
}
|
||||
|
||||
if came_from_cli!(args, "burp_replay") {
|
||||
config.replay_proxy = String::from("http://127.0.0.1:8080");
|
||||
}
|
||||
|
||||
if came_from_cli!(args, "random_agent") {
|
||||
config.random_agent = true;
|
||||
}
|
||||
|
||||
if args.is_present("redirects") {
|
||||
if came_from_cli!(args, "redirects") {
|
||||
config.redirects = true;
|
||||
}
|
||||
|
||||
if args.is_present("insecure") {
|
||||
if came_from_cli!(args, "insecure")
|
||||
|| came_from_cli!(args, "burp")
|
||||
|| came_from_cli!(args, "burp_replay")
|
||||
{
|
||||
config.insecure = true;
|
||||
}
|
||||
|
||||
if let Some(headers) = args.values_of("headers") {
|
||||
if let Some(headers) = args.get_many::<String>("headers") {
|
||||
for val in headers {
|
||||
let mut split_val = val.split(':');
|
||||
|
||||
@@ -725,7 +861,23 @@ impl Configuration {
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(queries) = args.values_of("queries") {
|
||||
if let Some(cookies) = args.get_many::<String>("cookies") {
|
||||
config.headers.insert(
|
||||
// we know the header name is always "cookie"
|
||||
"Cookie".to_string(),
|
||||
// on splitting, there should be only two elements,
|
||||
// a key and a value
|
||||
cookies
|
||||
.map(|cookie| cookie.split('=').collect::<Vec<&str>>()[..].to_owned())
|
||||
.filter(|parts| parts.len() == 2)
|
||||
.map(|parts| format!("{}={}", parts[0].trim(), parts[1].trim()))
|
||||
// trim the spaces, join with an equals sign
|
||||
.collect::<Vec<String>>()
|
||||
.join("; "), // join all the cookies with semicolons for the final header
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(queries) = args.get_many::<String>("queries") {
|
||||
for val in queries {
|
||||
// same basic logic used as reading in the headers HashMap above
|
||||
let mut split_val = val.split('=');
|
||||
@@ -825,14 +977,20 @@ impl Configuration {
|
||||
update_if_not_default!(&mut conf.quiet, new.quiet, false);
|
||||
update_if_not_default!(&mut conf.auto_bail, new.auto_bail, false);
|
||||
update_if_not_default!(&mut conf.auto_tune, new.auto_tune, false);
|
||||
update_if_not_default!(&mut conf.collect_extensions, new.collect_extensions, false);
|
||||
update_if_not_default!(&mut conf.collect_backups, new.collect_backups, false);
|
||||
update_if_not_default!(&mut conf.collect_words, new.collect_words, false);
|
||||
// use updated quiet/silent values to determine output level; same for requester policy
|
||||
conf.output_level = determine_output_level(conf.quiet, conf.silent);
|
||||
conf.requester_policy = determine_requester_policy(conf.auto_tune, conf.auto_bail);
|
||||
update_if_not_default!(&mut conf.output, new.output, "");
|
||||
update_if_not_default!(&mut conf.redirects, new.redirects, false);
|
||||
update_if_not_default!(&mut conf.insecure, new.insecure, false);
|
||||
update_if_not_default!(&mut conf.force_recursion, new.force_recursion, false);
|
||||
update_if_not_default!(&mut conf.extract_links, new.extract_links, false);
|
||||
update_if_not_default!(&mut conf.extensions, new.extensions, Vec::<String>::new());
|
||||
update_if_not_default!(&mut conf.methods, new.methods, methods());
|
||||
update_if_not_default!(&mut conf.data, new.data, Vec::<u8>::new());
|
||||
update_if_not_default!(&mut conf.url_denylist, new.url_denylist, Vec::<Url>::new());
|
||||
if !new.regex_denylist.is_empty() {
|
||||
// cant use the update_if_not_default macro due to the following error
|
||||
@@ -892,6 +1050,11 @@ impl Configuration {
|
||||
// status_codes() is the default for replay_codes, if they're not provided
|
||||
update_if_not_default!(&mut conf.replay_codes, new.replay_codes, status_codes());
|
||||
update_if_not_default!(&mut conf.save_state, new.save_state, save_state());
|
||||
update_if_not_default!(
|
||||
&mut conf.dont_collect,
|
||||
new.dont_collect,
|
||||
ignored_extensions()
|
||||
);
|
||||
}
|
||||
|
||||
/// If present, read in `DEFAULT_CONFIG_NAME` and deserialize the specified values
|
||||
@@ -899,7 +1062,17 @@ impl Configuration {
|
||||
/// uses serde to deserialize the toml into a `Configuration` struct
|
||||
pub(super) fn parse_config(config_file: PathBuf) -> Result<Self> {
|
||||
let content = read_to_string(config_file)?;
|
||||
let config: Self = toml::from_str(content.as_str())?;
|
||||
let mut config: Self = toml::from_str(content.as_str())?;
|
||||
|
||||
if !config.extensions.is_empty() {
|
||||
// remove leading periods, if any are found
|
||||
config.extensions = config
|
||||
.extensions
|
||||
.iter()
|
||||
.map(|ext| ext.trim_start_matches('.').to_string())
|
||||
.collect();
|
||||
}
|
||||
|
||||
Ok(config)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,7 +30,13 @@ fn setup_config_test() -> Configuration {
|
||||
resume_from = "/some/state/file"
|
||||
redirects = true
|
||||
insecure = true
|
||||
collect_backups = true
|
||||
collect_extensions = true
|
||||
collect_words = true
|
||||
extensions = ["html", "php", "js"]
|
||||
dont_collect = ["png", "gif", "jpg", "jpeg"]
|
||||
methods = ["GET", "PUT", "DELETE"]
|
||||
data = [31, 32, 33, 34]
|
||||
url_denylist = ["http://dont-scan.me", "https://also-not.me"]
|
||||
regex_denylist = ["/deny.*"]
|
||||
headers = {stuff = "things", mostuff = "mothings"}
|
||||
@@ -43,6 +49,7 @@ fn setup_config_test() -> Configuration {
|
||||
json = true
|
||||
save_state = false
|
||||
depth = 1
|
||||
force_recursion = true
|
||||
filter_size = [4120]
|
||||
filter_regex = ["^ignore me$"]
|
||||
filter_similar = ["https://somesite.com/soft404"]
|
||||
@@ -89,14 +96,21 @@ fn default_configuration() {
|
||||
assert!(config.save_state);
|
||||
assert!(!config.stdin);
|
||||
assert!(!config.add_slash);
|
||||
assert!(!config.force_recursion);
|
||||
assert!(!config.redirects);
|
||||
assert!(!config.extract_links);
|
||||
assert!(!config.insecure);
|
||||
assert!(!config.collect_extensions);
|
||||
assert!(!config.collect_backups);
|
||||
assert!(!config.collect_words);
|
||||
assert!(config.regex_denylist.is_empty());
|
||||
assert_eq!(config.queries, Vec::new());
|
||||
assert_eq!(config.filter_size, Vec::<u64>::new());
|
||||
assert_eq!(config.extensions, Vec::<String>::new());
|
||||
assert_eq!(config.methods, vec!["GET"]);
|
||||
assert_eq!(config.data, Vec::<u8>::new());
|
||||
assert_eq!(config.url_denylist, Vec::<Url>::new());
|
||||
assert_eq!(config.dont_collect, ignored_extensions());
|
||||
assert_eq!(config.filter_regex, Vec::<String>::new());
|
||||
assert_eq!(config.filter_similar, Vec::<String>::new());
|
||||
assert_eq!(config.filter_word_count, Vec::<usize>::new());
|
||||
@@ -196,6 +210,13 @@ fn config_reads_silent() {
|
||||
assert!(config.silent);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// parse the test config and see that the value parsed is correct
|
||||
fn config_reads_force_recursion() {
|
||||
let config = setup_config_test();
|
||||
assert!(config.force_recursion);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// parse the test config and see that the value parsed is correct
|
||||
fn config_reads_quiet() {
|
||||
@@ -287,6 +308,27 @@ fn config_reads_extract_links() {
|
||||
assert!(config.extract_links);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// parse the test config and see that the value parsed is correct
|
||||
fn config_reads_collect_extensions() {
|
||||
let config = setup_config_test();
|
||||
assert!(config.collect_extensions);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// parse the test config and see that the value parsed is correct
|
||||
fn config_reads_collect_backups() {
|
||||
let config = setup_config_test();
|
||||
assert!(config.collect_backups);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// parse the test config and see that the value parsed is correct
|
||||
fn config_reads_collect_words() {
|
||||
let config = setup_config_test();
|
||||
assert!(config.collect_words);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// parse the test config and see that the value parsed is correct
|
||||
fn config_reads_extensions() {
|
||||
@@ -294,6 +336,27 @@ fn config_reads_extensions() {
|
||||
assert_eq!(config.extensions, vec!["html", "php", "js"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// parse the test config and see that the value parsed is correct
|
||||
fn config_reads_dont_collect() {
|
||||
let config = setup_config_test();
|
||||
assert_eq!(config.dont_collect, vec!["png", "gif", "jpg", "jpeg"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// parse the test config and see that the value parsed is correct
|
||||
fn config_reads_methods() {
|
||||
let config = setup_config_test();
|
||||
assert_eq!(config.methods, vec!["GET", "PUT", "DELETE"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// parse the test config and see that the value parsed is correct
|
||||
fn config_reads_data() {
|
||||
let config = setup_config_test();
|
||||
assert_eq!(config.data, vec![31, 32, 33, 34]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// parse the test config and see that the value parsed is correct
|
||||
fn config_reads_regex_denylist() {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{
|
||||
utils::{module_colorizer, status_colorizer},
|
||||
DEFAULT_STATUS_CODES, DEFAULT_WORDLIST, VERSION,
|
||||
DEFAULT_IGNORED_EXTENSIONS, DEFAULT_METHOD, DEFAULT_STATUS_CODES, DEFAULT_WORDLIST, VERSION,
|
||||
};
|
||||
#[cfg(not(test))]
|
||||
use std::process::exit;
|
||||
@@ -52,6 +52,19 @@ pub(super) fn status_codes() -> Vec<u16> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// default HTTP Method
|
||||
pub(super) fn methods() -> Vec<String> {
|
||||
vec![DEFAULT_METHOD.to_owned()]
|
||||
}
|
||||
|
||||
/// default extensions to ignore while auto-collecting
|
||||
pub(super) fn ignored_extensions() -> Vec<String> {
|
||||
DEFAULT_IGNORED_EXTENSIONS
|
||||
.iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// default wordlist
|
||||
pub(super) fn wordlist() -> String {
|
||||
String::from(DEFAULT_WORDLIST)
|
||||
@@ -68,7 +81,7 @@ pub(super) fn depth() -> usize {
|
||||
}
|
||||
|
||||
/// enum representing the three possible states for informational output (not logging verbosity)
|
||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
pub enum OutputLevel {
|
||||
/// normal scan, no --quiet|--silent
|
||||
Default,
|
||||
@@ -103,7 +116,7 @@ pub fn determine_output_level(quiet: bool, silent: bool) -> OutputLevel {
|
||||
}
|
||||
|
||||
/// represents actions the Requester should take in certain situations
|
||||
#[derive(Debug, PartialEq, Copy, Clone)]
|
||||
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
|
||||
pub enum RequesterPolicy {
|
||||
/// automatically try to lower request rate in order to reduce errors
|
||||
AutoTune,
|
||||
|
||||
@@ -5,6 +5,8 @@ use tokio::sync::oneshot::Sender;
|
||||
|
||||
use crate::response::FeroxResponse;
|
||||
use crate::{
|
||||
event_handlers::Handles,
|
||||
message::FeroxMessage,
|
||||
statistics::{StatError, StatField},
|
||||
traits::FeroxFilter,
|
||||
};
|
||||
@@ -42,6 +44,9 @@ pub enum Command {
|
||||
/// Add a `FeroxFilter` implementor to `FilterHandler`'s instance of `FeroxFilters`
|
||||
AddFilter(Box<dyn FeroxFilter>),
|
||||
|
||||
/// Remove a set of `FeroxFilter` implementors from `FeroxFilters` by index
|
||||
RemoveFilters(Vec<usize>),
|
||||
|
||||
/// Send a `FeroxResponse` to the output handler for reporting
|
||||
Report(Box<FeroxResponse>),
|
||||
|
||||
@@ -66,6 +71,16 @@ pub enum Command {
|
||||
/// Just receive a sender and reply, used for slowing down the main thread
|
||||
Sync(Sender<bool>),
|
||||
|
||||
/// Notify event handler that a new extension has been seen
|
||||
AddDiscoveredExtension(String),
|
||||
|
||||
/// Write an arbitrary string to disk
|
||||
WriteToDisk(Box<FeroxMessage>),
|
||||
|
||||
/// Break out of the (infinite) mpsc receive loop
|
||||
Exit,
|
||||
|
||||
/// Give a handler access to an Arc<Handles> instance after the handler has
|
||||
/// already been initialized
|
||||
AddHandles(Arc<Handles>),
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ use crate::Joiner;
|
||||
#[cfg(test)]
|
||||
use crate::{filters::FeroxFilters, statistics::Stats, Command};
|
||||
use anyhow::{bail, Result};
|
||||
use std::collections::HashSet;
|
||||
use std::sync::{Arc, RwLock};
|
||||
#[cfg(test)]
|
||||
use tokio::sync::mpsc::{self, UnboundedReceiver};
|
||||
@@ -56,6 +57,9 @@ pub struct Handles {
|
||||
|
||||
/// Handle for recursion
|
||||
pub scans: RwLock<Option<ScanHandle>>,
|
||||
|
||||
/// Pointer to the list of words generated from reading in the wordlist
|
||||
pub wordlist: Arc<Vec<String>>,
|
||||
}
|
||||
|
||||
/// implementation of Handles
|
||||
@@ -66,6 +70,7 @@ impl Handles {
|
||||
filters: FiltersHandle,
|
||||
output: TermOutHandle,
|
||||
config: Arc<Configuration>,
|
||||
wordlist: Arc<Vec<String>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
stats,
|
||||
@@ -73,6 +78,7 @@ impl Handles {
|
||||
output,
|
||||
config,
|
||||
scans: RwLock::new(None),
|
||||
wordlist,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,7 +93,14 @@ impl Handles {
|
||||
let terminal_handle = TermOutHandle::new(tx.clone(), tx.clone());
|
||||
let stats_handle = StatsHandle::new(Arc::new(Stats::new(configuration.json)), tx.clone());
|
||||
let filters_handle = FiltersHandle::new(Arc::new(FeroxFilters::default()), tx.clone());
|
||||
let handles = Self::new(stats_handle, filters_handle, terminal_handle, configuration);
|
||||
let wordlist = Arc::new(vec![String::from("this_is_a_test")]);
|
||||
let handles = Self::new(
|
||||
stats_handle,
|
||||
filters_handle,
|
||||
terminal_handle,
|
||||
configuration,
|
||||
wordlist,
|
||||
);
|
||||
if let Some(sh) = scanned_urls {
|
||||
let scan_handle = ScanHandle::new(sh, tx);
|
||||
handles.set_scan_handle(scan_handle);
|
||||
@@ -116,6 +129,46 @@ impl Handles {
|
||||
bail!("Could not get underlying CommandSender object")
|
||||
}
|
||||
|
||||
/// wrapper to reach into `FeroxScans` and yank out the length of `collected_extensions`
|
||||
pub fn num_collected_extensions(&self) -> usize {
|
||||
if !self.config.collect_extensions {
|
||||
// if --collect-extensions wasn't used, simply return 0 and forego unlocking
|
||||
return 0;
|
||||
}
|
||||
|
||||
self.collected_extensions().len()
|
||||
}
|
||||
|
||||
/// wrapper to reach into `FeroxScans` and yank out the length of `collected_extensions`
|
||||
pub fn collected_extensions(&self) -> HashSet<String> {
|
||||
if let Ok(scans) = self.ferox_scans() {
|
||||
if let Ok(extensions) = scans.collected_extensions.read() {
|
||||
return extensions.clone();
|
||||
}
|
||||
}
|
||||
|
||||
HashSet::new()
|
||||
}
|
||||
|
||||
/// number of words in the wordlist, multiplied by `expected_num_requests_multiplier`
|
||||
pub fn expected_num_requests_per_dir(&self) -> usize {
|
||||
let num_words = self.wordlist.len();
|
||||
let multiplier = self.expected_num_requests_multiplier();
|
||||
multiplier * num_words
|
||||
}
|
||||
|
||||
/// number of extensions plus the number of request method types plus any dynamically collected
|
||||
/// extensions
|
||||
pub fn expected_num_requests_multiplier(&self) -> usize {
|
||||
let multiplier = self.config.extensions.len()
|
||||
+ self.config.methods.len()
|
||||
+ self.num_collected_extensions();
|
||||
|
||||
// methods should always have at least 1 member, likely making this .max call unneeded
|
||||
// but leaving it for 'just in case' reasons
|
||||
multiplier.max(1)
|
||||
}
|
||||
|
||||
/// Helper to easily get the (locked) underlying FeroxScans object
|
||||
pub fn ferox_scans(&self) -> Result<Arc<FeroxScans>> {
|
||||
if let Ok(guard) = self.scans.read().as_ref() {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::*;
|
||||
use crate::filters::EmptyFilter;
|
||||
use crate::{filters::FeroxFilters, CommandSender, FeroxChannel, Joiner};
|
||||
use anyhow::Result;
|
||||
use std::sync::Arc;
|
||||
@@ -84,8 +85,12 @@ impl FiltersHandler {
|
||||
while let Some(command) = self.receiver.recv().await {
|
||||
match command {
|
||||
Command::AddFilter(filter) => {
|
||||
self.data.push(filter)?;
|
||||
if filter.as_any().downcast_ref::<EmptyFilter>().is_none() {
|
||||
// don't add an empty filter
|
||||
self.data.push(filter)?;
|
||||
}
|
||||
}
|
||||
Command::RemoveFilters(mut indices) => self.data.remove(&mut indices),
|
||||
Command::Sync(sender) => {
|
||||
log::debug!("filters: {:?}", self);
|
||||
sender.send(true).unwrap_or_default();
|
||||
@@ -99,3 +104,41 @@ impl FiltersHandler {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::filters::WordsFilter;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
|
||||
async fn empty_filter_skipped() {
|
||||
let data = Arc::new(FeroxFilters::default());
|
||||
let (tx, rx): FeroxChannel<Command> = mpsc::unbounded_channel();
|
||||
|
||||
let mut handler = FiltersHandler::new(data.clone(), rx);
|
||||
|
||||
let event_handle = FiltersHandle::new(data, tx);
|
||||
|
||||
let _task = tokio::spawn(async move { handler.start().await });
|
||||
|
||||
event_handle
|
||||
.send(Command::AddFilter(Box::new(EmptyFilter {})))
|
||||
.unwrap();
|
||||
|
||||
let (tx, rx) = oneshot::channel::<bool>();
|
||||
event_handle.send(Command::Sync(tx)).unwrap();
|
||||
rx.await.unwrap();
|
||||
|
||||
assert!(event_handle.data.filters.read().unwrap().is_empty());
|
||||
|
||||
event_handle
|
||||
.send(Command::AddFilter(Box::new(WordsFilter { word_count: 1 })))
|
||||
.unwrap();
|
||||
|
||||
let (tx, rx) = oneshot::channel::<bool>();
|
||||
event_handle.send(Command::Sync(tx)).unwrap();
|
||||
rx.await.unwrap();
|
||||
|
||||
assert_eq!(event_handle.data.filters.read().unwrap().len(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,12 +98,16 @@ impl TermInputHandler {
|
||||
handles.config.clone(),
|
||||
&RESPONSES,
|
||||
handles.stats.data.clone(),
|
||||
handles.filters.data.clone(),
|
||||
);
|
||||
|
||||
let state_file = open_file(&filename);
|
||||
// User didn't set the --no-state flag (so saved_state is still the default true)
|
||||
if handles.config.save_state {
|
||||
let state_file = open_file(&filename);
|
||||
|
||||
let mut buffered_file = state_file?;
|
||||
write_to(&state, &mut buffered_file, true)?;
|
||||
let mut buffered_file = state_file?;
|
||||
write_to(&state, &mut buffered_file, true)?;
|
||||
}
|
||||
|
||||
log::trace!("exit: sigint_handler (end of program)");
|
||||
std::process::exit(1);
|
||||
|
||||
@@ -2,19 +2,32 @@ use super::Command::AddToUsizeField;
|
||||
use super::*;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use futures::future::{BoxFuture, FutureExt};
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
|
||||
use crate::{
|
||||
config::Configuration,
|
||||
progress::PROGRESS_PRINTER,
|
||||
response::FeroxResponse,
|
||||
scanner::RESPONSES,
|
||||
send_command, skip_fail,
|
||||
statistics::StatField::ResourcesDiscovered,
|
||||
statistics::StatField::{ResourcesDiscovered, TotalExpected},
|
||||
traits::FeroxSerialize,
|
||||
utils::{ferox_print, fmt_err, make_request, open_file, write_to},
|
||||
CommandReceiver, CommandSender, Joiner,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
use url::Url;
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
/// Simple enum for semantic clarity around calling expectations for `process_response`
|
||||
enum ProcessResponseCall {
|
||||
/// call should allow recursion
|
||||
Recursive,
|
||||
|
||||
/// call should not allow recursion
|
||||
NotRecursive,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
/// Container for terminal output transmitter
|
||||
@@ -90,6 +103,12 @@ impl FileOutHandler {
|
||||
Command::Report(response) => {
|
||||
skip_fail!(write_to(&*response, &mut file, self.config.json));
|
||||
}
|
||||
Command::WriteToDisk(message) => {
|
||||
// todo consider making report accept dyn FeroxSerialize; would mean adding
|
||||
// as_any/box_eq/PartialEq to the trait and then adding them to the
|
||||
// implementing structs
|
||||
skip_fail!(write_to(&*message, &mut file, self.config.json));
|
||||
}
|
||||
Command::Exit => {
|
||||
break;
|
||||
}
|
||||
@@ -124,6 +143,9 @@ pub struct TermOutHandler {
|
||||
|
||||
/// pointer to "global" configuration struct
|
||||
config: Arc<Configuration>,
|
||||
|
||||
/// handles instance
|
||||
handles: Option<Arc<Handles>>,
|
||||
}
|
||||
|
||||
/// implementation of TermOutHandler
|
||||
@@ -141,6 +163,7 @@ impl TermOutHandler {
|
||||
tx_file,
|
||||
file_task,
|
||||
config,
|
||||
handles: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,58 +208,16 @@ impl TermOutHandler {
|
||||
|
||||
while let Some(command) = self.receiver.recv().await {
|
||||
match command {
|
||||
Command::Report(mut resp) => {
|
||||
let contains_sentry =
|
||||
self.config.status_codes.contains(&resp.status().as_u16());
|
||||
let unknown_sentry = !RESPONSES.contains(&resp); // !contains == unknown
|
||||
let should_process_response = contains_sentry && unknown_sentry;
|
||||
|
||||
if should_process_response {
|
||||
// print to stdout
|
||||
ferox_print(&resp.as_str(), &PROGRESS_PRINTER);
|
||||
|
||||
send_command!(tx_stats, AddToUsizeField(ResourcesDiscovered, 1));
|
||||
|
||||
if self.file_task.is_some() {
|
||||
// -o used, need to send the report to be written out to disk
|
||||
self.tx_file
|
||||
.send(Command::Report(resp.clone()))
|
||||
.with_context(|| {
|
||||
fmt_err(&format!("Could not send {} to file handler", resp))
|
||||
})?;
|
||||
}
|
||||
}
|
||||
log::trace!("report complete: {}", resp.url());
|
||||
|
||||
if self.config.replay_client.is_some() && should_process_response {
|
||||
// replay proxy specified/client created and this response's status code is one that
|
||||
// should be replayed; not using logged_request due to replay proxy client
|
||||
make_request(
|
||||
self.config.replay_client.as_ref().unwrap(),
|
||||
resp.url(),
|
||||
self.config.output_level,
|
||||
&self.config,
|
||||
tx_stats.clone(),
|
||||
)
|
||||
.await
|
||||
.with_context(|| "Could not replay request through replay proxy")?;
|
||||
}
|
||||
|
||||
if should_process_response {
|
||||
// add response to RESPONSES for serialization in case of ctrl+c
|
||||
// placed all by its lonesome like this so that RESPONSES can take ownership
|
||||
// of the FeroxResponse
|
||||
|
||||
// before ownership is transferred, there's no real reason to keep the body anymore
|
||||
// so we can free that piece of data, reducing memory usage
|
||||
resp.drop_text();
|
||||
|
||||
RESPONSES.insert(*resp);
|
||||
}
|
||||
Command::Report(resp) => {
|
||||
self.process_response(tx_stats.clone(), resp, ProcessResponseCall::Recursive)
|
||||
.await?;
|
||||
}
|
||||
Command::Sync(sender) => {
|
||||
sender.send(true).unwrap_or_default();
|
||||
}
|
||||
Command::AddHandles(handles) => {
|
||||
self.handles = Some(handles);
|
||||
}
|
||||
Command::Exit => {
|
||||
if self.file_task.is_some() && self.tx_file.send(Command::Exit).is_ok() {
|
||||
self.file_task.as_mut().unwrap().await??; // wait for death
|
||||
@@ -249,11 +230,198 @@ impl TermOutHandler {
|
||||
log::trace!("exit: start");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// upon receiving a `FeroxResponse` from the mpsc, handle printing, sending to the replay
|
||||
/// proxy, checking for backups of the `FeroxResponse`'s url, and tracking the response.
|
||||
fn process_response(
|
||||
&self,
|
||||
tx_stats: CommandSender,
|
||||
mut resp: Box<FeroxResponse>,
|
||||
call_type: ProcessResponseCall,
|
||||
) -> BoxFuture<'_, Result<()>> {
|
||||
log::trace!("enter: process_response({:?}, {:?})", resp, call_type);
|
||||
|
||||
async move {
|
||||
let should_filter = self
|
||||
.handles
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.filters
|
||||
.data
|
||||
.should_filter_response(&resp, self.handles.as_ref().unwrap().stats.tx.clone());
|
||||
|
||||
let contains_sentry = if !self.config.filter_status.is_empty() {
|
||||
// -C was used, meaning -s was not and we should ignore the defaults
|
||||
// https://github.com/epi052/feroxbuster/issues/535
|
||||
// -C indicates that we should filter that status code, but allow all others
|
||||
!self.config.filter_status.contains(&resp.status().as_u16())
|
||||
} else {
|
||||
// -C wasn't used, so, we defer to checking the -s values
|
||||
self.config.status_codes.contains(&resp.status().as_u16())
|
||||
};
|
||||
|
||||
let unknown_sentry = !RESPONSES.contains(&resp); // !contains == unknown
|
||||
let should_process_response = contains_sentry && unknown_sentry && !should_filter;
|
||||
|
||||
if should_process_response {
|
||||
// print to stdout
|
||||
ferox_print(&resp.as_str(), &PROGRESS_PRINTER);
|
||||
|
||||
send_command!(tx_stats, AddToUsizeField(ResourcesDiscovered, 1));
|
||||
|
||||
if self.file_task.is_some() {
|
||||
// -o used, need to send the report to be written out to disk
|
||||
self.tx_file
|
||||
.send(Command::Report(resp.clone()))
|
||||
.with_context(|| {
|
||||
fmt_err(&format!("Could not send {} to file handler", resp))
|
||||
})?;
|
||||
}
|
||||
}
|
||||
log::trace!("report complete: {}", resp.url());
|
||||
|
||||
if self.config.replay_client.is_some() && should_process_response {
|
||||
// replay proxy specified/client created and this response's status code is one that
|
||||
// should be replayed; not using logged_request due to replay proxy client
|
||||
let data = if self.config.data.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(self.config.data.as_slice())
|
||||
};
|
||||
|
||||
make_request(
|
||||
self.config.replay_client.as_ref().unwrap(),
|
||||
resp.url(),
|
||||
resp.method().as_str(),
|
||||
data,
|
||||
self.config.output_level,
|
||||
&self.config,
|
||||
tx_stats.clone(),
|
||||
)
|
||||
.await
|
||||
.with_context(|| "Could not replay request through replay proxy")?;
|
||||
}
|
||||
|
||||
if self.config.collect_backups
|
||||
&& should_process_response
|
||||
&& matches!(call_type, ProcessResponseCall::Recursive)
|
||||
{
|
||||
// --collect-backups was used; the response is one we care about, and the function
|
||||
// call came from the loop in `.start` (i.e. recursive was specified)
|
||||
let backup_urls = self.generate_backup_urls(&resp).await;
|
||||
|
||||
// need to manually adjust stats
|
||||
send_command!(tx_stats, AddToUsizeField(TotalExpected, backup_urls.len()));
|
||||
|
||||
for backup_url in &backup_urls {
|
||||
let backup_response = make_request(
|
||||
&self.config.client,
|
||||
backup_url,
|
||||
resp.method().as_str(),
|
||||
None,
|
||||
self.config.output_level,
|
||||
&self.config,
|
||||
tx_stats.clone(),
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!("Could not request backup of {}", resp.url().as_str())
|
||||
})?;
|
||||
|
||||
let ferox_response = FeroxResponse::from(
|
||||
backup_response,
|
||||
resp.url().as_str(),
|
||||
resp.method().as_str(),
|
||||
resp.output_level,
|
||||
)
|
||||
.await;
|
||||
|
||||
self.process_response(
|
||||
tx_stats.clone(),
|
||||
Box::new(ferox_response),
|
||||
ProcessResponseCall::NotRecursive,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
|
||||
if should_process_response {
|
||||
// add response to RESPONSES for serialization in case of ctrl+c
|
||||
// placed all by its lonesome like this so that RESPONSES can take ownership
|
||||
// of the FeroxResponse
|
||||
|
||||
// before ownership is transferred, there's no real reason to keep the body anymore
|
||||
// so we can free that piece of data, reducing memory usage
|
||||
resp.drop_text();
|
||||
|
||||
RESPONSES.insert(*resp);
|
||||
}
|
||||
log::trace!("exit: process_response");
|
||||
Ok(())
|
||||
}
|
||||
.boxed()
|
||||
}
|
||||
|
||||
/// internal helper to stay DRY
|
||||
fn add_new_url_to_vec(&self, url: &Url, new_name: &str, urls: &mut Vec<Url>) {
|
||||
if let Ok(joined) = url.join(new_name) {
|
||||
urls.push(joined);
|
||||
}
|
||||
}
|
||||
|
||||
/// given a `FeroxResponse`, generate either 6 or 7 urls that are likely backups of the
|
||||
/// original.
|
||||
///
|
||||
/// example:
|
||||
/// original: LICENSE.txt
|
||||
/// backups:
|
||||
/// - LICENSE.txt~
|
||||
/// - LICENSE.txt.bak
|
||||
/// - LICENSE.txt.bak2
|
||||
/// - LICENSE.txt.old
|
||||
/// - LICENSE.txt.1
|
||||
/// - LICENSE.bak
|
||||
/// - .LICENSE.txt.swp
|
||||
async fn generate_backup_urls(&self, response: &FeroxResponse) -> Vec<Url> {
|
||||
log::trace!("enter: generate_backup_urls({:?})", response);
|
||||
|
||||
let mut urls = vec![];
|
||||
let url = response.url();
|
||||
|
||||
// confirmed safe: see src/response.rs for comments
|
||||
let filename = url.path_segments().unwrap().last().unwrap();
|
||||
|
||||
if !filename.is_empty() {
|
||||
// append rules
|
||||
for suffix in ["~", ".bak", ".bak2", ".old", ".1"] {
|
||||
self.add_new_url_to_vec(url, &format!("{}{}", filename, suffix), &mut urls);
|
||||
}
|
||||
|
||||
// vim swap rule
|
||||
self.add_new_url_to_vec(url, &format!(".{}.swp", filename), &mut urls);
|
||||
|
||||
// replace original extension rule
|
||||
let parts: Vec<_> = filename
|
||||
.split('.')
|
||||
// keep things like /.bash_history out of results
|
||||
.filter(|part| !part.is_empty())
|
||||
.collect();
|
||||
|
||||
if parts.len() > 1 {
|
||||
// filename + at least one extension, i.e. whatever.js becomes ["whatever", "js"]
|
||||
self.add_new_url_to_vec(url, &format!("{}.bak", parts.first().unwrap()), &mut urls);
|
||||
}
|
||||
}
|
||||
|
||||
log::trace!("exit: generate_backup_urls -> {:?}", urls);
|
||||
urls
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::event_handlers::Command;
|
||||
|
||||
#[test]
|
||||
/// try to hit struct field coverage of FileOutHandler
|
||||
@@ -273,15 +441,149 @@ mod tests {
|
||||
let (tx, rx) = mpsc::unbounded_channel::<Command>();
|
||||
let (tx_file, _) = mpsc::unbounded_channel::<Command>();
|
||||
let config = Arc::new(Configuration::new().unwrap());
|
||||
let handles = Arc::new(Handles::for_testing(None, None).0);
|
||||
|
||||
let toh = TermOutHandler {
|
||||
config,
|
||||
file_task: None,
|
||||
receiver: rx,
|
||||
tx_file,
|
||||
handles: Some(handles),
|
||||
};
|
||||
|
||||
println!("{:?}", toh);
|
||||
tx.send(Command::Exit).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
|
||||
/// when the feroxresponse's url contains an extension, there should be 7 urls returned
|
||||
async fn generate_backup_urls_creates_correct_urls_when_extension_present() {
|
||||
let (tx, rx) = mpsc::unbounded_channel::<Command>();
|
||||
let (tx_file, _) = mpsc::unbounded_channel::<Command>();
|
||||
let config = Arc::new(Configuration::new().unwrap());
|
||||
let handles = Arc::new(Handles::for_testing(None, None).0);
|
||||
|
||||
let toh = TermOutHandler {
|
||||
config,
|
||||
file_task: None,
|
||||
receiver: rx,
|
||||
tx_file,
|
||||
handles: Some(handles),
|
||||
};
|
||||
|
||||
let expected: Vec<_> = vec![
|
||||
"derp.php~",
|
||||
"derp.php.bak",
|
||||
"derp.php.bak2",
|
||||
"derp.php.old",
|
||||
"derp.php.1",
|
||||
".derp.php.swp",
|
||||
"derp.bak",
|
||||
];
|
||||
|
||||
let mut fr = FeroxResponse::default();
|
||||
fr.set_url("http://localhost/derp.php");
|
||||
|
||||
let urls = toh.generate_backup_urls(&fr).await;
|
||||
|
||||
let paths: Vec<_> = urls
|
||||
.iter()
|
||||
.map(|url| url.path_segments().unwrap().last().unwrap())
|
||||
.collect();
|
||||
|
||||
assert_eq!(urls.len(), 7);
|
||||
|
||||
for path in paths {
|
||||
assert!(expected.contains(&path));
|
||||
}
|
||||
|
||||
tx.send(Command::Exit).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
|
||||
/// when the feroxresponse's url doesn't contain an extension, there should be 6 urls returned
|
||||
async fn generate_backup_urls_creates_correct_urls_when_extension_not_present() {
|
||||
let (tx, rx) = mpsc::unbounded_channel::<Command>();
|
||||
let (tx_file, _) = mpsc::unbounded_channel::<Command>();
|
||||
let config = Arc::new(Configuration::new().unwrap());
|
||||
let handles = Arc::new(Handles::for_testing(None, None).0);
|
||||
|
||||
let toh = TermOutHandler {
|
||||
config,
|
||||
file_task: None,
|
||||
receiver: rx,
|
||||
tx_file,
|
||||
handles: Some(handles),
|
||||
};
|
||||
|
||||
let expected: Vec<_> = vec![
|
||||
"derp~",
|
||||
"derp.bak",
|
||||
"derp.bak2",
|
||||
"derp.old",
|
||||
"derp.1",
|
||||
".derp.swp",
|
||||
];
|
||||
|
||||
let mut fr = FeroxResponse::default();
|
||||
fr.set_url("http://localhost/derp");
|
||||
|
||||
let urls = toh.generate_backup_urls(&fr).await;
|
||||
|
||||
let paths: Vec<_> = urls
|
||||
.iter()
|
||||
.map(|url| url.path_segments().unwrap().last().unwrap())
|
||||
.collect();
|
||||
|
||||
assert_eq!(urls.len(), 6);
|
||||
|
||||
for path in paths {
|
||||
assert!(expected.contains(&path));
|
||||
}
|
||||
|
||||
tx.send(Command::Exit).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
|
||||
/// test to ensure that backups are requested from the directory in which they were found
|
||||
/// re: issue #513
|
||||
async fn generate_backup_urls_creates_correct_urls_when_not_at_root() {
|
||||
let (tx, rx) = mpsc::unbounded_channel::<Command>();
|
||||
let (tx_file, _) = mpsc::unbounded_channel::<Command>();
|
||||
let config = Arc::new(Configuration::new().unwrap());
|
||||
let handles = Arc::new(Handles::for_testing(None, None).0);
|
||||
|
||||
let toh = TermOutHandler {
|
||||
config,
|
||||
file_task: None,
|
||||
receiver: rx,
|
||||
tx_file,
|
||||
handles: Some(handles),
|
||||
};
|
||||
|
||||
let expected: Vec<_> = vec![
|
||||
"http://localhost/wordpress/derp.php~",
|
||||
"http://localhost/wordpress/derp.php.bak",
|
||||
"http://localhost/wordpress/derp.php.bak2",
|
||||
"http://localhost/wordpress/derp.php.old",
|
||||
"http://localhost/wordpress/derp.php.1",
|
||||
"http://localhost/wordpress/.derp.php.swp",
|
||||
"http://localhost/wordpress/derp.bak",
|
||||
];
|
||||
|
||||
let mut fr = FeroxResponse::default();
|
||||
fr.set_url("http://localhost/wordpress/derp.php");
|
||||
|
||||
let urls = toh.generate_backup_urls(&fr).await;
|
||||
|
||||
let url_strs: Vec<_> = urls.iter().map(|url| url.as_str()).collect();
|
||||
|
||||
assert_eq!(urls.len(), 7);
|
||||
|
||||
for url_str in url_strs {
|
||||
assert!(expected.contains(&url_str));
|
||||
}
|
||||
|
||||
tx.send(Command::Exit).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ use crate::{
|
||||
|
||||
use super::command::Command::AddToUsizeField;
|
||||
use super::*;
|
||||
use crate::statistics::StatField;
|
||||
use reqwest::Url;
|
||||
use tokio::time::Duration;
|
||||
|
||||
@@ -176,6 +177,23 @@ impl ScanHandler {
|
||||
Command::Sync(sender) => {
|
||||
sender.send(true).unwrap_or_default();
|
||||
}
|
||||
Command::AddDiscoveredExtension(new_extension) => {
|
||||
// if --collect-extensions was used, AND the new extension isn't in
|
||||
// the --dont-collect list AND it's also not in the --extensions list, AND
|
||||
// we actually added a new extension (i.e. wasn't previously known), add
|
||||
// it to FeroxScans.collected_extensions
|
||||
if self.handles.config.collect_extensions
|
||||
&& !self.handles.config.dont_collect.contains(&new_extension)
|
||||
&& !self.handles.config.extensions.contains(&new_extension)
|
||||
&& self.data.add_discovered_extension(new_extension)
|
||||
{
|
||||
self.update_all_bar_lengths()?;
|
||||
self.handles
|
||||
.stats
|
||||
.send(Command::AddToUsizeField(StatField::ExtensionsCollected, 1))
|
||||
.unwrap_or_default();
|
||||
}
|
||||
}
|
||||
_ => {} // no other commands needed for RecursionHandler
|
||||
}
|
||||
}
|
||||
@@ -184,6 +202,93 @@ impl ScanHandler {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// update all current and future bar lengths
|
||||
///
|
||||
/// updating all bar lengths correctly requires a few different actions on our part.
|
||||
/// - get the current number of requests expected per scan (dynamic when --collect-extensions
|
||||
/// is used)
|
||||
/// - update the overall progress bar via the statistics handler (total expected)
|
||||
/// - update the expected per scan value tracked in the statistics handler
|
||||
/// - update progress bars on each FeroxScan (type::directory) that are running/not-started
|
||||
/// - update progress bar length on FeroxScans (this is used when creating new a FeroxScan and
|
||||
/// determines the new scan's progress bar length)
|
||||
fn update_all_bar_lengths(&self) -> Result<()> {
|
||||
log::trace!("enter: update_all_bar_lengths");
|
||||
|
||||
// current number of requests expected per scan
|
||||
// ExpectedPerScan and TotalExpected are a += action, so we need the wordlist length to
|
||||
// update them while the other updates use expected_num_requests_per_dir
|
||||
let num_words = self.get_wordlist()?.len();
|
||||
let current_expectation = self.handles.expected_num_requests_per_dir() as u64;
|
||||
|
||||
// used in the calculation of bar width down below, see explanation there
|
||||
let divisor = self.handles.expected_num_requests_multiplier() as u64 - 1;
|
||||
|
||||
// add another `wordlist.len` to the expected per scan tracker in the statistics handler
|
||||
self.handles
|
||||
.stats
|
||||
.send(AddToUsizeField(StatField::ExpectedPerScan, num_words))?;
|
||||
|
||||
// since we're adding extensions in the middle of scans (potentially), we need to take
|
||||
// current number of requests into account, new_total will be used as an accumulator
|
||||
// used to increment the overall progress bar
|
||||
let mut new_total = 0;
|
||||
|
||||
if let Ok(ferox_scans) = self.handles.ferox_scans() {
|
||||
// update progress bar length on FeroxScans, which used when creating a new FeroxScan's
|
||||
// progress bar and should mirror the expected_per_scan field on Statistics
|
||||
ferox_scans.set_bar_length(current_expectation);
|
||||
|
||||
if let Ok(scans_guard) = ferox_scans.scans.read() {
|
||||
// update progress bars on each FeroxScan where its scan type is directory and
|
||||
// scan status is either running or not-started
|
||||
for scan in scans_guard.iter() {
|
||||
if scan.is_active() {
|
||||
// current number of words left in the 'to-scan' bin, for example:
|
||||
//
|
||||
// say we have a 2000 word wordlist, have `-x js` on the command line, and
|
||||
// just found `php` as a new extension
|
||||
//
|
||||
// that puts our state at:
|
||||
// - wordlist length: 2000
|
||||
// - total expected: 4000 (original length * 2 for -x js)
|
||||
//
|
||||
// let's assume the current scan has sent 3000 requests so far
|
||||
// that means to get the number of `words` left to send, we need to take
|
||||
// the difference of 4000 and 3000 and then divide that by the current
|
||||
// multiplier (2 in the example)
|
||||
//
|
||||
// (4000 - 3000) / 2 => 500 words left to send
|
||||
//
|
||||
// the remaining 500 words will be sent as 3 variations (word, word.js,
|
||||
// word.php). So, we would then need to increment the bar by 500 to
|
||||
// reflect the dynamism of adding extensions mid-scan.
|
||||
let bar = scan.progress_bar();
|
||||
|
||||
// (4000 - 3000) / 2 => 500 words left to send
|
||||
let length = bar.length();
|
||||
let num_words_left = (length - bar.position()) / divisor;
|
||||
|
||||
// accumulate each bar's increment value for incrementing the total bar
|
||||
new_total += num_words_left;
|
||||
|
||||
bar.inc_length(num_words_left);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// add the total number of newly expected requests to the overall progress bar
|
||||
// via the statistics handler
|
||||
self.handles.stats.send(AddToUsizeField(
|
||||
StatField::TotalExpected,
|
||||
new_total as usize,
|
||||
))?;
|
||||
}
|
||||
|
||||
log::trace!("exit: update_all_bar_lengths");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Helper to easily get the (locked) underlying wordlist
|
||||
pub fn get_wordlist(&self) -> Result<Arc<Vec<String>>> {
|
||||
if let Ok(guard) = self.wordlist.lock().as_ref() {
|
||||
@@ -263,8 +368,8 @@ impl ScanHandler {
|
||||
async fn try_recursion(&mut self, response: Box<FeroxResponse>) -> Result<()> {
|
||||
log::trace!("enter: try_recursion({:?})", response,);
|
||||
|
||||
if !response.is_directory() {
|
||||
// not a directory, quick exit
|
||||
if !self.handles.config.force_recursion && !response.is_directory() {
|
||||
// not a directory and --force-recursion wasn't used, quick exit
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
|
||||
@@ -103,7 +103,7 @@ impl StatsHandler {
|
||||
Command::AddToUsizeField(field, value) => {
|
||||
self.stats.update_usize_field(field, value);
|
||||
|
||||
if matches!(field, StatField::TotalScans) {
|
||||
if matches!(field, StatField::TotalScans | StatField::TotalExpected) {
|
||||
self.bar.set_length(self.stats.total_expected() as u64);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,14 +13,22 @@ pub(super) const LINKFINDER_REGEX: &str = r#"(?:"|')(((?:[a-zA-Z]{1,10}://|//)[^
|
||||
pub(super) const ROBOTS_TXT_REGEX: &str =
|
||||
r#"(?m)^ *(Allow|Disallow): *(?P<url_path>[a-zA-Z0-9._/?#@!&'()+,;%=-]+?)$"#; // multi-line (?m)
|
||||
|
||||
/// Regular expression to filter bad characters from extracted url paths
|
||||
///
|
||||
/// ref: https://www.rfc-editor.org/rfc/rfc3986#section-2
|
||||
pub(super) const URL_CHARS_REGEX: &str = r#"["<>\\^`{|} ]"#;
|
||||
|
||||
/// Which type of extraction should be performed
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub enum ExtractionTarget {
|
||||
/// Examine a response body and extract links
|
||||
/// Examine a response body and extract javascript and html links (multiple tags)
|
||||
ResponseBody,
|
||||
|
||||
/// Examine robots.txt (specifically) and extract links
|
||||
RobotsTxt,
|
||||
|
||||
/// Extract all <a> tags from a page
|
||||
DirectoryListing,
|
||||
}
|
||||
|
||||
/// responsible for building an `Extractor`
|
||||
@@ -28,7 +36,7 @@ pub struct ExtractorBuilder<'a> {
|
||||
/// Response from which to extract links
|
||||
response: Option<&'a FeroxResponse>,
|
||||
|
||||
/// Response from which to extract links
|
||||
/// URL of where to extract links
|
||||
url: String,
|
||||
|
||||
/// Handles object to house the underlying mpsc transmitters
|
||||
@@ -76,9 +84,9 @@ impl<'a> ExtractorBuilder<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// finalize configuration of ExtratorBuilder and return an Extractor
|
||||
/// finalize configuration of `ExtractorBuilder` and return an `Extractor`
|
||||
///
|
||||
/// requires either with_url or with_response to have been used in the build process
|
||||
/// requires either `with_url` or `with_response` to have been used in the build process
|
||||
pub fn build(&self) -> Result<Extractor<'a>> {
|
||||
if (self.url.is_empty() && self.response.is_none()) || self.handles.is_none() {
|
||||
bail!("Extractor requires a URL or a FeroxResponse be specified as well as a Handles object")
|
||||
@@ -87,6 +95,7 @@ impl<'a> ExtractorBuilder<'a> {
|
||||
Ok(Extractor {
|
||||
links_regex: Regex::new(LINKFINDER_REGEX).unwrap(),
|
||||
robots_regex: Regex::new(ROBOTS_TXT_REGEX).unwrap(),
|
||||
url_regex: Regex::new(URL_CHARS_REGEX).unwrap(),
|
||||
response: if self.response.is_some() {
|
||||
Some(self.response.unwrap())
|
||||
} else {
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
use super::*;
|
||||
use crate::utils::should_deny_url;
|
||||
use crate::{
|
||||
client,
|
||||
event_handlers::{
|
||||
Command,
|
||||
Command::{AddError, AddToUsizeField},
|
||||
Handles,
|
||||
},
|
||||
@@ -13,12 +11,13 @@ use crate::{
|
||||
StatField::{LinksExtracted, TotalExpected},
|
||||
},
|
||||
url::FeroxUrl,
|
||||
utils::{logged_request, make_request},
|
||||
utils::{logged_request, make_request, send_try_recursion_command, should_deny_url},
|
||||
ExtractionResult, DEFAULT_METHOD,
|
||||
};
|
||||
use anyhow::{bail, Context, Result};
|
||||
use reqwest::{StatusCode, Url};
|
||||
use std::collections::HashSet;
|
||||
use tokio::sync::oneshot;
|
||||
use reqwest::{Client, StatusCode, Url};
|
||||
use scraper::{Html, Selector};
|
||||
use std::{borrow::Cow, collections::HashSet};
|
||||
|
||||
/// Whether an active scan is recursive or not
|
||||
#[derive(Debug)]
|
||||
@@ -39,10 +38,13 @@ pub struct Extractor<'a> {
|
||||
/// `ROBOTS_TXT_REGEX` as a regex::Regex type
|
||||
pub(super) robots_regex: Regex,
|
||||
|
||||
/// regex to validate a url
|
||||
pub(super) url_regex: Regex,
|
||||
|
||||
/// Response from which to extract links
|
||||
pub(super) response: Option<&'a FeroxResponse>,
|
||||
|
||||
/// Response from which to extract links
|
||||
/// URL of where to extract links
|
||||
pub(super) url: String,
|
||||
|
||||
/// Handles object to house the underlying mpsc transmitters
|
||||
@@ -55,18 +57,77 @@ pub struct Extractor<'a> {
|
||||
/// Extractor implementation
|
||||
impl<'a> Extractor<'a> {
|
||||
/// perform extraction from the given target and return any links found
|
||||
pub async fn extract(&self) -> Result<HashSet<String>> {
|
||||
log::trace!("enter: extract (this fn has associated trace exit msg)");
|
||||
pub async fn extract(&self) -> Result<ExtractionResult> {
|
||||
log::trace!(
|
||||
"enter: extract({:?}) (this fn has no associated trace exit msg)",
|
||||
self.target
|
||||
);
|
||||
match self.target {
|
||||
ExtractionTarget::ResponseBody => Ok(self.extract_from_body().await?),
|
||||
ExtractionTarget::RobotsTxt => Ok(self.extract_from_robots().await?),
|
||||
ExtractionTarget::DirectoryListing => Ok(self.extract_from_dir_listing().await?),
|
||||
}
|
||||
}
|
||||
|
||||
/// wrapper around logic that performs the following:
|
||||
/// - parses `url_to_parse`
|
||||
/// - bails if the parsed url doesn't belong to the original host/domain
|
||||
/// - otherwise, calls `add_all_sub_paths` with the parsed result
|
||||
fn parse_url_and_add_subpaths(
|
||||
&self,
|
||||
url_to_parse: &str,
|
||||
original_url: &Url,
|
||||
links: &mut HashSet<String>,
|
||||
) -> Result<()> {
|
||||
log::trace!("enter: parse_url_and_add_subpaths({:?})", links);
|
||||
|
||||
match Url::parse(url_to_parse) {
|
||||
Ok(absolute) => {
|
||||
if absolute.domain() != original_url.domain()
|
||||
|| absolute.host() != original_url.host()
|
||||
{
|
||||
// domains/ips are not the same, don't scan things that aren't part of the original
|
||||
// target url
|
||||
bail!("parsed url does not belong to original domain/host");
|
||||
}
|
||||
|
||||
if self.add_all_sub_paths(absolute.path(), links).is_err() {
|
||||
log::warn!("could not add sub-paths from {} to {:?}", absolute, links);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
// this is the expected error that happens when we try to parse a url fragment
|
||||
// ex: Url::parse("/login") -> Err("relative URL without a base")
|
||||
// while this is technically an error, these are good results for us
|
||||
if e.to_string().contains("relative URL without a base") {
|
||||
if self.add_all_sub_paths(url_to_parse, links).is_err() {
|
||||
log::warn!(
|
||||
"could not add sub-paths from {} to {:?}",
|
||||
url_to_parse,
|
||||
links
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// unexpected error has occurred
|
||||
log::warn!("Could not parse given url: {}", e);
|
||||
self.handles.stats.send(AddError(Other)).unwrap_or_default();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log::trace!("exit: parse_url_and_add_subpaths");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// given a set of links from a normal http body response, task the request handler to make
|
||||
/// the requests
|
||||
pub async fn request_links(&self, links: HashSet<String>) -> Result<()> {
|
||||
pub async fn request_links(&mut self, links: HashSet<String>) -> Result<()> {
|
||||
log::trace!("enter: request_links({:?})", links);
|
||||
|
||||
if links.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let recursive = if self.handles.config.no_recursion {
|
||||
RecursionStatus::NotRecursive
|
||||
} else {
|
||||
@@ -74,6 +135,7 @@ impl<'a> Extractor<'a> {
|
||||
};
|
||||
|
||||
let scanned_urls = self.handles.ferox_scans()?;
|
||||
self.update_stats(links.len())?;
|
||||
|
||||
for link in links {
|
||||
let mut resp = match self.request_link(&link).await {
|
||||
@@ -91,11 +153,15 @@ impl<'a> Extractor<'a> {
|
||||
continue;
|
||||
}
|
||||
|
||||
if resp.is_file() {
|
||||
// very likely a file, simply request and report
|
||||
log::debug!("Extracted file: {}", resp);
|
||||
// request and report assumed file
|
||||
if resp.is_file() || !resp.is_directory() {
|
||||
log::debug!("Extracted File: {}", resp);
|
||||
|
||||
scanned_urls.add_file_scan(&resp.url().to_string(), ScanOrder::Latest);
|
||||
scanned_urls.add_file_scan(resp.url().as_str(), ScanOrder::Latest);
|
||||
|
||||
if self.handles.config.collect_extensions {
|
||||
resp.parse_extension(self.handles.clone())?;
|
||||
}
|
||||
|
||||
if let Err(e) = resp.send_report(self.handles.output.tx.clone()) {
|
||||
log::warn!("Could not send FeroxResponse to output handler: {}", e);
|
||||
@@ -121,19 +187,47 @@ impl<'a> Extractor<'a> {
|
||||
resp.set_url(&format!("{}/", resp.url()));
|
||||
}
|
||||
|
||||
self.handles
|
||||
.send_scan_command(Command::TryRecursion(Box::new(resp)))?;
|
||||
let (tx, rx) = oneshot::channel::<bool>();
|
||||
self.handles.send_scan_command(Command::Sync(tx))?;
|
||||
rx.await?;
|
||||
if self.handles.config.filter_status.is_empty() {
|
||||
// -C wasn't used, so -s is the only 'filter' left to account for
|
||||
if self
|
||||
.handles
|
||||
.config
|
||||
.status_codes
|
||||
.contains(&resp.status().as_u16())
|
||||
{
|
||||
send_try_recursion_command(self.handles.clone(), resp).await?;
|
||||
}
|
||||
} else {
|
||||
// -C was used, that means the filters above would have removed
|
||||
// those responses, and anything else should be let through
|
||||
send_try_recursion_command(self.handles.clone(), resp).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
log::trace!("exit: request_links");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Given a `reqwest::Response`, perform the following actions
|
||||
/// - parse the response's text for links using the linkfinder regex
|
||||
/// wrapper around link extraction via html attributes
|
||||
fn extract_all_links_from_html_tags(
|
||||
&self,
|
||||
resp_url: &Url,
|
||||
links: &mut HashSet<String>,
|
||||
html: &Html,
|
||||
) {
|
||||
self.extract_links_by_attr(resp_url, links, html, "a", "href");
|
||||
self.extract_links_by_attr(resp_url, links, html, "img", "src");
|
||||
self.extract_links_by_attr(resp_url, links, html, "form", "action");
|
||||
self.extract_links_by_attr(resp_url, links, html, "script", "src");
|
||||
self.extract_links_by_attr(resp_url, links, html, "iframe", "src");
|
||||
self.extract_links_by_attr(resp_url, links, html, "div", "src");
|
||||
self.extract_links_by_attr(resp_url, links, html, "frame", "src");
|
||||
self.extract_links_by_attr(resp_url, links, html, "embed", "src");
|
||||
self.extract_links_by_attr(resp_url, links, html, "link", "href");
|
||||
}
|
||||
|
||||
/// Given the body of a `reqwest::Response`, perform the following actions
|
||||
/// - parse the body for links using the linkfinder regex
|
||||
/// - for every link found take its url path and parse each sub-path
|
||||
/// - example: Response contains a link fragment `homepage/assets/img/icons/handshake.svg`
|
||||
/// with a base url of http://localhost, the following urls would be returned:
|
||||
@@ -142,62 +236,40 @@ impl<'a> Extractor<'a> {
|
||||
/// - homepage/assets/img/
|
||||
/// - homepage/assets/
|
||||
/// - homepage/
|
||||
pub(super) async fn extract_from_body(&self) -> Result<HashSet<String>> {
|
||||
log::trace!("enter: get_links");
|
||||
fn extract_all_links_from_javascript(
|
||||
&self,
|
||||
response_body: &str,
|
||||
response_url: &Url,
|
||||
links: &mut HashSet<String>,
|
||||
) {
|
||||
log::trace!(
|
||||
"enter: extract_all_links_from_javascript(html body..., {}, {:?})",
|
||||
response_url.as_str(),
|
||||
links
|
||||
);
|
||||
|
||||
let mut links = HashSet::<String>::new();
|
||||
|
||||
let body = self.response.unwrap().text();
|
||||
|
||||
for capture in self.links_regex.captures_iter(body) {
|
||||
for capture in self.links_regex.captures_iter(response_body) {
|
||||
// remove single & double quotes from both ends of the capture
|
||||
// capture[0] is the entire match, additional capture groups start at [1]
|
||||
let link = capture[0].trim_matches(|c| c == '\'' || c == '"');
|
||||
|
||||
match Url::parse(link) {
|
||||
Ok(absolute) => {
|
||||
if absolute.domain() != self.response.unwrap().url().domain()
|
||||
|| absolute.host() != self.response.unwrap().url().host()
|
||||
{
|
||||
// domains/ips are not the same, don't scan things that aren't part of the original
|
||||
// target url
|
||||
continue;
|
||||
}
|
||||
|
||||
if self.add_all_sub_paths(absolute.path(), &mut links).is_err() {
|
||||
log::warn!("could not add sub-paths from {} to {:?}", absolute, links);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
// this is the expected error that happens when we try to parse a url fragment
|
||||
// ex: Url::parse("/login") -> Err("relative URL without a base")
|
||||
// while this is technically an error, these are good results for us
|
||||
if e.to_string().contains("relative URL without a base") {
|
||||
if self.add_all_sub_paths(link, &mut links).is_err() {
|
||||
log::warn!("could not add sub-paths from {} to {:?}", link, links);
|
||||
}
|
||||
} else {
|
||||
// unexpected error has occurred
|
||||
log::warn!("Could not parse given url: {}", e);
|
||||
self.handles.stats.send(AddError(Other)).unwrap_or_default();
|
||||
}
|
||||
}
|
||||
if self
|
||||
.parse_url_and_add_subpaths(link, response_url, links)
|
||||
.is_err()
|
||||
{
|
||||
// purposely not logging the error here, due to the frequency with which it gets hit
|
||||
}
|
||||
}
|
||||
|
||||
self.update_stats(links.len())?;
|
||||
|
||||
log::trace!("exit: get_links -> {:?}", links);
|
||||
|
||||
Ok(links)
|
||||
log::trace!("exit: extract_all_links_from_javascript");
|
||||
}
|
||||
|
||||
/// take a url fragment like homepage/assets/img/icons/handshake.svg and
|
||||
/// incrementally add
|
||||
/// - homepage/assets/img/icons/
|
||||
/// - homepage/assets/img/
|
||||
/// - homepage/assets/
|
||||
/// - homepage/
|
||||
/// - homepage/assets/img/icons/
|
||||
/// - homepage/assets/img/
|
||||
/// - homepage/assets/
|
||||
/// - homepage/
|
||||
fn add_all_sub_paths(&self, url_path: &str, links: &mut HashSet<String>) -> Result<()> {
|
||||
log::trace!("enter: add_all_sub_paths({}, {:?})", url_path, links);
|
||||
|
||||
@@ -209,6 +281,45 @@ impl<'a> Extractor<'a> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// given a url path, trim whitespace, remove slashes, and queries/fragments; return the
|
||||
/// normalized string
|
||||
pub(super) fn normalize_url_path(&self, path: &str) -> String {
|
||||
log::trace!("enter: normalize_url_path({})", path);
|
||||
|
||||
// remove whitespace and leading '/'
|
||||
let path_str: String = path
|
||||
.trim()
|
||||
.trim_start_matches('/')
|
||||
.chars()
|
||||
.filter(|char| !char.is_whitespace())
|
||||
.collect();
|
||||
|
||||
// snippets from rfc-3986:
|
||||
//
|
||||
// foo://example.com:8042/over/there?name=ferret#nose
|
||||
// \_/ \______________/\_________/ \_________/ \__/
|
||||
// | | | | |
|
||||
// scheme authority path query fragment
|
||||
//
|
||||
// The path component is terminated
|
||||
// by the first question mark ("?") or number sign ("#") character, or
|
||||
// by the end of the URI.
|
||||
//
|
||||
// The query component is indicated by the first question
|
||||
// mark ("?") character and terminated by a number sign ("#") character
|
||||
// or by the end of the URI.
|
||||
let (path_str, _discarded) = path_str
|
||||
.split_once('?')
|
||||
// if there isn't a '?', try to remove a fragment
|
||||
.unwrap_or_else(|| {
|
||||
// if there isn't a '#', return (original, empty)
|
||||
path_str.split_once('#').unwrap_or((&path_str, ""))
|
||||
});
|
||||
|
||||
log::trace!("exit: normalize_url_path -> {}", path_str);
|
||||
path_str.into()
|
||||
}
|
||||
|
||||
/// Iterate over a given path, return a list of every sub-path found
|
||||
///
|
||||
/// example: `path` contains a link fragment `homepage/assets/img/icons/handshake.svg`
|
||||
@@ -222,8 +333,14 @@ impl<'a> Extractor<'a> {
|
||||
log::trace!("enter: get_sub_paths_from_path({})", path);
|
||||
let mut paths = vec![];
|
||||
|
||||
let normalized_path = self.normalize_url_path(path);
|
||||
|
||||
// filter out any empty strings caused by .split
|
||||
let mut parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
|
||||
let mut parts: Vec<Cow<_>> = normalized_path
|
||||
.split('/')
|
||||
.map(|s| self.url_regex.replace_all(s, ""))
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect();
|
||||
|
||||
let length = parts.len();
|
||||
|
||||
@@ -256,7 +373,7 @@ impl<'a> Extractor<'a> {
|
||||
paths
|
||||
}
|
||||
|
||||
/// simple helper to stay DRY, trys to join a url + fragment and add it to the `links` HashSet
|
||||
/// simple helper to stay DRY, tries to join a url + fragment and add it to the `links` HashSet
|
||||
pub(super) fn add_link_to_set_of_links(
|
||||
&self,
|
||||
link: &str,
|
||||
@@ -265,7 +382,9 @@ impl<'a> Extractor<'a> {
|
||||
log::trace!("enter: add_link_to_set_of_links({}, {:?})", link, links);
|
||||
|
||||
let old_url = match self.target {
|
||||
ExtractionTarget::ResponseBody => self.response.unwrap().url().clone(),
|
||||
ExtractionTarget::ResponseBody | ExtractionTarget::DirectoryListing => {
|
||||
self.response.unwrap().url().clone()
|
||||
}
|
||||
ExtractionTarget::RobotsTxt => match Url::parse(&self.url) {
|
||||
Ok(u) => u,
|
||||
Err(e) => {
|
||||
@@ -278,6 +397,17 @@ impl<'a> Extractor<'a> {
|
||||
.join(link)
|
||||
.with_context(|| format!("Could not join {} with {}", old_url, link))?;
|
||||
|
||||
if old_url.domain() != new_url.domain() || old_url.host() != old_url.host() {
|
||||
// domains/ips are not the same, don't scan things that aren't part of the original
|
||||
// target url
|
||||
log::debug!(
|
||||
"Skipping {} because it's not part of the original target",
|
||||
new_url
|
||||
);
|
||||
log::trace!("exit: add_link_to_set_of_links");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
links.insert(new_url.to_string());
|
||||
|
||||
log::trace!("exit: add_link_to_set_of_links");
|
||||
@@ -286,11 +416,6 @@ impl<'a> Extractor<'a> {
|
||||
}
|
||||
|
||||
/// Wrapper around link extraction logic
|
||||
/// currently used in two places:
|
||||
/// - links from response bodies
|
||||
/// - links from robots.txt responses
|
||||
///
|
||||
/// general steps taken:
|
||||
/// - create a new Url object based on cli options/args
|
||||
/// - check if the new Url has already been seen/scanned -> None
|
||||
/// - make a request to the new Url ? -> Some(response) : None
|
||||
@@ -304,7 +429,7 @@ impl<'a> Extractor<'a> {
|
||||
|
||||
let scanned_urls = self.handles.ferox_scans()?;
|
||||
|
||||
if scanned_urls.get_scan_by_url(&new_url.to_string()).is_some() {
|
||||
if scanned_urls.get_scan_by_url(new_url.as_ref()).is_some() {
|
||||
//we've seen the url before and don't need to scan again
|
||||
log::trace!("exit: request_link -> None");
|
||||
bail!("previously seen url");
|
||||
@@ -324,10 +449,16 @@ impl<'a> Extractor<'a> {
|
||||
}
|
||||
|
||||
// make the request and store the response
|
||||
let new_response = logged_request(&new_url, self.handles.clone()).await?;
|
||||
let new_response =
|
||||
logged_request(&new_url, DEFAULT_METHOD, None, self.handles.clone()).await?;
|
||||
|
||||
let new_ferox_response =
|
||||
FeroxResponse::from(new_response, url, true, self.handles.config.output_level).await;
|
||||
let new_ferox_response = FeroxResponse::from(
|
||||
new_response,
|
||||
url,
|
||||
DEFAULT_METHOD,
|
||||
self.handles.config.output_level,
|
||||
)
|
||||
.await;
|
||||
|
||||
log::trace!("exit: request_link -> {:?}", new_ferox_response);
|
||||
|
||||
@@ -342,83 +473,178 @@ impl<'a> Extractor<'a> {
|
||||
/// http://localhost/stuff/things
|
||||
/// this function requests:
|
||||
/// http://localhost/robots.txt
|
||||
pub(super) async fn extract_from_robots(&self) -> Result<HashSet<String>> {
|
||||
pub(super) async fn extract_from_robots(&self) -> Result<ExtractionResult> {
|
||||
log::trace!("enter: extract_robots_txt");
|
||||
|
||||
let mut links: HashSet<String> = HashSet::new();
|
||||
let mut result: HashSet<_> = ExtractionResult::new();
|
||||
|
||||
let response = self.request_robots_txt().await?;
|
||||
// request
|
||||
let response = self.make_extract_request("/robots.txt").await?;
|
||||
let body = response.text();
|
||||
|
||||
for capture in self.robots_regex.captures_iter(response.text()) {
|
||||
for capture in self.robots_regex.captures_iter(body) {
|
||||
if let Some(new_path) = capture.name("url_path") {
|
||||
let mut new_url = Url::parse(&self.url)?;
|
||||
|
||||
new_url.set_path(new_path.as_str());
|
||||
if self.add_all_sub_paths(new_url.path(), &mut links).is_err() {
|
||||
log::warn!("could not add sub-paths from {} to {:?}", new_url, links);
|
||||
|
||||
if self.add_all_sub_paths(new_url.path(), &mut result).is_err() {
|
||||
log::warn!("could not add sub-paths from {} to {:?}", new_url, result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.update_stats(links.len())?;
|
||||
|
||||
log::trace!("exit: extract_robots_txt -> {:?}", links);
|
||||
Ok(links)
|
||||
log::trace!("exit: extract_robots_txt -> {:?}", result);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// helper function that simply requests /robots.txt on the given url's base url
|
||||
/// outer-most wrapper for parsing html response bodies in search of additional content.
|
||||
/// performs the following high-level steps:
|
||||
/// - requests the page, if necessary
|
||||
/// - checks the page to see if directory listing is enabled and sucks up all the links, if so
|
||||
/// - uses the linkfinder regex to grab links from embedded javascript/javascript files
|
||||
/// - extracts many different types of link sources from the html itself
|
||||
pub(super) async fn extract_from_body(&self) -> Result<ExtractionResult> {
|
||||
log::trace!("enter: extract_from_body");
|
||||
|
||||
let mut result = ExtractionResult::new();
|
||||
|
||||
let response = self.response.unwrap();
|
||||
let resp_url = response.url();
|
||||
let body = response.text();
|
||||
let html = Html::parse_document(body);
|
||||
|
||||
// extract links from html tags/attributes and embedded javascript
|
||||
self.extract_all_links_from_html_tags(resp_url, &mut result, &html);
|
||||
self.extract_all_links_from_javascript(body, resp_url, &mut result);
|
||||
|
||||
log::trace!("exit: extract_from_body -> {:?}", result);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// parses html response bodies in search of <a> tags.
|
||||
///
|
||||
/// the assumption is that directory listing is turned on and this extraction target simply
|
||||
/// scoops up all the links for the given directory. The test to detect a directory listing
|
||||
/// is located in `HeuristicTests`
|
||||
pub async fn extract_from_dir_listing(&self) -> Result<ExtractionResult> {
|
||||
log::trace!("enter: extract_from_dir_listing");
|
||||
|
||||
let mut result = ExtractionResult::new();
|
||||
|
||||
let response = self.response.unwrap();
|
||||
let html = Html::parse_document(response.text());
|
||||
|
||||
self.extract_links_by_attr(response.url(), &mut result, &html, "a", "href");
|
||||
|
||||
log::trace!("exit: extract_from_dir_listing -> {:?}", result);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// simple helper to get html links by tag/attribute and add it to the `links` HashSet
|
||||
fn extract_links_by_attr(
|
||||
&self,
|
||||
resp_url: &Url,
|
||||
links: &mut HashSet<String>,
|
||||
html: &Html,
|
||||
html_tag: &str,
|
||||
html_attr: &str,
|
||||
) {
|
||||
log::trace!("enter: extract_links_by_attr");
|
||||
|
||||
let selector = Selector::parse(html_tag).unwrap();
|
||||
|
||||
let tags = html
|
||||
.select(&selector)
|
||||
.filter(|a| a.value().attrs().any(|attr| attr.0 == html_attr));
|
||||
|
||||
for tag in tags {
|
||||
if let Some(link) = tag.value().attr(html_attr) {
|
||||
log::debug!("Parsed link \"{}\" from {}", link, resp_url.as_str());
|
||||
|
||||
if self
|
||||
.parse_url_and_add_subpaths(link, resp_url, links)
|
||||
.is_err()
|
||||
{
|
||||
log::debug!("link didn't belong to the target domain/host: {}", link);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log::trace!("exit: extract_links_by_attr");
|
||||
}
|
||||
|
||||
/// helper function that simply requests at <location> on the given url's base url
|
||||
///
|
||||
/// example:
|
||||
/// http://localhost/api/users -> http://localhost/robots.txt
|
||||
///
|
||||
/// The length of the given path has no effect on what's requested; it's always
|
||||
/// base url + /robots.txt
|
||||
pub(super) async fn request_robots_txt(&self) -> Result<FeroxResponse> {
|
||||
log::trace!("enter: get_robots_file");
|
||||
/// http://localhost/api/users -> http://localhost/<location>
|
||||
pub(super) async fn make_extract_request(&self, location: &str) -> Result<FeroxResponse> {
|
||||
log::trace!("enter: make_extract_request");
|
||||
|
||||
// more often than not, domain/robots.txt will redirect to www.domain/robots.txt or something
|
||||
// similar; to account for that, create a client that will follow redirects, regardless of
|
||||
// what the user specified for the scanning client. Other than redirects, it will respect
|
||||
// all other user specified settings
|
||||
let follow_redirects = true;
|
||||
// need late binding here to avoid 'creates a temporary which is freed...' in the
|
||||
// `let ... if` below to avoid cloning the client out of config
|
||||
let mut client = Client::new();
|
||||
|
||||
let proxy = if self.handles.config.proxy.is_empty() {
|
||||
None
|
||||
if location == "/robots.txt" {
|
||||
// more often than not, domain/robots.txt will redirect to www.domain/robots.txt or something
|
||||
// similar; to account for that, create a client that will follow redirects, regardless of
|
||||
// what the user specified for the scanning client. Other than redirects, it will respect
|
||||
// all other user specified settings
|
||||
let follow_redirects = true;
|
||||
|
||||
let proxy = if self.handles.config.proxy.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(self.handles.config.proxy.as_str())
|
||||
};
|
||||
|
||||
client = client::initialize(
|
||||
self.handles.config.timeout,
|
||||
&self.handles.config.user_agent,
|
||||
follow_redirects,
|
||||
self.handles.config.insecure,
|
||||
&self.handles.config.headers,
|
||||
proxy,
|
||||
)?;
|
||||
}
|
||||
|
||||
let client = if location != "/robots.txt" {
|
||||
&self.handles.config.client
|
||||
} else {
|
||||
Some(self.handles.config.proxy.as_str())
|
||||
&client
|
||||
};
|
||||
|
||||
let client = client::initialize(
|
||||
self.handles.config.timeout,
|
||||
&self.handles.config.user_agent,
|
||||
follow_redirects,
|
||||
self.handles.config.insecure,
|
||||
&self.handles.config.headers,
|
||||
proxy,
|
||||
)?;
|
||||
|
||||
let mut url = Url::parse(&self.url)?;
|
||||
url.set_path("/robots.txt"); // overwrite existing path with /robots.txt
|
||||
url.set_path(location); // overwrite existing path
|
||||
|
||||
// purposefully not using logged_request here due to using the special client
|
||||
let response = make_request(
|
||||
&client,
|
||||
client,
|
||||
&url,
|
||||
DEFAULT_METHOD,
|
||||
None,
|
||||
self.handles.config.output_level,
|
||||
&self.handles.config,
|
||||
self.handles.stats.tx.clone(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let ferox_response =
|
||||
FeroxResponse::from(response, &self.url, true, self.handles.config.output_level).await;
|
||||
let ferox_response = FeroxResponse::from(
|
||||
response,
|
||||
&self.url,
|
||||
DEFAULT_METHOD,
|
||||
self.handles.config.output_level,
|
||||
)
|
||||
.await;
|
||||
// note: don't call parse_extension here. If we call it here, it gets called on robots.txt
|
||||
|
||||
log::trace!("exit: get_robots_file -> {}", ferox_response);
|
||||
log::trace!("exit: make_extract_request -> {}", ferox_response);
|
||||
Ok(ferox_response)
|
||||
}
|
||||
|
||||
/// update total number of links extracted and expected responses
|
||||
fn update_stats(&self, num_links: usize) -> Result<()> {
|
||||
let multiplier = self.handles.config.extensions.len().max(1);
|
||||
let multiplier = self.handles.expected_num_requests_multiplier();
|
||||
|
||||
self.handles
|
||||
.stats
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
use super::builder::{LINKFINDER_REGEX, ROBOTS_TXT_REGEX};
|
||||
use super::builder::{LINKFINDER_REGEX, ROBOTS_TXT_REGEX, URL_CHARS_REGEX};
|
||||
use super::*;
|
||||
use crate::config::{Configuration, OutputLevel};
|
||||
use crate::scan_manager::ScanOrder;
|
||||
use crate::{
|
||||
event_handlers::Handles, scan_manager::FeroxScans, utils::make_request, Command, FeroxChannel,
|
||||
DEFAULT_METHOD,
|
||||
};
|
||||
use anyhow::Result;
|
||||
use httpmock::{Method::GET, MockServer};
|
||||
@@ -19,6 +20,9 @@ lazy_static! {
|
||||
/// Extractor for testing response bodies
|
||||
static ref BODY_EXT: Extractor<'static> = setup_extractor(ExtractionTarget::ResponseBody, Arc::new(FeroxScans::default()));
|
||||
|
||||
/// Extractor for testing paring html
|
||||
static ref PARSEHTML_EXT: Extractor<'static> = setup_extractor(ExtractionTarget::DirectoryListing, Arc::new(FeroxScans::default()));
|
||||
|
||||
/// FeroxResponse for Extractor
|
||||
static ref RESPONSE: FeroxResponse = get_test_response();
|
||||
}
|
||||
@@ -41,6 +45,9 @@ fn setup_extractor(target: ExtractionTarget, scanned_urls: Arc<FeroxScans>) -> E
|
||||
ExtractionTarget::RobotsTxt => builder
|
||||
.url("http://localhost")
|
||||
.target(ExtractionTarget::RobotsTxt),
|
||||
ExtractionTarget::DirectoryListing => builder
|
||||
.url("http://localhost")
|
||||
.target(ExtractionTarget::DirectoryListing),
|
||||
};
|
||||
|
||||
let config = Arc::new(Configuration::new().unwrap());
|
||||
@@ -188,7 +195,6 @@ fn extractor_add_link_to_set_of_links_happy_path() {
|
||||
fn extractor_add_link_to_set_of_links_with_non_base_url() {
|
||||
let mut links = HashSet::<String>::new();
|
||||
let link = "\\\\\\\\";
|
||||
|
||||
assert_eq!(links.len(), 0);
|
||||
assert!(ROBOTS_EXT
|
||||
.add_link_to_set_of_links(link, &mut links)
|
||||
@@ -199,6 +205,34 @@ fn extractor_add_link_to_set_of_links_with_non_base_url() {
|
||||
assert!(links.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// test for filtering queries and fragments
|
||||
fn normalize_url_path_filters_queries_and_fragments() {
|
||||
let handles = Arc::new(Handles::for_testing(None, None).0);
|
||||
let extractor = ExtractorBuilder::default()
|
||||
.url("doesnt matter")
|
||||
.target(ExtractionTarget::RobotsTxt)
|
||||
.handles(handles)
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
let test_strings = [
|
||||
"over/there?name=ferret#nose",
|
||||
"over/there?name=ferret",
|
||||
"over/there#nose",
|
||||
"over/there",
|
||||
"over/there?name#nose",
|
||||
"over/there?name",
|
||||
" over/there?name=ferret#nose ",
|
||||
"over/there?name=ferret ",
|
||||
" over/there#nose",
|
||||
];
|
||||
test_strings.iter().for_each(|&ts| {
|
||||
let normed = extractor.normalize_url_path(ts);
|
||||
assert_eq!(normed, "over/there");
|
||||
});
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
|
||||
/// use make_request to generate a Response, and use the Response to test get_links;
|
||||
/// the response will contain an absolute path to a domain that is not part of the scanned
|
||||
@@ -222,6 +256,8 @@ async fn extractor_get_links_with_absolute_url_that_differs_from_target_domain()
|
||||
let response = make_request(
|
||||
&client,
|
||||
&url,
|
||||
DEFAULT_METHOD,
|
||||
None,
|
||||
OutputLevel::Default,
|
||||
&config,
|
||||
tx_stats.clone(),
|
||||
@@ -232,11 +268,12 @@ async fn extractor_get_links_with_absolute_url_that_differs_from_target_domain()
|
||||
|
||||
let handles = Arc::new(handles);
|
||||
let ferox_response =
|
||||
FeroxResponse::from(response, &srv.url(""), true, OutputLevel::Default).await;
|
||||
FeroxResponse::from(response, &srv.url(""), DEFAULT_METHOD, OutputLevel::Default).await;
|
||||
|
||||
let extractor = Extractor {
|
||||
links_regex: Regex::new(LINKFINDER_REGEX).unwrap(),
|
||||
robots_regex: Regex::new(ROBOTS_TXT_REGEX).unwrap(),
|
||||
url_regex: Regex::new(URL_CHARS_REGEX).unwrap(),
|
||||
response: Some(&ferox_response),
|
||||
url: String::new(),
|
||||
target: ExtractionTarget::ResponseBody,
|
||||
@@ -265,13 +302,14 @@ async fn request_robots_txt_without_proxy() -> Result<()> {
|
||||
let extractor = Extractor {
|
||||
links_regex: Regex::new(LINKFINDER_REGEX).unwrap(),
|
||||
robots_regex: Regex::new(ROBOTS_TXT_REGEX).unwrap(),
|
||||
url_regex: Regex::new(URL_CHARS_REGEX).unwrap(),
|
||||
response: None,
|
||||
url: srv.url("/api/users/stuff/things"),
|
||||
target: ExtractionTarget::RobotsTxt,
|
||||
handles,
|
||||
};
|
||||
|
||||
let resp = extractor.request_robots_txt().await?;
|
||||
let resp = extractor.make_extract_request("/robots.txt").await?;
|
||||
|
||||
assert!(matches!(resp.status(), &StatusCode::OK));
|
||||
println!("{}", resp);
|
||||
@@ -304,7 +342,7 @@ async fn request_robots_txt_with_proxy() -> Result<()> {
|
||||
.handles(handles)
|
||||
.build()?;
|
||||
|
||||
let resp = extractor.request_robots_txt().await?;
|
||||
let resp = extractor.make_extract_request("/robots.txt").await?;
|
||||
|
||||
assert!(matches!(resp.status(), &StatusCode::OK));
|
||||
assert_eq!(resp.content_length(), 19);
|
||||
|
||||
@@ -1,27 +1,30 @@
|
||||
use std::sync::Mutex;
|
||||
use std::sync::RwLock;
|
||||
|
||||
use anyhow::Result;
|
||||
use serde::{ser::SerializeSeq, Serialize, Serializer};
|
||||
|
||||
use crate::response::FeroxResponse;
|
||||
use crate::{
|
||||
event_handlers::Command::AddToUsizeField, statistics::StatField::WildcardsFiltered,
|
||||
CommandSender,
|
||||
event_handlers::Command::AddToUsizeField, response::FeroxResponse,
|
||||
statistics::StatField::WildcardsFiltered, CommandSender,
|
||||
};
|
||||
|
||||
use super::{FeroxFilter, WildcardFilter};
|
||||
use super::{
|
||||
FeroxFilter, LinesFilter, RegexFilter, SimilarityFilter, SizeFilter, StatusCodeFilter,
|
||||
WildcardFilter, WordsFilter,
|
||||
};
|
||||
|
||||
/// Container around a collection of `FeroxFilters`s
|
||||
#[derive(Debug, Default)]
|
||||
pub struct FeroxFilters {
|
||||
/// collection of `FeroxFilters`
|
||||
pub filters: Mutex<Vec<Box<dyn FeroxFilter>>>,
|
||||
pub filters: RwLock<Vec<Box<dyn FeroxFilter>>>,
|
||||
}
|
||||
|
||||
/// implementation of FeroxFilter collection
|
||||
impl FeroxFilters {
|
||||
/// add a single FeroxFilter to the collection
|
||||
pub fn push(&self, filter: Box<dyn FeroxFilter>) -> Result<()> {
|
||||
if let Ok(mut guard) = self.filters.lock() {
|
||||
if let Ok(mut guard) = self.filters.write() {
|
||||
if guard.contains(&filter) {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -31,6 +34,37 @@ impl FeroxFilters {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// remove items from the underlying collection by their index
|
||||
///
|
||||
/// note: indexes passed in should be index-to-remove+1. This is built for the scan mgt menu
|
||||
/// so indexes aren't 0-based whehn the user enters them.
|
||||
///
|
||||
pub fn remove(&self, indices: &mut [usize]) {
|
||||
// since we're removing by index, indices must be sorted and then reversed.
|
||||
// this allows us to iterate over the collection from the rear, allowing any shifting
|
||||
// of the vector to happen on sections that we no longer care about, as we're moving
|
||||
// in the opposite direction
|
||||
indices.sort_unstable();
|
||||
indices.reverse();
|
||||
|
||||
if let Ok(mut guard) = self.filters.write() {
|
||||
for index in indices {
|
||||
// numbering of the menu starts at 1, so we'll need to reduce the index by 1
|
||||
// to account for that. if they've provided 0 as an offset, we'll set the
|
||||
// result to a gigantic number and skip it in the loop with a bounds check
|
||||
let reduced_idx = index.checked_sub(1).unwrap_or(usize::MAX);
|
||||
|
||||
// check if number provided is out of range
|
||||
if reduced_idx >= guard.len() {
|
||||
// usize can't be negative, just need to handle exceeding bounds
|
||||
continue;
|
||||
}
|
||||
|
||||
guard.remove(reduced_idx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Simple helper to stay DRY; determines whether or not a given `FeroxResponse` should be reported
|
||||
/// to the user or not.
|
||||
pub fn should_filter_response(
|
||||
@@ -38,7 +72,7 @@ impl FeroxFilters {
|
||||
response: &FeroxResponse,
|
||||
tx_stats: CommandSender,
|
||||
) -> bool {
|
||||
if let Ok(filters) = self.filters.lock() {
|
||||
if let Ok(filters) = self.filters.read() {
|
||||
for filter in filters.iter() {
|
||||
// wildcard.should_filter goes here
|
||||
if filter.should_filter_response(response) {
|
||||
@@ -54,3 +88,43 @@ impl FeroxFilters {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for FeroxFilters {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
if let Ok(guard) = self.filters.read() {
|
||||
let mut seq = serializer.serialize_seq(Some(guard.len()))?;
|
||||
|
||||
for filter in &*guard {
|
||||
if let Some(line_filter) = filter.as_any().downcast_ref::<LinesFilter>() {
|
||||
seq.serialize_element(line_filter).unwrap_or_default();
|
||||
} else if let Some(word_filter) = filter.as_any().downcast_ref::<WordsFilter>() {
|
||||
seq.serialize_element(word_filter).unwrap_or_default();
|
||||
} else if let Some(size_filter) = filter.as_any().downcast_ref::<SizeFilter>() {
|
||||
seq.serialize_element(size_filter).unwrap_or_default();
|
||||
} else if let Some(status_filter) =
|
||||
filter.as_any().downcast_ref::<StatusCodeFilter>()
|
||||
{
|
||||
seq.serialize_element(status_filter).unwrap_or_default();
|
||||
} else if let Some(regex_filter) = filter.as_any().downcast_ref::<RegexFilter>() {
|
||||
seq.serialize_element(regex_filter).unwrap_or_default();
|
||||
} else if let Some(similarity_filter) =
|
||||
filter.as_any().downcast_ref::<SimilarityFilter>()
|
||||
{
|
||||
seq.serialize_element(similarity_filter).unwrap_or_default();
|
||||
} else if let Some(wildcard_filter) =
|
||||
filter.as_any().downcast_ref::<WildcardFilter>()
|
||||
{
|
||||
seq.serialize_element(wildcard_filter).unwrap_or_default();
|
||||
}
|
||||
}
|
||||
seq.end()
|
||||
} else {
|
||||
// if for some reason we can't unlock the mutex, just write an empty list
|
||||
let seq = serializer.serialize_seq(Some(0))?;
|
||||
seq.end()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
22
src/filters/empty.rs
Normal file
22
src/filters/empty.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
use super::*;
|
||||
|
||||
/// Dummy filter for internal shenanigans
|
||||
#[derive(Default, Debug, PartialEq, Eq)]
|
||||
pub struct EmptyFilter {}
|
||||
|
||||
impl FeroxFilter for EmptyFilter {
|
||||
/// `EmptyFilter` always returns false
|
||||
fn should_filter_response(&self, _response: &FeroxResponse) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Compare one EmptyFilter to another
|
||||
fn box_eq(&self, other: &dyn Any) -> bool {
|
||||
other.downcast_ref::<Self>().map_or(false, |a| self == a)
|
||||
}
|
||||
|
||||
/// Return self as Any for dynamic dispatch purposes
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,10 @@
|
||||
use super::{
|
||||
LinesFilter, RegexFilter, SimilarityFilter, SizeFilter, StatusCodeFilter, WordsFilter,
|
||||
};
|
||||
use crate::{
|
||||
event_handlers::Handles,
|
||||
response::FeroxResponse,
|
||||
skip_fail,
|
||||
utils::{fmt_err, logged_request},
|
||||
Command::AddFilter,
|
||||
SIMILARITY_THRESHOLD,
|
||||
utils::create_similarity_filter, LinesFilter, RegexFilter, SizeFilter, StatusCodeFilter,
|
||||
WordsFilter,
|
||||
};
|
||||
use crate::{event_handlers::Handles, skip_fail, utils::fmt_err, Command::AddFilter};
|
||||
use anyhow::Result;
|
||||
use fuzzyhash::FuzzyHash;
|
||||
use regex::Regex;
|
||||
use reqwest::Url;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// add all user-supplied filters to the (already started) filters handler
|
||||
@@ -68,23 +60,7 @@ pub async fn initialize(handles: Arc<Handles>) -> Result<()> {
|
||||
|
||||
// add any similarity filters to filters handler's FeroxFilters (--filter-similar-to)
|
||||
for similarity_filter in &handles.config.filter_similar {
|
||||
// url as-is based on input, ignores user-specified url manipulation options (add-slash etc)
|
||||
let url = skip_fail!(Url::parse(similarity_filter));
|
||||
|
||||
// attempt to request the given url
|
||||
let resp = skip_fail!(logged_request(&url, handles.clone()).await);
|
||||
|
||||
// if successful, create a filter based on the response's body
|
||||
let fr =
|
||||
FeroxResponse::from(resp, similarity_filter, true, handles.config.output_level).await;
|
||||
|
||||
// hash the response body and store the resulting hash in the filter object
|
||||
let hash = FuzzyHash::new(&fr.text()).to_string();
|
||||
|
||||
let filter = SimilarityFilter {
|
||||
text: hash,
|
||||
threshold: SIMILARITY_THRESHOLD,
|
||||
};
|
||||
let filter = skip_fail!(create_similarity_filter(similarity_filter, handles.clone()).await);
|
||||
|
||||
let boxed_filter = Box::new(filter);
|
||||
skip_fail!(handles.filters.send(AddFilter(boxed_filter)));
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::*;
|
||||
|
||||
/// Simple implementor of FeroxFilter; used to filter out responses based on the number of lines
|
||||
/// in a Response body; specified using -N|--filter-lines
|
||||
#[derive(Default, Debug, PartialEq)]
|
||||
#[derive(Default, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct LinesFilter {
|
||||
/// Number of lines in a Response's body that should be filtered
|
||||
pub line_count: usize,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! contains all of feroxbuster's filters
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::any::Any;
|
||||
use std::fmt::Debug;
|
||||
|
||||
@@ -6,12 +7,14 @@ use crate::response::FeroxResponse;
|
||||
use crate::traits::{FeroxFilter, FeroxSerialize};
|
||||
|
||||
pub use self::container::FeroxFilters;
|
||||
pub(crate) use self::empty::EmptyFilter;
|
||||
pub use self::init::initialize;
|
||||
pub use self::lines::LinesFilter;
|
||||
pub use self::regex::RegexFilter;
|
||||
pub use self::similarity::SimilarityFilter;
|
||||
pub use self::size::SizeFilter;
|
||||
pub use self::status_code::StatusCodeFilter;
|
||||
pub(crate) use self::utils::{create_similarity_filter, filter_lookup};
|
||||
pub use self::wildcard::WildcardFilter;
|
||||
pub use self::words::WordsFilter;
|
||||
|
||||
@@ -26,3 +29,5 @@ mod container;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod init;
|
||||
mod utils;
|
||||
mod empty;
|
||||
|
||||
@@ -3,15 +3,25 @@ use ::regex::Regex;
|
||||
|
||||
/// Simple implementor of FeroxFilter; used to filter out responses based on a given regular
|
||||
/// expression; specified using -X|--filter-regex
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct RegexFilter {
|
||||
/// Regular expression to be applied to the response body for filtering, compiled
|
||||
#[serde(with = "serde_regex")]
|
||||
pub compiled: Regex,
|
||||
|
||||
/// Regular expression as passed in on the command line, not compiled
|
||||
pub raw_string: String,
|
||||
}
|
||||
|
||||
impl Default for RegexFilter {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
compiled: Regex::new("").unwrap(),
|
||||
raw_string: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// implementation of FeroxFilter for RegexFilter
|
||||
impl FeroxFilter for RegexFilter {
|
||||
/// Check `expression` against the response body, if the expression matches, the response
|
||||
|
||||
@@ -3,13 +3,16 @@ use fuzzyhash::FuzzyHash;
|
||||
|
||||
/// Simple implementor of FeroxFilter; used to filter out responses based on the similarity of a
|
||||
/// Response body with a known response; specified using --filter-similar-to
|
||||
#[derive(Default, Debug, PartialEq)]
|
||||
#[derive(Default, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SimilarityFilter {
|
||||
/// Response's body to be used for comparison for similarity
|
||||
pub text: String,
|
||||
/// Hash of Response's body to be used during similarity comparison
|
||||
pub hash: String,
|
||||
|
||||
/// Percentage of similarity at which a page is determined to be a near-duplicate of another
|
||||
pub threshold: u32,
|
||||
|
||||
/// Url originally requested for the similarity filter
|
||||
pub original_url: String,
|
||||
}
|
||||
|
||||
/// implementation of FeroxFilter for SimilarityFilter
|
||||
@@ -17,9 +20,9 @@ impl FeroxFilter for SimilarityFilter {
|
||||
/// Check `FeroxResponse::text` against what was requested from the site passed in via
|
||||
/// --filter-similar-to
|
||||
fn should_filter_response(&self, response: &FeroxResponse) -> bool {
|
||||
let other = FuzzyHash::new(&response.text());
|
||||
let other = FuzzyHash::new(response.text());
|
||||
|
||||
if let Ok(result) = FuzzyHash::compare(&self.text, &other.to_string()) {
|
||||
if let Ok(result) = FuzzyHash::compare(&self.hash, other.to_string()) {
|
||||
return result >= self.threshold;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::*;
|
||||
|
||||
/// Simple implementor of FeroxFilter; used to filter out responses based on the length of a
|
||||
/// Response body; specified using -S|--filter-size
|
||||
#[derive(Default, Debug, PartialEq)]
|
||||
#[derive(Default, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SizeFilter {
|
||||
/// Overall length of a Response's body that should be filtered
|
||||
pub content_length: u64,
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::*;
|
||||
|
||||
/// Simple implementor of FeroxFilter; used to filter out status codes specified using
|
||||
/// -C|--filter-status
|
||||
#[derive(Default, Debug, PartialEq)]
|
||||
#[derive(Default, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct StatusCodeFilter {
|
||||
/// Status code that should not be displayed to the user
|
||||
pub filter_code: u16,
|
||||
|
||||
@@ -122,6 +122,7 @@ fn wildcard_should_filter_when_static_wildcard_found() {
|
||||
size: 83,
|
||||
dynamic: 0,
|
||||
dont_filter: false,
|
||||
method: "GET".to_owned(),
|
||||
};
|
||||
|
||||
assert!(filter.should_filter_response(&resp));
|
||||
@@ -152,6 +153,7 @@ fn wildcard_should_filter_when_dynamic_wildcard_found() {
|
||||
size: 0,
|
||||
dynamic: 59, // content-length - 5 (len('stuff'))
|
||||
dont_filter: false,
|
||||
method: "GET".to_owned(),
|
||||
};
|
||||
|
||||
println!("resp: {:?}: filter: {:?}", resp, filter);
|
||||
@@ -184,22 +186,23 @@ fn similarity_filter_is_accurate() {
|
||||
resp.set_text("sitting");
|
||||
|
||||
let mut filter = SimilarityFilter {
|
||||
text: FuzzyHash::new("kitten").to_string(),
|
||||
hash: FuzzyHash::new("kitten").to_string(),
|
||||
threshold: 95,
|
||||
original_url: "".to_string(),
|
||||
};
|
||||
|
||||
// kitten/sitting is 57% similar, so a threshold of 95 should not be filtered
|
||||
assert!(!filter.should_filter_response(&resp));
|
||||
|
||||
resp.set_text("");
|
||||
filter.text = String::new();
|
||||
filter.hash = String::new();
|
||||
filter.threshold = 100;
|
||||
|
||||
// two empty strings are the same, however ssdeep doesn't accept empty strings, expect false
|
||||
assert!(!filter.should_filter_response(&resp));
|
||||
|
||||
resp.set_text("some data to hash for the purposes of running a test");
|
||||
filter.text = FuzzyHash::new("some data to hash for the purposes of running a te").to_string();
|
||||
filter.hash = FuzzyHash::new("some data to hash for the purposes of running a te").to_string();
|
||||
filter.threshold = 17;
|
||||
|
||||
assert!(filter.should_filter_response(&resp));
|
||||
@@ -209,20 +212,58 @@ fn similarity_filter_is_accurate() {
|
||||
/// just a simple test to increase code coverage by hitting as_any and the inner value
|
||||
fn similarity_filter_as_any() {
|
||||
let filter = SimilarityFilter {
|
||||
text: String::from("stuff"),
|
||||
hash: String::from("stuff"),
|
||||
threshold: 95,
|
||||
original_url: "".to_string(),
|
||||
};
|
||||
|
||||
let filter2 = SimilarityFilter {
|
||||
text: String::from("stuff"),
|
||||
hash: String::from("stuff"),
|
||||
threshold: 95,
|
||||
original_url: "".to_string(),
|
||||
};
|
||||
|
||||
assert!(filter.box_eq(filter2.as_any()));
|
||||
|
||||
assert_eq!(filter.text, "stuff");
|
||||
assert_eq!(filter.hash, "stuff");
|
||||
assert_eq!(
|
||||
*filter.as_any().downcast_ref::<SimilarityFilter>().unwrap(),
|
||||
filter
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// test correctness of FeroxFilters::remove
|
||||
fn remove_function_works_as_expected() {
|
||||
let data = FeroxFilters::default();
|
||||
assert!(data.filters.read().unwrap().is_empty());
|
||||
|
||||
(0..8).for_each(|i| {
|
||||
data.push(Box::new(WordsFilter { word_count: i })).unwrap();
|
||||
});
|
||||
|
||||
// remove removes index-1 from the vec, zero is skipped, and out-of-bounds indices are skipped
|
||||
data.remove(&mut [0]);
|
||||
assert_eq!(data.filters.read().unwrap().len(), 8);
|
||||
|
||||
data.remove(&mut [10000]);
|
||||
assert_eq!(data.filters.read().unwrap().len(), 8);
|
||||
|
||||
// removing 0, 2, 4
|
||||
data.remove(&mut [1, 3, 5]);
|
||||
|
||||
assert_eq!(data.filters.read().unwrap().len(), 5);
|
||||
|
||||
let expected = vec![
|
||||
WordsFilter { word_count: 1 },
|
||||
WordsFilter { word_count: 3 },
|
||||
WordsFilter { word_count: 5 },
|
||||
WordsFilter { word_count: 6 },
|
||||
WordsFilter { word_count: 7 },
|
||||
];
|
||||
|
||||
for filter in data.filters.read().unwrap().iter() {
|
||||
let downcast = filter.as_any().downcast_ref::<WordsFilter>().unwrap();
|
||||
assert!(expected.contains(downcast));
|
||||
}
|
||||
}
|
||||
|
||||
204
src/filters/utils.rs
Normal file
204
src/filters/utils.rs
Normal file
@@ -0,0 +1,204 @@
|
||||
use super::FeroxFilter;
|
||||
use super::SimilarityFilter;
|
||||
use crate::event_handlers::Handles;
|
||||
use crate::response::FeroxResponse;
|
||||
use crate::utils::logged_request;
|
||||
use crate::{DEFAULT_METHOD, SIMILARITY_THRESHOLD};
|
||||
use anyhow::Result;
|
||||
use fuzzyhash::FuzzyHash;
|
||||
use regex::Regex;
|
||||
use reqwest::Url;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// wrapper around logic necessary to create a SimilarityFilter
|
||||
///
|
||||
/// - parses given url
|
||||
/// - makes request to the parsed url
|
||||
/// - gathers extensions from the url, if configured to do so
|
||||
/// - computes hash of response body
|
||||
/// - creates filter with hash
|
||||
pub(crate) async fn create_similarity_filter(
|
||||
similarity_filter: &str,
|
||||
handles: Arc<Handles>,
|
||||
) -> Result<SimilarityFilter> {
|
||||
// url as-is based on input, ignores user-specified url manipulation options (add-slash etc)
|
||||
let url = Url::parse(similarity_filter)?;
|
||||
|
||||
// attempt to request the given url
|
||||
let resp = logged_request(&url, DEFAULT_METHOD, None, handles.clone()).await?;
|
||||
|
||||
// if successful, create a filter based on the response's body
|
||||
let mut fr = FeroxResponse::from(
|
||||
resp,
|
||||
similarity_filter,
|
||||
DEFAULT_METHOD,
|
||||
handles.config.output_level,
|
||||
)
|
||||
.await;
|
||||
|
||||
if handles.config.collect_extensions {
|
||||
fr.parse_extension(handles.clone())?;
|
||||
}
|
||||
|
||||
// hash the response body and store the resulting hash in the filter object
|
||||
let hash = FuzzyHash::new(fr.text()).to_string();
|
||||
|
||||
Ok(SimilarityFilter {
|
||||
hash,
|
||||
threshold: SIMILARITY_THRESHOLD,
|
||||
original_url: similarity_filter.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// used in conjunction with the Scan Management Menu
|
||||
///
|
||||
/// when a user uses the n[ew-filter] command in the menu, the two params are passed here for
|
||||
/// processing.
|
||||
///
|
||||
/// an example command may be `new-filter lines 40`. `lines` and `40` are passed here as &str's
|
||||
///
|
||||
/// once here, the type and value are used to create an appropriate FeroxFilter. If anything
|
||||
/// goes wrong during creation, None is returned.
|
||||
pub(crate) fn filter_lookup(filter_type: &str, filter_value: &str) -> Option<Box<dyn FeroxFilter>> {
|
||||
match filter_type {
|
||||
"status" => {
|
||||
if let Ok(parsed) = filter_value.parse() {
|
||||
return Some(Box::new(super::StatusCodeFilter {
|
||||
filter_code: parsed,
|
||||
}));
|
||||
}
|
||||
}
|
||||
"lines" => {
|
||||
if let Ok(parsed) = filter_value.parse() {
|
||||
return Some(Box::new(super::LinesFilter { line_count: parsed }));
|
||||
}
|
||||
}
|
||||
"size" => {
|
||||
if let Ok(parsed) = filter_value.parse() {
|
||||
return Some(Box::new(super::SizeFilter {
|
||||
content_length: parsed,
|
||||
}));
|
||||
}
|
||||
}
|
||||
"words" => {
|
||||
if let Ok(parsed) = filter_value.parse() {
|
||||
return Some(Box::new(super::WordsFilter { word_count: parsed }));
|
||||
}
|
||||
}
|
||||
"regex" => {
|
||||
if let Ok(parsed) = Regex::new(filter_value) {
|
||||
return Some(Box::new(super::RegexFilter {
|
||||
compiled: parsed,
|
||||
raw_string: filter_value.to_string(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
"similarity" => {
|
||||
return Some(Box::new(SimilarityFilter {
|
||||
hash: String::new(),
|
||||
threshold: SIMILARITY_THRESHOLD,
|
||||
original_url: filter_value.to_string(),
|
||||
}));
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::config::Configuration;
|
||||
use crate::filters::{LinesFilter, RegexFilter, SizeFilter, StatusCodeFilter, WordsFilter};
|
||||
use crate::scan_manager::FeroxScans;
|
||||
use httpmock::Method::GET;
|
||||
use httpmock::MockServer;
|
||||
|
||||
#[test]
|
||||
/// filter_lookup returns correct filters
|
||||
fn filter_lookup_returns_correct_filters() {
|
||||
let filter = filter_lookup("status", "200").unwrap();
|
||||
assert_eq!(
|
||||
filter.as_any().downcast_ref::<StatusCodeFilter>().unwrap(),
|
||||
&StatusCodeFilter { filter_code: 200 }
|
||||
);
|
||||
|
||||
let filter = filter_lookup("lines", "10").unwrap();
|
||||
assert_eq!(
|
||||
filter.as_any().downcast_ref::<LinesFilter>().unwrap(),
|
||||
&LinesFilter { line_count: 10 }
|
||||
);
|
||||
|
||||
let filter = filter_lookup("size", "20").unwrap();
|
||||
assert_eq!(
|
||||
filter.as_any().downcast_ref::<SizeFilter>().unwrap(),
|
||||
&SizeFilter { content_length: 20 }
|
||||
);
|
||||
|
||||
let filter = filter_lookup("words", "30").unwrap();
|
||||
assert_eq!(
|
||||
filter.as_any().downcast_ref::<WordsFilter>().unwrap(),
|
||||
&WordsFilter { word_count: 30 }
|
||||
);
|
||||
|
||||
let filter = filter_lookup("regex", "stuff.*").unwrap();
|
||||
let compiled = Regex::new("stuff.*").unwrap();
|
||||
let raw_string = String::from("stuff.*");
|
||||
assert_eq!(
|
||||
filter.as_any().downcast_ref::<RegexFilter>().unwrap(),
|
||||
&RegexFilter {
|
||||
compiled,
|
||||
raw_string
|
||||
}
|
||||
);
|
||||
|
||||
let filter = filter_lookup("similarity", "http://localhost").unwrap();
|
||||
assert_eq!(
|
||||
filter.as_any().downcast_ref::<SimilarityFilter>().unwrap(),
|
||||
&SimilarityFilter {
|
||||
hash: String::new(),
|
||||
threshold: SIMILARITY_THRESHOLD,
|
||||
original_url: "http://localhost".to_string()
|
||||
}
|
||||
);
|
||||
|
||||
assert!(filter_lookup("non-existent", "").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
|
||||
/// ensure create_similarity_filter correctness of return value and side-effects
|
||||
async fn create_similarity_filter_is_correct() {
|
||||
let srv = MockServer::start();
|
||||
|
||||
let mock = srv.mock(|when, then| {
|
||||
when.method(GET).path("/");
|
||||
then.status(200).body("this is a test");
|
||||
});
|
||||
|
||||
let scans = FeroxScans::default();
|
||||
let config = Configuration {
|
||||
collect_extensions: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let (test_handles, _) = Handles::for_testing(Some(Arc::new(scans)), Some(Arc::new(config)));
|
||||
|
||||
let handles = Arc::new(test_handles);
|
||||
|
||||
let filter = create_similarity_filter(&srv.url("/"), handles.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(mock.hits(), 1);
|
||||
|
||||
assert_eq!(
|
||||
filter,
|
||||
SimilarityFilter {
|
||||
hash: "3:YKEpn:Yfp".to_string(),
|
||||
threshold: SIMILARITY_THRESHOLD,
|
||||
original_url: srv.url("/")
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::*;
|
||||
use crate::url::FeroxUrl;
|
||||
use crate::{url::FeroxUrl, DEFAULT_METHOD};
|
||||
|
||||
/// Data holder for two pieces of data needed when auto-filtering out wildcard responses
|
||||
///
|
||||
@@ -9,7 +9,7 @@ use crate::url::FeroxUrl;
|
||||
///
|
||||
/// `size` is size of the response that should be included with filters passed via runtime
|
||||
/// configuration and any static wildcard lengths.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct WildcardFilter {
|
||||
/// size of the response that will later be combined with the length of the path of the url
|
||||
/// requested
|
||||
@@ -18,6 +18,9 @@ pub struct WildcardFilter {
|
||||
/// size of the response that should be included with filters passed via runtime configuration
|
||||
pub size: u64,
|
||||
|
||||
/// method used in request that should be included with filters passed via runtime configuration
|
||||
pub method: String,
|
||||
|
||||
/// whether or not the user passed -D on the command line
|
||||
pub(super) dont_filter: bool,
|
||||
}
|
||||
@@ -40,6 +43,7 @@ impl Default for WildcardFilter {
|
||||
Self {
|
||||
dont_filter: false,
|
||||
size: u64::MAX,
|
||||
method: DEFAULT_METHOD.to_owned(),
|
||||
dynamic: u64::MAX,
|
||||
}
|
||||
}
|
||||
@@ -60,7 +64,10 @@ impl FeroxFilter for WildcardFilter {
|
||||
return false;
|
||||
}
|
||||
|
||||
if self.size != u64::MAX && self.size == response.content_length() {
|
||||
if self.size != u64::MAX
|
||||
&& self.size == response.content_length()
|
||||
&& self.method == response.method().as_str()
|
||||
{
|
||||
// static wildcard size found during testing
|
||||
// size isn't default, size equals response length, and auto-filter is on
|
||||
log::debug!("static wildcard: filtered out {}", response.url());
|
||||
@@ -68,7 +75,10 @@ impl FeroxFilter for WildcardFilter {
|
||||
return true;
|
||||
}
|
||||
|
||||
if self.size == u64::MAX && response.content_length() == 0 {
|
||||
if self.size == u64::MAX
|
||||
&& response.content_length() == 0
|
||||
&& self.method == response.method().as_str()
|
||||
{
|
||||
// static wildcard size found during testing
|
||||
// but response length was zero; pointed out by @Tib3rius
|
||||
log::debug!("static wildcard: filtered out {}", response.url());
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::*;
|
||||
|
||||
/// Simple implementor of FeroxFilter; used to filter out responses based on the number of words
|
||||
/// in a Response body; specified using -W|--filter-words
|
||||
#[derive(Default, Debug, PartialEq)]
|
||||
#[derive(Default, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct WordsFilter {
|
||||
/// Number of words in a Response's body that should be filtered
|
||||
pub word_count: usize,
|
||||
|
||||
@@ -2,8 +2,10 @@ use std::sync::Arc;
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
use console::style;
|
||||
use scraper::{Html, Selector};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::message::FeroxMessage;
|
||||
use crate::{
|
||||
config::OutputLevel,
|
||||
event_handlers::{Command, Handles},
|
||||
@@ -13,6 +15,7 @@ use crate::{
|
||||
skip_fail,
|
||||
url::FeroxUrl,
|
||||
utils::{ferox_print, fmt_err, logged_request, status_colorizer},
|
||||
DEFAULT_METHOD,
|
||||
};
|
||||
|
||||
/// length of a standard UUID, used when determining wildcard responses
|
||||
@@ -20,10 +23,11 @@ const UUID_LENGTH: u64 = 32;
|
||||
|
||||
/// wrapper around ugly string formatting
|
||||
macro_rules! format_template {
|
||||
($template:expr, $length:expr) => {
|
||||
($template:expr, $method:expr, $length:expr) => {
|
||||
format!(
|
||||
$template,
|
||||
status_colorizer("WLD"),
|
||||
$method,
|
||||
"-",
|
||||
"-",
|
||||
"-",
|
||||
@@ -34,6 +38,36 @@ macro_rules! format_template {
|
||||
};
|
||||
}
|
||||
|
||||
/// enum representing the different servers that `parse_html` can detect when directory listing is
|
||||
/// enabled
|
||||
#[derive(Copy, Debug, Clone)]
|
||||
pub enum DirListingType {
|
||||
/// apache server, detected by `Index of /`
|
||||
Apache,
|
||||
|
||||
/// tomcat/python server, detected by `Directory Listing for /`
|
||||
TomCatOrPython,
|
||||
|
||||
/// ASP.NET server, detected by `Directory Listing -- /`
|
||||
AspDotNet,
|
||||
|
||||
// /// IIS/Azure server, detected by `HOST_NAME - /` (not currently used)
|
||||
// IIS_AZURE,
|
||||
/// variant that represents the absence of directory listing
|
||||
None,
|
||||
}
|
||||
|
||||
/// Wrapper around the results of running a directory listing detection against a target web page
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DirListingResult {
|
||||
/// type of server where directory listing was detected
|
||||
/// i.e. https://portswigger.net/kb/issues/00600100_directory-listing
|
||||
pub dir_list_type: Option<DirListingType>,
|
||||
|
||||
/// the `FeroxResponse` generated during detection
|
||||
pub response: FeroxResponse,
|
||||
}
|
||||
|
||||
/// container for heuristics related info
|
||||
pub struct HeuristicTests {
|
||||
/// Handles object for event handler interaction
|
||||
@@ -57,7 +91,7 @@ impl HeuristicTests {
|
||||
let mut ids = vec![];
|
||||
|
||||
for _ in 0..length {
|
||||
ids.push(Uuid::new_v4().to_simple().to_string());
|
||||
ids.push(Uuid::new_v4().as_simple().to_string());
|
||||
}
|
||||
|
||||
let unique_id = ids.join("");
|
||||
@@ -89,55 +123,68 @@ impl HeuristicTests {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let data = match self.handles.config.data.is_empty() {
|
||||
true => None,
|
||||
false => Some(self.handles.config.data.as_slice()),
|
||||
};
|
||||
|
||||
let ferox_url = FeroxUrl::from_string(target_url, self.handles.clone());
|
||||
|
||||
let ferox_response = self.make_wildcard_request(&ferox_url, 1).await?;
|
||||
for method in self.handles.config.methods.iter() {
|
||||
let ferox_response = self
|
||||
.make_wildcard_request(&ferox_url, method.as_str(), data, 1)
|
||||
.await?;
|
||||
|
||||
// found a wildcard response
|
||||
let mut wildcard = WildcardFilter::new(self.handles.config.dont_filter);
|
||||
// found a wildcard response
|
||||
let mut wildcard = WildcardFilter::new(self.handles.config.dont_filter);
|
||||
|
||||
let wc_length = ferox_response.content_length();
|
||||
let wc_length = ferox_response.content_length();
|
||||
|
||||
if wc_length == 0 {
|
||||
log::trace!("exit: wildcard_test -> 1");
|
||||
self.send_filter(wildcard)?;
|
||||
return Ok(1);
|
||||
}
|
||||
|
||||
// content length of wildcard is non-zero, perform additional tests:
|
||||
// make a second request, with a known-sized (64) longer request
|
||||
let resp_two = self
|
||||
.make_wildcard_request(&ferox_url, method.as_str(), data, 3)
|
||||
.await?;
|
||||
|
||||
let wc2_length = resp_two.content_length();
|
||||
|
||||
wildcard.method = resp_two.method().as_str().to_owned();
|
||||
|
||||
if wc2_length == wc_length + (UUID_LENGTH * 2) {
|
||||
// second length is what we'd expect to see if the requested url is
|
||||
// reflected in the response along with some static content; aka custom 404
|
||||
let url_len = ferox_url.path_length()?;
|
||||
|
||||
wildcard.dynamic = wc_length - url_len;
|
||||
|
||||
if matches!(
|
||||
self.handles.config.output_level,
|
||||
OutputLevel::Default | OutputLevel::Quiet
|
||||
) {
|
||||
let msg = format_template!("{} {:>8} {:>9} {:>9} {:>9} Wildcard response is dynamic; {} ({} + url length) responses; toggle this behavior by using {}\n", method, wildcard.dynamic);
|
||||
ferox_print(&msg, &PROGRESS_PRINTER);
|
||||
}
|
||||
} else if wc_length == wc2_length {
|
||||
wildcard.size = wc_length;
|
||||
|
||||
if matches!(
|
||||
self.handles.config.output_level,
|
||||
OutputLevel::Default | OutputLevel::Quiet
|
||||
) {
|
||||
let msg = format_template!("{} {:>8} {:>9} {:>9} {:>9} Wildcard response is static; {} {} responses; toggle this behavior by using {}\n", method, wildcard.size);
|
||||
ferox_print(&msg, &PROGRESS_PRINTER);
|
||||
}
|
||||
}
|
||||
|
||||
if wc_length == 0 {
|
||||
log::trace!("exit: wildcard_test -> 1");
|
||||
self.send_filter(wildcard)?;
|
||||
return Ok(1);
|
||||
}
|
||||
|
||||
// content length of wildcard is non-zero, perform additional tests:
|
||||
// make a second request, with a known-sized (64) longer request
|
||||
let resp_two = self.make_wildcard_request(&ferox_url, 3).await?;
|
||||
|
||||
let wc2_length = resp_two.content_length();
|
||||
|
||||
if wc2_length == wc_length + (UUID_LENGTH * 2) {
|
||||
// second length is what we'd expect to see if the requested url is
|
||||
// reflected in the response along with some static content; aka custom 404
|
||||
let url_len = ferox_url.path_length()?;
|
||||
|
||||
wildcard.dynamic = wc_length - url_len;
|
||||
|
||||
if matches!(
|
||||
self.handles.config.output_level,
|
||||
OutputLevel::Default | OutputLevel::Quiet
|
||||
) {
|
||||
let msg = format_template!("{} {:>9} {:>9} {:>9} Wildcard response is dynamic; {} ({} + url length) responses; toggle this behavior by using {}\n", wildcard.dynamic);
|
||||
ferox_print(&msg, &PROGRESS_PRINTER);
|
||||
}
|
||||
} else if wc_length == wc2_length {
|
||||
wildcard.size = wc_length;
|
||||
|
||||
if matches!(
|
||||
self.handles.config.output_level,
|
||||
OutputLevel::Default | OutputLevel::Quiet
|
||||
) {
|
||||
let msg = format_template!("{} {:>9} {:>9} {:>9} Wildcard response is static; {} {} responses; toggle this behavior by using {}\n", wildcard.size);
|
||||
ferox_print(&msg, &PROGRESS_PRINTER);
|
||||
}
|
||||
}
|
||||
|
||||
self.send_filter(wildcard)?;
|
||||
|
||||
log::trace!("exit: wildcard_test");
|
||||
Ok(2)
|
||||
}
|
||||
@@ -151,6 +198,8 @@ impl HeuristicTests {
|
||||
async fn make_wildcard_request(
|
||||
&self,
|
||||
target: &FeroxUrl,
|
||||
method: &str,
|
||||
data: Option<&[u8]>,
|
||||
length: usize,
|
||||
) -> Result<FeroxResponse> {
|
||||
log::trace!("enter: make_wildcard_request({}, {})", target, length);
|
||||
@@ -166,7 +215,13 @@ impl HeuristicTests {
|
||||
|
||||
let nonexistent_url = target.format(&unique_str, slash)?;
|
||||
|
||||
let response = logged_request(&nonexistent_url.to_owned(), self.handles.clone()).await?;
|
||||
let response = logged_request(
|
||||
&nonexistent_url.to_owned(),
|
||||
method,
|
||||
data,
|
||||
self.handles.clone(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
if self
|
||||
.handles
|
||||
@@ -175,10 +230,11 @@ impl HeuristicTests {
|
||||
.contains(&response.status().as_u16())
|
||||
{
|
||||
// found a wildcard response
|
||||
|
||||
let mut ferox_response = FeroxResponse::from(
|
||||
response,
|
||||
&target.target,
|
||||
true,
|
||||
method,
|
||||
self.handles.config.output_level,
|
||||
)
|
||||
.await;
|
||||
@@ -223,7 +279,7 @@ impl HeuristicTests {
|
||||
let url = FeroxUrl::from_string(target_url, self.handles.clone());
|
||||
let request = skip_fail!(url.format("", None));
|
||||
|
||||
let result = logged_request(&request, self.handles.clone()).await;
|
||||
let result = logged_request(&request, DEFAULT_METHOD, None, self.handles.clone()).await;
|
||||
|
||||
match result {
|
||||
Ok(_) => {
|
||||
@@ -258,6 +314,111 @@ impl HeuristicTests {
|
||||
log::trace!("exit: connectivity_test -> {:?}", good_urls);
|
||||
Ok(good_urls)
|
||||
}
|
||||
|
||||
/// heuristic designed to detect when a server has directory listing enabled
|
||||
pub async fn directory_listing(&self, target_url: &str) -> Result<Option<DirListingResult>> {
|
||||
log::trace!("enter: directory_listing({})", target_url);
|
||||
|
||||
let tgt = if !target_url.ends_with('/') {
|
||||
// if left unchanged, this function would be called against redirects that point to
|
||||
// valid directories for most, if not all, directories beyond the initial urls.
|
||||
// so, instead of `directory_listing("http://localhost") -> None` we get
|
||||
// `directory_listing("http://localhost/") -> Some(DirListingResult)` if there is
|
||||
// directory listing beyond the redirect
|
||||
format!("{}/", target_url)
|
||||
} else {
|
||||
target_url.to_string()
|
||||
};
|
||||
|
||||
let url = FeroxUrl::from_string(&tgt, self.handles.clone());
|
||||
let request = url.format("", None)?;
|
||||
|
||||
let result = logged_request(&request, DEFAULT_METHOD, None, self.handles.clone()).await?;
|
||||
|
||||
let ferox_response = FeroxResponse::from(
|
||||
result,
|
||||
&url.target,
|
||||
DEFAULT_METHOD,
|
||||
self.handles.config.output_level,
|
||||
)
|
||||
.await;
|
||||
|
||||
let body = ferox_response.text();
|
||||
let html = Html::parse_document(body);
|
||||
|
||||
let dirlist_type = self.detect_directory_listing(&html);
|
||||
|
||||
if dirlist_type.is_some() {
|
||||
// folks that run things and step away/rely on logs need to be notified of directory
|
||||
// listing, since they won't see the message on the bar; bastardizing FeroxMessage
|
||||
// for ease of implementation. This could use a bit of polish at some point.
|
||||
let msg = format!(
|
||||
"detected directory listing: {} ({:?})",
|
||||
target_url,
|
||||
dirlist_type.unwrap()
|
||||
);
|
||||
let ferox_msg = FeroxMessage {
|
||||
kind: "log".to_string(),
|
||||
message: msg.clone(),
|
||||
level: "MSG".to_string(),
|
||||
time_offset: 0.0,
|
||||
module: "feroxbuster::heuristics".to_string(),
|
||||
};
|
||||
self.handles
|
||||
.output
|
||||
.tx_file
|
||||
.send(Command::WriteToDisk(Box::new(ferox_msg)))
|
||||
.unwrap_or_default();
|
||||
|
||||
log::info!("{}", msg);
|
||||
|
||||
let result = DirListingResult {
|
||||
dir_list_type: dirlist_type,
|
||||
response: ferox_response,
|
||||
};
|
||||
|
||||
log::trace!("exit: directory_listing -> {:?}", result);
|
||||
return Ok(Some(result));
|
||||
}
|
||||
|
||||
log::trace!("exit: directory_listing -> None");
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Directory listing heuristic detection, uses <title> tag to make its determination. When
|
||||
/// the inner html of <title> matches one of the following, a `DirListingType` is returned.
|
||||
/// - apache: `Index of /`
|
||||
/// - tomcat/python: `Directory Listing for /`
|
||||
/// - ASP.NET: `Directory Listing -- /`
|
||||
/// - <host> - /: iis, azure, skipping due to loose heuristic
|
||||
fn detect_directory_listing(&self, html: &Html) -> Option<DirListingType> {
|
||||
log::trace!("enter: detect_directory_listing(html body...)");
|
||||
|
||||
let title_selector = Selector::parse("title").expect("couldn't parse title selector");
|
||||
|
||||
for t in html.select(&title_selector) {
|
||||
let title = t.inner_html().to_lowercase();
|
||||
|
||||
let dirlist_type = if title.contains("directory listing for /") {
|
||||
Some(DirListingType::TomCatOrPython)
|
||||
} else if title.contains("index of /") {
|
||||
Some(DirListingType::Apache)
|
||||
} else if title.contains("directory listing -- /") {
|
||||
Some(DirListingType::AspDotNet)
|
||||
} else {
|
||||
// IIS_AZURE purposely skipped for now
|
||||
None
|
||||
};
|
||||
|
||||
if dirlist_type.is_some() {
|
||||
log::trace!("exit: detect_directory_listing -> {:?}", dirlist_type);
|
||||
return dirlist_type;
|
||||
}
|
||||
}
|
||||
|
||||
log::trace!("exit: detect_directory_listing -> None");
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -273,4 +434,51 @@ mod tests {
|
||||
assert_eq!(tester.unique_string(i).len(), i * 32);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// `detect_directory_listing` correctly identifies tomcat/python instances
|
||||
fn detect_directory_listing_finds_tomcat_python() {
|
||||
let html = "<title>directory listing for /</title>";
|
||||
let parsed = Html::parse_document(html);
|
||||
let handles = Handles::for_testing(None, None);
|
||||
let heuristics = HeuristicTests::new(Arc::new(handles.0));
|
||||
let dirlist_type = heuristics.detect_directory_listing(&parsed);
|
||||
assert!(matches!(
|
||||
dirlist_type.unwrap(),
|
||||
DirListingType::TomCatOrPython
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// `detect_directory_listing` correctly identifies apache instances
|
||||
fn detect_directory_listing_finds_apache() {
|
||||
let html = "<title>index of /</title>";
|
||||
let parsed = Html::parse_document(html);
|
||||
let handles = Handles::for_testing(None, None);
|
||||
let heuristics = HeuristicTests::new(Arc::new(handles.0));
|
||||
let dirlist_type = heuristics.detect_directory_listing(&parsed);
|
||||
assert!(matches!(dirlist_type.unwrap(), DirListingType::Apache));
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// `detect_directory_listing` correctly identifies ASP.NET instances
|
||||
fn detect_directory_listing_finds_asp_dot_net() {
|
||||
let html = "<title>directory listing -- /</title>";
|
||||
let parsed = Html::parse_document(html);
|
||||
let handles = Handles::for_testing(None, None);
|
||||
let heuristics = HeuristicTests::new(Arc::new(handles.0));
|
||||
let dirlist_type = heuristics.detect_directory_listing(&parsed);
|
||||
assert!(matches!(dirlist_type.unwrap(), DirListingType::AspDotNet));
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// `detect_directory_listing` returns None when heuristic doesn't match
|
||||
fn detect_directory_listing_returns_none_as_default() {
|
||||
let html = "<title>derp listing -- /</title>";
|
||||
let parsed = Html::parse_document(html);
|
||||
let handles = Handles::for_testing(None, None);
|
||||
let heuristics = HeuristicTests::new(Arc::new(handles.0));
|
||||
let dirlist_type = heuristics.detect_directory_listing(&parsed);
|
||||
assert!(dirlist_type.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
28
src/lib.rs
28
src/lib.rs
@@ -1,5 +1,8 @@
|
||||
#![deny(clippy::all)]
|
||||
#![allow(clippy::mutex_atomic)]
|
||||
use anyhow::Result;
|
||||
use reqwest::StatusCode;
|
||||
use std::collections::HashSet;
|
||||
use tokio::{
|
||||
sync::mpsc::{UnboundedReceiver, UnboundedSender},
|
||||
task::JoinHandle,
|
||||
@@ -26,6 +29,7 @@ mod macros;
|
||||
mod url;
|
||||
mod response;
|
||||
mod message;
|
||||
mod nlp;
|
||||
|
||||
/// Alias for tokio::sync::mpsc::UnboundedSender<Command>
|
||||
pub(crate) type CommandSender = UnboundedSender<Command>;
|
||||
@@ -39,6 +43,9 @@ pub(crate) type Joiner = JoinHandle<Result<()>>;
|
||||
/// Generic mpsc::unbounded_channel type to tidy up some code
|
||||
pub(crate) type FeroxChannel<T> = (UnboundedSender<T>, UnboundedReceiver<T>);
|
||||
|
||||
/// Wrapper around the results of performing any kind of extraction against a target web page
|
||||
pub(crate) type ExtractionResult = HashSet<String>;
|
||||
|
||||
/// Version pulled from Cargo.toml at compile time
|
||||
pub(crate) const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
@@ -48,13 +55,29 @@ pub const DEFAULT_OPEN_FILE_LIMIT: u64 = 8192;
|
||||
/// Default value used to determine near-duplicate web pages (equivalent to 95%)
|
||||
pub const SIMILARITY_THRESHOLD: u32 = 95;
|
||||
|
||||
/// Default set of extensions to Ignore when auto-collecting extensions during scans
|
||||
pub(crate) const DEFAULT_IGNORED_EXTENSIONS: [&str; 38] = [
|
||||
"tif", "tiff", "ico", "cur", "bmp", "webp", "svg", "png", "jpg", "jpeg", "jfif", "gif", "avif",
|
||||
"apng", "pjpeg", "pjp", "mov", "wav", "mpg", "mpeg", "mp3", "mp4", "m4a", "m4p", "m4v", "ogg",
|
||||
"webm", "ogv", "oga", "flac", "aac", "3gp", "css", "zip", "xls", "xml", "gz", "tgz",
|
||||
];
|
||||
|
||||
/// Default wordlist to use when `-w|--wordlist` isn't specified and not `wordlist` isn't set
|
||||
/// in a [ferox-config.toml](constant.DEFAULT_CONFIG_NAME.html) config file.
|
||||
///
|
||||
/// defaults to kali's default install location:
|
||||
/// defaults to kali's default install location on linux:
|
||||
/// - `/usr/share/seclists/Discovery/Web-Content/raft-medium-directories.txt`
|
||||
///
|
||||
/// and to the current directory on windows
|
||||
/// - `.\seclists\Discovery\Web-Content\raft-medium-directories.txt`
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
pub const DEFAULT_WORDLIST: &str =
|
||||
"/usr/share/seclists/Discovery/Web-Content/raft-medium-directories.txt";
|
||||
#[cfg(target_os = "windows")]
|
||||
pub const DEFAULT_WORDLIST: &str =
|
||||
".\\SecLists\\Discovery\\Web-Content\\raft-medium-directories.txt";
|
||||
pub const SECONDARY_WORDLIST: &str =
|
||||
"/usr/local/share/seclists/Discovery/Web-Content/raft-medium-directories.txt";
|
||||
|
||||
/// Number of milliseconds to wait between polls of `PAUSE_SCAN` when user pauses a scan
|
||||
pub(crate) const SLEEP_DURATION: u64 = 500;
|
||||
@@ -87,6 +110,9 @@ pub const DEFAULT_STATUS_CODES: [StatusCode; 10] = [
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
];
|
||||
|
||||
/// Default method for requests
|
||||
pub(crate) const DEFAULT_METHOD: &str = "GET";
|
||||
|
||||
/// Default filename for config file settings
|
||||
///
|
||||
/// Expected location is in the same directory as the feroxbuster binary.
|
||||
|
||||
@@ -65,7 +65,7 @@ pub fn initialize(config: Arc<Configuration>) -> Result<()> {
|
||||
kind: "log".to_string(),
|
||||
};
|
||||
|
||||
PROGRESS_PRINTER.println(&log_entry.as_str());
|
||||
PROGRESS_PRINTER.println(log_entry.as_str());
|
||||
|
||||
if let Some(buffered_file) = file.clone() {
|
||||
if let Ok(mut unlocked) = buffered_file.write() {
|
||||
|
||||
130
src/main.rs
130
src/main.rs
@@ -1,3 +1,4 @@
|
||||
use std::io::stdin;
|
||||
use std::{
|
||||
env::args,
|
||||
fs::{create_dir, remove_file, File},
|
||||
@@ -20,15 +21,18 @@ use feroxbuster::{
|
||||
banner::{Banner, UPDATE_URL},
|
||||
config::{Configuration, OutputLevel},
|
||||
event_handlers::{
|
||||
Command::{CreateBar, Exit, JoinTasks, LoadStats, ScanInitialUrls, UpdateWordlist},
|
||||
Command::{
|
||||
AddHandles, CreateBar, Exit, JoinTasks, LoadStats, ScanInitialUrls, UpdateWordlist,
|
||||
},
|
||||
FiltersHandler, Handles, ScanHandler, StatsHandler, Tasks, TermInputHandler,
|
||||
TermOutHandler, SCAN_COMPLETE,
|
||||
},
|
||||
filters, heuristics, logger,
|
||||
progress::{PROGRESS_BAR, PROGRESS_PRINTER},
|
||||
scan_manager::{self},
|
||||
scan_manager::{self, ScanType},
|
||||
scanner,
|
||||
utils::{fmt_err, slugify_filename},
|
||||
SECONDARY_WORDLIST,
|
||||
};
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
use feroxbuster::{utils::set_open_file_limit, DEFAULT_OPEN_FILE_LIMIT};
|
||||
@@ -40,27 +44,37 @@ lazy_static! {
|
||||
static ref PARALLEL_LIMITER: Semaphore = Semaphore::new(0);
|
||||
}
|
||||
|
||||
/// Create a HashSet of Strings from the given wordlist then stores it inside an Arc
|
||||
/// Create a Vec of Strings from the given wordlist then stores it inside an Arc
|
||||
fn get_unique_words_from_wordlist(path: &str) -> Result<Arc<Vec<String>>> {
|
||||
log::trace!("enter: get_unique_words_from_wordlist({})", path);
|
||||
let mut trimmed_word = false;
|
||||
|
||||
let file = File::open(&path).with_context(|| format!("Could not open {}", path))?;
|
||||
let file = File::open(path).with_context(|| format!("Could not open {}", path))?;
|
||||
|
||||
let reader = BufReader::new(file);
|
||||
|
||||
let mut words = Vec::new();
|
||||
// this empty string ensures that we call Requester::request with the base url, i.e.
|
||||
// `http://localhost/` instead of going straight into `http://localhost/WORD.EXT`.
|
||||
// for vanilla scans, it doesn't matter all that much, but it can be a significant difference
|
||||
// when `-e` is used, depending on the content at the base url.
|
||||
let mut words = vec![String::from("")];
|
||||
|
||||
for line in reader.lines() {
|
||||
let result = match line {
|
||||
Ok(read_line) => read_line,
|
||||
Err(_) => continue,
|
||||
};
|
||||
line.map(|result| {
|
||||
if !result.starts_with('#') && !result.is_empty() {
|
||||
if result.starts_with('/') {
|
||||
words.push(result.trim_start_matches('/').to_string());
|
||||
trimmed_word = true;
|
||||
} else {
|
||||
words.push(result);
|
||||
}
|
||||
}
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
|
||||
if result.starts_with('#') || result.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
words.push(result);
|
||||
if trimmed_word {
|
||||
log::warn!("Some words in the wordlist started with a leading forward-slash; those words were trimmed (i.e. /word -> word)");
|
||||
}
|
||||
|
||||
log::trace!(
|
||||
@@ -74,21 +88,12 @@ fn get_unique_words_from_wordlist(path: &str) -> Result<Arc<Vec<String>>> {
|
||||
/// Determine whether it's a single url scan or urls are coming from stdin, then scan as needed
|
||||
async fn scan(targets: Vec<String>, handles: Arc<Handles>) -> Result<()> {
|
||||
log::trace!("enter: scan({:?}, {:?})", targets, handles);
|
||||
// cloning an Arc is cheap (it's basically a pointer into the heap)
|
||||
// so that will allow for cheap/safe sharing of a single wordlist across multi-target scans
|
||||
// as well as additional directories found as part of recursion
|
||||
|
||||
let words = get_unique_words_from_wordlist(&handles.config.wordlist)?;
|
||||
|
||||
if words.len() == 0 {
|
||||
bail!("Did not find any words in {}", handles.config.wordlist);
|
||||
}
|
||||
|
||||
let scanned_urls = handles.ferox_scans()?;
|
||||
|
||||
handles.send_scan_command(UpdateWordlist(words.clone()))?;
|
||||
handles.send_scan_command(UpdateWordlist(handles.wordlist.clone()))?;
|
||||
|
||||
scanner::initialize(words.len(), handles.clone()).await?;
|
||||
scanner::initialize(handles.wordlist.len(), handles.clone()).await?;
|
||||
|
||||
// at this point, the stat thread's progress bar can be created; things that needed to happen
|
||||
// first:
|
||||
@@ -107,7 +112,7 @@ async fn scan(targets: Vec<String>, handles: Arc<Handles>) -> Result<()> {
|
||||
if handles.config.resumed {
|
||||
// display what has already been completed
|
||||
scanned_urls.print_known_responses();
|
||||
scanned_urls.print_completed_bars(words.len())?;
|
||||
scanned_urls.print_completed_bars(handles.wordlist.len())?;
|
||||
}
|
||||
|
||||
log::debug!("sending {:?} to be scanned as initial targets", targets);
|
||||
@@ -142,8 +147,8 @@ async fn get_targets(handles: Arc<Handles>) -> Result<Vec<String>> {
|
||||
for scan in scans.iter() {
|
||||
// ferox_scans gets deserialized scans added to it at program start if --resume-from
|
||||
// is used, so scans that aren't marked complete still need to be scanned
|
||||
if scan.is_complete() {
|
||||
// this one's already done, ignore it
|
||||
if scan.is_complete() || matches!(scan.scan_type, ScanType::File) {
|
||||
// this one's already done, or it's not a directory, ignore it
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -155,7 +160,7 @@ async fn get_targets(handles: Arc<Handles>) -> Result<Vec<String>> {
|
||||
}
|
||||
|
||||
// remove footgun that arises if a --dont-scan value matches on a base url
|
||||
for target in &targets {
|
||||
for target in targets.iter_mut() {
|
||||
for denier in &handles.config.regex_denylist {
|
||||
if denier.is_match(target) {
|
||||
bail!(
|
||||
@@ -174,6 +179,11 @@ async fn get_targets(handles: Arc<Handles>) -> Result<Vec<String>> {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if !target.starts_with("http") && !target.starts_with("https") {
|
||||
// --url hackerone.com
|
||||
*target = format!("https://{}", target);
|
||||
}
|
||||
}
|
||||
|
||||
log::trace!("exit: get_targets -> {:?}", targets);
|
||||
@@ -197,6 +207,30 @@ async fn wrapped_main(config: Arc<Configuration>) -> Result<()> {
|
||||
PROGRESS_BAR.join().unwrap();
|
||||
});
|
||||
|
||||
// cloning an Arc is cheap (it's basically a pointer into the heap)
|
||||
// so that will allow for cheap/safe sharing of a single wordlist across multi-target scans
|
||||
// as well as additional directories found as part of recursion
|
||||
let words = match get_unique_words_from_wordlist(&config.wordlist) {
|
||||
Ok(w) => w,
|
||||
Err(err) => {
|
||||
let secondary = Path::new(SECONDARY_WORDLIST);
|
||||
|
||||
if secondary.exists() {
|
||||
eprintln!("Found wordlist in secondary location");
|
||||
get_unique_words_from_wordlist(SECONDARY_WORDLIST)?
|
||||
} else {
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if words.len() <= 1 {
|
||||
// the check is now <= 1 due to the initial empty string added in 2.6.0
|
||||
// 1 -> empty wordlist
|
||||
// 0 -> error
|
||||
bail!("Did not find any words in {}", config.wordlist);
|
||||
}
|
||||
|
||||
// spawn all event handlers, expect back a JoinHandle and a *Handle to the specific event
|
||||
let (stats_task, stats_handle) = StatsHandler::initialize(config.clone());
|
||||
let (filters_task, filters_handle) = FiltersHandler::initialize();
|
||||
@@ -209,11 +243,13 @@ async fn wrapped_main(config: Arc<Configuration>) -> Result<()> {
|
||||
filters_handle,
|
||||
out_handle,
|
||||
config.clone(),
|
||||
words,
|
||||
));
|
||||
|
||||
let (scan_task, scan_handle) = ScanHandler::initialize(handles.clone());
|
||||
|
||||
handles.set_scan_handle(scan_handle); // must be done after Handles initialization
|
||||
handles.output.send(AddHandles(handles.clone()))?;
|
||||
|
||||
filters::initialize(handles.clone()).await?; // send user-supplied filters to the handler
|
||||
|
||||
@@ -241,7 +277,7 @@ async fn wrapped_main(config: Arc<Configuration>) -> Result<()> {
|
||||
let from_here = config.resume_from.clone();
|
||||
|
||||
// populate FeroxScans object with previously seen scans
|
||||
scanned_urls.add_serialized_scans(&from_here)?;
|
||||
scanned_urls.add_serialized_scans(&from_here, handles.clone())?;
|
||||
|
||||
// populate Stats object with previously known statistics
|
||||
handles.stats.send(LoadStats(from_here))?;
|
||||
@@ -302,7 +338,7 @@ async fn wrapped_main(config: Arc<Configuration>) -> Result<()> {
|
||||
|
||||
let new_folder = slugify_filename(&base_name.to_string_lossy(), "", "logs");
|
||||
|
||||
let final_path = output_path.with_file_name(&new_folder);
|
||||
let final_path = output_path.with_file_name(new_folder);
|
||||
|
||||
// create the directory or fail silently, assuming the reason for failure is that
|
||||
// the path exists already
|
||||
@@ -498,9 +534,39 @@ fn main() -> Result<()> {
|
||||
.enable_all()
|
||||
.build()
|
||||
{
|
||||
let future = wrapped_main(config);
|
||||
let future = wrapped_main(config.clone());
|
||||
if let Err(e) = runtime.block_on(future) {
|
||||
eprintln!("{}", e);
|
||||
|
||||
// the code below is to facilitate testing tests/test_banner entries. Since it's an
|
||||
// integration test, normal test detection (cfg!(test), etc...) won't work. So, in
|
||||
// the tests themselves, we pass
|
||||
// `--wordlist /definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676`
|
||||
// and look for that here to print the banner.
|
||||
//
|
||||
// this change became a necessity once we moved wordlist parsing out of `scan` and into
|
||||
// `wrapped_main`.
|
||||
if e.to_string()
|
||||
.contains("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
{
|
||||
// support the handful of tests that use `--stdin`
|
||||
let targets: Vec<_> = if config.stdin {
|
||||
stdin().lock().lines().map(|tgt| tgt.unwrap()).collect()
|
||||
} else {
|
||||
vec!["http://localhost".to_string()]
|
||||
};
|
||||
|
||||
// print the banner to stderr
|
||||
let std_stderr = stderr(); // std::io::stderr
|
||||
let banner = Banner::new(&targets, &config);
|
||||
if !config.quiet && !config.silent {
|
||||
banner.print_to(std_stderr, config).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
// if we've encountered an error before clean_up can be called (i.e. a wordlist error)
|
||||
// we need to at least spin-down the progress bar
|
||||
PROGRESS_PRINTER.finish();
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};
|
||||
use crate::traits::FeroxSerialize;
|
||||
use crate::utils::fmt_err;
|
||||
|
||||
#[derive(Serialize, Deserialize, Default)]
|
||||
#[derive(Serialize, Deserialize, Default, Debug)]
|
||||
/// Representation of a log entry, can be represented as a human readable string or JSON
|
||||
pub struct FeroxMessage {
|
||||
#[serde(rename = "type")]
|
||||
@@ -38,7 +38,7 @@ impl FeroxSerialize for FeroxMessage {
|
||||
"DEBUG" => ("DBG", Color::Yellow),
|
||||
"TRACE" => ("TRC", Color::Magenta),
|
||||
"WILDCARD" => ("WLD", Color::Cyan),
|
||||
_ => ("UNK", Color::White),
|
||||
_ => ("MSG", Color::White),
|
||||
};
|
||||
|
||||
format!(
|
||||
@@ -143,6 +143,6 @@ mod tests {
|
||||
assert!(console::strip_ansi_codes(&msg.as_str()).starts_with("WLD"));
|
||||
|
||||
msg.level = "UNKNOWN".to_string();
|
||||
assert!(console::strip_ansi_codes(&msg.as_str()).starts_with("UNK"));
|
||||
assert!(console::strip_ansi_codes(&msg.as_str()).starts_with("MSG"));
|
||||
}
|
||||
}
|
||||
|
||||
334
src/nlp/constants.rs
Normal file
334
src/nlp/constants.rs
Normal file
@@ -0,0 +1,334 @@
|
||||
use lazy_static::lazy_static;
|
||||
use regex::Regex;
|
||||
|
||||
lazy_static! {
|
||||
/// regular expression to match on words with numbers, underscores, and hyphens
|
||||
pub(super) static ref BOUNDED_WORD_REGEX: Regex = Regex::new(r"\b[a-zA-Z0-9_-]+\b").unwrap();
|
||||
}
|
||||
|
||||
/// collection of stop words from spaCy with small modifications
|
||||
pub(super) static STOP_WORDS: [&str; 323] = [
|
||||
"'d",
|
||||
"'ll",
|
||||
"'m",
|
||||
"'re",
|
||||
"'s",
|
||||
"'ve",
|
||||
"a",
|
||||
"about",
|
||||
"above",
|
||||
"across",
|
||||
"after",
|
||||
"afterwards",
|
||||
"again",
|
||||
"against",
|
||||
"almost",
|
||||
"alone",
|
||||
"along",
|
||||
"already",
|
||||
"also",
|
||||
"although",
|
||||
"always",
|
||||
"am",
|
||||
"among",
|
||||
"amongst",
|
||||
"amount",
|
||||
"an",
|
||||
"and",
|
||||
"another",
|
||||
"any",
|
||||
"anyhow",
|
||||
"anyone",
|
||||
"anything",
|
||||
"anyway",
|
||||
"anywhere",
|
||||
"are",
|
||||
"around",
|
||||
"as",
|
||||
"at",
|
||||
"back",
|
||||
"be",
|
||||
"became",
|
||||
"because",
|
||||
"become",
|
||||
"becomes",
|
||||
"becoming",
|
||||
"been",
|
||||
"before",
|
||||
"beforehand",
|
||||
"behind",
|
||||
"being",
|
||||
"below",
|
||||
"beside",
|
||||
"besides",
|
||||
"between",
|
||||
"beyond",
|
||||
"both",
|
||||
"bottom",
|
||||
"but",
|
||||
"by",
|
||||
"ca",
|
||||
"call",
|
||||
"can",
|
||||
"cannot",
|
||||
"could",
|
||||
"did",
|
||||
"do",
|
||||
"does",
|
||||
"doing",
|
||||
"done",
|
||||
"down",
|
||||
"due",
|
||||
"during",
|
||||
"each",
|
||||
"eight",
|
||||
"either",
|
||||
"eleven",
|
||||
"else",
|
||||
"elsewhere",
|
||||
"empty",
|
||||
"enough",
|
||||
"even",
|
||||
"ever",
|
||||
"every",
|
||||
"everyone",
|
||||
"everything",
|
||||
"everywhere",
|
||||
"except",
|
||||
"few",
|
||||
"fifteen",
|
||||
"fifty",
|
||||
"first",
|
||||
"five",
|
||||
"for",
|
||||
"former",
|
||||
"formerly",
|
||||
"forty",
|
||||
"four",
|
||||
"from",
|
||||
"front",
|
||||
"full",
|
||||
"further",
|
||||
"get",
|
||||
"got",
|
||||
"give",
|
||||
"go",
|
||||
"had",
|
||||
"has",
|
||||
"have",
|
||||
"he",
|
||||
"hence",
|
||||
"her",
|
||||
"here",
|
||||
"hereafter",
|
||||
"hereby",
|
||||
"herein",
|
||||
"hereupon",
|
||||
"hers",
|
||||
"herself",
|
||||
"him",
|
||||
"himself",
|
||||
"his",
|
||||
"how",
|
||||
"however",
|
||||
"hundred",
|
||||
"i",
|
||||
"if",
|
||||
"in",
|
||||
"indeed",
|
||||
"into",
|
||||
"is",
|
||||
"it",
|
||||
"its",
|
||||
"itself",
|
||||
"just",
|
||||
"keep",
|
||||
"last",
|
||||
"latter",
|
||||
"latterly",
|
||||
"least",
|
||||
"less",
|
||||
"made",
|
||||
"make",
|
||||
"many",
|
||||
"may",
|
||||
"me",
|
||||
"meanwhile",
|
||||
"might",
|
||||
"mine",
|
||||
"more",
|
||||
"moreover",
|
||||
"most",
|
||||
"mostly",
|
||||
"move",
|
||||
"much",
|
||||
"must",
|
||||
"my",
|
||||
"myself",
|
||||
"n't",
|
||||
"name",
|
||||
"namely",
|
||||
"neither",
|
||||
"never",
|
||||
"nevertheless",
|
||||
"next",
|
||||
"nine",
|
||||
"no",
|
||||
"nobody",
|
||||
"none",
|
||||
"noone",
|
||||
"nor",
|
||||
"not",
|
||||
"nothing",
|
||||
"now",
|
||||
"nowhere",
|
||||
"n\u{2018}t",
|
||||
"n\u{2019}t",
|
||||
"of",
|
||||
"off",
|
||||
"often",
|
||||
"on",
|
||||
"once",
|
||||
"one",
|
||||
"only",
|
||||
"onto",
|
||||
"or",
|
||||
"other",
|
||||
"others",
|
||||
"otherwise",
|
||||
"our",
|
||||
"ours",
|
||||
"ourselves",
|
||||
"out",
|
||||
"over",
|
||||
"own",
|
||||
"part",
|
||||
"per",
|
||||
"perhaps",
|
||||
"please",
|
||||
"put",
|
||||
"quite",
|
||||
"rather",
|
||||
"re",
|
||||
"really",
|
||||
"regarding",
|
||||
"same",
|
||||
"say",
|
||||
"see",
|
||||
"seem",
|
||||
"seemed",
|
||||
"seeming",
|
||||
"seems",
|
||||
"serious",
|
||||
"several",
|
||||
"she",
|
||||
"should",
|
||||
"side",
|
||||
"since",
|
||||
"six",
|
||||
"sixty",
|
||||
"so",
|
||||
"some",
|
||||
"somehow",
|
||||
"someone",
|
||||
"something",
|
||||
"sometime",
|
||||
"sometimes",
|
||||
"somewhere",
|
||||
"still",
|
||||
"such",
|
||||
"take",
|
||||
"ten",
|
||||
"than",
|
||||
"that",
|
||||
"the",
|
||||
"their",
|
||||
"them",
|
||||
"themselves",
|
||||
"then",
|
||||
"thence",
|
||||
"there",
|
||||
"thereafter",
|
||||
"thereby",
|
||||
"therefore",
|
||||
"therein",
|
||||
"thereupon",
|
||||
"these",
|
||||
"they",
|
||||
"third",
|
||||
"this",
|
||||
"those",
|
||||
"though",
|
||||
"three",
|
||||
"through",
|
||||
"throughout",
|
||||
"thru",
|
||||
"thus",
|
||||
"to",
|
||||
"together",
|
||||
"too",
|
||||
"toward",
|
||||
"towards",
|
||||
"twelve",
|
||||
"twenty",
|
||||
"two",
|
||||
"under",
|
||||
"unless",
|
||||
"until",
|
||||
"up",
|
||||
"upon",
|
||||
"used",
|
||||
"using",
|
||||
"various",
|
||||
"very",
|
||||
"via",
|
||||
"was",
|
||||
"we",
|
||||
"well",
|
||||
"were",
|
||||
"what",
|
||||
"whatever",
|
||||
"when",
|
||||
"whence",
|
||||
"whenever",
|
||||
"where",
|
||||
"whereafter",
|
||||
"whereas",
|
||||
"whereby",
|
||||
"wherein",
|
||||
"whereupon",
|
||||
"wherever",
|
||||
"whether",
|
||||
"which",
|
||||
"while",
|
||||
"whither",
|
||||
"who",
|
||||
"whoever",
|
||||
"whole",
|
||||
"whom",
|
||||
"whose",
|
||||
"why",
|
||||
"will",
|
||||
"with",
|
||||
"within",
|
||||
"without",
|
||||
"would",
|
||||
"yet",
|
||||
"you",
|
||||
"your",
|
||||
"yours",
|
||||
"yourself",
|
||||
"yourselves",
|
||||
"\u{2018}d",
|
||||
"\u{2018}ll",
|
||||
"\u{2018}m",
|
||||
"\u{2018}re",
|
||||
"\u{2018}s",
|
||||
"\u{2018}ve",
|
||||
"\u{2019}d",
|
||||
"\u{2019}ll",
|
||||
"\u{2019}m",
|
||||
"\u{2019}re",
|
||||
"\u{2019}s",
|
||||
"\u{2019}ve",
|
||||
];
|
||||
223
src/nlp/document.rs
Normal file
223
src/nlp/document.rs
Normal file
@@ -0,0 +1,223 @@
|
||||
use super::term::{Term, TermMetaData};
|
||||
use super::utils::preprocess;
|
||||
use scraper::{Html, Node, Selector};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// data container representing a single document, in the nlp sense
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Document {
|
||||
/// collection of `Term`s and their associated metadata
|
||||
terms: HashMap<Term, TermMetaData>,
|
||||
|
||||
/// number of terms contained within the document
|
||||
number_of_terms: usize,
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// create a new `Document` from the given string
|
||||
pub(super) fn new(text: &str) -> Self {
|
||||
let mut document = Self::default();
|
||||
|
||||
let processed = preprocess(text);
|
||||
|
||||
document.number_of_terms += processed.len();
|
||||
|
||||
for normalized in processed {
|
||||
if normalized.len() >= 2 {
|
||||
document.add_term(&normalized)
|
||||
}
|
||||
}
|
||||
document
|
||||
}
|
||||
|
||||
/// add a `Term` to the document if it's not already tracked, otherwise increment the number
|
||||
/// of times the term has been seen
|
||||
fn add_term(&mut self, word: &str) {
|
||||
let term = Term::new(word);
|
||||
|
||||
let metadata = self.terms.entry(term).or_insert_with(TermMetaData::new);
|
||||
*metadata.count_mut() += 1;
|
||||
}
|
||||
|
||||
/// create a new `Document` from the given HTML string
|
||||
pub(crate) fn from_html(raw_html: &str) -> Self {
|
||||
let selector = Selector::parse("body").unwrap();
|
||||
|
||||
let html = Html::parse_document(raw_html);
|
||||
|
||||
let text = html
|
||||
.select(&selector)
|
||||
.next()
|
||||
.unwrap()
|
||||
.descendants()
|
||||
.filter_map(|node| {
|
||||
if !node.value().is_text() && !node.value().is_comment() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// have a Text||Comment node, trim whitespace to test for all whitespace stuff
|
||||
let trimmed = if node.value().is_text() {
|
||||
node.value().as_text().unwrap().text.trim()
|
||||
} else {
|
||||
node.value().as_comment().unwrap().comment.trim()
|
||||
};
|
||||
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// found a non-empty Text||Comment node, need to check its parent to determine if
|
||||
// it's a <script>||<style> tag. We're assuming text within a script||style tag is
|
||||
// uninteresting
|
||||
|
||||
let parent = node.parent().unwrap().value();
|
||||
|
||||
if !parent.is_element() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// parent is an Element node, see if it's a <script> or <style>
|
||||
|
||||
if let Node::Element(element) = parent {
|
||||
if element.name() == "script" || element.name() == "style" {
|
||||
return None;
|
||||
}
|
||||
|
||||
// at this point, we have a non-empty Text element with a non-script|style parent;
|
||||
// now we can return the trimmed up string
|
||||
return Some(format!("{} ", trimmed));
|
||||
}
|
||||
|
||||
// not an Element node
|
||||
None
|
||||
})
|
||||
.collect::<String>();
|
||||
|
||||
// call `new` to push the parsed html through the pre-processing pipeline and process all
|
||||
// the words
|
||||
Self::new(&text)
|
||||
}
|
||||
|
||||
/// Log normalized weighting scheme for term frequency
|
||||
pub(super) fn term_frequency(&self, term: &Term) -> f32 {
|
||||
if let Some(metadata) = self.terms.get(term) {
|
||||
metadata.count() as f32 / self.number_of_terms() as f32
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
|
||||
/// immutable reference to the collection of terms and their metadata
|
||||
pub(super) fn terms(&self) -> &HashMap<Term, TermMetaData> {
|
||||
&self.terms
|
||||
}
|
||||
|
||||
/// number of terms the current document knows about
|
||||
fn number_of_terms(&self) -> usize {
|
||||
self.number_of_terms
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
/// `Document::new` should preprocess text and generate a hashmap of `Term, TermMetadata`
|
||||
fn nlp_document_creation_from_text() {
|
||||
let doc = Document::new("The air quality in Singapore got worse on Wednesday.");
|
||||
|
||||
let expected_terms = ["air", "quality", "singapore", "worse", "wednesday"];
|
||||
|
||||
for expected in expected_terms {
|
||||
let term = Term::new(expected);
|
||||
assert!(doc.terms().contains_key(&term));
|
||||
assert_eq!(doc.number_of_terms, 5);
|
||||
assert_eq!(doc.terms().get(&term).unwrap().count(), 1);
|
||||
|
||||
// since term frequencies aren't calculated on `new`, document frequency is zero in
|
||||
// addition to the empty term_frequencies slice
|
||||
let empty: &[f32] = &[];
|
||||
assert_eq!(doc.terms().get(&term).unwrap().term_frequencies(), empty);
|
||||
assert_eq!(doc.terms().get(&term).unwrap().document_frequency(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// `Document::new` should preprocess html and generate a hashmap of `Term, TermMetadata`
|
||||
fn nlp_document_creation_from_html() {
|
||||
let empty = Document::from_html("<html></html>");
|
||||
assert_eq!(empty.number_of_terms, 0);
|
||||
|
||||
let other_empty = Document::from_html("<html><body><p></p></body></html>");
|
||||
assert_eq!(other_empty.number_of_terms, 0);
|
||||
|
||||
let third_empty = Document::from_html("<!DOCTYPE html><html><!DOCTYPE html><p></p></html>");
|
||||
assert_eq!(third_empty.number_of_terms, 0);
|
||||
|
||||
// p tag for is_text check and comment for is_comment
|
||||
let doc = Document::from_html(
|
||||
"<html><body><p>The air quality in Singapore.</p><!--got worse on Wednesday--></body></html>",
|
||||
);
|
||||
|
||||
let expected_terms = ["air", "quality", "singapore", "worse", "wednesday"];
|
||||
|
||||
for expected in expected_terms {
|
||||
let term = Term::new(expected);
|
||||
assert_eq!(doc.number_of_terms, 5);
|
||||
assert!(doc.terms().contains_key(&term));
|
||||
assert_eq!(doc.terms().get(&term).unwrap().count(), 1);
|
||||
|
||||
// since term frequencies aren't calculated on `new`, document frequency is zero in
|
||||
// addition to the empty term_frequencies slice
|
||||
let empty: &[f32] = &[];
|
||||
assert_eq!(doc.terms().get(&term).unwrap().term_frequencies(), empty);
|
||||
assert_eq!(doc.terms().get(&term).unwrap().document_frequency(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// simple check of the `term_frequency` function's return value
|
||||
fn term_frequency_validation() {
|
||||
let doc = Document::new("The air quality in Singapore got worse on Wednesday. Air Jordan.");
|
||||
|
||||
let air_freq = doc.term_frequency(&Term::new("air"));
|
||||
|
||||
let abs_diff = (air_freq - 0.2857143).abs();
|
||||
assert!(abs_diff <= f32::EPSILON);
|
||||
|
||||
let non_existent = doc.term_frequency(&Term::new("derpatronic"));
|
||||
assert_eq!(non_existent, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// test accessors for correctness
|
||||
fn document_accessor_test() {
|
||||
let doc = Document::new("The air quality in Singapore got worse on Wednesday.");
|
||||
let keys = doc.terms().keys().map(|key| key.raw()).collect::<Vec<_>>();
|
||||
|
||||
let expected = ["air", "quality", "singapore", "worse", "wednesday"];
|
||||
|
||||
assert_eq!(doc.number_of_terms(), 5);
|
||||
|
||||
for key in keys {
|
||||
assert!(expected.contains(&key));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// ensure words in script/style tags aren't processed
|
||||
fn document_creation_skips_script_and_style_tags() {
|
||||
let html = "<body><script>The air quality</script><style>in Singapore</style><p>got worse on Wednesday.</p></body>";
|
||||
let doc = Document::from_html(html);
|
||||
let keys = doc.terms().keys().map(|key| key.raw()).collect::<Vec<_>>();
|
||||
|
||||
let expected = ["worse", "wednesday"];
|
||||
|
||||
assert_eq!(doc.number_of_terms(), 2);
|
||||
|
||||
for key in keys {
|
||||
assert!(expected.contains(&key));
|
||||
}
|
||||
}
|
||||
}
|
||||
10
src/nlp/mod.rs
Normal file
10
src/nlp/mod.rs
Normal file
@@ -0,0 +1,10 @@
|
||||
//! small stand-alone tf-idf library, specifically designed for use in feroxbuster
|
||||
|
||||
mod constants;
|
||||
mod document;
|
||||
mod model;
|
||||
mod term;
|
||||
mod utils;
|
||||
|
||||
pub(crate) use self::document::Document;
|
||||
pub(crate) use self::model::TfIdf;
|
||||
185
src/nlp/model.rs
Normal file
185
src/nlp/model.rs
Normal file
@@ -0,0 +1,185 @@
|
||||
use super::document::Document;
|
||||
use super::term::{Term, TermMetaData};
|
||||
use super::utils::{inverse_document_frequency, tf_idf_score};
|
||||
use std::borrow::{Borrow, BorrowMut};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// data container for the TF-IDF model
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct TfIdf {
|
||||
/// collection of `Term`s and their associated metadata
|
||||
terms: HashMap<Term, TermMetaData>,
|
||||
|
||||
/// number of documents processed by the model
|
||||
num_documents: usize,
|
||||
}
|
||||
|
||||
impl TfIdf {
|
||||
/// create an empty TF-IDF model; must be populated with `add_document` prior to use
|
||||
pub(crate) fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// accessor method for the collection of `Term`s and `TermMetaData`
|
||||
fn terms(&self) -> &HashMap<Term, TermMetaData> {
|
||||
self.terms.borrow()
|
||||
}
|
||||
|
||||
/// accessor method for the number of `Document`s the model has processed
|
||||
pub(crate) fn num_documents(&self) -> usize {
|
||||
self.num_documents
|
||||
}
|
||||
|
||||
/// add a `Document` to the model
|
||||
pub(crate) fn add_document(&mut self, document: Document) {
|
||||
// increment number of docs seen, since we don't preserve the document itself; this needs
|
||||
// to happen before calls to `self.inverse_document_frequency`, as it relies on the count
|
||||
// being up to date
|
||||
self.num_documents += 1;
|
||||
|
||||
for (term, doc_metadata) in document.terms().iter() {
|
||||
// an incoming `Term` from a `Document` only has a valid `count` for that particular
|
||||
// document; need to get the term frequency while both are known/valid
|
||||
let term_frequency = document.term_frequency(term);
|
||||
|
||||
let metadata = self
|
||||
.terms
|
||||
.entry(term.clone())
|
||||
.or_insert_with(|| doc_metadata.to_owned());
|
||||
|
||||
metadata.term_frequencies_mut().push(term_frequency);
|
||||
}
|
||||
}
|
||||
|
||||
/// (re)-calculate tf-idf scores for all terms, given the current number of documents
|
||||
///
|
||||
/// # Notes
|
||||
///
|
||||
/// old tf-idf scores are removed during calculations to keep new `Term`s at the same relative
|
||||
/// level as new ones WRT corpus size
|
||||
pub(crate) fn calculate_tf_idf_scores(&mut self) {
|
||||
for metadata in self.terms.borrow_mut().values_mut() {
|
||||
let num_frequencies = metadata.term_frequencies().len();
|
||||
|
||||
let mut to_add = Vec::with_capacity(num_frequencies);
|
||||
|
||||
for frequency in metadata.term_frequencies() {
|
||||
let idf = inverse_document_frequency(
|
||||
self.num_documents as f32,
|
||||
metadata.document_frequency() as f32,
|
||||
);
|
||||
|
||||
let score = tf_idf_score(*frequency, idf);
|
||||
to_add.push(score);
|
||||
}
|
||||
|
||||
let average: f32 = to_add.iter().sum::<f32>() / to_add.len() as f32;
|
||||
|
||||
*metadata.tf_idf_score_mut() = average;
|
||||
}
|
||||
}
|
||||
|
||||
/// select all terms with a non-zero tf-idf score
|
||||
pub(crate) fn all_words(&self) -> Vec<String> {
|
||||
self.terms()
|
||||
.iter()
|
||||
.filter(|(_, metadata)| metadata.tf_idf_score() > 0.0)
|
||||
.map(|(term, _)| term.raw().to_owned())
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// helper for this test suite
|
||||
fn get_score(word: &str, model: &TfIdf) -> f32 {
|
||||
model.terms().get(&Term::new(word)).unwrap().tf_idf_score()
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// given the example data at https://remykarem.github.io/tfidf-demo/, ensure the model
|
||||
/// produces the same results
|
||||
fn model_generates_expected_tf_idf_scores() {
|
||||
let one = "Air quality in the sunny island improved gradually throughout Wednesday.";
|
||||
let two =
|
||||
"Air quality in Singapore on Wednesday continued to get worse as haze hit the island.";
|
||||
let three = "The air quality in Singapore is monitored through a network of air monitoring stations located in different parts of the island";
|
||||
let four = "The air quality in Singapore got worse on Wednesday.";
|
||||
|
||||
let docs = [one, two, three, four];
|
||||
let mut model = TfIdf::new();
|
||||
|
||||
for doc in docs.iter() {
|
||||
let d = Document::new(doc);
|
||||
model.add_document(d);
|
||||
}
|
||||
|
||||
assert_eq!(model.terms().len(), 19);
|
||||
|
||||
model.calculate_tf_idf_scores();
|
||||
|
||||
assert_eq!(get_score("quality", &model), 0.0);
|
||||
assert_eq!(get_score("air", &model), 0.0);
|
||||
assert_eq!(get_score("wednesday", &model), 0.018906077);
|
||||
assert_eq!(get_score("island", &model), 0.014047348);
|
||||
assert_eq!(get_score("singapore", &model), 0.016427131);
|
||||
assert_eq!(get_score("sunny", &model), 0.08600858);
|
||||
assert_eq!(get_score("monitoring", &model), 0.05017167);
|
||||
assert_eq!(get_score("stations", &model), 0.05017167);
|
||||
assert_eq!(get_score("parts", &model), 0.05017167);
|
||||
assert_eq!(get_score("haze", &model), 0.06689556);
|
||||
assert_eq!(get_score("hit", &model), 0.06689556);
|
||||
assert_eq!(get_score("worse", &model), 0.04682689);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// given the example data at https://remykarem.github.io/tfidf-demo/, ensure the model
|
||||
/// produces the same results
|
||||
fn select_n_words_grabs_correct_words() {
|
||||
let one = "Air quality in the sunny island improved gradually throughout Wednesday.";
|
||||
let two =
|
||||
"Air quality in Singapore on Wednesday continued to get worse as haze hit the island.";
|
||||
let three = "The air quality in Singapore is monitored through a network of air monitoring stations located in different parts of the island";
|
||||
let four = "The air quality in Singapore got worse on Wednesday.";
|
||||
|
||||
let docs = [one, two, three, four];
|
||||
let mut model = TfIdf::new();
|
||||
|
||||
for doc in docs.iter() {
|
||||
let d = Document::new(doc);
|
||||
model.add_document(d);
|
||||
}
|
||||
|
||||
assert_eq!(model.num_documents(), 4);
|
||||
|
||||
model.calculate_tf_idf_scores();
|
||||
|
||||
let non_zero_words = model.all_words();
|
||||
|
||||
[
|
||||
"gradually",
|
||||
"network",
|
||||
"hit",
|
||||
"located",
|
||||
"continued",
|
||||
"island",
|
||||
"worse",
|
||||
"monitored",
|
||||
"monitoring",
|
||||
"haze",
|
||||
"different",
|
||||
"stations",
|
||||
"sunny",
|
||||
"singapore",
|
||||
"improved",
|
||||
"parts",
|
||||
"wednesday",
|
||||
]
|
||||
.iter()
|
||||
.for_each(|word| {
|
||||
assert!(non_zero_words.contains(&word.to_string()));
|
||||
});
|
||||
}
|
||||
}
|
||||
105
src/nlp/term.rs
Normal file
105
src/nlp/term.rs
Normal file
@@ -0,0 +1,105 @@
|
||||
use std::borrow::BorrowMut;
|
||||
|
||||
/// single word term for text processing
|
||||
#[derive(Debug, Hash, Eq, PartialEq, Default, Clone)]
|
||||
pub(crate) struct Term {
|
||||
/// underlying string that the term represents
|
||||
raw: String,
|
||||
}
|
||||
|
||||
impl Term {
|
||||
/// given a word, create a new `Term`
|
||||
pub(super) fn new(word: &str) -> Self {
|
||||
Self {
|
||||
raw: word.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// return a reference to the underlying string
|
||||
pub(super) fn raw(&self) -> &str {
|
||||
&self.raw
|
||||
}
|
||||
}
|
||||
|
||||
/// metadata to be associated with a `Term`
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub(super) struct TermMetaData {
|
||||
/// number of times the associated `Term` was seen in a single document
|
||||
count: u32,
|
||||
|
||||
/// collection of term frequencies for the associated `Term`
|
||||
term_frequencies: Vec<f32>,
|
||||
|
||||
/// tf-idf score for the associated `Term`
|
||||
tf_idf_score: f32,
|
||||
}
|
||||
|
||||
impl TermMetaData {
|
||||
/// create a new metadata container
|
||||
pub(super) fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// number of times a `Term` has appeared in any `Document` within the corpus
|
||||
pub(super) fn document_frequency(&self) -> usize {
|
||||
self.term_frequencies().len()
|
||||
}
|
||||
|
||||
/// mutable reference to the collection of term frequencies
|
||||
pub(super) fn term_frequencies_mut(&mut self) -> &mut Vec<f32> {
|
||||
self.term_frequencies.borrow_mut()
|
||||
}
|
||||
|
||||
/// immutable reference to the collection of term frequencies
|
||||
pub(super) fn term_frequencies(&self) -> &[f32] {
|
||||
&self.term_frequencies
|
||||
}
|
||||
|
||||
/// mutable reference to the number of times a `Term` was seen in a particular `Document`
|
||||
pub(super) fn count_mut(&mut self) -> &mut u32 {
|
||||
self.count.borrow_mut()
|
||||
}
|
||||
|
||||
/// number of times a `Term` was seen in a particular `Document`
|
||||
pub(super) fn count(&self) -> u32 {
|
||||
self.count
|
||||
}
|
||||
|
||||
/// mutable reference to the term's tf-idf score
|
||||
pub(super) fn tf_idf_score_mut(&mut self) -> &mut f32 {
|
||||
self.tf_idf_score.borrow_mut()
|
||||
}
|
||||
|
||||
/// immutable reference to the term's tf-idf score
|
||||
pub(super) fn tf_idf_score(&self) -> f32 {
|
||||
self.tf_idf_score
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
/// test accessors for correctness
|
||||
fn nlp_term_accessor_test() {
|
||||
let term = Term::new("stuff");
|
||||
assert_eq!(term.raw(), "stuff");
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// test accessors for correctness
|
||||
fn nlp_term_metadata_accessor_test() {
|
||||
let mut metadata = TermMetaData::new();
|
||||
|
||||
*metadata.count_mut() += 1;
|
||||
assert_eq!(metadata.count(), 1);
|
||||
|
||||
metadata.term_frequencies_mut().push(1.0);
|
||||
assert_eq!(metadata.document_frequency(), 1);
|
||||
assert_eq!(metadata.term_frequencies().first().unwrap(), &1.0);
|
||||
|
||||
*metadata.tf_idf_score_mut() = 1.0_f32;
|
||||
assert_eq!(metadata.tf_idf_score(), 1.0);
|
||||
}
|
||||
}
|
||||
158
src/nlp/utils.rs
Normal file
158
src/nlp/utils.rs
Normal file
@@ -0,0 +1,158 @@
|
||||
use super::constants::{BOUNDED_WORD_REGEX, STOP_WORDS};
|
||||
use regex::Captures;
|
||||
use std::borrow::Cow;
|
||||
|
||||
/// pre-processing pipeline wrapper that removes punctuation, normalizes word case (utf-8 included)
|
||||
/// to lowercase, and remove stop words
|
||||
pub(super) fn preprocess(text: &str) -> Vec<String> {
|
||||
let text = remove_punctuation(text);
|
||||
let text = normalize_case(text);
|
||||
let text = remove_stop_words(&text);
|
||||
|
||||
text.split_whitespace()
|
||||
.map(|word| word.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
|
||||
/// optimized version of `str::to_lowercase`
|
||||
fn normalize_case<'a, S: Into<Cow<'a, str>>>(input: S) -> Cow<'a, str> {
|
||||
let input = input.into();
|
||||
|
||||
let first = input.find(char::is_uppercase);
|
||||
|
||||
if let Some(first_idx) = first {
|
||||
let mut output = String::from(&input[..first_idx]);
|
||||
output.reserve(input.len() - first_idx);
|
||||
|
||||
for c in input[first_idx..].chars() {
|
||||
if c.is_uppercase() {
|
||||
output.push(c.to_lowercase().next().unwrap())
|
||||
} else {
|
||||
output.push(c)
|
||||
}
|
||||
}
|
||||
|
||||
Cow::Owned(output)
|
||||
} else {
|
||||
input
|
||||
}
|
||||
}
|
||||
|
||||
/// replace ascii and some utf-8 punctuation characters with ' ' (space) in the given string
|
||||
fn remove_punctuation(text: &str) -> String {
|
||||
text.replace(
|
||||
[
|
||||
'!', '\\', '"', '#', '$', '%', '&', '(', ')', '*', '+', ':', ';', '<', '=', '>', '?',
|
||||
'@', '[', ']', '^', '{', '}', '|', '~', ',', '\'', '“', '”', '’', '‘', '’', '‘', '/',
|
||||
'–', '—', '.',
|
||||
],
|
||||
" ",
|
||||
)
|
||||
}
|
||||
|
||||
/// remove stop words from the given string
|
||||
fn remove_stop_words(text: &str) -> String {
|
||||
BOUNDED_WORD_REGEX
|
||||
.replace_all(text, |caps: &Captures| {
|
||||
let word = &caps[0];
|
||||
if !STOP_WORDS.contains(&word) {
|
||||
word.to_owned()
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
})
|
||||
.into()
|
||||
}
|
||||
|
||||
/// calculate inverse document frequency
|
||||
pub(super) fn inverse_document_frequency(num_docs: f32, doc_frequency: f32) -> f32 {
|
||||
f32::log10(num_docs / doc_frequency)
|
||||
}
|
||||
|
||||
/// calculate term frequency-inverse document frequency (tf-idf)
|
||||
pub(super) fn tf_idf_score(term_frequency: f32, idf: f32) -> f32 {
|
||||
term_frequency * idf
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
/// ensure all expected punctuation characters are removed
|
||||
fn test_remove_punctuation() {
|
||||
let tester = "!\\\"#$%&()*+/:;<=>?@[]^{}|~,.'“”’‘–—\n‘’";
|
||||
// the `" \n"` is because of the things like / getting replaced with a space
|
||||
assert_eq!(
|
||||
remove_punctuation(tester),
|
||||
" \n "
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// ensure uppercase characters are swapped to lowercase
|
||||
fn test_normalize_case() {
|
||||
let tester = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
assert_eq!(normalize_case(tester), "abcdefghijklmnopqrstuvwxyz");
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// ensure all stop words are removed from the list of stopwords ... intestuous
|
||||
fn test_remove_stopwords() {
|
||||
let all_words = STOP_WORDS
|
||||
.iter()
|
||||
.map(|&word| word.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
|
||||
let removed = remove_stop_words(&all_words).replace(' ', "");
|
||||
|
||||
// the remaining chars are from the contraction-based stop words
|
||||
assert_eq!(removed, "'d'll'm''s'ven'tn‘tn’t‘d‘ll‘m‘‘s‘ve’d’ll’m’’s’ve");
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// ensure preprocess
|
||||
fn test_preprocess_results() {
|
||||
let tester = "WHY are Y'all YELLing?";
|
||||
assert_eq!(&preprocess(tester), &["y", "all", "yelling"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// ensure our calculations conform to the example provided at the link below
|
||||
///
|
||||
/// https://www.kaggle.com/paulrohan2020/tf-idf-tutorial/notebook#TF-IDF-Model
|
||||
///
|
||||
/// Consider a document containing 100 words wherein the word cat appears 3 times.
|
||||
/// The term frequency (i.e., tf) for cat is then (3 / 100) = 0.03. Now, assume we have 10
|
||||
/// million documents and the word cat appears in one thousand of these. Then, the inverse
|
||||
/// document frequency (i.e., idf) is calculated as log(10,000,000 / 1,000) = 4. Thus, the
|
||||
/// Tf-idf weight is the product of these quantities: 0.03 * 4 = 0.12.
|
||||
fn idf_returns_expected_value() {
|
||||
let num_docs = 10_000_000_f32;
|
||||
let num_occurrences = 1_000_f32;
|
||||
let abs_diff = (inverse_document_frequency(num_docs, num_occurrences) - 4.0).abs();
|
||||
|
||||
assert!(abs_diff <= f32::EPSILON);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// ensure our calculations conform to the example provided at the link below
|
||||
///
|
||||
/// https://www.kaggle.com/paulrohan2020/tf-idf-tutorial/notebook#TF-IDF-Model
|
||||
///
|
||||
/// Consider a document containing 100 words wherein the word cat appears 3 times.
|
||||
/// The term frequency (i.e., tf) for cat is then (3 / 100) = 0.03. Now, assume we have 10
|
||||
/// million documents and the word cat appears in one thousand of these. Then, the inverse
|
||||
/// document frequency (i.e., idf) is calculated as log(10,000,000 / 1,000) = 4. Thus, the
|
||||
/// Tf-idf weight is the product of these quantities: 0.03 * 4 = 0.12.
|
||||
fn tf_idf_returns_expected_value() {
|
||||
let term_freq = 0.03_f32;
|
||||
let num_docs = 10_000_000_f32;
|
||||
let num_occurrences = 1_000_f32;
|
||||
let idf = inverse_document_frequency(num_docs, num_occurrences);
|
||||
let abs_diff = (tf_idf_score(term_freq, idf) - 0.12).abs();
|
||||
|
||||
assert!(abs_diff <= f32::EPSILON);
|
||||
}
|
||||
}
|
||||
813
src/parser.rs
813
src/parser.rs
@@ -1,4 +1,7 @@
|
||||
use clap::{App, Arg, ArgGroup};
|
||||
use clap::ArgAction;
|
||||
use clap::{
|
||||
crate_authors, crate_description, crate_name, crate_version, Arg, ArgGroup, Command, ValueHint,
|
||||
};
|
||||
use lazy_static::lazy_static;
|
||||
use regex::Regex;
|
||||
use std::env;
|
||||
@@ -14,390 +17,635 @@ lazy_static! {
|
||||
/// - 1d
|
||||
pub static ref TIMESPEC_REGEX: Regex =
|
||||
Regex::new(r"^(?i)(?P<n>\d+)(?P<m>[smdh])$").expect("Could not compile regex");
|
||||
|
||||
/// help string for user agent, your guess is as good as mine as to why this is required...
|
||||
static ref DEFAULT_USER_AGENT: String = format!(
|
||||
"Sets the User-Agent (default: feroxbuster/{})",
|
||||
crate_version!()
|
||||
);
|
||||
}
|
||||
|
||||
/// Create and return an instance of [clap::App](https://docs.rs/clap/latest/clap/struct.App.html), i.e. the Command Line Interface's configuration
|
||||
pub fn initialize() -> App<'static, 'static> {
|
||||
let mut app = App::new("feroxbuster")
|
||||
.version(env!("CARGO_PKG_VERSION"))
|
||||
.author("Ben 'epi' Risher (@epi052)")
|
||||
.about("A fast, simple, recursive content discovery tool written in Rust")
|
||||
pub fn initialize() -> Command {
|
||||
let app = Command::new(crate_name!())
|
||||
.version(crate_version!())
|
||||
.author(crate_authors!())
|
||||
.about(crate_description!());
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// group - target selection
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
let app = app
|
||||
.arg(
|
||||
Arg::with_name("wordlist")
|
||||
.short("w")
|
||||
.long("wordlist")
|
||||
.value_name("FILE")
|
||||
.help("Path to the wordlist")
|
||||
.takes_value(true),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("url")
|
||||
.short("u")
|
||||
Arg::new("url")
|
||||
.short('u')
|
||||
.long("url")
|
||||
.required_unless_one(&["stdin", "resume_from"])
|
||||
.required_unless_present_any(["stdin", "resume_from"])
|
||||
.help_heading("Target selection")
|
||||
.value_name("URL")
|
||||
.multiple(true)
|
||||
.use_delimiter(true)
|
||||
.help("The target URL(s) (required, unless --stdin used)"),
|
||||
.use_value_delimiter(true)
|
||||
.value_hint(ValueHint::Url)
|
||||
.help("The target URL (required, unless [--stdin || --resume-from] used)"),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("threads")
|
||||
.short("t")
|
||||
.long("threads")
|
||||
.value_name("THREADS")
|
||||
.takes_value(true)
|
||||
.help("Number of concurrent threads (default: 50)"),
|
||||
Arg::new("stdin")
|
||||
.long("stdin")
|
||||
.help_heading("Target selection")
|
||||
.num_args(0)
|
||||
.help("Read url(s) from STDIN")
|
||||
.conflicts_with("url")
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("depth")
|
||||
.short("d")
|
||||
.long("depth")
|
||||
.value_name("RECURSION_DEPTH")
|
||||
.takes_value(true)
|
||||
.help("Maximum recursion depth, a depth of 0 is infinite recursion (default: 4)"),
|
||||
Arg::new("resume_from")
|
||||
.long("resume-from")
|
||||
.value_hint(ValueHint::FilePath)
|
||||
.value_name("STATE_FILE")
|
||||
.help_heading("Target selection")
|
||||
.help("State file from which to resume a partially complete scan (ex. --resume-from ferox-1606586780.state)")
|
||||
.conflicts_with("url")
|
||||
.num_args(1),
|
||||
);
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// group - composite settings
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
let app = app
|
||||
.arg(
|
||||
Arg::new("burp")
|
||||
.long("burp")
|
||||
.num_args(0)
|
||||
.help_heading("Composite settings")
|
||||
.conflicts_with_all(["proxy", "insecure", "burp_replay"])
|
||||
.help("Set --proxy to http://127.0.0.1:8080 and set --insecure to true"),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("timeout")
|
||||
.short("T")
|
||||
.long("timeout")
|
||||
.value_name("SECONDS")
|
||||
.takes_value(true)
|
||||
.help("Number of seconds before a request times out (default: 7)"),
|
||||
Arg::new("burp_replay")
|
||||
.long("burp-replay")
|
||||
.num_args(0)
|
||||
.help_heading("Composite settings")
|
||||
.conflicts_with_all(["replay_proxy", "insecure"])
|
||||
.help("Set --replay-proxy to http://127.0.0.1:8080 and set --insecure to true"),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("verbosity")
|
||||
.short("v")
|
||||
.long("verbosity")
|
||||
.takes_value(false)
|
||||
.multiple(true)
|
||||
.conflicts_with("silent")
|
||||
.help("Increase verbosity level (use -vv or more for greater effect. [CAUTION] 4 -v's is probably too much)"),
|
||||
)
|
||||
Arg::new("smart")
|
||||
.long("smart")
|
||||
.num_args(0)
|
||||
.help_heading("Composite settings")
|
||||
.help("Set --extract-links, --auto-tune, --collect-words, and --collect-backups to true"),
|
||||
).arg(
|
||||
Arg::new("thorough")
|
||||
.long("thorough")
|
||||
.num_args(0)
|
||||
.help_heading("Composite settings")
|
||||
.help("Use the same settings as --smart and set --collect-extensions to true"),
|
||||
);
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// group - proxy settings
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
let app = app
|
||||
.arg(
|
||||
Arg::with_name("proxy")
|
||||
.short("p")
|
||||
Arg::new("proxy")
|
||||
.short('p')
|
||||
.long("proxy")
|
||||
.takes_value(true)
|
||||
.num_args(1)
|
||||
.value_name("PROXY")
|
||||
.value_hint(ValueHint::Url)
|
||||
.help_heading("Proxy settings")
|
||||
.help(
|
||||
"Proxy to use for requests (ex: http(s)://host:port, socks5(h)://host:port)",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("replay_proxy")
|
||||
.short("P")
|
||||
Arg::new("replay_proxy")
|
||||
.short('P')
|
||||
.long("replay-proxy")
|
||||
.takes_value(true)
|
||||
.num_args(1)
|
||||
.value_hint(ValueHint::Url)
|
||||
.value_name("REPLAY_PROXY")
|
||||
.help_heading("Proxy settings")
|
||||
.help(
|
||||
"Send only unfiltered requests through a Replay Proxy, instead of all requests",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("replay_codes")
|
||||
.short("R")
|
||||
Arg::new("replay_codes")
|
||||
.short('R')
|
||||
.long("replay-codes")
|
||||
.value_name("REPLAY_CODE")
|
||||
.takes_value(true)
|
||||
.multiple(true)
|
||||
.use_delimiter(true)
|
||||
.num_args(1..)
|
||||
.action(ArgAction::Append)
|
||||
.use_value_delimiter(true)
|
||||
.requires("replay_proxy")
|
||||
.help_heading("Proxy settings")
|
||||
.help(
|
||||
"Status Codes to send through a Replay Proxy when found (default: --status-codes value)",
|
||||
),
|
||||
)
|
||||
);
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// group - request settings
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
let app = app
|
||||
.arg(
|
||||
Arg::with_name("status_codes")
|
||||
.short("s")
|
||||
.long("status-codes")
|
||||
.value_name("STATUS_CODE")
|
||||
.takes_value(true)
|
||||
.multiple(true)
|
||||
.use_delimiter(true)
|
||||
.help(
|
||||
"Status Codes to include (allow list) (default: 200 204 301 302 307 308 401 403 405)",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("silent")
|
||||
.long("silent")
|
||||
.takes_value(false)
|
||||
.conflicts_with("quiet")
|
||||
.help("Only print URLs + turn off logging (good for piping a list of urls to other commands)")
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("quiet")
|
||||
.short("q")
|
||||
.long("quiet")
|
||||
.takes_value(false)
|
||||
.help("Hide progress bars and banner (good for tmux windows w/ notifications)")
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("auto_tune")
|
||||
.long("auto-tune")
|
||||
.takes_value(false)
|
||||
.conflicts_with("auto_bail")
|
||||
.help("Automatically lower scan rate when an excessive amount of errors are encountered")
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("auto_bail")
|
||||
.long("auto-bail")
|
||||
.takes_value(false)
|
||||
.help("Automatically stop scanning when an excessive amount of errors are encountered")
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("json")
|
||||
.long("json")
|
||||
.takes_value(false)
|
||||
.requires("output_files")
|
||||
.help("Emit JSON logs to --output and --debug-log instead of normal text")
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("dont_filter")
|
||||
.short("D")
|
||||
.long("dont-filter")
|
||||
.takes_value(false)
|
||||
.help("Don't auto-filter wildcard responses")
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("output")
|
||||
.short("o")
|
||||
.long("output")
|
||||
.value_name("FILE")
|
||||
.help("Output file to write results to (use w/ --json for JSON entries)")
|
||||
.takes_value(true),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("resume_from")
|
||||
.long("resume-from")
|
||||
.value_name("STATE_FILE")
|
||||
.help("State file from which to resume a partially complete scan (ex. --resume-from ferox-1606586780.state)")
|
||||
.conflicts_with("url")
|
||||
.takes_value(true),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("debug_log")
|
||||
.long("debug-log")
|
||||
.value_name("FILE")
|
||||
.help("Output file to write log entries (use w/ --json for JSON entries)")
|
||||
.takes_value(true),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("user_agent")
|
||||
.short("a")
|
||||
Arg::new("user_agent")
|
||||
.short('a')
|
||||
.long("user-agent")
|
||||
.value_name("USER_AGENT")
|
||||
.takes_value(true)
|
||||
.help(
|
||||
"Sets the User-Agent (default: feroxbuster/VERSION)"
|
||||
),
|
||||
.num_args(1)
|
||||
.help_heading("Request settings")
|
||||
.help(&**DEFAULT_USER_AGENT),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("random_agent")
|
||||
.short("A")
|
||||
Arg::new("random_agent")
|
||||
.short('A')
|
||||
.long("random-agent")
|
||||
.takes_value(false)
|
||||
.help(
|
||||
"Use a random User-Agent"
|
||||
),
|
||||
.num_args(0)
|
||||
.help_heading("Request settings")
|
||||
.help("Use a random User-Agent"),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("redirects")
|
||||
.short("r")
|
||||
.long("redirects")
|
||||
.takes_value(false)
|
||||
.help("Follow redirects")
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("insecure")
|
||||
.short("k")
|
||||
.long("insecure")
|
||||
.takes_value(false)
|
||||
.help("Disables TLS certificate validation")
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("extensions")
|
||||
.short("x")
|
||||
Arg::new("extensions")
|
||||
.short('x')
|
||||
.long("extensions")
|
||||
.value_name("FILE_EXTENSION")
|
||||
.takes_value(true)
|
||||
.multiple(true)
|
||||
.use_delimiter(true)
|
||||
.num_args(1..)
|
||||
.action(ArgAction::Append)
|
||||
.use_value_delimiter(true)
|
||||
.help_heading("Request settings")
|
||||
.help(
|
||||
"File extension(s) to search for (ex: -x php -x pdf js)",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("url_denylist")
|
||||
.long("dont-scan")
|
||||
.value_name("URL")
|
||||
.takes_value(true)
|
||||
.multiple(true)
|
||||
.use_delimiter(true)
|
||||
Arg::new("methods")
|
||||
.short('m')
|
||||
.long("methods")
|
||||
.value_name("HTTP_METHODS")
|
||||
.num_args(1..)
|
||||
.action(ArgAction::Append)
|
||||
.use_value_delimiter(true)
|
||||
.help_heading("Request settings")
|
||||
.help(
|
||||
"URL(s) or Regex Pattern(s) to exclude from recursion/scans",
|
||||
"Which HTTP request method(s) should be sent (default: GET)",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("headers")
|
||||
.short("H")
|
||||
Arg::new("data")
|
||||
.long("data")
|
||||
.value_name("DATA")
|
||||
.num_args(1)
|
||||
.help_heading("Request settings")
|
||||
.help(
|
||||
"Request's Body; can read data from a file if input starts with an @ (ex: @post.bin)",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("headers")
|
||||
.short('H')
|
||||
.long("headers")
|
||||
.value_name("HEADER")
|
||||
.takes_value(true)
|
||||
.multiple(true)
|
||||
.use_delimiter(true)
|
||||
.num_args(1..)
|
||||
.action(ArgAction::Append)
|
||||
.help_heading("Request settings")
|
||||
.use_value_delimiter(true)
|
||||
.help(
|
||||
"Specify HTTP headers (ex: -H Header:val 'stuff: things')",
|
||||
"Specify HTTP headers to be used in each request (ex: -H Header:val -H 'stuff: things')",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("queries")
|
||||
.short("Q")
|
||||
Arg::new("cookies")
|
||||
.short('b')
|
||||
.long("cookies")
|
||||
.value_name("COOKIE")
|
||||
.num_args(1..)
|
||||
.action(ArgAction::Append)
|
||||
.use_value_delimiter(true)
|
||||
.help_heading("Request settings")
|
||||
.help(
|
||||
"Specify HTTP cookies to be used in each request (ex: -b stuff=things)",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("queries")
|
||||
.short('Q')
|
||||
.long("query")
|
||||
.value_name("QUERY")
|
||||
.takes_value(true)
|
||||
.multiple(true)
|
||||
.use_delimiter(true)
|
||||
.num_args(1..)
|
||||
.action(ArgAction::Append)
|
||||
.use_value_delimiter(true)
|
||||
.help_heading("Request settings")
|
||||
.help(
|
||||
"Specify URL query parameters (ex: -Q token=stuff -Q secret=key)",
|
||||
"Request's URL query parameters (ex: -Q token=stuff -Q secret=key)",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("no_recursion")
|
||||
.short("n")
|
||||
.long("no-recursion")
|
||||
.takes_value(false)
|
||||
.help("Do not scan recursively")
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("add_slash")
|
||||
.short("f")
|
||||
Arg::new("add_slash")
|
||||
.short('f')
|
||||
.long("add-slash")
|
||||
.takes_value(false)
|
||||
.help("Append / to each request")
|
||||
)
|
||||
.help_heading("Request settings")
|
||||
.num_args(0)
|
||||
.help("Append / to each request's URL")
|
||||
);
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// group - request filters
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
let app = app.arg(
|
||||
Arg::new("url_denylist")
|
||||
.long("dont-scan")
|
||||
.value_name("URL")
|
||||
.num_args(1..)
|
||||
.action(ArgAction::Append)
|
||||
.use_value_delimiter(true)
|
||||
.help_heading("Request filters")
|
||||
.help("URL(s) or Regex Pattern(s) to exclude from recursion/scans"),
|
||||
);
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// group - response filters
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
let app = app
|
||||
.arg(
|
||||
Arg::with_name("stdin")
|
||||
.long("stdin")
|
||||
.takes_value(false)
|
||||
.help("Read url(s) from STDIN")
|
||||
.conflicts_with("url")
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("filter_size")
|
||||
.short("S")
|
||||
Arg::new("filter_size")
|
||||
.short('S')
|
||||
.long("filter-size")
|
||||
.value_name("SIZE")
|
||||
.takes_value(true)
|
||||
.multiple(true)
|
||||
.use_delimiter(true)
|
||||
.num_args(1..)
|
||||
.action(ArgAction::Append)
|
||||
.use_value_delimiter(true)
|
||||
.help_heading("Response filters")
|
||||
.help(
|
||||
"Filter out messages of a particular size (ex: -S 5120 -S 4927,1970)",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("filter_regex")
|
||||
.short("X")
|
||||
Arg::new("filter_regex")
|
||||
.short('X')
|
||||
.long("filter-regex")
|
||||
.value_name("REGEX")
|
||||
.takes_value(true)
|
||||
.multiple(true)
|
||||
.use_delimiter(true)
|
||||
.num_args(1..)
|
||||
.action(ArgAction::Append)
|
||||
.use_value_delimiter(true)
|
||||
.help_heading("Response filters")
|
||||
.help(
|
||||
"Filter out messages via regular expression matching on the response's body (ex: -X '^ignore me$')",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("filter_words")
|
||||
.short("W")
|
||||
Arg::new("filter_words")
|
||||
.short('W')
|
||||
.long("filter-words")
|
||||
.value_name("WORDS")
|
||||
.takes_value(true)
|
||||
.multiple(true)
|
||||
.use_delimiter(true)
|
||||
.num_args(1..)
|
||||
.action(ArgAction::Append)
|
||||
.use_value_delimiter(true)
|
||||
.help_heading("Response filters")
|
||||
.help(
|
||||
"Filter out messages of a particular word count (ex: -W 312 -W 91,82)",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("filter_lines")
|
||||
.short("N")
|
||||
Arg::new("filter_lines")
|
||||
.short('N')
|
||||
.long("filter-lines")
|
||||
.value_name("LINES")
|
||||
.takes_value(true)
|
||||
.multiple(true)
|
||||
.use_delimiter(true)
|
||||
.num_args(1..)
|
||||
.action(ArgAction::Append)
|
||||
.use_value_delimiter(true)
|
||||
.help_heading("Response filters")
|
||||
.help(
|
||||
"Filter out messages of a particular line count (ex: -N 20 -N 31,30)",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("filter_status")
|
||||
.short("C")
|
||||
Arg::new("filter_status")
|
||||
.short('C')
|
||||
.long("filter-status")
|
||||
.value_name("STATUS_CODE")
|
||||
.takes_value(true)
|
||||
.multiple(true)
|
||||
.use_delimiter(true)
|
||||
.num_args(1..)
|
||||
.action(ArgAction::Append)
|
||||
.use_value_delimiter(true)
|
||||
.conflicts_with("status_codes")
|
||||
.help_heading("Response filters")
|
||||
.help(
|
||||
"Filter out status codes (deny list) (ex: -C 200 -C 401)",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("filter_similar")
|
||||
Arg::new("filter_similar")
|
||||
.long("filter-similar-to")
|
||||
.value_name("UNWANTED_PAGE")
|
||||
.takes_value(true)
|
||||
.multiple(true)
|
||||
.use_delimiter(true)
|
||||
.num_args(1..)
|
||||
.action(ArgAction::Append)
|
||||
.value_hint(ValueHint::Url)
|
||||
.use_value_delimiter(true)
|
||||
.help_heading("Response filters")
|
||||
.help(
|
||||
"Filter out pages that are similar to the given page (ex. --filter-similar-to http://site.xyz/soft404)",
|
||||
),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("extract_links")
|
||||
.short("e")
|
||||
.long("extract-links")
|
||||
.takes_value(false)
|
||||
.help("Extract links from response body (html, javascript, etc...); make new requests based on findings (default: false)")
|
||||
Arg::new("status_codes")
|
||||
.short('s')
|
||||
.long("status-codes")
|
||||
.value_name("STATUS_CODE")
|
||||
.num_args(1..)
|
||||
.action(ArgAction::Append)
|
||||
.use_value_delimiter(true)
|
||||
.help_heading("Response filters")
|
||||
.help(
|
||||
"Status Codes to include (allow list) (default: 200 204 301 302 307 308 401 403 405)",
|
||||
),
|
||||
);
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// group - client settings
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
let app = app
|
||||
.arg(
|
||||
Arg::new("timeout")
|
||||
.short('T')
|
||||
.long("timeout")
|
||||
.value_name("SECONDS")
|
||||
.num_args(1)
|
||||
.help_heading("Client settings")
|
||||
.help("Number of seconds before a client's request times out (default: 7)"),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("scan_limit")
|
||||
.short("L")
|
||||
Arg::new("redirects")
|
||||
.short('r')
|
||||
.long("redirects")
|
||||
.num_args(0)
|
||||
.help_heading("Client settings")
|
||||
.help("Allow client to follow redirects"),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("insecure")
|
||||
.short('k')
|
||||
.long("insecure")
|
||||
.num_args(0)
|
||||
.help_heading("Client settings")
|
||||
.help("Disables TLS certificate validation in the client"),
|
||||
);
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// group - scan settings
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
let app = app
|
||||
.arg(
|
||||
Arg::new("threads")
|
||||
.short('t')
|
||||
.long("threads")
|
||||
.value_name("THREADS")
|
||||
.num_args(1)
|
||||
.help_heading("Scan settings")
|
||||
.help("Number of concurrent threads (default: 50)"),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("no_recursion")
|
||||
.short('n')
|
||||
.long("no-recursion")
|
||||
.num_args(0)
|
||||
.help_heading("Scan settings")
|
||||
.help("Do not scan recursively"),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("depth")
|
||||
.short('d')
|
||||
.long("depth")
|
||||
.value_name("RECURSION_DEPTH")
|
||||
.num_args(1)
|
||||
.help_heading("Scan settings")
|
||||
.help("Maximum recursion depth, a depth of 0 is infinite recursion (default: 4)"),
|
||||
).arg(
|
||||
Arg::new("force_recursion")
|
||||
.long("force-recursion")
|
||||
.num_args(0)
|
||||
.conflicts_with("no_recursion")
|
||||
.help_heading("Scan settings")
|
||||
.help("Force recursion attempts on all 'found' endpoints (still respects recursion depth)"),
|
||||
).arg(
|
||||
Arg::new("extract_links")
|
||||
.short('e')
|
||||
.long("extract-links")
|
||||
.num_args(0)
|
||||
.help_heading("Scan settings")
|
||||
.help("Extract links from response body (html, javascript, etc...); make new requests based on findings")
|
||||
)
|
||||
.arg(
|
||||
Arg::new("scan_limit")
|
||||
.short('L')
|
||||
.long("scan-limit")
|
||||
.value_name("SCAN_LIMIT")
|
||||
.takes_value(true)
|
||||
.num_args(1)
|
||||
.help_heading("Scan settings")
|
||||
.help("Limit total number of concurrent scans (default: 0, i.e. no limit)")
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("parallel")
|
||||
Arg::new("parallel")
|
||||
.long("parallel")
|
||||
.value_name("PARALLEL_SCANS")
|
||||
.takes_value(true)
|
||||
.num_args(1)
|
||||
.requires("stdin")
|
||||
.help_heading("Scan settings")
|
||||
.help("Run parallel feroxbuster instances (one child process per url passed via stdin)")
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("rate_limit")
|
||||
Arg::new("rate_limit")
|
||||
.long("rate-limit")
|
||||
.value_name("RATE_LIMIT")
|
||||
.takes_value(true)
|
||||
.num_args(1)
|
||||
.conflicts_with("auto_tune")
|
||||
.help_heading("Scan settings")
|
||||
.help("Limit number of requests per second (per directory) (default: 0, i.e. no limit)")
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("time_limit")
|
||||
Arg::new("time_limit")
|
||||
.long("time-limit")
|
||||
.value_name("TIME_SPEC")
|
||||
.takes_value(true)
|
||||
.validator(valid_time_spec)
|
||||
.num_args(1)
|
||||
.value_parser(valid_time_spec)
|
||||
.help_heading("Scan settings")
|
||||
.help("Limit total run time of all scans (ex: --time-limit 10m)")
|
||||
)
|
||||
.group(ArgGroup::with_name("output_files")
|
||||
.args(&["debug_log", "output"])
|
||||
.multiple(true)
|
||||
.arg(
|
||||
Arg::new("wordlist")
|
||||
.short('w')
|
||||
.long("wordlist")
|
||||
.value_hint(ValueHint::FilePath)
|
||||
.value_name("FILE")
|
||||
.help("Path to the wordlist")
|
||||
.help_heading("Scan settings")
|
||||
.num_args(1),
|
||||
).arg(
|
||||
Arg::new("auto_tune")
|
||||
.long("auto-tune")
|
||||
.num_args(0)
|
||||
.conflicts_with("auto_bail")
|
||||
.help_heading("Scan settings")
|
||||
.help("Automatically lower scan rate when an excessive amount of errors are encountered")
|
||||
)
|
||||
.after_help(r#"NOTE:
|
||||
.arg(
|
||||
Arg::new("auto_bail")
|
||||
.long("auto-bail")
|
||||
.num_args(0)
|
||||
.help_heading("Scan settings")
|
||||
.help("Automatically stop scanning when an excessive amount of errors are encountered")
|
||||
).arg(
|
||||
Arg::new("dont_filter")
|
||||
.short('D')
|
||||
.long("dont-filter")
|
||||
.num_args(0)
|
||||
.help_heading("Scan settings")
|
||||
.help("Don't auto-filter wildcard responses")
|
||||
).arg(
|
||||
Arg::new("collect_extensions")
|
||||
.short('E')
|
||||
.long("collect-extensions")
|
||||
.num_args(0)
|
||||
.help_heading("Dynamic collection settings")
|
||||
.help("Automatically discover extensions and add them to --extensions (unless they're in --dont-collect)")
|
||||
).arg(
|
||||
Arg::new("collect_backups")
|
||||
.short('B')
|
||||
.long("collect-backups")
|
||||
.num_args(0)
|
||||
.help_heading("Dynamic collection settings")
|
||||
.help("Automatically request likely backup extensions for \"found\" urls")
|
||||
).arg(
|
||||
Arg::new("collect_words")
|
||||
.short('g')
|
||||
.long("collect-words")
|
||||
.num_args(0)
|
||||
.help_heading("Dynamic collection settings")
|
||||
.help("Automatically discover important words from within responses and add them to the wordlist")
|
||||
).arg(
|
||||
Arg::new("dont_collect")
|
||||
.short('I')
|
||||
.long("dont-collect")
|
||||
.value_name("FILE_EXTENSION")
|
||||
.num_args(1..)
|
||||
.action(ArgAction::Append)
|
||||
.use_value_delimiter(true)
|
||||
.help_heading("Dynamic collection settings")
|
||||
.help(
|
||||
"File extension(s) to Ignore while collecting extensions (only used with --collect-extensions)",
|
||||
),
|
||||
);
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// group - output settings
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
let app = app
|
||||
.arg(
|
||||
Arg::new("verbosity")
|
||||
.short('v')
|
||||
.long("verbosity")
|
||||
.num_args(0)
|
||||
.action(ArgAction::Count)
|
||||
.conflicts_with("silent")
|
||||
.help_heading("Output settings")
|
||||
.help("Increase verbosity level (use -vv or more for greater effect. [CAUTION] 4 -v's is probably too much)"),
|
||||
).arg(
|
||||
Arg::new("silent")
|
||||
.long("silent")
|
||||
.num_args(0)
|
||||
.conflicts_with("quiet")
|
||||
.help_heading("Output settings")
|
||||
.help("Only print URLs + turn off logging (good for piping a list of urls to other commands)")
|
||||
)
|
||||
.arg(
|
||||
Arg::new("quiet")
|
||||
.short('q')
|
||||
.long("quiet")
|
||||
.num_args(0)
|
||||
.help_heading("Output settings")
|
||||
.help("Hide progress bars and banner (good for tmux windows w/ notifications)")
|
||||
)
|
||||
|
||||
.arg(
|
||||
Arg::new("json")
|
||||
.long("json")
|
||||
.num_args(0)
|
||||
.requires("output_files")
|
||||
.help_heading("Output settings")
|
||||
.help("Emit JSON logs to --output and --debug-log instead of normal text")
|
||||
).arg(
|
||||
Arg::new("output")
|
||||
.short('o')
|
||||
.long("output")
|
||||
.value_hint(ValueHint::FilePath)
|
||||
.value_name("FILE")
|
||||
.help_heading("Output settings")
|
||||
.help("Output file to write results to (use w/ --json for JSON entries)")
|
||||
.num_args(1),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("debug_log")
|
||||
.long("debug-log")
|
||||
.value_name("FILE")
|
||||
.value_hint(ValueHint::FilePath)
|
||||
.help_heading("Output settings")
|
||||
.help("Output file to write log entries (use w/ --json for JSON entries)")
|
||||
.num_args(1),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("no_state")
|
||||
.long("no-state")
|
||||
.num_args(0)
|
||||
.help_heading("Output settings")
|
||||
.help("Disable state output file (*.state)")
|
||||
);
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// group - miscellaneous
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
let mut app = app
|
||||
.group(
|
||||
ArgGroup::new("output_files")
|
||||
.args(["debug_log", "output"])
|
||||
.multiple(true),
|
||||
)
|
||||
.after_long_help(EPILOGUE);
|
||||
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// end parser
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
for arg in env::args() {
|
||||
// secure-77 noticed that when an incorrect flag/option is used, the short help message is printed
|
||||
// which is fine, but if you add -h|--help, it still errors out on the bad flag/option,
|
||||
// never showing the full help message. This code addresses that behavior
|
||||
if arg == "--help" {
|
||||
app.print_long_help().unwrap();
|
||||
println!(); // just a newline to mirror original --help output
|
||||
process::exit(0);
|
||||
} else if arg == "-h" {
|
||||
// same for -h, just shorter
|
||||
app.print_help().unwrap();
|
||||
println!();
|
||||
process::exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
app
|
||||
}
|
||||
|
||||
/// Validate that a string is formatted as a number followed by s, m, h, or d (10d, 30s, etc...)
|
||||
fn valid_time_spec(time_spec: &str) -> Result<String, String> {
|
||||
match TIMESPEC_REGEX.is_match(time_spec) {
|
||||
true => Ok(time_spec.to_string()),
|
||||
false => {
|
||||
let msg = format!(
|
||||
"Expected a non-negative, whole number followed by s, m, h, or d (case insensitive); received {}",
|
||||
time_spec
|
||||
);
|
||||
Err(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const EPILOGUE: &str = r#"NOTE:
|
||||
Options that take multiple values are very flexible. Consider the following ways of specifying
|
||||
extensions:
|
||||
./feroxbuster -u http://127.1 -x pdf -x js,html -x php txt json,docx
|
||||
@@ -418,7 +666,7 @@ EXAMPLES:
|
||||
cat targets | ./feroxbuster --stdin --silent -s 200 301 302 --redirects -x js | fff -s 200 -o js-files
|
||||
|
||||
Proxy traffic through Burp
|
||||
./feroxbuster -u http://127.1 --insecure --proxy http://127.0.0.1:8080
|
||||
./feroxbuster -u http://127.1 --burp
|
||||
|
||||
Proxy traffic through a SOCKS proxy
|
||||
./feroxbuster -u http://127.1 --proxy socks5://127.0.0.1:9050
|
||||
@@ -430,36 +678,21 @@ EXAMPLES:
|
||||
./feroxbuster -u http://127.1 --extract-links
|
||||
|
||||
Ludicrous speed... go!
|
||||
./feroxbuster -u http://127.1 -t 200
|
||||
"#);
|
||||
|
||||
for arg in env::args() {
|
||||
// secure-77 noticed that when an incorrect flag/option is used, the short help message is printed
|
||||
// which is fine, but if you add -h|--help, it still errors out on the bad flag/option,
|
||||
// never showing the full help message. This code addresses that behavior
|
||||
if arg == "--help" || arg == "-h" {
|
||||
app.print_long_help().unwrap();
|
||||
println!(); // just a newline to mirror original --help output
|
||||
process::exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
app
|
||||
}
|
||||
|
||||
/// Validate that a string is formatted as a number followed by s, m, h, or d (10d, 30s, etc...)
|
||||
fn valid_time_spec(time_spec: String) -> Result<(), String> {
|
||||
match TIMESPEC_REGEX.is_match(&time_spec) {
|
||||
true => Ok(()),
|
||||
false => {
|
||||
let msg = format!(
|
||||
"Expected a non-negative, whole number followed by s, m, h, or d (case insensitive); received {}",
|
||||
time_spec
|
||||
);
|
||||
Err(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
./feroxbuster -u http://127.1 --threads 200
|
||||
|
||||
Limit to a total of 60 active requests at any given time (threads * scan limit)
|
||||
./feroxbuster -u http://127.1 --threads 30 --scan-limit 2
|
||||
|
||||
Send all 200/302 responses to a proxy (only proxy requests/responses you care about)
|
||||
./feroxbuster -u http://127.1 --replay-proxy http://localhost:8080 --replay-codes 200 302 --insecure
|
||||
|
||||
Abort or reduce scan speed to individual directory scans when too many errors have occurred
|
||||
./feroxbuster -u http://127.1 --auto-bail
|
||||
./feroxbuster -u http://127.1 --auto-tune
|
||||
|
||||
Examples and demonstrations of all features
|
||||
https://epi052.github.io/feroxbuster-docs/docs/examples/
|
||||
"#;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -479,29 +712,29 @@ mod tests {
|
||||
/// that i didn't hose up the regex. Going to consolidate them into a single test
|
||||
fn validate_valid_time_spec_validation() {
|
||||
let float_rejected = "1.4m";
|
||||
assert!(valid_time_spec(float_rejected.into()).is_err());
|
||||
assert!(valid_time_spec(float_rejected).is_err());
|
||||
|
||||
let negative_rejected = "-1m";
|
||||
assert!(valid_time_spec(negative_rejected.into()).is_err());
|
||||
assert!(valid_time_spec(negative_rejected).is_err());
|
||||
|
||||
let only_number_rejected = "1";
|
||||
assert!(valid_time_spec(only_number_rejected.into()).is_err());
|
||||
assert!(valid_time_spec(only_number_rejected).is_err());
|
||||
|
||||
let only_measurement_rejected = "m";
|
||||
assert!(valid_time_spec(only_measurement_rejected.into()).is_err());
|
||||
assert!(valid_time_spec(only_measurement_rejected).is_err());
|
||||
|
||||
for accepted_measurement in &["s", "m", "h", "d", "S", "M", "H", "D"] {
|
||||
// all upper/lowercase should be good
|
||||
assert!(valid_time_spec(format!("1{}", *accepted_measurement)).is_ok());
|
||||
assert!(valid_time_spec(&format!("1{}", *accepted_measurement)).is_ok());
|
||||
}
|
||||
|
||||
let leading_space_rejected = " 14m";
|
||||
assert!(valid_time_spec(leading_space_rejected.into()).is_err());
|
||||
assert!(valid_time_spec(leading_space_rejected).is_err());
|
||||
|
||||
let trailing_space_rejected = "14m ";
|
||||
assert!(valid_time_spec(trailing_space_rejected.into()).is_err());
|
||||
assert!(valid_time_spec(trailing_space_rejected).is_err());
|
||||
|
||||
let space_between_rejected = "1 4m";
|
||||
assert!(valid_time_spec(space_between_rejected.into()).is_err());
|
||||
assert!(valid_time_spec(space_between_rejected).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,10 +35,11 @@ pub fn add_bar(prefix: &str, length: u64, bar_type: BarType) -> ProgressBar {
|
||||
|
||||
style = match bar_type {
|
||||
BarType::Hidden => style.template(""),
|
||||
BarType::Default => style
|
||||
.template("[{bar:.cyan/blue}] - {elapsed:<4} {pos:>7}/{len:7} {per_sec:7} {prefix}"),
|
||||
BarType::Default => style.template(
|
||||
"[{bar:.cyan/blue}] - {elapsed:<4} {pos:>7}/{len:7} {per_sec:7} {prefix} {msg}",
|
||||
),
|
||||
BarType::Message => style.template(&format!(
|
||||
"[{{bar:.cyan/blue}}] - {{elapsed:<4}} {{pos:>7}}/{{len:7}} {:7} {{prefix}}",
|
||||
"[{{bar:.cyan/blue}}] - {{elapsed:<4}} {{pos:>7}}/{{len:7}} {:7} {{prefix}} {{msg}}",
|
||||
"-"
|
||||
)),
|
||||
BarType::Total => {
|
||||
|
||||
296
src/response.rs
296
src/response.rs
@@ -7,9 +7,10 @@ use std::{
|
||||
};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use console::style;
|
||||
use reqwest::{
|
||||
header::{HeaderMap, HeaderName, HeaderValue},
|
||||
Response, StatusCode, Url,
|
||||
Method, Response, StatusCode, Url,
|
||||
};
|
||||
use serde::ser::SerializeStruct;
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
@@ -36,6 +37,9 @@ pub struct FeroxResponse {
|
||||
/// The `StatusCode` of this `FeroxResponse`
|
||||
status: StatusCode,
|
||||
|
||||
/// The HTTP Request `Method` of this `FeroxResponse`
|
||||
method: Method,
|
||||
|
||||
/// The full response text
|
||||
text: String,
|
||||
|
||||
@@ -56,6 +60,9 @@ pub struct FeroxResponse {
|
||||
|
||||
/// whether the user passed --quiet|--silent on the command line
|
||||
pub(crate) output_level: OutputLevel,
|
||||
|
||||
/// Url's file extension, if one exists
|
||||
pub(crate) extension: Option<String>,
|
||||
}
|
||||
|
||||
/// implement Default trait for FeroxResponse
|
||||
@@ -66,6 +73,7 @@ impl Default for FeroxResponse {
|
||||
url: Url::parse("http://localhost").unwrap(),
|
||||
original_url: "".to_string(),
|
||||
status: Default::default(),
|
||||
method: Method::default(),
|
||||
text: "".to_string(),
|
||||
content_length: 0,
|
||||
line_count: 0,
|
||||
@@ -73,6 +81,7 @@ impl Default for FeroxResponse {
|
||||
headers: Default::default(),
|
||||
wildcard: false,
|
||||
output_level: Default::default(),
|
||||
extension: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -83,8 +92,9 @@ impl fmt::Display for FeroxResponse {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"FeroxResponse {{ url: {}, status: {}, content-length: {} }}",
|
||||
"FeroxResponse {{ url: {}, method: {}, status: {}, content-length: {} }}",
|
||||
self.url(),
|
||||
self.method(),
|
||||
self.status(),
|
||||
self.content_length()
|
||||
)
|
||||
@@ -98,6 +108,11 @@ impl FeroxResponse {
|
||||
&self.status
|
||||
}
|
||||
|
||||
/// Get the `Method` of this `FeroxResponse`
|
||||
pub fn method(&self) -> &Method {
|
||||
&self.method
|
||||
}
|
||||
|
||||
/// Get the `wildcard` of this `FeroxResponse`
|
||||
pub fn wildcard(&self) -> bool {
|
||||
self.wildcard
|
||||
@@ -193,7 +208,7 @@ impl FeroxResponse {
|
||||
pub async fn from(
|
||||
response: Response,
|
||||
original_url: &str,
|
||||
read_body: bool,
|
||||
method: &str,
|
||||
output_level: OutputLevel,
|
||||
) -> Self {
|
||||
let url = response.url().clone();
|
||||
@@ -201,21 +216,12 @@ impl FeroxResponse {
|
||||
let headers = response.headers().clone();
|
||||
let content_length = response.content_length().unwrap_or(0);
|
||||
|
||||
let text = if read_body {
|
||||
// .text() consumes the response, must be called last
|
||||
// additionally, --extract-links is currently the only place we use the body of the
|
||||
// response, so we forego the processing if not performing extraction
|
||||
match response.text().await {
|
||||
// await the response's body
|
||||
Ok(text) => text,
|
||||
Err(e) => {
|
||||
log::warn!("Could not parse body from response: {}", e);
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
// .text() consumes the response, must be called last
|
||||
let text = response
|
||||
.text()
|
||||
.await
|
||||
.with_context(|| "Could not parse body from response")
|
||||
.unwrap_or_default();
|
||||
|
||||
let line_count = text.lines().count();
|
||||
let word_count = text.lines().map(|s| s.split_whitespace().count()).sum();
|
||||
@@ -224,6 +230,7 @@ impl FeroxResponse {
|
||||
url,
|
||||
original_url: original_url.to_string(),
|
||||
status,
|
||||
method: Method::from_bytes(method.as_bytes()).unwrap_or(Method::GET),
|
||||
content_length,
|
||||
text,
|
||||
headers,
|
||||
@@ -231,9 +238,67 @@ impl FeroxResponse {
|
||||
word_count,
|
||||
output_level,
|
||||
wildcard: false,
|
||||
extension: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// if --collect-extensions is used, examine the response's url and grab the file's extension
|
||||
/// if one is available to be grabbed. If an extension is found, send it to the ScanHandler
|
||||
/// for further processing
|
||||
pub(crate) fn parse_extension(&mut self, handles: Arc<Handles>) -> Result<()> {
|
||||
log::trace!("enter: parse_extension");
|
||||
|
||||
if !handles.config.collect_extensions {
|
||||
// early return, --collect-extensions not used
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// path_segments:
|
||||
// Return None for cannot-be-a-base URLs.
|
||||
// When Some is returned, the iterator always contains at least one string
|
||||
// (which may be empty).
|
||||
//
|
||||
// meaning: the two unwraps here are fine, the worst outcome is an empty string
|
||||
let filename = self.url.path_segments().unwrap().last().unwrap();
|
||||
|
||||
if !filename.is_empty() {
|
||||
// non-empty string, try to get extension
|
||||
let parts: Vec<_> = filename
|
||||
.split('.')
|
||||
// keep things like /.bash_history from becoming an extension
|
||||
.filter(|part| !part.is_empty())
|
||||
.collect();
|
||||
|
||||
if parts.len() > 1 {
|
||||
// filename + at least one extension, i.e. whatever.js becomes ["whatever", "js"]
|
||||
self.extension = Some(parts.last().unwrap().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(extension) = &self.extension {
|
||||
if handles
|
||||
.config
|
||||
.status_codes
|
||||
.contains(&self.status().as_u16()) // in -s list
|
||||
// or -C was used, and -s should be all responses that aren't filtered
|
||||
|| !handles.config.filter_status.is_empty()
|
||||
{
|
||||
// only add extensions to those responses that pass our checks; filtered out
|
||||
// status codes are handled by should_filter, but we need to still check against
|
||||
// the allow list for what we want to keep
|
||||
#[cfg(test)]
|
||||
handles
|
||||
.send_scan_command(Command::AddDiscoveredExtension(extension.to_owned()))
|
||||
.unwrap_or_default();
|
||||
#[cfg(not(test))]
|
||||
handles.send_scan_command(Command::AddDiscoveredExtension(extension.to_owned()))?;
|
||||
}
|
||||
}
|
||||
|
||||
log::trace!("exit: parse_extension");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Helper function that determines if the configured maximum recursion depth has been reached
|
||||
///
|
||||
/// Essentially looks at the Url path and determines how many directories are present in the
|
||||
@@ -336,16 +401,53 @@ impl FeroxSerialize for FeroxResponse {
|
||||
let words = self.word_count().to_string();
|
||||
let chars = self.content_length().to_string();
|
||||
let status = self.status().as_str();
|
||||
let method = self.method().as_str();
|
||||
let wild_status = status_colorizer("WLD");
|
||||
|
||||
let mut url_with_redirect = match (
|
||||
self.status().is_redirection(),
|
||||
self.headers().get("Location").is_some(),
|
||||
) {
|
||||
(true, true) => {
|
||||
// redirect with Location header, show where it goes if possible
|
||||
let loc = self
|
||||
.headers()
|
||||
.get("Location")
|
||||
.unwrap() // known Some() already
|
||||
.to_str()
|
||||
.unwrap_or("Unknown")
|
||||
.to_string();
|
||||
|
||||
let loc = if loc.starts_with('/') {
|
||||
if let Ok(joined) = self.url().join(&loc) {
|
||||
joined.to_string()
|
||||
} else {
|
||||
loc
|
||||
}
|
||||
} else {
|
||||
loc
|
||||
};
|
||||
|
||||
// prettify the redirect target
|
||||
let loc = style(loc).yellow();
|
||||
|
||||
format!("{} => {loc}", self.url())
|
||||
}
|
||||
_ => {
|
||||
// no redirect, just use the normal url
|
||||
self.url().to_string()
|
||||
}
|
||||
};
|
||||
|
||||
if self.wildcard && matches!(self.output_level, OutputLevel::Default | OutputLevel::Quiet) {
|
||||
// --silent was not used and response is a wildcard, special messages abound when
|
||||
// this is the case...
|
||||
|
||||
// create the base message
|
||||
let mut message = format!(
|
||||
"{} {:>8}l {:>8}w {:>8}c Got {} for {} (url length: {})\n",
|
||||
"{} {:>8} {:>8}l {:>8}w {:>8}c Got {} for {} (url length: {})\n",
|
||||
wild_status,
|
||||
method,
|
||||
lines,
|
||||
words,
|
||||
chars,
|
||||
@@ -355,34 +457,26 @@ impl FeroxSerialize for FeroxResponse {
|
||||
);
|
||||
|
||||
if self.status().is_redirection() {
|
||||
// when it's a redirect, show where it goes, if possible
|
||||
if let Some(next_loc) = self.headers().get("Location") {
|
||||
let next_loc_str = next_loc.to_str().unwrap_or("Unknown");
|
||||
// initial wildcard messages are wordy enough, put the redirect by itself
|
||||
url_with_redirect = format!(
|
||||
"{} {:>9} {:>9} {:>9} {}\n",
|
||||
wild_status, "-", "-", "-", url_with_redirect
|
||||
);
|
||||
|
||||
let redirect_msg = format!(
|
||||
"{} {:>9} {:>9} {:>9} {} redirects to => {}\n",
|
||||
wild_status,
|
||||
"-",
|
||||
"-",
|
||||
"-",
|
||||
self.url(),
|
||||
next_loc_str
|
||||
);
|
||||
|
||||
message.push_str(&redirect_msg);
|
||||
}
|
||||
// base message + redirection message (either empty string or redir msg)
|
||||
message.push_str(&url_with_redirect);
|
||||
}
|
||||
|
||||
// base message + redirection message (if appropriate)
|
||||
message
|
||||
} else {
|
||||
// not a wildcard, just create a normal entry
|
||||
utils::create_report_string(
|
||||
self.status.as_str(),
|
||||
method,
|
||||
&lines,
|
||||
&words,
|
||||
&chars,
|
||||
self.url().as_str(),
|
||||
&url_with_redirect,
|
||||
self.output_level,
|
||||
)
|
||||
}
|
||||
@@ -448,10 +542,15 @@ impl Serialize for FeroxResponse {
|
||||
state.serialize_field("path", self.url.path())?;
|
||||
state.serialize_field("wildcard", &self.wildcard)?;
|
||||
state.serialize_field("status", &self.status.as_u16())?;
|
||||
state.serialize_field("method", &self.method.as_str())?;
|
||||
state.serialize_field("content_length", &self.content_length)?;
|
||||
state.serialize_field("line_count", &self.line_count)?;
|
||||
state.serialize_field("word_count", &self.word_count)?;
|
||||
state.serialize_field("headers", &headers)?;
|
||||
state.serialize_field(
|
||||
"extension",
|
||||
self.extension.as_ref().unwrap_or(&String::new()),
|
||||
)?;
|
||||
|
||||
state.end()
|
||||
}
|
||||
@@ -468,6 +567,7 @@ impl<'de> Deserialize<'de> for FeroxResponse {
|
||||
url: Url::parse("http://localhost").unwrap(),
|
||||
original_url: String::new(),
|
||||
status: StatusCode::OK,
|
||||
method: Method::GET,
|
||||
text: String::new(),
|
||||
content_length: 0,
|
||||
headers: HeaderMap::new(),
|
||||
@@ -475,6 +575,7 @@ impl<'de> Deserialize<'de> for FeroxResponse {
|
||||
output_level: Default::default(),
|
||||
line_count: 0,
|
||||
word_count: 0,
|
||||
extension: None,
|
||||
};
|
||||
|
||||
let map: HashMap<String, Value> = HashMap::deserialize(deserializer)?;
|
||||
@@ -502,6 +603,11 @@ impl<'de> Deserialize<'de> for FeroxResponse {
|
||||
}
|
||||
}
|
||||
}
|
||||
"method" => {
|
||||
if let Some(method) = value.as_str() {
|
||||
response.method = Method::from_bytes(method.as_bytes()).unwrap_or_default();
|
||||
}
|
||||
}
|
||||
"content_length" => {
|
||||
if let Some(num) = value.as_u64() {
|
||||
response.content_length = num;
|
||||
@@ -538,6 +644,11 @@ impl<'de> Deserialize<'de> for FeroxResponse {
|
||||
response.wildcard = result;
|
||||
}
|
||||
}
|
||||
"extension" => {
|
||||
if let Some(result) = value.as_str() {
|
||||
response.extension = Some(result.to_string());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -549,6 +660,8 @@ impl<'de> Deserialize<'de> for FeroxResponse {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::config::Configuration;
|
||||
use std::default::Default;
|
||||
|
||||
#[test]
|
||||
/// call reached_max_depth with max depth of zero, which is infinite recursion, expect false
|
||||
@@ -557,15 +670,7 @@ mod tests {
|
||||
let url = Url::parse("http://localhost").unwrap();
|
||||
let response = FeroxResponse {
|
||||
url,
|
||||
original_url: String::new(),
|
||||
status: Default::default(),
|
||||
text: "".to_string(),
|
||||
content_length: 0,
|
||||
line_count: 0,
|
||||
word_count: 0,
|
||||
headers: Default::default(),
|
||||
wildcard: false,
|
||||
output_level: Default::default(),
|
||||
..Default::default()
|
||||
};
|
||||
let result = response.reached_max_depth(0, 0, handles);
|
||||
assert!(!result);
|
||||
@@ -579,15 +684,7 @@ mod tests {
|
||||
let url = Url::parse("http://localhost/one/two").unwrap();
|
||||
let response = FeroxResponse {
|
||||
url,
|
||||
original_url: String::new(),
|
||||
status: Default::default(),
|
||||
text: "".to_string(),
|
||||
content_length: 0,
|
||||
line_count: 0,
|
||||
word_count: 0,
|
||||
headers: Default::default(),
|
||||
wildcard: false,
|
||||
output_level: Default::default(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let result = response.reached_max_depth(0, 2, handles);
|
||||
@@ -601,15 +698,7 @@ mod tests {
|
||||
let url = Url::parse("http://localhost").unwrap();
|
||||
let response = FeroxResponse {
|
||||
url,
|
||||
original_url: String::new(),
|
||||
status: Default::default(),
|
||||
text: "".to_string(),
|
||||
content_length: 0,
|
||||
line_count: 0,
|
||||
word_count: 0,
|
||||
headers: Default::default(),
|
||||
wildcard: false,
|
||||
output_level: Default::default(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let result = response.reached_max_depth(0, 2, handles);
|
||||
@@ -623,15 +712,7 @@ mod tests {
|
||||
let url = Url::parse("http://localhost/one/two").unwrap();
|
||||
let response = FeroxResponse {
|
||||
url,
|
||||
original_url: String::new(),
|
||||
status: Default::default(),
|
||||
text: "".to_string(),
|
||||
content_length: 0,
|
||||
line_count: 0,
|
||||
word_count: 0,
|
||||
headers: Default::default(),
|
||||
wildcard: false,
|
||||
output_level: Default::default(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let result = response.reached_max_depth(2, 2, handles);
|
||||
@@ -645,18 +726,71 @@ mod tests {
|
||||
let url = Url::parse("http://localhost/one/two/three").unwrap();
|
||||
let response = FeroxResponse {
|
||||
url,
|
||||
original_url: String::new(),
|
||||
status: Default::default(),
|
||||
text: "".to_string(),
|
||||
content_length: 0,
|
||||
line_count: 0,
|
||||
word_count: 0,
|
||||
headers: Default::default(),
|
||||
wildcard: false,
|
||||
output_level: Default::default(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let result = response.reached_max_depth(0, 2, handles);
|
||||
assert!(result);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// simple case of a single extension gets parsed correctly and stored on the `FeroxResponse`
|
||||
fn parse_extension_finds_simple_extension() {
|
||||
let config = Configuration {
|
||||
collect_extensions: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let (handles, _) = Handles::for_testing(None, Some(Arc::new(config)));
|
||||
|
||||
let url = Url::parse("http://localhost/derp.js").unwrap();
|
||||
|
||||
let mut response = FeroxResponse {
|
||||
url,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
response.parse_extension(Arc::new(handles)).unwrap();
|
||||
|
||||
assert_eq!(response.extension, Some(String::from("js")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// hidden files shouldn't be parsed as extensions, i.e. `/.bash_history`
|
||||
fn parse_extension_ignores_hidden_files() {
|
||||
let config = Configuration {
|
||||
collect_extensions: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let (handles, _) = Handles::for_testing(None, Some(Arc::new(config)));
|
||||
|
||||
let url = Url::parse("http://localhost/.bash_history").unwrap();
|
||||
|
||||
let mut response = FeroxResponse {
|
||||
url,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
response.parse_extension(Arc::new(handles)).unwrap();
|
||||
|
||||
assert_eq!(response.extension, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// `parse_extension` should return immediately if `--collect-extensions` isn't used
|
||||
fn parse_extension_early_returns_based_on_config() {
|
||||
let (handles, _) = Handles::for_testing(None, None);
|
||||
|
||||
let url = Url::parse("http://localhost/derp.js").unwrap();
|
||||
|
||||
let mut response = FeroxResponse {
|
||||
url,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
response.parse_extension(Arc::new(handles)).unwrap();
|
||||
|
||||
assert_eq!(response.extension, None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use crate::filters::filter_lookup;
|
||||
use crate::progress::PROGRESS_BAR;
|
||||
use crate::traits::FeroxFilter;
|
||||
use console::{measure_text_width, pad_str, style, Alignment, Term};
|
||||
use indicatif::ProgressDrawTarget;
|
||||
use regex::Regex;
|
||||
@@ -7,10 +9,16 @@ use regex::Regex;
|
||||
#[derive(Debug)]
|
||||
pub enum MenuCmd {
|
||||
/// user wants to add a url to be scanned
|
||||
Add(String),
|
||||
AddUrl(String),
|
||||
|
||||
/// user wants to cancel one or more active scans
|
||||
Cancel(Vec<usize>, bool),
|
||||
|
||||
/// user wants to create a new filter
|
||||
AddFilter(Box<dyn FeroxFilter>),
|
||||
|
||||
/// user wants to remove one or more active filters
|
||||
RemoveFilter(Vec<usize>),
|
||||
}
|
||||
|
||||
/// Data container for a command result to be used internally by the ferox_scanner
|
||||
@@ -21,6 +29,9 @@ pub enum MenuCmdResult {
|
||||
|
||||
/// Number of scans that were actually cancelled, can be 0
|
||||
NumCancelled(usize),
|
||||
|
||||
/// Filter to be added to current list of `FeroxFilters`
|
||||
Filter(Box<dyn FeroxFilter>),
|
||||
}
|
||||
|
||||
/// Interactive scan cancellation menu
|
||||
@@ -32,6 +43,9 @@ pub(super) struct Menu {
|
||||
/// footer: instructions surrounded by separators
|
||||
footer: String,
|
||||
|
||||
/// unicode line border, matched to longest displayed line
|
||||
border: String,
|
||||
|
||||
/// target for output
|
||||
pub(super) term: Term,
|
||||
}
|
||||
@@ -57,16 +71,44 @@ impl Menu {
|
||||
);
|
||||
|
||||
let canx_cmd = format!(
|
||||
" {}[{}] [-f] SCAN_ID[-SCAN_ID[,...]] (ex: {} 1-4,8,9-13 or {} -f 3)",
|
||||
" {}[{}] [-f] SCAN_ID[-SCAN_ID[,...]] (ex: {} 1-4,8,9-13 or {} -f 3)\n",
|
||||
style("c").red(),
|
||||
style("ancel").red(),
|
||||
style("cancel").red(),
|
||||
style("c").red(),
|
||||
);
|
||||
|
||||
let mut commands = String::from("Commands:\n");
|
||||
let new_filter_cmd = format!(
|
||||
" {}[{}] FILTER_TYPE FILTER_VALUE (ex: {} lines 40)\n",
|
||||
style("n").green(),
|
||||
style("ew-filter").green(),
|
||||
style("n").green(),
|
||||
);
|
||||
|
||||
let valid_filters = format!(
|
||||
" FILTER_TYPEs: {}, {}, {}, {}, {}, {}\n",
|
||||
style("status").yellow(),
|
||||
style("lines").yellow(),
|
||||
style("size").yellow(),
|
||||
style("words").yellow(),
|
||||
style("regex").yellow(),
|
||||
style("similarity").yellow()
|
||||
);
|
||||
|
||||
let rm_filter_cmd = format!(
|
||||
" {}[{}] FILTER_ID[-FILTER_ID[,...]] (ex: {} 1-4,8,9-13 or {} 3)",
|
||||
style("r").red(),
|
||||
style("m-filter").red(),
|
||||
style("rm-filter").red(),
|
||||
style("r").red(),
|
||||
);
|
||||
|
||||
let mut commands = format!("{}:\n", style("Commands").bright().blue());
|
||||
commands.push_str(&add_cmd);
|
||||
commands.push_str(&canx_cmd);
|
||||
commands.push_str(&new_filter_cmd);
|
||||
commands.push_str(&valid_filters);
|
||||
commands.push_str(&rm_filter_cmd);
|
||||
|
||||
let longest = measure_text_width(&canx_cmd).max(measure_text_width(&name));
|
||||
|
||||
@@ -75,11 +117,12 @@ impl Menu {
|
||||
let padded_name = pad_str(&name, longest, Alignment::Center, None);
|
||||
|
||||
let header = format!("{}\n{}\n{}", border, padded_name, border);
|
||||
let footer = format!("{}\n{}\n{}", border, commands, border);
|
||||
let footer = format!("{}\n{}", commands, border);
|
||||
|
||||
Self {
|
||||
header,
|
||||
footer,
|
||||
border,
|
||||
term: Term::stderr(),
|
||||
}
|
||||
}
|
||||
@@ -89,6 +132,11 @@ impl Menu {
|
||||
self.println(&self.header);
|
||||
}
|
||||
|
||||
/// print menu unicode border line
|
||||
pub(super) fn print_border(&self) {
|
||||
self.println(&self.border);
|
||||
}
|
||||
|
||||
/// print menu footer
|
||||
pub(super) fn print_footer(&self) {
|
||||
self.println(&self.footer);
|
||||
@@ -198,7 +246,39 @@ impl Menu {
|
||||
let re = Regex::new(r"^[aA][dD]*").unwrap();
|
||||
let line = re.replace(line, "").to_string().trim().to_string();
|
||||
|
||||
Some(MenuCmd::Add(line))
|
||||
Some(MenuCmd::AddUrl(line))
|
||||
}
|
||||
'n' => {
|
||||
// new filter command
|
||||
let mut line = line.split_whitespace();
|
||||
line.next(); // 'n' or 'new-filter'
|
||||
|
||||
if let Some(filter_type) = line.next() {
|
||||
// have a string in the filter_type position
|
||||
if let Some(filter_value) = line.next() {
|
||||
// have a string in the filter_value position
|
||||
if let Some(result) = filter_lookup(filter_type, filter_value) {
|
||||
// lookup was successful, return the new filter
|
||||
return Some(MenuCmd::AddFilter(result));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
'r' => {
|
||||
// remove filter command
|
||||
|
||||
// remove r[m-filter] from the command so it can be passed to the number
|
||||
// splitter
|
||||
let re = Regex::new(r"^[rR][mfilterMFILTER-]*").unwrap();
|
||||
// we don't respect a -f or lack thereof in this command, but in case the user
|
||||
// doesn't realize / thinks its the same as cancel -f, just remove it
|
||||
let line = line.replace("-f", "");
|
||||
let line = re.replace(&line, "").to_string();
|
||||
|
||||
let indices = self.split_to_nums(&line);
|
||||
|
||||
Some(MenuCmd::RemoveFilter(indices))
|
||||
}
|
||||
_ => {
|
||||
// invalid input
|
||||
|
||||
@@ -45,7 +45,7 @@ impl FeroxResponses {
|
||||
pub fn contains(&self, other: &FeroxResponse) -> bool {
|
||||
if let Ok(responses) = self.responses.read() {
|
||||
for response in responses.iter() {
|
||||
if response.url() == other.url() {
|
||||
if response.url() == other.url() && response.method() == other.method() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,8 +32,11 @@ pub struct FeroxScan {
|
||||
/// The URL that to be scanned
|
||||
pub(super) url: String,
|
||||
|
||||
/// A url used solely for comparison to other URLs
|
||||
pub(super) normalized_url: String,
|
||||
|
||||
/// The type of scan
|
||||
pub(super) scan_type: ScanType,
|
||||
pub scan_type: ScanType,
|
||||
|
||||
/// The order in which the scan was received
|
||||
pub(crate) scan_order: ScanOrder,
|
||||
@@ -42,7 +45,7 @@ pub struct FeroxScan {
|
||||
pub(super) num_requests: u64,
|
||||
|
||||
/// Status of this scan
|
||||
pub(super) status: Mutex<ScanStatus>,
|
||||
pub status: Mutex<ScanStatus>,
|
||||
|
||||
/// The spawned tokio task performing this scan (uses tokio::sync::Mutex)
|
||||
pub(super) task: sync::Mutex<Option<JoinHandle<()>>>,
|
||||
@@ -70,7 +73,7 @@ pub struct FeroxScan {
|
||||
impl Default for FeroxScan {
|
||||
/// Create a default FeroxScan, populates ID with a new UUID
|
||||
fn default() -> Self {
|
||||
let new_id = Uuid::new_v4().to_simple().to_string();
|
||||
let new_id = Uuid::new_v4().as_simple().to_string();
|
||||
|
||||
FeroxScan {
|
||||
id: new_id,
|
||||
@@ -79,6 +82,7 @@ impl Default for FeroxScan {
|
||||
num_requests: 0,
|
||||
scan_order: ScanOrder::Latest,
|
||||
url: String::new(),
|
||||
normalized_url: String::new(),
|
||||
progress_bar: Mutex::new(None),
|
||||
scan_type: ScanType::File,
|
||||
output_level: Default::default(),
|
||||
@@ -191,6 +195,7 @@ impl FeroxScan {
|
||||
) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
url: url.to_string(),
|
||||
normalized_url: format!("{}/", url.trim_end_matches('/')),
|
||||
scan_type,
|
||||
scan_order,
|
||||
num_requests,
|
||||
@@ -228,6 +233,14 @@ impl FeroxScan {
|
||||
false
|
||||
}
|
||||
|
||||
/// small wrapper to inspect ScanStatus and see if it's Cancelled
|
||||
pub fn is_cancelled(&self) -> bool {
|
||||
if let Ok(guard) = self.status.lock() {
|
||||
return matches!(*guard, ScanStatus::Cancelled);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// await a task's completion, similar to a thread's join; perform necessary bookkeeping
|
||||
pub async fn join(&self) {
|
||||
log::trace!("enter join({:?})", self);
|
||||
@@ -332,10 +345,11 @@ impl Serialize for FeroxScan {
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
let mut state = serializer.serialize_struct("FeroxScan", 4)?;
|
||||
let mut state = serializer.serialize_struct("FeroxScan", 6)?;
|
||||
|
||||
state.serialize_field("id", &self.id)?;
|
||||
state.serialize_field("url", &self.url)?;
|
||||
state.serialize_field("normalized_url", &self.normalized_url)?;
|
||||
state.serialize_field("scan_type", &self.scan_type)?;
|
||||
state.serialize_field("status", &self.status)?;
|
||||
state.serialize_field("num_requests", &self.num_requests)?;
|
||||
@@ -387,6 +401,11 @@ impl<'de> Deserialize<'de> for FeroxScan {
|
||||
scan.url = url.to_string();
|
||||
}
|
||||
}
|
||||
"normalized_url" => {
|
||||
if let Some(normalized_url) = value.as_str() {
|
||||
scan.normalized_url = normalized_url.to_string();
|
||||
}
|
||||
}
|
||||
"num_requests" => {
|
||||
if let Some(num_requests) = value.as_u64() {
|
||||
scan.num_requests = num_requests;
|
||||
@@ -480,6 +499,7 @@ mod tests {
|
||||
let scan = FeroxScan {
|
||||
id: "".to_string(),
|
||||
url: "".to_string(),
|
||||
normalized_url: String::from("/"),
|
||||
scan_type: ScanType::Directory,
|
||||
scan_order: ScanOrder::Initial,
|
||||
num_requests: 0,
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
use super::scan::ScanType;
|
||||
use super::*;
|
||||
use crate::event_handlers::Handles;
|
||||
use crate::filters::{
|
||||
EmptyFilter, LinesFilter, RegexFilter, SimilarityFilter, SizeFilter, StatusCodeFilter,
|
||||
WildcardFilter, WordsFilter,
|
||||
};
|
||||
use crate::traits::FeroxFilter;
|
||||
use crate::Command::AddFilter;
|
||||
use crate::{
|
||||
config::OutputLevel,
|
||||
progress::PROGRESS_PRINTER,
|
||||
@@ -7,12 +14,14 @@ use crate::{
|
||||
scan_manager::{MenuCmd, MenuCmdResult},
|
||||
scanner::RESPONSES,
|
||||
traits::FeroxSerialize,
|
||||
SLEEP_DURATION,
|
||||
Command, SLEEP_DURATION,
|
||||
};
|
||||
use anyhow::Result;
|
||||
use console::style;
|
||||
use reqwest::StatusCode;
|
||||
use serde::{ser::SerializeSeq, Serialize, Serializer};
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
convert::TryInto,
|
||||
fs::File,
|
||||
io::BufReader,
|
||||
@@ -47,6 +56,9 @@ pub struct FeroxScans {
|
||||
|
||||
/// whether or not the user passed --silent|--quiet on the command line
|
||||
output_level: OutputLevel,
|
||||
|
||||
/// vector of extensions discovered and collected during scans
|
||||
pub(crate) collected_extensions: RwLock<HashSet<String>>,
|
||||
}
|
||||
|
||||
/// Serialize implementation for FeroxScans
|
||||
@@ -58,17 +70,20 @@ impl Serialize for FeroxScans {
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
if let Ok(scans) = self.scans.read() {
|
||||
let mut seq = serializer.serialize_seq(Some(scans.len()))?;
|
||||
for scan in scans.iter() {
|
||||
seq.serialize_element(&*scan).unwrap_or_default();
|
||||
}
|
||||
match self.scans.read() {
|
||||
Ok(scans) => {
|
||||
let mut seq = serializer.serialize_seq(Some(scans.len() + 1))?;
|
||||
|
||||
seq.end()
|
||||
} else {
|
||||
// if for some reason we can't unlock the RwLock, just write an empty list
|
||||
let seq = serializer.serialize_seq(Some(0))?;
|
||||
seq.end()
|
||||
for scan in scans.iter() {
|
||||
seq.serialize_element(scan).unwrap_or_default();
|
||||
}
|
||||
seq.end()
|
||||
}
|
||||
Err(_) => {
|
||||
// if for some reason we can't unlock the RwLock, just write an empty list
|
||||
let seq = serializer.serialize_seq(Some(0))?;
|
||||
seq.end()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -109,8 +124,8 @@ impl FeroxScans {
|
||||
sentry
|
||||
}
|
||||
|
||||
/// load serialized FeroxScan(s) into this FeroxScans
|
||||
pub fn add_serialized_scans(&self, filename: &str) -> Result<()> {
|
||||
/// load serialized FeroxScan(s) and any previously collected extensions into this FeroxScans
|
||||
pub fn add_serialized_scans(&self, filename: &str, handles: Arc<Handles>) -> Result<()> {
|
||||
log::trace!("enter: add_serialized_scans({})", filename);
|
||||
let file = File::open(filename)?;
|
||||
|
||||
@@ -122,18 +137,83 @@ impl FeroxScans {
|
||||
for scan in arr_scans {
|
||||
let mut deser_scan: FeroxScan =
|
||||
serde_json::from_value(scan.clone()).unwrap_or_default();
|
||||
|
||||
if deser_scan.is_cancelled() {
|
||||
// if the scan was cancelled by the user, mark it as complete. This will
|
||||
// prevent the scan from being resumed as well as prevent the wordlist
|
||||
// from requesting it again
|
||||
if let Ok(mut guard) = deser_scan.status.lock() {
|
||||
*guard = ScanStatus::Complete;
|
||||
}
|
||||
}
|
||||
|
||||
// FeroxScans gets -q value from config as usual; the FeroxScans themselves
|
||||
// rely on that value being passed in. If the user starts a scan without -q
|
||||
// and resumes the scan but adds -q, FeroxScan will not have the proper value
|
||||
// without the line below
|
||||
deser_scan.output_level = self.output_level;
|
||||
|
||||
log::debug!("added: {}", deser_scan);
|
||||
self.insert(Arc::new(deser_scan));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(extensions) = state.get("collected_extensions") {
|
||||
if let Some(arr_exts) = extensions.as_array() {
|
||||
if let Ok(mut guard) = self.collected_extensions.write() {
|
||||
for ext in arr_exts {
|
||||
let deser_ext: String =
|
||||
serde_json::from_value(ext.clone()).unwrap_or_default();
|
||||
|
||||
guard.insert(deser_ext);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(filters) = state.get("filters") {
|
||||
if let Some(arr_filters) = filters.as_array() {
|
||||
for filter in arr_filters {
|
||||
let final_filter: Box<dyn FeroxFilter> = if let Ok(deserialized) =
|
||||
serde_json::from_value::<RegexFilter>(filter.clone())
|
||||
{
|
||||
Box::new(deserialized)
|
||||
} else if let Ok(deserialized) =
|
||||
serde_json::from_value::<WordsFilter>(filter.clone())
|
||||
{
|
||||
Box::new(deserialized)
|
||||
} else if let Ok(deserialized) =
|
||||
serde_json::from_value::<WildcardFilter>(filter.clone())
|
||||
{
|
||||
Box::new(deserialized)
|
||||
} else if let Ok(deserialized) =
|
||||
serde_json::from_value::<SizeFilter>(filter.clone())
|
||||
{
|
||||
Box::new(deserialized)
|
||||
} else if let Ok(deserialized) =
|
||||
serde_json::from_value::<LinesFilter>(filter.clone())
|
||||
{
|
||||
Box::new(deserialized)
|
||||
} else if let Ok(deserialized) =
|
||||
serde_json::from_value::<SimilarityFilter>(filter.clone())
|
||||
{
|
||||
Box::new(deserialized)
|
||||
} else if let Ok(deserialized) =
|
||||
serde_json::from_value::<StatusCodeFilter>(filter.clone())
|
||||
{
|
||||
Box::new(deserialized)
|
||||
} else {
|
||||
Box::new(EmptyFilter {})
|
||||
};
|
||||
|
||||
handles
|
||||
.filters
|
||||
.send(AddFilter(final_filter))
|
||||
.unwrap_or_default();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log::trace!("exit: add_serialized_scans");
|
||||
Ok(())
|
||||
}
|
||||
@@ -142,8 +222,10 @@ impl FeroxScans {
|
||||
/// on the given URL
|
||||
pub fn contains(&self, url: &str) -> bool {
|
||||
if let Ok(scans) = self.scans.read() {
|
||||
let normalized = format!("{}/", url.trim_end_matches('/'));
|
||||
|
||||
for scan in scans.iter() {
|
||||
if scan.url == url {
|
||||
if scan.normalized_url == normalized {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -154,8 +236,10 @@ impl FeroxScans {
|
||||
/// Find and return a `FeroxScan` based on the given URL
|
||||
pub fn get_scan_by_url(&self, url: &str) -> Option<Arc<FeroxScan>> {
|
||||
if let Ok(guard) = self.scans.read() {
|
||||
let normalized = format!("{}/", url.trim_end_matches('/'));
|
||||
|
||||
for scan in guard.iter() {
|
||||
if scan.url == url {
|
||||
if scan.normalized_url == normalized {
|
||||
return Some(scan.clone());
|
||||
}
|
||||
}
|
||||
@@ -163,8 +247,8 @@ impl FeroxScans {
|
||||
None
|
||||
}
|
||||
|
||||
pub(super) fn get_base_scan_by_url(&self, url: &str) -> Option<Arc<FeroxScan>> {
|
||||
log::trace!("enter: get_sub_paths_from_path({})", url);
|
||||
pub fn get_base_scan_by_url(&self, url: &str) -> Option<Arc<FeroxScan>> {
|
||||
log::trace!("enter: get_base_scan_by_url({})", url);
|
||||
|
||||
// rmatch_indices returns tuples in index, match form, i.e. (10, "/")
|
||||
// with the furthest-right match in the first position in the vector
|
||||
@@ -188,14 +272,14 @@ impl FeroxScans {
|
||||
for scan in guard.iter() {
|
||||
let slice = url.index(0..*idx);
|
||||
if slice == scan.url || format!("{}/", slice).as_str() == scan.url {
|
||||
log::trace!("enter: get_sub_paths_from_path -> {}", scan);
|
||||
log::trace!("enter: get_base_scan_by_url -> {}", scan);
|
||||
return Some(scan.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log::trace!("enter: get_sub_paths_from_path -> None");
|
||||
log::trace!("enter: get_base_scan_by_url -> None");
|
||||
None
|
||||
}
|
||||
/// add one to either 403 or 429 tracker in the scan related to the given url
|
||||
@@ -237,6 +321,8 @@ impl FeroxScans {
|
||||
.clone()
|
||||
};
|
||||
|
||||
let mut printed = 0;
|
||||
|
||||
for (i, scan) in scans.iter().enumerate() {
|
||||
if matches!(scan.scan_order, ScanOrder::Initial) || scan.task.try_lock().is_err() {
|
||||
// original target passed in via either -u or --stdin
|
||||
@@ -244,12 +330,21 @@ impl FeroxScans {
|
||||
}
|
||||
|
||||
if matches!(scan.scan_type, ScanType::Directory) {
|
||||
if printed == 0 {
|
||||
self.menu
|
||||
.println(&format!("{}:", style("Scans").bright().blue()));
|
||||
}
|
||||
// we're only interested in displaying directory scans, as those are
|
||||
// the only ones that make sense to be stopped
|
||||
let scan_msg = format!("{:3}: {}", i, scan);
|
||||
self.menu.println(&scan_msg);
|
||||
printed += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if printed > 0 {
|
||||
self.menu.print_border();
|
||||
}
|
||||
}
|
||||
|
||||
/// Given a list of indexes, cancel their associated FeroxScans
|
||||
@@ -300,12 +395,34 @@ impl FeroxScans {
|
||||
num_cancelled
|
||||
}
|
||||
|
||||
fn display_filters(&self, handles: Arc<Handles>) {
|
||||
let mut printed = 0;
|
||||
|
||||
if let Ok(guard) = handles.filters.data.filters.read() {
|
||||
for (i, filter) in guard.iter().enumerate() {
|
||||
if i == 0 {
|
||||
self.menu
|
||||
.println(&format!("{}:", style("Filters").bright().blue()));
|
||||
}
|
||||
|
||||
let filter_msg = format!("{:3}: {}", i + 1, filter);
|
||||
self.menu.println(&filter_msg);
|
||||
printed += 1;
|
||||
}
|
||||
|
||||
if printed > 0 {
|
||||
self.menu.print_border();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// CLI menu that allows for interactive cancellation of recursed-into directories
|
||||
async fn interactive_menu(&self) -> Option<MenuCmdResult> {
|
||||
async fn interactive_menu(&self, handles: Arc<Handles>) -> Option<MenuCmdResult> {
|
||||
self.menu.hide_progress_bars();
|
||||
self.menu.clear_screen();
|
||||
self.menu.print_header();
|
||||
self.display_scans().await;
|
||||
self.display_filters(handles.clone());
|
||||
self.menu.print_footer();
|
||||
|
||||
let menu_cmd = if let Ok(line) = self.menu.term.read_line() {
|
||||
@@ -320,7 +437,15 @@ impl FeroxScans {
|
||||
let num_cancelled = self.cancel_scans(indices, should_force).await;
|
||||
Some(MenuCmdResult::NumCancelled(num_cancelled))
|
||||
}
|
||||
Some(MenuCmd::Add(url)) => Some(MenuCmdResult::Url(url)),
|
||||
Some(MenuCmd::AddUrl(url)) => Some(MenuCmdResult::Url(url)),
|
||||
Some(MenuCmd::AddFilter(filter)) => Some(MenuCmdResult::Filter(filter)),
|
||||
Some(MenuCmd::RemoveFilter(indices)) => {
|
||||
handles
|
||||
.filters
|
||||
.send(Command::RemoveFilters(indices))
|
||||
.unwrap_or_default();
|
||||
None
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
@@ -375,7 +500,11 @@ impl FeroxScans {
|
||||
///
|
||||
/// When the value stored in `PAUSE_SCAN` becomes `false`, the function returns, exiting the busy
|
||||
/// loop
|
||||
pub async fn pause(&self, get_user_input: bool) -> Option<MenuCmdResult> {
|
||||
pub async fn pause(
|
||||
&self,
|
||||
get_user_input: bool,
|
||||
handles: Arc<Handles>,
|
||||
) -> Option<MenuCmdResult> {
|
||||
// function uses tokio::time, not std
|
||||
|
||||
// local testing showed a pretty slow increase (less than linear) in CPU usage as # of
|
||||
@@ -387,7 +516,7 @@ impl FeroxScans {
|
||||
INTERACTIVE_BARRIER.fetch_add(1, Ordering::Relaxed);
|
||||
|
||||
if get_user_input {
|
||||
command_result = self.interactive_menu().await;
|
||||
command_result = self.interactive_menu(handles).await;
|
||||
PAUSE_SCAN.store(false, Ordering::Relaxed);
|
||||
self.print_known_responses();
|
||||
}
|
||||
@@ -473,7 +602,8 @@ impl FeroxScans {
|
||||
///
|
||||
/// Also return a reference to the new `FeroxScan`
|
||||
pub fn add_directory_scan(&self, url: &str, scan_order: ScanOrder) -> (bool, Arc<FeroxScan>) {
|
||||
self.add_scan(url, ScanType::Directory, scan_order)
|
||||
let normalized = format!("{}/", url.trim_end_matches('/'));
|
||||
self.add_scan(&normalized, ScanType::Directory, scan_order)
|
||||
}
|
||||
|
||||
/// Given a url, create a new `FeroxScan` and add it to `FeroxScans` as a File Scan
|
||||
@@ -511,4 +641,67 @@ impl FeroxScans {
|
||||
}
|
||||
scans
|
||||
}
|
||||
|
||||
/// given an extension, add it to `collected_extensions` if all constraints are met
|
||||
/// returns `true` if an extension was added, `false` otherwise
|
||||
pub fn add_discovered_extension(&self, extension: String) -> bool {
|
||||
log::trace!("enter: add_discovered_extension({})", extension);
|
||||
let mut extension_added = false;
|
||||
|
||||
// note: the filter by --dont-collect happens in the event handler, since it has access
|
||||
// to a Handles object form which it can check the config value. additionally, the check
|
||||
// against --extensions is performed there for the same reason
|
||||
|
||||
if let Ok(extensions) = self.collected_extensions.read() {
|
||||
// quicker to allow most to read and return and then reopen for write if necessary
|
||||
if extensions.contains(&extension) {
|
||||
return extension_added;
|
||||
}
|
||||
}
|
||||
|
||||
if let Ok(mut extensions) = self.collected_extensions.write() {
|
||||
log::info!("discovered new extension: {}", extension);
|
||||
extensions.insert(extension);
|
||||
extension_added = true;
|
||||
}
|
||||
|
||||
log::trace!("exit: add_discovered_extension -> {}", extension_added);
|
||||
extension_added
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
/// unknown extension should be added to collected_extensions
|
||||
fn unknown_extension_is_added_to_collected_extensions() {
|
||||
let scans = FeroxScans::new(OutputLevel::Default);
|
||||
|
||||
assert_eq!(0, scans.collected_extensions.read().unwrap().len());
|
||||
|
||||
let added = scans.add_discovered_extension(String::from("js"));
|
||||
|
||||
assert!(added);
|
||||
assert_eq!(1, scans.collected_extensions.read().unwrap().len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// known extension should not be added to collected_extensions
|
||||
fn known_extension_is_added_to_collected_extensions() {
|
||||
let scans = FeroxScans::new(OutputLevel::Default);
|
||||
scans
|
||||
.collected_extensions
|
||||
.write()
|
||||
.unwrap()
|
||||
.insert(String::from("js"));
|
||||
|
||||
assert_eq!(1, scans.collected_extensions.read().unwrap().len());
|
||||
|
||||
let added = scans.add_discovered_extension(String::from("js"));
|
||||
|
||||
assert!(!added);
|
||||
assert_eq!(1, scans.collected_extensions.read().unwrap().len());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
use super::*;
|
||||
use crate::filters::FeroxFilters;
|
||||
use crate::{config::Configuration, statistics::Stats, traits::FeroxSerialize, utils::fmt_err};
|
||||
use anyhow::{Context, Result};
|
||||
use serde::Serialize;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Data container for (de)?serialization of multiple items
|
||||
@@ -18,6 +20,12 @@ pub struct FeroxState {
|
||||
|
||||
/// Gathered statistics
|
||||
statistics: Arc<Stats>,
|
||||
|
||||
/// collected extensions
|
||||
collected_extensions: HashSet<String>,
|
||||
|
||||
/// runtime filters, as they may differ from original config
|
||||
filters: Arc<FeroxFilters>,
|
||||
}
|
||||
|
||||
/// implementation of FeroxState
|
||||
@@ -28,12 +36,20 @@ impl FeroxState {
|
||||
config: Arc<Configuration>,
|
||||
responses: &'static FeroxResponses,
|
||||
statistics: Arc<Stats>,
|
||||
filters: Arc<FeroxFilters>,
|
||||
) -> Self {
|
||||
let collected_extensions = match scans.collected_extensions.read() {
|
||||
Ok(extensions) => extensions.clone(),
|
||||
Err(_) => HashSet::new(),
|
||||
};
|
||||
|
||||
Self {
|
||||
scans,
|
||||
config,
|
||||
responses,
|
||||
statistics,
|
||||
collected_extensions,
|
||||
filters,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
use super::*;
|
||||
use crate::filters::{
|
||||
FeroxFilters, LinesFilter, RegexFilter, SimilarityFilter, SizeFilter, StatusCodeFilter,
|
||||
WordsFilter,
|
||||
};
|
||||
use crate::{
|
||||
config::{Configuration, OutputLevel},
|
||||
event_handlers::Handles,
|
||||
@@ -6,10 +10,11 @@ use crate::{
|
||||
scanner::RESPONSES,
|
||||
statistics::Stats,
|
||||
traits::FeroxSerialize,
|
||||
SLEEP_DURATION, VERSION,
|
||||
SIMILARITY_THRESHOLD, SLEEP_DURATION, VERSION,
|
||||
};
|
||||
use indicatif::ProgressBar;
|
||||
use predicates::prelude::*;
|
||||
use regex::Regex;
|
||||
use std::sync::{atomic::Ordering, Arc};
|
||||
use std::thread::sleep;
|
||||
use std::time::Instant;
|
||||
@@ -31,6 +36,7 @@ fn default_scantype_is_file() {
|
||||
async fn scanner_pause_scan_with_finished_spinner() {
|
||||
let now = time::Instant::now();
|
||||
let urls = FeroxScans::default();
|
||||
let handles = Arc::new(Handles::for_testing(None, None).0);
|
||||
|
||||
PAUSE_SCAN.store(true, Ordering::Relaxed);
|
||||
|
||||
@@ -41,7 +47,7 @@ async fn scanner_pause_scan_with_finished_spinner() {
|
||||
PAUSE_SCAN.store(false, Ordering::Relaxed);
|
||||
});
|
||||
|
||||
urls.pause(false).await;
|
||||
urls.pause(false, handles).await;
|
||||
|
||||
assert!(now.elapsed() > expected);
|
||||
}
|
||||
@@ -271,7 +277,7 @@ fn ferox_scan_serialize() {
|
||||
None,
|
||||
);
|
||||
let fs_json = format!(
|
||||
r#"{{"id":"{}","url":"https://spiritanimal.com","scan_type":"Directory","status":"NotStarted","num_requests":0}}"#,
|
||||
r#"{{"id":"{}","url":"https://spiritanimal.com","normalized_url":"https://spiritanimal.com/","scan_type":"Directory","status":"NotStarted","num_requests":0}}"#,
|
||||
fs.id
|
||||
);
|
||||
assert_eq!(fs_json, serde_json::to_string(&*fs).unwrap());
|
||||
@@ -290,7 +296,7 @@ fn ferox_scans_serialize() {
|
||||
);
|
||||
let ferox_scans = FeroxScans::default();
|
||||
let ferox_scans_json = format!(
|
||||
r#"[{{"id":"{}","url":"https://spiritanimal.com","scan_type":"Directory","status":"NotStarted","num_requests":0}}]"#,
|
||||
r#"[{{"id":"{}","url":"https://spiritanimal.com","normalized_url":"https://spiritanimal.com/","scan_type":"Directory","status":"NotStarted","num_requests":0}}]"#,
|
||||
ferox_scan.id
|
||||
);
|
||||
ferox_scans.scans.write().unwrap().push(ferox_scan);
|
||||
@@ -303,7 +309,7 @@ fn ferox_scans_serialize() {
|
||||
#[test]
|
||||
/// given a FeroxResponses, test that it serializes into the proper JSON entry
|
||||
fn ferox_responses_serialize() {
|
||||
let json_response = r#"{"type":"response","url":"https://nerdcore.com/css","original_url":"https://nerdcore.com","path":"/css","wildcard":true,"status":301,"content_length":173,"line_count":10,"word_count":16,"headers":{"server":"nginx/1.16.1"}}"#;
|
||||
let json_response = r#"{"type":"response","url":"https://nerdcore.com/css","original_url":"https://nerdcore.com","path":"/css","wildcard":true,"status":301,"method":"GET","content_length":173,"line_count":10,"word_count":16,"headers":{"server":"nginx/1.16.1"},"extension":""}"#;
|
||||
let response: FeroxResponse = serde_json::from_str(json_response).unwrap();
|
||||
|
||||
let responses = FeroxResponses::default();
|
||||
@@ -321,7 +327,7 @@ fn ferox_responses_serialize() {
|
||||
/// given a FeroxResponse, test that it serializes into the proper JSON entry
|
||||
fn ferox_response_serialize_and_deserialize() {
|
||||
// deserialize
|
||||
let json_response = r#"{"type":"response","url":"https://nerdcore.com/css","original_url":"https://nerdcore.com","path":"/css","wildcard":true,"status":301,"content_length":173,"line_count":10,"word_count":16,"headers":{"server":"nginx/1.16.1"}}"#;
|
||||
let json_response = r#"{"type":"response","url":"https://nerdcore.com/css","original_url":"https://nerdcore.com","path":"/css","wildcard":true,"status":301,"method":"GET","content_length":173,"line_count":10,"word_count":16,"headers":{"server":"nginx/1.16.1"},"extension":""}"#;
|
||||
let response: FeroxResponse = serde_json::from_str(json_response).unwrap();
|
||||
|
||||
assert_eq!(response.url().as_str(), "https://nerdcore.com/css");
|
||||
@@ -351,20 +357,60 @@ fn feroxstates_feroxserialize_implementation() {
|
||||
);
|
||||
let ferox_scans = FeroxScans::default();
|
||||
let saved_id = ferox_scan.id.clone();
|
||||
|
||||
ferox_scans.insert(ferox_scan);
|
||||
|
||||
let config = Configuration::new().unwrap();
|
||||
ferox_scans
|
||||
.collected_extensions
|
||||
.write()
|
||||
.unwrap()
|
||||
.insert(String::from("php"));
|
||||
|
||||
let mut config = Configuration::new().unwrap();
|
||||
|
||||
config.collect_extensions = true;
|
||||
|
||||
let stats = Arc::new(Stats::new(config.json));
|
||||
|
||||
let json_response = r#"{"type":"response","url":"https://nerdcore.com/css","path":"/css","wildcard":true,"status":301,"content_length":173,"line_count":10,"word_count":16,"headers":{"server":"nginx/1.16.1"}}"#;
|
||||
let json_response = r#"{"type":"response","url":"https://nerdcore.com/css","path":"/css","wildcard":true,"status":301,"content_length":173,"line_count":10,"word_count":16,"headers":{"server":"nginx/1.16.1"},"extension":""}"#;
|
||||
let response: FeroxResponse = serde_json::from_str(json_response).unwrap();
|
||||
RESPONSES.insert(response);
|
||||
|
||||
let filters = FeroxFilters::default();
|
||||
filters
|
||||
.push(Box::new(StatusCodeFilter { filter_code: 100 }))
|
||||
.unwrap();
|
||||
filters
|
||||
.push(Box::new(WordsFilter { word_count: 200 }))
|
||||
.unwrap();
|
||||
filters
|
||||
.push(Box::new(SizeFilter {
|
||||
content_length: 300,
|
||||
}))
|
||||
.unwrap();
|
||||
filters
|
||||
.push(Box::new(LinesFilter { line_count: 400 }))
|
||||
.unwrap();
|
||||
filters
|
||||
.push(Box::new(RegexFilter {
|
||||
raw_string: ".*".to_string(),
|
||||
compiled: Regex::new(".*").unwrap(),
|
||||
}))
|
||||
.unwrap();
|
||||
filters
|
||||
.push(Box::new(SimilarityFilter {
|
||||
hash: "3:YKEpn:Yfp".to_string(),
|
||||
threshold: SIMILARITY_THRESHOLD,
|
||||
original_url: "http://localhost:12345/".to_string(),
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
let ferox_state = FeroxState::new(
|
||||
Arc::new(ferox_scans),
|
||||
Arc::new(Configuration::new().unwrap()),
|
||||
Arc::new(config),
|
||||
&RESPONSES,
|
||||
stats,
|
||||
Arc::new(filters),
|
||||
);
|
||||
|
||||
let expected_strs = predicates::str::contains("scans: FeroxScans").and(
|
||||
@@ -372,12 +418,16 @@ fn feroxstates_feroxserialize_implementation() {
|
||||
.and(predicate::str::contains("responses: FeroxResponses"))
|
||||
.and(predicate::str::contains("nerdcore.com"))
|
||||
.and(predicate::str::contains("/css"))
|
||||
.and(predicate::str::contains("https://spiritanimal.com")),
|
||||
.and(predicate::str::contains("https://spiritanimal.com"))
|
||||
.and(predicate::str::contains("php")),
|
||||
);
|
||||
|
||||
assert!(expected_strs.eval(&ferox_state.as_str()));
|
||||
|
||||
let json_state = ferox_state.as_json().unwrap();
|
||||
|
||||
println!("echo '{}'|jq", json_state); // for debugging, if the test fails, can see what's going on
|
||||
|
||||
for expected in [
|
||||
r#""scans""#,
|
||||
&format!(r#""id":"{}""#, saved_id),
|
||||
@@ -402,6 +452,7 @@ fn feroxstates_feroxserialize_implementation() {
|
||||
r#""quiet":false"#,
|
||||
r#""auto_bail":false"#,
|
||||
r#""auto_tune":false"#,
|
||||
r#""force_recursion":false"#,
|
||||
r#""json":false"#,
|
||||
r#""output":"""#,
|
||||
r#""debug_log":"""#,
|
||||
@@ -410,6 +461,8 @@ fn feroxstates_feroxserialize_implementation() {
|
||||
r#""redirects":false"#,
|
||||
r#""insecure":false"#,
|
||||
r#""extensions":[]"#,
|
||||
r#""methods":["GET"],"#,
|
||||
r#""data":[]"#,
|
||||
r#""headers""#,
|
||||
r#""queries":[]"#,
|
||||
r#""no_recursion":false"#,
|
||||
@@ -437,19 +490,24 @@ fn feroxstates_feroxserialize_implementation() {
|
||||
r#""path":"/css""#,
|
||||
r#""wildcard":true"#,
|
||||
r#""status":301"#,
|
||||
r#""method":"GET""#,
|
||||
r#""content_length":173"#,
|
||||
r#""line_count":10"#,
|
||||
r#""word_count":16"#,
|
||||
r#""headers""#,
|
||||
r#""server":"nginx/1.16.1"#,
|
||||
r#""collect_extensions":true"#,
|
||||
r#""collect_backups":false"#,
|
||||
r#""collect_words":false"#,
|
||||
r#""filters":[{"filter_code":100},{"word_count":200},{"content_length":300},{"line_count":400},{"compiled":".*","raw_string":".*"},{"hash":"3:YKEpn:Yfp","threshold":95,"original_url":"http://localhost:12345/"}]"#,
|
||||
r#""collected_extensions":["php"]"#,
|
||||
r#""dont_collect":["tif","tiff","ico","cur","bmp","webp","svg","png","jpg","jpeg","jfif","gif","avif","apng","pjpeg","pjp","mov","wav","mpg","mpeg","mp3","mp4","m4a","m4p","m4v","ogg","webm","ogv","oga","flac","aac","3gp","css","zip","xls","xml","gz","tgz"]"#,
|
||||
]
|
||||
.iter()
|
||||
{
|
||||
assert!(
|
||||
predicates::str::contains(*expected).eval(&json_state),
|
||||
"{}",
|
||||
expected
|
||||
)
|
||||
predicates::str::contains(*expected).eval(&json_state)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -498,6 +556,7 @@ fn feroxscan_display() {
|
||||
let scan = FeroxScan {
|
||||
id: "".to_string(),
|
||||
url: String::from("http://localhost"),
|
||||
normalized_url: String::from("http://localhost/"),
|
||||
scan_order: ScanOrder::Latest,
|
||||
scan_type: Default::default(),
|
||||
num_requests: 0,
|
||||
@@ -542,6 +601,7 @@ async fn ferox_scan_abort() {
|
||||
let scan = FeroxScan {
|
||||
id: "".to_string(),
|
||||
url: String::from("http://localhost"),
|
||||
normalized_url: String::from("http://localhost/"),
|
||||
scan_order: ScanOrder::Latest,
|
||||
scan_type: Default::default(),
|
||||
num_requests: 0,
|
||||
@@ -572,7 +632,7 @@ async fn ferox_scan_abort() {
|
||||
/// and their correctness can be verified easily manually; just calling for now
|
||||
fn menu_print_header_and_footer() {
|
||||
let menu = Menu::new();
|
||||
let menu_cmd_1 = MenuCmd::Add(String::from("http://localhost"));
|
||||
let menu_cmd_1 = MenuCmd::AddUrl(String::from("http://localhost"));
|
||||
let menu_cmd_2 = MenuCmd::Cancel(vec![0], false);
|
||||
let menu_cmd_res_1 = MenuCmdResult::Url(String::from("http://localhost"));
|
||||
let menu_cmd_res_2 = MenuCmdResult::NumCancelled(2);
|
||||
@@ -587,8 +647,8 @@ fn menu_print_header_and_footer() {
|
||||
menu.show_progress_bars();
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// ensure command parsing from user input results int he correct MenuCmd returned
|
||||
#[test]
|
||||
fn menu_get_command_input_from_user_returns_cancel() {
|
||||
let menu = Menu::new();
|
||||
|
||||
@@ -616,8 +676,8 @@ fn menu_get_command_input_from_user_returns_cancel() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// ensure command parsing from user input results int he correct MenuCmd returned
|
||||
#[test]
|
||||
fn menu_get_command_input_from_user_returns_add() {
|
||||
let menu = Menu::new();
|
||||
|
||||
@@ -627,9 +687,9 @@ fn menu_get_command_input_from_user_returns_add() {
|
||||
|
||||
if cmd != "None" {
|
||||
let result = menu.get_command_input_from_user(&full_cmd).unwrap();
|
||||
assert!(matches!(result, MenuCmd::Add(_)));
|
||||
assert!(matches!(result, MenuCmd::AddUrl(_)));
|
||||
|
||||
if let MenuCmd::Add(url) = result {
|
||||
if let MenuCmd::AddUrl(url) = result {
|
||||
assert_eq!(url, test_url);
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -1,18 +1,25 @@
|
||||
use std::fmt::Write as _;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::{ops::Deref, sync::atomic::Ordering, sync::Arc, time::Instant};
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
use console::style;
|
||||
use futures::{stream, StreamExt};
|
||||
use indicatif::ProgressBar;
|
||||
use lazy_static::lazy_static;
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
use crate::filters::{create_similarity_filter, EmptyFilter, SimilarityFilter};
|
||||
use crate::Command::AddFilter;
|
||||
use crate::{
|
||||
event_handlers::{
|
||||
Command::{AddError, AddToF64Field, SubtractFromUsizeField},
|
||||
Command::{AddError, AddToF64Field, AddToUsizeField, SubtractFromUsizeField},
|
||||
Handles,
|
||||
},
|
||||
extractor::{ExtractionTarget::RobotsTxt, ExtractorBuilder},
|
||||
extractor::{ExtractionTarget, ExtractorBuilder},
|
||||
heuristics,
|
||||
scan_manager::{FeroxResponses, MenuCmdResult, ScanOrder, ScanStatus, PAUSE_SCAN},
|
||||
scan_manager::{FeroxResponses, FeroxScans, MenuCmdResult, ScanOrder, ScanStatus, PAUSE_SCAN},
|
||||
scanner::requester::TF_IDF,
|
||||
statistics::{
|
||||
StatError::Other,
|
||||
StatField::{DirScanTimes, TotalExpected},
|
||||
@@ -28,6 +35,75 @@ lazy_static! {
|
||||
pub static ref RESPONSES: FeroxResponses = FeroxResponses::default();
|
||||
// todo consider removing this
|
||||
}
|
||||
|
||||
/// check to see if `pause_flag` is set to true. when true; enter a busy loop that only exits
|
||||
/// by setting PAUSE_SCAN back to false
|
||||
async fn check_for_user_input(
|
||||
pause_flag: &AtomicBool,
|
||||
scanned_urls: Arc<FeroxScans>,
|
||||
handles: Arc<Handles>,
|
||||
) {
|
||||
log::trace!(
|
||||
"enter: check_for_user_input({:?}, SCANNED_URLS, HANDLES)",
|
||||
pause_flag
|
||||
);
|
||||
|
||||
// todo write a test or two for this function at some point...
|
||||
if pause_flag.load(Ordering::Acquire) {
|
||||
match scanned_urls.pause(true, handles.clone()).await {
|
||||
Some(MenuCmdResult::Url(url)) => {
|
||||
// user wants to add a new url to be scanned, need to send
|
||||
// it over to the event handler for processing
|
||||
handles
|
||||
.send_scan_command(Command::ScanNewUrl(url))
|
||||
.unwrap_or_else(|e| log::warn!("Could not add scan to scan queue: {}", e))
|
||||
}
|
||||
Some(MenuCmdResult::NumCancelled(num_canx)) => {
|
||||
if num_canx > 0 {
|
||||
handles
|
||||
.stats
|
||||
.send(SubtractFromUsizeField(TotalExpected, num_canx))
|
||||
.unwrap_or_else(|e| log::warn!("Could not update overall scan bar: {}", e));
|
||||
}
|
||||
}
|
||||
Some(MenuCmdResult::Filter(mut filter)) => {
|
||||
let url = if let Some(SimilarityFilter { original_url, .. }) =
|
||||
filter.as_any().downcast_ref::<SimilarityFilter>()
|
||||
{
|
||||
original_url.to_owned()
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
if !url.is_empty() {
|
||||
// filter was a SimilarityFilter and now we have a url to request.
|
||||
//
|
||||
// The reason for this janky structure is that `filter.as_any().downcast_ref`
|
||||
// isn't Send so we can't call create_similarity_filter(...).await, within
|
||||
// the if let Some ipso-facto, janky code /shrug
|
||||
let real_filter = create_similarity_filter(&url, handles.clone())
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
|
||||
if real_filter.original_url.is_empty() {
|
||||
// failed to create filter
|
||||
filter = Box::new(EmptyFilter {});
|
||||
} else {
|
||||
filter = Box::new(real_filter)
|
||||
}
|
||||
}
|
||||
|
||||
handles
|
||||
.filters
|
||||
.send(AddFilter(filter))
|
||||
.unwrap_or_else(|e| log::warn!("Could not add new filter: {}", e));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
log::trace!("exit: check_for_user_input");
|
||||
}
|
||||
|
||||
/// handles the main muscle movement of scanning a url
|
||||
pub struct FeroxScanner {
|
||||
/// handles to handlers and config
|
||||
@@ -43,7 +119,7 @@ pub struct FeroxScanner {
|
||||
/// wordlist that's already been read from disk
|
||||
wordlist: Arc<Vec<String>>,
|
||||
|
||||
/// limiter that restricts the number of active FeroxScanners
|
||||
/// limiter that restricts the number of active FeroxScanners
|
||||
scan_limiter: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
@@ -66,6 +142,57 @@ impl FeroxScanner {
|
||||
}
|
||||
}
|
||||
|
||||
/// produces and awaits tasks (mp of mpsc); responsible for making requests
|
||||
async fn stream_requests(
|
||||
&self,
|
||||
looping_words: Arc<Vec<String>>,
|
||||
progress_bar: ProgressBar,
|
||||
scanned_urls: Arc<FeroxScans>,
|
||||
requester: Arc<Requester>,
|
||||
) {
|
||||
log::trace!("enter: stream_requests(params too verbose to print)");
|
||||
|
||||
let producers = stream::iter(looping_words.deref().to_owned())
|
||||
.map(|word| {
|
||||
let pb = progress_bar.clone(); // progress bar is an Arc around internal state
|
||||
let scanned_urls_clone = scanned_urls.clone();
|
||||
let requester_clone = requester.clone();
|
||||
let handles_clone = self.handles.clone();
|
||||
(
|
||||
tokio::spawn(async move {
|
||||
// for every word in the wordlist, check to see if user has pressed enter
|
||||
// in order to go into the interactive menu
|
||||
check_for_user_input(&PAUSE_SCAN, scanned_urls_clone, handles_clone).await;
|
||||
|
||||
// after checking for user input, send the request
|
||||
requester_clone
|
||||
.request(&word)
|
||||
.await
|
||||
.unwrap_or_else(|e| log::warn!("Requester encountered an error: {}", e))
|
||||
}),
|
||||
pb,
|
||||
)
|
||||
})
|
||||
.for_each_concurrent(self.handles.config.threads, |(resp, bar)| async move {
|
||||
match resp.await {
|
||||
Ok(_) => {
|
||||
let increment_len = self.handles.expected_num_requests_multiplier() as u64;
|
||||
bar.inc(increment_len);
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("error awaiting a response: {}", e);
|
||||
self.handles.stats.send(AddError(Other)).unwrap_or_default();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// await tx tasks
|
||||
log::trace!("awaiting scan producers");
|
||||
producers.await;
|
||||
log::trace!("done awaiting scan producers");
|
||||
log::trace!("exit: stream_requests");
|
||||
}
|
||||
|
||||
/// Scan a given url using a given wordlist
|
||||
///
|
||||
/// This is the primary entrypoint for the scanner
|
||||
@@ -73,23 +200,21 @@ impl FeroxScanner {
|
||||
log::trace!("enter: scan_url");
|
||||
log::info!("Starting scan against: {}", self.target_url);
|
||||
|
||||
let scan_timer = Instant::now();
|
||||
let mut scan_timer = Instant::now();
|
||||
|
||||
if matches!(self.order, ScanOrder::Initial) && self.handles.config.extract_links {
|
||||
// only grab robots.txt on the initial scan_url calls. all fresh dirs will be passed
|
||||
// to try_recursion
|
||||
let extractor = ExtractorBuilder::default()
|
||||
if self.handles.config.extract_links && matches!(self.order, ScanOrder::Initial) {
|
||||
// check for robots.txt (cannot be in sub-directories, so limited to Initial)
|
||||
let mut extractor = ExtractorBuilder::default()
|
||||
.target(ExtractionTarget::RobotsTxt)
|
||||
.url(&self.target_url)
|
||||
.handles(self.handles.clone())
|
||||
.target(RobotsTxt)
|
||||
.build()?;
|
||||
|
||||
let links = extractor.extract().await?;
|
||||
extractor.request_links(links).await?;
|
||||
let result = extractor.extract().await?;
|
||||
extractor.request_links(result).await?;
|
||||
}
|
||||
|
||||
let scanned_urls = self.handles.ferox_scans()?;
|
||||
|
||||
let ferox_scan = match scanned_urls.get_scan_by_url(&self.target_url) {
|
||||
Some(scan) => {
|
||||
scan.set_status(ScanStatus::Running)?;
|
||||
@@ -112,82 +237,108 @@ impl FeroxScanner {
|
||||
// to the caller.
|
||||
let _permit = self.scan_limiter.acquire().await;
|
||||
|
||||
// Arc clones to be passed around to the various scans
|
||||
let looping_words = self.wordlist.clone();
|
||||
if self.handles.config.scan_limit > 0 {
|
||||
scan_timer = Instant::now();
|
||||
progress_bar.reset();
|
||||
}
|
||||
|
||||
{
|
||||
// heuristics test block
|
||||
let test = heuristics::HeuristicTests::new(self.handles.clone());
|
||||
|
||||
if let Ok(num_reqs) = test.wildcard(&self.target_url).await {
|
||||
progress_bar.inc(num_reqs);
|
||||
}
|
||||
|
||||
if let Ok(dirlist_result) = test.directory_listing(&self.target_url).await {
|
||||
if dirlist_result.is_some() {
|
||||
let dirlist_result = dirlist_result.unwrap();
|
||||
// at this point, we have a DirListingType, and it's not the None variant
|
||||
// which means we found directory listing based on the heuristic; now we need
|
||||
// to process the links that are available if --extract-links was used
|
||||
|
||||
if self.handles.config.extract_links {
|
||||
let mut extractor = ExtractorBuilder::default()
|
||||
.response(&dirlist_result.response)
|
||||
.target(ExtractionTarget::DirectoryListing)
|
||||
.url(&self.target_url)
|
||||
.handles(self.handles.clone())
|
||||
.build()?;
|
||||
|
||||
let result = extractor.extract_from_dir_listing().await?;
|
||||
|
||||
extractor.request_links(result).await?;
|
||||
|
||||
log::trace!("exit: scan_url -> Directory listing heuristic");
|
||||
|
||||
self.handles.stats.send(AddToF64Field(
|
||||
DirScanTimes,
|
||||
scan_timer.elapsed().as_secs_f64(),
|
||||
))?;
|
||||
|
||||
self.handles.stats.send(SubtractFromUsizeField(
|
||||
TotalExpected,
|
||||
progress_bar.length() as usize,
|
||||
))?;
|
||||
}
|
||||
|
||||
let mut message = format!("=> {}", style("Directory listing").blue().bright());
|
||||
|
||||
if !self.handles.config.extract_links {
|
||||
write!(message, " (add {} to scan)", style("-e").bright().yellow())?;
|
||||
}
|
||||
|
||||
progress_bar.reset_eta();
|
||||
progress_bar.finish_with_message(&message);
|
||||
|
||||
ferox_scan.finish()?;
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Arc clones to be passed around to the various scans
|
||||
let looping_words = self.wordlist.clone();
|
||||
|
||||
let requester = Arc::new(Requester::from(self, ferox_scan.clone())?);
|
||||
let increment_len = (self.handles.config.extensions.len() + 1) as u64;
|
||||
|
||||
// producer tasks (mp of mpsc); responsible for making requests
|
||||
let producers = stream::iter(looping_words.deref().to_owned())
|
||||
.map(|word| {
|
||||
let pb = progress_bar.clone(); // progress bar is an Arc around internal state
|
||||
let scanned_urls_clone = scanned_urls.clone();
|
||||
let requester_clone = requester.clone();
|
||||
let handles_clone = self.handles.clone();
|
||||
(
|
||||
tokio::spawn(async move {
|
||||
if PAUSE_SCAN.load(Ordering::Acquire) {
|
||||
// for every word in the wordlist, check to see if PAUSE_SCAN is set to true
|
||||
// when true; enter a busy loop that only exits by setting PAUSE_SCAN back
|
||||
// to false
|
||||
match scanned_urls_clone.pause(true).await {
|
||||
Some(MenuCmdResult::Url(url)) => {
|
||||
// user wants to add a new url to be scanned, need to send
|
||||
// it over to the event handler for processing
|
||||
handles_clone
|
||||
.send_scan_command(Command::ScanNewUrl(url))
|
||||
.unwrap_or_else(|e| {
|
||||
log::warn!("Could not add scan to scan queue: {}", e)
|
||||
})
|
||||
}
|
||||
Some(MenuCmdResult::NumCancelled(num_canx)) => {
|
||||
if num_canx > 0 {
|
||||
handles_clone
|
||||
.stats
|
||||
.send(SubtractFromUsizeField(TotalExpected, num_canx))
|
||||
.unwrap_or_else(|e| {
|
||||
log::warn!(
|
||||
"Could not update overall scan bar: {}",
|
||||
e
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
requester_clone
|
||||
.request(&word)
|
||||
.await
|
||||
.unwrap_or_else(|e| log::warn!("Requester encountered an error: {}", e))
|
||||
}),
|
||||
pb,
|
||||
)
|
||||
})
|
||||
.for_each_concurrent(self.handles.config.threads, |(resp, bar)| async move {
|
||||
match resp.await {
|
||||
Ok(_) => {
|
||||
bar.inc(increment_len);
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("error awaiting a response: {}", e);
|
||||
self.handles.stats.send(AddError(Other)).unwrap_or_default();
|
||||
}
|
||||
}
|
||||
});
|
||||
self.stream_requests(
|
||||
looping_words.clone(),
|
||||
progress_bar.clone(),
|
||||
scanned_urls.clone(),
|
||||
requester.clone(),
|
||||
)
|
||||
.await;
|
||||
|
||||
// await tx tasks
|
||||
log::trace!("awaiting scan producers");
|
||||
producers.await;
|
||||
log::trace!("done awaiting scan producers");
|
||||
if self.handles.config.collect_words {
|
||||
let new_words = TF_IDF.read().unwrap().all_words();
|
||||
let new_words_len = new_words.len();
|
||||
|
||||
let cur_length = progress_bar.length();
|
||||
let new_length = cur_length + new_words_len as u64;
|
||||
|
||||
progress_bar.set_length(new_length);
|
||||
|
||||
self.handles
|
||||
.stats
|
||||
.send(AddToUsizeField(TotalExpected, new_words.len()))
|
||||
.unwrap_or_default();
|
||||
|
||||
log::info!(
|
||||
"requesting {} collected words: {:?}...",
|
||||
new_words_len,
|
||||
&new_words[..new_words_len.min(3)]
|
||||
);
|
||||
|
||||
self.stream_requests(
|
||||
Arc::new(new_words),
|
||||
progress_bar.clone(),
|
||||
scanned_urls.clone(),
|
||||
requester.clone(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
self.handles.stats.send(AddToF64Field(
|
||||
DirScanTimes,
|
||||
|
||||
@@ -11,12 +11,7 @@ pub async fn initialize(num_words: usize, handles: Arc<Handles>) -> Result<()> {
|
||||
log::trace!("enter: initialize({}, {:?})", num_words, handles);
|
||||
|
||||
// number of requests only needs to be calculated once, and then can be reused
|
||||
let num_reqs_expected: u64 = if handles.config.extensions.is_empty() {
|
||||
num_words.try_into()?
|
||||
} else {
|
||||
let total = num_words * (handles.config.extensions.len() + 1);
|
||||
total.try_into()?
|
||||
};
|
||||
let num_reqs_expected: u64 = handles.expected_num_requests_per_dir().try_into()?;
|
||||
|
||||
{
|
||||
// no real reason to keep the arc around beyond this call
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
use std::{
|
||||
cmp::max,
|
||||
sync::{atomic::Ordering, Arc, Mutex},
|
||||
collections::HashSet,
|
||||
sync::{self, atomic::Ordering, Arc, Mutex},
|
||||
};
|
||||
|
||||
use anyhow::Result;
|
||||
use leaky_bucket::LeakyBucket;
|
||||
use lazy_static::lazy_static;
|
||||
use leaky_bucket::RateLimiter;
|
||||
use tokio::{
|
||||
sync::{oneshot, RwLock},
|
||||
sync::RwLock,
|
||||
time::{sleep, Duration},
|
||||
};
|
||||
|
||||
@@ -14,21 +16,25 @@ use crate::{
|
||||
atomic_load, atomic_store,
|
||||
config::RequesterPolicy,
|
||||
event_handlers::{
|
||||
Command::{self, AddError, SubtractFromUsizeField},
|
||||
Command::{AddError, SubtractFromUsizeField},
|
||||
Handles,
|
||||
},
|
||||
extractor::{ExtractionTarget::ResponseBody, ExtractorBuilder},
|
||||
extractor::{ExtractionTarget, ExtractorBuilder},
|
||||
nlp::{Document, TfIdf},
|
||||
response::FeroxResponse,
|
||||
scan_manager::{FeroxScan, ScanStatus},
|
||||
statistics::{StatError::Other, StatField::TotalExpected},
|
||||
url::FeroxUrl,
|
||||
utils::logged_request,
|
||||
utils::{logged_request, send_try_recursion_command, should_deny_url},
|
||||
HIGH_ERROR_RATIO,
|
||||
};
|
||||
|
||||
use super::{policy_data::PolicyData, FeroxScanner, PolicyTrigger};
|
||||
use crate::utils::should_deny_url;
|
||||
use std::collections::HashSet;
|
||||
|
||||
lazy_static! {
|
||||
/// make sure to note that this is a std rwlock and not tokio
|
||||
pub(crate) static ref TF_IDF: Arc<sync::RwLock<TfIdf>> = Arc::new(sync::RwLock::new(TfIdf::new()));
|
||||
}
|
||||
|
||||
/// Makes multiple requests based on the presence of extensions
|
||||
pub(super) struct Requester {
|
||||
@@ -39,7 +45,7 @@ pub(super) struct Requester {
|
||||
target_url: String,
|
||||
|
||||
/// limits requests per second if present
|
||||
rate_limiter: RwLock<Option<LeakyBucket>>,
|
||||
rate_limiter: RwLock<Option<RateLimiter>>,
|
||||
|
||||
/// data regarding policy and metadata about last enforced trigger etc...
|
||||
policy_data: PolicyData,
|
||||
@@ -88,18 +94,18 @@ impl Requester {
|
||||
})
|
||||
}
|
||||
|
||||
/// build a LeakyBucket, given a rate limit (as requests per second)
|
||||
fn build_a_bucket(limit: usize) -> Result<LeakyBucket> {
|
||||
/// build a RateLimiter, given a rate limit (as requests per second)
|
||||
fn build_a_bucket(limit: usize) -> Result<RateLimiter> {
|
||||
let refill = max((limit as f64 / 10.0).round() as usize, 1); // minimum of 1 per second
|
||||
let tokens = max((limit as f64 / 2.0).round() as usize, 1);
|
||||
let interval = if refill == 1 { 1000 } else { 100 }; // 1 second if refill is 1
|
||||
|
||||
Ok(LeakyBucket::builder()
|
||||
.refill_interval(Duration::from_millis(interval)) // add tokens every 0.1s
|
||||
.refill_amount(refill) // ex: 100 req/s -> 10 tokens per 0.1s
|
||||
.tokens(tokens) // reduce initial burst, 2 is arbitrary, but felt good
|
||||
Ok(RateLimiter::builder()
|
||||
.interval(Duration::from_millis(interval)) // add tokens every 0.1s
|
||||
.refill(refill) // ex: 100 req/s -> 10 tokens per 0.1s
|
||||
.initial(tokens) // reduce initial burst, 2 is arbitrary, but felt good
|
||||
.max(limit)
|
||||
.build()?)
|
||||
.build())
|
||||
}
|
||||
|
||||
/// sleep and set a flag that can be checked by other threads
|
||||
@@ -118,13 +124,12 @@ impl Requester {
|
||||
|
||||
/// limit the number of requests per second
|
||||
pub async fn limit(&self) -> Result<()> {
|
||||
self.rate_limiter
|
||||
.read()
|
||||
.await
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.acquire_one()
|
||||
.await?;
|
||||
let guard = self.rate_limiter.read().await;
|
||||
|
||||
if guard.is_some() {
|
||||
guard.as_ref().unwrap().acquire_one().await;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -203,7 +208,7 @@ impl Requester {
|
||||
} else {
|
||||
// errors can only be incremented, so an else is sufficient
|
||||
*guard += 1;
|
||||
self.policy_data.adjust_up(&*guard);
|
||||
self.policy_data.adjust_up(&guard);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -303,116 +308,176 @@ impl Requester {
|
||||
pub async fn request(&self, word: &str) -> Result<()> {
|
||||
log::trace!("enter: request({})", word);
|
||||
|
||||
let urls =
|
||||
FeroxUrl::from_string(&self.target_url, self.handles.clone()).formatted_urls(word)?;
|
||||
let collected = self.handles.collected_extensions();
|
||||
|
||||
let urls = FeroxUrl::from_string(&self.target_url, self.handles.clone())
|
||||
.formatted_urls(word, collected)?;
|
||||
|
||||
let should_test_deny = !self.handles.config.url_denylist.is_empty()
|
||||
|| !self.handles.config.regex_denylist.is_empty();
|
||||
|
||||
for url in urls {
|
||||
// auto_tune is true, or rate_limit was set (mutually exclusive to user)
|
||||
// and a rate_limiter has been created
|
||||
// short-circuiting the lock access behind the first boolean check
|
||||
let should_tune = self.handles.config.auto_tune || self.handles.config.rate_limit > 0;
|
||||
let should_limit = should_tune && self.rate_limiter.read().await.is_some();
|
||||
for method in self.handles.config.methods.iter() {
|
||||
// auto_tune is true, or rate_limit was set (mutually exclusive to user)
|
||||
// and a rate_limiter has been created
|
||||
// short-circuiting the lock access behind the first boolean check
|
||||
let should_tune =
|
||||
self.handles.config.auto_tune || self.handles.config.rate_limit > 0;
|
||||
let should_limit = should_tune && self.rate_limiter.read().await.is_some();
|
||||
|
||||
if should_limit {
|
||||
// found a rate limiter, limit that junk!
|
||||
if let Err(e) = self.limit().await {
|
||||
log::warn!("Could not rate limit scan: {}", e);
|
||||
self.handles.stats.send(AddError(Other)).unwrap_or_default();
|
||||
}
|
||||
}
|
||||
|
||||
if should_test_deny && should_deny_url(&url, self.handles.clone())? {
|
||||
// can't allow a denied url to be requested
|
||||
continue;
|
||||
}
|
||||
|
||||
let response = logged_request(&url, self.handles.clone()).await?;
|
||||
|
||||
if (should_tune || self.handles.config.auto_bail)
|
||||
&& !atomic_load!(self.policy_data.cooling_down, Ordering::SeqCst)
|
||||
{
|
||||
// only check for policy enforcement when the trigger isn't on cooldown and tuning
|
||||
// or bailing is in place (should_tune used here because when auto-tune is on, we'll
|
||||
// reach this without a rate_limiter in place)
|
||||
match self.policy_data.policy {
|
||||
RequesterPolicy::AutoTune => {
|
||||
if let Some(trigger) = self.should_enforce_policy() {
|
||||
self.tune(trigger).await?;
|
||||
}
|
||||
if should_limit {
|
||||
// found a rate limiter, limit that junk!
|
||||
if let Err(e) = self.limit().await {
|
||||
log::warn!("Could not rate limit scan: {}", e);
|
||||
self.handles.stats.send(AddError(Other)).unwrap_or_default();
|
||||
}
|
||||
RequesterPolicy::AutoBail => {
|
||||
if let Some(trigger) = self.should_enforce_policy() {
|
||||
self.bail(trigger).await?;
|
||||
}
|
||||
}
|
||||
RequesterPolicy::Default => {}
|
||||
}
|
||||
}
|
||||
|
||||
// response came back without error, convert it to FeroxResponse
|
||||
let ferox_response = FeroxResponse::from(
|
||||
response,
|
||||
&self.target_url,
|
||||
true,
|
||||
self.handles.config.output_level,
|
||||
)
|
||||
.await;
|
||||
if should_test_deny && should_deny_url(&url, self.handles.clone())? {
|
||||
// can't allow a denied url to be requested
|
||||
continue;
|
||||
}
|
||||
|
||||
// do recursion if appropriate
|
||||
if !self.handles.config.no_recursion {
|
||||
self.handles
|
||||
.send_scan_command(Command::TryRecursion(Box::new(ferox_response.clone())))?;
|
||||
let (tx, rx) = oneshot::channel::<bool>();
|
||||
self.handles.send_scan_command(Command::Sync(tx))?;
|
||||
rx.await?;
|
||||
}
|
||||
let data = if self.handles.config.data.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(self.handles.config.data.as_slice())
|
||||
};
|
||||
|
||||
// purposefully doing recursion before filtering. the thought process is that
|
||||
// even though this particular url is filtered, subsequent urls may not
|
||||
if self
|
||||
.handles
|
||||
.filters
|
||||
.data
|
||||
.should_filter_response(&ferox_response, self.handles.stats.tx.clone())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if self.handles.config.extract_links && !ferox_response.status().is_redirection() {
|
||||
let extractor = ExtractorBuilder::default()
|
||||
.target(ResponseBody)
|
||||
.response(&ferox_response)
|
||||
.handles(self.handles.clone())
|
||||
.build()?;
|
||||
|
||||
let new_links: HashSet<_>;
|
||||
let extracted = extractor.extract().await?;
|
||||
let response =
|
||||
logged_request(&url, method.as_str(), data, self.handles.clone()).await?;
|
||||
|
||||
if (should_tune || self.handles.config.auto_bail)
|
||||
&& !atomic_load!(self.policy_data.cooling_down, Ordering::SeqCst)
|
||||
{
|
||||
// gain and quickly drop the read lock on seen_links, using it while unlocked
|
||||
// to determine if there are any new links to process
|
||||
let read_links = self.seen_links.read().await;
|
||||
new_links = extracted.difference(&read_links).cloned().collect();
|
||||
}
|
||||
|
||||
if !new_links.is_empty() {
|
||||
// using is_empty instead of direct iteration to acquire the write lock behind
|
||||
// some kind of less expensive gate (and not in a loop, obv)
|
||||
let mut write_links = self.seen_links.write().await;
|
||||
for new_link in &new_links {
|
||||
write_links.insert(new_link.to_owned());
|
||||
// only check for policy enforcement when the trigger isn't on cooldown and tuning
|
||||
// or bailing is in place (should_tune used here because when auto-tune is on, we'll
|
||||
// reach this without a rate_limiter in place)
|
||||
match self.policy_data.policy {
|
||||
RequesterPolicy::AutoTune => {
|
||||
if let Some(trigger) = self.should_enforce_policy() {
|
||||
self.tune(trigger).await?;
|
||||
}
|
||||
}
|
||||
RequesterPolicy::AutoBail => {
|
||||
if let Some(trigger) = self.should_enforce_policy() {
|
||||
self.bail(trigger).await?;
|
||||
}
|
||||
}
|
||||
RequesterPolicy::Default => {}
|
||||
}
|
||||
}
|
||||
|
||||
extractor.request_links(new_links).await?;
|
||||
}
|
||||
// response came back without error, convert it to FeroxResponse
|
||||
let mut ferox_response = FeroxResponse::from(
|
||||
response,
|
||||
&self.target_url,
|
||||
method,
|
||||
self.handles.config.output_level,
|
||||
)
|
||||
.await;
|
||||
|
||||
// everything else should be reported
|
||||
if let Err(e) = ferox_response.send_report(self.handles.output.tx.clone()) {
|
||||
log::warn!("Could not send FeroxResponse to output handler: {}", e);
|
||||
// do recursion if appropriate
|
||||
if !self.handles.config.no_recursion && !self.handles.config.force_recursion {
|
||||
// to support --force-recursion, we want to limit recursive calls to only
|
||||
// 'found' assets. That means we need to either gate or delay the call.
|
||||
//
|
||||
// this branch will retain the 'old' behavior by checking that
|
||||
// --force-recursion isn't turned on
|
||||
send_try_recursion_command(self.handles.clone(), ferox_response.clone())
|
||||
.await?;
|
||||
}
|
||||
|
||||
// purposefully doing recursion before filtering. the thought process is that
|
||||
// even though this particular url is filtered, subsequent urls may not
|
||||
if self
|
||||
.handles
|
||||
.filters
|
||||
.data
|
||||
.should_filter_response(&ferox_response, self.handles.stats.tx.clone())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if !self.handles.config.no_recursion && self.handles.config.force_recursion {
|
||||
// in this branch, we're saying that both recursion AND force recursion
|
||||
// are turned on. It comes after should_filter_response, so those cases
|
||||
// are handled. Now we need to account for -s/-C options.
|
||||
|
||||
if self.handles.config.filter_status.is_empty() {
|
||||
// -C wasn't used, so -s is the only 'filter' left to account for
|
||||
if self
|
||||
.handles
|
||||
.config
|
||||
.status_codes
|
||||
.contains(&ferox_response.status().as_u16())
|
||||
{
|
||||
send_try_recursion_command(
|
||||
self.handles.clone(),
|
||||
ferox_response.clone(),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
} else {
|
||||
// -C was used, that means the filters above would have removed
|
||||
// those responses, and anything else should be let through
|
||||
send_try_recursion_command(self.handles.clone(), ferox_response.clone())
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
|
||||
if self.handles.config.collect_extensions {
|
||||
ferox_response.parse_extension(self.handles.clone())?;
|
||||
}
|
||||
|
||||
if self.handles.config.collect_words {
|
||||
if let Ok(mut guard) = TF_IDF.write() {
|
||||
let doc = Document::from_html(ferox_response.text());
|
||||
guard.add_document(doc);
|
||||
if guard.num_documents() % 12 == 0
|
||||
|| (guard.num_documents() < 5 && guard.num_documents() % 2 == 0)
|
||||
{
|
||||
guard.calculate_tf_idf_scores();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if self.handles.config.extract_links {
|
||||
let mut extractor = ExtractorBuilder::default()
|
||||
.target(ExtractionTarget::ResponseBody)
|
||||
.response(&ferox_response)
|
||||
.handles(self.handles.clone())
|
||||
.build()?;
|
||||
|
||||
let new_links: HashSet<_>;
|
||||
|
||||
let result = extractor.extract().await?;
|
||||
|
||||
{
|
||||
// gain and quickly drop the read lock on seen_links, using it while unlocked
|
||||
// to determine if there are any new links to process
|
||||
let read_links = self.seen_links.read().await;
|
||||
new_links = result.difference(&read_links).cloned().collect();
|
||||
}
|
||||
|
||||
if !new_links.is_empty() {
|
||||
// using is_empty instead of direct iteration to acquire the write lock behind
|
||||
// some kind of less expensive gate (and not in a loop, obv)
|
||||
let mut write_links = self.seen_links.write().await;
|
||||
for new_link in &new_links {
|
||||
write_links.insert(new_link.to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
if !new_links.is_empty() {
|
||||
extractor.request_links(new_links).await?;
|
||||
}
|
||||
}
|
||||
|
||||
// everything else should be reported
|
||||
if let Err(e) = ferox_response.send_report(self.handles.output.tx.clone()) {
|
||||
log::warn!("Could not send FeroxResponse to output handler: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -430,6 +495,7 @@ mod tests {
|
||||
use crate::{
|
||||
config::Configuration,
|
||||
config::OutputLevel,
|
||||
event_handlers::Command::AddStatus,
|
||||
event_handlers::{FiltersHandler, ScanHandler, StatsHandler, Tasks, TermOutHandler},
|
||||
filters,
|
||||
scan_manager::{ScanOrder, ScanType},
|
||||
@@ -447,12 +513,14 @@ mod tests {
|
||||
let (filters_task, filters_handle) = FiltersHandler::initialize();
|
||||
let (out_task, out_handle) =
|
||||
TermOutHandler::initialize(configuration.clone(), stats_handle.tx.clone());
|
||||
let wordlist = Arc::new(vec![String::from("this_is_a_test")]);
|
||||
|
||||
let handles = Arc::new(Handles::new(
|
||||
stats_handle,
|
||||
filters_handle,
|
||||
out_handle,
|
||||
configuration.clone(),
|
||||
wordlist,
|
||||
));
|
||||
|
||||
let (scan_task, scan_handle) = ScanHandler::initialize(handles.clone());
|
||||
@@ -468,10 +536,7 @@ mod tests {
|
||||
/// helper to stay DRY
|
||||
async fn increment_errors(handles: Arc<Handles>, scan: Arc<FeroxScan>, num_errors: usize) {
|
||||
for _ in 0..num_errors {
|
||||
handles
|
||||
.stats
|
||||
.send(Command::AddError(StatError::Other))
|
||||
.unwrap();
|
||||
handles.stats.send(AddError(StatError::Other)).unwrap();
|
||||
scan.add_error();
|
||||
}
|
||||
|
||||
@@ -508,7 +573,7 @@ mod tests {
|
||||
code: StatusCode,
|
||||
) {
|
||||
for _ in 0..num_codes {
|
||||
handles.stats.send(Command::AddStatus(code)).unwrap();
|
||||
handles.stats.send(AddStatus(code)).unwrap();
|
||||
if code == StatusCode::FORBIDDEN {
|
||||
scan.add_403();
|
||||
} else {
|
||||
@@ -576,10 +641,10 @@ mod tests {
|
||||
|
||||
let requester = Requester {
|
||||
handles,
|
||||
target_url: "http://localhost".to_string(),
|
||||
seen_links: RwLock::new(HashSet::<String>::new()),
|
||||
tuning_lock: Mutex::new(0),
|
||||
ferox_scan: Arc::new(FeroxScan::default()),
|
||||
target_url: "http://localhost".to_string(),
|
||||
rate_limiter: RwLock::new(None),
|
||||
policy_data: Default::default(),
|
||||
};
|
||||
@@ -860,10 +925,10 @@ mod tests {
|
||||
/// decrease the scan rate
|
||||
async fn adjust_limit_resets_streak_counter_on_downward_movement() {
|
||||
let (handles, _) = setup_requester_test(None).await;
|
||||
let mut buckets = leaky_bucket::LeakyBuckets::new();
|
||||
let coordinator = buckets.coordinate().unwrap();
|
||||
tokio::spawn(async move { coordinator.await.expect("coordinator errored") });
|
||||
let limiter = buckets.rate_limiter().max(200).build().unwrap();
|
||||
let limiter = RateLimiter::builder()
|
||||
.interval(Duration::from_secs(1))
|
||||
.max(200)
|
||||
.build();
|
||||
|
||||
let scan = FeroxScan::default();
|
||||
scan.add_error();
|
||||
@@ -882,9 +947,10 @@ mod tests {
|
||||
requester.policy_data.set_reqs_sec(400);
|
||||
requester.policy_data.set_errors(1);
|
||||
|
||||
let mut guard = requester.tuning_lock.lock().unwrap();
|
||||
*guard = 2;
|
||||
drop(guard);
|
||||
{
|
||||
let mut guard = requester.tuning_lock.lock().unwrap();
|
||||
*guard = 2;
|
||||
}
|
||||
|
||||
requester
|
||||
.adjust_limit(PolicyTrigger::Errors, false)
|
||||
@@ -971,10 +1037,10 @@ mod tests {
|
||||
/// set_rate_limiter should exit early when new limit equals the current bucket's max
|
||||
async fn set_rate_limiter_early_exit() {
|
||||
let (handles, _) = setup_requester_test(None).await;
|
||||
let mut buckets = leaky_bucket::LeakyBuckets::new();
|
||||
let coordinator = buckets.coordinate().unwrap();
|
||||
tokio::spawn(async move { coordinator.await.expect("coordinator errored") });
|
||||
let limiter = buckets.rate_limiter().max(200).build().unwrap();
|
||||
let limiter = RateLimiter::builder()
|
||||
.interval(Duration::from_secs(1))
|
||||
.max(200)
|
||||
.build();
|
||||
|
||||
let requester = Requester {
|
||||
handles,
|
||||
@@ -1003,10 +1069,10 @@ mod tests {
|
||||
async fn tune_sets_expected_values_and_then_waits() {
|
||||
let (handles, _) = setup_requester_test(None).await;
|
||||
|
||||
let mut buckets = leaky_bucket::LeakyBuckets::new();
|
||||
let coordinator = buckets.coordinate().unwrap();
|
||||
tokio::spawn(async move { coordinator.await.expect("coordinator errored") });
|
||||
let limiter = buckets.rate_limiter().max(200).build().unwrap();
|
||||
let limiter = RateLimiter::builder()
|
||||
.interval(Duration::from_secs(1))
|
||||
.max(200)
|
||||
.build();
|
||||
|
||||
let scan = FeroxScan::new(
|
||||
"http://localhost",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#[derive(Copy, Clone, PartialEq, Debug)]
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
/// represents different situations where different criteria can trigger auto-tune/bail behavior
|
||||
pub enum PolicyTrigger {
|
||||
/// excessive 403 trigger
|
||||
|
||||
@@ -69,6 +69,10 @@ pub struct Stats {
|
||||
/// response bodies and robots.txt as of v1.11.0
|
||||
links_extracted: AtomicUsize,
|
||||
|
||||
/// tracker for number of extensions discovered when `--collect-extensions` is used; sources
|
||||
/// are response bodies
|
||||
extensions_collected: AtomicUsize,
|
||||
|
||||
/// tracker for overall number of 200s seen by the client
|
||||
status_200s: AtomicUsize,
|
||||
|
||||
@@ -166,6 +170,10 @@ impl Serialize for Stats {
|
||||
state.serialize_field("total_scans", &atomic_load!(self.total_scans))?;
|
||||
state.serialize_field("initial_targets", &atomic_load!(self.initial_targets))?;
|
||||
state.serialize_field("links_extracted", &atomic_load!(self.links_extracted))?;
|
||||
state.serialize_field(
|
||||
"extensions_collected",
|
||||
&atomic_load!(self.extensions_collected),
|
||||
)?;
|
||||
state.serialize_field("status_200s", &atomic_load!(self.status_200s))?;
|
||||
state.serialize_field("status_301s", &atomic_load!(self.status_301s))?;
|
||||
state.serialize_field("status_302s", &atomic_load!(self.status_302s))?;
|
||||
@@ -290,6 +298,13 @@ impl<'a> Deserialize<'a> for Stats {
|
||||
}
|
||||
}
|
||||
}
|
||||
"extensions_collected" => {
|
||||
if let Some(num) = value.as_u64() {
|
||||
if let Ok(parsed) = usize::try_from(num) {
|
||||
atomic_increment!(stats.extensions_collected, parsed);
|
||||
}
|
||||
}
|
||||
}
|
||||
"status_200s" => {
|
||||
if let Some(num) = value.as_u64() {
|
||||
if let Ok(parsed) = usize::try_from(num) {
|
||||
@@ -628,6 +643,9 @@ impl Stats {
|
||||
StatField::LinksExtracted => {
|
||||
atomic_increment!(self.links_extracted, value);
|
||||
}
|
||||
StatField::ExtensionsCollected => {
|
||||
atomic_increment!(self.extensions_collected, value);
|
||||
}
|
||||
StatField::WildcardsFiltered => {
|
||||
atomic_increment!(self.wildcards_filtered, value);
|
||||
atomic_increment!(self.responses_filtered, value);
|
||||
@@ -664,6 +682,10 @@ impl Stats {
|
||||
atomic_increment!(self.client_errors, atomic_load!(d_stats.client_errors));
|
||||
atomic_increment!(self.server_errors, atomic_load!(d_stats.server_errors));
|
||||
atomic_increment!(self.links_extracted, atomic_load!(d_stats.links_extracted));
|
||||
atomic_increment!(
|
||||
self.extensions_collected,
|
||||
atomic_load!(d_stats.extensions_collected)
|
||||
);
|
||||
atomic_increment!(self.status_200s, atomic_load!(d_stats.status_200s));
|
||||
atomic_increment!(self.status_301s, atomic_load!(d_stats.status_301s));
|
||||
atomic_increment!(self.status_302s, atomic_load!(d_stats.status_302s));
|
||||
@@ -834,7 +856,7 @@ mod tests {
|
||||
#[test]
|
||||
/// Stats::merge_from should properly increment expected fields and ignore others
|
||||
fn stats_merge_from_alters_correct_fields() {
|
||||
let contents = r#"{"statistics":{"type":"statistics","timeouts":1,"requests":9207,"expected_per_scan":707,"total_expected":9191,"errors":3,"successes":720,"redirects":13,"client_errors":8474,"server_errors":2,"total_scans":13,"initial_targets":1,"links_extracted":51,"status_403s":3,"status_200s":720,"status_301s":12,"status_302s":1,"status_401s":4,"status_429s":2,"status_500s":5,"status_503s":9,"status_504s":6,"status_508s":7,"wildcards_filtered":707,"responses_filtered":707,"resources_discovered":27,"directory_scan_times":[2.211973078,1.989015505,1.898675839,3.9714468910000003,4.938152838,5.256073528,6.021986595,6.065740734,6.42633762,7.095142125,7.336982137,5.319785619,4.843649778],"total_runtime":[11.556575456000001],"url_format_errors":17,"redirection_errors":12,"connection_errors":21,"request_errors":4}}"#;
|
||||
let contents = r#"{"statistics":{"type":"statistics","timeouts":1,"requests":9207,"expected_per_scan":707,"total_expected":9191,"errors":3,"successes":720,"redirects":13,"client_errors":8474,"server_errors":2,"total_scans":13,"initial_targets":1,"links_extracted":51,"extensions_collected":4,"status_403s":3,"status_200s":720,"status_301s":12,"status_302s":1,"status_401s":4,"status_429s":2,"status_500s":5,"status_503s":9,"status_504s":6,"status_508s":7,"wildcards_filtered":707,"responses_filtered":707,"resources_discovered":27,"directory_scan_times":[2.211973078,1.989015505,1.898675839,3.9714468910000003,4.938152838,5.256073528,6.021986595,6.065740734,6.42633762,7.095142125,7.336982137,5.319785619,4.843649778],"total_runtime":[11.556575456000001],"url_format_errors":17,"redirection_errors":12,"connection_errors":21,"request_errors":4}}"#;
|
||||
let config = Configuration::new().unwrap();
|
||||
let stats = Stats::new(config.json);
|
||||
|
||||
@@ -857,6 +879,7 @@ mod tests {
|
||||
assert_eq!(atomic_load!(stats.total_scans), 0); // not updated in merge_from
|
||||
assert_eq!(atomic_load!(stats.initial_targets), 0); // not updated in merge_from
|
||||
assert_eq!(atomic_load!(stats.links_extracted), 51);
|
||||
assert_eq!(atomic_load!(stats.extensions_collected), 4);
|
||||
assert_eq!(atomic_load!(stats.status_200s), 720);
|
||||
assert_eq!(atomic_load!(stats.status_301s), 12);
|
||||
assert_eq!(atomic_load!(stats.status_302s), 1);
|
||||
|
||||
@@ -13,6 +13,9 @@ pub enum StatField {
|
||||
/// Translates to `links_extracted`
|
||||
LinksExtracted,
|
||||
|
||||
/// Translates to `extensions_collected`
|
||||
ExtensionsCollected,
|
||||
|
||||
/// Translates to `total_expected`
|
||||
TotalExpected,
|
||||
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
//! collection of all traits used
|
||||
use crate::filters::{
|
||||
LinesFilter, RegexFilter, SimilarityFilter, SizeFilter, StatusCodeFilter, WildcardFilter,
|
||||
WordsFilter,
|
||||
};
|
||||
use crate::response::FeroxResponse;
|
||||
use anyhow::Result;
|
||||
use crossterm::style::{style, Stylize};
|
||||
use serde::Serialize;
|
||||
use std::any::Any;
|
||||
use std::fmt::Debug;
|
||||
use std::fmt::{self, Debug, Display, Formatter};
|
||||
|
||||
// references:
|
||||
// https://dev.to/magnusstrale/rust-trait-objects-in-a-vector-non-trivial-4co5
|
||||
@@ -22,6 +27,36 @@ pub trait FeroxFilter: Debug + Send + Sync {
|
||||
fn as_any(&self) -> &dyn Any;
|
||||
}
|
||||
|
||||
impl Display for dyn FeroxFilter {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
|
||||
if let Some(filter) = self.as_any().downcast_ref::<LinesFilter>() {
|
||||
write!(f, "Line count: {}", style(filter.line_count).cyan())
|
||||
} else if let Some(filter) = self.as_any().downcast_ref::<WordsFilter>() {
|
||||
write!(f, "Word count: {}", style(filter.word_count).cyan())
|
||||
} else if let Some(filter) = self.as_any().downcast_ref::<SizeFilter>() {
|
||||
write!(f, "Response size: {}", style(filter.content_length).cyan())
|
||||
} else if let Some(filter) = self.as_any().downcast_ref::<RegexFilter>() {
|
||||
write!(f, "Regex: {}", style(&filter.raw_string).cyan())
|
||||
} else if let Some(filter) = self.as_any().downcast_ref::<WildcardFilter>() {
|
||||
if filter.dynamic != u64::MAX {
|
||||
write!(f, "Dynamic wildcard: {}", style(filter.dynamic).cyan())
|
||||
} else {
|
||||
write!(f, "Static wildcard: {}", style(filter.size).cyan())
|
||||
}
|
||||
} else if let Some(filter) = self.as_any().downcast_ref::<StatusCodeFilter>() {
|
||||
write!(f, "Status code: {}", style(filter.filter_code).cyan())
|
||||
} else if let Some(filter) = self.as_any().downcast_ref::<SimilarityFilter>() {
|
||||
write!(
|
||||
f,
|
||||
"Pages similar to: {}",
|
||||
style(&filter.original_url).cyan()
|
||||
)
|
||||
} else {
|
||||
write!(f, "Filter: {:?}", self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// implementation of PartialEq, necessary long-form due to "trait cannot be made into an object"
|
||||
/// error when attempting to derive PartialEq on the trait itself
|
||||
impl PartialEq for Box<dyn FeroxFilter> {
|
||||
|
||||
23
src/url.rs
23
src/url.rs
@@ -1,6 +1,7 @@
|
||||
use crate::{event_handlers::Handles, statistics::StatError::UrlFormat, Command::AddError};
|
||||
use anyhow::{anyhow, bail, Result};
|
||||
use reqwest::Url;
|
||||
use std::collections::HashSet;
|
||||
use std::{convert::TryInto, fmt, sync::Arc};
|
||||
|
||||
/// abstraction around target urls; collects all Url related shenanigans in one place
|
||||
@@ -37,7 +38,11 @@ impl FeroxUrl {
|
||||
///
|
||||
/// If any extensions were passed to the program, each extension will add a
|
||||
/// (base_url + word + ext) Url to the vector
|
||||
pub fn formatted_urls(&self, word: &str) -> Result<Vec<Url>> {
|
||||
pub fn formatted_urls(
|
||||
&self,
|
||||
word: &str,
|
||||
collected_extensions: HashSet<String>,
|
||||
) -> Result<Vec<Url>> {
|
||||
log::trace!("enter: formatted_urls({})", word);
|
||||
|
||||
let mut urls = vec![];
|
||||
@@ -54,7 +59,13 @@ impl FeroxUrl {
|
||||
Err(_) => self.handles.stats.send(AddError(UrlFormat))?,
|
||||
}
|
||||
|
||||
for ext in self.handles.config.extensions.iter() {
|
||||
for ext in self
|
||||
.handles
|
||||
.config
|
||||
.extensions
|
||||
.iter()
|
||||
.chain(collected_extensions.iter())
|
||||
{
|
||||
match self.format(word, Some(ext)) {
|
||||
// any extensions passed in
|
||||
Ok(url) => urls.push(url),
|
||||
@@ -254,7 +265,7 @@ mod tests {
|
||||
fn formatted_urls_no_extension_returns_base_url_with_word() {
|
||||
let handles = Arc::new(Handles::for_testing(None, None).0);
|
||||
let url = FeroxUrl::from_string("http://localhost", handles);
|
||||
let urls = url.formatted_urls("turbo").unwrap();
|
||||
let urls = url.formatted_urls("turbo", HashSet::new()).unwrap();
|
||||
assert_eq!(urls, [Url::parse("http://localhost/turbo").unwrap()])
|
||||
}
|
||||
|
||||
@@ -268,7 +279,7 @@ mod tests {
|
||||
|
||||
let handles = Arc::new(Handles::for_testing(None, Some(Arc::new(config))).0);
|
||||
let url = FeroxUrl::from_string("http://localhost", handles);
|
||||
let urls = url.formatted_urls("turbo").unwrap();
|
||||
let urls = url.formatted_urls("turbo", HashSet::new()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
urls,
|
||||
@@ -315,7 +326,7 @@ mod tests {
|
||||
let handles = Arc::new(Handles::for_testing(None, Some(Arc::new(config))).0);
|
||||
let url = FeroxUrl::from_string("http://localhost", handles);
|
||||
|
||||
let urls = url.formatted_urls("turbo").unwrap();
|
||||
let urls = url.formatted_urls("turbo", HashSet::new()).unwrap();
|
||||
assert_eq!(urls, expected[i]);
|
||||
}
|
||||
}
|
||||
@@ -502,7 +513,7 @@ mod tests {
|
||||
};
|
||||
let handles = Arc::new(Handles::for_testing(None, Some(Arc::new(config))).0);
|
||||
let url = FeroxUrl::from_string("http://localhost", handles);
|
||||
match url.formatted_urls("ferox") {
|
||||
match url.formatted_urls("ferox", HashSet::new()) {
|
||||
Ok(urls) => {
|
||||
// 3 = One for the main word + slash and for the two extensions
|
||||
assert_eq!(urls.len(), 3);
|
||||
|
||||
110
src/utils.rs
110
src/utils.rs
@@ -2,7 +2,7 @@ use anyhow::{bail, Context, Result};
|
||||
use console::{strip_ansi_codes, style, user_attended};
|
||||
use indicatif::ProgressBar;
|
||||
use regex::Regex;
|
||||
use reqwest::{Client, Response, StatusCode, Url};
|
||||
use reqwest::{Client, Method, Response, StatusCode, Url};
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
use rlimit::{getrlimit, setrlimit, Resource};
|
||||
use std::{
|
||||
@@ -12,16 +12,17 @@ use std::{
|
||||
time::Duration,
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
use tokio::sync::mpsc::UnboundedSender;
|
||||
use tokio::sync::{mpsc::UnboundedSender, oneshot};
|
||||
|
||||
use crate::config::Configuration;
|
||||
use crate::{
|
||||
config::Configuration,
|
||||
config::OutputLevel,
|
||||
event_handlers::{
|
||||
Command::{self, AddError, AddStatus},
|
||||
Handles,
|
||||
},
|
||||
progress::PROGRESS_PRINTER,
|
||||
response::FeroxResponse,
|
||||
send_command,
|
||||
statistics::StatError::{Connection, Other, Redirection, Request, Timeout},
|
||||
traits::FeroxSerialize,
|
||||
@@ -67,6 +68,20 @@ pub fn fmt_err(msg: &str) -> String {
|
||||
format!("{}: {}", status_colorizer("ERROR"), msg)
|
||||
}
|
||||
|
||||
/// given a FeroxResponse, send a TryRecursion command
|
||||
///
|
||||
/// moved to utils to allow for calls from extractor and scanner
|
||||
pub(crate) async fn send_try_recursion_command(
|
||||
handles: Arc<Handles>,
|
||||
response: FeroxResponse,
|
||||
) -> Result<()> {
|
||||
handles.send_scan_command(Command::TryRecursion(Box::new(response.clone())))?;
|
||||
let (tx, rx) = oneshot::channel::<bool>();
|
||||
handles.send_scan_command(Command::Sync(tx))?;
|
||||
rx.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Takes in a string and colors it using console::style
|
||||
///
|
||||
/// mainly putting this here in case i want to change the color later, making any changes easy
|
||||
@@ -95,15 +110,19 @@ pub fn ferox_print(msg: &str, bar: &ProgressBar) {
|
||||
|
||||
/// wrapper for make_request used to pass error/response codes to FeroxScans for per-scan stats
|
||||
/// tracking of information related to auto-tune/bail
|
||||
pub async fn logged_request(url: &Url, handles: Arc<Handles>) -> Result<Response> {
|
||||
pub async fn logged_request(
|
||||
url: &Url,
|
||||
method: &str,
|
||||
data: Option<&[u8]>,
|
||||
handles: Arc<Handles>,
|
||||
) -> Result<Response> {
|
||||
let client = &handles.config.client;
|
||||
let level = handles.config.output_level;
|
||||
let tx_stats = handles.stats.tx.clone();
|
||||
|
||||
let response = make_request(client, url, level, &handles.config, tx_stats).await;
|
||||
let response = make_request(client, url, method, data, level, &handles.config, tx_stats).await;
|
||||
|
||||
let scans = handles.ferox_scans()?;
|
||||
|
||||
match response {
|
||||
Ok(resp) => {
|
||||
match resp.status() {
|
||||
@@ -126,6 +145,8 @@ pub async fn logged_request(url: &Url, handles: Arc<Handles>) -> Result<Response
|
||||
pub async fn make_request(
|
||||
client: &Client,
|
||||
url: &Url,
|
||||
method: &str,
|
||||
mut data: Option<&[u8]>,
|
||||
output_level: OutputLevel,
|
||||
config: &Configuration,
|
||||
tx_stats: UnboundedSender<Command>,
|
||||
@@ -136,8 +157,33 @@ pub async fn make_request(
|
||||
output_level,
|
||||
tx_stats
|
||||
);
|
||||
let tmp_workaround: Option<&[u8]> = Some(&[0xd_u8, 0xa]); // \r\n
|
||||
|
||||
let mut request = client.get(url.to_owned());
|
||||
let mut request = client.request(Method::from_bytes(method.as_bytes())?, url.to_owned());
|
||||
|
||||
if (!config.proxy.is_empty() || !config.replay_proxy.is_empty())
|
||||
&& data.is_none()
|
||||
&& ["post", "put", "patch"].contains(&method.to_ascii_lowercase().as_str())
|
||||
{
|
||||
// either --proxy or --replay-proxy was specified
|
||||
// AND
|
||||
// --data wasn't used
|
||||
// AND
|
||||
// the method is either post/put/patch (case insensitive)
|
||||
//
|
||||
// this combination of factors results in requests that are delayed for 10 seconds before
|
||||
// being issued. The tracking issues are
|
||||
// https://github.com/epi052/feroxbuster/issues/501
|
||||
// https://github.com/seanmonstar/reqwest/issues/1474
|
||||
//
|
||||
// as a (hopefully temporary) workaround, we'll add \r\n to the body so that there's no
|
||||
// delay
|
||||
data = tmp_workaround;
|
||||
}
|
||||
|
||||
if let Some(body_data) = data {
|
||||
request = request.body(body_data.to_vec());
|
||||
}
|
||||
|
||||
if config.random_agent {
|
||||
let index = unsafe {
|
||||
@@ -159,22 +205,28 @@ pub async fn make_request(
|
||||
} else if e.is_redirect() {
|
||||
if let Some(last_redirect) = e.url() {
|
||||
// get where we were headed (last_redirect) and where we came from (url)
|
||||
let fancy_message = format!("{} !=> {}", url, last_redirect);
|
||||
let fancy_message = format!(
|
||||
"{} !=> {} ({})",
|
||||
url,
|
||||
last_redirect,
|
||||
style("too many redirects").red(),
|
||||
);
|
||||
|
||||
let report = if let Some(msg_status) = e.status() {
|
||||
send_command!(tx_stats, AddStatus(msg_status));
|
||||
create_report_string(
|
||||
msg_status.as_str(),
|
||||
"-1",
|
||||
"-1",
|
||||
"-1",
|
||||
&fancy_message,
|
||||
output_level,
|
||||
)
|
||||
} else {
|
||||
create_report_string("UNK", "-1", "-1", "-1", &fancy_message, output_level)
|
||||
let msg_status = match e.status() {
|
||||
Some(status) => status.to_string(),
|
||||
None => "ERR".to_string(),
|
||||
};
|
||||
|
||||
let report = create_report_string(
|
||||
&msg_status,
|
||||
method,
|
||||
"-1",
|
||||
"-1",
|
||||
"-1",
|
||||
&fancy_message,
|
||||
output_level,
|
||||
);
|
||||
|
||||
send_command!(tx_stats, AddError(Redirection));
|
||||
|
||||
ferox_print(&report, &PROGRESS_PRINTER)
|
||||
@@ -204,6 +256,7 @@ pub async fn make_request(
|
||||
/// 200 127l 283w 4134c http://localhost/faq
|
||||
pub fn create_report_string(
|
||||
status: &str,
|
||||
method: &str,
|
||||
line_count: &str,
|
||||
word_count: &str,
|
||||
content_length: &str,
|
||||
@@ -216,10 +269,17 @@ pub fn create_report_string(
|
||||
} else {
|
||||
// normal printing with status and sizes
|
||||
let color_status = status_colorizer(status);
|
||||
format!(
|
||||
"{} {:>8}l {:>8}w {:>8}c {}\n",
|
||||
color_status, line_count, word_count, content_length, url
|
||||
)
|
||||
if status.contains("MSG") {
|
||||
format!(
|
||||
"{} {:>8} {:>9} {:>9} {:>9} {}\n",
|
||||
color_status, method, line_count, word_count, content_length, url
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"{} {:>8} {:>8}l {:>8}w {:>8}c {}\n",
|
||||
color_status, method, line_count, word_count, content_length, url
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -466,7 +526,7 @@ pub fn slugify_filename(url: &str, prefix: &str, suffix: &str) -> String {
|
||||
String::new()
|
||||
};
|
||||
|
||||
let slug = url.replace("://", "_").replace("/", "_").replace(".", "_");
|
||||
let slug = url.replace("://", "_").replace(['/', '.'], "_");
|
||||
|
||||
let filename = format!("{}{}-{}.{}", altered_prefix, slug, ts, suffix);
|
||||
|
||||
|
||||
@@ -16,10 +16,10 @@ fn banner_prints_proxy() -> Result<(), Box<dyn std::error::Error>> {
|
||||
Command::cargo_bin("feroxbuster")
|
||||
.unwrap()
|
||||
.arg("--stdin")
|
||||
.arg("--wordlist")
|
||||
.arg(file.as_os_str())
|
||||
.arg("--proxy")
|
||||
.arg("http://127.0.0.1:8080")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.pipe_stdin(file)
|
||||
.unwrap()
|
||||
.assert()
|
||||
@@ -57,7 +57,7 @@ fn banner_prints_replay_proxy() -> Result<(), Box<dyn std::error::Error>> {
|
||||
.unwrap()
|
||||
.arg("--stdin")
|
||||
.arg("--wordlist")
|
||||
.arg(file.as_os_str())
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.arg("--replay-proxy")
|
||||
.arg("http://127.0.0.1:8081")
|
||||
.pipe_stdin(file)
|
||||
@@ -95,6 +95,8 @@ fn banner_prints_headers() {
|
||||
.arg("stuff:things")
|
||||
.arg("-H")
|
||||
.arg("mostuff:mothings")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -126,6 +128,8 @@ fn banner_prints_denied_urls() {
|
||||
.arg("https://also-not.me")
|
||||
.arg("https:")
|
||||
.arg("/deny.*")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -156,6 +160,8 @@ fn banner_prints_random_agent() {
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("--random-agent")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -192,6 +198,8 @@ fn banner_prints_filter_sizes() {
|
||||
.arg("93")
|
||||
.arg("--filter-words")
|
||||
.arg("94")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -228,6 +236,8 @@ fn banner_prints_queries() {
|
||||
.arg("token=supersecret")
|
||||
.arg("--query")
|
||||
.arg("stuff=things")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -256,6 +266,8 @@ fn banner_prints_status_codes() {
|
||||
.arg("http://localhost")
|
||||
.arg("-s")
|
||||
.arg("201,301,401")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -284,6 +296,8 @@ fn banner_prints_replay_codes() {
|
||||
.arg("200,302")
|
||||
.arg("--replay-proxy")
|
||||
.arg("http://localhost:8081")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -312,6 +326,8 @@ fn banner_prints_output_file() {
|
||||
.arg("http://localhost")
|
||||
.arg("--output")
|
||||
.arg("/super/cool/path")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -326,7 +342,7 @@ fn banner_prints_output_file() {
|
||||
.and(predicate::str::contains("Output File"))
|
||||
.and(predicate::str::contains("/super/cool/path"))
|
||||
.and(predicate::str::contains(
|
||||
"ERROR: Couldn't start /super/cool/path file handler",
|
||||
"Could not open /definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676",
|
||||
))
|
||||
.and(predicate::str::contains("─┴─")),
|
||||
);
|
||||
@@ -341,6 +357,8 @@ fn banner_prints_insecure() {
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("-k")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -367,6 +385,8 @@ fn banner_prints_redirects() {
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("-r")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -396,6 +416,8 @@ fn banner_prints_extensions() {
|
||||
.arg("js")
|
||||
.arg("--extensions")
|
||||
.arg("pdf")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -422,6 +444,8 @@ fn banner_prints_dont_filter() {
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("--dont-filter")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -448,6 +472,8 @@ fn banner_prints_verbosity_one() {
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("-v")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -474,6 +500,8 @@ fn banner_prints_verbosity_two() {
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("-vv")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -500,6 +528,8 @@ fn banner_prints_verbosity_three() {
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("-vvv")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -526,6 +556,8 @@ fn banner_prints_verbosity_four() {
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("-vvvv")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -552,6 +584,8 @@ fn banner_prints_add_slash() {
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("-f")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -579,6 +613,8 @@ fn banner_prints_infinite_depth() {
|
||||
.arg("http://localhost")
|
||||
.arg("--depth")
|
||||
.arg("0")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -606,6 +642,8 @@ fn banner_prints_recursion_depth() {
|
||||
.arg("http://localhost")
|
||||
.arg("--depth")
|
||||
.arg("343214")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -632,6 +670,8 @@ fn banner_prints_no_recursion() {
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("-n")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -658,10 +698,12 @@ fn banner_doesnt_print() {
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("-q")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(predicate::str::contains(
|
||||
"Could not connect to any target provided",
|
||||
"Could not open /definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676",
|
||||
));
|
||||
}
|
||||
|
||||
@@ -674,6 +716,8 @@ fn banner_prints_extract_links() {
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("-e")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -701,6 +745,8 @@ fn banner_prints_scan_limit() {
|
||||
.arg("http://localhost")
|
||||
.arg("-L")
|
||||
.arg("4")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -728,6 +774,8 @@ fn banner_prints_filter_status() {
|
||||
.arg("http://localhost")
|
||||
.arg("-C")
|
||||
.arg("200")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -736,7 +784,6 @@ fn banner_prints_filter_status() {
|
||||
.and(predicate::str::contains("http://localhost"))
|
||||
.and(predicate::str::contains("Threads"))
|
||||
.and(predicate::str::contains("Wordlist"))
|
||||
.and(predicate::str::contains("Status Codes"))
|
||||
.and(predicate::str::contains("Timeout (secs)"))
|
||||
.and(predicate::str::contains("User-Agent"))
|
||||
.and(predicate::str::contains("Status Code Filters"))
|
||||
@@ -756,6 +803,8 @@ fn banner_prints_json() {
|
||||
.arg("--json")
|
||||
.arg("--output")
|
||||
.arg("/dev/null")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -783,6 +832,8 @@ fn banner_prints_debug_log() {
|
||||
.arg("http://localhost")
|
||||
.arg("--debug-log")
|
||||
.arg("/dev/null")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -810,6 +861,8 @@ fn banner_prints_filter_regex() {
|
||||
.arg("http://localhost")
|
||||
.arg("--filter-regex")
|
||||
.arg("^ignore me$")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -837,6 +890,8 @@ fn banner_prints_time_limit() {
|
||||
.arg("http://localhost")
|
||||
.arg("--time-limit")
|
||||
.arg("10m")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -864,6 +919,8 @@ fn banner_prints_similarity_filter() {
|
||||
.arg("http://localhost")
|
||||
.arg("--filter-similar-to")
|
||||
.arg("https://somesite.com")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -891,6 +948,8 @@ fn banner_prints_rate_limit() {
|
||||
.arg("http://localhost")
|
||||
.arg("--rate-limit")
|
||||
.arg("6735")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -917,6 +976,8 @@ fn banner_prints_auto_tune() {
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("--auto-tune")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -943,6 +1004,8 @@ fn banner_prints_auto_bail() {
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("--auto-bail")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -969,6 +1032,8 @@ fn banner_doesnt_print_when_silent() {
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("--silent")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -993,6 +1058,8 @@ fn banner_doesnt_print_when_quiet() {
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("--quiet")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
@@ -1017,17 +1084,339 @@ fn banner_prints_parallel() {
|
||||
.arg("--stdin")
|
||||
.arg("--parallel")
|
||||
.arg("4316")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
predicate::str::contains("─┬─")
|
||||
.not()
|
||||
.and(predicate::str::contains("Target Url").not())
|
||||
.and(predicate::str::contains("Parallel Scans").not())
|
||||
.and(predicate::str::contains("Threads").not())
|
||||
.and(predicate::str::contains("Wordlist").not())
|
||||
.and(predicate::str::contains("Status Codes").not())
|
||||
.and(predicate::str::contains("Timeout (secs)").not())
|
||||
.and(predicate::str::contains("User-Agent").not()),
|
||||
.and(predicate::str::contains("Parallel Scans"))
|
||||
.and(predicate::str::contains("4316"))
|
||||
.and(predicate::str::contains("Threads"))
|
||||
.and(predicate::str::contains("Wordlist"))
|
||||
.and(predicate::str::contains("Status Codes"))
|
||||
.and(predicate::str::contains("Timeout (secs)"))
|
||||
.and(predicate::str::contains("User-Agent")),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// test allows non-existent wordlist to trigger the banner printing to stderr
|
||||
/// expect to see all mandatory prints + methods
|
||||
fn banner_prints_methods() {
|
||||
Command::cargo_bin("feroxbuster")
|
||||
.unwrap()
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("-m")
|
||||
.arg("PUT")
|
||||
.arg("--methods")
|
||||
.arg("OPTIONS")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
predicate::str::contains("─┬─")
|
||||
.and(predicate::str::contains("Target Url"))
|
||||
.and(predicate::str::contains("http://localhost"))
|
||||
.and(predicate::str::contains("Threads"))
|
||||
.and(predicate::str::contains("Wordlist"))
|
||||
.and(predicate::str::contains("Status Codes"))
|
||||
.and(predicate::str::contains("Timeout (secs)"))
|
||||
.and(predicate::str::contains("User-Agent"))
|
||||
.and(predicate::str::contains("HTTP methods"))
|
||||
.and(predicate::str::contains("[PUT, OPTIONS]"))
|
||||
.and(predicate::str::contains("─┴─")),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// test allows non-existent wordlist to trigger the banner printing to stderr
|
||||
/// expect to see all mandatory prints + data body
|
||||
fn banner_prints_data() {
|
||||
Command::cargo_bin("feroxbuster")
|
||||
.unwrap()
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("-m")
|
||||
.arg("PUT")
|
||||
.arg("--methods")
|
||||
.arg("POST")
|
||||
.arg("--data")
|
||||
.arg("some_data")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
predicate::str::contains("─┬─")
|
||||
.and(predicate::str::contains("Target Url"))
|
||||
.and(predicate::str::contains("http://localhost"))
|
||||
.and(predicate::str::contains("Threads"))
|
||||
.and(predicate::str::contains("Wordlist"))
|
||||
.and(predicate::str::contains("Status Codes"))
|
||||
.and(predicate::str::contains("Timeout (secs)"))
|
||||
.and(predicate::str::contains("User-Agent"))
|
||||
.and(predicate::str::contains("HTTP Body"))
|
||||
.and(predicate::str::contains("some_data"))
|
||||
.and(predicate::str::contains("─┴─")),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// test allows non-existent wordlist to trigger the banner printing to stderr
|
||||
/// expect to see all mandatory prints + ignored extensions
|
||||
fn banner_prints_collect_extensions_and_dont_collect_default() {
|
||||
Command::cargo_bin("feroxbuster")
|
||||
.unwrap()
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("--collect-extensions")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
predicate::str::contains("─┬─")
|
||||
.and(predicate::str::contains("Target Url"))
|
||||
.and(predicate::str::contains("http://localhost"))
|
||||
.and(predicate::str::contains("Threads"))
|
||||
.and(predicate::str::contains("Wordlist"))
|
||||
.and(predicate::str::contains("Status Codes"))
|
||||
.and(predicate::str::contains("Timeout (secs)"))
|
||||
.and(predicate::str::contains("User-Agent"))
|
||||
.and(predicate::str::contains("Collect Extensions"))
|
||||
.and(predicate::str::contains("Ignored Extensions"))
|
||||
.and(predicate::str::contains("Images, Movies, Audio, etc..."))
|
||||
.and(predicate::str::contains("─┴─")),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// test allows non-existent wordlist to trigger the banner printing to stderr
|
||||
/// expect to see all mandatory prints + collect extensions
|
||||
fn banner_prints_collect_extensions_and_dont_collect_with_input() {
|
||||
Command::cargo_bin("feroxbuster")
|
||||
.unwrap()
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("--collect-extensions")
|
||||
.arg("--dont-collect")
|
||||
.arg("pdf")
|
||||
.arg("xps")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
predicate::str::contains("─┬─")
|
||||
.and(predicate::str::contains("Target Url"))
|
||||
.and(predicate::str::contains("http://localhost"))
|
||||
.and(predicate::str::contains("Threads"))
|
||||
.and(predicate::str::contains("Wordlist"))
|
||||
.and(predicate::str::contains("Status Codes"))
|
||||
.and(predicate::str::contains("Timeout (secs)"))
|
||||
.and(predicate::str::contains("User-Agent"))
|
||||
.and(predicate::str::contains("Collect Extensions"))
|
||||
.and(predicate::str::contains("Ignored Extensions"))
|
||||
.and(predicate::str::contains("[pdf, xps]"))
|
||||
.and(predicate::str::contains("─┴─")),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// test allows non-existent wordlist to trigger the banner printing to stderr
|
||||
/// expect to see all mandatory prints + collect backups
|
||||
fn banner_prints_collect_backups() {
|
||||
Command::cargo_bin("feroxbuster")
|
||||
.unwrap()
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("--collect-backups")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
predicate::str::contains("─┬─")
|
||||
.and(predicate::str::contains("Target Url"))
|
||||
.and(predicate::str::contains("http://localhost"))
|
||||
.and(predicate::str::contains("Threads"))
|
||||
.and(predicate::str::contains("Wordlist"))
|
||||
.and(predicate::str::contains("Status Codes"))
|
||||
.and(predicate::str::contains("Timeout (secs)"))
|
||||
.and(predicate::str::contains("User-Agent"))
|
||||
.and(predicate::str::contains("Collect Backups"))
|
||||
.and(predicate::str::contains("─┴─")),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// test allows non-existent wordlist to trigger the banner printing to stderr
|
||||
/// expect to see all mandatory prints + collect words
|
||||
fn banner_prints_collect_words() {
|
||||
Command::cargo_bin("feroxbuster")
|
||||
.unwrap()
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("--collect-words")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
predicate::str::contains("─┬─")
|
||||
.and(predicate::str::contains("Target Url"))
|
||||
.and(predicate::str::contains("http://localhost"))
|
||||
.and(predicate::str::contains("Threads"))
|
||||
.and(predicate::str::contains("Wordlist"))
|
||||
.and(predicate::str::contains("Status Codes"))
|
||||
.and(predicate::str::contains("Timeout (secs)"))
|
||||
.and(predicate::str::contains("User-Agent"))
|
||||
.and(predicate::str::contains("Collect Words"))
|
||||
.and(predicate::str::contains("─┴─")),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// test allows non-existent wordlist to trigger the banner printing to stderr
|
||||
/// expect to see all mandatory prints + collect words
|
||||
fn banner_prints_all_composite_settings_smart() {
|
||||
Command::cargo_bin("feroxbuster")
|
||||
.unwrap()
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("--smart")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
predicate::str::contains("─┬─")
|
||||
.and(predicate::str::contains("Target Url"))
|
||||
.and(predicate::str::contains("http://localhost"))
|
||||
.and(predicate::str::contains("Threads"))
|
||||
.and(predicate::str::contains("Wordlist"))
|
||||
.and(predicate::str::contains("Status Codes"))
|
||||
.and(predicate::str::contains("Timeout (secs)"))
|
||||
.and(predicate::str::contains("User-Agent"))
|
||||
.and(predicate::str::contains("Collect Words"))
|
||||
.and(predicate::str::contains("Collect Backups"))
|
||||
.and(predicate::str::contains("Extract Links"))
|
||||
.and(predicate::str::contains("Auto Tune"))
|
||||
.and(predicate::str::contains("─┴─")),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// test allows non-existent wordlist to trigger the banner printing to stderr
|
||||
/// expect to see all mandatory prints + collect words
|
||||
fn banner_prints_all_composite_settings_thorough() {
|
||||
Command::cargo_bin("feroxbuster")
|
||||
.unwrap()
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("--thorough")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
predicate::str::contains("─┬─")
|
||||
.and(predicate::str::contains("Target Url"))
|
||||
.and(predicate::str::contains("http://localhost"))
|
||||
.and(predicate::str::contains("Threads"))
|
||||
.and(predicate::str::contains("Wordlist"))
|
||||
.and(predicate::str::contains("Status Codes"))
|
||||
.and(predicate::str::contains("Timeout (secs)"))
|
||||
.and(predicate::str::contains("User-Agent"))
|
||||
.and(predicate::str::contains("Collect Words"))
|
||||
.and(predicate::str::contains("Collect Extensions"))
|
||||
.and(predicate::str::contains("Collect Backups"))
|
||||
.and(predicate::str::contains("Extract Links"))
|
||||
.and(predicate::str::contains("Auto Tune"))
|
||||
.and(predicate::str::contains("─┴─")),
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
/// test allows non-existent wordlist to trigger the banner printing to stderr
|
||||
/// expect to see all mandatory prints + collect words
|
||||
fn banner_prints_all_composite_settings_burp() {
|
||||
Command::cargo_bin("feroxbuster")
|
||||
.unwrap()
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("--burp")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
predicate::str::contains("─┬─")
|
||||
.and(predicate::str::contains("Target Url"))
|
||||
.and(predicate::str::contains("http://localhost"))
|
||||
.and(predicate::str::contains("Threads"))
|
||||
.and(predicate::str::contains("Wordlist"))
|
||||
.and(predicate::str::contains("Status Codes"))
|
||||
.and(predicate::str::contains("Timeout (secs)"))
|
||||
.and(predicate::str::contains("User-Agent"))
|
||||
.and(predicate::str::contains("Proxy"))
|
||||
.and(predicate::str::contains("Insecure"))
|
||||
.and(predicate::str::contains("─┴─")),
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
/// test allows non-existent wordlist to trigger the banner printing to stderr
|
||||
/// expect to see all mandatory prints + collect words
|
||||
fn banner_prints_all_composite_settings_burp_replay() {
|
||||
Command::cargo_bin("feroxbuster")
|
||||
.unwrap()
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("--burp-replay")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
predicate::str::contains("─┬─")
|
||||
.and(predicate::str::contains("Target Url"))
|
||||
.and(predicate::str::contains("http://localhost"))
|
||||
.and(predicate::str::contains("Threads"))
|
||||
.and(predicate::str::contains("Wordlist"))
|
||||
.and(predicate::str::contains("Status Codes"))
|
||||
.and(predicate::str::contains("Timeout (secs)"))
|
||||
.and(predicate::str::contains("User-Agent"))
|
||||
.and(predicate::str::contains("Replay Proxy"))
|
||||
.and(predicate::str::contains("Insecure"))
|
||||
.and(predicate::str::contains("─┴─")),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// test allows non-existent wordlist to trigger the banner printing to stderr
|
||||
/// expect to see all mandatory prints + force recursion
|
||||
fn banner_prints_force_recursion() {
|
||||
Command::cargo_bin("feroxbuster")
|
||||
.unwrap()
|
||||
.arg("--url")
|
||||
.arg("http://localhost")
|
||||
.arg("--force-recursion")
|
||||
.arg("--wordlist")
|
||||
.arg("/definitely/doesnt/exist/0cd7fed0-47f4-4b18-a1b0-ac39708c1676")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(
|
||||
predicate::str::contains("─┬─")
|
||||
.and(predicate::str::contains("Target Url"))
|
||||
.and(predicate::str::contains("http://localhost"))
|
||||
.and(predicate::str::contains("Threads"))
|
||||
.and(predicate::str::contains("Wordlist"))
|
||||
.and(predicate::str::contains("Status Codes"))
|
||||
.and(predicate::str::contains("Timeout (secs)"))
|
||||
.and(predicate::str::contains("User-Agent"))
|
||||
.and(predicate::str::contains("Force Recursion"))
|
||||
.and(predicate::str::contains("─┴─")),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ fn deny_list_works_during_extraction() {
|
||||
let mock = srv.mock(|when, then| {
|
||||
when.method(GET).path("/LICENSE");
|
||||
then.status(200)
|
||||
.body(&srv.url("'/homepage/assets/img/icons/handshake.svg'"));
|
||||
.body(srv.url("'/homepage/assets/img/icons/handshake.svg'"));
|
||||
});
|
||||
|
||||
let mock_two = srv.mock(|when, then| {
|
||||
@@ -90,17 +90,17 @@ fn deny_list_works_during_recursion() {
|
||||
|
||||
let js_mock = srv.mock(|when, then| {
|
||||
when.method(GET).path("/js");
|
||||
then.status(301).header("Location", &srv.url("/js/"));
|
||||
then.status(301).header("Location", srv.url("/js/"));
|
||||
});
|
||||
|
||||
let js_prod_mock = srv.mock(|when, then| {
|
||||
when.method(GET).path("/js/prod");
|
||||
then.status(301).header("Location", &srv.url("/js/prod/"));
|
||||
then.status(301).header("Location", srv.url("/js/prod/"));
|
||||
});
|
||||
|
||||
let js_dev_mock = srv.mock(|when, then| {
|
||||
when.method(GET).path("/js/dev");
|
||||
then.status(301).header("Location", &srv.url("/js/dev/"));
|
||||
then.status(301).header("Location", srv.url("/js/dev/"));
|
||||
});
|
||||
|
||||
let js_dev_file_mock = srv.mock(|when, then| {
|
||||
@@ -131,8 +131,8 @@ fn deny_list_works_during_recursion() {
|
||||
.not(),
|
||||
);
|
||||
|
||||
assert_eq!(js_mock.hits(), 1);
|
||||
assert_eq!(js_prod_mock.hits(), 1);
|
||||
assert_eq!(js_mock.hits(), 2);
|
||||
assert_eq!(js_prod_mock.hits(), 2);
|
||||
assert_eq!(js_dev_mock.hits(), 0);
|
||||
assert_eq!(js_dev_file_mock.hits(), 0);
|
||||
|
||||
@@ -155,7 +155,7 @@ fn deny_list_works_during_recursion_with_inverted_parents() {
|
||||
|
||||
let js_mock = srv.mock(|when, then| {
|
||||
when.method(GET).path("/js");
|
||||
then.status(301).header("Location", &srv.url("/js/"));
|
||||
then.status(301).header("Location", srv.url("/js/"));
|
||||
});
|
||||
|
||||
let api_mock = srv.mock(|when, then| {
|
||||
@@ -165,12 +165,12 @@ fn deny_list_works_during_recursion_with_inverted_parents() {
|
||||
|
||||
let js_prod_mock = srv.mock(|when, then| {
|
||||
when.method(GET).path("/js/prod");
|
||||
then.status(301).header("Location", &srv.url("/js/prod/"));
|
||||
then.status(301).header("Location", srv.url("/js/prod/"));
|
||||
});
|
||||
|
||||
let js_dev_mock = srv.mock(|when, then| {
|
||||
when.method(GET).path("/js/dev");
|
||||
then.status(301).header("Location", &srv.url("/js/dev/"));
|
||||
then.status(301).header("Location", srv.url("/js/dev/"));
|
||||
});
|
||||
|
||||
let js_dev_file_mock = srv.mock(|when, then| {
|
||||
@@ -202,9 +202,9 @@ fn deny_list_works_during_recursion_with_inverted_parents() {
|
||||
.not(),
|
||||
);
|
||||
|
||||
assert_eq!(js_mock.hits(), 1);
|
||||
assert_eq!(js_prod_mock.hits(), 1);
|
||||
assert_eq!(js_dev_mock.hits(), 1);
|
||||
assert_eq!(js_mock.hits(), 2);
|
||||
assert_eq!(js_prod_mock.hits(), 2);
|
||||
assert_eq!(js_dev_mock.hits(), 2);
|
||||
assert_eq!(js_dev_file_mock.hits(), 1);
|
||||
assert_eq!(api_mock.hits(), 0);
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ fn extractor_finds_absolute_url() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mock = srv.mock(|when, then| {
|
||||
when.method(GET).path("/LICENSE");
|
||||
then.status(200)
|
||||
.body(&srv.url("'/homepage/assets/img/icons/handshake.svg'"));
|
||||
.body(srv.url("'/homepage/assets/img/icons/handshake.svg'"));
|
||||
});
|
||||
|
||||
let mock_two = srv.mock(|when, then| {
|
||||
@@ -136,13 +136,13 @@ fn extractor_finds_same_relative_url_twice() {
|
||||
let mock = srv.mock(|when, then| {
|
||||
when.method(GET).path("/LICENSE");
|
||||
then.status(200)
|
||||
.body(&srv.url("\"/homepage/assets/img/icons/handshake.svg\""));
|
||||
.body(srv.url("\"/homepage/assets/img/icons/handshake.svg\""));
|
||||
});
|
||||
|
||||
let mock_two = srv.mock(|when, then| {
|
||||
when.method(GET).path("/README");
|
||||
then.status(200)
|
||||
.body(&srv.url("\"/homepage/assets/img/icons/handshake.svg\""));
|
||||
.body(srv.url("\"/homepage/assets/img/icons/handshake.svg\""));
|
||||
});
|
||||
|
||||
let mock_three = srv.mock(|when, then| {
|
||||
@@ -185,7 +185,7 @@ fn extractor_finds_filtered_content() -> Result<(), Box<dyn std::error::Error>>
|
||||
let mock = srv.mock(|when, then| {
|
||||
when.method(GET).path("/LICENSE");
|
||||
then.status(200)
|
||||
.body(&srv.url("\"/homepage/assets/img/icons/handshake.svg\""));
|
||||
.body(srv.url("\"/homepage/assets/img/icons/handshake.svg\""));
|
||||
});
|
||||
|
||||
let mock_two = srv.mock(|when, then| {
|
||||
@@ -284,11 +284,11 @@ fn extractor_finds_robots_txt_links_and_displays_files_or_scans_directories() {
|
||||
.and(predicate::str::contains("22c"))
|
||||
.and(predicate::str::contains("/misc/LICENSE"))
|
||||
.and(predicate::str::contains("29c"))
|
||||
.and(predicate::str::contains("200").count(3)),
|
||||
.and(predicate::str::contains("200").count(4)),
|
||||
);
|
||||
|
||||
assert_eq!(mock.hits(), 1);
|
||||
assert_eq!(mock_dir.hits(), 1);
|
||||
assert_eq!(mock_dir.hits(), 3);
|
||||
assert_eq!(mock_two.hits(), 1);
|
||||
assert_eq!(mock_file.hits(), 1);
|
||||
assert_eq!(mock_disallowed.hits(), 1);
|
||||
@@ -370,6 +370,226 @@ fn extractor_finds_robots_txt_links_and_displays_files_non_recursive() {
|
||||
teardown_tmp_directory(tmp_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// serve a directory listing with a file and and a folder contained within it. ferox should
|
||||
/// find both links and request each one.
|
||||
fn extractor_finds_directory_listing_links_and_displays_files() {
|
||||
let srv = MockServer::start();
|
||||
let (tmp_dir, file) = setup_tmp_directory(&["invalid".to_string()], "wordlist").unwrap();
|
||||
|
||||
let mock_root = srv.mock(|when, then| {
|
||||
when.method(GET).path("/");
|
||||
then.status(200).body(
|
||||
r#"
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
||||
<title>Directory listing for /</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Directory listing for /</h1>
|
||||
<hr>
|
||||
<ul>
|
||||
<li><a href="disallowed-subdir/">disallowed-subdir/</a></li>
|
||||
<li><a href="LICENSE">LICENSE</a></li>
|
||||
<li><a href="misc/">misc/</a></li>
|
||||
</ul>
|
||||
<hr>
|
||||
</body>
|
||||
</html>
|
||||
"#,
|
||||
);
|
||||
});
|
||||
|
||||
let mock_root_file = srv.mock(|when, then| {
|
||||
when.method(GET).path("/LICENSE");
|
||||
then.status(200).body("im a little teapot"); // 18
|
||||
});
|
||||
|
||||
let mock_dir_disallowed = srv.mock(|when, then| {
|
||||
when.method(GET).path("/disallowed-subdir");
|
||||
then.status(404);
|
||||
});
|
||||
|
||||
let mock_dir_redir = srv.mock(|when, then| {
|
||||
when.method(GET).path("/misc");
|
||||
then.status(301).header("Location", srv.url("/misc/"));
|
||||
});
|
||||
let mock_dir = srv.mock(|when, then| {
|
||||
when.method(GET).path("/misc/");
|
||||
then.status(200).body(
|
||||
r#"
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
||||
<title>Directory listing for /misc</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Directory listing for /misc</h1>
|
||||
<hr>
|
||||
<ul>
|
||||
<li><a href="LICENSE">LICENSE</a></li>
|
||||
<li><a href="stupidfile.php">stupidfile.php</a></li>
|
||||
</ul>
|
||||
<hr>
|
||||
</body>
|
||||
</html>
|
||||
"#,
|
||||
);
|
||||
});
|
||||
|
||||
let mock_dir_file = srv.mock(|when, then| {
|
||||
when.method(GET).path("/misc/LICENSE");
|
||||
then.status(200).body("i too, am a container for tea"); // 29
|
||||
});
|
||||
|
||||
let mock_dir_file_ext = srv.mock(|when, then| {
|
||||
when.method(GET).path("/misc/stupidfile.php");
|
||||
then.status(200).body("im a little teapot too"); // 22
|
||||
});
|
||||
|
||||
let cmd = Command::cargo_bin("feroxbuster")
|
||||
.unwrap()
|
||||
.arg("--url")
|
||||
.arg(srv.url("/"))
|
||||
.arg("--wordlist")
|
||||
.arg(file.as_os_str())
|
||||
.arg("--extract-links")
|
||||
.arg("--redirects")
|
||||
.unwrap();
|
||||
|
||||
cmd.assert().success().stdout(
|
||||
predicate::str::contains("/LICENSE") // 2 directories contain LICENSE
|
||||
.count(2)
|
||||
.and(predicate::str::contains("18c"))
|
||||
.and(predicate::str::contains("/misc/stupidfile.php"))
|
||||
.and(predicate::str::contains("22c"))
|
||||
.and(predicate::str::contains("/misc/LICENSE"))
|
||||
.and(predicate::str::contains("29c"))
|
||||
.and(predicate::str::contains("200").count(3)),
|
||||
);
|
||||
|
||||
assert_eq!(mock_root.hits(), 2);
|
||||
assert_eq!(mock_root_file.hits(), 1);
|
||||
assert_eq!(mock_dir_disallowed.hits(), 1);
|
||||
assert_eq!(mock_dir_redir.hits(), 1);
|
||||
assert_eq!(mock_dir.hits(), 2);
|
||||
assert_eq!(mock_dir_file.hits(), 1);
|
||||
assert_eq!(mock_dir_file_ext.hits(), 1);
|
||||
teardown_tmp_directory(tmp_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// serve a directory listing with a file and and a folder contained within it. ferox should
|
||||
/// find both links and request each one. This is the non-recursive version of the test above
|
||||
fn extractor_finds_directory_listing_links_and_displays_files_non_recursive() {
|
||||
let srv = MockServer::start();
|
||||
let (tmp_dir, file) = setup_tmp_directory(&["invalid".to_string()], "wordlist").unwrap();
|
||||
|
||||
let mock_root = srv.mock(|when, then| {
|
||||
when.method(GET).path("/");
|
||||
then.status(200).body(
|
||||
r#"
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
||||
<title>Directory listing for /</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Directory listing for /</h1>
|
||||
<hr>
|
||||
<ul>
|
||||
<li><a href="disallowed-subdir/">disallowed-subdir/</a></li>
|
||||
<li><a href="LICENSE">LICENSE</a></li>
|
||||
<li><a href="misc/">misc/</a></li>
|
||||
</ul>
|
||||
<hr>
|
||||
</body>
|
||||
</html>
|
||||
"#,
|
||||
);
|
||||
});
|
||||
|
||||
let mock_root_file = srv.mock(|when, then| {
|
||||
when.method(GET).path("/LICENSE");
|
||||
then.status(200).body("im a little teapot"); // 18
|
||||
});
|
||||
|
||||
let mock_dir_disallowed = srv.mock(|when, then| {
|
||||
when.method(GET).path("/disallowed-subdir");
|
||||
then.status(404);
|
||||
});
|
||||
|
||||
let mock_dir_redir = srv.mock(|when, then| {
|
||||
when.method(GET).path("/misc");
|
||||
then.status(301).header("Location", srv.url("/misc/"));
|
||||
});
|
||||
let mock_dir = srv.mock(|when, then| {
|
||||
when.method(GET).path("/misc/");
|
||||
then.status(200).body(
|
||||
r#"
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
||||
<title>Directory listing for /misc</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Directory listing for /misc</h1>
|
||||
<hr>
|
||||
<ul>
|
||||
<li><a href="LICENSE">LICENSE</a></li>
|
||||
<li><a href="stupidfile.php">stupidfile.php</a></li>
|
||||
</ul>
|
||||
<hr>
|
||||
</body>
|
||||
</html>
|
||||
"#,
|
||||
);
|
||||
});
|
||||
|
||||
let mock_dir_file = srv.mock(|when, then| {
|
||||
when.method(GET).path("/misc/LICENSE");
|
||||
then.status(200).body("i too, am a container for tea"); // 29
|
||||
});
|
||||
|
||||
let mock_dir_file_ext = srv.mock(|when, then| {
|
||||
when.method(GET).path("/misc/stupidfile.php");
|
||||
then.status(200).body("im a little teapot too"); // 22
|
||||
});
|
||||
|
||||
let cmd = Command::cargo_bin("feroxbuster")
|
||||
.unwrap()
|
||||
.arg("--url")
|
||||
.arg(srv.url("/"))
|
||||
.arg("--wordlist")
|
||||
.arg(file.as_os_str())
|
||||
.arg("--extract-links")
|
||||
.arg("--redirects")
|
||||
.arg("--no-recursion")
|
||||
.unwrap();
|
||||
|
||||
cmd.assert().success().stdout(
|
||||
predicate::str::contains("/LICENSE")
|
||||
.and(predicate::str::contains("18c"))
|
||||
.and(predicate::str::contains("/misc/stupidfile.php"))
|
||||
.not()
|
||||
.and(predicate::str::contains("22c"))
|
||||
.not()
|
||||
.and(predicate::str::contains("/misc/LICENSE").not())
|
||||
.and(predicate::str::contains("29c").not())
|
||||
.and(predicate::str::contains("200").count(1)),
|
||||
);
|
||||
|
||||
assert_eq!(mock_root.hits(), 2);
|
||||
assert_eq!(mock_root_file.hits(), 1);
|
||||
assert_eq!(mock_dir_disallowed.hits(), 1);
|
||||
assert_eq!(mock_dir_redir.hits(), 1);
|
||||
assert_eq!(mock_dir.hits(), 1);
|
||||
assert_eq!(mock_dir_file.hits(), 0);
|
||||
assert_eq!(mock_dir_file_ext.hits(), 0);
|
||||
teardown_tmp_directory(tmp_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// send a request to a page that contains a link that contains a directory that returns a 403
|
||||
/// --extract-links should find the link and make recurse into the 403 directory, finding LICENSE
|
||||
@@ -380,7 +600,7 @@ fn extractor_recurses_into_403_directories() -> Result<(), Box<dyn std::error::E
|
||||
let mock = srv.mock(|when, then| {
|
||||
when.method(GET).path("/LICENSE");
|
||||
then.status(200)
|
||||
.body(&srv.url("'/homepage/assets/img/icons/handshake.svg'"));
|
||||
.body(srv.url("'/homepage/assets/img/icons/handshake.svg'"));
|
||||
});
|
||||
|
||||
let mock_two = srv.mock(|when, then| {
|
||||
@@ -416,7 +636,7 @@ fn extractor_recurses_into_403_directories() -> Result<(), Box<dyn std::error::E
|
||||
|
||||
assert_eq!(mock.hits(), 1);
|
||||
assert_eq!(mock_two.hits(), 1);
|
||||
assert_eq!(forbidden_dir.hits(), 1);
|
||||
assert_eq!(forbidden_dir.hits(), 3);
|
||||
teardown_tmp_directory(tmp_dir);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -269,51 +269,53 @@ fn heuristics_static_wildcard_request_with_dont_filter() -> Result<(), Box<dyn s
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// test finds a static wildcard and reports as much to stdout
|
||||
fn heuristics_wildcard_test_with_two_static_wildcards() {
|
||||
let srv = MockServer::start();
|
||||
let (tmp_dir, file) = setup_tmp_directory(&["LICENSE".to_string()], "wordlist").unwrap();
|
||||
// #[test]
|
||||
// /// test finds a static wildcard and reports as much to stdout
|
||||
// fn heuristics_wildcard_test_with_two_static_wildcards() {
|
||||
// let srv = MockServer::start();
|
||||
// let (tmp_dir, file) = setup_tmp_directory(&["LICENSE".to_string()], "wordlist").unwrap();
|
||||
|
||||
let mock = srv.mock(|when, then| {
|
||||
when.method(GET)
|
||||
.path_matches(Regex::new("/[a-zA-Z0-9]{32}/").unwrap());
|
||||
then.status(200)
|
||||
.body("this is a testAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
|
||||
});
|
||||
// let mock = srv.mock(|when, then| {
|
||||
// when.method(GET)
|
||||
// .path_matches(Regex::new("/[a-zA-Z0-9]{32}/").unwrap());
|
||||
// then.status(200)
|
||||
// .body("this is a testAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
|
||||
// });
|
||||
|
||||
let mock2 = srv.mock(|when, then| {
|
||||
when.method(GET)
|
||||
.path_matches(Regex::new("/[a-zA-Z0-9]{96}/").unwrap());
|
||||
then.status(200)
|
||||
.body("this is a testAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
|
||||
});
|
||||
// let mock2 = srv.mock(|when, then| {
|
||||
// when.method(GET)
|
||||
// .path_matches(Regex::new("/[a-zA-Z0-9]{96}/").unwrap());
|
||||
// then.status(200)
|
||||
// .body("this is a testAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
|
||||
// });
|
||||
|
||||
let cmd = Command::cargo_bin("feroxbuster")
|
||||
.unwrap()
|
||||
.arg("--url")
|
||||
.arg(srv.url("/"))
|
||||
.arg("--wordlist")
|
||||
.arg(file.as_os_str())
|
||||
.arg("--add-slash")
|
||||
.unwrap();
|
||||
// let cmd = Command::cargo_bin("feroxbuster")
|
||||
// .unwrap()
|
||||
// .arg("--url")
|
||||
// .arg(srv.url("/"))
|
||||
// .arg("--wordlist")
|
||||
// .arg(file.as_os_str())
|
||||
// .arg("--add-slash")
|
||||
// .arg("--threads")
|
||||
// .arg("1")
|
||||
// .unwrap();
|
||||
|
||||
teardown_tmp_directory(tmp_dir);
|
||||
// teardown_tmp_directory(tmp_dir);
|
||||
|
||||
cmd.assert().success().stdout(
|
||||
predicate::str::contains("WLD")
|
||||
.and(predicate::str::contains("Got"))
|
||||
.and(predicate::str::contains("200"))
|
||||
.and(predicate::str::contains("(url length: 32)"))
|
||||
.and(predicate::str::contains("(url length: 96)"))
|
||||
.and(predicate::str::contains(
|
||||
"Wildcard response is static; auto-filtering 46",
|
||||
)),
|
||||
);
|
||||
// cmd.assert().success().stdout(
|
||||
// predicate::str::contains("WLD")
|
||||
// .and(predicate::str::contains("Got"))
|
||||
// .and(predicate::str::contains("200"))
|
||||
// .and(predicate::str::contains("(url length: 32)"))
|
||||
// .and(predicate::str::contains("(url length: 96)"))
|
||||
// .and(predicate::str::contains(
|
||||
// "Wildcard response is static; auto-filtering 46",
|
||||
// )),
|
||||
// );
|
||||
|
||||
assert_eq!(mock.hits(), 1);
|
||||
assert_eq!(mock2.hits(), 1);
|
||||
}
|
||||
// assert_eq!(mock.hits(), 1);
|
||||
// assert_eq!(mock2.hits(), 1);
|
||||
// }
|
||||
|
||||
#[test]
|
||||
/// test finds a static wildcard and reports nothing to stdout
|
||||
@@ -344,6 +346,8 @@ fn heuristics_wildcard_test_with_two_static_wildcards_with_silent_enabled(
|
||||
.arg(file.as_os_str())
|
||||
.arg("--add-slash")
|
||||
.arg("--silent")
|
||||
.arg("--threads")
|
||||
.arg("1")
|
||||
.unwrap();
|
||||
|
||||
teardown_tmp_directory(tmp_dir);
|
||||
@@ -355,119 +359,126 @@ fn heuristics_wildcard_test_with_two_static_wildcards_with_silent_enabled(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// test finds a static wildcard and reports as much to stdout and a file
|
||||
fn heuristics_wildcard_test_with_two_static_wildcards_and_output_to_file() {
|
||||
let srv = MockServer::start();
|
||||
let (tmp_dir, file) = setup_tmp_directory(&["LICENSE".to_string()], "wordlist").unwrap();
|
||||
let outfile = tmp_dir.path().join("outfile");
|
||||
// #[test]
|
||||
// /// test finds a static wildcard and reports as much to stdout and a file
|
||||
// fn heuristics_wildcard_test_with_two_static_wildcards_and_output_to_file() {
|
||||
// let srv = MockServer::start();
|
||||
// let (tmp_dir, file) = setup_tmp_directory(&["LICENSE".to_string()], "wordlist").unwrap();
|
||||
// let outfile = tmp_dir.path().join("outfile");
|
||||
|
||||
let mock = srv.mock(|when, then| {
|
||||
when.method(GET)
|
||||
.path_matches(Regex::new("/[a-zA-Z0-9]{32}/").unwrap());
|
||||
then.status(200)
|
||||
.body("this is a testAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
|
||||
});
|
||||
// let mock = srv.mock(|when, then| {
|
||||
// when.method(GET)
|
||||
// .path_matches(Regex::new("/[a-zA-Z0-9]{32}/").unwrap());
|
||||
// then.status(200)
|
||||
// .body("this is a testAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
|
||||
// });
|
||||
|
||||
let mock2 = srv.mock(|when, then| {
|
||||
when.method(GET)
|
||||
.path_matches(Regex::new("/[a-zA-Z0-9]{96}/").unwrap());
|
||||
then.status(200)
|
||||
.body("this is a testAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
|
||||
});
|
||||
// let mock2 = srv.mock(|when, then| {
|
||||
// when.method(GET)
|
||||
// .path_matches(Regex::new("/[a-zA-Z0-9]{96}/").unwrap());
|
||||
// then.status(200)
|
||||
// .body("this is a testAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
|
||||
// });
|
||||
|
||||
let cmd = Command::cargo_bin("feroxbuster")
|
||||
.unwrap()
|
||||
.arg("--url")
|
||||
.arg(srv.url("/"))
|
||||
.arg("--wordlist")
|
||||
.arg(file.as_os_str())
|
||||
.arg("--add-slash")
|
||||
.arg("--output")
|
||||
.arg(outfile.as_os_str())
|
||||
.unwrap();
|
||||
// let cmd = Command::cargo_bin("feroxbuster")
|
||||
// .unwrap()
|
||||
// .arg("--url")
|
||||
// .arg(srv.url("/"))
|
||||
// .arg("--wordlist")
|
||||
// .arg(file.as_os_str())
|
||||
// .arg("--add-slash")
|
||||
// .arg("--output")
|
||||
// .arg(outfile.as_os_str())
|
||||
// .arg("--threads")
|
||||
// .arg("1")
|
||||
// .unwrap();
|
||||
|
||||
let contents = std::fs::read_to_string(outfile).unwrap();
|
||||
// let contents = std::fs::read_to_string(outfile).unwrap();
|
||||
|
||||
teardown_tmp_directory(tmp_dir);
|
||||
// teardown_tmp_directory(tmp_dir);
|
||||
|
||||
assert!(contents.contains("WLD"));
|
||||
assert!(contents.contains("Got"));
|
||||
assert!(contents.contains("200"));
|
||||
assert!(contents.contains("(url length: 32)"));
|
||||
assert!(contents.contains("(url length: 96)"));
|
||||
// assert!(contents.contains("WLD"));
|
||||
// assert!(contents.contains("Got"));
|
||||
// assert!(contents.contains("200"));
|
||||
// assert!(contents.contains("(url length: 32)"));
|
||||
// assert!(contents.contains("(url length: 96)"));
|
||||
|
||||
cmd.assert().success().stdout(
|
||||
predicate::str::contains("WLD")
|
||||
.and(predicate::str::contains("Got"))
|
||||
.and(predicate::str::contains("200"))
|
||||
.and(predicate::str::contains("(url length: 32)"))
|
||||
.and(predicate::str::contains("(url length: 96)"))
|
||||
.and(predicate::str::contains(
|
||||
"Wildcard response is static; auto-filtering 46",
|
||||
)),
|
||||
);
|
||||
// cmd.assert().success().stdout(
|
||||
// predicate::str::contains("WLD")
|
||||
// .and(predicate::str::contains("Got"))
|
||||
// .and(predicate::str::contains("200"))
|
||||
// .and(predicate::str::contains("(url length: 32)"))
|
||||
// .and(predicate::str::contains("(url length: 96)"))
|
||||
// .and(predicate::str::contains(
|
||||
// "Wildcard response is static; auto-filtering 46",
|
||||
// )),
|
||||
// );
|
||||
|
||||
assert_eq!(mock.hits(), 1);
|
||||
assert_eq!(mock2.hits(), 1);
|
||||
}
|
||||
// assert_eq!(mock.hits(), 1);
|
||||
// assert_eq!(mock2.hits(), 1);
|
||||
// }
|
||||
|
||||
#[test]
|
||||
/// test finds a static wildcard that returns 3xx, expect redirects to => in response as well as
|
||||
/// in the output file
|
||||
fn heuristics_wildcard_test_with_redirect_as_response_code(
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let srv = MockServer::start();
|
||||
let (tmp_dir, file) = setup_tmp_directory(&["LICENSE".to_string()], "wordlist")?;
|
||||
let outfile = tmp_dir.path().join("outfile");
|
||||
// #[test]
|
||||
// /// test finds a static wildcard that returns 3xx, expect redirects to => in response as well as
|
||||
// /// in the output file
|
||||
// fn heuristics_wildcard_test_with_redirect_as_response_code(
|
||||
// ) -> Result<(), Box<dyn std::error::Error>> {
|
||||
// let srv = MockServer::start();
|
||||
|
||||
let mock = srv.mock(|when, then| {
|
||||
when.method(GET)
|
||||
.path_matches(Regex::new("/[a-zA-Z0-9]{32}/").unwrap());
|
||||
then.status(301)
|
||||
.body("this is a testAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
|
||||
});
|
||||
// let (tmp_dir, file) = setup_tmp_directory(&["LICENSE".to_string()], "wordlist")?;
|
||||
// let outfile = tmp_dir.path().join("outfile");
|
||||
|
||||
let mock2 = srv.mock(|when, then| {
|
||||
when.method(GET)
|
||||
.path_matches(Regex::new("/[a-zA-Z0-9]{96}/").unwrap());
|
||||
then.status(301)
|
||||
.header("Location", &srv.url("/some-redirect"))
|
||||
.body("this is a testAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
|
||||
});
|
||||
// let mock = srv.mock(|when, then| {
|
||||
// when.method(GET)
|
||||
// .path_matches(Regex::new("/[a-zA-Z0-9]{32}/").unwrap());
|
||||
// then.status(301)
|
||||
// .body("this is a testAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
|
||||
// });
|
||||
|
||||
let cmd = Command::cargo_bin("feroxbuster")
|
||||
.unwrap()
|
||||
.arg("--url")
|
||||
.arg(srv.url("/"))
|
||||
.arg("--wordlist")
|
||||
.arg(file.as_os_str())
|
||||
.arg("--add-slash")
|
||||
.arg("--output")
|
||||
.arg(outfile.as_os_str())
|
||||
.unwrap();
|
||||
// let mock2 = srv.mock(|when, then| {
|
||||
// when.method(GET)
|
||||
// .path_matches(Regex::new("/[a-zA-Z0-9]{96}/").unwrap());
|
||||
// then.status(301)
|
||||
// .header("Location", &srv.url("/some-redirect"))
|
||||
// .body("this is a testAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
|
||||
// });
|
||||
|
||||
let contents = std::fs::read_to_string(outfile).unwrap();
|
||||
// let cmd = Command::cargo_bin("feroxbuster")
|
||||
// .unwrap()
|
||||
// .arg("--url")
|
||||
// .arg(srv.url("/"))
|
||||
// .arg("--wordlist")
|
||||
// .arg(file.as_os_str())
|
||||
// .arg("--add-slash")
|
||||
// .arg("--output")
|
||||
// .arg(outfile.as_os_str())
|
||||
// .arg("--threads")
|
||||
// .arg("1")
|
||||
// .unwrap();
|
||||
|
||||
teardown_tmp_directory(tmp_dir);
|
||||
// let contents = std::fs::read_to_string(outfile).unwrap();
|
||||
|
||||
assert!(contents.contains("WLD"));
|
||||
assert!(contents.contains("301"));
|
||||
assert!(contents.contains("/some-redirect"));
|
||||
assert!(contents.contains("redirects to => "));
|
||||
assert!(contents.contains(&srv.url("/")));
|
||||
assert!(contents.contains("(url length: 32)"));
|
||||
// teardown_tmp_directory(tmp_dir);
|
||||
|
||||
cmd.assert().success().stdout(
|
||||
predicate::str::contains("redirects to => ")
|
||||
.and(predicate::str::contains("/some-redirect"))
|
||||
.and(predicate::str::contains("301"))
|
||||
.and(predicate::str::contains(srv.url("/")))
|
||||
.and(predicate::str::contains("(url length: 32)"))
|
||||
.and(predicate::str::contains("WLD")),
|
||||
);
|
||||
// assert!(contents.contains("WLD"));
|
||||
// assert!(contents.contains("301"));
|
||||
// assert!(contents.contains("/some-redirect"));
|
||||
// assert!(contents.contains(" => "));
|
||||
// assert!(contents.contains(&srv.url("/")));
|
||||
// assert!(contents.contains("(url length: 32)"));
|
||||
|
||||
assert_eq!(mock.hits(), 1);
|
||||
assert_eq!(mock2.hits(), 1);
|
||||
Ok(())
|
||||
}
|
||||
// cmd.assert().success().stdout(
|
||||
// predicate::str::contains(" => ")
|
||||
// .and(predicate::str::contains("/some-redirect"))
|
||||
// .and(predicate::str::contains("301"))
|
||||
// .and(predicate::str::contains(srv.url("/")))
|
||||
// .and(predicate::str::contains("(url length: 32)"))
|
||||
// .and(predicate::str::contains("WLD")),
|
||||
// );
|
||||
|
||||
// assert_eq!(mock.hits(), 1);
|
||||
// assert_eq!(mock2.hits(), 1);
|
||||
// Ok(())
|
||||
// }
|
||||
|
||||
// todo figure out why ci hates these tests
|
||||
|
||||
@@ -25,12 +25,9 @@ fn main_use_root_owned_file_as_wordlist() {
|
||||
.arg("-vvvv")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(predicate::str::contains(
|
||||
"Failed while scanning: Could not open /etc/shadow",
|
||||
));
|
||||
.stderr(predicate::str::contains("Could not open /etc/shadow"));
|
||||
|
||||
// connectivity test hits it once
|
||||
assert_eq!(mock.hits(), 1);
|
||||
assert_eq!(mock.hits(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -53,11 +50,9 @@ fn main_use_empty_wordlist() -> Result<(), Box<dyn std::error::Error>> {
|
||||
.arg("-vvvv")
|
||||
.assert()
|
||||
.success()
|
||||
.stderr(predicate::str::contains(
|
||||
"Failed while scanning: Did not find any words in",
|
||||
));
|
||||
.stderr(predicate::str::contains("Did not find any words in"));
|
||||
|
||||
assert_eq!(mock.hits(), 1);
|
||||
assert_eq!(mock.hits(), 0);
|
||||
|
||||
teardown_tmp_directory(tmp_dir);
|
||||
Ok(())
|
||||
@@ -201,10 +196,10 @@ fn main_parallel_creates_output_directory() -> Result<(), Box<dyn std::error::Er
|
||||
let file_regex = Regex::new("ferox-[a-zA-Z_:0-9]+-[0-9]+.log").unwrap();
|
||||
let dir_regex = Regex::new("output-file-[0-9]+.logs").unwrap();
|
||||
|
||||
let sub_dir = output_dir.as_ref().join(&sub_dir);
|
||||
let sub_dir = output_dir.as_ref().join(sub_dir);
|
||||
|
||||
// created directory like output-file-1627845741.logs/
|
||||
assert!(dir_regex.is_match(&sub_dir.to_string_lossy().to_string()));
|
||||
assert!(dir_regex.is_match(&sub_dir.to_string_lossy()));
|
||||
|
||||
for entry in sub_dir.read_dir()? {
|
||||
let entry = entry?;
|
||||
|
||||
@@ -33,8 +33,8 @@ fn parser_incorrect_param_with_tack_tack_help() {
|
||||
///
|
||||
/// For more information try --help
|
||||
///
|
||||
/// the new behavior we expect to see is to print the long form help message, of which
|
||||
/// Ludicrous speed... go! is near the bottom of that output, so we can test for that
|
||||
/// the new behavior we expect to see is to print the short form help message, of which
|
||||
/// "[CAUTION] 4 -v's is probably too much" is near the bottom of that output, so we can test for that
|
||||
fn parser_incorrect_param_with_tack_h() {
|
||||
Command::cargo_bin("feroxbuster")
|
||||
.unwrap()
|
||||
@@ -42,5 +42,13 @@ fn parser_incorrect_param_with_tack_h() {
|
||||
.arg("-h")
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(predicate::str::contains("Ludicrous speed... go!"));
|
||||
.stdout(
|
||||
predicate::str::contains("[CAUTION]")
|
||||
.and(predicate::str::contains("4"))
|
||||
.and(predicate::str::contains("-v's"))
|
||||
.and(predicate::str::contains("is"))
|
||||
.and(predicate::str::contains("probably"))
|
||||
.and(predicate::str::contains("too"))
|
||||
.and(predicate::str::contains("much")),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -20,11 +20,13 @@ fn resume_scan_works() {
|
||||
// localhost:PORT/ <- complete
|
||||
// localhost:PORT/js <- will get scanned with /css and /stuff
|
||||
let complete_scan = format!(
|
||||
r#"{{"id":"057016a14769414aac9a7a62707598cb","url":"{}","scan_type":"Directory","status":"Complete"}}"#,
|
||||
srv.url("/")
|
||||
r#"{{"id":"057016a14769414aac9a7a62707598cb","url":"{}","normalized_url":"{}","scan_type":"Directory","status":"Complete"}}"#,
|
||||
srv.url("/"),
|
||||
srv.url("/"),
|
||||
);
|
||||
let incomplete_scan = format!(
|
||||
r#"{{"id":"400b2323a16f43468a04ffcbbeba34c6","url":"{}","scan_type":"Directory","status":"NotStarted"}}"#,
|
||||
r#"{{"id":"400b2323a16f43468a04ffcbbeba34c6","url":"{}","normalized_url":"{}/","scan_type":"Directory","status":"NotStarted"}}"#,
|
||||
srv.url("/js"),
|
||||
srv.url("/js")
|
||||
);
|
||||
let scans = format!(r#""scans":[{},{}]"#, complete_scan, incomplete_scan);
|
||||
|
||||
@@ -3,6 +3,8 @@ use assert_cmd::prelude::*;
|
||||
use httpmock::Method::GET;
|
||||
use httpmock::MockServer;
|
||||
use predicates::prelude::*;
|
||||
use std::thread::sleep;
|
||||
use std::time::Duration;
|
||||
use std::{process::Command, time};
|
||||
use utils::{setup_tmp_directory, teardown_tmp_directory};
|
||||
|
||||
@@ -51,17 +53,17 @@ fn scanner_recursive_request_scan() -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
let js_mock = srv.mock(|when, then| {
|
||||
when.method(GET).path("/js");
|
||||
then.status(301).header("Location", &srv.url("/js/"));
|
||||
then.status(301).header("Location", srv.url("/js/"));
|
||||
});
|
||||
|
||||
let js_prod_mock = srv.mock(|when, then| {
|
||||
when.method(GET).path("/js/prod");
|
||||
then.status(301).header("Location", &srv.url("/js/prod/"));
|
||||
then.status(301).header("Location", srv.url("/js/prod/"));
|
||||
});
|
||||
|
||||
let js_dev_mock = srv.mock(|when, then| {
|
||||
when.method(GET).path("/js/dev");
|
||||
then.status(301).header("Location", &srv.url("/js/dev/"));
|
||||
then.status(301).header("Location", srv.url("/js/dev/"));
|
||||
});
|
||||
|
||||
let js_dev_file_mock = srv.mock(|when, then| {
|
||||
@@ -89,9 +91,9 @@ fn scanner_recursive_request_scan() -> Result<(), Box<dyn std::error::Error>> {
|
||||
.and(predicate::str::is_match("200.*js/dev/file.js").unwrap()),
|
||||
);
|
||||
|
||||
assert_eq!(js_mock.hits(), 1);
|
||||
assert_eq!(js_prod_mock.hits(), 1);
|
||||
assert_eq!(js_dev_mock.hits(), 1);
|
||||
assert_eq!(js_mock.hits(), 2);
|
||||
assert_eq!(js_prod_mock.hits(), 2);
|
||||
assert_eq!(js_dev_mock.hits(), 2);
|
||||
assert_eq!(js_dev_file_mock.hits(), 1);
|
||||
|
||||
teardown_tmp_directory(tmp_dir);
|
||||
@@ -114,17 +116,17 @@ fn scanner_recursive_request_scan_using_only_success_responses(
|
||||
|
||||
let js_mock = srv.mock(|when, then| {
|
||||
when.method(GET).path("/js/");
|
||||
then.status(200).header("Location", &srv.url("/js/"));
|
||||
then.status(200).header("Location", srv.url("/js/"));
|
||||
});
|
||||
|
||||
let js_prod_mock = srv.mock(|when, then| {
|
||||
when.method(GET).path("/js/prod/");
|
||||
then.status(200).header("Location", &srv.url("/js/prod/"));
|
||||
then.status(200).header("Location", srv.url("/js/prod/"));
|
||||
});
|
||||
|
||||
let js_dev_mock = srv.mock(|when, then| {
|
||||
when.method(GET).path("/js/dev/");
|
||||
then.status(200).header("Location", &srv.url("/js/dev/"));
|
||||
then.status(200).header("Location", srv.url("/js/dev/"));
|
||||
});
|
||||
|
||||
let js_dev_file_mock = srv.mock(|when, then| {
|
||||
@@ -153,9 +155,9 @@ fn scanner_recursive_request_scan_using_only_success_responses(
|
||||
.and(predicate::str::is_match("200.*js/dev/file.js").unwrap()),
|
||||
);
|
||||
|
||||
assert_eq!(js_mock.hits(), 1);
|
||||
assert_eq!(js_prod_mock.hits(), 1);
|
||||
assert_eq!(js_dev_mock.hits(), 1);
|
||||
assert_eq!(js_mock.hits(), 3);
|
||||
assert_eq!(js_prod_mock.hits(), 3);
|
||||
assert_eq!(js_dev_mock.hits(), 3);
|
||||
assert_eq!(js_dev_file_mock.hits(), 1);
|
||||
|
||||
teardown_tmp_directory(tmp_dir);
|
||||
@@ -363,7 +365,7 @@ fn scanner_single_request_replayed_to_proxy() -> Result<(), Box<dyn std::error::
|
||||
.arg("--wordlist")
|
||||
.arg(file.as_os_str())
|
||||
.arg("--replay-proxy")
|
||||
.arg(format!("http://{}", proxy.address().to_string()))
|
||||
.arg(format!("http://{}", proxy.address()))
|
||||
.arg("--replay-codes")
|
||||
.arg("200")
|
||||
.unwrap();
|
||||
@@ -596,7 +598,7 @@ fn scanner_recursion_works_with_403_directories() {
|
||||
|
||||
assert_eq!(mock.hits(), 1);
|
||||
assert_eq!(found_anyway.hits(), 1);
|
||||
assert_eq!(forbidden_dir.hits(), 1);
|
||||
assert_eq!(forbidden_dir.hits(), 3);
|
||||
|
||||
teardown_tmp_directory(tmp_dir);
|
||||
}
|
||||
@@ -638,3 +640,274 @@ fn rate_limit_enforced_when_specified() {
|
||||
|
||||
teardown_tmp_directory(tmp_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// ensure that auto-discovered extensions are tracked in statistics and bar lengths are updated
|
||||
fn add_discovered_extension_updates_bars_and_stats() {
|
||||
let srv = MockServer::start();
|
||||
let (tmp_dir, file) = setup_tmp_directory(
|
||||
&["LICENSE".to_string(), "stuff.php".to_string()],
|
||||
"wordlist",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
srv.mock(|when, then| {
|
||||
when.method(GET).path("/stuff.php");
|
||||
then.status(200).body("cool... coolcoolcool");
|
||||
});
|
||||
|
||||
let file_path = tmp_dir.path().join("debug-file.txt");
|
||||
|
||||
assert!(!file_path.exists());
|
||||
|
||||
Command::cargo_bin("feroxbuster")
|
||||
.unwrap()
|
||||
.arg("--url")
|
||||
.arg(srv.url("/"))
|
||||
.arg("--wordlist")
|
||||
.arg(file.as_os_str())
|
||||
.arg("--extract-links")
|
||||
.arg("--collect-extensions")
|
||||
.arg("-vvvv")
|
||||
.arg("--debug-log")
|
||||
.arg(file_path.as_os_str())
|
||||
.unwrap()
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let contents = std::fs::read_to_string(file_path).unwrap();
|
||||
println!("{}", contents);
|
||||
assert!(contents.contains("discovered new extension: php"));
|
||||
assert!(contents.contains("extensions_collected: 1"));
|
||||
assert!(contents.contains("expected_per_scan: 6"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// send a request to a 200 file, expect pre-configured backup collection rules to be applied
|
||||
/// and then requested
|
||||
fn collect_backups_makes_appropriate_requests() {
|
||||
let srv = MockServer::start();
|
||||
let (tmp_dir, file) = setup_tmp_directory(&["LICENSE.txt".to_string()], "wordlist").unwrap();
|
||||
|
||||
let valid_paths = vec![
|
||||
"/LICENSE.txt",
|
||||
"/LICENSE.txt~",
|
||||
"/LICENSE.txt.bak",
|
||||
"/LICENSE.txt.bak2",
|
||||
"/LICENSE.txt.old",
|
||||
"/LICENSE.txt.1",
|
||||
"/LICENSE.bak",
|
||||
"/.LICENSE.txt.swp",
|
||||
];
|
||||
|
||||
let valid_mocks: Vec<_> = valid_paths
|
||||
.iter()
|
||||
.map(|&p| {
|
||||
srv.mock(|when, then| {
|
||||
when.method(GET).path(p);
|
||||
then.status(200).body("this is a valid test");
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let invalid_paths: Vec<_> = vec![
|
||||
"/LICENSE.txt~~",
|
||||
"/LICENSE.txt.bak.bak",
|
||||
"/LICENSE.txt.bak2.bak2",
|
||||
"/LICENSE.txt.old.old",
|
||||
"/LICENSE.txt.1.1",
|
||||
"/..LICENSE.txt.swp.swp",
|
||||
];
|
||||
|
||||
let invalid_mocks: Vec<_> = invalid_paths
|
||||
.iter()
|
||||
.map(|&p| {
|
||||
srv.mock(|when, then| {
|
||||
when.method(GET).path(p);
|
||||
then.status(200).body("this is an invalid test");
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let cmd = Command::cargo_bin("feroxbuster")
|
||||
.unwrap()
|
||||
.arg("--url")
|
||||
.arg(srv.url("/"))
|
||||
.arg("--collect-backups")
|
||||
.arg("--wordlist")
|
||||
.arg(file.as_os_str())
|
||||
.unwrap();
|
||||
|
||||
cmd.assert().success().stdout(
|
||||
predicate::str::contains("/LICENSE.txt")
|
||||
.and(predicate::str::contains("/LICENSE.txt~"))
|
||||
.and(predicate::str::contains("/LICENSE.txt.bak"))
|
||||
.and(predicate::str::contains("/LICENSE.txt.bak2"))
|
||||
.and(predicate::str::contains("/LICENSE.txt.old"))
|
||||
.and(predicate::str::contains("/LICENSE.txt.1"))
|
||||
.and(predicate::str::contains("/LICENSE.bak"))
|
||||
.and(predicate::str::contains("/.LICENSE.txt.swp")),
|
||||
);
|
||||
|
||||
for valid_mock in valid_mocks {
|
||||
assert_eq!(valid_mock.hits(), 1);
|
||||
}
|
||||
|
||||
for invalid_mock in invalid_mocks {
|
||||
assert_eq!(invalid_mock.hits(), 0);
|
||||
}
|
||||
|
||||
teardown_tmp_directory(tmp_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// send a request to 4 200 files, expect non-zero tf-idf rated words to be requested as well
|
||||
fn collect_words_makes_appropriate_requests() {
|
||||
let srv = MockServer::start();
|
||||
|
||||
let wordlist: Vec<_> = [
|
||||
"doc1", "doc2", "doc3", "doc4", "blah", "blah2", "blah3", "blah4",
|
||||
]
|
||||
.iter()
|
||||
.map(|w| w.to_string())
|
||||
.collect();
|
||||
|
||||
let (tmp_dir, file) = setup_tmp_directory(&wordlist, "wordlist").unwrap();
|
||||
|
||||
srv.mock(|when, then| {
|
||||
when.method(GET).path("/doc1");
|
||||
then.status(200)
|
||||
.body("Air quality in the sunny island improved gradually throughout Wednesday.");
|
||||
});
|
||||
srv.mock(|when, then| {
|
||||
when.method(GET).path("/doc2");
|
||||
then.status(200).body(
|
||||
"Air quality in Singapore on Wednesday continued to get worse as haze hit the island.",
|
||||
);
|
||||
});
|
||||
srv.mock(|when, then| {
|
||||
when.method(GET).path("/doc3");
|
||||
then.status(200).body("The air quality in Singapore is monitored through a network of air monitoring stations located in different parts of the island");
|
||||
});
|
||||
srv.mock(|when, then| {
|
||||
when.method(GET).path("/doc4");
|
||||
then.status(200)
|
||||
.body("The air quality in Singapore got worse on Wednesday.");
|
||||
});
|
||||
|
||||
let valid_paths = vec![
|
||||
"/gradually",
|
||||
"/network",
|
||||
"/hit",
|
||||
"/located",
|
||||
"/continued",
|
||||
"/island",
|
||||
"/worse",
|
||||
"/monitored",
|
||||
"/monitoring",
|
||||
"/haze",
|
||||
"/different",
|
||||
"/stations",
|
||||
"/sunny",
|
||||
"/singapore",
|
||||
"/improved",
|
||||
"/parts",
|
||||
"/wednesday",
|
||||
];
|
||||
|
||||
let valid_mocks: Vec<_> = valid_paths
|
||||
.iter()
|
||||
.map(|&p| {
|
||||
srv.mock(|when, then| {
|
||||
when.method(GET).path(p);
|
||||
then.status(200);
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let cmd = Command::cargo_bin("feroxbuster")
|
||||
.unwrap()
|
||||
.arg("--url")
|
||||
.arg(srv.url("/"))
|
||||
.arg("-vv")
|
||||
.arg("--collect-words")
|
||||
.arg("-t")
|
||||
.arg("1")
|
||||
.arg("--wordlist")
|
||||
.arg(file.as_os_str())
|
||||
.unwrap();
|
||||
|
||||
cmd.assert().success().stdout(
|
||||
predicate::str::contains("/doc1")
|
||||
.and(predicate::str::contains("/doc2"))
|
||||
.and(predicate::str::contains("/doc3"))
|
||||
.and(predicate::str::contains("/doc4")),
|
||||
);
|
||||
|
||||
sleep(Duration::new(2, 0));
|
||||
|
||||
for valid_mock in valid_mocks {
|
||||
assert_eq!(valid_mock.hits(), 1);
|
||||
}
|
||||
|
||||
teardown_tmp_directory(tmp_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// send a request to an endpoint that has abnormal redirect logic, ala fast-api
|
||||
fn scanner_forced_recursion_ignores_normal_redirect_logic() -> Result<(), Box<dyn std::error::Error>>
|
||||
{
|
||||
let srv = MockServer::start();
|
||||
let (tmp_dir, file) = setup_tmp_directory(&["LICENSE".to_string()], "wordlist")?;
|
||||
|
||||
let mock1 = srv.mock(|when, then| {
|
||||
when.method(GET).path("/LICENSE");
|
||||
then.status(301)
|
||||
.body("this is a test")
|
||||
.header("Location", srv.url("/LICENSE"));
|
||||
});
|
||||
|
||||
let mock2 = srv.mock(|when, then| {
|
||||
when.method(GET).path("/LICENSE/LICENSE");
|
||||
then.status(404);
|
||||
});
|
||||
|
||||
let mock3 = srv.mock(|when, then| {
|
||||
when.method(GET).path("/LICENSE/LICENSE/LICENSE");
|
||||
then.status(404);
|
||||
});
|
||||
|
||||
let mock4 = srv.mock(|when, then| {
|
||||
when.method(GET).path("/LICENSE/LICENSE/LICENSE/LICENSE");
|
||||
then.status(404);
|
||||
});
|
||||
|
||||
let outfile = tmp_dir.path().join("output");
|
||||
|
||||
Command::cargo_bin("feroxbuster")
|
||||
.unwrap()
|
||||
.arg("--url")
|
||||
.arg(srv.url("/"))
|
||||
.arg("--wordlist")
|
||||
.arg(file.as_os_str())
|
||||
.arg("--force-recursion")
|
||||
.arg("-o")
|
||||
.arg(outfile.as_os_str())
|
||||
.unwrap();
|
||||
|
||||
let contents = std::fs::read_to_string(outfile)?;
|
||||
println!("{}", contents);
|
||||
|
||||
assert!(contents.contains("/LICENSE"));
|
||||
assert!(contents.contains("301"));
|
||||
assert!(contents.contains("14"));
|
||||
|
||||
assert_eq!(mock1.hits(), 2);
|
||||
assert_eq!(mock2.hits(), 1);
|
||||
assert_eq!(mock3.hits(), 0);
|
||||
assert_eq!(mock4.hits(), 0);
|
||||
|
||||
teardown_tmp_directory(tmp_dir);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ pub fn setup_tmp_directory(
|
||||
filename: &str,
|
||||
) -> Result<(TempDir, PathBuf), Box<dyn std::error::Error>> {
|
||||
let tmp_dir = TempDir::new()?;
|
||||
let file = tmp_dir.path().join(&filename);
|
||||
let file = tmp_dir.path().join(filename);
|
||||
write(&file, words.join("\n"))?;
|
||||
Ok((tmp_dir, file))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user