예제 #1
0
def load_session(key):
    #session = Session()
    session = SessionManager().current()   
    if session.has_key(key):
        mem_key = session[key]
        return memcache.get(mem_key)
    else:return None
예제 #2
0
    def finish_initializing(self, builder):   # pylint: disable=E1002

        self.sm = SessionManager('gecos-firstart')
        self.sm.start()

        iconfile = config.get_data_file('media', '%s' % ('wizard1.png',))
        self.set_icon_from_file(iconfile)

        screen = Gdk.Screen.get_default()
        sw = math.floor(screen.width() - screen.width() / 8)
        sh = math.floor(screen.height() - screen.height() / 9)
        self.resize(sw, sh)

        self.ui.btnTest.set_visible(False)
        self.ui.btnTest.set_sensitive(False)

        self.show_browser()
        self.block()

        self.dbusclient = DBusClient()
        self.dbusclient.connect('state-changed', self.on_dbusclient_state_changed)

        try:
            self.dbusclient.start()
            self.dbusclient.user_login()
            state = self.dbusclient.get_state(reply_handler=self.reply_handler, error_handler=self.error_handler)

        except Exception as e:
            self.unblock()
예제 #3
0
def load_session(key):
    #session = Session()
    session = SessionManager().current()
    if session.has_key(key):
        mem_key = session[key]
        return memcache.get(mem_key)
    else:
        return None
예제 #4
0
def save_session(key, value):
    #session = Session()
    session = SessionManager().current()
    if session.has_key(key):
        mem_key = session[key]
        if memcache.get(mem_key):
            memcache.set(mem_key, value, time=EXPIRATION_DELTA_SECONDS)
        else:
            memcache.add(mem_key, value, time=EXPIRATION_DELTA_SECONDS)
예제 #5
0
def save_session(key,value):
    #session = Session()
    session = SessionManager().current()   
    if session.has_key(key):
        mem_key = session[key]
        if memcache.get(mem_key):
            memcache.set(mem_key, value, time=EXPIRATION_DELTA_SECONDS)
        else:
            memcache.add(mem_key, value, time=EXPIRATION_DELTA_SECONDS)
예제 #6
0
파일: Sample.py 프로젝트: Neeneko/OKMiner
def runSampler(sample):
    sample.init()
    searches    =   sample.loadSearches()
    logging.info("Total search size [%s]" % len(searches))
    filtered    =   sample.filterSearches(searches)
    logging.info("Filtered search size [%s]" % len(filtered))
    logging.info("Logging in as [%s]" % sample.getUserName())
    SessionManager.doLogin(sample.getUserName())
    
    #for k,v in filtered.iteritems():
    #    logging.info("[%32s] => [%2d][%s]" % (k,v.Match,v.UserName))
    sample.crawlProfiles([x.UserName for x in filtered.itervalues()])
예제 #7
0
    def init(self):
        logging.info("Initializing Experiment [%s]" % self.__expName)

        bigConfigPath   =   os.path.join(self.__rootPath,"Config","experiments.ini")
        if not os.path.exists(bigConfigPath):
            raise RuntimError,"Global experiment list not found"

        bigConfig       =   ConfigParser.ConfigParser()
        bigConfig.optionxform=str
        
        bigConfig.read(bigConfigPath)
        if not bigConfig.has_section(self.__expName):
            raise RuntimeError,"No such experiment [%s] in global list" % self.__expName       

        if not os.path.exists(self.__dataPath):
            logging.warn("Data path does not exist, creating")
            os.mkdir(self.__dataPath)

        if os.path.exists(self.__expPath):
            logging.warn("Old experiment directory exists, clearing")
            shutil.rmtree(self.__expPath)
        os.mkdir(self.__expPath)
        os.mkdir(self.__searchPath)
        os.mkdir(self.__profilePath)

        self.__config.add_section("Settings")
        self.__config.add_section("Locations")
        self.__config.add_section("User")
        self.__config.add_section("Timestamps")
        for k,v in MinerExperiment.PROPERTIES.iteritems():
            if bigConfig.has_option(self.__expName,k):
                self.__config.set("Settings",k,bigConfig.get(self.__expName,k))
            else:
                self.__config.set("Settings",k,v)

        SessionManager.doLogin(self.getUserName())

        self.__fillUserProfile()

        if bigConfig.has_option(self.__expName,"Locations"):
            parser = shlex.shlex(bigConfig.get(self.__expName,"Locations"))
            parser.whitespace += ','
            for location in parser:
                if location == "Anywhere":
                    self.__config.set("Locations",location,"%s,0" % self.__getLocation(location))
                else:
                    self.__config.set("Locations",location,"%s,25" % self.__getLocation(location))
        else:
            self.__config.set("Locations","Near me","%s,25" % self.__getLocation("Near me"))

        self.saveConfig()
