def query_plugins(self, weapon_system, rpc):
     if 0 < len(weapon_system.plugins):
         self.output += "[-] Clearing old plugin(s) ...\n"
         for old_plugin in weapon_system.plugins:
             dbsession.delete(old_plugin)
         dbsession.flush()
     self.output += "[*] Attempting to detect remote plugin(s) ...\n"
     for algo in Algorithm.all():
         self.output += "[+] Looking for %s plugins ..." % algo
         plugin_names = rpc.root.exposed_get_category_plugins(algo.name)
         self.output += " found %d\n" % len(plugin_names)
         for plugin_name in plugin_names:
             self.output += "[+] Query info from remote plugin '%s'\n" % plugin_name
             details = rpc.root.exposed_get_plugin_details(algo.name, plugin_name)
             plugin = PluginDetails(
                 name=unicode(plugin_name),
                 author=unicode(details['author']),
                 website=unicode(details['website']),
                 version=unicode(details['version']),
                 description=unicode(details['description']),
                 copyright=unicode(details['copyright']),
             )
             plugin.precomputation = details['precomputation']
             plugin.algorithm_id = algo.id
             weapon_system.plugins.append(plugin)
 def __queue__(self):
     ''' Starts a job or leaves it in the queue (thread safe) '''
     logging.debug("Attempting to acquire queue mutex ...")
     self.mutex.acquire()
     logging.debug("Successfully acquired queue mutex.")
     queue = list(Job.queue())  # Create a copy of the queue
     for job in queue:
         logging.info("Dispatching job: %s" % job.job_name)
         if len(job) == 0:
             job.status = u"COMPLETED"
             dbsession.add(job)
             dbsession.flush()
         else:
             algo = Algorithm.by_id(job.algorithm_id)
             weapon_systems = WeaponSystem.system_ready(algo)
             if weapon_systems is not None and 0 < len(weapon_systems):
                 logging.info("Weapon systems available: %d" % (
                     len(weapon_systems),
                 ))
                 thread.start_new_thread(
                     self.__crack__, 
                     (job, weapon_systems[0],)
                 )
             else:
                 logging.info("No available weapon systems at this time.")
     self.mutex.release()
 def __queue__(self):
     ''' Starts a job or leaves it in the queue (thread safe) '''
     logging.debug("Attempting to acquire queue mutex ...")
     self.mutex.acquire()
     logging.debug("Successfully acquired queue mutex.")
     queue = list(Job.queue())  # Create a copy of the queue
     for job in queue:
         logging.info("Dispatching job: %s" % job.job_name)
         if len(job) == 0:
             job.status = u"COMPLETED"
             dbsession.add(job)
             dbsession.flush()
         else:
             algo = Algorithm.by_id(job.algorithm_id)
             weapon_systems = WeaponSystem.system_ready(algo)
             if weapon_systems is not None and 0 < len(weapon_systems):
                 logging.info("Weapon systems available: %d" %
                              (len(weapon_systems), ))
                 thread.start_new_thread(self.__crack__, (
                     job,
                     weapon_systems[0],
                 ))
             else:
                 logging.info("No available weapon systems at this time.")
     self.mutex.release()
Exemple #4
0
 def query_plugins(self, weapon_system, rpc):
     if 0 < len(weapon_system.plugins):
         self.output += "[-] Clearing old plugin(s) ...\n"
         for old_plugin in weapon_system.plugins:
             dbsession.delete(old_plugin)
         dbsession.flush()
     self.output += "[*] Attempting to detect remote plugin(s) ...\n"
     for algo in Algorithm.all():
         self.output += "[+] Looking for %s plugins ..." % algo
         plugin_names = rpc.root.exposed_get_category_plugins(algo.name)
         self.output += " found %d\n" % len(plugin_names)
         for plugin_name in plugin_names:
             self.output += "[+] Query info from remote plugin '%s'\n" % plugin_name
             details = rpc.root.exposed_get_plugin_details(
                 algo.name, plugin_name)
             plugin = PluginDetails(
                 name=unicode(plugin_name),
                 author=unicode(details['author']),
                 website=unicode(details['website']),
                 version=unicode(details['version']),
                 description=unicode(details['description']),
                 copyright=unicode(details['copyright']),
             )
             plugin.precomputation = details['precomputation']
             plugin.algorithm_id = algo.id
             weapon_system.plugins.append(plugin)
