Example #1
0
def encryption_oracle(plain):
    prefix = utils.randomString(randint(5, 10))
    suffix = utils.randomString(randint(5, 10))
    if randint(0, 1) == 0:
        return utils.AES_ECB_encrypt(utils.randomString(BLOCKSIZE),
                                     prefix + plain + suffix), "ECB"
    else:
        return utils.AES_CBC_encrypt(utils.randomString(BLOCKSIZE),
                                     utils.randomString(BLOCKSIZE),
                                     prefix + plain + suffix), "CBC"
Example #2
0
def LoadExperiment(folder):
    # folder = os.path.abspath(folder)

    # ParseExperiment = importlib.import_module(folder.replace('/','.')+'.ParseExperiment')
    ParseExperiment = SourceFileLoader(utils.randomString(10), folder +
                                       '/ParseExperiment.py').load_module()
    return ParseExperiment.parse()
Example #3
0
def check(host):
    s = session()
    # reg
    result = s.post(f"http://customer.{host}/", data={
        "username": utils.randomString(),
        "password": "******"
    }).content
    if b"You are not eligible to view flag!" not in result:
        return 0, "Failed to login"

    # check promote
    result = s.post(f"http://customer.{host}/promote", data={
        "user_token": "123"
    }).content
    if b"Not Admin..." not in result:
        return 0, "Wrong result of plebian promotion"

    # admin promotion
    headers = {"cookie": "token=bi6yQTB5nhBi7CaSMYF"}
    result = post(f"http://customer.{host}/promote", data={
        "user_token": s.cookies.get("token")
    }, headers=headers).content
    result = s.get(f"http://customer.{host}/").content
    if b'we{3d090a68-02bf-4e6d-b2d7-3d9db9a2f6f1@p00r-A6m1n}' not in result:
        return 0, "Failed to get flag"
    return 1, ""
Example #4
0
def exploit(host):
    s = session()
    # reg
    un = utils.randomString()
    print(un)
    result = s.post(f"http://faster.{host}:1002/",
                    data={
                        "username": un,
                        "password": "******"
                    }).content
    if b"Hello Our Precious Customers!" not in result:
        return 0, "Failed to login"
    # race cond buy
    def f():
        s.post(f"http://faster.{host}:1002/buy/1")

    ps = []
    for i in range(10):
        p = Process(target=f)
        ps.append(p)
        p.start()
    for i in ps:
        i.join()
    # sell
    result = s.get(f"http://faster.{host}:1002/").content
    ids = match_ids.findall(result.decode("utf-8"))
    for i in ids:
        s.post(f"http://faster.{host}:1002/sell/{i}")
    result = s.get(f"http://faster.{host}:1002/").content
    bucks = match_bucks.findall(str(result))
    if int(bucks[0]) <= 20:
        return 0, "Failed to exploit"
    return 1, ""
Example #5
0
def createRoom(hostName):
    key = randomString(stringLength=4)
    result = db.child("rooms").child(key).set({"roomKey": key, "players": [hostName], "open": True})

    if len(result) != 0:
        return True, f"Successfully created room. Your room key is {key}. Please share it with your friends", \
            {"roomKey": key}
    else:
        return False, "Could not create room. Please try again", {}
Example #6
0
		def __init__(self, url, dirname, urlfile):
				self.secret = randomString(SECRET_LENGTH)
				n = ListableNode(url,dirname, self.secret)
				t = Thread(target=n._start)
				t.setDaemon(1)
				t.start()

				sleep(HEAD_START)
				self.server = ServerProxy(url)
				super(Client, self).__init__()
Example #7
0
 def get(self, groupId):
     if is_group_admin(self.current_user['id'], groupId):
         update_group(groupId, invitationKey=randomString(10))
         log_user(self.current_user['id'],
                  f'group id {groupId} new invitation key get')
     else:
         log_user(
             self.current_user['id'],
             f'group id {groupId} new invitation key unauthorized get')
     self.redirect(f"/group_invitation_settings/{groupId}")
Example #8
0
 def reportResult(self, result):
     self._buildStamp = '{0}-Nightly'.format(
         datetime.datetime.now().strftime('%Y%m%d-%H%M'),
         utils.randomString(4))
     try:
         #generate XML
         self.genXml(self.genTestXml, result)
         #generate Tests.xml
         #submitFile('Tests.xml')
     except:
         raise