예제 #8
0
    def __init__(self, parent=None):  # attach to top-level?
        self.first = 1
        self.USERID = None
        self.PASSWORD = None
        self.myScreen = None

        Frame.__init__(self, parent)  # do superclass init
        self.canvas = Canvas(parent, width=600, height=500, bg='black')
        self.manager = SessionManager()
        self.pack()

        self.createWidgets()  # attach frames/widgets
        self.master.title("TN5250 for Python - Testing")
        self.master.iconname("TN5250")  # label when iconified
        self.strprg()
예제 #9
0
 def load_from_session_or_new(url):
     site = urlparse.urlparse(url).netloc.encode('utf-8')
     #site = url
     
     session = SessionManager().current()     
     cookie = None        
     if session.has_key(COOKIE_SESSION_NAME%get_url_key_name(site)):
         cookie = load_session( COOKIE_SESSION_NAME%get_url_key_name(site))
     
     if not cookie:
         session[COOKIE_SESSION_NAME%get_url_key_name(site)] =str(uuid.uuid4())
         cookie = MySimpleCookie()
     
     cookie.site = site
     return cookie
예제 #10
0
    def answerUDP(self, packet):
        # print(udp_color + 'New udp client:')
        # packet.summary()
        # print(reset_color, end="")

        dst_port = packet.sport
        src_port = packet.dport
        victim_ip = packet['IP'].src
        my_ip = packet['IP'].dst
        service = self.port_mapper[str(src_port) + "False"]

        if self.subscribers and victim_ip in self.subscribers[
                0].white_list or victim_ip in self.subscribers[0].black_list:
            return

        # TODO identify UDP -sV packet
        # if not self.os_spoofer and self.os_spoofer.personality_fingerprint:
        #	self.publish(Event(EventTypes.UDPOpenHit, victim_ip))

        ip = IP(src=my_ip, dst=victim_ip)
        udp = UDP(sport=src_port, dport=dst_port)
        payload = service.genRegexString()
        udp_main = ip / udp / payload
        # print(udp_color, end="")
        if SessionManager.getInstance().is_android:
            ether = Ether(src=packet['Ether'].dst,
                          dst=packet['Ether'].src,
                          type=0x800)
            sendp(ether / udp_main, iface=self.interfaces[0])
        else:
            send(udp_main, verbose=False)
        # print(udp_color + 'udp client done' + reset_color)
        return ""
예제 #11
0
    def OnHttpRecv(self, httpObj):
        if httpObj.header["method"] == "GET":
            action = httpObj.urlParamDict.get("action")
            if action == "user_new":
                userId = httpObj.urlParamDict.get("userid")
                s = SessionManager().CreateSession(userId, httpObj)
                if s:
                    s.Start()
            elif action == "user_close":
                userId = httpObj.urlParamDict.get("userid")
                SessionManager().StopSession(userId)

                #itchat.auto_login()

        if httpObj.header["method"] == "POST":
            pass
예제 #12
0
 def Disconnect(token):
     """
     Destroy a auth token
     :param token: auth token string
     :return:
     """
     return True, SessionManager.Logout(token)
예제 #13
0
    def load_from_session_or_new(url):
        site = urlparse.urlparse(url).netloc.encode('utf-8')
        #site = url

        session = SessionManager().current()
        cookie = None
        if session.has_key(COOKIE_SESSION_NAME % get_url_key_name(site)):
            cookie = load_session(COOKIE_SESSION_NAME % get_url_key_name(site))

        if not cookie:
            session[COOKIE_SESSION_NAME % get_url_key_name(site)] = str(
                uuid.uuid4())
            cookie = MySimpleCookie()

        cookie.site = site
        return cookie
예제 #14
0
def delete_session(message):
    log.logi(message, "Session deleting")
    ok = SessionManager.deleteSession(message.from_user.id, message.chat.id)
    if (ok):
        bot.reply_to(message, "Session successfully deleted")
    else:
        bot.reply_to(message,
                     "Failed to delete: you probably don't have any here")
예제 #15
0
 def __init__(self, con, cur):
     """ Virtually private constructor. """
     if EPSController.__instance != None:
         raise Exception("This class is a singleton!")
     else:
         EPSController.__instance = self
         self.con = con
         self.cur = cur
         self.sm = SessionManager.getInstance()
예제 #16
0
 def wrapper(self, session, *args, **kwargs):
     try:
         if SessionManager.CheckAdmin(session) is True:
             return fn(self, session, *args, **kwargs)
         else:
             return False, RenUIController.Unauthorized(session)
     except Exception as e:
         print "Exception in COrgan: %s" % str(e)
         return False, e
예제 #17
0
 def Disconnect(session):
     """
     Disconnect from the engine.
     :param session: session id
     """
     try:
         return True, SessionManager.Logout(session)
     except Exception as e:
         print "Exception in COrgan: %s" % str(e)
         return False, e
예제 #18
0
 def CheckConnect(session):
     """
     Check a session is valid.
     :param session: session id
     """
     try:
         return True, SessionManager.Check(session)
     except Exception as e:
         print "Exception in COrgan: %s" % str(e)
         return False, e
