Conversion to python3, using 2to3.

This commit is contained in:
Cas Cremers 2020-10-27 22:09:03 +01:00
parent eecf68dc98
commit 3a6041ccac
34 changed files with 245 additions and 245 deletions

View File

@ -50,7 +50,7 @@ def setBaseDir(mybasedir):
class AboutScyther(wx.Dialog):
def __init__(self,parent,mybasedir=None):
from Version import SCYTHER_GUI_VERSION
from .Version import SCYTHER_GUI_VERSION
global basedir
self.text = '''

View File

@ -1,5 +1,5 @@
#!/usr/bin/python
from __future__ import division # 2.2+-only
# 2.2+-only
"""
Scyther : An automatic verifier for security protocols.
Copyright (C) 2007-2013 Cas Cremers
@ -25,14 +25,14 @@ from __future__ import division # 2.2+-only
""" Import externals """
import wx
import os
from Misc import *
from .Misc import *
#---------------------------------------------------------------------------
""" Import scyther-gui components """
import Icon
import Preference
import Error
from . import Icon
from . import Preference
from . import Error
#---------------------------------------------------------------------------
try:
@ -74,7 +74,7 @@ class AttackDisplay(wx.ScrolledWindow):
Preference.doNotUsePIL()
raise Error.PILError
else:
print "Unknown file type %s." % (self.filetype)
print("Unknown file type %s." % (self.filetype))
# TODO self.Bind(wxSizeEvent
self.update(True)
@ -142,7 +142,7 @@ class AttackDisplay(wx.ScrolledWindow):
self.Image.SetBitmap(image.ConvertToBitmap())
else:
print "Unknown file type %s." % (self.attack.filetype)
print("Unknown file type %s." % (self.attack.filetype))
self.SetVirtualSize((virtualwidth,virtualheight))

View File

@ -29,7 +29,7 @@ import sys
#---------------------------------------------------------------------------
""" Import scyther-gui components """
import Misc
from . import Misc
#---------------------------------------------------------------------------

View File

@ -28,12 +28,12 @@ import os.path
#---------------------------------------------------------------------------
""" Import scyther-gui components """
import Settingswindow
import Scytherthread
import Icon
import About
import Editor
import Preference
from . import Settingswindow
from . import Scytherthread
from . import Icon
from . import About
from . import Editor
from . import Preference
#---------------------------------------------------------------------------

View File

@ -34,8 +34,8 @@ from Scyther import Misc as MiscScyther
from Scyther import FindDot
""" Import scyther-gui components """
import Temporary
import Preference
from . import Temporary
from . import Preference
#---------------------------------------------------------------------------
try:

View File

@ -32,15 +32,15 @@ from subprocess import Popen,PIPE
def confirm(question):
answer = ''
while answer not in ('y','n'):
print question,
answer = raw_input().lower()
print(question, end=' ')
answer = input().lower()
return answer == 'y'
def exists(func,list):
return len(filter(func,list)) > 0
return len(list(filter(func,list))) > 0
def forall(func,list):
return len(filter(func,list)) == len(list)
return len(list(filter(func,list))) == len(list)
def uniq(li):
result = []

View File

@ -49,7 +49,7 @@ from time import localtime,strftime
#---------------------------------------------------------------------------
""" Import scyther-gui components """
import Makeimage
from . import Makeimage
#---------------------------------------------------------------------------
@ -127,7 +127,7 @@ class Preferences(dict):
"""
Copy dict into self.
"""
for x in d.keys():
for x in list(d.keys()):
self[x] = d[x]
def parse(self,line):
@ -164,13 +164,13 @@ class Preferences(dict):
fp.close()
def show(self):
print "Preferences:"
for k in self.keys():
print "%s=%s" % (k, self[k])
print("Preferences:")
for k in list(self.keys()):
print("%s=%s" % (k, self[k]))
def save(self):
print "Saving preferences"
print("Saving preferences")
prefpath = preflocs[-1]
if not os.access(prefpath,os.W_OK):
os.makedirs(prefpath)
@ -215,7 +215,7 @@ def init():
def get(key,alt=None):
global prefs
if key in prefs.keys():
if key in list(prefs.keys()):
return prefs[key]
else:
return alt
@ -223,7 +223,7 @@ def get(key,alt=None):
def getkeys():
global prefs
return prefs.keys()
return list(prefs.keys())
def set(key,value):
global prefs

View File

@ -33,11 +33,11 @@ import Scyther.Error
from Scyther.Misc import *
""" Import scyther-gui components """
import Preference
import Attackwindow
import Icon
import Error
import Makeimage
from . import Preference
from . import Attackwindow
from . import Icon
from . import Error
from . import Makeimage
#---------------------------------------------------------------------------
if Preference.havePIL:
@ -114,7 +114,7 @@ class ScytherThread(threading.Thread):
# verification start
try:
claims = scyther.verify(storePopen=self.storePopen)
except Scyther.Error.ScytherError, el:
except Scyther.Error.ScytherError as el:
claims = None
pass
@ -464,7 +464,7 @@ class ScytherRun(object):
# which makes error reporting somewhat easier
try:
Scyther.Scyther.Check()
except Scyther.Error.BinaryError, e:
except Scyther.Error.BinaryError as e:
# e.file is the supposed location of the binary
text = "Could not find Scyther binary at\n%s" % (e.file)
Error.ShowAndExit(text)

View File

@ -28,7 +28,7 @@ import sys
#---------------------------------------------------------------------------
""" Import scyther-gui components """
import Preference
from . import Preference
import Scyther.Claim as Claim
#---------------------------------------------------------------------------

View File

@ -19,7 +19,7 @@ def scanThis(fn,f,rewritelist,cnt):
mapping.append((lhs,rhs))
fp = open(fn,"r")
for rl in fp.xreadlines():
for rl in fp:
l = rl
if f != None:
l = f(l)
@ -34,7 +34,7 @@ def convertEm(f=None,path=".",rewritelist=[],newdir=".",oldext="",newext=None):
cnt = 1
for fn in fl:
ffn = os.path.join(path,fn)
print "Processing",ffn
print("Processing",ffn)
s = scanThis(ffn,f,rewritelist,cnt)
if newext == None:
fn2 = fn
@ -44,7 +44,7 @@ def convertEm(f=None,path=".",rewritelist=[],newdir=".",oldext="",newext=None):
fp = open(ffn2,"w")
fp.write(s)
fp.close()
print "Produced",ffn2
print("Produced",ffn2)
cnt = cnt+1
def preprocess(s):
@ -55,7 +55,7 @@ def preprocess(s):
def main():
convertEm(f=preprocess,rewritelist=["@OracleA","@executability","@OracleB"],path=".",newdir="mpa",oldext=".spdl")
print "Done."
print("Done.")
if __name__ == '__main__':
main()

View File

@ -34,8 +34,8 @@ def stripRowEnd(l):
# Assume ends with \\, split by dtl
endstr = "\\\\"
if not l.endswith(endstr):
print "Error: some line does not end with \\\\"
print ">>%s<<" % (l)
print("Error: some line does not end with \\\\")
print(">>%s<<" % (l))
sys.exit(-1)
return l[:-len(endstr)]
@ -63,7 +63,7 @@ def scanAttackFile(fn):
prot = None
role = None
claim = None
for rawline in fp.xreadlines():
for rawline in fp:
l = rawline.strip()
@ -94,7 +94,7 @@ def scanAttackFile(fn):
attl[i] = x[1:-1]
ak = (prot,role,claim)
if ak not in attackmap.keys():
if ak not in list(attackmap.keys()):
attackmap[ak] = set()
attackmap[ak].add(tuple(attl))
@ -136,7 +136,7 @@ def mpaTable(attackmap):
s += "\\begin{longtable}{|l|lll|l|}\n"
s += "\\hline\n"
for kk in sorted(ALLCLAIMS):
if kk not in attackmap.keys():
if kk not in list(attackmap.keys()):
continue
(prot,role,claim) = kk
@ -174,7 +174,7 @@ def mpaTable2(attackmap,tabtype="tabular",options=""):
# To find the number of columns, we first need to find all protocols involved in two-protocol attacks
involved = set()
for kk in attackmap.keys():
for kk in list(attackmap.keys()):
for atl in attackmap[kk]:
# convert tuple back to list
att = list(atl)
@ -210,7 +210,7 @@ def mpaTable2(attackmap,tabtype="tabular",options=""):
s += "\\hline\n"
last = None
for kk in sorted(ALLCLAIMS):
if kk not in attackmap.keys():
if kk not in list(attackmap.keys()):
continue
(prot,role,claim) = kk
@ -256,7 +256,7 @@ def mpaTable3(attackmaps,tabtype="tabular",options=""):
involved = set()
allkeys = set()
for (attackmap,symbs) in attackmaps:
for kk in attackmap.keys():
for kk in list(attackmap.keys()):
allkeys.add(kk)
for atl in attackmap[kk]:
# convert tuple back to list
@ -298,7 +298,7 @@ def mpaTable3(attackmaps,tabtype="tabular",options=""):
s += "\\hline\n"
last = None
for kk in sorted(ALLCLAIMS):
if kk not in attackmap.keys():
if kk not in list(attackmap.keys()):
continue
(prot,role,claim) = kk
@ -313,7 +313,7 @@ def mpaTable3(attackmaps,tabtype="tabular",options=""):
se = tuple([ch])
sl += "& "
for (attackmap,symb) in attackmaps:
if kk in attackmap.keys():
if kk in list(attackmap.keys()):
if se in attackmap[kk]:
sl += symb
break
@ -341,7 +341,7 @@ def scanClaimList(fn):
fp = open("gen-%s-claims.txt" % (fn),"r")
claimmap = {}
for rawline in fp.xreadlines():
for rawline in fp:
l = rawline.strip()
@ -380,7 +380,7 @@ def scanClaimFile(fn):
fp = open("gen-%s-correctclaims.tex" % (fn),"r")
claimmap = {}
for rawline in fp.xreadlines():
for rawline in fp:
l = rawline.strip()
@ -396,7 +396,7 @@ def scanClaimFile(fn):
if not FFUNC(prot):
continue
if prot not in claimmap.keys():
if prot not in list(claimmap.keys()):
claimmap[prot] = {}
cll = splitStrip(dtl[1],";")
@ -404,7 +404,7 @@ def scanClaimFile(fn):
for dt in cll:
(role,claim) = roleClaim(dt)
if role not in claimmap[prot].keys():
if role not in list(claimmap[prot].keys()):
claimmap[prot][role] = set()
claimmap[prot][role].add(claim)
@ -420,7 +420,7 @@ def scanClaimFile(fn):
def getRoleClaims(rcmap):
rc = set()
for role in rcmap.keys():
for role in list(rcmap.keys()):
for claim in rcmap[role]:
rc.add((role,claim))
@ -459,8 +459,8 @@ def typeScanMatrix(cml,onlyChanged = False):
alltrue = True
for (txt,cm) in cml:
verdict = badverdict
if prot in cm.keys():
if role in cm[prot].keys():
if prot in list(cm.keys()):
if role in list(cm[prot].keys()):
if claim in cm[prot][role]:
verdict = goodverdict
if verdict == badverdict:
@ -518,8 +518,8 @@ def typeScanMatrix2(cml,onlyChanged = False,additive = False):
res = ""
for (txt,cm) in cml:
verdict = badverdict
if prot in cm.keys():
if role in cm[prot].keys():
if prot in list(cm.keys()):
if role in list(cm[prot].keys()):
if claim in cm[prot][role]:
verdict = goodverdict
if verdict == badverdict:
@ -582,8 +582,8 @@ def typeScanMatrix3(hd1,hd2,cml,f,onlyChanged = False,tabletype="longtable"):
resl = []
for cm in cml:
verdict = badverdict
if prot in cm.keys():
if role in cm[prot].keys():
if prot in list(cm.keys()):
if role in list(cm[prot].keys()):
if claim in cm[prot][role]:
verdict = goodverdict
if verdict == badverdict:
@ -660,11 +660,11 @@ def docWrite(fn,tex,author=None,title=None):
def docMake(fn,tex,author=None,title=None):
import commands
import subprocess
docWrite(fn,tex,author,title)
cmd = "pdflatex %s" % (fn)
commands.getoutput(cmd)
subprocess.getoutput(cmd)
def f1(resl):
txtl = []

View File

@ -32,7 +32,7 @@ def parseArgs():
parser.print_help()
sys.exit(0)
if opts.protocol not in ["nsl","bke","nsl-priv-noprop","nsl-pub-nap","bke-nap"]:
print "I don't know the %s protocol." % (opts.protocol)
print("I don't know the %s protocol." % (opts.protocol))
sys.exit(0)
return (opts,args)
@ -158,7 +158,7 @@ def message1 (label,inrole):
return msg
else:
print "Hmm, I don't know how to create the first message for protocol %s" % (opts.protocol)
print("Hmm, I don't know how to create the first message for protocol %s" % (opts.protocol))
def message2 (label,inrole):
global P,variant,opts
@ -205,7 +205,7 @@ def message2 (label,inrole):
return msg
else:
print "Hmm, I don't know how to create the final message for protocol %s" % (opts.protocol)
print("Hmm, I don't know how to create the final message for protocol %s" % (opts.protocol))
def message (label,inrole):
global P,opts
@ -338,7 +338,7 @@ def main():
global opts
(opts,args) = parseArgs()
print protocol(args)
print(protocol(args))
# Only if main stuff
if __name__ == '__main__':

View File

@ -7,11 +7,11 @@
# and sincerely hope on gives a complete proof.
# we slowly refine the tests.
#
import commands
import subprocess
def startset():
mainlist = [11, 15]
print "Starting with", mainlist
print("Starting with", mainlist)
return mainlist
def tuplingchoice(heur,variant,P,runs,latupling):
@ -37,15 +37,15 @@ def tuplingchoice(heur,variant,P,runs,latupling):
#s += " | scyther -a -r%i --summary" % runs
# Show what we're doing
print s
print(s)
#s += " | grep \"complete\""
out = commands.getoutput(s)
out = subprocess.getoutput(s)
if out == "":
#print "Okay"
return False
else:
print out
print(out)
return True
def testvariant(h,v,p,r):
@ -55,11 +55,11 @@ def testvariant(h,v,p,r):
return tuplingchoice (h,v,p,r, True)
def scan(testlist, P, runs):
print "Testing using P %i and %i runs." % (P,runs)
print("Testing using P %i and %i runs." % (P,runs))
for i in testlist:
print "Testing protocol %i." % (i)
print("Testing protocol %i." % (i))
for h in range (0,32):
print "Heuristic %i:" % (h)
print("Heuristic %i:" % (h))
testvariant (h,i,P,runs)
def main():

View File

@ -6,13 +6,13 @@
# We test all variants [0..31] until we are sure they work. Thus,
# we slowly refine the tests.
#
import commands
import subprocess
def startset():
return range(0,32)
return list(range(0,32))
mainlist = [11, 15]
print "Starting with", mainlist
print("Starting with", mainlist)
return mainlist
def tuplingchoice(variant,P,runs,latupling):
@ -30,7 +30,7 @@ def tuplingchoice(variant,P,runs,latupling):
#s += " | scyther -a -r%i --summary" % runs
#print s
s += " | grep \"Fail\""
out = commands.getoutput(s)
out = subprocess.getoutput(s)
if out == "":
#print "Okay"
return True
@ -53,15 +53,15 @@ def removeattacks (testlist, P, runs):
return okaylist
def scan(testlist, P, runs):
print "Testing using P %i and %i runs." % (P,runs)
print("Testing using P %i and %i runs." % (P,runs))
results = removeattacks (testlist, P, runs)
if len(results) < len(testlist):
attacked = []
for i in range(0,len(testlist)):
if testlist[i] not in results:
attacked.append(testlist[i])
print "Using P %i and %i runs, we find attacks on %s" % (P,runs, str(attacked))
print "Therefore, we are left with %i candidates: " % (len(results)), results
print("Using P %i and %i runs, we find attacks on %s" % (P,runs, str(attacked)))
print("Therefore, we are left with %i candidates: " % (len(results)), results)
return results
@ -71,9 +71,9 @@ def main():
for rundiff in range(0,5):
candidates = scan(candidates,P,P+rundiff)
print
print "Good variants:"
print candidates
print()
print("Good variants:")
print(candidates)
main()

View File

@ -52,7 +52,7 @@ def evaluate(fn,prefix=""):
fstderr.seek(0)
res = ""
for l in fstdout.xreadlines():
for l in fstdout:
res += prefix + l.strip() + "\n"
#for l in fstderr.xreadlines():
# print l
@ -72,7 +72,7 @@ def main():
cnt = 1
tres = ""
for (prefix,fn) in sorted(fl):
print "Evaluating %s (%i/%i)" % (fn,cnt,len(fl))
print("Evaluating %s (%i/%i)" % (fn,cnt,len(fl)))
res = evaluate(prefix+fn, "%s\t" % (fn))
fp.write(res)
tres += res
@ -83,7 +83,7 @@ def main():
fp.write(tres)
fp.close()
print res
print(res)

View File

@ -30,7 +30,7 @@
# Note 2: this code assumes that both scyther-linux and dot can be found in the
# environment (i.e. PATH variable)
#
import os,sys,commands
import os,sys,subprocess
import os.path
tempcount = 0
@ -59,7 +59,7 @@ def scyther_to_dotfile():
tmpdotfile = generateTemp('dot')
command = "%s --plain --dot-output %s > %s" % (scythername, args, tmpdotfile)
output = commands.getoutput(command)
output = subprocess.getoutput(command)
return (output,tmpdotfile)
def dotfile_to_pdffile(dotfile,outfile=None):
@ -72,10 +72,10 @@ def dotfile_to_pdffile(dotfile,outfile=None):
# it fit to a landscape page
dotdata = open(dotfile, "r")
f = None
for line in dotdata.xreadlines():
for line in dotdata:
if (line.find('digraph') == 0):
f = os.popen("dot -Gsize='11.0,8.0' -Gratio=fill -Tps >>%s" % (tmp),'w')
print >>f, line
print(line, file=f)
dotdata.close()
if not f:
@ -96,18 +96,18 @@ def dotfile_to_pdffile(dotfile,outfile=None):
def main():
(output,dotfile) = scyther_to_dotfile()
print output
print(output)
pdffile = dotfile_to_pdffile(dotfile)
os.unlink(dotfile)
if pdffile:
commands.getoutput("kpdf %s" % pdffile)
subprocess.getoutput("kpdf %s" % pdffile)
os.unlink(pdffile)
else:
print "No graphs generated."
print("No graphs generated.")
if __name__ == '__main__':
if len(sys.argv) > 1:
main()
else:
print "Please provide the name of an input file."
print("Please provide the name of an input file.")

View File

@ -21,10 +21,10 @@
# Attack
#
import Trace
import Term
from . import Trace
from . import Term
#import Classification
from Misc import *
from .Misc import *
class Attack(object):
def __init__(self):
@ -47,7 +47,7 @@ class Attack(object):
def getInvolvedAgents(self):
result = []
for run in self.semiTrace.runs:
for agent in run.roleAgents.values():
for agent in list(run.roleAgents.values()):
result.append(agent)
return uniq(result)

View File

@ -21,7 +21,7 @@
# Claim
#
import Term
from . import Term
def stateDescription(okay,n=1,caps=False):
if okay:

View File

@ -29,7 +29,7 @@ import sys
import os
#---------------------------------------------------------------------------
""" Import internals """
import Misc
from . import Misc
#---------------------------------------------------------------------------
DOTLOCATION = None

View File

@ -40,15 +40,15 @@ You need at least Python 2.4 to use this program.
def confirm(question):
answer = ''
while answer not in ('y','n'):
print question,
answer = raw_input().lower()
print(question, end=' ')
answer = input().lower()
return answer == 'y'
def exists(func,list):
return len(filter(func,list)) > 0
return len(list(filter(func,list))) > 0
def forall(func,list):
return len(filter(func,list)) == len(list)
return len(list(filter(func,list))) == len(list)
def uniq(li):
result = []
@ -123,12 +123,12 @@ def safeCommand(cmd, storePopen=None):
if storePopen != None:
storePopen(p)
sts = p.wait()
except KeyboardInterrupt, EnvironmentError:
except KeyboardInterrupt as EnvironmentError:
raise
except:
print "Wile processing [%s] we had an" % (cmd)
print "unexpected error:", sys.exc_info()[0]
print
print("Wile processing [%s] we had an" % (cmd))
print("unexpected error:", sys.exc_info()[0])
print()
sts = -1
raise # For now still raise
@ -142,15 +142,15 @@ def panic(text):
"""
try:
import Tkinter
import tkinter
except:
print text
print(text)
sys.exit(-1)
print text
print(text)
root = Tkinter.Tk()
w = Tkinter.Label(root, justify=Tkinter.LEFT, padx = 10, text=text)
root = tkinter.Tk()
w = tkinter.Label(root, justify=tkinter.LEFT, padx = 10, text=text)
w.pack()
root.mainloop()

View File

@ -28,7 +28,7 @@
import os
import os.path
import sys
import StringIO
import io
import tempfile
try:
import hashlib
@ -40,10 +40,10 @@ except ImportError:
#---------------------------------------------------------------------------
""" Import scyther components """
import XMLReader
import Error
import Claim
from Misc import *
from . import XMLReader
from . import Error
from . import Claim
from .Misc import *
#---------------------------------------------------------------------------
@ -77,7 +77,7 @@ def getCacheDir():
# Check if user chose the path
cachedirkey = "SCYTHERCACHEDIR"
if cachedirkey in os.environ.keys():
if cachedirkey in list(os.environ.keys()):
tmpdir = os.environ[cachedirkey]
if tmpdir == "":
# Special value: if the variable is present, but equals the empty string, we disable caching.
@ -126,7 +126,7 @@ def CheckSanity(program):
"""
if not os.path.isfile(program):
raise Error.BinaryError, program
raise Error.BinaryError(program)
#---------------------------------------------------------------------------
@ -149,7 +149,7 @@ def EnsureString(x,sep=" "):
return sep.join(newlist)
else:
raise Error.StringListError, x
raise Error.StringListError(x)
#---------------------------------------------------------------------------
@ -177,7 +177,7 @@ def getScytherBackend():
else:
""" Unsupported"""
raise Error.UnknownPlatformError, sys.platform
raise Error.UnknownPlatformError(sys.platform)
program = os.path.join(getBinDir(),scythername)
return program

View File

@ -20,8 +20,8 @@
#
# Term
#
import Trace
from Misc import *
from . import Trace
from .Misc import *
class InvalidTerm(TypeError):
"Exception used to indicate that a given term is invalid"

View File

@ -20,7 +20,7 @@
#
# Trace
#
from Misc import *
from .Misc import *
class InvalidAction(TypeError):
"Exception used to indicate that a given action is invalid"
@ -79,7 +79,7 @@ class SemiTrace(object):
def getPrecedingEvents(self,event,previous=[]):
# If it is cached return cached version
if event.preceding != None:
return filter(lambda x: x not in previous,event.preceding)
return [x for x in event.preceding if x not in previous]
preceding = []
for prec in event.getBefore():
preceding.append(prec)
@ -90,7 +90,7 @@ class SemiTrace(object):
preceding.extend(self.getPrecedingEvents(fol))
preceding = uniq(preceding)
event.preceding = preceding
preceding = filter(lambda x: x not in previous,preceding)
preceding = [x for x in preceding if x not in previous]
return preceding
# Returns -1 if the first event has to be before the second one
@ -175,7 +175,7 @@ class ProtocolDescription(object):
# Find event by label
def findEvent(self,eventlabel,eventType=None):
for (role,descr) in self.roledescr.items():
for (role,descr) in list(self.roledescr.items()):
for event in descr:
if event.label == eventlabel:
if eventType == None or isinstance(event,eventType):
@ -206,7 +206,7 @@ class ProtocolDescription(object):
# that are in the precedingEvents of a certain event
def getPrecedingLabelSet(self,eventlabel):
events = self.getPrecedingEvents(eventlabel)
events = filter(lambda x: isinstance(x,EventRead),events)
events = [x for x in events if isinstance(x,EventRead)]
return [x.label for x in events]
# Calculate the roles in preceding labelset that is all roles that
@ -219,7 +219,7 @@ class ProtocolDescription(object):
def __str__(self):
s = ''
for x in self.roledescr.values():
for x in list(self.roledescr.values()):
for e in x:
s += str(e) + "\n"
return s
@ -318,7 +318,7 @@ class EventClaim(Event):
# agents
def ignore(self):
for untrusted in self.run.attack.untrusted:
if untrusted in self.run.roleAgents.values():
if untrusted in list(self.run.roleAgents.values()):
return True
return False

View File

@ -48,7 +48,7 @@ except:
try:
from elementtree import ElementTree
except ImportError:
print """
print("""
ERROR:
Could not locate either the [elementtree] or the [cElementTree] package.
@ -56,7 +56,7 @@ Please install one of them in order to work with the Scyther python interface.
The [cElementTree] packages can be found at http://effbot.org/zone/celementtree.htm
Note that you can still use the Scyther binaries in the 'Bin' directory.
"""
""")
sys.exit(1)
## Simply pick cElementTree
@ -65,10 +65,10 @@ Note that you can still use the Scyther binaries in the 'Bin' directory.
#useiter = False
#from elementtree import ElementTree
import Term
import Attack
import Trace
import Claim
from . import Term
from . import Attack
from . import Trace
from . import Claim
class XMLReader(object):
@ -148,7 +148,7 @@ class XMLReader(object):
# value
return Term.TermVariable(name,None)
else:
raise Term.InvalidTerm, "Invalid term type in XML: %s" % tag.tag
raise Term.InvalidTerm("Invalid term type in XML: %s" % tag.tag)
def readEvent(self,xml):
label = self.readTerm(xml.find('label'))
@ -188,7 +188,7 @@ class XMLReader(object):
pass
return Trace.EventClaim(index,label,followlist,role,etype,argument)
else:
raise Trace.InvalidAction, "Invalid action in XML: %s" % (xml.get('type'))
raise Trace.InvalidAction("Invalid action in XML: %s" % (xml.get('type')))
def readRun(self,xml):
assert(xml.tag == 'run')
@ -276,7 +276,7 @@ class XMLReader(object):
elif event.tag == 'timebound':
claim.timebound = True
else:
print >>sys.stderr,"Warning unknown tag in claim: %s" % claim.tag
print("Warning unknown tag in claim: %s" % claim.tag, file=sys.stderr)
claim.analyze()
return claim
@ -353,6 +353,6 @@ class XMLReader(object):
# this list
self.varlist = attack.variables
else:
print >>sys.stderr,"Warning unknown tag in attack: %s" % event.tag
print("Warning unknown tag in attack: %s" % event.tag, file=sys.stderr)
return attack

View File

@ -22,7 +22,7 @@
#
# Set prefix for __all__
#
import Scyther
from . import Scyther
# Provide scope
__all__ = ["Scyther"]

View File

@ -34,17 +34,17 @@ import sys
try:
from constraint import *
except:
print "Could not import constraint solver module."
print "For more information, visit"
print " http://labix.org/python-constraint"
print("Could not import constraint solver module.")
print("For more information, visit")
print(" http://labix.org/python-constraint")
sys.exit()
#---------------------------------------------------------------------------
def test():
problem = Problem()
problem.addVariables(range(0, 16), range(1, 16+1))
problem.addConstraint(AllDifferentConstraint(), range(0, 16))
problem.addVariables(list(range(0, 16)), list(range(1, 16+1)))
problem.addConstraint(AllDifferentConstraint(), list(range(0, 16)))
problem.addConstraint(ExactSumConstraint(34), [0,5,10,15])
problem.addConstraint(ExactSumConstraint(34), [3,6,9,12])
for row in range(4):
@ -54,7 +54,7 @@ def test():
problem.addConstraint(ExactSumConstraint(34),
[col+4*i for i in range(4)])
solutions = problem.getSolutions()
print solutions
print(solutions)
#---------------------------------------------------------------------------

View File

@ -109,7 +109,7 @@ def render_best_attack(fn,cid):
render_dot(dotfile,"png")
render_dot(dotfile,"pdf")
print "%s; %s" % (fn,cl)
print("%s; %s" % (fn,cl))
def main():

View File

@ -48,9 +48,9 @@ def fileandline(fn,linenos):
ln = 1
done = 0
sz = len(linenos)
for l in fp.xreadlines():
for l in fp:
if str(ln) in linenos:
print l
print(l)
scyther_json(l)
done = done + 1
if done >= sz:

View File

@ -18,7 +18,7 @@ Arguments:
def countlines(fn):
count = 0
fh = open(fn,'r')
for l in fh.xreadlines():
for l in fh:
count = count + 1
fh.close()
return count
@ -26,7 +26,7 @@ def countlines(fn):
def marker(jobcount,todo):
left = todo - jobcount
dperc = int((100 * jobcount) / todo)
print "echo \"Sent %i out of %i jobs, hence %i left. %i%% done.\"" % (jobcount,todo,left,dperc)
print("echo \"Sent %i out of %i jobs, hence %i left. %i%% done.\"" % (jobcount,todo,left,dperc))
def main(fn,step,optlist):
@ -39,7 +39,7 @@ def main(fn,step,optlist):
jobcount = 0
done = 0
for l in fh.xreadlines():
for l in fh:
if buf == 0:
s = "bsub %s ./json-scyther.py %s" % (" ".join(optlist),fn)
s += " %i" % (ln)

View File

@ -36,13 +36,13 @@ class ProgressBar(object):
def start(self):
if self.widgets:
if len(self.widgets) > 0:
print self.widgets[0],
print(self.widgets[0], end=' ')
def update(self,count):
pass
def finish(self):
print " Done."
print(" Done.")
def SimpleProgress():

View File

@ -22,8 +22,8 @@
#---------------------------------------------------------------------------
# Try to get wxPython
try:
import wx.adv
except ImportError,err:
import wx
except ImportError as err:
from Scyther import Misc
errmsg = "Problem with importing the required [wxPython] package."

View File

@ -50,8 +50,8 @@ def simpleRun(args):
if __name__ == '__main__':
pars = sys.argv[1:]
if len(pars) == 0:
print usage()
print(usage())
else:
print simpleRun(" ".join(pars))
print(simpleRun(" ".join(pars)))

View File

@ -48,7 +48,7 @@ TEST2 = "--max-runs=4"
#---------------------------------------------------------------------------
""" Import externals """
import commands
import subprocess
#---------------------------------------------------------------------------
@ -128,7 +128,7 @@ def findProtocols():
"""
cmd = "find -iname '*.spdl'"
plist = commands.getoutput(cmd).splitlines()
plist = subprocess.getoutput(cmd).splitlines()
nlist = []
for prot in plist:
if filterProtocol(prot):
@ -143,35 +143,35 @@ def main():
global TEST0,TEST1,TEST2
list = findProtocols()
print "Performing delta analysis"
print
print "String 0 (used for both): '%s'" % TEST0
print "String 1: '%s'" % TEST1
print "String 2: '%s'" % TEST2
print
print "After filtering, we are left with the following protocols:", list
print
print("Performing delta analysis")
print()
print("String 0 (used for both): '%s'" % TEST0)
print("String 1: '%s'" % TEST1)
print("String 2: '%s'" % TEST2)
print()
print("After filtering, we are left with the following protocols:", list)
print()
maxcount = len(list)
count = 1
delta = 0
for prot in list:
perc = (100 * count) / maxcount
print "[%i%%] %s: " % (perc,prot),
print("[%i%%] %s: " % (perc,prot), end=' ')
res = ScytherDiff(prot)
if res != None:
print
print "-" * 72
print prot
print "-" * 72
print res
print()
print("-" * 72)
print(prot)
print("-" * 72)
print(res)
delta = delta + 1
else:
print "No interesting delta found."
print("No interesting delta found.")
count = count + 1
print
print "Analysis complete."
print "%i out of %i protocols differed [%i%%]." % (delta,maxcount,(100 * delta)/maxcount)
print()
print("Analysis complete.")
print("%i out of %i protocols differed [%i%%]." % (delta,maxcount,(100 * delta)/maxcount))
if __name__ == '__main__':

View File

@ -44,14 +44,14 @@ try:
except ImportError:
from progressbarDummy import *
PROGRESSBAR = False
print """
print("""
Missing the progressbar library.
It can be downloaded from:
http://code.google.com/p/python-progressbar/
"""
""")
FOUND = []
ALLMPA = []
@ -227,7 +227,7 @@ def MyScyther(protocollist,filt=None,options=[],checkpickle=True):
# arguments to call
s.options = (" ".join(sorted(uniq(opts)))).strip()
if OPTS.debug:
print s.options
print(s.options)
for protocol in sorted(protocollist):
s.addFile(protocol)
@ -356,7 +356,7 @@ def verifyMPAlist(mpalist,claimid,options=[]):
global OPTS, ARGS
if OPTS.debug:
print time.asctime(), mpalist, claimid, options
print(time.asctime(), mpalist, claimid, options)
if not verifyMPAattack(mpalist,claimid,options):
global FOUND
@ -367,7 +367,7 @@ def verifyMPAlist(mpalist,claimid,options=[]):
# This is an MPA attack!
if OPTS.debug:
print "I've found a multi-protocol attack on claim %s in the context %s." % (claimid,str(mpalist))
print("I've found a multi-protocol attack on claim %s in the context %s." % (claimid,str(mpalist)))
att = Attack(claim,mpalist)
FOUND.append(att)
@ -442,9 +442,9 @@ def foundToDicts(attacklist = []):
pn = str(att.protocol())
cl = att.claimid()
if pn not in res.keys():
if pn not in list(res.keys()):
res[pn] = {}
if cl not in res[pn].keys():
if cl not in list(res[pn].keys()):
res[pn][cl] = set()
res[pn][cl].add(att)
return res
@ -464,13 +464,13 @@ def findAllMPA(protocolset,options=[],mpaoptions=[]):
# Find all correct claims in each protocol
(protocolset,correct,cpcount) = getCorrectIsolatedClaims(protocolset,options)
print "Investigating %i correct claims in %i protocols." % (len(correct), cpcount)
print("Investigating %i correct claims in %i protocols." % (len(correct), cpcount))
mpaprots = []
res = []
if len(correct) == 0:
print "Nothing to do."
print("Nothing to do.")
return res
if OPTS.verbose:
@ -479,27 +479,27 @@ def findAllMPA(protocolset,options=[],mpaoptions=[]):
"""
pmapclaims = {}
for (protocol,claimid) in correct:
if protocol not in pmapclaims.keys():
if protocol not in list(pmapclaims.keys()):
pmapclaims[protocol] = set()
pmapclaims[protocol].add(claimid)
print "Protocols with correct claims:"
if len(pmapclaims.keys()) == 0:
print " None."
print("Protocols with correct claims:")
if len(list(pmapclaims.keys())) == 0:
print(" None.")
else:
for pk in pmapclaims.keys():
print " %s, %s" % (pk, pmapclaims[pk])
print
for pk in list(pmapclaims.keys()):
print(" %s, %s" % (pk, pmapclaims[pk]))
print()
left = set()
for p in protocolset:
if p not in pmapclaims.keys():
if p not in list(pmapclaims.keys()):
left.add(p)
print "Protocols with no correct claims:"
print("Protocols with no correct claims:")
if len(left) == 0:
print " None."
print(" None.")
else:
for p in left:
print " %s" % (p)
print
print(" %s" % (p))
print()
# output of all claims (only if latex required)
@ -528,7 +528,7 @@ def findAllMPA(protocolset,options=[],mpaoptions=[]):
if OPTS.latex:
pmapclaims = {}
for (protocol,claimid) in correct:
if protocol not in pmapclaims.keys():
if protocol not in list(pmapclaims.keys()):
pmapclaims[protocol] = set()
pmapclaims[protocol].add(claimid)
@ -640,19 +640,19 @@ def findAllMPA(protocolset,options=[],mpaoptions=[]):
fp.write("\\end{tabular}\n")
fp.close()
print "-" * 70
print "Summary:"
print
print "We scanned %i protocols with options [%s]." % (len(protocolset),options)
print "We found %i correct claims." % (len(correct))
print "We then scanned combinations of at most %i protocols with options [%s]." % (OPTS.maxprotocols,alloptions)
print("-" * 70)
print("Summary:")
print()
print("We scanned %i protocols with options [%s]." % (len(protocolset),options))
print("We found %i correct claims." % (len(correct)))
print("We then scanned combinations of at most %i protocols with options [%s]." % (OPTS.maxprotocols,alloptions))
if OPTS.pickle:
print "However, just precomputing now, hence we are not drawing any conclusions."
print("However, just precomputing now, hence we are not drawing any conclusions.")
else:
print "We found %i MPA attacks." % (len(FOUND))
print "The attacks involve the claims of %i protocols." % (len(mpaprots))
print "-" * 70
print
print("We found %i MPA attacks." % (len(FOUND)))
print("The attacks involve the claims of %i protocols." % (len(mpaprots)))
print("-" * 70)
print()
return res
@ -674,37 +674,37 @@ def showDiff(reslist):
Show difference between (opts,mpaopts,attacklist) tuples in list
"""
if len(reslist) == 0:
print "Comparison list is empty"
print("Comparison list is empty")
return
(opt1,mpaopt1,al1) = reslist[0]
print "-" * 70
print "Base case: attacks for \n [%s]:" % (opt1 + mpaopt1)
print
print len(al1)
print("-" * 70)
print("Base case: attacks for \n [%s]:" % (opt1 + mpaopt1))
print()
print(len(al1))
for a in al1:
print "Base attack: %s" % (a)
print("Base attack: %s" % (a))
print "-" * 70
print
print("-" * 70)
print()
for i in range(0,len(reslist)-1):
(opt1,mpaopt1,al1) = reslist[i]
(opt2,mpaopt2,al2) = reslist[i+1]
print "-" * 70
print "Comparing the attacks for \n [%s] with\n [%s]:" % (opt1 + mpaopt1, opt2 + mpaopt2)
print
print len(al1), len(al2)
print("-" * 70)
print("Comparing the attacks for \n [%s] with\n [%s]:" % (opt1 + mpaopt1, opt2 + mpaopt2))
print()
print(len(al1), len(al2))
for a in al2:
if a not in al1:
print "Added attack: %s" % (a)
print("Added attack: %s" % (a))
for a in al1:
if a not in al2:
print "Removed attack: %s" % (a)
print("Removed attack: %s" % (a))
print "-" * 70
print
print("-" * 70)
print()
@ -758,7 +758,7 @@ def exploreTree( i, choices , l, options = [], mpaoptions = []):
res = []
for (txt,arg) in cl:
print "For choice %i, selecting options %s" % (i,txt)
print("For choice %i, selecting options %s" % (i,txt))
if mpaonly:
o1 = []
o2 = arg
@ -811,23 +811,23 @@ def fullScan(l, options = [], mpaoptions = []):
invprots.add(str(prot))
if not OPTS.pickle:
print "The bottom line: we found %i protocols with multi-protocol attacks from a set of %i protocols." % (len(attprots),len(allprots))
print
print("The bottom line: we found %i protocols with multi-protocol attacks from a set of %i protocols." % (len(attprots),len(allprots)))
print()
print "Multi-protocol attacks were found on:"
print("Multi-protocol attacks were found on:")
for prot in sorted(list(allprots & attprots)):
print " %s" % (prot)
print
print(" %s" % (prot))
print()
print "No multi-protocol attacks were found on these protocols, but they caused MPA attacks:"
print("No multi-protocol attacks were found on these protocols, but they caused MPA attacks:")
for prot in sorted(list((allprots - attprots) & invprots)):
print " %s" % (prot)
print
print(" %s" % (prot))
print()
print "These protocols were not involved in any MPA attacks:"
print("These protocols were not involved in any MPA attacks:")
for prot in sorted(list((allprots - attprots) - invprots)):
print " %s\t[%s]" % (prot,PROTNAMETOFILE[prot])
print
print(" %s\t[%s]" % (prot,PROTNAMETOFILE[prot]))
print()
@ -864,7 +864,7 @@ def bigTest():
nl = l
# Report list
print "Performing multi-protocol analysis for the following protocols:", nl
print("Performing multi-protocol analysis for the following protocols:", nl)
fullScan(l)