Exemplo n.º 1
0
def validateReceipt():

    receipts = []
    names = []

    cert = getCertificate()
    clientId, _ = getUserInfo(cert)

    if not os.path.exists("receipts/" + clientId):
        print("No receipts found!")
        return

    for entry in scandir("receipts/" + clientId):
        names.append(entry.name)
        with open("receipts/" + clientId + "/" + entry.name, "r") as f:
            receipts.append(json.loads(f.read()))

    for i, name in enumerate(names):
        print("## {} ##".format(i+1))
        print("Receipt name:", name)
        print("-----------------\n")

    while True:
        opt = input("$ ")

        if not match("^[0-9]+$", opt):
            print("ERROR: Insert a valid number!")
            continue

        opt = int(opt)
    
        if opt < 1 or opt > len(names):
            print("Error: Insert a number between 1 and " + str(len(names)))
            continue

        opt -= 1

        break

    receipt = receipts[opt]
    auctionId = receipt["auctionId"]
    receipt = receipt["receipt"]

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    sock.connect(constants.REPOSITORY_ADDR)
    cert = getCertificate()
    symmetricEncryption, sessionId = clientHandShake(sock, privateKey, cert, ciphers, modes, paddings)

    sendEncryptedMessage(sock, {"action":ActionTypes.VALIDATE_RECEIPT}, symmetricEncryption, sessionId, 3)
    sendEncryptedMessage(sock, {"auctionId":auctionId}, symmetricEncryption, sessionId, 4)

    msgRecv = readMessage(sock, [], symmetricEncryption, sessionId, 5)

    sock.close()

    validateReceiptLoaded(receipt, msgRecv["dataToValidate"], auctionId)
Exemplo n.º 2
0
def closeAuction(sock, clientCert, symmetricEncryption, sessionId):

    # Gets clientID to receive open auctions
    clientID, clientName = getUserInfo(clientCert)

    # Verify if the current client has auction open
    if clientID not in CLIENTS.keys() or len(CLIENTS[clientID]) == 0:
        sendEncryptedMessage(sock, {"openAuctionList": []},
                             symmetricEncryption, sessionId, 4)
        return

    # Gather info of all open auction of the client
    openAuctionList = []
    for auctionId in CLIENTS[clientID]:
        openAuctionList.append(AUCTIONS[auctionId].auctionInfo)

    # Sends open auctions
    sendEncryptedMessage(sock, {'openAuctionList': openAuctionList},
                         symmetricEncryption, sessionId, 4)

    # Gets auctionID to close
    mandatoryFields = []
    mandatoryFields.append(Field("auctionID", int))
    msgRecv = readMessage(sock, mandatoryFields, symmetricEncryption,
                          sessionId, 5)
    auctionID = msgRecv['auctionID']
    auction = AUCTIONS[auctionID]

    # Connect to the repository to close the auction
    sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock2.connect(constants.REPOSITORY_ADDR)
    symmetricEncryption2, sessionId2 = handshake.clientHandShake(
        sock2, privateKey, certificate, POSSIB_CIPHERS, POSSIB_MODES,
        POSSIB_PADDING)

    key = b64encode(auction.key).decode("ascii")

    # Sends the request to Repository
    sendEncryptedMessage(sock2, {'action': ActionTypes.CLOSE_AUCTION},
                         symmetricEncryption2, sessionId2, 3)
    sendEncryptedMessage(sock2, {
        "auctionID": auctionID,
        'key': key
    }, symmetricEncryption2, sessionId2, 4)

    # Receive the winner bid
    msgRecv = readMessage(sock2, [], symmetricEncryption2, sessionId2, 5)

    # Send the winner bid to the creator
    sendEncryptedMessage(sock, {
        'winnerBid': msgRecv["winnerBid"],
        "key": key
    }, symmetricEncryption, sessionId, 6)

    # Remove local info
    AUCTIONS.pop(auctionID)
    CLIENTS[clientID].remove(auctionID)