예제 #19
0
 def Auth(username, rawPassword):
     """
     Get authorization token by username and password
     :param username: unique username string, in pattern of username@domain
     :param rawPassword: password without encryption
     :return:
     """
     retVal = SessionManager.Login(username,
                                   EncryptUtil.EncryptSHA256(rawPassword))
     return retVal is not None, retVal
예제 #20
0
    def __fillUserProfile(self):
        payload =   {
                        "okc_api"   :   1
                    }
        payloadStr  =   urllib.urlencode(payload)

        page = SessionManager.getSession().get("http://www.okcupid.com/profile/%s?%s" % (self.getUserName(),payloadStr))
        data    =   json.loads(page.text)


        self.__config.set("User","Age","%s" % data["age"])
예제 #21
0
    def __getLocation(self,name):
        payload =   {
                        "okc_api"   :   1,
                        "func"      :   "query",
                        "query"     :   name
                    }
        payloadStr  =   urllib.urlencode(payload)

        page = SessionManager.getSession().get("http://www.okcupid.com/locquery?%s" % payloadStr)
        data    =   json.loads(page.text)
        return data["locid"]
예제 #22
0
 def AmIAdmin(session):
     """
     Get whether I am an admin.
     :param session: session id
     :return: True if admin session
     """
     try:
         return True, SessionManager.CheckAdmin(session)
     except Exception as e:
         print "Exception in WebUI: %s" % str(e)
         return False, e
예제 #23
0
def create_session(message):
    log.logi(message, "Session creation")
    ok = SessionManager.createSession("Untitled", message.from_user.id,
                                      message.chat.id)
    if (ok):
        bot.reply_to(message, "Session is created")
    else:
        bot.reply_to(
            message,
            "Failed to create: there is one already created by you in this chat."
        )
예제 #24
0
 def GetSessionLevel(session):
     """
     Get session level
     :param session: session id
     :return: session level value in int
     """
     try:
         return True, SessionManager.GetSession(session).Level
     except Exception as e:
         print "Exception in WebUI: %s" % str(e)
         return False, e
예제 #25
0
 def _stopIpTables(self):
     if SessionManager.getInstance().is_android:
         iptables = '/system/bin/iptables'
     else:
         iptables = 'iptables'
     for service in self.services:
         if service.tcp:
             set_iptable = iptables + ' -D OUTPUT -p tcp --tcp-flags RST RST --sport ' + str(
                 service.port) + ' -j DROP'
         elif service.udp:
             set_iptable = iptables + ' -D OUTPUT -p icmp --icmp-type destination-unreachable -j DROP'
         os.system(set_iptable)
예제 #26
0
def start(dbconnectionstring, username, password):
    Database.StartEngine(dbconnectionstring)

    session = SessionManager()
    
    if username != '' and password != '':
        if session.Login(username, password):
            print "Login success"
        else:
            print "Login Error Invalid Username/Password"

    peripherals = Peripherals

    from ReciptPrinter import ReciptPrinter
    peripherals.ReciptPrinter = ReciptPrinter

    #from EpsonEscPos import EpsonEscPos
    #peripherals.ReciptPrinter = EpsonEscPos
    
    app = Vikuraa(session, peripherals)
    
    app.MainLoop()
예제 #27
0
    def initBackend(self, backend, page):

        #init session if session is None
        if not page.session:
            #TO-DO: open session dialog to get connnection info
            page.session = SessionManager(self.parent)
        if len(page.session.sessionManagerDialog.auth_info.hostname) == 0:
            return

        term = backend(page.writeText,
                       page.session.sessionManagerDialog.auth_info)
        page.sendToBackend = term.sendChar
        page.term = term
예제 #28
0
    class Inventory(BaseDaemon.Inventory):

        import pyre.facilities
        import pyre.properties
        from UserManager import UserManager
        from SessionManager import SessionManager

        inventory = [
            pyre.properties.str("db", default="users.db"),
            pyre.properties.int("port", default=50000),
            pyre.facilities.facility("userManager", default=UserManager()),
            pyre.facilities.facility("sessionManager",
                                     default=SessionManager())
        ]
예제 #29
0
파일: Search.py 프로젝트: Neeneko/OKMiner
def doSearchJSON(url):
    """
    TODO -  this currently does one search to many, but we can not depend on the result numbers since
            blocked profiles are not returned.   So gotta make that more effient.
    """
    session =   SessionManager.getSession()
    pageSize    =   200
    rv  =   []
    

    i = 0
    timeKey = 1
    while True:
        newURL = url + "&timekey=%s&count=%s&low=%s&okc_api=1" % (timeKey,pageSize,(1+i*pageSize))
        if i == 0:
            newURL += "#Search"

        try:
            print newURL
            page = session.get(newURL)
        except requests.exceptions.ConnectionError:
            logging.warn("Connection error, sleeping 30 seconds")
            time.sleep(30)
            continue
        """
        print page
        print page.text
        print page.status_code
        print page.reason
        """
        if page.status_code != 200:
            logging.warn("Page Error [%s:%s] sleeping 60 seconds" % (page.status_code,page.reason))
            time.sleep(30)
            continue

        data        =   json.loads(page.text)
        data["url"] =   newURL
        logging.info("Search total_matches [%s] matches [%s]" % (data["total_matches"],len(data["amateur_results"])))
        if len(data["amateur_results"]) == 0:
            total = 0
            for v in rv:
                total += len(v["amateur_results"])
            logging.info("\tTotal [%s]" % total)

            return rv

        rv.append(data)
        timeKey    =   data["cache_timekey"]
        i+=1
        time.sleep(10)
