# coding: utf-8 """ 'Simple Web Application Self Html Injection Tester' : swashit $Id$ For Web Application Developers, XSS Injection Simple Test Tool. Load YAML file wich described target url, cookie, parameters, and inject "'>&< string into empty parameters, request it, and check -(1), ">&<" is exist?, -(2), "'>&< exist?, and if existed specialchars in response html body, log with "BEEP" word. All of response data are saved into epoch-time-named directory. (requires PyYAML) have fun! http://www.glamenv-septzen.net/ copyright (c) 2009, sakamoto-gsyc-3s@glamenv-septzen.net All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import sys, os, datetime, time, logging, re import urllib, urlparse, httplib import yaml if 2 != len(sys.argv): print 'usage: python %s param_yaml_file' % sys.argv[0] sys.exit(-1) yaml_file = sys.argv[1] stream = '' try: f = open(yaml_file, 'r') stream = f.read() except IOError, e: print str(e) print 'open %s failure.' % yaml_file sys.exit(-1) try: targets = yaml.load(stream) except yaml.YAMLError, e: print str(e) sys.exit(-1) now_str = datetime.datetime.now().strftime('%Y%m%d_%H%M%S') cfg = {} cfg['now'] = now_str cfg['save_dir'] = os.path.join(os.getcwd(), now_str) cfg['log_file'] = now_str + ".log" cfg['reqtotal'] = 0 # basic file log configuration. logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(name)s %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', filename=cfg['log_file'], filemode='w+b') # create and adjust console log handler. console = logging.StreamHandler() console.setLevel(logging.DEBUG) console.setFormatter(logging.Formatter('%(name)s %(levelname)s %(message)s')) # add console log handler to root logger. logging.getLogger('').addHandler(console) log = logging.getLogger('main') try: os.mkdir(cfg['save_dir']) except BaseException, e: log.error("mkdir(%s) for image files failed." % cfg['save_dir']) log.error(e) sys.exit(-1) def proc_target(target): url = target['url'] parts = urlparse.urlsplit(url) if 'http' == parts.scheme: httpcon = httplib.HTTPConnection(parts.netloc) elif 'https' == parts.scheme: httpcon = httplib.HTTPSConnection(parts.netloc) headers = target['headers'] requests = target['requests'] for request in requests: proc_request(httpcon, target, headers, request, parts.path) cfg['reqtotal'] += 1 try: httpcon.close() except: pass special_chars = '''"'>AAA&BBB<''' re_special_chars1 = re.compile(r'>AAA&BBB<', re.M) re_special_chars2 = re.compile(r'"\'>AAA&BBB<', re.M) def inject_query(params): injected = False r = {} for k, v in params.items(): if None != v: r[k] = v else: r[k] = special_chars injected = True return (r, injected) def proc_request(con, target, headers, request, path): method = request['method'] (params, injected) = inject_query(request['params']) query = urllib.urlencode(params) body = '' if 'POST' == method: body = query headers['Content-Type'] = 'application/x-www-form-urlencoded' else: path = path + '?' + query try: con.request(method, path, body, headers) res = con.getresponse() log.info("\t[%s %s]" % (res.status, res.reason)) data = res.read() save_response(data) if injected and re_special_chars1.search(data): log.error('BEEEEP!! LEVEL1 at #%d' % (cfg['reqtotal'])) log.error("\tquery : %s" % (repr(params))) if injected and re_special_chars2.search(data): log.error('BEEEEP!! LEVEL2 at #%d' % (cfg['reqtotal'])) log.error("\tquery : %s" % (repr(query))) except BaseException, e: log.warn("HTTP socket error occurrs.") log.warn(e) # re-connect http try: con.close() con.connect() except: log.error("HTTP re-connect failure.") def save_response(data): # gen image data save filename filename = "%s_%05d.txt" % (cfg['now'], cfg['reqtotal']) filepath = os.path.join(cfg['save_dir'], filename) log.info("\tsave to [%s]" % filepath) # save f = None try: f = open(filepath, 'w+b') f.write(data) log.info("\t\tsave ok.") except IOError, e: log.warn("\t\tsaving failed, skipped.") log.warn(e) finally: if f: try: f.close() except: pass for target in targets: proc_target(target)