Exemple #5
0
    def get(self):
        author = users.get_current_user()
        name = self.request.get('name')
        query = Algorithm.query(ancestor=ndb.Key('Python Algorithms', 'scrap')) \
            .filter(Algorithm.author == author) \
            .filter(Algorithm.name == name) \
            .order(Algorithm.date)
        self.response.content_type = 'application/json'
        try:
            for algo in query.fetch(None):
                algo.public = True
                algo.put()
            msg = 'User %s shared "%s".' % (author.email(), name)

            result = Executor(algo.script, algo.viz, False)
            if result.events:
                step = max(1, len(result.events) / 10)
                events = result.events[2::step] + [result.events[-1]]
                events = [viz for lineno, viz, output in events]
                algo.events = str(events)
                algo.put()
                msg += '\nAdded %d preview events' % len(events)
            else:
                msg += '\nNo preview events were recorded'
            info(msg)
            notify(author, 'share', algo.name, algo.script, algo.viz)
            self.response.write(json.encode({'result': msg}))
        except Exception as e:
            msg = 'Cannot publish "%s": %s' % (name, e)
            error(msg)
            self.response.write(json.encode({'result': msg}))
 def post(self, *args, **kwargs):
     ''' Creates a job based on the parameters '''
     form = Form(
         jobname="Please enter a job name",
         algorithm_uuid="Please select an algorithm",
         hashes="Please provide the target hashes",
     )
     if form.validate(self.request.arguments):
         algo = Algorithm.by_uuid(self.get_argument('algorithm_uuid'))
         user = self.get_current_user()
         if algo is None:
             self.render('cracking/jobs/create.html', 
                 errors=['Invalid algorithm']
             )
         elif Job.by_job_name(self.get_argument('jobname')) is not None:
             self.render('cracking/jobs/create.html', 
                 errors=['Duplicate job name']
             )
         else:
             job = self.create_job(user, algo)
             dispatch = Dispatch.Instance()
             dispatch.refresh()
             self.render("cracking/jobs/created.html", job=job)
     else:
         self.render('cracking/jobs/create.html', errors=form.errors)
 def __crack__(self, job, weapon_system):
     '''
     Does the actual password cracking, before calling this function you should
     ensure the weapon system is online and not busy
     '''
     results = None
     user = User.by_id(job.user_id)
     if user is None:
         logging.error(
             "Invalid job passed to dispatcher (no user with id %d)." %
             (job.user_id, ))
     elif job == None:
         logging.error("Invalid job passed to dispatcher (job is None).")
     else:
         job.started = datetime.now()
         algorithm = Algorithm.by_id(job.algorithm_id)
         try:
             ssh_keyfile = NamedTemporaryFile()
             ssh_keyfile.write(weapon_system.ssh_key)
             ssh_keyfile.seek(0)
             ssh_context = SshContext(
                 weapon_system.ip_address,
                 user=weapon_system.ssh_user,
                 keyfile=ssh_keyfile.name,
             )
             rpc_connection = rpyc.ssh_connect(
                 ssh_context,
                 weapon_system.service_port,
             )
             hashes = job.to_list()
             logging.info("Sending %s job to %s for cracking." % (
                 job.job_name,
                 weapon_system.weapon_system_name,
             ))
             job.status = u"IN_PROGRESS"
             dbsession.add(job)
             dbsession.flush()
             results = rpc_connection.root.exposed_crack_list(
                 job.id,
                 job.to_list(),
                 algorithm.algorithm_name,
             )
         except:
             logging.exception(
                 "Connection to remote weapon system failed, check parameters."
             )
         finally:
             ssh_keyfile.close()
         if results is not None:
             job.save_results(results)
         else:
             logging.warn("No results returned from weapon system.")
         job.status = u"COMPLETED"
         job.finished = datetime.now()
         dbsession.add(job)
         dbsession.flush()
         self.__next__()
 def __crack__(self, job, weapon_system):
     '''
     Does the actual password cracking, before calling this function you should
     ensure the weapon system is online and not busy
     '''
     results = None
     user = User.by_id(job.user_id)
     if user is None:
         logging.error("Invalid job passed to dispatcher (no user with id %d)." % (
             job.user_id,
         ))
     elif job == None:
         logging.error("Invalid job passed to dispatcher (job is None).")
     else:
         job.started = datetime.now()
         algorithm = Algorithm.by_id(job.algorithm_id)
         try:
             ssh_keyfile = NamedTemporaryFile()
             ssh_keyfile.write(weapon_system.ssh_key)
             ssh_keyfile.seek(0)
             ssh_context = SshContext(
                 weapon_system.ip_address,
                 user=weapon_system.ssh_user, 
                 keyfile=ssh_keyfile.name,
             )
             rpc_connection = rpyc.ssh_connect(
                 ssh_context, 
                 weapon_system.service_port,
             )
             hashes = job.to_list()
             logging.info("Sending %s job to %s for cracking." % (
                 job.job_name, 
                 weapon_system.weapon_system_name,
             ))
             job.status = u"IN_PROGRESS"
             dbsession.add(job)
             dbsession.flush()
             results = rpc_connection.root.exposed_crack_list(
                 job.id, 
                 job.to_list(), 
                 algorithm.algorithm_name,
             )
         except:
             logging.exception("Connection to remote weapon system failed, check parameters.")
         finally:
             ssh_keyfile.close()
         if results is not None:
             job.save_results(results)
         else:
             logging.warn("No results returned from weapon system.")
         job.status = u"COMPLETED"
         job.finished = datetime.now()
         dbsession.add(job)
         dbsession.flush()
         self.__next__()