Exemplo n.º 3
0
def closeAuctionTime(auctionId, creatorId):

    mutex.acquire()

    if auctionId not in OPEN_AUCTIONS.keys():
        mutex.release()
        return

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(constants.MANAGER_ADDR)

    symmetricEncryption, sessionId = handshake.clientHandShake(
        sock, privateKey, certificate, POSSIB_CIPHERS, POSSIB_MODES,
        POSSIB_PADDING)

    sendEncryptedMessage(sock, {"action": ActionTypes.CLOSE_AUCTION_TIME},
                         symmetricEncryption, sessionId, 3)

    auction = OPEN_AUCTIONS[auctionId]
    sendEncryptedMessage(sock, {"auctionId": auctionId}, symmetricEncryption,
                         sessionId, 4)

    mandatoryFields = []
    mandatoryFields.append(BytesField("key"))
    msgRecv = readMessage(sock, mandatoryFields, symmetricEncryption,
                          sessionId, 5)

    _, participatingClients = auction.makePublic(msgRecv["key"])

    creatorId = auction.getAuctionInfo()["creatorId"]
    if creatorId not in CLIENTS:
        CLIENTS[creatorId] = set()
    CLIENTS[creatorId].add(auctionId)

    for clientId in participatingClients:
        if clientId not in CLIENTS:
            CLIENTS[clientId] = set()
        CLIENTS[clientId].add(auctionID)

        if auction.getAuctionInfo()["type"] == "BlindShown":
            del CLIENTS_BIDS_COUNT[clientId][auctionID]

    #Moves auction from openAuctions to closedAuctions
    CLOSED_AUCTIONS[auctionId] = OPEN_AUCTIONS.pop(auctionId)

    mutex.release()
Exemplo n.º 4
0
def listClientBids():

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    clientId = input("Client Id to search: ")

    sock.connect(constants.REPOSITORY_ADDR)
    cert = getCertificate()
    symmetricEncryption, sessionId = clientHandShake(sock, privateKey, cert, ciphers, modes, paddings)

    sendEncryptedMessage(sock, {'action':ActionTypes.LIST_ALL_CLIENT_BIDS}, symmetricEncryption, sessionId, 3)
    sendEncryptedMessage(sock, {'clientId':clientId}, symmetricEncryption, sessionId, 4)

    msgRecv = readMessage(sock, [], symmetricEncryption, sessionId, 5)

    if len(msgRecv["auctionsList"]) == 0:
        print("No bids of this client")
        sock.close()
        return

    for auction in msgRecv["auctionsList"]:
        bids = []
        if type(auction) == list:
            bids = auction
        elif type(auction) == dict:
            key = b64decode(bytes(auction["key"], "ascii"))

            for bid in auction["bidsList"]:
                decryptBid(bid, key)

            bids = auction["bidsList"]
        else:
            assert False

        for bid in bids:
            print("Client Id:",          bid["clientId"])
            print("Client Name:",        bid["clientName"])
            print("Client Certificate:", bid["clientCertificate"])
            print("Amount:",             bid["amount"])
            print("Timestamp:",          bid["timestamp"])
            print("Nonce:",              bid["nonce"])
            print("Auction Id:",         bid["auctionId"])
            print("Auction Type:",       bid["auctionType"])
            print("------------------------\n")

    sock.close()
Exemplo n.º 5
0
def listCloseAuctions():

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    #connect to the repository to get data
    sock.connect(constants.REPOSITORY_ADDR)
    cert = getCertificate()
    symmetricEncryption, sessionId = clientHandShake(sock, privateKey, cert, ciphers, modes, paddings)

    sendEncryptedMessage(sock, {'action':ActionTypes.LIST_ALL_CLOSED_AUCTIONS}, symmetricEncryption, sessionId, 3)

    msgRecv = readMessage(sock, [], symmetricEncryption, sessionId, 4)

    #display data
    closedAuctionList = msgRecv["closedAuctionList"]

    if len(closedAuctionList) == 0:
        print("No closed auctions")
        sock.close()
        return

    for auction in closedAuctionList:
        print("Auction Id:     ",     auction["auctionId"])
        print("Name:           ",     auction["name"])
        print("Description:    ",     auction["description"])
        print("Type:           ",     auction["type"])
        print("Duration:       ",     auction["duration"])
        print("Creation Time:  ",     auction["creationTime"])
        print("Difficulty:     ",     auction["difficulty"])
        print("Base amount:    ",     auction["baseAmount"])
        print("Validation Code\n"   + auction["validationCode"])
        print("Modification Code\n" + auction["modificationCode"])
        print("Creator Id:     ",     auction["creatorId"])
        print("Creator Name:   ",     auction["creatorName"])
        print("--------------------------------------\n")

    sock.close()
