rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
FixedTargetTest.__init__(self, targets)
FixedTargetTest.__init__(self, utargets)
def __init__(self, targets): BaseHTMLTest.__init__(self) utargets = [t for t in targets if self._is_useable_url(t, ['http'])] FixedTargetTest.__init__(self, targets)
utargets = [t for t in targets if self._is_useable_url(t)] FixedTargetTest.__init__(self, targets)
utargets = [t for t in targets if self._is_useable_url(t, [''])] FixedTargetTest.__init__(self, utargets)
def __init__(self, targets): BaseSSLTest.__init__(self) utargets = [t for t in targets if self._is_useable_url(t)] FixedTargetTest.__init__(self, targets)
if 100.0/conf.siterate > r.site_result_rate[1]:
if r.site_result_rate[0] and \ 100.0/conf.siterate > (1.0*r.site_result_rate[1])/r.site_result_rate[0]:
def main(argv): now = time.time() conf=SIConf(argv) dh = DataHandler(conf.use_dir) if conf.use_file: results = [dh.getResult(conf.use_file)] elif conf.node: results = dh.filterByNode(dh.getAll(), conf.node) else: results = dh.getAll() if conf.sortby == "url": results.sort(lambda x, y: cmp(x.site, y.site)) elif conf.s...
if 100.0/(100-conf.exitrate) > r.exit_result_rate[1]:
if r.exit_result_rate[0] and \ 100.0/(100-conf.exitrate) > \ (1.0*r.exit_result_rate[1])/r.exit_result_rate[0]:
def main(argv): now = time.time() conf=SIConf(argv) dh = DataHandler(conf.use_dir) if conf.use_file: results = [dh.getResult(conf.use_file)] elif conf.node: results = dh.filterByNode(dh.getAll(), conf.node) else: results = dh.getAll() if conf.sortby == "url": results.sort(lambda x, y: cmp(x.site, y.site)) elif conf.s...
self.rescan_nodes.add(r.exit_node[1:])
self.rescan_nodes.add(r.exit_node)
def load_rescan(self, type, since=None): self.rescan_nodes = set([]) results = datahandler.getAll() for r in results: if r.status == type: if not since or r.timestamp >= since: self.rescan_nodes.add(r.exit_node[1:]) plog("INFO", "Loaded "+str(len(self.rescan_nodes))+" nodes to rescan") if self.nodes and self.rescan_nod...
reason=None, exit_ip=None, exit_cert_pem=None):
reason=None, resolved_ip=0, exit_cert_pem=None):
def __init__(self, exit_obj, ssl_site, ssl_file, status, reason=None, exit_ip=None, exit_cert_pem=None): super(SSLTestResult, self).__init__(exit_obj, ssl_site, status, reason) self.ssl_file = ssl_file self.exit_cert = exit_cert_pem # Meh, not that much space self.exit_ip = exit_ip # XXX: Wrong! self.proto = "ssl"
self.exit_ip = exit_ip
self.resolved_ip = resolved_ip
def __init__(self, exit_obj, ssl_site, ssl_file, status, reason=None, exit_ip=None, exit_cert_pem=None): super(SSLTestResult, self).__init__(exit_obj, ssl_site, status, reason) self.ssl_file = ssl_file self.exit_cert = exit_cert_pem # Meh, not that much space self.exit_ip = exit_ip # XXX: Wrong! self.proto = "ssl"
if self.exit_ip: ret += "\nExit node's cert for "+self.exit_ip+":\n"
if self.resolved_ip: ret += "\nExit node's cert for "+self.resolved_ip+":\n"
def __str__(self): ret = TestResult.__str__(self) ssl_domain = SnakePickler.load(self.ssl_file) ret += " Rotates: "+str(ssl_domain.cert_rotates) ret += " Changed: "+str(ssl_domain.cert_changed)+"\n" if self.verbose: if self.exit_cert: for cert in ssl_domain.cert_map.iterkeys(): ret += "\nCert for "+ssl_domain.cert_map[...
raise NotImplemented() def get_targets(self): raise NotImplemented()
raise NotImplementedError()
def run_test(self): raise NotImplemented()
def refill_targets(self): if len(self.targets) < self.min_targets: plog("NOTICE", self.proto+" scanner short on targets. Adding more") self.targets.extend(self.get_targets()) def _remove_target_addr(self, target): if target in self.targets: self.targets.remove(target)
def refill_targets(self): if len(self.targets) < self.min_targets: plog("NOTICE", self.proto+" scanner short on targets. Adding more") self.targets.extend(self.get_targets())
self._remove_target_addr(target)
if target in self.targets: self.targets.remove(target)
def remove_target(self, target, reason="None"): self.banned_targets.add(target) self.refill_targets() self._remove_target_addr(target) if target in self.dynamic_fails: del self.dynamic_fails[target] if target in self.successes: del self.successes[target] if target in self.exit_fails: del self.exit_fails[target] if targ...
class SearchBasedTest(Test): def __init__(self, proto, port, wordlist_file): self.wordlist_file = wordlist_file Test.__init__(self, proto, port) def rewind(self): self.wordlist = load_wordlist(self.wordlist_file) Test.rewind(self) def _is_useable_url(self, url, valid_schemes=None, filetypes=None): (scheme, netloc, pa...
class BaseHTTPTest(Test): def __init__(self, filetypes=scan_filetypes):
def register_dynamic_failure(self, result): if self.rescan_nodes: result.from_rescan = True self.results.append(result) datahandler.saveResult(result) if result.site in self.dynamic_fails: self.dynamic_fails[result.site].add(result.exit_node) else: self.dynamic_fails[result.site] = set([result.exit_node])
SearchBasedTest.__init__(self, "HTTP", 80, wordlist)
Test.__init__(self, "HTTP", 80)
def __init__(self, wordlist, filetypes=scan_filetypes): # FIXME: Handle http urls w/ non-80 ports.. SearchBasedTest.__init__(self, "HTTP", 80, wordlist) self.fetch_targets = urls_per_filetype self.httpcode_fails = {} self.scan_filetypes = filetypes
def _reset(self): SearchBasedTest._reset(self) self.targets = {} def rewind(self): SearchBasedTest.rewind(self) self.httpcode_fails = {}
def __init__(self, wordlist, filetypes=scan_filetypes): # FIXME: Handle http urls w/ non-80 ports.. SearchBasedTest.__init__(self, "HTTP", 80, wordlist) self.fetch_targets = urls_per_filetype self.httpcode_fails = {} self.scan_filetypes = filetypes
n_tests = random.choice(xrange(1,len(self.targets)+1)) filetypes = random.sample(self.targets.keys(), n_tests)
typed_targets = {} for target in self.targets: for ftype in self.scan_filetypes: if target[-len(ftype):] == ftype: typed_targets.setdefault(ftype,[]) typed_targets[ftype].append(target) n_tests = random.choice(xrange(1,len(typed_targets)+1)) filetypes = random.sample(typed_targets.keys(), n_tests)
def run_test(self): # A single test should have a single cookie jar self.tor_cookie_jar = cookielib.MozillaCookieJar() self.cookie_jar = cookielib.MozillaCookieJar() self.headers = copy.copy(firefox_headers) self.tests_run += 1
address = random.choice(self.targets[ftype])
address = random.choice(typed_targets[ftype])
def run_test(self): # A single test should have a single cookie jar self.tor_cookie_jar = cookielib.MozillaCookieJar() self.cookie_jar = cookielib.MozillaCookieJar() self.headers = copy.copy(firefox_headers) self.tests_run += 1
def _remove_target_addr(self, target): for ftype in self.targets: if target in self.targets[ftype]: self.targets[ftype].remove(target)
def _remove_target_addr(self, target): for ftype in self.targets: if target in self.targets[ftype]: self.targets[ftype].remove(target)
SearchBasedTest.remove_target(self, address, reason)
Test.remove_target(self, address, reason)
def remove_target(self, address, reason): SearchBasedTest.remove_target(self, address, reason) if address in self.httpcode_fails: del self.httpcode_fails[address]
def refill_targets(self): for ftype in self.targets: if len(self.targets[ftype]) < self.fetch_targets: plog("NOTICE", self.proto+" scanner short on "+ftype+" targets. Adding more") raw_urls = self.get_search_urls('http', self.fetch_targets, filetypes=[ftype]) self.targets[ftype].extend(raw_urls) def get_targets(self)...
def refill_targets(self): for ftype in self.targets: if len(self.targets[ftype]) < self.fetch_targets: plog("NOTICE", self.proto+" scanner short on "+ftype+" targets. Adding more") raw_urls = self.get_search_urls('http', self.fetch_targets, filetypes=[ftype]) self.targets[ftype].extend(raw_urls)
SearchBasedTest.remove_false_positives(self)
Test.remove_false_positives(self)
def remove_false_positives(self): SearchBasedTest.remove_false_positives(self) self._remove_false_positive_type(self.httpcode_fails, FALSEPOSITIVE_HTTPERRORS, max_httpcode_fail_pct)
tot_cnt = SearchBasedTest.site_tests(self, site)
tot_cnt = Test.site_tests(self, site)
def site_tests(self, site): tot_cnt = SearchBasedTest.site_tests(self, site) if site in self.httpcode_fails: tot_cnt += len(self.httpcode_fails[site]) return tot_cnt
class HTMLTest(HTTPTest): def __init__(self, wordlist, recurse_filetypes=scan_filetypes): HTTPTest.__init__(self, wordlist, recurse_filetypes)
class BaseHTMLTest(BaseHTTPTest): def __init__(self, recurse_filetypes=scan_filetypes): BaseHTTPTest.__init__(self, recurse_filetypes)
def _check_http_worker(self, address, http_ret): (mime_type,pcontent,psha1sum,content,sha1sum,content_new,sha1sum_new,exit_node) = http_ret address_file = DataHandler.safeFilename(address[7:]) content_prefix = http_content_dir+address_file failed_prefix = http_failed_dir+address_file
def _reset(self): HTTPTest._reset(self) self.targets = [] self.soupdiffer_files = {} self.jsdiffer_files = {} def depickle_upgrade(self): if self._pickle_revision < 2: self.soupdiffer_files = {} self.jsdiffer_files = {} SearchBasedTest.depickle_upgrade(self)
def _reset(self): HTTPTest._reset(self) self.targets = [] # FIXME: Lame.. self.soupdiffer_files = {} # XXX: These two are now deprecated self.jsdiffer_files = {}
def _remove_target_addr(self, target): Test._remove_target_addr(self, target) if target in self.soupdiffer_files: del self.soupdiffer_files[target] if target in self.jsdiffer_files: del self.jsdiffer_files[target] def refill_targets(self): Test.refill_targets(self) def get_targets(self): return self.get_search_urls('...
def run_test(self): # A single test should have a single cookie jar self.tor_cookie_jar = cookielib.MozillaCookieJar() self.cookie_jar = cookielib.MozillaCookieJar() self.headers = copy.copy(firefox_headers)
class SSLTest(SearchBasedTest): def __init__(self, wordlist):
class BaseSSLTest(Test): def __init__(self): Test.__init__(self, "SSL", 443)
def _check_html_worker(self, address, http_ret): (mime_type,tor_html,tsha,orig_html,osha,new_html,nsha,exit_node)=http_ret
SearchBasedTest.__init__(self, "SSL", 443, wordlist)
def __init__(self, wordlist): self.test_hosts = num_ssl_hosts SearchBasedTest.__init__(self, "SSL", 443, wordlist)
def get_targets(self): return self.get_search_urls('https', self.test_hosts, True, search_mode=google_search_mode)
def run_test(self): self.tests_run += 1 return self.check_ssl(random.choice(self.targets))
opts = ['ssl','rescan', 'pernode=', 'resume=', 'html','http','ssh','smtp','pop','imap','dns','dnsrebind','policies','exit=']
opts = ['ssl','rescan', 'pernode=', 'resume=', 'html','http','ssh','smtp','pop','imap','dns','dnsrebind','policies','exit=','target=']
def main(argv): # make sure we have something to test for if len(argv) < 2: print '' print 'Please provide at least one test option:' print '--pernode <n>' print '--resume [<n>]' print '--rescan [<n>]' print '--ssl' print '--http' print '--html'
tests["SSL"] = SSLTest(ssl_wordlist_file)
tests["SSL"] = SearchBasedSSLTest(ssl_wordlist_file)
def main(argv): # make sure we have something to test for if len(argv) < 2: print '' print 'Please provide at least one test option:' print '--pernode <n>' print '--resume [<n>]' print '--rescan [<n>]' print '--ssl' print '--http' print '--html'
tests["HTTP"] = HTTPTest(filetype_wordlist_file)
tests["HTTP"] = SearchBasedHTTPTest(filetype_wordlist_file)
def main(argv): # make sure we have something to test for if len(argv) < 2: print '' print 'Please provide at least one test option:' print '--pernode <n>' print '--resume [<n>]' print '--rescan [<n>]' print '--ssl' print '--http' print '--html'
tests["HTML"] = HTMLTest(html_wordlist_file)
tests["HTML"] = SearchBasedHTMLTest(html_wordlist_file)
def main(argv): # make sure we have something to test for if len(argv) < 2: print '' print 'Please provide at least one test option:' print '--pernode <n>' print '--resume [<n>]' print '--rescan [<n>]' print '--ssl' print '--http' print '--html'
self.targets_by_type = dict.fromkeys(self.scan_filetypes, [])
self.targets_by_type = {}
def _reset(self): self.httpcode_fails = {} self.httpcode_fails_per_exit = {} self.targets_by_type = dict.fromkeys(self.scan_filetypes, []) Test._reset(self)
def add_target(self, target): pass
def add_target(self, target): pass
for ftype in self.targets_by_type: if len(self.targets_by_type[ftype]) < self.fetch_targets:
for ftype in self.scan_filetypes: if not ftype in self.targets_by_type or len(self.targets_by_type[ftype]) < self.fetch_targets:
def refill_targets(self): for ftype in self.targets_by_type: if len(self.targets_by_type[ftype]) < self.fetch_targets: plog("NOTICE", self.proto+" scanner short on "+ftype+" targets. Adding more") # :-\ - This swapping out result_filetypes thing is a hack. tmp = self.result_filetypes self.result_filetypes = [ftype] map...
def add_target(self, target, type=None): if type is None: split = target.rsplit('.',1) if len(split) > 1: type = split[-1] if type in self.scan_filetypes: self.targets.append(target) self.targets_by_type[type].append(target)
def refill_targets(self): for ftype in self.targets_by_type: if len(self.targets_by_type[ftype]) < self.fetch_targets: plog("NOTICE", self.proto+" scanner short on "+ftype+" targets. Adding more") # :-\ - This swapping out result_filetypes thing is a hack. tmp = self.result_filetypes self.result_filetypes = [ftype] map...
if len(split) > 1 and split[-1] in self.targets_by_type:
if len(split) > 1 and split[-1] in self.scan_filetypes:
def get_targets(self): raw_urls = self.get_search_urls() new = {} for url in raw_urls: split = url.rsplit('.',1) # Try to get filetype if len(split) > 1 and split[-1] in self.targets_by_type: new.setdefault(split[-1],[]).append(url) for k,v in new.items(): self.targets_by_type[k].extend(v) return raw_urls
self.targets_by_type[k].extend(v)
self.targets_by_type.setdefault(k, []).extend(v)
def get_targets(self): raw_urls = self.get_search_urls() new = {} for url in raw_urls: split = url.rsplit('.',1) # Try to get filetype if len(split) > 1 and split[-1] in self.targets_by_type: new.setdefault(split[-1],[]).append(url) for k,v in new.items(): self.targets_by_type[k].extend(v) return raw_urls
if conf.confirmed != r.confirmed: continue
if conf.confirmed != r.from_rescan: continue
def main(argv): now = time.time() conf=SIConf(argv) dh = DataHandler(conf.use_dir) if conf.use_file: results = [dh.getResult(conf.use_file)] elif conf.node: results = dh.filterByNode(dh.getAll(), conf.node) else: results = dh.getAll() if conf.sortby == "url": results.sort(lambda x, y: cmp(x.site, y.site)) elif conf.s...
def remove_target(self, target):
def remove_target(self, target, reason="None"):
def remove_target(self, target): if target in self.targets: self.targets.remove(target) # I'm not trusting the target's extension here. Should # give us a little more flexibility w/o much overhead. for k,v in self.targets_by_type.items(): if target in v: v.remove(target) Test.remove_target(self, target)
for k,v in new:
for k,v in new.items():
def get_targets(self): raw_urls = self.get_search_urls() new = {} for url in raw_urls: split = url.rsplit('.',1) # Try to get filetype if len(split) > 1 and split[-1] in self.targets_by_type: new.setdefault(split[-1],[]).append(url) for k,v in new: self.targets_by_type[k].extend(v) return raw_urls
guards = get_guards(2-len(self.up_guards))
guards = get_guards(self.c, 2-len(self.up_guards))
def guard_event(self, event): changed = False plog("NOTICE", "Guard $"+event.idhex+" is "+event.status) # XXX: remove from our list of guards and get a new one if event.status == "DOWN": if event.idhex in self.up_guards: self.down_guards[event.idhex] = self.up_guards[event.idhex] del self.up_guards[event.idhex] # If mo...
guards = get_guards(1)
guards = get_guards(self.c, 1)
def guard_event(self, event): changed = False plog("NOTICE", "Guard $"+event.idhex+" is "+event.status) # XXX: remove from our list of guards and get a new one if event.status == "DOWN": if event.idhex in self.up_guards: self.down_guards[event.idhex] = self.up_guards[event.idhex] del self.up_guards[event.idhex] # If mo...
plog("NOTICE", "Setting guards: "+guard_str) self.c.setcont("EntryNodes", guard_str)
plog("NOTICE", "Setting new guards: "+guard_str) self.c.set_option("EntryNodes", guard_str)
def guard_event(self, event): changed = False plog("NOTICE", "Guard $"+event.idhex+" is "+event.status) # XXX: remove from our list of guards and get a new one if event.status == "DOWN": if event.idhex in self.up_guards: self.down_guards[event.idhex] = self.up_guards[event.idhex] del self.up_guards[event.idhex] # If mo...
self.circs[circ_event.circ_id] = circ_event.status self.built_circs[circ_event.circ_id] = True self.c.close_circuit(circ_event.circ_id)
def circ_status_event(self, circ_event): if circ_event.status == 'LAUNCHED': self.circs[circ_event.circ_id] = circ_event.status self.circ_times[circ_event.circ_id] = CircTime(circ_event.arrived_at) self.live_circs[circ_event.circ_id] = True elif circ_event.status == 'BUILT': self.circs[circ_event.circ_id] = circ_event....
plog("INFO", "Closing circuit "+str(circ_event.circ_id)+" with build time of "+str(self.circ_times[circ_event.circ_id].end_time-self.circ_times[circ_event.circ_id].start_time))
buildtime = self.circ_times[circ_event.circ_id].end_time-self.circ_times[circ_event.circ_id].start_time plog("INFO", "Closing circuit "+str(circ_event.circ_id)+" with build time of "+str(buildtime)) self.buildtimes_file.write("BUILT "+str(circ_event.circ_id) +" "+str(buildtime)+"\n")
def circ_status_event(self, circ_event): if circ_event.status == 'LAUNCHED': self.circs[circ_event.circ_id] = circ_event.status self.circ_times[circ_event.circ_id] = CircTime(circ_event.arrived_at) self.live_circs[circ_event.circ_id] = True elif circ_event.status == 'BUILT': self.circs[circ_event.circ_id] = circ_event....
self.circs[circ_event.circ_id] = circ_event.status if circ_event.circ_id in self.live_circs: del self.live_circs[circ_event.circ_id] if circ_event.reason == 'TIMEOUT': self.timeout_circs[circ_event.circ_id] = True if circ_event.circ_id in self.circ_times:
if circ_event.circ_id in self.circ_times: self.circs[circ_event.circ_id] = circ_event.status if circ_event.circ_id in self.live_circs: del self.live_circs[circ_event.circ_id] if circ_event.reason == 'TIMEOUT': self.timeout_circs[circ_event.circ_id] = True
def circ_status_event(self, circ_event): if circ_event.status == 'LAUNCHED': self.circs[circ_event.circ_id] = circ_event.status self.circ_times[circ_event.circ_id] = CircTime(circ_event.arrived_at) self.live_circs[circ_event.circ_id] = True elif circ_event.status == 'BUILT': self.circs[circ_event.circ_id] = circ_event....
plog("INFO", circ_event.status+" timeout circuit "+str(circ_event.circ_id)+" with build time of "+str(self.circ_times[circ_event.circ_id].end_time-self.circ_times[circ_event.circ_id].start_time)) else: self.closed_circs[circ_event.circ_id] = True
buildtime = self.circ_times[circ_event.circ_id].end_time-self.circ_times[circ_event.circ_id].start_time plog("INFO", circ_event.status+" timeout circuit "+str(circ_event.circ_id)+" with build time of "+str(buildtime)) self.buildtimes_file.write("TIMEOUT "+str(circ_event.circ_id) +" "+str(buildtime)+"\n") else: self.clo...
def circ_status_event(self, circ_event): if circ_event.status == 'LAUNCHED': self.circs[circ_event.circ_id] = circ_event.status self.circ_times[circ_event.circ_id] = CircTime(circ_event.arrived_at) self.live_circs[circ_event.circ_id] = True elif circ_event.status == 'BUILT': self.circs[circ_event.circ_id] = circ_event....
fuzzy_last = int(round(self.buildtimeout_fuzzy.timeout_ms, -3)) fuzzy_curr = int(round(bt_event.timeout_ms, -3))
fuzzy_last = int(self.buildtimeout_fuzzy.timeout_ms) fuzzy_curr = int(bt_event.timeout_ms)
def buildtimeout_set_event(self, bt_event): plog("INFO", "Got buildtimeout event: "+bt_event.set_type+" TOTAL_TIMES=" +str(bt_event.total_times)+" TIMEOUT_MS=" +str(bt_event.timeout_ms))
if fuzzy_diff > 1000:
if fuzzy_diff > self.buildtimeout_fuzzy.timeout_ms*FUZZY_DEV:
def buildtimeout_set_event(self, bt_event): plog("INFO", "Got buildtimeout event: "+bt_event.set_type+" TOTAL_TIMES=" +str(bt_event.total_times)+" TIMEOUT_MS=" +str(bt_event.timeout_ms))
strict_last = int(round(self.buildtimeout_strict.timeout_ms, -3)) strict_curr = int(round(bt_event.timeout_ms, -3))
strict_last = int(self.buildtimeout_strict.timeout_ms) strict_curr = int(bt_event.timeout_ms)
def buildtimeout_set_event(self, bt_event): plog("INFO", "Got buildtimeout event: "+bt_event.set_type+" TOTAL_TIMES=" +str(bt_event.total_times)+" TIMEOUT_MS=" +str(bt_event.timeout_ms))
if strict_diff > 0:
if strict_diff > self.buildtimeout_strict.timeout_ms*STRICT_DEV:
def buildtimeout_set_event(self, bt_event): plog("INFO", "Got buildtimeout event: "+bt_event.set_type+" TOTAL_TIMES=" +str(bt_event.total_times)+" TIMEOUT_MS=" +str(bt_event.timeout_ms))
if (self.cond.min_circs and self.strict_streak_count >= self.total_times*STREAK_RATIO):
if (self.cond.min_circs and self.strict_streak_count >= self.total_times*STRICT_RATIO):
def buildtimeout_set_event(self, bt_event): plog("INFO", "Got buildtimeout event: "+bt_event.set_type+" TOTAL_TIMES=" +str(bt_event.total_times)+" TIMEOUT_MS=" +str(bt_event.timeout_ms))
t = c.launch_thread()
def open_controller(filename): """ starts stat gathering thread """ s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((TorUtil.control_host,TorUtil.control_port)) c = TorCtl.Connection(s) t = c.launch_thread() c.authenticate_cookie(file("./tor-data/control_auth_cookie", "r")) c.debug(file(filename+".log",...
out = file(output_dir+"/result", "a") out.write("NUM_CIRCS: "+str(cond.min_circs)) out.write("MIN_CIRCS: "+str(cond.num_circs))
out = file(output_dir+"/result", "w") out.write("NUM_CIRCS: "+str(cond.min_circs)+"\n") out.write("MIN_CIRCS: "+str(cond.num_circs)+"\n") timeout_cnt = len(h.timeout_circs) built_cnt = len(h.built_circs) build_rate = float(built_cnt)/(built_cnt+timeout_cnt) out.write("BUILD_RATE: "+str(built_cnt)+"/"+str(built_cnt+time...
def open_controller(filename): """ starts stat gathering thread """ s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((TorUtil.control_host,TorUtil.control_port)) c = TorCtl.Connection(s) t = c.launch_thread() c.authenticate_cookie(file("./tor-data/control_auth_cookie", "r")) c.debug(file(filename+".log",...
elif o == '-r': redo_run = True
def getargs(): if len(sys.argv[1:]) < 3: usage() sys.exit(2) try: opts,args = getopt.getopt(sys.argv[1:],"p:o:b:fmr") except getopt.GetoptError,err: print str(err) usage() global pct_start global output_dir for o,a in opts: if o == '-p': pct_start = int(a) elif o == '-o': output_dir = a # XXX: -r retest else: assert ...
return (output_dir, pct_start)
return (output_dir, pct_start, redo_run)
def getargs(): if len(sys.argv[1:]) < 3: usage() sys.exit(2) try: opts,args = getopt.getopt(sys.argv[1:],"p:o:b:fmr") except getopt.GetoptError,err: print str(err) usage() global pct_start global output_dir for o,a in opts: if o == '-p': pct_start = int(a) elif o == '-o': output_dir = a # XXX: -r retest else: assert ...
ret += " Exit: "+socket.inet_ntoa(struct.pack(">I",self.exit_obj.ip))+" "+self.exit_node+" ("+self.exit_name+")\n"
ret += " Exit: "+socket.inet_ntoa(struct.pack(">I",self.exit_ip))+" "+self.exit_node+" ("+self.exit_name+")\n"
def __str__(self): ret = self.__class__.__name__+" for "+self.site+"\n" ret += " Time: "+time.ctime(self.timestamp)+"\n" ret += " Exit: "+socket.inet_ntoa(struct.pack(">I",self.exit_obj.ip))+" "+self.exit_node+" ("+self.exit_name+")\n" ret += " Contact: "+str(self.contact)+"\n" ret += " "+str(RESULT_STRINGS[self.status...
else:
self.cond.num_circs = 0 elif not self.cond.num_circs:
def buildtimeout_set_event(self, bt_event): plog("INFO", "Got buildtimeout event: "+bt_event.set_type+" TOTAL_TIMES=" +str(bt_event.total_times)+" TIMEOUT_MS=" +str(bt_event.timeout_ms)) self.timeouts_file.write(bt_event.set_type+" " +str(bt_event.total_times)+" "+str(bt_event.timeout_ms)+"\n")
shutil.copyfile('./tor-data/state', output_dir+"/state.full") self.cond.acquire() self.cond.num_circs = self.reset_total+self.total_times-\ self.strict_streak_count self.cond.num_timeout = bt_event.timeout_ms self.cond.notify() self.cond.release()
if not redo_run: shutil.copyfile('./tor-data/state', output_dir+"/state.full") self.cond.acquire() self.cond.num_circs = self.reset_total+self.total_times-\ self.strict_streak_count self.cond.num_timeout = bt_event.timeout_ms self.cond.notify() self.cond.release()
def buildtimeout_set_event(self, bt_event): plog("INFO", "Got buildtimeout event: "+bt_event.set_type+" TOTAL_TIMES=" +str(bt_event.total_times)+" TIMEOUT_MS=" +str(bt_event.timeout_ms)) self.timeouts_file.write(bt_event.set_type+" " +str(bt_event.total_times)+" "+str(bt_event.timeout_ms)+"\n")
out.write("MIN_CIRCS: "+str(cond.min_circs)+"\n") out.write("MIN_TIMEOUT: "+str(cond.min_timeout)+"\n")
if not redo_run: out.write("MIN_CIRCS: "+str(cond.min_circs)+"\n") out.write("MIN_TIMEOUT: "+str(cond.min_timeout)+"\n")
def open_controller(filename): """ starts stat gathering thread """ s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((TorUtil.control_host,TorUtil.control_port)) c = TorCtl.Connection(s) c.authenticate_cookie(file("./tor-data/control_auth_cookie", "r")) c.debug(file(filename+".log", "w", buffering=0)) g...
return (0, int(str(start_date - today).split('.')[0]))
return (0, int(str(self.start_date - today).split('.')[0]))
def get_days_left(self): """ Returns the remaining days for the consultation or the number of days before it starts """
value = widget.default
if widget.data_type == 'list': value = [widget.default, ] else: value = widget.default
def processForm(self, form, _all_values=True): """ Parse the given form against this schema, do validation, then return the data and any errors """
return sorted(p_list, key=lambda obj: isinstance(obj, str) and \ force_to_unicode(getattr(obj, p_attr, '')) or \ getattr(obj, p_attr, None), reverse=bool(p_desc))
def sort_key(obj): attr = getattr(obj, p_attr, None) if isinstance(attr, basestring): return force_to_unicode(attr) else: return attr return sorted(p_list, key=sort_key, reverse=bool(p_desc))
def utSortObjsListByAttr(self, p_list, p_attr, p_desc=1): """Sort a list of objects by an attribute values""" return sorted(p_list, key=lambda obj: isinstance(obj, str) and \ force_to_unicode(getattr(obj, p_attr, '')) or \ getattr(obj, p_attr, None), reverse=bool(p_desc))
_pin_add = PageTemplateFile('zpt/pin_add', globals())
_pin_add = ViewPageTemplateFile('zpt/pin_add.zpt', globals())
def convert_to_datetime(date_index_val): year = date_index_val / 535680 month = (date_index_val / 44640) % 12 day = (date_index_val / 1440) % 31 hour = (date_index_val / 60) % 24 minute = date_index_val % 60 return datetime(year, month, day, hour, minute)
html = self._pin_add.__of__(self.context)(latitude=latitude, longitude=longitude, address=address, country=country, type=type)
html = self._pin_add(latitude=latitude, longitude=longitude, address=address, country=country, type=type)
def pin_add(self, latitude, longitude, REQUEST, type=None): """ """ lat, lon = float(latitude), float(longitude) author, session_key = self.get_author_and_session(REQUEST)
_cluster_index = PageTemplateFile('zpt/cluster_index', globals())
_cluster_index = ViewPageTemplateFile('zpt/cluster_index.zpt', globals())
def pin_add(self, latitude, longitude, REQUEST, type=None): """ """ lat, lon = float(latitude), float(longitude) author, session_key = self.get_author_and_session(REQUEST)
group_users = [x.split(',')[0].split('=')[1] for x in result['results'][result['size']-1]['uniqueMember']]
group_user_members = result['results'][result['size']-1]['uniqueMember'] group_users = [] for member in group_user_members: try: uid = member.split(',')[0].split('=')[1] except IndexError, e: auth_logger.exception("Can't parse the uid " "(skipping member %s)", member) else: group_users.append(uid)
def group_member_ids(self, group): if not hasattr(self, '_v_ldap_groups_cache'): cache = self._v_ldap_groups_cache = {} cache = self._v_ldap_groups_cache ldap_folder = self.getUserFolder() root_dn = self.getRootDN(ldap_folder) scope = self.getGroupScope(ldap_folder) if not cache.get(group, {}): result = self.delegate.s...
"id=%(source_id)s&params=uid&term=%(userid)s&search_user=Search&"
"id=%(source_id)s&s=assign_to_users&params=uid&term=%(userid)s&search_user=Search&"
def request_ig_access(self, REQUEST): """ Called when `request_ig_access_html` submits. Sends a mail to the portal administrator informing that the current user has requested elevated access. """ role = REQUEST.form.get('role', '') location = REQUEST.form.get('location', '') sources = self.getAuthenticationTool().getSo...
rating = round(self.averageRating)
rating = int(round(self.averageRating))
def __call__(self, REQUEST, RESPONSE): rating = round(self.averageRating) if not (0 <= rating < 5): raise RatingOutOfBoundsError(rating)
file_type = REQUEST.get('file_type', 'csv')
file_type = REQUEST.get('file_type', 'CSV')
def download(self, REQUEST=None, RESPONSE=None): """returns all the answers in a csv file"""
self.cleanup_blob_patch = patch_testing_db()
def setUp(self): from Products.ExtFile import ExtFile ExtFile.REPOSITORY_PATH = ['var', 'testing'] self.cleanup_blob_patch = patch_testing_db()
self.cleanup_blob_patch()
cleanup_blob_patch()
def tearDown(self): self.mail_divert.restore() repository = os.path.join(INSTANCE_HOME, 'var', 'testing') if os.path.isdir(repository): import shutil shutil.rmtree(repository, 1) self.cleanup_blob_patch()
ws.write(current_row, 2, translator('Percent'), header_style)
ws.write(current_row, 3, translator('Percent'), header_style)
def add_to_excel(self, state): """ adds content to the excel file based on the specific statistic type """ import xlwt answers = state['answers'] ws = state['ws'] current_row = state['current_row'] translator = self.getSite().getPortalTranslations() total, answered, unanswered = self.calculate(self.question, answers)
month_folder = create_month_folder(self, contributor, schema_raw_data)
try: month_folder = create_month_folder(self, contributor, schema_raw_data) except: month_folder = self
def addNySemNews(self, id='', contributor=None, REQUEST=None, **kwargs): """ """ if REQUEST is not None: schema_raw_data = dict(REQUEST.form) else: schema_raw_data = kwargs #process parameters id = make_id(self, id=id, title=schema_raw_data.get('title', ''), prefix=PREFIX_OBJECT) if contributor is None: contributor = ...
return self.news_date
return getattr(self, 'news_date', None)
def resource_date(self): return self.news_date
schema_raw_data['title'] = schema_raw_data['title'].replace(self.id, id)
schema_raw_data['title'] = schema_raw_data.get('title', '').replace(self.id, id)
def process_add(self, REQUEST, **kwargs): """ """ schema_raw_data = dict(REQUEST.form) _lang = schema_raw_data.pop('_lang', schema_raw_data.pop('lang', None)) _releasedate = self.process_releasedate(schema_raw_data.pop('releasedate', ''), self.releasedate)
def test_aaaasearch_local_users(self):
def test_search_local_users(self):
def test_aaaasearch_local_users(self): """Search users using jquery ui autocomplete and normal search using form
self.selenium.add_selection("names", "label=user3")
self.selenium.add_selection("names", "label=User Three (user3)")
def test_assign_role(self): """Assign a role XXX: Do the jstree click """ self.selenium.open("/portal/admin_assignroles_html", True) self.selenium.add_selection("names", "label=user3") self.selenium.add_selection("//select[@name='roles']", 'Manager') self.selenium.type('location', "info") self.selenium.click("send_mail...
def search_directory(self, search_string='', REQUEST=None):
def search_directory(self, search_string=u'', REQUEST=None):
def search_directory(self, search_string='', REQUEST=None): """ """ users = self.get_users() if not search_string: user_list = users else: user_list = [user for user in users if \ search_string in user['firstname'] or \ search_string in user['lastname']] return self.index_html(user_list=user_list)
search_string in user['firstname'] or \ search_string in user['lastname']]
search_string in user['firstname'].lower() or \ search_string in user['lastname'].lower() or \ search_string in user['userid'].lower()]
def search_directory(self, search_string='', REQUEST=None): """ """ users = self.get_users() if not search_string: user_list = users else: user_list = [user for user in users if \ search_string in user['firstname'] or \ search_string in user['lastname']] return self.index_html(user_list=user_list)
for source in acl_tool.getSources(): if not isinstance(source, plugLDAPUserFolder): continue acl_folder = source.getUserFolder() individual_users = source.getUsersRoles(acl_folder).keys()
for source_id in self.sources.keys(): source = self.sources[source_id]['source'] individual_users = self.sources[source_id]['user_roles'].keys()
def get_users(self): if not hasattr(self, '_v_external_user_cache'): self._v_external_user_cache = {} cache = self._v_external_user_cache users = []
for group_id in source.get_groups_roles_map().keys(): group_users.extend(source.group_member_ids(group_id))
for group_id in self.sources[source_id]['group_map'].keys(): group_users.extend( source.group_member_ids(group_id) )
def get_users(self): if not hasattr(self, '_v_external_user_cache'): self._v_external_user_cache = {} cache = self._v_external_user_cache users = []
'firstname': user.firstname, 'lastname': user.lastname,
'firstname': handle_unicode(user.firstname), 'lastname': handle_unicode(user.lastname),
def get_users(self): if not hasattr(self, '_v_external_user_cache'): self._v_external_user_cache = {} cache = self._v_external_user_cache users = []
'firstname': user['givenName'], 'lastname': user['sn'],
'firstname': handle_unicode(user['givenName']), 'lastname': handle_unicode(user['sn']),
def get_users(self): if not hasattr(self, '_v_external_user_cache'): self._v_external_user_cache = {} cache = self._v_external_user_cache users = []
'postal_address': user.get('postalAddress', 'N/A'),
'postal_address': handle_unicode( user.get('postalAddress', 'N/A') ),
def get_users(self): if not hasattr(self, '_v_external_user_cache'): self._v_external_user_cache = {} cache = self._v_external_user_cache users = []
if not hasattr(self, '_v_individual_users_roles'): self._v_individual_users_roles = None source_uf = source.getUserFolder() if not self._v_individual_users_roles: self._v_individual_users_roles = source.getUsersRoles(source_uf) individual_ldap_users = self._v_individual_users_roles group_to_role_mapping = source.get_gr...
individual_ldap_users = self.sources[source.id]['user_roles'] group_to_role_mapping = self.sources[source.id]['group_map']
def get_external_user_roles(self, source, userid): if not hasattr(self, '_v_individual_users_roles'): self._v_individual_users_roles = None source_uf = source.getUserFolder() if not self._v_individual_users_roles: self._v_individual_users_roles = source.getUsersRoles(source_uf) individual_ldap_users = self._v_individua...
user_details = PageTemplateFile('zpt/directory_user_details', globals())
def is_member(self): return self.get_user_access() in ['member', 'admin']
self.selenium.click( "//div[@class='datatable']/table/tbody/tr[last()]/td/input") username = self.selenium.get_text( "//div[@class='datatable']/table/tbody/tr[last()]/td[2]")
last_row = "//table[contains(@class, 'datatable')]/tbody/tr[last()]" self.selenium.click("%s/td/input" % last_row) username = self.selenium.get_text("%s/td[2]" % last_row)
def test_delete_user(self): self.selenium.open("/portal/admin_local_users_html", True) #Check the last user checkbox self.selenium.click( "//div[@class='datatable']/table/tbody/tr[last()]/td/input") username = self.selenium.get_text( "//div[@class='datatable']/table/tbody/tr[last()]/td[2]") self.selenium.click("css=.de...
'//div[@class="datatable"]/table/tbody/tr[last()]/td[2]') ==\
"//table[contains(@class, 'datatable')]/tbody/tr[last()]//td[2]") ==\
def check_result(user): "Check if the user is alone in the result list" #Also check if the the results are right assert self.selenium.get_text(\ '//div[@class="datatable"]/table/tbody/tr[last()]/td[2]') ==\ user
get_xpath_count('//div[@class="datatable"]/table/tbody/tr')) > 2
get_xpath_count('//table[contains(@class, "datatable")]/tbody/tr')) > 2
def check_result(user): "Check if the user is alone in the result list" #Also check if the the results are right assert self.selenium.get_text(\ '//div[@class="datatable"]/table/tbody/tr[last()]/td[2]') ==\ user
self.selenium.click("//input[@value='Add new role']")
self.selenium.click("//input[@value='Add']")
def test_add_role(self): self.selenium.open("/portal/admin_roles_html", True) self.selenium.type("//input[@id='input-role']", "SOMErOLE") self.selenium.click("//input[@value='Add new role']") self.selenium.wait_for_page_to_load("3000") assert self.selenium.is_text_present('SOMErOLE') self.selenium.open("/portal/admin_e...
last_row = "//div[@class='datatable']/table/tbody/tr[last()]"
last_row = "//table[contains(@class, 'datatable')]/tbody/tr[last()]"
def test_assign_role(self): """Assign a role XXX: Do the jstree click """ self.selenium.open("/portal/admin_assignroles_html", True) self.selenium.add_selection("names", "label=user3") self.selenium.add_selection("//select[@name='roles']", 'Manager') self.selenium.type('location', "info") self.selenium.click("//input[@...
source_obj = self.getSourceObj(source.getId()) groups_roles_map = source_obj.get_groups_roles_map() for group, roles in groups_roles_map.iteritems(): if source_obj.user_in_group(user, group):
if not hasattr(source, 'get_groups_roles_map'): continue for group, roles in source.get_groups_roles_map().iteritems(): if source.user_in_group(user, group):
def getAuthenticatedUserRoles(self, p_meta_types=None): """ Returns a list with all roles of the authenticated user.
key = KEYBASE + str(self.context)
key = self.KEYBASE + str(self.context)
def getContentKey(self): """Create a unique string to identify the content for a cookie key, hopefully this will work in zope 2 and 3.""" key = getattr(self, '_key_cache', None) if key: return key key = [] if not hasattr(self.context, '__parent__'): subloc = None else: subloc = ISublocations(self.context.__parent__, al...
key = KEYBASE + '-'.join(key)
key = self.KEYBASE + '-'.join(key)
def getContentKey(self): """Create a unique string to identify the content for a cookie key, hopefully this will work in zope 2 and 3.""" key = getattr(self, '_key_cache', None) if key: return key key = [] if not hasattr(self.context, '__parent__'): subloc = None else: subloc = ISublocations(self.context.__parent__, al...
if getattr(obj, 'approved', False):
if not getattr(obj, 'approved', False):
def getPublishedFolders(self): folders = [] for obj in self.objectValues(self.get_naaya_containers_metatypes()): if getattr(obj, 'approved', False): continue if getattr(obj, 'submitted', False): continue folders.append(obj) folders.sort(operator.attrgetter('sortorder')) return folders
if getattr(obj, 'submitted', False):
if not getattr(obj, 'submitted', False):
def getPublishedFolders(self): folders = [] for obj in self.objectValues(self.get_naaya_containers_metatypes()): if getattr(obj, 'approved', False): continue if getattr(obj, 'submitted', False): continue folders.append(obj) folders.sort(operator.attrgetter('sortorder')) return folders
if getattr(obj, 'approved', False):
if not getattr(obj, 'approved', False):
def getPublishedObjects(self, items=0): doc_metatypes = [m for m in self.get_meta_types() if m not in self.get_naaya_containers_metatypes()] result = [] for obj in self.objectValues(doc_metatypes): if getattr(obj, 'approved', False): continue if getattr(obj, 'submitted', False): continue result.append(obj)
if getattr(obj, 'submitted', False):
if not getattr(obj, 'submitted', False):
def getPublishedObjects(self, items=0): doc_metatypes = [m for m in self.get_meta_types() if m not in self.get_naaya_containers_metatypes()] result = [] for obj in self.objectValues(doc_metatypes): if getattr(obj, 'approved', False): continue if getattr(obj, 'submitted', False): continue result.append(obj)
def getUserAdditionalRoles(self, name): """ Returns a list with an user additional roles. """ r = [] for x in self.getAssignedUsers(): if x['username'] == name: for y in x['roles']: wg = self.getWorkgroupByLocation(y[1]) if wg: if wg[3] != y[0]: r.append(y) else: r.append(y) return r
def getUserAllRoles(self, name): """ Returns a list with all user roles (including local in all portal). """ for x in self.getAssignedUsers(): if x['username'] == name: return x['roles'] return []