Exemple #1
0
    def __init__(self, msfclient):
        self.msfclient = msfclient
        # starting mongo
        global_init()
        # clearing sessions for new sessions
        svc.deleteSessions()

        print("[!]Starting Automation...")
        EventUtils.settingEvent(self, "Starting automation!")
        msfrpcdHandler()
        if self.msfclient.connect() is False:
            sys.exit()
        
        sessionMod(self.msfclient).sessionPrint() # NEED TO IMPROVE THIS

        session = Session.objects()
        if session:
            sessionMod(self.msfclient).activeSessionController()
        else:
            print("[!]Running exploit: exploit/multi/handler")
            exploit = self.msfclient.client.modules.use('exploit', 'exploit/multi/handler')
            time.sleep(5)
            exploit['ExitOnSession'] = False
            time.sleep(2)
            randomPayload = random.choice(self.choose_payload)
            print("[!]Using payload: ", randomPayload)
            _payload = self.msfclient.client.modules.use('payload', randomPayload)
            time.sleep(2)
            _payload['LHOST'] = '0.0.0.0'
            _payload['LPORT'] = '4444'
            time.sleep(5)
            exploit.execute(payload=_payload)
            print("[!]Executing exploit on port ", _payload['LPORT'])
            time.sleep(10)
            sessionMod(self.msfclient).activeSessionController()
def main():
    global_init('curae_domo')
    p = Patients()
    p.name = "Karl"
    p.address = "Berlin"
    p.phone = "00000000"
    p.care_level = "high"
    p.caretaker = "Alex"
    p.save()
Exemple #3
0
def main():
    # TODO: Setup mongoengine global values
    mongo_setup.global_init()
    df = pd.read_csv('VentasTienda.csv',
                     sep=',',
                     names=['TransactionID', 'ProductCode', 'ProductName'],
                     header=None)
    listOfTransaction = []
    df = df.sort_values(by='TransactionID')
    df.head()
    df1 = df.groupby(['TransactionID']).groups.keys()
    for i in df1:
        subset = df[(df['TransactionID'] == i)]
        mongo_json = {
            "TransactionID": i,
            "ProductCode": subset['ProductCode'].tolist()
        }
        istOfTransaction.append(mongo_json)
    finally:
        return {"return": ret, "error": error}


def query_ledger(**query):
    error = ""
    try:
        ret = dsvc.query_ledger(query)
    except Exception as e:
        error = f"Unable to query {e}"
        logging.error(error)
        ret = "Fail"
        raise Exception(error)
    finally:
        return {"return": ret, "error": error}


if __name__ == "__main__":
    import mongo_setup as ms
    ms.global_init()

    args = [
        'add_ledger', "--transaction_id", '1', "--transaction_category",
        TransactionTypes.APPLY_INCOME.name, "--description",
        f"MY DESCRIPTION - {_get_next_id()}", "--credit", '100', "--debit",
        '0', "--from_account", "fAccount", "--from_bucket", "fBucket",
        "--to_account", "tAccount", "--to_bucket", "tBucket"
    ]

    exec = LedgerManager()
    exec.run()
Exemple #5
0
                           values=['value'],
                           index=['accountId', 'class', 'name'],
                           columns=['BOM']).fillna(0)
    pivot.sort_index(axis=1, ascending=False, inplace=True)
    pivot.sort_values(by=['accountId', 'class', 'name'], inplace=True)

    return pivot


def clear_equities():
    Equity.drop_collection()


if __name__ == "__main__":
    import mongo_setup
    mongo_setup.global_init()

    name = "test"
    description = "test equity"
    accountId = "12345"
    equityClass = EquityClass.ASSET
    equityType = AssetType.ANNUITY
    equityTimeHorizon = EquityTimeHorizon.LONG_TERM
    equityStatus = EquityStatus.OPEN
    equityContingency = EquityContingency.FIXED
    interestRate = .01
    ret = enter_if_not_exists(name, description, accountId, equityClass,
                              equityType, equityTimeHorizon, equityStatus,
                              equityContingency, interestRate)

    if ret is not None:
Exemple #6
0
def init():
    mongo_setup.global_init()
def init_db(db_name):
    mongo_setup.global_init(db_name=db_name)
def main():
    mongo_setup.global_init()
