def globalSecret(): global gSecret if not gSecret: # This always works... gSecret = '%8.8x%s%8.8x' % (random.randint( 0, 0x7FFFFFFE), time.time(), random.randint(0, 0x7FFFFFFE)) # Next, see if we can augment that with some real randomness. try: newSecret = sha1hex( s(open('/dev/urandom', 'rb').read(64)) + gSecret) gSecret = newSecret logging.LogDebug('Seeded signatures using /dev/urandom, hooray!') except: try: newSecret = sha1hex(s(os.urandom(64)) + gSecret) gSecret = newSecret logging.LogDebug( 'Seeded signatures using os.urandom(), hooray!') except: logging.LogInfo( 'WARNING: Seeding signatures with time.time() and random.randint()' ) return gSecret
def ParseRequest(self, line): self.method, self.path, self.version = line.split() if not self.method in HTTP_METHODS: logging.LogDebug('Invalid method: %s' % self.method) return False if not self.version.upper() in HTTP_VERSIONS: logging.LogDebug('Invalid version: %s' % self.version) return False self.state = self.IN_HEADERS return True
def Parse(self, line): BaseLineParser.Parse(self, line) if line in ('\n', '\r\n'): return True if self.state == IrcLineParser.WANT_USER: try: ocmd, arg = line.strip().split(' ', 1) cmd = ocmd.lower() self.seen.append(cmd) args = arg.split(' ') if cmd == 'pass': pass elif cmd in ('user', 'nick'): if '@' in args[0]: parts = args[0].split('@') self.domain = parts[-1] arg0 = '@'.join(parts[:-1]) elif 'nick' in self.seen and 'user' in self.seen and not self.domain: raise Error('No domain found') if self.domain: self.state = BaseLineParser.PARSE_OK self.lines[-1] = '%s %s %s\n' % (ocmd, arg0, ' '.join( args[1:])) else: self.state = BaseLineParser.PARSE_FAILED except Exception as err: logging.LogDebug('IRC parse failed: %s, %s, %s' % (self.state, err, self.lines)) self.state = BaseLineParser.PARSE_FAILED return (self.state != BaseLineParser.PARSE_FAILED)
def Cleanup(self, close=True): self.peeked = self.zw = '' self.Die(discard_buffer=True) if close: if self.fd: if logging.DEBUG_IO: self.LogDebug('Closing FD: %s' % self) self.fd.close() # Update DNS if necessary if hasattr(self, "backends"): if common.pko.dnsclient: try: for b in self.backends: domain = b.split(':')[1] logging.LogDebug("Deleting dynamic DNS name: %s" % domain) common.pko.dnsclient.delete_async(domain) except Exception as e: logging.LogError( "Could not delete dynamic DNS name: %s" % e) self.fd = None if not self.dead: self.dead = True self.CountAs('selectables_dead') if close: self.LogTraffic(final=True)
def ParseResponse(self, line): self.version, self.code, self.message = line.split(' ', 2) if not self.version.upper() in HTTP_VERSIONS: logging.LogDebug('Invalid version: %s' % self.version) return False self.state = self.IN_HEADERS return True
def performAuthChecks(self, scheme, netloc, path, qs): try: auth = self.headers.get('authorization') if auth: (how, ab64) = auth.strip().split() if how.lower() == 'basic': (username, password) = base64.decodestring(ab64).split(':') self.checkUsernamePasswordAuth(username, password) return True self.checkRequestAuth(scheme, netloc, path, qs) return True except (ValueError, KeyError, AuthError) as e: logging.LogDebug('HTTP Auth failed: %s' % e) else: logging.LogDebug('HTTP Auth failed: Unauthorized') self.sendResponse('<h1>Unauthorized</h1>\n', code=401, msg='Forbidden') return False
def Flush(self, loops=50, wait=False, allow_blocking=False): while (loops != 0 and len(self.write_blocked) > 0 and self.Send( [], try_flush=True, activity=False, allow_blocking=allow_blocking)): if wait and len(self.write_blocked) > 0: time.sleep(0.1) logging.LogDebug('Flushing...') loops -= 1 if self.write_blocked: return False return True
def getSelectableId(what): global SELECTABLES, SELECTABLE_ID, SELECTABLE_LOCK with SELECTABLE_LOCK: count = 0 while SELECTABLE_ID in SELECTABLES: SELECTABLE_ID += 1 SELECTABLE_ID %= 0x40000 if (SELECTABLE_ID % 0x00800) == 0: logging.LogDebug('Selectable map: %s' % (SELECTABLES, )) count += 1 if count > 0x40000: raise ValueError('Too many conns!') SELECTABLES[SELECTABLE_ID] = what return SELECTABLE_ID
def performAuthChecks(self, scheme, netloc, path, qs): try: auth = self.headers.get('authorization') if auth: (how, ab64) = auth.strip().split() if how.lower() == 'basic': (username, password) = base64.decodestring(ab64).split(':') self.checkUsernamePasswordAuth(username, password) return True self.checkRequestAuth(scheme, netloc, path, qs) return True except (ValueError, KeyError, AuthError), e: logging.LogDebug('HTTP Auth failed: %s' % e)
def getSelectableId(what): global SELECTABLES, SELECTABLE_ID, SELECTABLE_LOCK try: SELECTABLE_LOCK.acquire() count = 0 while SELECTABLE_ID in SELECTABLES: SELECTABLE_ID += 1 SELECTABLE_ID %= 0x10000 if (SELECTABLE_ID % 0x00800) == 0: logging.LogDebug('Selectable map: %s' % (SELECTABLES, )) count += 1 if count > 0x10001: raise ValueError('Too many conns!') SELECTABLES[SELECTABLE_ID] = what return SELECTABLE_ID finally: SELECTABLE_LOCK.release()
def Parse(self, line): BaseLineParser.Parse(self, line) try: if (self.state == self.IN_RESPONSE): return self.ParseResponse(line) elif (self.state == self.IN_REQUEST): return self.ParseRequest(line) elif (self.state == self.IN_HEADERS): return self.ParseHeader(line) elif (self.state == self.IN_BODY): return self.ParseBody(line) except ValueError, err: logging.LogDebug('Parse failed: %s, %s, %s' % (self.state, err, self.lines))
def Parse(self, line): BaseLineParser.Parse(self, line) self.last_parser = self.parsers[-1] for p in self.parsers[:]: if not p.Parse(line): self.parsers.remove(p) elif p.ParsedOK(): self.last_parser = p self.domain = p.domain self.protocol = p.protocol self.state = p.state self.parsers = [p] break if not self.parsers: logging.LogDebug('No more parsers!') return (len(self.parsers) > 0)
def handleHttpRequest(self, scheme, netloc, path, params, query, frag, qs, posted): data = { 'prog': self.server.pkite.progname, 'mimetype': self.getMimeType(path), 'hostname': socket.gethostname() or 'Your Computer', 'http_host': self.http_host, 'query_string': query, 'code': 200, 'body': '', 'msg': 'OK', 'now': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), 'ver': APPVER } for key in self.headers.keys(): data['http_' + key.lower()] = self.headers.get(key) if 'download' in qs: data['mimetype'] = 'application/octet-stream' # Would be nice to set Content-Disposition too. elif 'view' in qs: data['mimetype'] = 'text/plain' data['method'] = data.get('http_x-pagekite-proto', 'http').lower() if 'http_cookie' in data: cookies = Cookie.SimpleCookie(data['http_cookie']) else: cookies = {} # Do we expose the built-in console? console = self.host_config.get('console', False) console = "/home/jjmontes/git/PyPagekite/jsui" if path == self.host_config.get('yamon', False): if common.gYamon: data['body'] = common.gYamon.render_vars_text( qs.get('view', [None])[0]) else: data['body'] = '' elif console and path.startswith('/_pagekite/logout/'): parts = path.split('/') location = parts[3] or ('%s://%s/' % (data['method'], data['http_host'])) self.sendResponse('\n', code=302, msg='Moved', header_list=[('Set-Cookie', 'pkite_token=; path=/'), ('Location', location)]) return elif console and path.startswith('/_pagekite/login/'): parts = path.split('/', 4) token = parts[3] location = parts[4] or ('%s://%s/_pagekite/' % (data['method'], data['http_host'])) if query: location += '?' + query if token == self.server.secret: self.sendResponse('\n', code=302, msg='Moved', header_list=[ ('Set-Cookie', 'pkite_token=%s; path=/' % token), ('Location', location) ]) return else: logging.LogDebug("Invalid token, %s != %s" % (token, self.server.secret)) data.update(self.E404) elif console and path.startswith('/_pagekite/'): #if not ('pkite_token' in cookies and cookies['pkite_token'].value == self.server.secret): # self.sendResponse('<h1>Forbidden</h1>\n', code=403, msg='Forbidden') # return if path == '/_pagekite/': if not self.sendStaticPath('%s/control.pk-shtml' % console, 'text/html', shtml_vars=data): self.sendResponse('<h1>Not found</h1>\n', code=404, msg='Missing') return elif path.startswith('/_pagekite/quitquitquit/'): self.sendResponse('<h1>Kaboom</h1>\n', code=500, msg='Asplode') self.wfile.flush() os._exit(2) elif path.startswith('/_pagekite/add_kite/'): data.update(self.add_kite(path, qs)) else: data.update(self.E403) else: if self.sendStaticPath(path, data['mimetype'], shtml_vars=data): return if path == '/robots.txt': data.update(self.ROBOTSTXT) else: data.update(self.E404) if data['mimetype'] in ('application/octet-stream', 'text/plain'): response = self.TEMPLATE_RAW % data elif path.endswith('.jsonp'): response = self.TEMPLATE_JSONP % (data, ) else: response = self.TEMPLATE_HTML % data self.sendResponse(response, msg=data['msg'], code=data['code'], mimetype=data['mimetype'], chunked=False) self.sendEof()
try: auth = self.headers.get('authorization') if auth: (how, ab64) = auth.strip().split() if how.lower() == 'basic': (username, password) = base64.decodestring(ab64).split(':') self.checkUsernamePasswordAuth(username, password) return True self.checkRequestAuth(scheme, netloc, path, qs) return True except (ValueError, KeyError, AuthError), e: logging.LogDebug('HTTP Auth failed: %s' % e) else: logging.LogDebug('HTTP Auth failed: Unauthorized') self.sendResponse('<h1>Unauthorized</h1>\n', code=401, msg='Forbidden') return False def performPostAuthChecks(self, scheme, netloc, path, qs, posted): try: self.checkPostAuth(scheme, netloc, path, qs, posted) return True except AuthError: self.sendResponse('<h1>Unauthorized</h1>\n', code=401, msg='Forbidden') return False def do_UNSUPPORTED(self):
def LogDebug(self, message, params=None): values = params or [] if self.log_id: values.append(('id', self.log_id)) logging.LogDebug(message, values)
def LogDebug(self, message, params=None): values = params or [] if self.log_id: values.extend([('id', self.log_id), ('s', self.sstate)]) logging.LogDebug(message, values)