Exemplo n.º 6
0
def newBid(sock, clientCert, symmetricEncryption, sessionId):

    mutex.acquire()

    openAuctionList = []
    for auction in OPEN_AUCTIONS.values():
        openAuctionList.append(auction.getAuctionInfo())

    #Sends lists with all open auctions
    sendEncryptedMessage(sock, {"openAuctionList": openAuctionList},
                         symmetricEncryption, sessionId, 4)

    mandatoryFields = []
    mandatoryFields.append(Field("auctionId", int))
    mandatoryFields.append(Field("timestamp", int))
    mandatoryFields.append(Field("amount", float))
    mandatoryFields.append(BytesField("nonce"))
    mandatoryFields.append(BytesField("signature"))
    msg = readMessage(sock, mandatoryFields, symmetricEncryption, sessionId, 5)

    auctionId = msg["auctionId"]

    if auctionId not in OPEN_AUCTIONS.keys():
        sendEncryptedMessage(sock, {"error": "No auction with that id"},
                             symmetricEncryption, sessionId, 6)
        return

    clientId, clientName = getUserInfo(clientCert)
    clientCertBytes = b64encode(clientCert.public_bytes(
        Encoding.PEM)).decode("ascii")

    bid = {
        "timestamp": msg["timestamp"],
        "clientId": clientId,
        "clientName": clientName,
        "clientCertificate": clientCertBytes,
        "amount": msg["amount"],
        "nonce": msg["nonce"],
        "auctionId": auctionId,
        "auctionType": OPEN_AUCTIONS[auctionId].getAuctionInfo()["type"]
    }

    if not PublicKeyClient(clientCert.public_key()).verify(
            calculateHashOverFields(bid),
            b64decode(bytes(msg["signature"], "ascii"))):
        mutex.release()
        sendEncryptedMessage(sock, {"error": "Invalid signature over bid"},
                             symmetricEncryption, sessionId, 6)
        return

    sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock2.connect(constants.MANAGER_ADDR)

    symmetricEncryption2, sessionId2 = handshake.clientHandShake(
        sock2, privateKey, certificate, POSSIB_CIPHERS, POSSIB_MODES,
        POSSIB_PADDING)

    sendEncryptedMessage(sock2, {"action": ActionTypes.VALIDATE_BID},
                         symmetricEncryption2, sessionId2, 3)

    toValidate = {"clientValidation": msg["signature"], "bid": bid}

    auction = OPEN_AUCTIONS[auctionId]
    if auction.getAuctionInfo()["type"] == "BlindShown":
        if clientId not in CLIENTS_BIDS_COUNT.keys():
            CLIENTS_BIDS_COUNT[clientId] = dict()
        if auctionId not in CLIENTS_BIDS_COUNT[clientId].keys():
            CLIENTS_BIDS_COUNT[clientId][auctionId] = 0

        toValidate["countBidsDone"] = CLIENTS_BIDS_COUNT[clientId][auctionId]

    sendEncryptedMessage(sock2, toValidate, symmetricEncryption2, sessionId2,
                         4)

    exceptionHappen = False
    try:
        msg = readMessage(sock2, [], symmetricEncryption2, sessionId2, 5)
    except ErrorMessage as e:
        exceptionHappen = True
        sendEncryptedMessage(sock, {"error": e.args[0]}, symmetricEncryption,
                             sessionId, 6)

    if exceptionHappen:
        mutex.release()
        return

    sock2.close()

    blockNum, prevHash = auction.lastBlockInfo()
    blockNum += 1

    cryptopuzzleChallange = {
        "difficulty": auction.getAuctionInfo()["difficulty"],
        "toMine": {
            "blockNumber": blockNum,
            "previousHash": prevHash,
            "data": msg
        }
    }

    sendEncryptedMessage(sock, cryptopuzzleChallange, symmetricEncryption,
                         sessionId, 6)

    mandatoryFields = []
    mandatoryFields.append(BytesField("hash"))
    mandatoryFields.append(BytesField("nonce"))
    msg = readMessage(sock, mandatoryFields, symmetricEncryption, sessionId, 7,
                      60)

    blockInfo = cryptopuzzleChallange["toMine"]
    blockInfo["nonce"] = msg["nonce"]

    valid, cause = verifyCryptopuzzle(msg["hash"], blockInfo,
                                      auction.getAuctionInfo()["difficulty"])

    if not valid:
        mutex.release()
        sendEncryptedMessage(sock, {"error": cause}, symmetricEncryption,
                             sessionId, 8)
        return

    if auction.getAuctionInfo()["type"] == "BlindShown":
        if clientId not in CLIENTS.keys():
            CLIENTS[clientId] = set()
        CLIENTS[clientId].add(auctionId)

    auction.newBid(blockInfo["data"], blockInfo["nonce"], msg["hash"])

    receipt = auction.getAllData()
    signature = privateKey.sign(calculateHashOverFields({"": receipt}))
    signature = b64encode(signature).decode("ascii")
    cert = b64encode(certificate.public_bytes(Encoding.PEM)).decode("ascii")

    sendEncryptedMessage(sock, {
        "receipt": receipt,
        "signature": signature,
        "certificate": cert
    }, symmetricEncryption, sessionId, 8)

    mutex.release()