Exemple #9
0
 def post(self):
     author = users.get_current_user()
     self.response.content_type = 'application/json'
     try:
         algo = Algorithm(parent=ndb.Key('Python Algorithms', 'scrap'))
         algo.author = author
         algo.script = self.request.get('script')
         algo.viz = self.request.get('viz')
         algo.name = self.request.get('name')
         algo.public = False
         algo.put()
         # notify(author, 'save', algo.name, algo.script, algo.viz)
         msg = 'Script was successfully saved by %s as "%s"' % (
             author.email(), algo.name)
         info(msg)
         info(algo.script)
     except Exception as e:
         msg = 'Could not save script: %s' % e
     self.response.write(json.encode({'result': msg}))
Exemple #10
0
 def loadScript(self, name, user=None):
     query = Algorithm.query(ancestor=ndb.Key('Python Algorithms', 'scrap')) \
         .filter(Algorithm.name == name) \
         .order(-Algorithm.date)
     algo = None
     for algo in query.fetch(None):
         if algo.public or not user or algo.author == user:
             break
     if algo:
         logging.info('Load script ' + str(algo.date))
         return algo.name, algo.script, algo.viz, algo.author
     else:
         logging.info('No algo found for ' + name)
         return name, "# Cannot find: '" + name + "'", "", user
Exemple #11
0
 def get(self):
     author = users.get_current_user()
     name = self.request.get('name')
     query = Algorithm.query(ancestor=ndb.Key('Python Algorithms', 'scrap')) \
         .filter(Algorithm.author == author) \
         .filter(Algorithm.name == name)
     self.response.content_type = 'application/json'
     try:
         for version in query.fetch(None):
             version.key.delete()
         self.response.write(json.encode({'result': 'Deleted "%s"' % name}))
         info('User %s deleted "%s"' % (
             author.email(),
             self.request.get('name'),
         ))
     except Exception as e:
         self.response.write(
             json.encode(
                 {'result': 'Could not delete "%s": %s' % (name, e)}))
 def post(self, *args, **kwargs):
     ''' Creates a job based on the parameters '''
     form = Form(
         jobname="Please enter a job name",
         algorithm_uuid="Please select an algorithm",
         hashes="Please provide the target hashes",
     )
     if form.validate(self.request.arguments):
         algo = Algorithm.by_uuid(self.get_argument('algorithm_uuid'))
         user = self.get_current_user()
         if algo is None:
             self.render('cracking/jobs/create.html',
                         errors=['Invalid algorithm'])
         elif Job.by_job_name(self.get_argument('jobname')) is not None:
             self.render('cracking/jobs/create.html',
                         errors=['Duplicate job name'])
         else:
             job = self.create_job(user, algo)
             dispatch = Dispatch.Instance()
             dispatch.refresh()
             self.render("cracking/jobs/created.html", job=job)
     else:
         self.render('cracking/jobs/create.html', errors=form.errors)
Exemple #13
0
    def load(self, filter):
        query = Algorithm.query(ancestor=ndb.Key('Python Algorithms', 'scrap')) \
            .filter(filter)

        def info(pair):
            n, algo = pair
            return (
                algo.name,
                algo.author.nickname(),
                algo.author.user_id(),
                algo.events or '[]',
                n,
                'not yet shared' if not algo.public else '',
            )

        algos = reversed(sorted(query.fetch(None), key=lambda algo: algo.date))
        algos = map(info, enumerate(algos))
        found = set()
        result = []
        for algo in algos:
            if algo[0] not in found:
                found.add(algo[0])
                result.append(algo)
        return sorted(result)
