pile_js / EFForg__OpenWireless.jsonl
Hamhams's picture
commit files to HF hub
c7f4bd0
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/set_timezone.py","language":"python","identifier":"jsonrpc_set_timezone","parameters":"(etc=common.get_etc())","argument_list":"","return_statement":"","docstring":"Accept an olson-style set timezone, with parameters like so:\n\n {\"jsonrpc\":\"2.0\",\"method\":\"set_timezone\",\"params\":[\"timezonestring\"],\"id\":1}\n\n Set the local timezone on the router by looking up and placing the POSIX compatible timezone string\n in the \/etc\/TZ file.","docstring_summary":"Accept an olson-style set timezone, with parameters like so:","docstring_tokens":["Accept","an","olson","-","style","set","timezone","with","parameters","like","so",":"],"function":"def jsonrpc_set_timezone(etc=common.get_etc()):\n \"\"\"Accept an olson-style set timezone, with parameters like so:\n\n {\"jsonrpc\":\"2.0\",\"method\":\"set_timezone\",\"params\":[\"timezonestring\"],\"id\":1}\n\n Set the local timezone on the router by looking up and placing the POSIX compatible timezone string\n in the \/etc\/TZ file.\n \"\"\"\n\n data = json.loads(sys.stdin.read())\n try:\n params = data[\"params\"]\n tz_string = tz_info[params[0]]\n except KeyError, e:\n common.render_error(e.__str__())\n except IndexError, e:\n common.render_error(e.__str__())\n\n with open(os.path.join(etc, 'TZ'), \"w\") as tz_file:\n tz_file.write(tz_string)\n common.render_success({})\n return true","function_tokens":["def","jsonrpc_set_timezone","(","etc","=","common",".","get_etc","(",")",")",":","data","=","json",".","loads","(","sys",".","stdin",".","read","(",")",")","try",":","params","=","data","[","\"params\"","]","tz_string","=","tz_info","[","params","[","0","]","]","except","KeyError",",","e",":","common",".","render_error","(","e",".","__str__","(",")",")","except","IndexError",",","e",":","common",".","render_error","(","e",".","__str__","(",")",")","with","open","(","os",".","path",".","join","(","etc",",","'TZ'",")",",","\"w\"",")","as","tz_file",":","tz_file",".","write","(","tz_string",")","common",".","render_success","(","{","}",")","return","true"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/set_timezone.py#L9-L30"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/gen_tz_dictionary.py","language":"python","identifier":"get_zone_info","parameters":"(zone_dir=TZ_DB)","argument_list":"","return_statement":"","docstring":"get_zone_info - parse zone info from zoneinfo database into\n a python dictionary","docstring_summary":"get_zone_info - parse zone info from zoneinfo database into\n a python dictionary","docstring_tokens":["get_zone_info","-","parse","zone","info","from","zoneinfo","database","into","a","python","dictionary"],"function":"def get_zone_info(zone_dir=TZ_DB):\n \"\"\"\n get_zone_info - parse zone info from zoneinfo database into\n a python dictionary\n \"\"\"\n tzd = {}\n try:\n with open(os.path.join(zone_dir, \"zone.tab\"), \"r\") as zonetab:\n for line in zonetab:\n # Skip comments and whitespace\n if re.match(\"^#\", line) or re.match(\"^\\s+$\", line):\n continue\n\n # Olson zone paths are the third column in the table\n zone = re.split(\"\\s+\", line)[2]\n\n try:\n tzd[zone] = read_posix_zone(zone)\n except EnvironmentError: # IOError or OSError\n continue\n \n return tzd\n\n except EnvironmentError: # IOError or OSError\n return False","function_tokens":["def","get_zone_info","(","zone_dir","=","TZ_DB",")",":","tzd","=","{","}","try",":","with","open","(","os",".","path",".","join","(","zone_dir",",","\"zone.tab\"",")",",","\"r\"",")","as","zonetab",":","for","line","in","zonetab",":","# Skip comments and whitespace","if","re",".","match","(","\"^#\"",",","line",")","or","re",".","match","(","\"^\\s+$\"",",","line",")",":","continue","# Olson zone paths are the third column in the table","zone","=","re",".","split","(","\"\\s+\"",",","line",")","[","2","]","try",":","tzd","[","zone","]","=","read_posix_zone","(","zone",")","except","EnvironmentError",":","# IOError or OSError","continue","return","tzd","except","EnvironmentError",":","# IOError or OSError","return","False"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/gen_tz_dictionary.py#L25-L49"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/gen_tz_dictionary.py","language":"python","identifier":"read_posix_zone","parameters":"(zone)","argument_list":"","return_statement":"","docstring":"read_posix_zone - return the posix time zone for a give olson time zone\n @param string zone - olson time zone string","docstring_summary":"read_posix_zone - return the posix time zone for a give olson time zone","docstring_tokens":["read_posix_zone","-","return","the","posix","time","zone","for","a","give","olson","time","zone"],"function":"def read_posix_zone(zone):\n \"\"\"\n read_posix_zone - return the posix time zone for a give olson time zone\n @param string zone - olson time zone string\n \"\"\"\n with open(os.path.join(TZ_DB, zone), \"r\") as zonefile:\n # Return last line of file\n return list(zonefile)[-1].rstrip()","function_tokens":["def","read_posix_zone","(","zone",")",":","with","open","(","os",".","path",".","join","(","TZ_DB",",","zone",")",",","\"r\"",")","as","zonefile",":","# Return last line of file","return","list","(","zonefile",")","[","-","1","]",".","rstrip","(",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/gen_tz_dictionary.py#L52-L59"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/gen_tz_dictionary.py","language":"python","identifier":"write_zone_file","parameters":"(tz_dict)","argument_list":"","return_statement":"","docstring":"write_zone_file - write a timezone dictionary to a new python file\n @param dictionary tz_info - a dictionary mapping olson timezones to POSIX \n equivalents","docstring_summary":"write_zone_file - write a timezone dictionary to a new python file","docstring_tokens":["write_zone_file","-","write","a","timezone","dictionary","to","a","new","python","file"],"function":"def write_zone_file(tz_dict):\n \"\"\"\n write_zone_file - write a timezone dictionary to a new python file\n @param dictionary tz_info - a dictionary mapping olson timezones to POSIX \n equivalents\n \"\"\"\n with open(PY_TZ_FILE_PATH, 'w') as py_file:\n header = (\"#!\/usr\/bin\/python\\n\"\n \"\\\"\\\"\\\"\\ntz_info - maps Olson time zones to POSIX equivalents\\nAutogenerated by gen_tz_dictionary.py\\n\\\"\\\"\\\"\\n\"\n \"tz_info = {\\n\")\n\n footer = \"}\\n\"\n\n py_file.write(header)\n\n for otz in tz_dict:\n py_file.write(\" \\\"{0}\\\": \\\"{1}\\\",\\n\".format(otz,tz_dict[otz]))\n\n py_file.write(footer)","function_tokens":["def","write_zone_file","(","tz_dict",")",":","with","open","(","PY_TZ_FILE_PATH",",","'w'",")","as","py_file",":","header","=","(","\"#!\/usr\/bin\/python\\n\"","\"\\\"\\\"\\\"\\ntz_info - maps Olson time zones to POSIX equivalents\\nAutogenerated by gen_tz_dictionary.py\\n\\\"\\\"\\\"\\n\"","\"tz_info = {\\n\"",")","footer","=","\"}\\n\"","py_file",".","write","(","header",")","for","otz","in","tz_dict",":","py_file",".","write","(","\" \\\"{0}\\\": \\\"{1}\\\",\\n\"",".","format","(","otz",",","tz_dict","[","otz","]",")",")","py_file",".","write","(","footer",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/gen_tz_dictionary.py#L62-L80"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"default_path","parameters":"()","argument_list":"","return_statement":"return os.path.join(os.environ.get('OVERRIDE_ETC', '\/etc'), 'auth')","docstring":"The default path for auth files.\n\n Since auth is imported by common, not all functions from common are available\n yet, so we have to duplicate common.get_etc().","docstring_summary":"The default path for auth files.","docstring_tokens":["The","default","path","for","auth","files","."],"function":"def default_path():\n \"\"\"\n The default path for auth files.\n\n Since auth is imported by common, not all functions from common are available\n yet, so we have to duplicate common.get_etc().\n \"\"\"\n return os.path.join(os.environ.get('OVERRIDE_ETC', '\/etc'), 'auth')","function_tokens":["def","default_path","(",")",":","return","os",".","path",".","join","(","os",".","environ",".","get","(","'OVERRIDE_ETC'",",","'\/etc'",")",",","'auth'",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L45-L52"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"check_request","parameters":"(auth_dir = default_path())","argument_list":"","return_statement":"return True","docstring":"When processing a CGI request, validate that request is authenticated and, if\n it's a POST request, has a CSRF token.","docstring_summary":"When processing a CGI request, validate that request is authenticated and, if\n it's a POST request, has a CSRF token.","docstring_tokens":["When","processing","a","CGI","request","validate","that","request","is","authenticated","and","if","it","s","a","POST","request","has","a","CSRF","token","."],"function":"def check_request(auth_dir = default_path()):\n \"\"\"\n When processing a CGI request, validate that request is authenticated and, if\n it's a POST request, has a CSRF token.\n \"\"\"\n if (REQUEST_URI in os.environ and\n not os.environ[REQUEST_URI] in LOGGED_OUT_ENDPOINTS):\n a = Auth(auth_dir)\n a.check_authentication()\n if REQUEST_METHOD in os.environ and os.environ[REQUEST_METHOD] == \"POST\":\n a.check_csrf()\n return True","function_tokens":["def","check_request","(","auth_dir","=","default_path","(",")",")",":","if","(","REQUEST_URI","in","os",".","environ","and","not","os",".","environ","[","REQUEST_URI","]","in","LOGGED_OUT_ENDPOINTS",")",":","a","=","Auth","(","auth_dir",")","a",".","check_authentication","(",")","if","REQUEST_METHOD","in","os",".","environ","and","os",".","environ","[","REQUEST_METHOD","]","==","\"POST\"",":","a",".","check_csrf","(",")","return","True"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L54-L65"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"constant_time_equals","parameters":"(a, b)","argument_list":"","return_statement":"return result == 0","docstring":"Return True iff a == b, and do it in constant time.","docstring_summary":"Return True iff a == b, and do it in constant time.","docstring_tokens":["Return","True","iff","a","==","b","and","do","it","in","constant","time","."],"function":"def constant_time_equals(a, b):\n \"\"\"Return True iff a == b, and do it in constant time.\"\"\"\n a = bytearray(a)\n b = bytearray(b)\n if len(a) != len(b):\n return False\n\n result = 0\n for x, y in zip(a, b):\n result |= x ^ y\n return result == 0","function_tokens":["def","constant_time_equals","(","a",",","b",")",":","a","=","bytearray","(","a",")","b","=","bytearray","(","b",")","if","len","(","a",")","!=","len","(","b",")",":","return","False","result","=","0","for","x",",","y","in","zip","(","a",",","b",")",":","result","|=","x","^","y","return","result","==","0"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L67-L77"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.check_sane","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Check that the authentication data directory is owned by current user,\n with safe permissions. throw exception if not.","docstring_summary":"Check that the authentication data directory is owned by current user,\n with safe permissions. throw exception if not.","docstring_tokens":["Check","that","the","authentication","data","directory","is","owned","by","current","user","with","safe","permissions",".","throw","exception","if","not","."],"function":"def check_sane(self):\n \"\"\"\n Check that the authentication data directory is owned by current user,\n with safe permissions. throw exception if not.\n \"\"\"\n st = os.stat(self.path)\n if st.st_uid != os.getuid():\n raise Exception('Auth dir %s not owned by user %d.' % (\n self.path, os.getuid()))\n # Mode 16832 is equal to (stat.S_IFDIR | stat.S_IRWXU)\n # In other words, a directory with mode bits rwx------\n if st.st_mode != 16832:\n raise Exception('Auth dir %s not a dir or wrong permissions.' % self.path)","function_tokens":["def","check_sane","(","self",")",":","st","=","os",".","stat","(","self",".","path",")","if","st",".","st_uid","!=","os",".","getuid","(",")",":","raise","Exception","(","'Auth dir %s not owned by user %d.'","%","(","self",".","path",",","os",".","getuid","(",")",")",")","# Mode 16832 is equal to (stat.S_IFDIR | stat.S_IRWXU)","# In other words, a directory with mode bits rwx------","if","st",".","st_mode","!=","16832",":","raise","Exception","(","'Auth dir %s not a dir or wrong permissions.'","%","self",".","path",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L97-L109"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.write","parameters":"(self, filename, data)","argument_list":"","return_statement":"","docstring":"Save data into file, with mode bits rw-------.","docstring_summary":"Save data into file, with mode bits rw-------.","docstring_tokens":["Save","data","into","file","with","mode","bits","rw","-------","."],"function":"def write(self, filename, data):\n \"\"\"\n Save data into file, with mode bits rw-------.\n \"\"\"\n owner_rw = 0600\n fd = os.open(filename, os.O_WRONLY | os.O_CREAT, owner_rw)\n # In case file existed already with wrong permissions, fix them.\n os.chmod(filename, owner_rw)\n os.write(fd, data)\n os.close(fd)","function_tokens":["def","write","(","self",",","filename",",","data",")",":","owner_rw","=","0600","fd","=","os",".","open","(","filename",",","os",".","O_WRONLY","|","os",".","O_CREAT",",","owner_rw",")","# In case file existed already with wrong permissions, fix them.","os",".","chmod","(","filename",",","owner_rw",")","os",".","write","(","fd",",","data",")","os",".","close","(","fd",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L111-L120"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.rate_limit_remaining","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Return the number of failed passwords the can be entered before\n logins attempts are disabled for a day.\n\n The rate limit information is stored as a count of failed attempts so far.\n\n If there have been no failed attempts, or they were more than a day ago,\n treat that as zero failed attempts.","docstring_summary":"Return the number of failed passwords the can be entered before\n logins attempts are disabled for a day.","docstring_tokens":["Return","the","number","of","failed","passwords","the","can","be","entered","before","logins","attempts","are","disabled","for","a","day","."],"function":"def rate_limit_remaining(self):\n \"\"\"\n Return the number of failed passwords the can be entered before\n logins attempts are disabled for a day.\n\n The rate limit information is stored as a count of failed attempts so far.\n\n If there have been no failed attempts, or they were more than a day ago,\n treat that as zero failed attempts.\n \"\"\"\n if os.path.isfile(self.rate_limit_filename):\n st = os.stat(self.rate_limit_filename)\n if time.time() - st.st_ctime > self.RATE_LIMIT_DURATION:\n return self.RATE_LIMIT_COUNT\n else:\n with open(self.rate_limit_filename, 'r') as f:\n failed_login_attempts = int(f.read())\n return max(0, self.RATE_LIMIT_COUNT - failed_login_attempts)\n else:\n return self.RATE_LIMIT_COUNT","function_tokens":["def","rate_limit_remaining","(","self",")",":","if","os",".","path",".","isfile","(","self",".","rate_limit_filename",")",":","st","=","os",".","stat","(","self",".","rate_limit_filename",")","if","time",".","time","(",")","-","st",".","st_ctime",">","self",".","RATE_LIMIT_DURATION",":","return","self",".","RATE_LIMIT_COUNT","else",":","with","open","(","self",".","rate_limit_filename",",","'r'",")","as","f",":","failed_login_attempts","=","int","(","f",".","read","(",")",")","return","max","(","0",",","self",".","RATE_LIMIT_COUNT","-","failed_login_attempts",")","else",":","return","self",".","RATE_LIMIT_COUNT"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L122-L141"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.increment_rate_limit","parameters":"(self)","argument_list":"","return_statement":"","docstring":"On failed login attempt, increment the number of failed attempts.","docstring_summary":"On failed login attempt, increment the number of failed attempts.","docstring_tokens":["On","failed","login","attempt","increment","the","number","of","failed","attempts","."],"function":"def increment_rate_limit(self):\n \"\"\"On failed login attempt, increment the number of failed attempts.\"\"\"\n attempts = self.RATE_LIMIT_COUNT - self.rate_limit_remaining()\n attempts += 1\n self.write(self.rate_limit_filename, \"%d\" % attempts)","function_tokens":["def","increment_rate_limit","(","self",")",":","attempts","=","self",".","RATE_LIMIT_COUNT","-","self",".","rate_limit_remaining","(",")","attempts","+=","1","self",".","write","(","self",".","rate_limit_filename",",","\"%d\"","%","attempts",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L143-L147"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.password_exists","parameters":"(self)","argument_list":"","return_statement":"return os.path.isfile(self.password_filename)","docstring":"Return whether a password file exists.","docstring_summary":"Return whether a password file exists.","docstring_tokens":["Return","whether","a","password","file","exists","."],"function":"def password_exists(self):\n \"\"\"Return whether a password file exists.\"\"\"\n return os.path.isfile(self.password_filename)","function_tokens":["def","password_exists","(","self",")",":","return","os",".","path",".","isfile","(","self",".","password_filename",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L149-L151"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.is_password","parameters":"(self, candidate)","argument_list":"","return_statement":"","docstring":"Returns true iff the candidate password equals the stored one.","docstring_summary":"Returns true iff the candidate password equals the stored one.","docstring_tokens":["Returns","true","iff","the","candidate","password","equals","the","stored","one","."],"function":"def is_password(self, candidate):\n \"\"\"\n Returns true iff the candidate password equals the stored one.\n \"\"\"\n if self.rate_limit_remaining() > 0:\n with open(self.password_filename, 'r') as f:\n hashed = f.read().strip()\n b_valid = bytearray(hashed)\n b_guess = bytearray(pbkdf2.crypt(candidate, unicode(hashed)), 'utf-8')\n if constant_time_equals(b_valid, b_guess):\n return True\n else:\n # Increment rate limit on failures.\n self.increment_rate_limit()\n return False\n else:\n common.render_error('Too many failed login attempts. Try again tomorrow.')","function_tokens":["def","is_password","(","self",",","candidate",")",":","if","self",".","rate_limit_remaining","(",")",">","0",":","with","open","(","self",".","password_filename",",","'r'",")","as","f",":","hashed","=","f",".","read","(",")",".","strip","(",")","b_valid","=","bytearray","(","hashed",")","b_guess","=","bytearray","(","pbkdf2",".","crypt","(","candidate",",","unicode","(","hashed",")",")",",","'utf-8'",")","if","constant_time_equals","(","b_valid",",","b_guess",")",":","return","True","else",":","# Increment rate limit on failures.","self",".","increment_rate_limit","(",")","return","False","else",":","common",".","render_error","(","'Too many failed login attempts. Try again tomorrow.'",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L153-L169"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.save_password","parameters":"(self, new_password)","argument_list":"","return_statement":"return True","docstring":"Store a new password.\n Returns True is the password was stored and False if the password \n didn't fulfil all criteria.","docstring_summary":"Store a new password.\n Returns True is the password was stored and False if the password \n didn't fulfil all criteria.","docstring_tokens":["Store","a","new","password",".","Returns","True","is","the","password","was","stored","and","False","if","the","password","didn","t","fulfil","all","criteria","."],"function":"def save_password(self, new_password):\n \"\"\"\n Store a new password.\n Returns True is the password was stored and False if the password \n didn't fulfil all criteria.\n \"\"\"\n if len(new_password) < self.PASSWORD_LENGTH_MIN:\n return False\n # 55 iterations takes about 100 ms on a Netgear WNDR3800 or about 8ms on a\n # Core2 Duo at 1200 MHz.\n hashed = pbkdf2.crypt(new_password, iterations=55)\n self.write(self.password_filename, hashed)\n return True","function_tokens":["def","save_password","(","self",",","new_password",")",":","if","len","(","new_password",")","<","self",".","PASSWORD_LENGTH_MIN",":","return","False","# 55 iterations takes about 100 ms on a Netgear WNDR3800 or about 8ms on a","# Core2 Duo at 1200 MHz.","hashed","=","pbkdf2",".","crypt","(","new_password",",","iterations","=","55",")","self",".","write","(","self",".","password_filename",",","hashed",")","return","True"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L171-L183"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.get_csrf_token","parameters":"(self)","argument_list":"","return_statement":"return h.hexdigest()","docstring":"Generate a CSRF prevention token. We derive this token as the SHA256 hash\n of the auth token, which ensures the two are bound together, preventing\n cookie forcing attacks.\n\n Returns a valid CSRF prevention token.","docstring_summary":"Generate a CSRF prevention token. We derive this token as the SHA256 hash\n of the auth token, which ensures the two are bound together, preventing\n cookie forcing attacks.","docstring_tokens":["Generate","a","CSRF","prevention","token",".","We","derive","this","token","as","the","SHA256","hash","of","the","auth","token","which","ensures","the","two","are","bound","together","preventing","cookie","forcing","attacks","."],"function":"def get_csrf_token(self):\n \"\"\"\n Generate a CSRF prevention token. We derive this token as the SHA256 hash\n of the auth token, which ensures the two are bound together, preventing\n cookie forcing attacks.\n\n Returns a valid CSRF prevention token.\n \"\"\"\n h = hashlib.new('sha256')\n h.update(self.__current_authentication_token())\n return h.hexdigest()","function_tokens":["def","get_csrf_token","(","self",")",":","h","=","hashlib",".","new","(","'sha256'",")","h",".","update","(","self",".","__current_authentication_token","(",")",")","return","h",".","hexdigest","(",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L185-L195"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.is_csrf_token","parameters":"(self, candidate_csrf_token)","argument_list":"","return_statement":"return constant_time_equals(valid_token, candidate)","docstring":"Validate a presented CSRF token. Note that we validate by re-hashing the\n auth_token, rather than comparing directly to the csrf_token cookie. This\n prevents cookie forcing by requiring that the auth token and CSRF token be\n related.","docstring_summary":"Validate a presented CSRF token. Note that we validate by re-hashing the\n auth_token, rather than comparing directly to the csrf_token cookie. This\n prevents cookie forcing by requiring that the auth token and CSRF token be\n related.","docstring_tokens":["Validate","a","presented","CSRF","token",".","Note","that","we","validate","by","re","-","hashing","the","auth_token","rather","than","comparing","directly","to","the","csrf_token","cookie",".","This","prevents","cookie","forcing","by","requiring","that","the","auth","token","and","CSRF","token","be","related","."],"function":"def is_csrf_token(self, candidate_csrf_token):\n \"\"\"\n Validate a presented CSRF token. Note that we validate by re-hashing the\n auth_token, rather than comparing directly to the csrf_token cookie. This\n prevents cookie forcing by requiring that the auth token and CSRF token be\n related.\n \"\"\"\n valid_token = bytearray(self.get_csrf_token())\n candidate = bytearray(candidate_csrf_token)\n return constant_time_equals(valid_token, candidate)","function_tokens":["def","is_csrf_token","(","self",",","candidate_csrf_token",")",":","valid_token","=","bytearray","(","self",".","get_csrf_token","(",")",")","candidate","=","bytearray","(","candidate_csrf_token",")","return","constant_time_equals","(","valid_token",",","candidate",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L197-L206"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.check_csrf","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Get a CSRF token from CGI request headers and validate it. If validation\n fails, render an error and exit early.\n\n In our current JSONRPC style, we can send custom headers, so we look for the\n CSRF token in a header. We may switch to a form-submission-based approach,\n in which case we would need to update this code to look for a CSRF token in\n the POST parameters.","docstring_summary":"Get a CSRF token from CGI request headers and validate it. If validation\n fails, render an error and exit early.","docstring_tokens":["Get","a","CSRF","token","from","CGI","request","headers","and","validate","it",".","If","validation","fails","render","an","error","and","exit","early","."],"function":"def check_csrf(self):\n \"\"\"\n Get a CSRF token from CGI request headers and validate it. If validation\n fails, render an error and exit early.\n\n In our current JSONRPC style, we can send custom headers, so we look for the\n CSRF token in a header. We may switch to a form-submission-based approach,\n in which case we would need to update this code to look for a CSRF token in\n the POST parameters.\n \"\"\"\n if (self.HTTP_X_CSRF_TOKEN in os.environ and\n self.is_csrf_token(os.environ[self.HTTP_X_CSRF_TOKEN])):\n pass\n else:\n common.render_error('Invalid CSRF token.')","function_tokens":["def","check_csrf","(","self",")",":","if","(","self",".","HTTP_X_CSRF_TOKEN","in","os",".","environ","and","self",".","is_csrf_token","(","os",".","environ","[","self",".","HTTP_X_CSRF_TOKEN","]",")",")",":","pass","else",":","common",".","render_error","(","'Invalid CSRF token.'",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L208-L222"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.login_headers","parameters":"(self, tokens)","argument_list":"","return_statement":"return ('Set-Cookie: %s=true; path=\/\\n'\n 'Set-Cookie: %s=%s; path=\/; HttpOnly;%s\\n'\n 'Set-Cookie: %s=%s; path=\/;%s\\n' % (\n LOGGED_IN_COOKIE_NAME,\n AUTH_COOKIE_NAME, tokens.auth_token, secure_suffix,\n CSRF_COOKIE_NAME, tokens.csrf_token, secure_suffix))","docstring":"Return the HTTP headers required to log the user in. Specifically, set the\n auth cookie, the csrf token cookie, and an unsecured cookie logged_in=true,\n indicating the user is logged in even if the current request context doesn't\n have the auth cookies. The server should redirect users with the logged-in\n cookie to the HTTPS version of the site.\n\n Calling this method immediately regenerates the stored auth token,\n invalidating other active sessions.","docstring_summary":"Return the HTTP headers required to log the user in. Specifically, set the\n auth cookie, the csrf token cookie, and an unsecured cookie logged_in=true,\n indicating the user is logged in even if the current request context doesn't\n have the auth cookies. The server should redirect users with the logged-in\n cookie to the HTTPS version of the site.","docstring_tokens":["Return","the","HTTP","headers","required","to","log","the","user","in",".","Specifically","set","the","auth","cookie","the","csrf","token","cookie","and","an","unsecured","cookie","logged_in","=","true","indicating","the","user","is","logged","in","even","if","the","current","request","context","doesn","t","have","the","auth","cookies",".","The","server","should","redirect","users","with","the","logged","-","in","cookie","to","the","HTTPS","version","of","the","site","."],"function":"def login_headers(self, tokens):\n \"\"\"\n Return the HTTP headers required to log the user in. Specifically, set the\n auth cookie, the csrf token cookie, and an unsecured cookie logged_in=true,\n indicating the user is logged in even if the current request context doesn't\n have the auth cookies. The server should redirect users with the logged-in\n cookie to the HTTPS version of the site.\n\n Calling this method immediately regenerates the stored auth token,\n invalidating other active sessions.\n \"\"\"\n secure = 'HTTPS' in os.environ\n secure_suffix = ' secure;' if secure else ''\n return ('Set-Cookie: %s=true; path=\/\\n'\n 'Set-Cookie: %s=%s; path=\/; HttpOnly;%s\\n'\n 'Set-Cookie: %s=%s; path=\/;%s\\n' % (\n LOGGED_IN_COOKIE_NAME,\n AUTH_COOKIE_NAME, tokens.auth_token, secure_suffix,\n CSRF_COOKIE_NAME, tokens.csrf_token, secure_suffix))","function_tokens":["def","login_headers","(","self",",","tokens",")",":","secure","=","'HTTPS'","in","os",".","environ","secure_suffix","=","' secure;'","if","secure","else","''","return","(","'Set-Cookie: %s=true; path=\/\\n'","'Set-Cookie: %s=%s; path=\/; HttpOnly;%s\\n'","'Set-Cookie: %s=%s; path=\/;%s\\n'","%","(","LOGGED_IN_COOKIE_NAME",",","AUTH_COOKIE_NAME",",","tokens",".","auth_token",",","secure_suffix",",","CSRF_COOKIE_NAME",",","tokens",".","csrf_token",",","secure_suffix",")",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L224-L242"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.logout_headers","parameters":"(self)","argument_list":"","return_statement":"return ('Set-Cookie: %s=; path=\/; expires=Thu, 01 Jan 1970 00:00:00 GMT\\n'\n 'Set-Cookie: %s=; path=\/; expires=Thu, 01 Jan 1970 00:00:00 GMT\\n'\n 'Set-Cookie: %s=; path=\/; expires=Thu, 01 Jan 1970 00:00:00 GMT\\n' % (\n LOGGED_IN_COOKIE_NAME, AUTH_COOKIE_NAME,\n CSRF_COOKIE_NAME))","docstring":"Return the HTTP headers required to log the user out.\n\n Specifically, delete and invalidate the auth token and CSRF token.","docstring_summary":"Return the HTTP headers required to log the user out.","docstring_tokens":["Return","the","HTTP","headers","required","to","log","the","user","out","."],"function":"def logout_headers(self):\n \"\"\"\n Return the HTTP headers required to log the user out.\n\n Specifically, delete and invalidate the auth token and CSRF token.\n \"\"\"\n self.regenerate_authentication_token()\n return ('Set-Cookie: %s=; path=\/; expires=Thu, 01 Jan 1970 00:00:00 GMT\\n'\n 'Set-Cookie: %s=; path=\/; expires=Thu, 01 Jan 1970 00:00:00 GMT\\n'\n 'Set-Cookie: %s=; path=\/; expires=Thu, 01 Jan 1970 00:00:00 GMT\\n' % (\n LOGGED_IN_COOKIE_NAME, AUTH_COOKIE_NAME,\n CSRF_COOKIE_NAME))","function_tokens":["def","logout_headers","(","self",")",":","self",".","regenerate_authentication_token","(",")","return","(","'Set-Cookie: %s=; path=\/; expires=Thu, 01 Jan 1970 00:00:00 GMT\\n'","'Set-Cookie: %s=; path=\/; expires=Thu, 01 Jan 1970 00:00:00 GMT\\n'","'Set-Cookie: %s=; path=\/; expires=Thu, 01 Jan 1970 00:00:00 GMT\\n'","%","(","LOGGED_IN_COOKIE_NAME",",","AUTH_COOKIE_NAME",",","CSRF_COOKIE_NAME",")",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L252-L263"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.__current_authentication_token","parameters":"(self)","argument_list":"","return_statement":"return None","docstring":"Return the current authentication token if it still valid, else None.","docstring_summary":"Return the current authentication token if it still valid, else None.","docstring_tokens":["Return","the","current","authentication","token","if","it","still","valid","else","None","."],"function":"def __current_authentication_token(self):\n \"\"\"Return the current authentication token if it still valid, else None.\"\"\"\n if os.path.isfile(self.token_filename):\n with open(self.token_filename, 'r') as f:\n (stored_token, expires) = f.read().split(' ')\n t = time.time()\n if int(expires) > t:\n return stored_token\n return None","function_tokens":["def","__current_authentication_token","(","self",")",":","if","os",".","path",".","isfile","(","self",".","token_filename",")",":","with","open","(","self",".","token_filename",",","'r'",")","as","f",":","(","stored_token",",","expires",")","=","f",".","read","(",")",".","split","(","' '",")","t","=","time",".","time","(",")","if","int","(","expires",")",">","t",":","return","stored_token","return","None"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L265-L273"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.__valid_token_format","parameters":"(self, token)","argument_list":"","return_statement":"return True","docstring":"Basic length and character checking on tokens.","docstring_summary":"Basic length and character checking on tokens.","docstring_tokens":["Basic","length","and","character","checking","on","tokens","."],"function":"def __valid_token_format(self, token):\n \"\"\"Basic length and character checking on tokens.\"\"\"\n if len(token) != self.TOKEN_LENGTH * 2:\n return False\n for c in token:\n if c not in '01234567890abcdef':\n return False\n return True","function_tokens":["def","__valid_token_format","(","self",",","token",")",":","if","len","(","token",")","!=","self",".","TOKEN_LENGTH","*","2",":","return","False","for","c","in","token",":","if","c","not","in","'01234567890abcdef'",":","return","False","return","True"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L275-L282"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.is_authentication_token","parameters":"(self, candidate)","argument_list":"","return_statement":"","docstring":"Return true iff candidate authentication token matches stored one.","docstring_summary":"Return true iff candidate authentication token matches stored one.","docstring_tokens":["Return","true","iff","candidate","authentication","token","matches","stored","one","."],"function":"def is_authentication_token(self, candidate):\n \"\"\"Return true iff candidate authentication token matches stored one.\"\"\"\n current_token = self.__current_authentication_token()\n # TODO: Add expiry checking\n if (current_token and\n self.__valid_token_format(current_token) and\n self.__valid_token_format(candidate) and\n constant_time_equals(current_token, candidate)):\n return True\n else:\n return False","function_tokens":["def","is_authentication_token","(","self",",","candidate",")",":","current_token","=","self",".","__current_authentication_token","(",")","# TODO: Add expiry checking","if","(","current_token","and","self",".","__valid_token_format","(","current_token",")","and","self",".","__valid_token_format","(","candidate",")","and","constant_time_equals","(","current_token",",","candidate",")",")",":","return","True","else",":","return","False"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L284-L294"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.regenerate_authentication_token","parameters":"(self)","argument_list":"","return_statement":"return new_token","docstring":"Create and store a new random authentication token. Expires old sessions.","docstring_summary":"Create and store a new random authentication token. Expires old sessions.","docstring_tokens":["Create","and","store","a","new","random","authentication","token",".","Expires","old","sessions","."],"function":"def regenerate_authentication_token(self):\n \"\"\"\n Create and store a new random authentication token. Expires old sessions.\n \"\"\"\n new_token = os.urandom(self.TOKEN_LENGTH).encode('hex')\n expires = int(time.time()) + Auth.SESSION_DURATION\n self.write(self.token_filename, ('%s %d' % (new_token, expires)))\n return new_token","function_tokens":["def","regenerate_authentication_token","(","self",")",":","new_token","=","os",".","urandom","(","self",".","TOKEN_LENGTH",")",".","encode","(","'hex'",")","expires","=","int","(","time",".","time","(",")",")","+","Auth",".","SESSION_DURATION","self",".","write","(","self",".","token_filename",",","(","'%s %d'","%","(","new_token",",","expires",")",")",")","return","new_token"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L296-L303"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/auth.py","language":"python","identifier":"Auth.check_authentication","parameters":"(self)","argument_list":"","return_statement":"","docstring":"In the context of a CGI request, check whether an authentication\n cookie is present and valid. If not, render an error.","docstring_summary":"In the context of a CGI request, check whether an authentication\n cookie is present and valid. If not, render an error.","docstring_tokens":["In","the","context","of","a","CGI","request","check","whether","an","authentication","cookie","is","present","and","valid",".","If","not","render","an","error","."],"function":"def check_authentication(self):\n \"\"\"\n In the context of a CGI request, check whether an authentication\n cookie is present and valid. If not, render an error.\n \"\"\"\n try:\n cookies = os.environ['HTTP_COOKIE'].split('; ')\n except KeyError:\n cookies = []\n for c in cookies:\n prefix = AUTH_COOKIE_NAME + '='\n if (c.startswith(prefix) and\n self.is_authentication_token(c[len(prefix):])):\n return True\n print 'Status: 403 Forbidden'\n print 'Content-Type: application\/json'\n print self.logout_headers()\n print json.JSONEncoder().encode({'error': 'Not authenticated.'})\n sys.exit(1)","function_tokens":["def","check_authentication","(","self",")",":","try",":","cookies","=","os",".","environ","[","'HTTP_COOKIE'","]",".","split","(","'; '",")","except","KeyError",":","cookies","=","[","]","for","c","in","cookies",":","prefix","=","AUTH_COOKIE_NAME","+","'='","if","(","c",".","startswith","(","prefix",")","and","self",".","is_authentication_token","(","c","[","len","(","prefix",")",":","]",")",")",":","return","True","print","'Status: 403 Forbidden'","print","'Content-Type: application\/json'","print","self",".","logout_headers","(",")","print","json",".","JSONEncoder","(",")",".","encode","(","{","'error'",":","'Not authenticated.'","}",")","sys",".","exit","(","1",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/auth.py#L305-L323"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/change_password.py","language":"python","identifier":"jsonrpc_change_password","parameters":"()","argument_list":"","return_statement":"","docstring":"Accept a JSONRPC-style change password, with parameters like so:\n\n {\"jsonrpc\":\"2.0\",\"method\":\"use.setpassword\",\"params\":[\"username\",\"password\", \"oldpassword\"],\"id\":1}\n\n On successful login, set two cookies: The auth cookie, used for primary\n authentication, is HttpOnly so JS cannot access it in case of an XSS. The\n CSRF token, used to validate that POSTs come from the same origin, is\n accessible to JS so it can be included in <form>'s.","docstring_summary":"Accept a JSONRPC-style change password, with parameters like so:","docstring_tokens":["Accept","a","JSONRPC","-","style","change","password","with","parameters","like","so",":"],"function":"def jsonrpc_change_password():\n \"\"\"Accept a JSONRPC-style change password, with parameters like so:\n\n {\"jsonrpc\":\"2.0\",\"method\":\"use.setpassword\",\"params\":[\"username\",\"password\", \"oldpassword\"],\"id\":1}\n\n On successful login, set two cookies: The auth cookie, used for primary\n authentication, is HttpOnly so JS cannot access it in case of an XSS. The\n CSRF token, used to validate that POSTs come from the same origin, is\n accessible to JS so it can be included in <form>'s.\n \"\"\"\n data = json.loads(sys.stdin.read())\n try:\n params = data[\"params\"]\n username = params[0]\n new_password = params[1]\n old_password = params[2]\n except KeyError, e:\n common.render_error(e.__str__())\n except IndexError, e:\n common.render_error(e.__str__())\n\n a = auth.Auth()\n if a.is_password(old_password):\n if not a.save_password(new_password):\n common.render_error(\"Invalid password supplied.\")\n remote_address = os.environ.get('REMOTE_ADDR')\n tokens = a.authenticate(new_password, remote_address)\n print \"Content-Type: application\/json\"\n print a.login_headers(tokens)\n print\n print \"{}\"\n else:\n common.render_error(\"Old password is incorrect.\")","function_tokens":["def","jsonrpc_change_password","(",")",":","data","=","json",".","loads","(","sys",".","stdin",".","read","(",")",")","try",":","params","=","data","[","\"params\"","]","username","=","params","[","0","]","new_password","=","params","[","1","]","old_password","=","params","[","2","]","except","KeyError",",","e",":","common",".","render_error","(","e",".","__str__","(",")",")","except","IndexError",",","e",":","common",".","render_error","(","e",".","__str__","(",")",")","a","=","auth",".","Auth","(",")","if","a",".","is_password","(","old_password",")",":","if","not","a",".","save_password","(","new_password",")",":","common",".","render_error","(","\"Invalid password supplied.\"",")","remote_address","=","os",".","environ",".","get","(","'REMOTE_ADDR'",")","tokens","=","a",".","authenticate","(","new_password",",","remote_address",")","print","\"Content-Type: application\/json\"","print","a",".","login_headers","(","tokens",")","print","print","\"{}\"","else",":","common",".","render_error","(","\"Old password is incorrect.\"",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/change_password.py#L9-L41"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/login.py","language":"python","identifier":"jsonrpc_login","parameters":"()","argument_list":"","return_statement":"","docstring":"Accept a JSONRPC-style login, with parameters like so:\n\n {\"jsonrpc\":\"2.0\",\"method\":\"login\",\"params\":[\"username\",\"password\"],\"id\":1}","docstring_summary":"Accept a JSONRPC-style login, with parameters like so:","docstring_tokens":["Accept","a","JSONRPC","-","style","login","with","parameters","like","so",":"],"function":"def jsonrpc_login():\n \"\"\"Accept a JSONRPC-style login, with parameters like so:\n\n {\"jsonrpc\":\"2.0\",\"method\":\"login\",\"params\":[\"username\",\"password\"],\"id\":1}\n \"\"\"\n data = json.loads(sys.stdin.read())\n try:\n params = data[\"params\"]\n username = params[0]\n password = params[1]\n except KeyError, e:\n common.render_error(e.__str__())\n a = auth.Auth()\n remote_address = os.environ.get('REMOTE_ADDR')\n tokens = a.authenticate(password, remote_address)\n if tokens:\n print \"Content-Type: application\/json\"\n print a.login_headers(tokens)\n print\n print \"{}\"\n else:\n common.render_error(\"Bad password.\")","function_tokens":["def","jsonrpc_login","(",")",":","data","=","json",".","loads","(","sys",".","stdin",".","read","(",")",")","try",":","params","=","data","[","\"params\"","]","username","=","params","[","0","]","password","=","params","[","1","]","except","KeyError",",","e",":","common",".","render_error","(","e",".","__str__","(",")",")","a","=","auth",".","Auth","(",")","remote_address","=","os",".","environ",".","get","(","'REMOTE_ADDR'",")","tokens","=","a",".","authenticate","(","password",",","remote_address",")","if","tokens",":","print","\"Content-Type: application\/json\"","print","a",".","login_headers","(","tokens",")","print","print","\"{}\"","else",":","common",".","render_error","(","\"Bad password.\"",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/login.py#L9-L30"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/settings.py","language":"python","identifier":"openwrt_release","parameters":"()","argument_list":"","return_statement":"return (items.get('DISTRIB_DESCRIPTION', 'Unknown'),\n items.get('DISTRIB_RELEASE_DATE', 0))","docstring":"Returns a tuple of (software_version, release date)","docstring_summary":"Returns a tuple of (software_version, release date)","docstring_tokens":["Returns","a","tuple","of","(","software_version","release","date",")"],"function":"def openwrt_release():\n \"\"\"Returns a tuple of (software_version, release date)\"\"\"\n items = {}\n try:\n with open(os.path.join(common.get_etc(), 'openwrt_release')) as f:\n for line in f:\n key, val = line.split('=')\n # Strip trailing newline, and any wrapping quotes.\n items[key] = val.strip('\"\\n')\n except IOError:\n pass\n return (items.get('DISTRIB_DESCRIPTION', 'Unknown'),\n items.get('DISTRIB_RELEASE_DATE', 0))","function_tokens":["def","openwrt_release","(",")",":","items","=","{","}","try",":","with","open","(","os",".","path",".","join","(","common",".","get_etc","(",")",",","'openwrt_release'",")",")","as","f",":","for","line","in","f",":","key",",","val","=","line",".","split","(","'='",")","# Strip trailing newline, and any wrapping quotes.","items","[","key","]","=","val",".","strip","(","'\"\\n'",")","except","IOError",":","pass","return","(","items",".","get","(","'DISTRIB_DESCRIPTION'",",","'Unknown'",")",",","items",".","get","(","'DISTRIB_RELEASE_DATE'",",","0",")",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/settings.py#L11-L23"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/dashboard.py","language":"python","identifier":"get_dashboard","parameters":"()","argument_list":"","return_statement":"","docstring":"Render JSON dashboard data response.","docstring_summary":"Render JSON dashboard data response.","docstring_tokens":["Render","JSON","dashboard","data","response","."],"function":"def get_dashboard():\n \"\"\"Render JSON dashboard data response.\"\"\"\n def get_ping_output():\n \"\"\"Ping a server and return the output\"\"\"\n try:\n return run.check_output(\n ['\/usr\/bin\/sudo', '\/bin\/ping', '-c1', 'eff.org'])\n except subprocess.CalledProcessError:\n return 'N\/A'\n\n ping_output = get_ping_output()\n\n if \"N\/A\" in ping_output:\n connected = False\n ping_speed = \"N\/A\"\n else:\n connected = True\n ping_speed = int(float(ping_output.split(' ')[11].split('=')[1]))\n\n wan_ip = ip_address_retriever.get_external_ip_address()\n lan_ip = ip_address_retriever.get_internal_ip_address(\"ge00\")\n\n ssid = uci.get(\"wireless.@wifi-iface[2].ssid\")\n\n private_wifi_on = check_interface_connection.enabled(2)\n openwireless_on = check_interface_connection.enabled(1)\n\n def get_openwireless_use():\n use_in_bytes = float(uci.get(\"openwireless.use_since_last_ui_reset\"))\n use_in_mbs = use_in_bytes\/1000000.0\n return(str(int(use_in_mbs)))\n\n openwireless_use = get_openwireless_use()\n\n last_update_path = os.path.join(common.get_etc(), \"last_update_check\")\n if os.path.exists(last_update_path):\n [last_check_date,avail] = open(last_update_path).read().split()\n else:\n [last_check_date, avail] = (0, \"N\")\n\n update_check_datetime = datetime.datetime.utcfromtimestamp(float(last_check_date)\/1000)\n\n if (avail==\"Y\"):\n update_available = True\n else:\n update_available = False\n\n activateCap = (uci.get(\"openwireless.activatedatacap\") == \"Yes\")\n\n result = {\n \"id\": 1,\n \"jsonrpc\": \"2.0\",\n \"result\": {\n \"internet\": {\n \"name\": \"Internet\",\n \"uploadSpeed\": \"...\",\n \"uploadSpeedMetric\": \"Mb\/s\",\n \"downloadSpeed\": \"...\",\n \"downloadSpeedMetric\": \"Mb\/s\",\n \"pingSpeed\": ping_speed,\n \"pingSpeedMetric\": \"ms\",\n \"connected\": connected\n },\n \"lanNetwork\": {\n \"name\": \"LAN Network\",\n \"uploadSpeed\": \"...\",\n \"uploadSpeedMetric\": \"Mb\/s\",\n \"downloadSpeed\": \"...\",\n \"downloadSpeedMetric\": \"Mb\/s\",\n \"devices\": \"0\"\n },\n \"privateWifi\": {\n \"name\": \"Private WiFi\",\n \"uploadSpeed\": \"...\",\n \"uploadSpeedMetric\": \"Mb\/s\",\n \"downloadSpeed\": \"...\",\n \"downloadSpeedMetric\": \"Mb\/s\",\n \"devices\": \"0\",\n \"on\": private_wifi_on,\n \"ssid\": ssid\n },\n \"openWireless\": {\n \"name\": \"Openwireless.org\",\n \"uploadSpeed\": \"...\",\n \"uploadSpeedMetric\": \"Mb\/s\",\n \"downloadSpeed\": \"...\",\n \"downloadSpeedMetric\": \"Mb\/s\",\n \"maxBandwidthPercent\":\n uci.get(\"openwireless.maxbandwidthpercentage\"),\n \"activateDataCap\": activateCap,\n \"maxMonthlyBandwidth\":\n uci.get(\"openwireless.maxmonthlybandwidth\"),\n \"maxMonthlyBandwidthMetric\": \"Mb\",\n \"monthlyBandwidthUsage\": openwireless_use,\n \"on\": openwireless_on\n },\n \"updateAvailable\": update_available,\n \"lastCheckDate\": update_check_datetime,\n \"wanIp\": wan_ip,\n \"lanIp\": lan_ip,\n \"previousLogin\" : audit.previous_login(),\n }\n }\n common.render_success(result)","function_tokens":["def","get_dashboard","(",")",":","def","get_ping_output","(",")",":","\"\"\"Ping a server and return the output\"\"\"","try",":","return","run",".","check_output","(","[","'\/usr\/bin\/sudo'",",","'\/bin\/ping'",",","'-c1'",",","'eff.org'","]",")","except","subprocess",".","CalledProcessError",":","return","'N\/A'","ping_output","=","get_ping_output","(",")","if","\"N\/A\"","in","ping_output",":","connected","=","False","ping_speed","=","\"N\/A\"","else",":","connected","=","True","ping_speed","=","int","(","float","(","ping_output",".","split","(","' '",")","[","11","]",".","split","(","'='",")","[","1","]",")",")","wan_ip","=","ip_address_retriever",".","get_external_ip_address","(",")","lan_ip","=","ip_address_retriever",".","get_internal_ip_address","(","\"ge00\"",")","ssid","=","uci",".","get","(","\"wireless.@wifi-iface[2].ssid\"",")","private_wifi_on","=","check_interface_connection",".","enabled","(","2",")","openwireless_on","=","check_interface_connection",".","enabled","(","1",")","def","get_openwireless_use","(",")",":","use_in_bytes","=","float","(","uci",".","get","(","\"openwireless.use_since_last_ui_reset\"",")",")","use_in_mbs","=","use_in_bytes","\/","1000000.0","return","(","str","(","int","(","use_in_mbs",")",")",")","openwireless_use","=","get_openwireless_use","(",")","last_update_path","=","os",".","path",".","join","(","common",".","get_etc","(",")",",","\"last_update_check\"",")","if","os",".","path",".","exists","(","last_update_path",")",":","[","last_check_date",",","avail","]","=","open","(","last_update_path",")",".","read","(",")",".","split","(",")","else",":","[","last_check_date",",","avail","]","=","(","0",",","\"N\"",")","update_check_datetime","=","datetime",".","datetime",".","utcfromtimestamp","(","float","(","last_check_date",")","\/","1000",")","if","(","avail","==","\"Y\"",")",":","update_available","=","True","else",":","update_available","=","False","activateCap","=","(","uci",".","get","(","\"openwireless.activatedatacap\"",")","==","\"Yes\"",")","result","=","{","\"id\"",":","1",",","\"jsonrpc\"",":","\"2.0\"",",","\"result\"",":","{","\"internet\"",":","{","\"name\"",":","\"Internet\"",",","\"uploadSpeed\"",":","\"...\"",",","\"uploadSpeedMetric\"",":","\"Mb\/s\"",",","\"downloadSpeed\"",":","\"...\"",",","\"downloadSpeedMetric\"",":","\"Mb\/s\"",",","\"pingSpeed\"",":","ping_speed",",","\"pingSpeedMetric\"",":","\"ms\"",",","\"connected\"",":","connected","}",",","\"lanNetwork\"",":","{","\"name\"",":","\"LAN Network\"",",","\"uploadSpeed\"",":","\"...\"",",","\"uploadSpeedMetric\"",":","\"Mb\/s\"",",","\"downloadSpeed\"",":","\"...\"",",","\"downloadSpeedMetric\"",":","\"Mb\/s\"",",","\"devices\"",":","\"0\"","}",",","\"privateWifi\"",":","{","\"name\"",":","\"Private WiFi\"",",","\"uploadSpeed\"",":","\"...\"",",","\"uploadSpeedMetric\"",":","\"Mb\/s\"",",","\"downloadSpeed\"",":","\"...\"",",","\"downloadSpeedMetric\"",":","\"Mb\/s\"",",","\"devices\"",":","\"0\"",",","\"on\"",":","private_wifi_on",",","\"ssid\"",":","ssid","}",",","\"openWireless\"",":","{","\"name\"",":","\"Openwireless.org\"",",","\"uploadSpeed\"",":","\"...\"",",","\"uploadSpeedMetric\"",":","\"Mb\/s\"",",","\"downloadSpeed\"",":","\"...\"",",","\"downloadSpeedMetric\"",":","\"Mb\/s\"",",","\"maxBandwidthPercent\"",":","uci",".","get","(","\"openwireless.maxbandwidthpercentage\"",")",",","\"activateDataCap\"",":","activateCap",",","\"maxMonthlyBandwidth\"",":","uci",".","get","(","\"openwireless.maxmonthlybandwidth\"",")",",","\"maxMonthlyBandwidthMetric\"",":","\"Mb\"",",","\"monthlyBandwidthUsage\"",":","openwireless_use",",","\"on\"",":","openwireless_on","}",",","\"updateAvailable\"",":","update_available",",","\"lastCheckDate\"",":","update_check_datetime",",","\"wanIp\"",":","wan_ip",",","\"lanIp\"",":","lan_ip",",","\"previousLogin\"",":","audit",".","previous_login","(",")",",","}","}","common",".","render_success","(","result",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/dashboard.py#L15-L118"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/ssh_key.py","language":"python","identifier":"key_locked","parameters":"(authorized_keys = AUTHORIZED_KEYS)","argument_list":"","return_statement":"return (os.path.exists(authorized_keys) and\n uci.get('openwireless.ssh_success') == 'true')","docstring":"Return whether a key is locked in place - i.e. a key is stored and\n user has logged in once via SSH.","docstring_summary":"Return whether a key is locked in place - i.e. a key is stored and\n user has logged in once via SSH.","docstring_tokens":["Return","whether","a","key","is","locked","in","place","-","i",".","e",".","a","key","is","stored","and","user","has","logged","in","once","via","SSH","."],"function":"def key_locked(authorized_keys = AUTHORIZED_KEYS):\n \"\"\"\n Return whether a key is locked in place - i.e. a key is stored and\n user has logged in once via SSH.\n \"\"\"\n return (os.path.exists(authorized_keys) and\n uci.get('openwireless.ssh_success') == 'true')","function_tokens":["def","key_locked","(","authorized_keys","=","AUTHORIZED_KEYS",")",":","return","(","os",".","path",".","exists","(","authorized_keys",")","and","uci",".","get","(","'openwireless.ssh_success'",")","==","'true'",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/ssh_key.py#L27-L33"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/pbkdf2.py","language":"python","identifier":"crypt","parameters":"(word, salt=None, iterations=None)","argument_list":"","return_statement":"return salt + \"$\" + b64encode(rawhash, \".\/\")","docstring":"PBKDF2-based unix crypt(3) replacement.\n\n The number of iterations specified in the salt overrides the 'iterations'\n parameter.\n\n The effective hash length is 192 bits.","docstring_summary":"PBKDF2-based unix crypt(3) replacement.","docstring_tokens":["PBKDF2","-","based","unix","crypt","(","3",")","replacement","."],"function":"def crypt(word, salt=None, iterations=None):\n \"\"\"PBKDF2-based unix crypt(3) replacement.\n\n The number of iterations specified in the salt overrides the 'iterations'\n parameter.\n\n The effective hash length is 192 bits.\n \"\"\"\n\n # Generate a (pseudo-)random salt if the user hasn't provided one.\n if salt is None:\n salt = _makesalt()\n\n # salt must be a string or the us-ascii subset of unicode\n if isunicode(salt):\n salt = salt.encode('us-ascii').decode('us-ascii')\n elif isbytes(salt):\n salt = salt.decode('us-ascii')\n else:\n raise TypeError(\"salt must be a string\")\n\n # word must be a string or unicode (in the latter case, we convert to UTF-8)\n if isunicode(word):\n word = word.encode(\"UTF-8\")\n elif not isbytes(word):\n raise TypeError(\"word must be a string or unicode\")\n\n # Try to extract the real salt and iteration count from the salt\n if salt.startswith(\"$p5k2$\"):\n (iterations, salt, dummy) = salt.split(\"$\")[2:5]\n if iterations == \"\":\n iterations = 400\n else:\n converted = int(iterations, 16)\n if iterations != \"%x\" % converted: # lowercase hex, minimum digits\n raise ValueError(\"Invalid salt\")\n iterations = converted\n if not (iterations >= 1):\n raise ValueError(\"Invalid salt\")\n\n # Make sure the salt matches the allowed character set\n allowed = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.\/\"\n for ch in salt:\n if ch not in allowed:\n raise ValueError(\"Illegal character %r in salt\" % (ch,))\n\n if iterations is None or iterations == 400:\n iterations = 400\n salt = \"$p5k2$$\" + salt\n else:\n salt = \"$p5k2$%x$%s\" % (iterations, salt)\n rawhash = PBKDF2(word, salt, iterations).read(24)\n return salt + \"$\" + b64encode(rawhash, \".\/\")","function_tokens":["def","crypt","(","word",",","salt","=","None",",","iterations","=","None",")",":","# Generate a (pseudo-)random salt if the user hasn't provided one.","if","salt","is","None",":","salt","=","_makesalt","(",")","# salt must be a string or the us-ascii subset of unicode","if","isunicode","(","salt",")",":","salt","=","salt",".","encode","(","'us-ascii'",")",".","decode","(","'us-ascii'",")","elif","isbytes","(","salt",")",":","salt","=","salt",".","decode","(","'us-ascii'",")","else",":","raise","TypeError","(","\"salt must be a string\"",")","# word must be a string or unicode (in the latter case, we convert to UTF-8)","if","isunicode","(","word",")",":","word","=","word",".","encode","(","\"UTF-8\"",")","elif","not","isbytes","(","word",")",":","raise","TypeError","(","\"word must be a string or unicode\"",")","# Try to extract the real salt and iteration count from the salt","if","salt",".","startswith","(","\"$p5k2$\"",")",":","(","iterations",",","salt",",","dummy",")","=","salt",".","split","(","\"$\"",")","[","2",":","5","]","if","iterations","==","\"\"",":","iterations","=","400","else",":","converted","=","int","(","iterations",",","16",")","if","iterations","!=","\"%x\"","%","converted",":","# lowercase hex, minimum digits","raise","ValueError","(","\"Invalid salt\"",")","iterations","=","converted","if","not","(","iterations",">=","1",")",":","raise","ValueError","(","\"Invalid salt\"",")","# Make sure the salt matches the allowed character set","allowed","=","\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.\/\"","for","ch","in","salt",":","if","ch","not","in","allowed",":","raise","ValueError","(","\"Illegal character %r in salt\"","%","(","ch",",",")",")","if","iterations","is","None","or","iterations","==","400",":","iterations","=","400","salt","=","\"$p5k2$$\"","+","salt","else",":","salt","=","\"$p5k2$%x$%s\"","%","(","iterations",",","salt",")","rawhash","=","PBKDF2","(","word",",","salt",",","iterations",")",".","read","(","24",")","return","salt","+","\"$\"","+","b64encode","(","rawhash",",","\".\/\"",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/pbkdf2.py#L229-L281"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/pbkdf2.py","language":"python","identifier":"_makesalt","parameters":"()","argument_list":"","return_statement":"return b64encode(binarysalt, \".\/\")","docstring":"Return a 48-bit pseudorandom salt for crypt().\n\n This function is not suitable for generating cryptographic secrets.","docstring_summary":"Return a 48-bit pseudorandom salt for crypt().","docstring_tokens":["Return","a","48","-","bit","pseudorandom","salt","for","crypt","()","."],"function":"def _makesalt():\n \"\"\"Return a 48-bit pseudorandom salt for crypt().\n\n This function is not suitable for generating cryptographic secrets.\n \"\"\"\n binarysalt = b(\"\").join([pack(\"@H\", randint(0, 0xffff)) for i in range(3)])\n return b64encode(binarysalt, \".\/\")","function_tokens":["def","_makesalt","(",")",":","binarysalt","=","b","(","\"\"",")",".","join","(","[","pack","(","\"@H\"",",","randint","(","0",",","0xffff",")",")","for","i","in","range","(","3",")","]",")","return","b64encode","(","binarysalt",",","\".\/\"",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/pbkdf2.py#L288-L294"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/pbkdf2.py","language":"python","identifier":"PBKDF2._pseudorandom","parameters":"(self, key, msg)","argument_list":"","return_statement":"return self.__macmodule.new(key=key, msg=msg,\n digestmod=self.__digestmodule).digest()","docstring":"Pseudorandom function. e.g. HMAC-SHA1","docstring_summary":"Pseudorandom function. e.g. HMAC-SHA1","docstring_tokens":["Pseudorandom","function",".","e",".","g",".","HMAC","-","SHA1"],"function":"def _pseudorandom(self, key, msg):\n \"\"\"Pseudorandom function. e.g. HMAC-SHA1\"\"\"\n return self.__macmodule.new(key=key, msg=msg,\n digestmod=self.__digestmodule).digest()","function_tokens":["def","_pseudorandom","(","self",",","key",",","msg",")",":","return","self",".","__macmodule",".","new","(","key","=","key",",","msg","=","msg",",","digestmod","=","self",".","__digestmodule",")",".","digest","(",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/pbkdf2.py#L142-L145"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/pbkdf2.py","language":"python","identifier":"PBKDF2.read","parameters":"(self, bytes)","argument_list":"","return_statement":"return retval","docstring":"Read the specified number of key bytes.","docstring_summary":"Read the specified number of key bytes.","docstring_tokens":["Read","the","specified","number","of","key","bytes","."],"function":"def read(self, bytes):\n \"\"\"Read the specified number of key bytes.\"\"\"\n if self.closed:\n raise ValueError(\"file-like object is closed\")\n\n size = len(self.__buf)\n blocks = [self.__buf]\n i = self.__blockNum\n while size < bytes:\n i += 1\n if i > _0xffffffffL or i < 1:\n # We could return \"\" here, but\n raise OverflowError(\"derived key too long\")\n block = self.__f(i)\n blocks.append(block)\n size += len(block)\n buf = b(\"\").join(blocks)\n retval = buf[:bytes]\n self.__buf = buf[bytes:]\n self.__blockNum = i\n return retval","function_tokens":["def","read","(","self",",","bytes",")",":","if","self",".","closed",":","raise","ValueError","(","\"file-like object is closed\"",")","size","=","len","(","self",".","__buf",")","blocks","=","[","self",".","__buf","]","i","=","self",".","__blockNum","while","size","<","bytes",":","i","+=","1","if","i",">","_0xffffffffL","or","i","<","1",":","# We could return \"\" here, but","raise","OverflowError","(","\"derived key too long\"",")","block","=","self",".","__f","(","i",")","blocks",".","append","(","block",")","size","+=","len","(","block",")","buf","=","b","(","\"\"",")",".","join","(","blocks",")","retval","=","buf","[",":","bytes","]","self",".","__buf","=","buf","[","bytes",":","]","self",".","__blockNum","=","i","return","retval"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/pbkdf2.py#L147-L167"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/pbkdf2.py","language":"python","identifier":"PBKDF2.hexread","parameters":"(self, octets)","argument_list":"","return_statement":"return b2a_hex(self.read(octets))","docstring":"Read the specified number of octets. Return them as hexadecimal.\n\n Note that len(obj.hexread(n)) == 2*n.","docstring_summary":"Read the specified number of octets. Return them as hexadecimal.","docstring_tokens":["Read","the","specified","number","of","octets",".","Return","them","as","hexadecimal","."],"function":"def hexread(self, octets):\n \"\"\"Read the specified number of octets. Return them as hexadecimal.\n\n Note that len(obj.hexread(n)) == 2*n.\n \"\"\"\n return b2a_hex(self.read(octets))","function_tokens":["def","hexread","(","self",",","octets",")",":","return","b2a_hex","(","self",".","read","(","octets",")",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/pbkdf2.py#L179-L184"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/pbkdf2.py","language":"python","identifier":"PBKDF2.close","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Close the stream.","docstring_summary":"Close the stream.","docstring_tokens":["Close","the","stream","."],"function":"def close(self):\n \"\"\"Close the stream.\"\"\"\n if not self.closed:\n del self.__passphrase\n del self.__salt\n del self.__iterations\n del self.__prf\n del self.__blockNum\n del self.__buf\n self.closed = True","function_tokens":["def","close","(","self",")",":","if","not","self",".","closed",":","del","self",".","__passphrase","del","self",".","__salt","del","self",".","__iterations","del","self",".","__prf","del","self",".","__blockNum","del","self",".","__buf","self",".","closed","=","True"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/pbkdf2.py#L218-L227"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"routerapi\/change_password_first_time.py","language":"python","identifier":"jsonrpc_change_password_first_time","parameters":"(auth_path)","argument_list":"","return_statement":"","docstring":"Accept a JSONRPC-style change password, with parameters like so:\n\n {\"jsonrpc\":\"2.0\",\"method\":\"setpassword\",\"params\":[\"username\",\"password\"],\"id\":1}\n\n This endpoint does not require the user to provide their existing password,\n but it can only be used when setting the administrator password for the first\n time. If a password is already set, this endpoint will return 403.\n\n This needs to be a separate endpoint from change_password because it is\n listed in auth.py as not requiring authentication cookies.","docstring_summary":"Accept a JSONRPC-style change password, with parameters like so:","docstring_tokens":["Accept","a","JSONRPC","-","style","change","password","with","parameters","like","so",":"],"function":"def jsonrpc_change_password_first_time(auth_path):\n \"\"\"Accept a JSONRPC-style change password, with parameters like so:\n\n {\"jsonrpc\":\"2.0\",\"method\":\"setpassword\",\"params\":[\"username\",\"password\"],\"id\":1}\n\n This endpoint does not require the user to provide their existing password,\n but it can only be used when setting the administrator password for the first\n time. If a password is already set, this endpoint will return 403.\n\n This needs to be a separate endpoint from change_password because it is\n listed in auth.py as not requiring authentication cookies.\n \"\"\"\n data = json.loads(sys.stdin.read())\n try:\n params = data[\"params\"]\n username = params[0]\n new_password = params[1]\n except KeyError, e:\n common.render_error(e.__str__())\n except IndexError, e:\n common.render_error(e.__str__())\n\n a = auth.Auth(auth_path)\n if a.password_exists():\n common.render_error('Administrator password has already been set.')\n else:\n if not a.save_password(new_password):\n common.render_error(\"Invalid password supplied.\")\n remote_address = os.environ.get('REMOTE_ADDR')\n tokens = a.authenticate(new_password, remote_address)\n uci.set('openwireless.setup_state', 'setup-private-net')\n uci.commit('openwireless')\n print \"Content-Type: application\/json\"\n print a.login_headers(tokens)\n print\n print \"{}\"","function_tokens":["def","jsonrpc_change_password_first_time","(","auth_path",")",":","data","=","json",".","loads","(","sys",".","stdin",".","read","(",")",")","try",":","params","=","data","[","\"params\"","]","username","=","params","[","0","]","new_password","=","params","[","1","]","except","KeyError",",","e",":","common",".","render_error","(","e",".","__str__","(",")",")","except","IndexError",",","e",":","common",".","render_error","(","e",".","__str__","(",")",")","a","=","auth",".","Auth","(","auth_path",")","if","a",".","password_exists","(",")",":","common",".","render_error","(","'Administrator password has already been set.'",")","else",":","if","not","a",".","save_password","(","new_password",")",":","common",".","render_error","(","\"Invalid password supplied.\"",")","remote_address","=","os",".","environ",".","get","(","'REMOTE_ADDR'",")","tokens","=","a",".","authenticate","(","new_password",",","remote_address",")","uci",".","set","(","'openwireless.setup_state'",",","'setup-private-net'",")","uci",".","commit","(","'openwireless'",")","print","\"Content-Type: application\/json\"","print","a",".","login_headers","(","tokens",")","print","print","\"{}\""],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/routerapi\/change_password_first_time.py#L10-L45"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"lib\/update\/update.py","language":"python","identifier":"Updater.valid_sig","parameters":"(self)","argument_list":"","return_statement":"return True","docstring":"Is self.purported_manifest correctly signed by a trusted key?","docstring_summary":"Is self.purported_manifest correctly signed by a trusted key?","docstring_tokens":["Is","self",".","purported_manifest","correctly","signed","by","a","trusted","key?"],"function":"def valid_sig(self):\n \"\"\"Is self.purported_manifest correctly signed by a trusted key?\"\"\"\n if not self.purported_manifest:\n return False\n in_fd, out_fd = os.pipe()\n command = [\"gpg\", \"--keyring\", keyring, \"--no-default-keyring\", \"--status-fd\", str(out_fd), \"--decrypt\"]\n p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n proc_stdout, proc_stderr = p.communicate(self.purported_manifest)\n if p.returncode != 0:\n return False\n print \"verification reported successful\"\n status = os.read(in_fd, 65536).split(\"\\n\")\n print \"status_fd output = \", status\n print \"proc_stdout = \", proc_stdout\n print \"all nonempty lines start with [GNUPG:]? \", all(bool(re.match(r\"^\\[GNUPG:\\]\", L) or not L) for L in status)\n if not all(bool(re.match(r\"^\\[GNUPG:\\]\", L) or not L) for L in status):\n return False\n if not any(re.match(r\"^\\[GNUPG:\\] GOODSIG \", L) for L in status):\n return False\n if not any(re.match(r\"^\\[GNUPG:\\] VALIDSIG \", L) for L in status):\n return False\n self.signed_manifest = proc_stdout\n return True","function_tokens":["def","valid_sig","(","self",")",":","if","not","self",".","purported_manifest",":","return","False","in_fd",",","out_fd","=","os",".","pipe","(",")","command","=","[","\"gpg\"",",","\"--keyring\"",",","keyring",",","\"--no-default-keyring\"",",","\"--status-fd\"",",","str","(","out_fd",")",",","\"--decrypt\"","]","p","=","subprocess",".","Popen","(","command",",","stdin","=","subprocess",".","PIPE",",","stdout","=","subprocess",".","PIPE",",","stderr","=","subprocess",".","PIPE",")","proc_stdout",",","proc_stderr","=","p",".","communicate","(","self",".","purported_manifest",")","if","p",".","returncode","!=","0",":","return","False","print","\"verification reported successful\"","status","=","os",".","read","(","in_fd",",","65536",")",".","split","(","\"\\n\"",")","print","\"status_fd output = \"",",","status","print","\"proc_stdout = \"",",","proc_stdout","print","\"all nonempty lines start with [GNUPG:]? \"",",","all","(","bool","(","re",".","match","(","r\"^\\[GNUPG:\\]\"",",","L",")","or","not","L",")","for","L","in","status",")","if","not","all","(","bool","(","re",".","match","(","r\"^\\[GNUPG:\\]\"",",","L",")","or","not","L",")","for","L","in","status",")",":","return","False","if","not","any","(","re",".","match","(","r\"^\\[GNUPG:\\] GOODSIG \"",",","L",")","for","L","in","status",")",":","return","False","if","not","any","(","re",".","match","(","r\"^\\[GNUPG:\\] VALIDSIG \"",",","L",")","for","L","in","status",")",":","return","False","self",".","signed_manifest","=","proc_stdout","return","True"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/lib\/update\/update.py#L51-L73"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"OWrt\/pbkdf2.py","language":"python","identifier":"crypt","parameters":"(word, salt=None, iterations=None)","argument_list":"","return_statement":"return salt + \"$\" + b64encode(rawhash, \".\/\")","docstring":"PBKDF2-based unix crypt(3) replacement.\n\n The number of iterations specified in the salt overrides the 'iterations'\n parameter.\n\n The effective hash length is 192 bits.","docstring_summary":"PBKDF2-based unix crypt(3) replacement.","docstring_tokens":["PBKDF2","-","based","unix","crypt","(","3",")","replacement","."],"function":"def crypt(word, salt=None, iterations=None):\n \"\"\"PBKDF2-based unix crypt(3) replacement.\n\n The number of iterations specified in the salt overrides the 'iterations'\n parameter.\n\n The effective hash length is 192 bits.\n \"\"\"\n\n # Generate a (pseudo-)random salt if the user hasn't provided one.\n if salt is None:\n salt = _makesalt()\n\n # salt must be a string or the us-ascii subset of unicode\n if isunicode(salt):\n salt = salt.encode('us-ascii').decode('us-ascii')\n elif isbytes(salt):\n salt = salt.decode('us-ascii')\n else:\n raise TypeError(\"salt must be a string\")\n\n # word must be a string or unicode (in the latter case, we convert to UTF-8)\n if isunicode(word):\n word = word.encode(\"UTF-8\")\n elif not isbytes(word):\n raise TypeError(\"word must be a string or unicode\")\n\n # Try to extract the real salt and iteration count from the salt\n if salt.startswith(\"$p5k2$\"):\n (iterations, salt, dummy) = salt.split(\"$\")[2:5]\n if iterations == \"\":\n iterations = 400\n else:\n converted = int(iterations, 16)\n if iterations != \"%x\" % converted: # lowercase hex, minimum digits\n raise ValueError(\"Invalid salt\")\n iterations = converted\n if not (iterations >= 1):\n raise ValueError(\"Invalid salt\")\n\n # Make sure the salt matches the allowed character set\n allowed = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.\/\"\n for ch in salt:\n if ch not in allowed:\n raise ValueError(\"Illegal character %r in salt\" % (ch,))\n\n if iterations is None or iterations == 400:\n iterations = 400\n salt = \"$p5k2$$\" + salt\n else:\n salt = \"$p5k2$%x$%s\" % (iterations, salt)\n rawhash = PBKDF2(word, salt, iterations).read(24)\n return salt + \"$\" + b64encode(rawhash, \".\/\")","function_tokens":["def","crypt","(","word",",","salt","=","None",",","iterations","=","None",")",":","# Generate a (pseudo-)random salt if the user hasn't provided one.","if","salt","is","None",":","salt","=","_makesalt","(",")","# salt must be a string or the us-ascii subset of unicode","if","isunicode","(","salt",")",":","salt","=","salt",".","encode","(","'us-ascii'",")",".","decode","(","'us-ascii'",")","elif","isbytes","(","salt",")",":","salt","=","salt",".","decode","(","'us-ascii'",")","else",":","raise","TypeError","(","\"salt must be a string\"",")","# word must be a string or unicode (in the latter case, we convert to UTF-8)","if","isunicode","(","word",")",":","word","=","word",".","encode","(","\"UTF-8\"",")","elif","not","isbytes","(","word",")",":","raise","TypeError","(","\"word must be a string or unicode\"",")","# Try to extract the real salt and iteration count from the salt","if","salt",".","startswith","(","\"$p5k2$\"",")",":","(","iterations",",","salt",",","dummy",")","=","salt",".","split","(","\"$\"",")","[","2",":","5","]","if","iterations","==","\"\"",":","iterations","=","400","else",":","converted","=","int","(","iterations",",","16",")","if","iterations","!=","\"%x\"","%","converted",":","# lowercase hex, minimum digits","raise","ValueError","(","\"Invalid salt\"",")","iterations","=","converted","if","not","(","iterations",">=","1",")",":","raise","ValueError","(","\"Invalid salt\"",")","# Make sure the salt matches the allowed character set","allowed","=","\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.\/\"","for","ch","in","salt",":","if","ch","not","in","allowed",":","raise","ValueError","(","\"Illegal character %r in salt\"","%","(","ch",",",")",")","if","iterations","is","None","or","iterations","==","400",":","iterations","=","400","salt","=","\"$p5k2$$\"","+","salt","else",":","salt","=","\"$p5k2$%x$%s\"","%","(","iterations",",","salt",")","rawhash","=","PBKDF2","(","word",",","salt",",","iterations",")",".","read","(","24",")","return","salt","+","\"$\"","+","b64encode","(","rawhash",",","\".\/\"",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/OWrt\/pbkdf2.py#L229-L281"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"OWrt\/pbkdf2.py","language":"python","identifier":"_makesalt","parameters":"()","argument_list":"","return_statement":"return b64encode(binarysalt, \".\/\")","docstring":"Return a 48-bit pseudorandom salt for crypt().\n\n This function is not suitable for generating cryptographic secrets.","docstring_summary":"Return a 48-bit pseudorandom salt for crypt().","docstring_tokens":["Return","a","48","-","bit","pseudorandom","salt","for","crypt","()","."],"function":"def _makesalt():\n \"\"\"Return a 48-bit pseudorandom salt for crypt().\n\n This function is not suitable for generating cryptographic secrets.\n \"\"\"\n binarysalt = b(\"\").join([pack(\"@H\", randint(0, 0xffff)) for i in range(3)])\n return b64encode(binarysalt, \".\/\")","function_tokens":["def","_makesalt","(",")",":","binarysalt","=","b","(","\"\"",")",".","join","(","[","pack","(","\"@H\"",",","randint","(","0",",","0xffff",")",")","for","i","in","range","(","3",")","]",")","return","b64encode","(","binarysalt",",","\".\/\"",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/OWrt\/pbkdf2.py#L288-L294"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"OWrt\/pbkdf2.py","language":"python","identifier":"PBKDF2._pseudorandom","parameters":"(self, key, msg)","argument_list":"","return_statement":"return self.__macmodule.new(key=key, msg=msg,\n digestmod=self.__digestmodule).digest()","docstring":"Pseudorandom function. e.g. HMAC-SHA1","docstring_summary":"Pseudorandom function. e.g. HMAC-SHA1","docstring_tokens":["Pseudorandom","function",".","e",".","g",".","HMAC","-","SHA1"],"function":"def _pseudorandom(self, key, msg):\n \"\"\"Pseudorandom function. e.g. HMAC-SHA1\"\"\"\n return self.__macmodule.new(key=key, msg=msg,\n digestmod=self.__digestmodule).digest()","function_tokens":["def","_pseudorandom","(","self",",","key",",","msg",")",":","return","self",".","__macmodule",".","new","(","key","=","key",",","msg","=","msg",",","digestmod","=","self",".","__digestmodule",")",".","digest","(",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/OWrt\/pbkdf2.py#L142-L145"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"OWrt\/pbkdf2.py","language":"python","identifier":"PBKDF2.read","parameters":"(self, bytes)","argument_list":"","return_statement":"return retval","docstring":"Read the specified number of key bytes.","docstring_summary":"Read the specified number of key bytes.","docstring_tokens":["Read","the","specified","number","of","key","bytes","."],"function":"def read(self, bytes):\n \"\"\"Read the specified number of key bytes.\"\"\"\n if self.closed:\n raise ValueError(\"file-like object is closed\")\n\n size = len(self.__buf)\n blocks = [self.__buf]\n i = self.__blockNum\n while size < bytes:\n i += 1\n if i > _0xffffffffL or i < 1:\n # We could return \"\" here, but\n raise OverflowError(\"derived key too long\")\n block = self.__f(i)\n blocks.append(block)\n size += len(block)\n buf = b(\"\").join(blocks)\n retval = buf[:bytes]\n self.__buf = buf[bytes:]\n self.__blockNum = i\n return retval","function_tokens":["def","read","(","self",",","bytes",")",":","if","self",".","closed",":","raise","ValueError","(","\"file-like object is closed\"",")","size","=","len","(","self",".","__buf",")","blocks","=","[","self",".","__buf","]","i","=","self",".","__blockNum","while","size","<","bytes",":","i","+=","1","if","i",">","_0xffffffffL","or","i","<","1",":","# We could return \"\" here, but","raise","OverflowError","(","\"derived key too long\"",")","block","=","self",".","__f","(","i",")","blocks",".","append","(","block",")","size","+=","len","(","block",")","buf","=","b","(","\"\"",")",".","join","(","blocks",")","retval","=","buf","[",":","bytes","]","self",".","__buf","=","buf","[","bytes",":","]","self",".","__blockNum","=","i","return","retval"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/OWrt\/pbkdf2.py#L147-L167"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"OWrt\/pbkdf2.py","language":"python","identifier":"PBKDF2.hexread","parameters":"(self, octets)","argument_list":"","return_statement":"return b2a_hex(self.read(octets))","docstring":"Read the specified number of octets. Return them as hexadecimal.\n\n Note that len(obj.hexread(n)) == 2*n.","docstring_summary":"Read the specified number of octets. Return them as hexadecimal.","docstring_tokens":["Read","the","specified","number","of","octets",".","Return","them","as","hexadecimal","."],"function":"def hexread(self, octets):\n \"\"\"Read the specified number of octets. Return them as hexadecimal.\n\n Note that len(obj.hexread(n)) == 2*n.\n \"\"\"\n return b2a_hex(self.read(octets))","function_tokens":["def","hexread","(","self",",","octets",")",":","return","b2a_hex","(","self",".","read","(","octets",")",")"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/OWrt\/pbkdf2.py#L179-L184"}
{"nwo":"EFForg\/OpenWireless","sha":"9a93f9ed6033751d121c6851e86375b2b4912ab2","path":"OWrt\/pbkdf2.py","language":"python","identifier":"PBKDF2.close","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Close the stream.","docstring_summary":"Close the stream.","docstring_tokens":["Close","the","stream","."],"function":"def close(self):\n \"\"\"Close the stream.\"\"\"\n if not self.closed:\n del self.__passphrase\n del self.__salt\n del self.__iterations\n del self.__prf\n del self.__blockNum\n del self.__buf\n self.closed = True","function_tokens":["def","close","(","self",")",":","if","not","self",".","closed",":","del","self",".","__passphrase","del","self",".","__salt","del","self",".","__iterations","del","self",".","__prf","del","self",".","__blockNum","del","self",".","__buf","self",".","closed","=","True"],"url":"https:\/\/github.com\/EFForg\/OpenWireless\/blob\/9a93f9ed6033751d121c6851e86375b2b4912ab2\/OWrt\/pbkdf2.py#L218-L227"}