예제 #30
0
    def __init__(self, parent=None):               # attach to top-level?
        self.first = 1
        self.USERID = None
        self.PASSWORD = None
        self.myScreen = None

        Frame.__init__(self, parent)               # do superclass init
        self.canvas = Canvas(parent,width=600,height=500, bg='black')
        self.manager = SessionManager()
        self.pack()

        self.createWidgets()                       # attach frames/widgets
        self.master.title("TN5250 for Python - Testing")
        self.master.iconname("TN5250") # label when iconified
        self.strprg()
예제 #31
0
 def Connect(username, encrypted_password):
     """
     Connect to the engine.
     :param username: username to connect
     :param encrypted_password: password string with specific encryption
     """
     try:
         success_flag = UserModel.Verify(username, encrypted_password)
         if success_flag is False:
             return True, None
         session_id = SessionManager.Login(username, encrypted_password)
         return True, session_id
     except Exception as e:
         print "Exception in COrgan: %s" % str(e)
         return False, e
예제 #32
0
 def Unauthorized(session):
     """
     Warp unauthorized service request feedback package.
     :param session: session id
     :return: unauthorized feedback
     """
     try:
         sObj = SessionManager.GetSession(session)
         sUser = ""
         if sObj is not None:
             sUser = sObj.Username
         LogUtil.Log(
             "username:%s, session:%s unauthorized request." %
             (sUser, session), RenUIController.__name__, "Warning", True)
     except Exception as e:
         print "Exception in RenWebUI authorization check: %s" % str(e)
     finally:
         return GCC.UNAUTHORIZED
예제 #33
0
    def __init__(self, interfaces, service_list, os_spoofer=None):
        super(ServiceSpoofer, self).__init__()
        if type(service_list) == str:
            service_list = [service_list]
        # service_list = [ "port,tcp/udp,id", "", ... ]
        self.interfaces = interfaces
        self.os_spoofer = os_spoofer

        self.tcp_ports = ""
        self.udp_ports = ""
        self.tcp_port_list = []
        self.udp_port_list = []
        self.services = []
        self.port_mapper = {
        }  # self.port_mapper[port+True] = mapped tcp service  #False for udp
        for service_data in service_list:
            data = service_data.split(',')
            s = Service(data[0], data[2],
                        True if data[1].lower() == 'tcp' else False)
            self.services.append(s)
            self.port_mapper[str(s.port) + str(s.tcp)] = self.services[
                -1]  # for Duel sniff version
            if s.tcp:
                if self.tcp_ports:
                    self.tcp_ports += " or "
                self.tcp_ports += "port " + str(s.port)
            else:
                if self.udp_ports:
                    self.udp_ports += " or "
                self.udp_ports += "port " + str(s.port)

        self.thread = Thread(target=self._start, daemon=True)
        self.tcp_thread = Thread(target=self._startTCP, daemon=True)
        self.udp_thread = Thread(target=self._startUDP, daemon=True)
        self.stopper = True

        self.ip_addrs = []
        self.ip_filter = ""
        for interface in self.interfaces:
            addr = SessionManager.getIpAddress(interface)
            self.ip_addrs.append(addr)
            if self.ip_filter:
                self.ip_filter += " or "
            self.ip_filter += "dst host " + addr
예제 #34
0
    def __init__(self, reference, manager):

        if isinstance(manager, str):
            ## If we have a current session, use this to try and get the required
            ## manager @todo This needs cleaning up I think.
            from SessionManager import SessionManager
            session = SessionManager.currentSession()
            if session:
                manager = session._factory.instantiate(manager)
            else:
                manager = None

        if not manager:
            raise RuntimeError(
                "Entity constructed with no Manager, or invalid " +
                "identifier")

        self.__reference = reference
        self.__manager = manager
        self.__interface = manager._getInterface()

        # This can be set to false, to disable API debugging at the per-class level
        self._debugCalls = True