Example #9
0
def saveImage(bits,name=None):
  if not bits: return None
  if not name: name=utils.randomString()
  image = ForumImages(key_name=name)
  format,width,height=utils.getImageInfo(bits)
  image.imageid = name
  image.format  = format
  image.width   = width
  image.height  = height
  image.size    = len(bits)
  image.bits    = db.Blob(bits)
  image.put()
  return name
Example #10
0
 def __init__(self, url, dirname, urlfile):
     super().__init__()
     self.secret = randomString(SECRET_LENGTH)
     n = Node(url, dirname, self.secret)
     t = Thread(target=n._start)
     t.setDaemon(1)
     t.start()
     sleep(HEAD_START)
     self.server = ServerProxy(url)
     with open(urlfile) as input:
         for line in input:
             line = line.strip()
             self.server.hello(line)
Example #11
0
def saveImage(bits, name=None):
    if not bits: return None
    if not name: name = utils.randomString()
    image = ForumImages(key_name=name)
    format, width, height = utils.getImageInfo(bits)
    image.imageid = name
    image.format = format
    image.width = width
    image.height = height
    image.size = len(bits)
    image.bits = db.Blob(bits)
    image.put()
    return name
Example #12
0
def check(host):
    s = session()
    # reg
    result = s.post(f"http://na2.{host}/",
                    data={
                        "username": utils.randomString(),
                        "password": "******"
                    }).content
    if b"Welcome to our super-duper-duper safe note app!" not in result:
        return 0, "Failed to login"

    # add note
    result = s.post(f"http://na2.{host}/add_note",
                    data={
                        "content": "<script>alert(1)</script>",
                        "xsrf": s.cookies.get("token")
                    }).content
    if b"Note ID: " not in result:
        return 0, "Wrong result of add note"

    # test xss
    note_id = match_ids.findall(str(result))[0]
    result = s.get(f"http://na2.{host}/note/{note_id}").content
    if b"<script>alert(1)</script>" not in result:
        return 0, "Cannot trigger XSS"

    # test logout
    s.post(f"http://na2.{host}/logout")

    if "token" in s.cookies:
        return 0, "Logout failed"

    # test admin
    result = s.post(f"http://na2.{host}/",
                    data={
                        "username": "******",
                        "password": "******"
                    }).content

    # admin flag
    result = s.get(f"http://na2.{host}/note/1").content
    if b'we{f93486a2-4f82-42b6-8dc8-04cd765501f3@1nsp1reD-bY-cHa1I-1N-BbC7F}' not in result:
        return 0, "Failed to get flag"
    return 1, ""
Example #13
0
def testContainsNANA():
    numTests = 25
    strings = ['CACA', 'GAGA', 'TATA', 'AAAA']
    for i in range(numTests):
        randStr = utils.randomString('abcdef')
        val = containsNANA(randStr)
        utils.tprint(randStr, ':', val)
        assert val == 'no'
        for string in strings:
            if i == 0:
                insertLoc = 0
            elif i == 1:
                insertLoc = len(randStr)
            else:
                insertLoc = utils.aRandom.randint(0, len(randStr))
            inString = randStr[:insertLoc] + string + randStr[insertLoc:]
            val = containsNANA(inString)
            utils.tprint(inString, ':', val)
            assert val == 'yes'
Example #14
0
def check(host):
    s = session()
    # reg
    result = s.post(f"http://na1.{host}/",
                    data={
                        "username": utils.randomString(),
                        "password": "******"
                    }).content
    if b"Welcome to our super-duper safe note app!" not in result:
        return 0, "Failed to login"

    # add note
    result = s.post(f"http://na1.{host}/add_note", data={
        "content": "123"
    }).content
    if b"Note ID: " not in result:
        return 0, "Wrong result of add note"

    # idor
    result = s.get(f"http://na1.{host}/note/1").content
    if b'we{7b9f9649-9226-4027-92cc-53d192efa414@H0w-1-Cee-CLasSmaTe8-sc0Res}' not in result:
        return 0, "Failed to get flag"
    return 1, ""