Exemplo n.º 7
0
def validateAuction():

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    #connect to the repository to get data
    sock.connect(constants.REPOSITORY_ADDR)
    cert = getCertificate()
    symmetricEncryption, sessionId = clientHandShake(sock, privateKey, cert, ciphers, modes, paddings)

    sendEncryptedMessage(sock, {'action':ActionTypes.VALIDATE_AUCTION}, symmetricEncryption, sessionId, 3)

    msgRecv = readMessage(sock, [], symmetricEncryption, sessionId, 4)

    #display data
    auctionList = msgRecv["auctionList"]

    if len(auctionList) == 0:
        print("No auctions")
        sock.close()
        return

    for i, auction in enumerate(auctionList):
        print("## {} ##".format(i+1))
        print("Auction Id:     ",     auction["auctionId"])
        print("Name:           ",     auction["name"])
        print("Description:    ",     auction["description"])
        print("Type:           ",     auction["type"])
        print("Duration:       ",     auction["duration"])
        print("Creation Time:  ",     auction["creationTime"])
        print("Difficulty:     ",     auction["difficulty"])
        print("Base amount:    ",     auction["baseAmount"])
        print("Validation Code\n"   + auction["validationCode"])
        print("Modification Code\n" + auction["modificationCode"])
        print("Creator Id:     ",     auction["creatorId"])
        print("Creator Name:   ",     auction["creatorName"])
        print("--------------------------------------\n")

    while True:
        opt = input("$ ")

        if not match("^[0-9]+$", opt):
            print("ERROR: Insert a valid number!")
            continue

        opt = int(opt)
    
        if opt < 1 or opt > len(auctionList):
            print("Error: Insert a number between 1 and " + str(len(auctionList)))
            continue

        opt -= 1

        break

    sendEncryptedMessage(sock, {"auctionId":auctionList[opt]["auctionId"]}, symmetricEncryption, sessionId, 5)

    msgRecv = readMessage(sock, [], symmetricEncryption, sessionId, 6)

    sock.close()

    validateAuctionContent(msgRecv["allData"])
Exemplo n.º 8
0
def checkOutcome():

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    sock.connect(constants.REPOSITORY_ADDR)
    cert = getCertificate()
    symmetricEncryption, sessionId = clientHandShake(sock, privateKey, cert, ciphers, modes, paddings)

    sendEncryptedMessage(sock, {'action':ActionTypes.CHECK_OUTCOME_OF_AUCTION}, symmetricEncryption, sessionId, 3)

    msgRecv = readMessage(sock, [], symmetricEncryption, sessionId, 4)

    closedAuctionList = msgRecv["participatedAuctionList"]

    if len(closedAuctionList) == 0:
        print("No closed auctions participated")
        sock.close()
        return

    for i, auction in enumerate(closedAuctionList):
        print("## {} ##".format(i+1))
        print("Auction Id:     ",     auction["auctionId"])
        print("Name:           ",     auction["name"])
        print("Description:    ",     auction["description"])
        print("Type:           ",     auction["type"])
        print("Duration:       ",     auction["duration"])
        print("Creation Time:  ",     auction["creationTime"])
        print("Difficulty:     ",     auction["difficulty"])
        print("Base amount:    ",     auction["baseAmount"])
        print("Validation Code\n"   + auction["validationCode"])
        print("Modification Code\n" + auction["modificationCode"])
        print("Creator Id:     ",     auction["creatorId"])
        print("Creator Name:   ",     auction["creatorName"])
        print("--------------------------------------\n")

    print("Select an auction to check who won")
    while True:
        opt = input("$ ")

        if not match("^[0-9]+$", opt):
            print("ERROR: Insert a valid number!")
            continue

        opt = int(opt)
    
        if opt < 1 or opt > len(closedAuctionList):
            print("Error: Insert a number between 1 and " + str(len(closedAuctionList)))
            continue

        opt -= 1

        break

    sendEncryptedMessage(sock, {'auctionId':closedAuctionList[opt]["auctionId"]}, symmetricEncryption, sessionId, 5)

    msgRecv = readMessage(sock, [], symmetricEncryption, sessionId, 6)

    if msgRecv["winnerBid"] == {}:
        print("No winner!")
        return

    decryptBid(
            msgRecv["winnerBid"],
            b64decode(bytes(msgRecv["key"], "ascii"))
            )

    print("Winner Bid")
    print("Client Id:",          msgRecv["winnerBid"]["clientId"])
    print("Client Name:",        msgRecv["winnerBid"]["clientName"])
    print("Client Certificate:", msgRecv["winnerBid"]["clientCertificate"])
    print("Amount:",             msgRecv["winnerBid"]["amount"])
    print("Timestamp:",          msgRecv["winnerBid"]["timestamp"])
    print("Nonce:",              msgRecv["winnerBid"]["nonce"])
    print("Auction Id:",         msgRecv["winnerBid"]["auctionId"])
    print("Auction Type:",       msgRecv["winnerBid"]["auctionType"])

    sock.close()