예제 #35
0
class FirstartWindow(Window):

    __gtype_name__ = "FirstartWindow"

    def finish_initializing(self, builder):   # pylint: disable=E1002

        self.sm = SessionManager('gecos-firstart')
        self.sm.start()

        iconfile = config.get_data_file('media', '%s' % ('wizard1.png',))
        self.set_icon_from_file(iconfile)

        screen = Gdk.Screen.get_default()
        sw = math.floor(screen.width() - screen.width() / 8)
        sh = math.floor(screen.height() - screen.height() / 9)
        self.resize(sw, sh)

        self.ui.btnTest.set_visible(False)
        self.ui.btnTest.set_sensitive(False)

        self.show_browser()
        self.block()

        self.dbusclient = DBusClient()
        self.dbusclient.connect('state-changed', self.on_dbusclient_state_changed)

        try:
            self.dbusclient.start()
            self.dbusclient.user_login()
            state = self.dbusclient.get_state(reply_handler=self.reply_handler, error_handler=self.error_handler)

        except Exception as e:
            self.unblock()

    def show_browser(self):
        self.webview = webkit.WebView()
        self.ui.scContent.add(self.webview)
        self.webview.show()

    def reply_handler(self, state):
        if state == DBC_STATE_FINISHED:
            self.unblock()

    def error_handler(self, e):
        self.unblock()

    def translate(self):
        self.set_title(_('Guadalinex GECOS Guide'))
        self.ui.btnTest.set_label(_('Test'))
        self.ui.btnClose.set_label(_('Close'))

    def on_delete_event(self, widget, data=None):
        self.ungrab()
        return False

    def on_btnTest_clicked(self, widget):
        self.block()
        self.dbusclient.user_login()

    def on_btnClose_clicked(self, widget):
        self.sm.stop()
        self.ungrab()
        self.destroy()

    def on_show(self, widget):
        self.grab()

    def on_grab_broken_event(self, widget, event, user_data):
        self.grab()

    def on_dbusclient_state_changed(self, sender, state):
        if state == DBC_STATE_STOPPED:
            #print 'stopped...'
            pass

        elif state == DBC_STATE_RUNNING:
            #print 'running...'
            pass

        elif state == DBC_STATE_FINISHED:
            self.unblock()

    def block(self):
        self.webview.load_uri(GECOS_BLOCKED_URI)
        self.ui.btnClose.set_sensitive(False)
        self.ui.lblInfo.set_label(_('Please, wait while your system is being configured ...'))

    def unblock(self):
        self.webview.load_uri(GECOS_UNBLOCKED_URI)
        self.ui.btnClose.set_sensitive(True)
        self.ui.lblInfo.set_label(_('Your system has been configured.'))

    def grab(self):
        #return
        w = self.get_window()
        i = 0
        while i < 10:
            i = i + 1
            r = Gdk.keyboard_grab(w, False, 0L)
            #print r
            if r == Gdk.GrabStatus.SUCCESS:
                break
            time.sleep(1)
        r = Gdk.pointer_grab(w, True, 0, w, None, 0L)
        #print r

    def ungrab(self):
        r = Gdk.keyboard_ungrab(0L)
        r = Gdk.pointer_ungrab(0L)
예제 #36
0
import random
import string

from Administrator import Administrator
from Category import Category
from Customer import Customer
from Department import Department
from Product import Product
from Orders import Orders
import datetime

from SessionManager import SessionManager
from ShoppingCart import ShoppingCart

sesManag = SessionManager()
user = sesManag.add_user("qwerty", "pass", "name", "customer", "as", "asa",
                         1231, "asdas", "asdas")
admin = sesManag.add_user("qwertyAdmin", "pass", "name", "admin", "Asda")

user.register()
admin.register()
prod1 = Product("prod1", "prod1", 14, "as", 12431)
prod2 = Product("prod2", "prod1", 14, "as", 12412)
prod3 = Product("prod3", "prod1", 14, "as", 12413)

prod1.add_product()
prod2.add_product()
prod3.add_product()