Example #15
0
 def post(self):
     user = get_user_by_username(self.get_body_argument('username'))
     if user is None:
         log_user(-1, 'reset password wrong username post')
         self.render(
             "reset_password.html",
             alert=
             "username incorrect. If you do not know your username anymore, pease write us an email ([email protected])"
         )
         return
     else:
         log_user(user['id'], 'reset password correct post')
         user = update_user(user['id'], reset_key=randomString(10))
         resetLink = f"https://electric.vote/new_password/{user['username']}/{user['reset_key']}"
         send_email(
             user, "new password",
             f"Dear {user['name']},\nyou can set a new password using the following link: {resetLink}.\nIf you didn't request a password reset, this email can be savely ignored.\nKind regards,\nNils Wandel",
             f"<html><body>Dear {user['name']},<br><br>you can set a new password <a href='{resetLink}'>here</a>.<br>If you didn't request a password reset, this email can be savely ignored.<br><br>Kind regards,<br>Nils Wandel</body></html>"
         )
         self.render(
             "login.html",
             alert=
             "We are sending you an email to reset your password. This may take a few minutes. Be sure to check your junk inbox as well. If you are still facing problems: please write us an email ([email protected])"
         )
Example #16
0
def hello_http(requests):

    print("function start")

    try:

        # # save data to firebase barrier
        # database.write_to_barrier()

        file_car_path = "/tmp/car.jpg"

        # write the image to an temporary folder
        utils.write_tmp(requests.data, file_car_path)

        fileSavePath = utils.randomString()

        fileSavePath = "images/-MB9f1lIglsLw2hpA4a9/"+fileSavePath+"jpg"

        print(fileSavePath)

        # save image to bucket
        car_image = database.saveImageToBucket(
            fileLocationPath=file_car_path, fileSavePath=fileSavePath)

        # save data to firebase barrier
        database.write_to_barrier(
            car_image=car_image)

        # return a binary image filtered
        car_image_binary = localization.ImageToBinary(file_car_path)

        # return the located plate
        licensePlateObject = localization.cca2(car_image_binary)

        # save the object plate as jpg image
        file_plate_path = "/tmp/plate.jpg"

        utils.object_to_image(licensePlateObject, file_plate_path)

        fileSavePath = ""

        fileSavePath = "images/-MB9f1lIglsLw2hpA4a9/"+fileSavePath+"jpg"

        # save image to bucket
        car_plate = database.saveImageToBucket(
            fileLocationPath=file_plate_path, fileSavePath=fileSavePath)

        # save data to firebase barrier
        database.write_to_barrier(
            car_image=car_image, car_plate=car_plate)

        # read plate image
        plate_image_binary = utils.read_tmp(file_plate_path)

        # call vision api
        result = predict.predict_text(plate_image_binary)

        # save data to firebase barrier
        database.write_to_barrier(
            car_image=car_image, car_plate=car_plate, car_number=result)

        # check if license plate exist in reservations
        response = database.read_reservation(result)

        print(response)

        return response

    except:

        return 'Not Found', 404
 def __init__( self, name, result, errorString ):
     self.name = utils.randomString( 3 ) + '_' + name 
     self.result = result
     self.errorString = errorString
Example #18
0
import utils
import random
import MT19937RNG
import struct

KEY = random.randint(0, 2**16)
PREFIX = utils.randomString(random.randint(10, 100))