Exemplo n.º 9
0
def listAuctionBids():

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    sock.connect(constants.REPOSITORY_ADDR)
    cert = getCertificate()
    symmetricEncryption, sessionId = clientHandShake(sock, privateKey, cert, ciphers, modes, paddings)

    sendEncryptedMessage(sock, {'action':ActionTypes.LIST_ALL_AUCTION_BIDS}, symmetricEncryption, sessionId, 3)

    msgRecv = readMessage(sock, [], symmetricEncryption, sessionId, 4)

    openAuctionList = msgRecv["auctionList"]

    if len(openAuctionList) == 0:
        print("No auctions")
        sock.close()
        return

    for i, auction in enumerate(openAuctionList):
        print("## {} ##".format(i+1))
        print("Auction Id:     ",     auction["auctionId"])
        print("Name:           ",     auction["name"])
        print("Description:    ",     auction["description"])
        print("Type:           ",     auction["type"])
        print("Duration:       ",     auction["duration"])
        print("Creation Time:  ",     auction["creationTime"])
        print("Difficulty:     ",     auction["difficulty"])
        print("Base amount:    ",     auction["baseAmount"])
        print("Validation Code\n"   + auction["validationCode"])
        print("Modification Code\n" + auction["modificationCode"])
        print("Creator Id:     ",     auction["creatorId"])
        print("Creator Name:   ",     auction["creatorName"])
        print("--------------------------------------\n")

    while True:
        opt = input("$ ")

        if not match("^[0-9]+$", opt):
            print("ERROR: Insert a valid number!")
            continue

        opt = int(opt)
    
        if opt < 1 or opt > len(openAuctionList):
            print("Error: Insert a number between 1 and " + str(len(openAuctionList)))
            continue

        opt -= 1

        break

    sendEncryptedMessage(sock, {'auctionID': openAuctionList[opt]["auctionId"]}, symmetricEncryption, sessionId, 5)

    msgRecv = readMessage(sock, [], symmetricEncryption, sessionId, 6)

    bidsList = msgRecv['bidsList']

    if len(bidsList) == 0:
        print("No bids")
        sock.close()
        return

    auctionType = openAuctionList[opt]["type"]

    if "key" in msgRecv.keys():
        key = b64decode(bytes(msgRecv["key"], "ascii"))
        for bid in bidsList:
            decryptBid(bid, key)

    for bid in bidsList:
        print("Client Id:",          bid["clientId"])
        print("Client Name:",        bid["clientName"])
        print("Client Certificate:", bid["clientCertificate"])
        print("Amount:",             bid["amount"])
        print("Timestamp:",          bid["timestamp"])
        print("Nonce:",              bid["nonce"])
        print("Auction Id:",         bid["auctionId"])
        print("Auction Type:",       bid["auctionType"])
        print("------------------------\n")

    sock.close()