shopping = ShoppingCart()
shopping.add_cart_item(prod1, 1)
예제 #37
0
class StartFrame(Frame):                          # an extended frame
    def __init__(self, parent=None):               # attach to top-level?
        self.first = 1
        self.USERID = None
        self.PASSWORD = None
        self.myScreen = None

        Frame.__init__(self, parent)               # do superclass init
        self.canvas = Canvas(parent,width=600,height=500, bg='black')
        self.manager = SessionManager()
        self.pack()

        self.createWidgets()                       # attach frames/widgets
        self.master.title("TN5250 for Python - Testing")
        self.master.iconname("TN5250") # label when iconified
        self.strprg()

    def outputScreen(self, initiator, startRow, startColumn, endRow, endColumn):
	"""
        Callable method to get screen updates
        """
        print 'ScreenUpdated - initiated from ', initiator, \
              ' Starting from -> ',startRow,endRow,' to -> ', \
              endRow,endColumn

        if initiator == 0:  ## 0  is from client and 1 is from host
            return

        # Note we only print the first 12 rows here
        indices = range(1,24)

        # for idx in indices:
        #     print self.myScreen.getPlaneData(idx,1,idx,80,1)
        #     print self.screen.getPlaneData(idx,1,80,2)

        fields = self.myScreen.getFields()

        if self.USERID == None or self.PASSWORD == None:
            self.USERID = raw_input("What's your username ? > ")
            self.PASSWORD = raw_input("What's your password ? > ")

        if self.first == 1:
            field = fields.getItem(0)
            field.setString(self.USERID)
            field = fields.getItem(1)
            field.setString(self.PASSWORD)

        for field in fields:
            #print field.toString()
            print field.getText()

            #print fields.readFormatTable(0x42,CodePage.CodePage())
            #print myScreen.getFields().readFormatTable(0x52,CodePage.CodePage())
        # Note we only print the first 12 rows here
        indices = range(1,25)
        row = 0

        for idx in indices:
            text = self.myScreen.getPlaneData(idx,1,idx,80,1)
            row += 15
            col = 0
            indx = range(0,79)
            for x in indx:
                col += 10
                self.canvas.create_text(col,row,text=text[x], anchor=E, fill='green')

        print 'number of fields',self.myScreen.getFields().getCount()
        """
            Patrick here I just keep pressing enter so that the screens
            keep coming up to see the messages.  Actually 6 times.
            the first is to send username and password.  Then 2 more times
            to get passed messages and stuff.  Then 2 more times to
            get messages at the bottom of the screen to make sure all is
            coming up.  Change this number if you want less for now.
        """

        if self.first < 7:
            self.myScreen.sendAidKey(0xF1)
            self.first += 1

    def strprg(self):
        if len(argv) >= 2: host = argv[1]
        else:
            host = askstring('Hostname', "Name of the Host ?")

        #ts = testsession()

        if len(argv) > 3:
            self.USERID = argv[2]
            self.PASSWORD = argv[3]

        session = self.manager.openSession('Session 1')
        session.setHost(host)      
        #session = Session.Session(host)

        session.set_debuglevel(1)
        self.myScreen = session.getScreen()
        session.getScreen().add_screen_listener(self.outputScreen)
        session.connect()

    def createWidgets(self):
        self.makeMenuBar()
        #self.canvas = self.root.createcomponent('canvas', (), None, \
        #Canvas, (self.interior(),), width=self.width, \
        #height=self.height,background="black")
        self.canvas.pack(fill=BOTH)
        #text = Text(self, relief=SUNKEN, fg='green', bg='black', \
        #width=150, height=50)
        #text.pack(fill=BOTH)

    def makeMenuBar(self):
        self.menubar = Menu(self.master)
        self.master.config(menu=self.menubar)    # master=top-level window
        self.fileMenu()
        self.editMenu()

    def fileMenu(self):
        pulldown = Menu(self.menubar, tearoff=0)
        pulldown.add_command(label='Open...', command=self.notdone, \
                             underline=0)
        pulldown.add_command(label='Quit',    command=self.quit,    \
                             underline=0)
        pulldown.entryconfig(0, state=DISABLED)
        self.menubar.add_cascade(label='File', underline=0, menu=pulldown)

    def editMenu(self):
        pulldown = Menu(self.menubar, tearoff=0)
        pulldown.add_command(label='Copy',   command=self.notdone)
        pulldown.add_command(label='Paste',    command=self.notdone)
        pulldown.entryconfig(0, state=DISABLED)
        pulldown.entryconfig(1, state=DISABLED)
        self.menubar.add_cascade(label='Edit', underline=0, menu=pulldown)

    def notdone(self):
        showerror('Not implemented', 'Not yet available')

    def quit(self):
        if askyesno('Verify quit', 'Are you sure you want to quit?'):
            Frame.quit(self)