def encrypt(plain, key):
    prng = MT19937RNG.MT19937RNG()
    prng.seed_mt(KEY)
    keystream = b"".join(
        struct.pack('>I', prng.extract_number())
        for _ in range(len(plain) // 4 + 1))
    cipher = utils.xor(plain, keystream)
    return cipher


def oracle(plain):
    return encrypt(PREFIX + plain, KEY)


print("ORIGINAL SEED : %d" % KEY)

cipher = oracle(b"A" * 7)  # 7 is enought to have an aligned block (% 4 == 0)

# compute last block aligned with a number from MT19937RNG ( % 4 == 0)
endBlock = len(cipher) - (len(cipher) % 4)
begBlock = endBlock - 4
idblock = begBlock // 4
Example #19
0
import utils
from random import randint
from collections import defaultdict

BLOCKSIZE = 16
KEY = utils.randomString(BLOCKSIZE)
NONCE = randint(0, 0xFFFFFFFFFFFFFFFF)

if __name__ == "__main__":
    with open("19.txt", "r") as file:
        lines = file.readlines()

    plains = [utils.b64Decode(line[:-1]) for line in lines]

    ciphers = [utils.ARS_CTR_encrypt(KEY, NONCE, plain) for plain in plains]

    keystream = b""
    for idx in range(0, max([len(c) for c in ciphers])):
        candidateScore = defaultdict(int)
        for candidate in range(256):
            for c in ciphers:
                if len(c) > idx:
                    keystreamChar = c[idx] ^ candidate
                    if keystreamChar in utils.ENGLISH_CHAR_FREQ:
                        candidateScore[candidate] += utils.ENGLISH_CHAR_FREQ[
                            keystreamChar]
        keystream += bytes([max(candidateScore, key=candidateScore.get)])

    for c in ciphers:
        print(utils.xor(c, keystream))
Example #20
0
def check(host):
    s = session()
    # reg
    un = utils.randomString()
    result = s.post(f"http://na3.{host}/api/", data={
        "action": "register",
        "username": un,
        "password": "******"
    }).json()
    if result["result"] is None or len(result["result"]) < 10:
        return 0, "Failed to login / Not in safe mode"
    user_token = result["result"]

    # add note
    result = s.post(f"http://na3.{host}/api/", data={
        "action": "add_note",
        "user": user_token,
        "content": "xxxx"
    }).content

    result = s.post(f"http://na3.{host}/api/", data={
        "action": "user_notes",
        "user": user_token,
    }).json()

    if result["success"] and len(result["result"]) >= 1 and result["result"][0]["content"] == "xxxx":
        pass
    else:
        return 0, "Failed to create note"

    # exploit
    out = subprocess.Popen(["php", "na3.php", un],
                           stdout=subprocess.PIPE,
                           stderr=subprocess.STDOUT)
    stdout, stderr = out.communicate()
    print(stdout)
    result = s.post(f"http://na3.{host}/api/", data={
        "action": "user_notes",
        "user": stdout,
    }).content

    result = s.post(f"http://na3.{host}/api/", data={
        "action": "user_notes",
        "user": user_token,
    }).json()
    if result["success"] and len(result["result"]) >= 2 and \
            result["result"][1]["content"] == "<img src='x' onerror='alert(1)'>":
        pass
    else:
        return 0, "Failed to exploit"
    token = result["result"][1]["token"]
    result = s.post(f"http://na3.{host}/api/", data={
        "action": "get_note",
        "user": user_token,
        "token": token
    }).json()
    if result["success"] and result["result"]["content"] == "<img src='x' onerror='alert(1)'>":
        pass
    else:
        return 0, "Failed to get note"

    result = s.post(f"http://na3.{host}/api/", data={
        "action": "get_note",
        "user": "******",
        "token": token
    }).json()
    if result["success"] and result["result"]["content"] == "<img src='x' onerror='alert(1)'>":
        pass
    else:
        return 0, "Failed to get note for anonymous"

    # add note
    # print(s.cookies.get("token"))
    # result = s.post(f"http://na2.{host}/add_note", data={
    #     "content": "<script>alert(1)</script>",
    #     "xsrf": s.cookies.get("token")
    # }).content
    # print(result)
    # if b"Note ID: " not in result:
    #     return 0, "Wrong result of add note"
    #
    # # test xss
    # note_id = match_ids.findall(str(result))[0]
    # result = s.get(f"http://na2.{host}/note/{note_id}").content
    # print(note_id)
    # if b"<script>alert(1)</script>" not in result:
    #     return 0, "Cannot trigger XSS"
    #
    # # test logout
    # s.post(f"http://na2.{host}/logout")
    #
    # if "token" in s.cookies:
    #     return 0, "Logout failed"
    #
    # # test admin
    # result = s.post(f"http://na2.{host}/", data={
    #     "username": "******",
    #     "password": "******"
    # }).content
    #
    # # admin flag
    # result = s.get(f"http://na2.{host}/note/1").content
    # if b'we{f93486a2-4f82-42b6-8dc8-04cd765501f3@1nsp1reD-bY-cHa1I-1N-BbC7F}' not in result:
    #     return 0, "Failed to get flag"
    return 1, ""
 def reportResult( self, result ):
     self._buildStamp = '{0}-Nightly'.format( datetime.datetime.now().strftime( '%Y%m%d-%H%M' ), utils.randomString( 4 ) )
     try:
         #generate XML
         self.genXml( self.genTestXml, result )
         #generate Tests.xml
         #submitFile('Tests.xml')
     except:
         raise
Example #22
0
import utils
import base64
import random

KEY = utils.randomString(16)
NONCE = random.randint(0, 2**128)

with open("25.txt", "r") as file:
    content = base64.b64decode("".join([line.strip() for line in file.readlines()]))

plain = utils.AES_ECB_decrypt(b"YELLOW SUBMARINE", content)
cipher = utils.AES_CTR_encrypt(KEY, NONCE, plain)

# ----------

def edit(cipher, offset, newplain):
    plain = utils.AES_CTR_decrypt(KEY, NONCE, cipher)
    plain = plain[:offset] + newplain + plain[offset+len(newplain):]
    return utils.AES_CTR_encrypt(KEY, NONCE, plain)

cipher2 = edit(cipher, 0, b"A" * len(cipher))
keystream = utils.xor(b"A" * len(cipher), cipher2)
plain = utils.xor(cipher, keystream)

print(plain)
Example #23
0
def addString(value):
    resul = randomString(value)
    return resul
    def run_test( self, installerPath, vm, testcase, res ):  
        steps = testcase.steps()
        if len( steps ) == 0:
            raise ControlException( "No steps found for testcase {0}".format( testcase.name() ) )

        revertStatus, _ = vm.revertToSnapshot()
        if revertStatus != 0:
            raise VMException( "Failed to revert to snapshot '{0}'".format( vm.snapshot() ) )

        
        time.sleep( 5 ) # Trying to avoid a possible race between restore and start
        
        vm.start()

        try:
            try:
                vm.checkPythonInstalled()        
                wrapperpath = vm.copyToTemp( utils.execution_path( 'guest.py' ) )
                
                for stepNum in range( len( steps ) ):
                    needSnapshot = False
                    step = steps[stepNum]
                    if stepNum == 0:               
                        executableguestpath = vm.copyToTemp( installerPath )
                    else:
                        executableguestpath = testcase.maintenanceToolLocation()
    
                    outputFileName = 'output{0}.log'.format( stepNum )
                    outputpath = vm.mkTempPath( outputFileName  )
                    scriptguestpath = vm.copyToTemp( step.installscript() )
                    timeout = step.timeout()
                    checkerguestpath = vm.copyToTemp( step.checkerTestDir(), "checkerTestDir{0}".format( stepNum ) ) if len( string.strip( step.checkerTestDir() ) ) > 0 else None
                    vm.command( 'Execute installer', "runProgramInGuest", "'{0}' '{1}' '{2}' '{3}' '{4}' --script '{5}'".format( vm.python(), wrapperpath, outputpath, timeout, executableguestpath, scriptguestpath ) )            
                    vm.copyFromTemp( outputFileName, outputFileName )
                    r = ConfigParser.SafeConfigParser()
                    r.read( outputFileName )
                    try:
                        s = r.get( 'Result', 'ExitCode' )
                        exitCode = int( s )
                    except ValueError:
                        res.addInternalError( "Could not parse integer exit code from '{0}'".format( r.get( 'Result', 'ExitCode' ) ) )                
                        exitCode = -1
                    try:
                        s = r.get( 'Result', 'ExecutionTime' )
                        executionTime = float( s )
                    except ValueError:
                        res.addInternalError( "Could not parse float execution time from '{0}'".format( r.get( 'Result', 'ExecutionTime' ) ) )                
                        executionTime = 0.0 
        
                    exitStatus = result.exitStatusFromString( r.get( 'Result', 'ExitStatus' ) )
                    instR = result.ExecutionResult( exitCode, exitStatus, executionTime )
                    
                    if instR.hasError():
                        needSnapshot = True
                    
                    checkerResults = []
                    if checkerguestpath and not instR.hasError():
                        if ( platform.system() == "Darwin" ):
                            # Have to sleep to work around VMware Fusion bug
                            time.sleep( 30 )
                        run_py = vm.copyToTemp( self._checkerDir ) + vm.pathSep() + "run.py"
                        if ( platform.system() == "Darwin" ):
                            # Have to sleep to work around VMware Fusion bug
                            time.sleep( 30 )
                        checkeroutputFileName = 'checker-output{0}.xml'.format( stepNum )
                        checkeroutput = vm.mkTempPath( checkeroutputFileName )
                        vm.command( 'Execute checker tests', "runProgramInGuest", "'{0}' '{1}' '{2}' -o '{3}' -p '{4}'".format( vm.python(), run_py, checkerguestpath, checkeroutput, testcase.targetDirectory() ) )            
                        vm.copyFromTemp( checkeroutputFileName, checkeroutputFileName )
                        self.convertCheckerResults( localcheckeroutput, checkerResults )
                        if res.hasCheckerErrors():
                            needSnapshot = True
                    if self._createErrorSnapshots and needSnapshot:
                        snapshot = 'error-{0}-{1}'.format( datetime.datetime.now().strftime( '%Y%m%d_%H%M%S' ), utils.randomString( 4 ) )
                        status, _ = vm.createSnapshot( snapshot )
                        if status == 0:
                            res.setErrorSnapshot( snapshot )
                        else:
                            res.addInternalError( 'Could not create error snapshot "{0}"'.format( snapshot ) )
                    res.addStepResult( result.StepResult( instR, checkerResults ) )
                #TODO handle timeouts?
            finally:
                vm.kill()
        except e:
            print( e )
            res.addInternalError( str( e ) )
Example #25
0
    def run_test(self, installerPath, vm, testcase, res):
        steps = testcase.steps()
        if len(steps) == 0:
            raise ControlException("No steps found for testcase {0}".format(
                testcase.name()))

        revertStatus, _ = vm.revertToSnapshot()
        if revertStatus != 0:
            raise VMException("Failed to revert to snapshot '{0}'".format(
                vm.snapshot()))

        time.sleep(
            5)  # Trying to avoid a possible race between restore and start

        vm.start()

        try:
            try:
                vm.checkPythonInstalled()
                wrapperpath = vm.copyToTemp(utils.execution_path('guest.py'))

                for stepNum in range(len(steps)):
                    needSnapshot = False
                    step = steps[stepNum]
                    if stepNum == 0:
                        executableguestpath = vm.copyToTemp(installerPath)
                    else:
                        executableguestpath = testcase.maintenanceToolLocation(
                        )

                    outputFileName = 'output{0}.log'.format(stepNum)
                    outputpath = vm.mkTempPath(outputFileName)
                    scriptguestpath = vm.copyToTemp(step.installscript())
                    timeout = step.timeout()
                    checkerguestpath = vm.copyToTemp(
                        step.checkerTestDir(),
                        "checkerTestDir{0}".format(stepNum)) if len(
                            string.strip(step.checkerTestDir())) > 0 else None
                    vm.command(
                        'Execute installer', "runProgramInGuest",
                        "'{0}' '{1}' '{2}' '{3}' '{4}' --script '{5}'".format(
                            vm.python(), wrapperpath, outputpath, timeout,
                            executableguestpath, scriptguestpath))
                    vm.copyFromTemp(outputFileName, outputFileName)
                    r = ConfigParser.SafeConfigParser()
                    r.read(outputFileName)
                    try:
                        s = r.get('Result', 'ExitCode')
                        exitCode = int(s)
                    except ValueError:
                        res.addInternalError(
                            "Could not parse integer exit code from '{0}'".
                            format(r.get('Result', 'ExitCode')))
                        exitCode = -1
                    try:
                        s = r.get('Result', 'ExecutionTime')
                        executionTime = float(s)
                    except ValueError:
                        res.addInternalError(
                            "Could not parse float execution time from '{0}'".
                            format(r.get('Result', 'ExecutionTime')))
                        executionTime = 0.0

                    exitStatus = result.exitStatusFromString(
                        r.get('Result', 'ExitStatus'))
                    instR = result.ExecutionResult(exitCode, exitStatus,
                                                   executionTime)

                    if instR.hasError():
                        needSnapshot = True

                    checkerResults = []
                    if checkerguestpath and not instR.hasError():
                        if (platform.system() == "Darwin"):
                            # Have to sleep to work around VMware Fusion bug
                            time.sleep(30)
                        run_py = vm.copyToTemp(
                            self._checkerDir) + vm.pathSep() + "run.py"
                        if (platform.system() == "Darwin"):
                            # Have to sleep to work around VMware Fusion bug
                            time.sleep(30)
                        checkeroutputFileName = 'checker-output{0}.xml'.format(
                            stepNum)
                        checkeroutput = vm.mkTempPath(checkeroutputFileName)
                        vm.command(
                            'Execute checker tests', "runProgramInGuest",
                            "'{0}' '{1}' '{2}' -o '{3}' -p '{4}'".format(
                                vm.python(), run_py, checkerguestpath,
                                checkeroutput, testcase.targetDirectory()))
                        vm.copyFromTemp(checkeroutputFileName,
                                        checkeroutputFileName)
                        self.convertCheckerResults(localcheckeroutput,
                                                   checkerResults)
                        if res.hasCheckerErrors():
                            needSnapshot = True
                    if self._createErrorSnapshots and needSnapshot:
                        snapshot = 'error-{0}-{1}'.format(
                            datetime.datetime.now().strftime('%Y%m%d_%H%M%S'),
                            utils.randomString(4))
                        status, _ = vm.createSnapshot(snapshot)
                        if status == 0:
                            res.setErrorSnapshot(snapshot)
                        else:
                            res.addInternalError(
                                'Could not create error snapshot "{0}"'.format(
                                    snapshot))
                    res.addStepResult(result.StepResult(instR, checkerResults))
                #TODO handle timeouts?
            finally:
                vm.kill()
        except e:
            print(e)
            res.addInternalError(str(e))
Example #26
0
import utils
from sha1 import SHA1
import random
import binascii
import struct

# server
KEY = utils.randomString(random.randint(10, 10))


def secureMessageWithMAC(message):
    sha1 = SHA1()
    hash = binascii.hexlify(sha1.hash(KEY + message))
    return (message, hash)


def isMessageValidMAC(message, signature):
    sha1 = SHA1()
    print(sha1.hash(KEY + b"A" * 100))
    hash = binascii.hexlify(sha1.hash(KEY + message))
    print(hash)
    print(signature)
    return hash == signature


message, signature = secureMessageWithMAC(
    b"comment1=cooking%20MCs;userdata=foo;comment2=%20like%20a%20pound%20of%20bacon"
)

# client
MESSAGE_EXTENTION = b";admin=true"
Example #27
0
     transaction.RecipientPublickey = TESTPKEY.serialize().hex()
     transaction.NodeListSeed = 28  # Node list seed
     transaction.commitment = False  # Commitment Flag
     for i in range(5):
         timestamps.append(-1)
     tx_bytes = transaction.SerializeToString()
     #sock.sendall(tx_bytes)
     print(tx_bytes)
     print(len(tx_bytes))
     r = requests.post(url=API_ENDPOINT, data=tx_bytes)
     print(r.text)
     #serversockin.sendto(tx_bytes, (serverip, 2020))
 if a == 2:
     N = int(input("Enter number of transactions to create : "))
     for i in range(N):
         payload = utils.randomString()
         transaction = serialization_pb2.Transaction()
         transaction.payload = payload.encode('utf-8')  # Payload set
         transaction.UserPublicKey = PUBLIC_KEY.serialize().hex(
         )  # User PKey set
         signature = PRIVATE_KEY.sign(payload.encode('utf-8'))
         transaction.MultiSignature = signature.serialize().hex(
         )  # Signature Set
         transaction.txHash = txhash_generator(signature.serialize(),
                                               payload.encode('utf-8'))
         timestamps = transaction.timestamp  # Fixing the timestamps
         transaction.RecipientPublickey = TESTPKEY.serialize().hex()
         transaction.NodeListSeed = 28  # Node list seed
         transaction.commitment = False  # Commitment Flag
         for i in range(5):
             timestamps.append(-1)
Example #28
0
 def __init__(self, name, result, errorString):
     self.name = utils.randomString(3) + '_' + name
     self.result = result
     self.errorString = errorString