Exemplo n.º 10
0
def createAuction():

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # Get type of auction
    while True:
        print("########################################\n" + \
              "#                                      #\n" + \
              "#  1 - English Auction                 #\n" + \
              "#  2 - Blind Auction (Entities Shown)  #\n" + \
              "#  3 - Blind Auction (Entities Hidden) #\n" + \
              "#  0 - Go Back                         #\n" + \
              "#                                      #\n" + \
              "########################################")

        choice = input("$ ")

        if not match("^[0-9]+$", choice):
            print("ERROR: Insert a valid number!")
            continue

        choice = int(choice)

        if choice == 1:
            type = "English"
            break
        elif choice == 2:
            type = "BlindShown"
            break
        elif choice == 3:
            type = "BlindHidden"
            break
        elif choice == 0:
            return
        else:
            print("ERROR: No option {}! Choose a number from 0 to 2.".format(choice))
            continue

    # Get auction Name
    name = input("Auction name(Max 40): ")[:40]

    # Get auction duration (days:hours:minutes)
    while True:
        duration = input("Duration (days:hours:minutes): ")
        if not match("^[0-9]+:[0-9]+:[0-9]+$", duration):
            print("ERROR: Invalid input!")
            continue
        
        days, hours, minutes = duration.split(":")

        days = int(days)
        hours = int(hours)
        minutes = int(minutes)

        #convert all to minutes
        duration = (days * 24 * 60) + \
                   (hours * 60) + \
                   minutes

        if duration == 0:
            print("ERROR: Duration can't be zero")
            continue

        break

    # Get auction description
    description = input("Description (Max:200): ")[:200]

    print("Base amount")
    while True:
        baseAmount = input("$ ")

        if not match("^[0-9]+(\.[0-9][0-9]?)?$", baseAmount):
            print("ERROR: Insert a valid amount")
            continue

        baseAmount = float(baseAmount)

        if baseAmount < 0:
            print("ERROR: Insert a number greater than 0")
            continue

        break

    print("Difficulty")
    print("Value in the interval [0, 256[")
    print("Higher the number, higher the difficulty")
    while True:
        difficulty = input("$ ")

        if not match("^[0-9]+$", difficulty):
            print("ERROR: Insert a valid number!")
            continue

        difficulty = int(difficulty)

        if not (0 <= difficulty < 256):
            print("ERROR: Insert a number in the interval [0, 256[!")
            continue

        break

    #Get dinamic code of auction
    print("Validation Code")
    print("DISCLAIMER: We only do a syntax check on your code")
    print("so if there's any semantic error the auction will")
    print("reject all bids")

    print("You have acess to the variable \"data\" that is a dictionary")
    print("that has the fields:")
    if type == "English":
        print("amount")
        print("lastAmount : last amount made to this auction")
    elif type == "BlindShown":
        print("clientId")
        print("clientName")
        print("timestamp")
        print("clientCertificate")
        print("numberOfBids : Number of bids made by the creator of the bid to this auction")
    elif type == "Hidden":
        print("Nothin both identities and amount are hidden")
    print("The goal is to change the variable validBid to True or False")
    while True:
        filename = input("Filename: ")

        if filename == "":
            validationCode = ""
            break

        if not os.path.exists("code/" + filename):
            print("No such file")
            continue

        with open("code/" + filename) as f:
            validationCode = f.read()
        break

    print("---------")
    print("Modification code")
    print("DISCLAIMER: We only do a syntax check on your code")
    print("so if there's any semantic error the auction will")
    print("reject all bids")

    print("You have acess to the variable \"data\" that is a dictionary")
    print("that has the fields:")
    if type == "English":
        print("amount")
        print("lastAmount : last amount made to this auction")
    elif type == "BlindShown":
        print("clientId")
        print("clientName")
        print("timestamp")
        print("clientCertificate")
        print("numberOfBids : Number of bids made by the creator of the bid to this auction")
    elif type == "Hidden":
        print("Nothing both identities and amount are hidden")
    print("The goal is to change the variable payload with something to add to the block")
    while True:
        filename = input("Filename: ")

        if filename == "":
            modificationCode = ""
            break

        if not os.path.exists("code/" + filename):
            print("No such file")
            continue

        with open("code/" + filename) as f:
            modificationCode = f.read()
        break

    msg = {'name': name, 
           'duration': duration, 
           'description' : description,
           'type' : type,
           "difficulty":difficulty,
           "baseAmount":baseAmount,
           'validationCode':validationCode,
           "modificationCode":modificationCode
           }

    #connect to the manager to send the auction info
    sock.connect(constants.MANAGER_ADDR)
    cert = getCertificate()
    symmetricEncryption, sessionId = clientHandShake(sock, privateKey, cert, ciphers, modes, paddings)
    
    sendEncryptedMessage(sock, {"action":ActionTypes.CREATE_AUCTION}, symmetricEncryption, sessionId, 3)

    sendEncryptedMessage(sock, msg, symmetricEncryption, sessionId, 4)
    
    #get info of created auction
    msg = readMessage(sock, [], symmetricEncryption, sessionId, 5)
    
    print("Auction created successfully with id", msg["auctionId"], "on", msg["creationTime"], "(timestamp)")

    sock.close()