예제 #38
0
    def answerTCP(self, packet):
        try:
            # print(tcp_color + 'New tcp client:')
            # packet.show()
            # print(reset_color, end="")

            dport = packet.sport
            sport = packet.dport
            SeqNr = packet.seq
            AckNr = packet.seq + 1
            my_mac = packet['Ether'].dst
            victim_mac = packet['Ether'].src
            victim_ip = packet['IP'].src
            my_ip = packet['IP'].dst
            service = self.port_mapper[str(sport) + "True"]

            if self.subscribers and victim_ip in self.subscribers[
                    0].white_list or victim_ip in self.subscribers[
                        0].black_list:
                return

            # Let os_spoofer handle publishing if able to
            '''
			if not self.os_spoofer:
				is_nmap = False
				is_sv = False
				try:
					if packet['TCP'].window == 64240 and \
							(('MSS', 1460) == packet['TCP'].options[0]) and \
							(('WScale', 8) == packet['TCP'].options[-1]):
						self.publish(Event(EventTypes.ServiceVersionScan, victim_ip))
						is_sv = True
				except:
					pass
				try:
					if packet['TCP'].window == 1024 and \
							packet['TCP'].options == [('MSS', 1460)] and \
							packet['IP'].flags == 0:
						self.publish(Event(EventTypes.TCPScan, victim_ip))
						is_nmap = True
				except:
					pass
				if not is_nmap and not is_sv:
					self.publish(Event(EventTypes.TCPOpenHit, victim_ip))
			'''

            # send syn ack
            ip = IP(src=my_ip, dst=victim_ip)
            ether = Ether(src=my_mac, dst=victim_mac, type=0x800)
            tcp_synack = TCP(sport=sport,
                             dport=dport,
                             flags="SA",
                             seq=SeqNr,
                             ack=AckNr,
                             options=[('MSS', 1460)])
            handshake = ip / tcp_synack
            if SessionManager.getInstance().is_android:
                handshake = ether / handshake
            # print(tcp_color+"sending synack", end="")
            if self.os_spoofer and self.os_spoofer.personality_fingerprint:
                handshake = self.os_spoofer.handleTCP(packet, handshake)
                if not handshake:
                    return
            if SessionManager.getInstance().is_android:
                ANSWER = srp1(handshake, timeout=8, iface=self.interfaces[0])
            else:
                ANSWER = sr1(handshake, timeout=8, verbose=0)
            # print("\ngot it"+reset_color)
            if not ANSWER:
                # print(red + "TIMEOUT on syn ack" + reset_color)
                return ""

            # Capture next TCP packet if the client talks first
            # GEThttp = sniff(filter="tcp and src host "+str(victim_ip)+" and port "+str(server_port),count=1)
            # GEThttp = GEThttp[0]
            # AckNr = AckNr+len(GEThttp['Raw'].load)

            # send psh ack (main tcp packet)
            SeqNr += 1
            # payload="HTTP/1.1 200 OK\x0d\x0aDate: Wed, 29 Sep 2010 20:19:05 GMT\x0d\x0aServer: Testserver\x0d\x0aConnection: Keep-Alive\x0d\x0aContent-Type: text/html; charset=UTF-8\x0d\x0aContent-Length: 291\x0d\x0a\x0d\x0a<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\"><html><head><title>Testserver</title></head><body bgcolor=\"black\" text=\"white\" link=\"blue\" vlink=\"purple\" alink=\"red\"><p><font face=\"Courier\" color=\"blue\">-Welcome to test server-------------------------------</font></p></body></html>"
            payload = service.genRegexString()
            tcp_pshack = TCP(sport=sport,
                             dport=dport,
                             flags="PA",
                             seq=SeqNr,
                             ack=AckNr,
                             options=[('MSS', 1460)])
            tcp_main = ip / tcp_pshack / payload
            if SessionManager.getInstance().is_android:
                tcp_main = ether / tcp_main
            # print(tcp_color, end="")

            if SessionManager.getInstance().is_android:
                ACKDATA = srp1(tcp_main, timeout=5, iface=self.interfaces[0])
            else:
                ACKDATA = sr1(tcp_main, timeout=5, verbose=0)
            # print(reset_color, end="")
            if not ACKDATA:
                # print(red + "TIMEOUT on ack data" + reset_color)
                return ""

            # send fin
            SeqNr = ACKDATA.ack
            tcp_fin_ack = TCP(sport=sport,
                              dport=dport,
                              flags="FA",
                              seq=SeqNr,
                              ack=AckNr,
                              options=[('MSS', 1460)])
            # print(tcp_color, end="")
            goodbye = ether / ip / tcp_fin_ack
            if SessionManager.getInstance().is_android:
                sendp(goodbye, iface=self.interfaces[0])
            else:
                send(goodbye, verbose=0)
            print(tcp_color + 'tcp client done' + reset_color)
        except Exception as e:
            print("TCP ERR", e)
            traceback.print_exec()
        return ""
