Contents

  1. file_input.py
  2. fixed_input.py
  3. security_bug.py

file_input.py 1/3

[
top][prev][next]
# Example of providing a validated list of input
# Sara Sprenkle

def main():
    # the list of valid files user can choose from
    VALID_LIST= ["killers.txt", "fergie.txt", "west.txt", "coldplay.txt", "adele.txt"]
    VALID_LIST.sort()
        
    print 
    print "Which of the following album files do you want to process?"
    
    x = 1
    for filename in VALID_LIST:
        print "\t%d: %s"%(x, filename)
        x+=1
    
    choicestr = raw_input("Select the file by number: ")
    print
    
    try:
        choice = int(choicestr)
        if choice < 1 or choice > len(VALID_LIST):
            print "ERROR:", choice, "is not a valid selection."
        else:
            print "Processing file %d: %s" % (choice, VALID_LIST[choice-1])
        
    except:
        print "ERROR: selection must be an integer."
    
    
main()

fixed_input.py 2/3

[
top][prev][next]
# Example of addressing the input() security bug in Python
# Sara Sprenkle

total = 0
numDeposits = input("How many deposits are there? ")

if numDeposits <= 0:
    print "Error: Number of deposits must be positive"
    sys.exit(1)

for x in xrange(numDeposits):
    depositString = raw_input("Enter deposit " + str(x) + ": ")
    
    try:
        deposit = int(depositString)
        total += deposit
    except:
    # Note that one less deposit will be included in total; does not
    # reprompt for deposit
        print "Error: the grade must be an integer."
        
print "The total amount deposited is $%.2f." % total

security_bug.py 3/3

[
top][prev][next]
# Example of security bug in python with input() function in Python
# Sara Sprenkle

total = 0
numDeposits = input("How many deposits are there? ")

if numDeposits <= 0:
    print "Error: Number of deposits must be positive"
    sys.exit(1)

for x in xrange(numDeposits):
    # Try entering something like "total * 2" for the second deposit
    total += input("Enter deposit " + str(x) + ": ")

print "The total amount deposited is $%.2f." % total

Generated by GNU enscript 1.6.4.