Exemplo n.º 11
0
def closeAuction():

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    sock.connect(constants.MANAGER_ADDR)
    cert = getCertificate()
    symmetricEncryption, sessionId = clientHandShake(sock, privateKey, cert, ciphers, modes, paddings)

    sendEncryptedMessage(sock, {'action':ActionTypes.CLOSE_AUCTION}, symmetricEncryption, sessionId, 3)

    #get all open auctions that this client created
    msgRecv = readMessage(sock, [], symmetricEncryption, sessionId, 4)

    openAuctionList = msgRecv["openAuctionList"]

    if len(openAuctionList) == 0:
        print("No aucton to close")
        sock.close()
        return

    for i, auction in enumerate(openAuctionList):
        print("## {} ##".format(i+1))
        print("Auction Id:     ",     auction["auctionId"])
        print("Name:           ",     auction["name"])
        print("Description:    ",     auction["description"])
        print("Type:           ",     auction["type"])
        print("Duration:       ",     auction["duration"])
        print("Creation Time:  ",     auction["creationTime"])
        print("Difficulty:     ",     auction["difficulty"])
        print("Base amount:    ",     auction["baseAmount"])
        print("Validation Code\n"   + auction["validationCode"])
        print("Modification Code\n" + auction["modificationCode"])
        print("Creator Id:     ",     auction["creatorId"])
        print("Creator Name:   ",     auction["creatorName"])
        print("--------------------------------------\n")


    #choose one
    while True:
        opt = input("$ ")

        if not match("^[0-9]+$", opt):
            print("ERROR: Insert a valid number!")
            continue

        opt = int(opt)
    
        if opt < 1 or opt > len(openAuctionList):
            print("Error: Insert a number between 1 and " + str(len(openAuctionList)))
            continue

        opt -= 1

        break

    #send the serial number/auction Id of the chosen one
    sendEncryptedMessage(sock, {'auctionID':openAuctionList[opt]["auctionId"]}, symmetricEncryption, sessionId, 5)

    #wait to see if all went good
    msgRecv = readMessage(sock, [], symmetricEncryption, sessionId, 6)
    
    if msgRecv["winnerBid"] == {}:
        print("No winner!")
        return

    decryptBid(
            msgRecv["winnerBid"],
            b64decode(bytes(msgRecv["key"], "ascii"))
            )

    print("Winner Bid")
    print("Client Id:",          msgRecv["winnerBid"]["clientId"])
    print("Client Name:",        msgRecv["winnerBid"]["clientName"])
    print("Client Certificate:", msgRecv["winnerBid"]["clientCertificate"])
    print("Amount:",             msgRecv["winnerBid"]["amount"])
    print("Timestamp:",          msgRecv["winnerBid"]["timestamp"])
    print("Nonce:",              msgRecv["winnerBid"]["nonce"])
    print("Auction Id:",         msgRecv["winnerBid"]["auctionId"])
    print("Auction Type:",       msgRecv["winnerBid"]["auctionType"])

    sock.close()
Exemplo n.º 12
0
def newBid():

    while True:
        amount = input("Amount to bid: ")

        if not match("^[0-9]+(\.[0-9][0-9]?)?$", amount):
            print("ERROR: Insert a valid amount")
            continue

        amount = float(amount)

        break

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    sock.connect(constants.REPOSITORY_ADDR)
    cert = getCertificate()
    symmetricEncryption, sessionId = clientHandShake(sock, privateKey, cert, ciphers, modes, paddings)

    sendEncryptedMessage(sock, {'action':ActionTypes.NEW_BID}, symmetricEncryption, sessionId, 3)

    msgRecv = readMessage(sock, [], symmetricEncryption, sessionId, 4)

    #display data
    openAuctionList = msgRecv["openAuctionList"]

    if len(openAuctionList) == 0:
        print("No open auctions")
        sock.close()
        return

    for i, auction in enumerate(openAuctionList):
        print("## {} ##".format(i+1))
        print("Auction Id:     ",     auction["auctionId"])
        print("Name:           ",     auction["name"])
        print("Description:    ",     auction["description"])
        print("Type:           ",     auction["type"])
        print("Duration:       ",     auction["duration"])
        print("Creation Time:  ",     auction["creationTime"])
        print("Difficulty:     ",     auction["difficulty"])
        print("Base amount:    ",     auction["baseAmount"])
        print("Validation Code\n"   + auction["validationCode"])
        print("Modification Code\n" + auction["modificationCode"])
        print("Creator Id:     ",     auction["creatorId"])
        print("Creator Name:   ",     auction["creatorName"])
        print("--------------------------------------\n")

    while True:
        opt = input("$ ")

        if not match("^[0-9]+$", opt):
            print("ERROR: Insert a valid number!")
            continue

        opt = int(opt)
    
        if opt < 1 or opt > len(openAuctionList):
            print("Error: Insert a number between 1 and " + str(len(openAuctionList)))
            continue

        opt -= 1

        break

    clientId, clientName = getUserInfo(cert)

    auctionId = openAuctionList[opt]["auctionId"]
    auctionType = openAuctionList[opt]["type"]
    timestamp = int(time.time())
    nonce = b64encode(urandom(32)).decode("ascii")
    bid = {
        "timestamp":timestamp,
        "clientId":clientId,
        "clientName":clientName,
        "clientCertificate":b64encode(cert.public_bytes(Encoding.PEM)).decode("ascii"),
        "amount":amount,
        "nonce":nonce,
        "auctionId":auctionId,
        "auctionType":auctionType
    }

    signature = b64encode(privateKey.sign(calculateHashOverFields(bid))).decode("ascii")

    sendEncryptedMessage(sock, {'auctionId': auctionId, "timestamp":timestamp, "nonce":nonce, "amount":amount, "signature":signature},
            symmetricEncryption, sessionId, 5)

    cryptopuzzleChallange = readMessage(sock, [], symmetricEncryption, sessionId, 6)

    nonce, newHash = solveCriptopuzzle(cryptopuzzleChallange["difficulty"], cryptopuzzleChallange["toMine"])

    sendEncryptedMessage(sock, {"nonce":nonce, "hash":newHash}, symmetricEncryption, sessionId, 7)

    msg = readMessage(sock, [], symmetricEncryption, sessionId, 8)

    if not validReceiptSignature(msg["signature"], msg["certificate"], msg["receipt"]):
        print("Signature on receipt received not valid")
        return
    else:
        print("Signature on receipt ok")

    if not os.path.exists("receipts"):
        os.mkdir("receipts")
        os.mkdir("receipts/" + clientId)

    if not os.path.exists("receipts/" + clientId):
        os.mkdir("receipts/" + clientId)

    while True:
        receiptName = input("Name for receipt: ")
        if receiptName == "":
            print("ERROR: Insert a valid name")
            continue
        break

    cryptopuzzleChallange["toMine"]["nonce"] = nonce

    receipt = {
        "whatISaw":{
            'bid': bid,
            "cryptopuzzleChallange":cryptopuzzleChallange
        },
        "received":msg
    }

    f = open("receipts/" + clientId + "/" + receiptName + ".txt", "w+")
    f.write(json.dumps({"auctionId":auctionId, "receipt":receipt}))
    f.close()

    sock.close()