예제 #39
0
    def __init__(self,
                 interface_list,
                 os_id='',
                 service_list='',
                 ignore='',
                 security_level=1,
                 log_dir=None,
                 kill_file='',
                 white_list='',
                 black_list='',
                 trusted=False,
                 trusted_file=''):
        if os_id == None:
            os_id = ''
        if service_list == None:
            service_list = ''
        if ignore == None:
            ignore = ''
        if log_dir == None:
            log_dir = os.path.dirname(sys.argv[0]) + '/logs'
        if kill_file == None:
            kill_file = ''
        if security_level == None:
            security_level = 1
        if white_list == None:
            white_list = ''
        if black_list == None:
            black_list = ''
        if trusted == None:
            trusted = False
        if trusted_file == None:
            trusted_file = ''

        self.interface_list = interface_list.split(',')
        self.os_id = os_id
        self.service_list = service_list
        self.services = self.service_list.split(';')
        self.ignore = ignore.split(',')
        self.kill_file = kill_file
        self.log_dir = log_dir
        self.security_level = int(security_level)
        self.white_list = white_list.split(',')
        self.black_list = black_list.split(',')
        if trusted and not trusted_file:
            trusted_file = os.path.dirname(
                sys.argv[0]) + '/settings/Default/trusted.csv'
        if trusted_file:
            open(trusted_file, 'a+').close()
        # TODO V&V inputs

        if self.kill_file:
            w = open(self.kill_file + ".good", "w+")
            w.write("nothing gold can stay")
            w.close()

        if not self.interface_list[-1]:
            self.interface_list = self.interface_list[:-1]
        if not self.white_list[-1]:
            self.white_list = self.white_list[:-1]
        if not self.black_list[-1]:
            self.black_list = self.black_list[:-1]
        if not self.services[-1]:
            self.services = self.services[:-1]
        if not self.ignore[-1]:
            self.ignore = self.ignore[:-1]

        self.os_spoofer = None
        self.service_spoofer = None

        if self.security_level:
            self.ids = IDS(self.log_dir, self.security_level, self.white_list,
                           self.black_list)
        #if self.os_id:
        self.os_spoofer = OsSpoofer(self.interface_list, self.os_id,
                                    self.ignore, self.services, trusted_file)
        if self.security_level:
            self.os_spoofer.addSubscriber(self.ids)
        print(str(self.os_spoofer))
        if self.service_list:
            self.service_spoofer = ServiceSpoofer(self.interface_list,
                                                  self.services,
                                                  self.os_spoofer)
            if self.security_level:
                self.service_spoofer.addSubscriber(self.ids)

        if self.os_spoofer:
            self.os_spoofer.start()
        if self.service_spoofer:
            self.service_spoofer.start()

        #'''
        # Normal mode
        while True if not self.kill_file else not os.path.isfile(
                self.kill_file):
            try:
                time.sleep(5)
            except:
                break
        if self.kill_file:
            os.remove(self.kill_file)
            os.remove(self.kill_file + ".good")

        # '''
        '''
        # Testing mode
        time.sleep(5)
        OhHoney.scpNmap(self.os_spoofer, True, self.log_file)
        #time.sleep(3)
        #print('____________________FIRST ROUND DONE______________________')
        #OhHoney.scpNmap(self.os_spoofer, True, self.log_file)
        #time.sleep(3)
        #print('____________________SECOND ROUND DONE______________________')
        #OhHoney.scpNmap(self.os_spoofer, True)
        # '''

        if self.os_spoofer:
            self.os_spoofer.stop()
        if self.service_spoofer:
            self.service_spoofer.stop()
        if self.ids and not SessionManager.getInstance().is_android:
            self.ids.clearIptables()
        print('ALL DONE')
예제 #40
0
from SessionManager import SessionManager
import sqlite3

if __name__ == "__main__":
    SessionManager.enterSession()
예제 #41
0
파일: Sample.py 프로젝트: Neeneko/OKMiner
    def crawlProfiles(self,names):
        count   =   0
        idx     =   0
        session =   SessionManager.getSession()
        while True:

            if idx >= len(names):
                return

            if count >= self.getMaxSample():
                return

            name    =   names[idx]
            logging.info("[%s]" % name)
            count += 1
            #-----------------------------------------------------------------------------------------
            url = "http://www.okcupid.com/profile/%s?okc_api=1" % name
            try:
                logging.info(url)
                page = session.get(url)
            except requests.exceptions.ConnectionError:
                logging.warn("Connection error, sleeping 30 seconds")
                time.sleep(30)
                continue
            if page.status_code != 200:
                logging.warn("Page Error [%s:%s] sleeping 60 seconds" % (page.status_code,page.reason))
                time.sleep(30)
                continue

            data    =       json.loads(page.text)
            idx     +=  1
            if int(data["status"]) > 100:
                logging.warn("Profile returned status [%s:%s]" % (data["status"],data["status_str"]))
                continue
            userId      =   data["userid"]
            fileName    =   os.path.join(self.__profilePath,"%s.json" % userId)
            with open(fileName,'wb') as fp:
                json.dump(data,fp,indent=4, separators=(',', ': '))
            #-----------------------------------------------------------------------------------------
            url = "http://www.okcupid.com/profile/%s" % name
            try:
                logging.info(url)
                page = session.get(url)
            except requests.exceptions.ConnectionError:
                logging.warn("Connection error, sleeping 30 seconds")
                time.sleep(30)
                continue
            if page.status_code != 200:
                logging.warn("Page Error [%s:%s] sleeping 60 seconds" % (page.status_code,page.reason))
                time.sleep(30)
                continue

            fileName    =   os.path.join(self.__profilePath,"%s.html" % userId)
            with open(fileName,'wb') as fp:
                fp.write(page.text.encode("UTF-8"))
            #-----------------------------------------------------------------------------------------
            low =   1
            while True:
                url = "http://www.okcupid.com/profile/%s/questions?okc_api=1&low=%d" % (name,low)
                result = json.loads(session.get(url).text)
                try:
                    logging.info(url)
                    page = session.get(url)
                except requests.exceptions.ConnectionError:
                    logging.warn("Connection error, sleeping 30 seconds")
                    time.sleep(30)
                    continue
                if page.status_code != 200:
                    logging.warn("Page Error [%s:%s] sleeping 60 seconds" % (page.status_code,page.reason))
                    time.sleep(30)
                    continue

                data    =       json.loads(page.text)
                fileName   =  os.path.join(self.__answerPath,"%s.%s.json" % (userId,low))
                with open(fileName,'wb') as fp:
                    json.dump(data,fp,indent=4, separators=(',', ': '))

                if data["pagination"]["cur_last"] == data["pagination"]["last"]:
                    break
                else:
                    low += 10
                time.sleep(2)

            time.sleep(10)