Exemple #14
0
    def execute_upload(self,request):
                import uuid
                form = self.form_class(request.POST, request.FILES)
                print request.FILES['file']
                if  form.is_valid():
                    print request.FILES['file']
                    resp = self.handle_uploaded_file(request.FILES['file'])
                    if resp['score'] < 100 :
                        button_type = 'btn-warning'
                    else:
                        button_type = 'btn-success'
                    self.uuid_index  = str(uuid.uuid4())


                    resp['score']= random.randint(1, 100)

                    model = Algorithm

                    run_rank = model.objects.filter(rating__gt=int(resp['score'])).order_by('ranking')
                    if len(run_rank) > 0:
                        rankobj = run_rank.last()
                        rank = rankobj.ranking + 1

                    else:
                        rank = 1

                    run_rank_low = model.objects.filter(rating__lte=int(resp['score']))
                    if len(run_rank_low) > 0 :
                        for i in run_rank_low:
                            i.ranking += 1
                            i.save()

                    else:
                        pass

                    
                   

                    b = Algorithm(run_id= self.uuid_index, name=request.user.username, user=request.user, ranking = rank, rating=resp['score'], button = button_type, time= resp['duration'], cpu=18)
                    b.save()
                    job_post = u'{0} has sent a job score: {1} rank: {2} :'.format(request.user.username,resp['score'], rank)
                    
                    resp = model.objects.all().order_by('ranking')
                    values = resp.values('run_id')
                    
                    for ind, item  in enumerate(values) :
                        if (item['run_id']) == self.uuid_index :
                            paging =  divmod(ind, 5)[0]

                    feed = Feed(user=request.user, post=job_post, job_link='/leaderboard?q=foo&flop=flip&page='+str(paging+1))
                    feed.save()


                    #request.user.profile.notify_job_done(b)      
                    

                    like = Activity(activity_type=Activity.RUN_PROCESSED, feed=feed.pk, user=request.user)
                    like.save()

                    user = request.user
                    user.profile.notify_liked_bis(feed)
                    

                    return paging
Exemple #15
0
    def execute_upload(self, request):
        import uuid
        form = self.form_class(request.POST, request.FILES)
        print request.FILES['file']
        if form.is_valid():
            print request.FILES['file']
            resp = self.handle_uploaded_file(request.FILES['file'])
            if resp['score'] < 100:
                button_type = 'btn-warning'
            else:
                button_type = 'btn-success'
            self.uuid_index = str(uuid.uuid4())

            resp['score'] = random.randint(1, 100)

            model = Algorithm

            run_rank = model.objects.filter(
                rating__gt=int(resp['score'])).order_by('ranking')
            if len(run_rank) > 0:
                rankobj = run_rank.last()
                rank = rankobj.ranking + 1

            else:
                rank = 1

            run_rank_low = model.objects.filter(rating__lte=int(resp['score']))
            if len(run_rank_low) > 0:
                for i in run_rank_low:
                    i.ranking += 1
                    i.save()

            else:
                pass

            b = Algorithm(run_id=self.uuid_index,
                          name=request.user.username,
                          user=request.user,
                          ranking=rank,
                          rating=resp['score'],
                          button=button_type,
                          time=resp['duration'],
                          cpu=18)
            b.save()
            job_post = u'{0} has sent a job score: {1} rank: {2} :'.format(
                request.user.username, resp['score'], rank)

            resp = model.objects.all().order_by('ranking')
            values = resp.values('run_id')

            for ind, item in enumerate(values):
                if (item['run_id']) == self.uuid_index:
                    paging = divmod(ind, 5)[0]

            feed = Feed(user=request.user,
                        post=job_post,
                        job_link='/leaderboard?q=foo&flop=flip&page=' +
                        str(paging + 1))
            feed.save()

            #request.user.profile.notify_job_done(b)

            like = Activity(activity_type=Activity.RUN_PROCESSED,
                            feed=feed.pk,
                            user=request.user)
            like.save()

            user = request.user
            user.profile.notify_liked_bis(feed)

            return paging
    def create_or_edit(self, data, contract):
        try:
            algorithm_id = data.get('id')
            if not algorithm_id:
                algorithm = Algorithm()
            else:
                algorithm = Algorithm.query.filter_by(
                    id=algorithm_id).first_or_404()

                if algorithm.contract_id != contract.id and not contract.is_admin:
                    return None

            algorithm.title = data.get('title')
            algorithm.steps = data.get('steps')
            algorithm.description = data.get('description')
            algorithm.categories = data.get('categories')
            algorithm.template_id = data.get('template_id')
            algorithm.initial_step = data.get('steps')[0].get('uid')
            algorithm.current_step = data.get('steps')[0].get('uid')

            if data.get('is_template') and contract.is_admin:
                algorithm.clinics = data.get('clinics')
                algorithm.is_template = True
                algorithm.template_category = data.get('template_category')
            else:
                algorithm.patient_id = contract.patient_id
                algorithm.contract_id = contract.id

            if not algorithm_id:
                self.db.session.add(algorithm)

            self.change_step(algorithm, algorithm.initial_step)

            self.check_inits(algorithm)

            return algorithm
        except Exception as e:
            log(e)
            return None
