-
Notifications
You must be signed in to change notification settings - Fork 0
/
pw_spec.py
230 lines (194 loc) · 5.73 KB
/
pw_spec.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import logging
import json
log = logging.getLogger(__name__)
log.setLevel(logging.WARN)
class iterfromrule:
def __init__(self, rulefilename):
self.rules, self.states = self._read_rulefile(rulefilename)
self.statesIdx = 0 # Point to current state machine in states
self.avoids = {} # A dictionary of statesIdx->stateIdx->set(AVOID_CHARACTERS)
def __iter__(self):
return self
def next(self):
# All state machines are terminated
if not self.states:
raise StopIteration
value = self._getStateValue()
# Advance current state
if not self._nextState():
del self.states[self.statesIdx]
# Switch to other state machine
if self.states:
self.statesIdx = (self.statesIdx-1) % len(self.states)
return value
def _getStateValue(self):
curState = self.states[self.statesIdx]
value=[]
for stateIdx, stateVal in enumerate(curState):
value.append(self.rules[stateIdx][stateVal])
return ''.join(value)
def _nextState(self):
curState = self.states[self.statesIdx]
curAvoid = self.avoids.setdefault(self.statesIdx,{})
myQueue = [(len(self.rules)-1, 1)]
while myQueue:
ruleIdx, stateChg = myQueue.pop()
if ruleIdx>=len(self.rules):
continue
if ruleIdx<0:
return False
curAvoid.pop(ruleIdx, None)
ruleSet = self.rules[ruleIdx]
stateVal = curState[ruleIdx]
avoidSet = curAvoid.get(ruleIdx-1, set())
while True:
stateVal = (stateVal+stateChg)%len(ruleSet)
if stateVal==0 and stateChg!=0:
myQueue.append((ruleIdx-1, 1))
break
curRuleVal=ruleSet[stateVal]
if curRuleVal == '':
curAvoid[ruleIdx]=avoidSet | set(ruleSet) - {''}
myQueue.append((ruleIdx+1, 0))
log.debug("Avoid[%d]=%s",ruleIdx, curAvoid[ruleIdx])
break
if curRuleVal not in avoidSet:
break
stateChg = 1
curState[ruleIdx] = stateVal
log.debug("curState=%s",curState)
return True
def save_state(self, filename):
log.debug("Saving current state into %s...", filename)
with open(filename, 'w') as f:
for rule in self.rules:
f.write(self._genRuleLine(rule))
f.write('\n')
for state in self.states:
f.write('\n')
f.write(json.dumps(state))
@classmethod
def _read_rulefile(cls, rulefilename):
log.debug("Processing rule file %s...", rulefilename)
lineCnt=0
with open(rulefilename, 'r') as f:
# Read password rules
rules=[]
for line in f:
lineCnt += 1
rule = cls._parseRuleLine(line)
if not rule:
if rules:
#Stop at the empty line where password rule should be ended
break
else:
#Not password rule had been started, so keep going
continue
rules.append(rule)
log.debug(" [%s:%d] - %s", rulefilename, lineCnt, rule)
# Read next search state(s)
states = []
for line in f:
lineCnt +=1
state = json.loads(line)
#Stop at the empty line where state(s) should be ended
if not state:
break
if len(state) != len(rules):
log.warn("expected state length is %d, but got %d"
, len(rules), len(state))
# Extend state
while len(state)<len(rules): state.append(0)
# Truncate state
while len(state)>len(rules): state.pop()
states.append(state)
if not states:
states.append([0]*len(rules))
return rules, states
@staticmethod
def _parseRuleLine(line):
"""Parse a line of rule for a password letter
Using \ for escape any special control characters. Following are
special control characters:
$ - password letter can be empty or skip
# - will be use as inline comment
"""
escape=''
charSet=set()
charList=[]
for c in line:
if c in ('\n', '\r'):
continue
elif escape:
cc = c
escape=''
elif c == '#':
# Ignore inline commenting
break
elif c == '\\':
escape=c
continue
elif c == '$':
cc = ''
else:
cc = c
if cc not in charSet:
charSet.add(cc)
charList.append(cc)
if escape and (escape not in charSet):
charSet.add(escape)
charList.append(escape)
return charList
@staticmethod
def _genRuleLine(rule):
"""Generate rule line for a password letter
Using \ for escape any special control characters. Following are
special control characters:
$ - password letter can be empty or skip
# - will be use as inline comment
"""
line = []
for r in rule:
if r == '':
line.append('$')
elif r == '$':
line.append('\\$')
else:
line.append(r)
return ''.join(line)
# @staticmethod
# def _parseStateLine(line):
# """Parse a state line
#
# Using \ for escape any special control characters. Following are
# special control characters:
# , - state separator
# # - will be use as inline comment
# """
# escape=''
# states=[]
#
# for c in line:
# if c in ('\n', '\r'):
# continue
# elif escape:
# cc = c
# escape=''
# elif c == '#':
# # Ignore inline commenting
# break
# elif c == '\\':
# escape=c
# continue
# elif c == ',':
# states.append('')
# continue
# else:
# cc = c
#
# states[-1] = states[-1] + cc
#
# if escape and (escape not in charSet):
# states[-1] = states[-1] + escape
#
# return map(int, states)