Exemplo n.º 13
0
def createAuction(sock, clientCert, symmetricEncryption, sessionId):

    # Receive auction info
    mandatoryFields = []
    mandatoryFields.append(Field("name", str))
    mandatoryFields.append(Field("duration", int))
    mandatoryFields.append(Field("description", str))
    mandatoryFields.append(
        Field("type", str,
              lambda v: v in ["English", "BlindShown", "BlindHidden"]))
    mandatoryFields.append(Field("difficulty", int))
    mandatoryFields.append(Field("baseAmount", float))
    mandatoryFields.append(Field("validationCode", str))
    mandatoryFields.append(Field("modificationCode", str))
    msgRecv = readMessage(sock, mandatoryFields, symmetricEncryption,
                          sessionId, 4)

    for code in [msgRecv["validationCode"], msgRecv["modificationCode"]]:
        with open("dummy.py", "w+") as f:
            f.write(code)

        #check syntax of validation code
        try:
            py_compile.compile("dummy.py", doraise=True)
        except py_compile.PyCompileError:
            sendEncryptedMessage(
                sock, {"error": "Dynamic code with syntatic errors"},
                symmetricEncryption, sessionId, 5)
            return

    # Insert client id and name to auction info
    clientId, clientName = getUserInfo(clientCert)
    msgRecv["creatorId"] = clientId
    msgRecv["creatorName"] = clientName

    # Connect to repository to instantiate an auction
    sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock2.connect(constants.REPOSITORY_ADDR)
    symmetricEncryption2, sessionId2 = handshake.clientHandShake(
        sock2, privateKey, certificate, POSSIB_CIPHERS, POSSIB_MODES,
        POSSIB_PADDING)

    # Send auction info
    sendEncryptedMessage(sock2, {"action": ActionTypes.CREATE_AUCTION},
                         symmetricEncryption2, sessionId2, 3)
    sendEncryptedMessage(sock2, msgRecv, symmetricEncryption2, sessionId2, 4)

    # Receive auction Id of the created auction
    msgRecv2 = readMessage(sock2, [], symmetricEncryption2, sessionId2, 5)
    auctionId = msgRecv2['auctionId']
    creationTime = msgRecv2['creationTime']

    # Create some info on manager to show if users want to close auctions
    auctionInfo = msgRecv
    auctionInfo["auctionId"] = auctionId
    auctionInfo["creationTime"] = creationTime

    # Save that info
    AUCTIONS[auctionId] = Auction(auctionInfo, msgRecv["validationCode"],
                                  msgRecv["modificationCode"],
                                  msgRecv["baseAmount"])
    if clientId in CLIENTS.keys():
        CLIENTS[clientId].append(auctionId)
    else:
        CLIENTS[clientId] = [auctionId]

    sendEncryptedMessage(sock, {
        "auctionId": auctionId,
        "creationTime": creationTime
    }, symmetricEncryption, sessionId, 5)