Exemple #17
0
#!/usr/bin/env python

import sqlalchemy

from models import Algorithm, Base, Currency, Wallet

if __name__ == "__main__":
    engine = sqlalchemy.create_engine('sqlite:///:memory:', echo=True)

    Base.metadata.create_all(engine)

    Session = sqlalchemy.orm.sessionmaker(bind=engine)

    algo = Algorithm(name="crytponight")
    session = Session()
    session.add(algo)
    session.commit()
 def algorithm(self):
     ''' Returns an algorithm object based on self.algorithm_id '''
     return Algorithm.by_id(self.algorithm_id)
    def execute_upload(self,request):
                import uuid
                form = self.form_class(request.POST, request.FILES)

                if  form.is_valid():
                    #resp = self.handle_uploaded_file(request.FILES['file'])
                    with open('uploaded_custom.py', 'wb+') as destination:
                        for chunk in request.FILES['file'].chunks():
                            destination.write(chunk)
                        destination.close()

                    proxy = callme.Proxy(server_id='fooserver2',amqp_host='amqp://*****:*****@37.187.117.106/echopen1', timeout=3600)
               
                    resp = proxy.denoise(open('uploaded_custom.py', 'rb').read())

                    self.uuid_index  = str(uuid.uuid4())

                    model = Algorithm

                    run_rank = model.objects.filter(rating__gt=int(resp['score'])).order_by('ranking')
                    if len(run_rank) > 0:
                        rankobj = run_rank.last()
                        rank = rankobj.ranking + 1

                    else:
                        rank = 1
                     
                    run_rank_low = model.objects.filter(rating__lte=int(resp['score']))
                    if len(run_rank_low) > 0 :
                        for i in run_rank_low:
                            i.ranking += 1
                            i.save()

                    else:
                        pass
                    
                                  
                    b = Algorithm(run_id= self.uuid_index, name=request.user.username, user=request.user, ranking = rank, rating=resp['score'], button = button_type, time= resp['duration'], source_code=source, cpu=18)
                    b.save()
                    job_post = u'{0} has sent a job score: {1} rank: {2} :'.format(request.user.username,resp['score'], rank)
                    
                    resp = model.objects.all().order_by('ranking')
                    values = resp.values('run_id')
                    
                    for ind, item  in enumerate(values) :
                        if (item['run_id']) == self.uuid_index :
                            paging =  divmod(ind, 5)[0]

                    feed = Feed(user=request.user, post=job_post, job_link='/leaderboard?q=foo&flop=flip&page='+str(paging+1))
                    feed.save()


                    #request.user.profile.notify_job_done(b)      
                    

                    like = Activity(activity_type=Activity.RUN_PROCESSED, feed=feed.pk, user=request.user)
                    like.save()

                    user = request.user
                    user.profile.notify_liked_bis(feed)
                    

                    return paging
Exemple #20
0
    sys.stdout.flush()
    password1 = getpass.getpass()
    sys.stdout.write(PROMPT + "Confirm New Admin ")
    sys.stdout.flush()
    password2 = getpass.getpass()
    if password1 == password2 and 12 <= len(password1):
        password = password1
    else:
        print(WARN +
              'Error: Passwords did not match, or were less than 12 chars')
        os._exit(1)

### Initialize algorithms
md5 = Algorithm(
    name=u'MD5',
    length=32,
    chars=u'1234567890ABCDEF',
)
lm = Algorithm(
    name=u'LM',
    length=16,
    chars=u'1234567890ABCDEF',
)
ntlm = Algorithm(
    name=u'NTLM',
    length=16,
    chars=u'1234567890ABCDEF',
)
dbsession.add(md5)
dbsession.add(lm)
dbsession.add(ntlm)
 def algorithm(self):
     ''' Returns an algorithm object based on self.algorithm_id '''
     return Algorithm.by_id(self.algorithm_id)