Exemple #9
0
class pyRon:
    # starting mongo
    global_init()
    # clearing sessions for new sessions
    svc.deleteSessions()
    # Conditonals
    setSSL = ''

    # Object
    msfclient = None

    meta = {
        'db_alias': 'core',
        'collections': 'sessions'
    }

    def __init__(self):
        '''
        Init for pyRon.
        Sets up the client and session module.
        Enter for defaults.
        Puts you into mainMenu.
        Automation added to make the setup straight forward.
        '''
        dir_path = os.path.dirname(os.path.realpath(__file__))
        json_path = dir_path+'/json'
        if not os.path.isdir(json_path):
            os.mkdir(json_path)
        file = open(json_path+'/jobsJSON.json', 'w')
        file = open(json_path+'/sessionJSON.json', 'w')
        file = open(json_path+'/transportJSON.json', 'w')

        # Adding Customization OR using defaults
        try:
            automation = input("[!]Start automation or manual y/n: ").upper()
            if automation == 'Y':
                logger.info("Started Automation")
                self.msfclient = connectMsfRpcClient('msf', 'pass', '55553', '127.0.0.1', 'False')
                msfAutomation(self.msfclient)
                self.mainMenu()
            if automation == 'N':
                logger.info("Starting client setup")
                msfrpcdHandler()
                useDefaults = input("[DEFAULTS] Would you like to use the all defaults? y/n: ").upper()
                if useDefaults == 'Y':
                    self.username = '******'
                    self.password = '******'
                    self.port = 55553
                    self.host = "127.0.0.1"
                    self.ssl = False
                elif useDefaults == 'N':
                    print ('Press enter for individual defaults')
                    self.username = input('[Set Username] Please enter the username: '******'':
                        print ('[Set Username] Using default username: msf')
                        self.username = '******'
                    self.password = input('[Set Password] Please enter the password: '******'':
                        print ('[Set Password] Using default password: msf')
                        self.password = '******'
                    self.port = input('[Set Port] Please enter the port: ')
                    if self.port == '':
                        print('[Set Port] Using default port: 55553')
                        self.port = 55553
                    else:
                        self.port = int(self.port)
                    self.host = input('[Set Host] Please select the host: ')
                    if self.host == '':
                        print ('[Set Host] Using default host: 127.0.0.1')
                        self.host = '127.0.0.1'
                    setSSL = input('[Set SSL] Using ssl? t/F: ').upper()
                    if setSSL == '':
                        print ('[Set SSL] Using default: True')
                        self.ssl = True
                    elif setSSL == "T":
                        print ('[Set SSL] Setting SSL to True')
                        self.ssl = True
                    elif setSSL == "F":
                        print ('[Set SSL] Setting SSL to False')
                        self.ssl = False
        except ValueError:
            logger.info("User put wrong info for client and program is exiting")
            print ('Wrong input!')
            sys.exit()

        # Objects
        if automation == 'N':
            logger.info("Connecting to client with info")
            self.msfclient = connectMsfRpcClient(self.username, self.password, self.port, self.host, self.ssl)

        # Connect to msfrpcd
            if self.msfclient.connect() is False:
                logger.info("Client did not connect and program is exiting")
                sys.exit()
            self.sessionMod = sessionMod(self.msfclient)
            logger.info("Entering main menu")
            self.mainMenu()

    def epMenu(self, *args):
        '''
        Checking for required exploit and payload values.
        The user can provide required and edit any other run values.
        Can't run more than two arguments!!!
        '''
        choice = args[0]
        runOptions = choice.options
        if not choice.missing_required:
            print("[!]No required options!")
        else:
            logger.info("Entering required options")
            print("[+]Printing required options...")
            print("[!]Please fill out required options...")
            while choice.missing_required:
                try:
                    for r in choice.missing_required:
                        c = input(f"[!]{r}: ")
                        if '.' in c:
                            pass
                        else:
                            if any(char.isdigit() for char in c):
                                c = int(c)
                        choice[r] = c
                except ValueError as msg:
                    logger.info("Wrong value for required options")
                    print("Value error: " + str(msg))
                    continue
        menu = True
        while menu:
            try:
                logger.info("Entering changing options for exploit and payload")
                g = False
                print("[+]Printing run options...")
                for options in runOptions:
                    print(options)
                uc = input("[!]Do you want to change these values? y/n: ").upper()
                if uc not in ['Y', 'N']:
                    raise ValueError
                while g == False:
                    if uc == 'N':
                        return True
                    elif uc == "Y":
                        sg = False
                        while sg == False:
                            c = input("[!]Which option would you like to change: ")
                            # _isTrue = c in runOptions REMOVE IF IF STATEMENT WORKS
                            if c in runOptions:
                                cv = input("[!]Please enter new value: ")
                                if '.' in cv:
                                    pass
                                else:
                                    if any(char.isdigit() for char in cv):
                                        cv = int(cv)
                                choice[c] = cv
                                for options in runOptions:
                                    print(options)
                            if c == '':
                                uc = input("[!]Done changing values y/n:")
                            uc = input("[!]Do you want to change another value y/n: ").upper()
                            if uc == 'N':
                                return True
                            else:
                                return False
                return False
            except KeyboardInterrupt:
                logger.info('Keyboard interrupt in exploit and payload options')
                print('\n[!!]Exit Exploit and Payload Options')
                break
            except ValueError:
                logger.info("Wrong input in exploit options and payload options. Program exiting.")
                print("Wrong input!")
                continue


    def execteSimpleExploit(self):
        '''
        User inputting exploit and payload
        '''
        menu = True
        exploit = None
        _payload = None
        while menu:
            try:
                if exploit is None:
                    logger.info("Entering choice for exploit")
                    print ("[+]Using Exploit...")
                    exploit = input("[!]Please enter exploit: ")
                    exploit = self.msfclient.client.modules.use('exploit', exploit)
                    self.epMenu(exploit)
                if _payload is None:
                    logger.info("Entering choice for payload")
                    print ("[+]Setting payload...")
                    payload = input("[!]Please enter payload: ")
                    _payload = self.msfclient.client.modules.use('payload', payload)
                    self.epMenu(_payload)
                print("[+]Executing exploit...")
                exploit.execute(payload=_payload)
                time.sleep(10)
                sessions = self.msfclient.client.sessions.list
                if not sessions:
                    print('[!]No sessions connected directly after!')
                    print('[!]Please select option two in main menu to print connected sessions.')
                return False
            except KeyboardInterrupt:
                print('\n[!!]Exit Exploit and Payload Menu')
                break
            except ValueError as msg:
                logging.info("Wrong value entering the exploit or payload file path")
                logging.info(msg)
                print ("\n[!!]Wrong value for exploit! or payload")
                break
            except TypeError:
                logging.info("Wrong value entering the exploit or payload file path")
                print ("\n[!!]Wrong value for exploit or payload!")
                continue
        
    def listJobs(self):
        '''
        Prints currently running jobs.
        '''
        logger.info("Printing job list")
        try:
            self.dumpJobs()
            currentJobs = self.retrieveJobs()
            for s_id, s_info in currentJobs.items():
                print("\nJob ID: ", s_id)
                for info in s_info:
                    print(info + ':', s_info[info])
        except Exception as msg:
            print(msg)
            pass

    def dumpJobs(self):
        '''
        Dumps current jobs into a JSON file in order to read.
        '''
        logger.info("Dumping current jobs. I really need a better name for this.")
        try:
            with open('json/jobsJSON.json', 'w') as fp:
                json.dump(self.msfclient.client.jobs.list, fp, indent=4)
        except Exception as msg:
            print(msg)
            pass

    def retrieveJobs(self):
        logger.info("Retrieving jobs from JSON file")
        '''
        Retrieve session from json file
        '''
        try:
            json_file = open('json/jobsJSON.json', 'r')
            json_read = json_file.read()
            jobsFromJson = json.loads(json_read)
            return jobsFromJson
        except Exception:
            logger.info("No jobs. Closing as normal.")
            pass

    def mainMenu(self):
        '''
        MainMenu
        Option 1 will walk through exploit execution
        Option 2 will start session module
        '''
        menuGoing = False
        print("[+]Console Running and Connected!")
        print("\n[!]Entering Main Menu")
        while menuGoing == False:
            try:
                logger.info("Entering menu choice")
                print("\n[***]Main[***]\n")
                print("1.) Start Exploit and Payload")
                print("2.) Enter Session Module")
                print("press 0 to exit...")
                selection = int(input("[!] Please select an option: "))
                if selection == 1:
                    self.execteSimpleExploit()
                if selection == 2:
                    logging.info("Changing over sessionMod")
                    self.sessionMod.sessionMenu()
                if selection == 3:
                    self.listJobs()
                if selection == 0:
                    self.Exit()
                    exit(0)
            except Exception as msg:
                print(msg)
                print('\n[!!]Wrong input. Please select the correct input.')
                continue

    def Exit(self):
        logger.info("User is exiting")
        print("[!!] Exiting...")
        killall = input("[+]Kill all sessions? y/n: ").upper()
        if killall == 'Y':
            logger.info("User killing sessions")
            self.msfclient.client.consoles.console(self.msfclient.console).write('sessions -K')
        jobs = self.retrieveJobs()    
        if jobs:
            killjobs = input("[+]Kill all jobs? y/n: ").upper()
            if killjobs == 'Y':
                logger.info("User killing jobs")
                for k in jobs:
                    self.msfclient.client.jobs.stop(k)
        self.msfclient.client.consoles.destroy(self.msfclient.console)
Exemple #10
0
from flask_restful import Resource, Api
from resources.HealthCheck import HealthCheck
from resources.ShortenUrl import ShortenUrl
from resources.LongUrl import LongUrl
from resources.ReadShortUrl import ReadShortUrl
from resources.TinyUrlStats import TinyUrlStats
import mongo_setup as mgo
"""
Installation:
Download Python and Pycharm. Make sure you get pip with Python if you're on Windows
pip install flask
pip install flask-restful
Install the actual mongo from the website
pip install mongoengine
create the database collections all_urls and short_url_access
"""

app = Flask(__name__)
api = Api(app)
# initialize db connection
mgo.global_init()

api.add_resource(HealthCheck, '/healthcheck')
api.add_resource(ShortenUrl, '/shorten')
api.add_resource(LongUrl, '/getlong')
api.add_resource(ReadShortUrl, '/shortaccess')
api.add_resource(TinyUrlStats, '/getstats')

if __name__ == '__main__':
    app.run(debug=False)