idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
241,700 | def _parse_bracketed_uri_scheme ( self ) : self . _push ( contexts . EXT_LINK_URI ) if self . _read ( ) == self . _read ( 1 ) == "/" : self . _emit_text ( "//" ) self . _head += 2 else : valid = "abcdefghijklmnopqrstuvwxyz0123456789+.-" all_valid = lambda : all ( char in valid for char in self . _read ( ) ) scheme = ""... | Parse the URI scheme of a bracket - enclosed external link . |
241,701 | def _handle_free_link_text ( self , punct , tail , this ) : if "(" in this and ")" in punct : punct = punct [ : - 1 ] if this . endswith ( punct ) : for i in range ( len ( this ) - 1 , 0 , - 1 ) : if this [ i - 1 ] not in punct : break else : i = 0 stripped = this [ : i ] if stripped and tail : self . _emit_text ( tail... | Handle text in a free ext link including trailing punctuation . |
241,702 | def _is_free_link_end ( self , this , next ) : after , ctx = self . _read ( 2 ) , self . _context equal_sign_contexts = contexts . TEMPLATE_PARAM_KEY | contexts . HEADING return ( this in ( self . END , "\n" , "[" , "]" , "<" , ">" ) or this == next == "'" or ( this == "|" and ctx & contexts . TEMPLATE ) or ( this == "... | Return whether the current head is the end of a free link . |
241,703 | def _really_parse_external_link ( self , brackets ) : if brackets : self . _parse_bracketed_uri_scheme ( ) invalid = ( "\n" , " " , "]" ) else : self . _parse_free_uri_scheme ( ) invalid = ( "\n" , " " , "[" , "]" ) punct = tuple ( ",;\\.:!?)" ) if self . _read ( ) is self . END or self . _read ( ) [ 0 ] in invalid : s... | Really parse an external link . |
241,704 | def _remove_uri_scheme_from_textbuffer ( self , scheme ) : length = len ( scheme ) while length : if length < len ( self . _textbuffer [ - 1 ] ) : self . _textbuffer [ - 1 ] = self . _textbuffer [ - 1 ] [ : - length ] break length -= len ( self . _textbuffer [ - 1 ] ) self . _textbuffer . pop ( ) | Remove the URI scheme of a new external link from the textbuffer . |
241,705 | def _parse_external_link ( self , brackets ) : if self . _context & contexts . NO_EXT_LINKS or not self . _can_recurse ( ) : if not brackets and self . _context & contexts . DL_TERM : self . _handle_dl_term ( ) else : self . _emit_text ( self . _read ( ) ) return reset = self . _head self . _head += 1 try : link , extr... | Parse an external link at the head of the wikicode string . |
241,706 | def _parse_heading ( self ) : self . _global |= contexts . GL_HEADING reset = self . _head self . _head += 1 best = 1 while self . _read ( ) == "=" : best += 1 self . _head += 1 context = contexts . HEADING_LEVEL_1 << min ( best - 1 , 5 ) try : title , level = self . _parse ( context ) except BadRoute : self . _head = ... | Parse a section heading at the head of the wikicode string . |
241,707 | def _handle_heading_end ( self ) : reset = self . _head self . _head += 1 best = 1 while self . _read ( ) == "=" : best += 1 self . _head += 1 current = int ( log ( self . _context / contexts . HEADING_LEVEL_1 , 2 ) ) + 1 level = min ( current , min ( best , 6 ) ) try : after , after_level = self . _parse ( self . _con... | Handle the end of a section heading at the head of the string . |
241,708 | def _really_parse_entity ( self ) : self . _emit ( tokens . HTMLEntityStart ( ) ) self . _head += 1 this = self . _read ( strict = True ) if this == "#" : numeric = True self . _emit ( tokens . HTMLEntityNumeric ( ) ) self . _head += 1 this = self . _read ( strict = True ) if this [ 0 ] . lower ( ) == "x" : hexadecimal... | Actually parse an HTML entity and ensure that it is valid . |
241,709 | def _parse_entity ( self ) : reset = self . _head try : self . _push ( contexts . HTML_ENTITY ) self . _really_parse_entity ( ) except BadRoute : self . _head = reset self . _emit_text ( self . _read ( ) ) else : self . _emit_all ( self . _pop ( ) ) | Parse an HTML entity at the head of the wikicode string . |
241,710 | def _parse_comment ( self ) : self . _head += 4 reset = self . _head - 1 self . _push ( ) while True : this = self . _read ( ) if this == self . END : self . _pop ( ) self . _head = reset self . _emit_text ( "<!--" ) return if this == self . _read ( 1 ) == "-" and self . _read ( 2 ) == ">" : self . _emit_first ( tokens... | Parse an HTML comment at the head of the wikicode string . |
241,711 | def _handle_blacklisted_tag ( self ) : strip = lambda text : text . rstrip ( ) . lower ( ) while True : this , next = self . _read ( ) , self . _read ( 1 ) if this is self . END : self . _fail_route ( ) elif this == "<" and next == "/" : self . _head += 3 if self . _read ( ) != ">" or ( strip ( self . _read ( - 1 ) ) !... | Handle the body of an HTML tag that is parser - blacklisted . |
241,712 | def _handle_single_only_tag_end ( self ) : padding = self . _stack . pop ( ) . padding self . _emit ( tokens . TagCloseSelfclose ( padding = padding , implicit = True ) ) self . _head -= 1 return self . _pop ( ) | Handle the end of an implicitly closing single - only HTML tag . |
241,713 | def _handle_single_tag_end ( self ) : stack = self . _stack depth = 1 for index , token in enumerate ( stack [ 2 : ] , 2 ) : if isinstance ( token , tokens . TagOpenOpen ) : depth += 1 elif isinstance ( token , tokens . TagCloseOpen ) : depth -= 1 if depth == 0 : break elif isinstance ( token , tokens . TagCloseSelfclo... | Handle the stream end when inside a single - supporting HTML tag . |
241,714 | def _parse_tag ( self ) : reset = self . _head self . _head += 1 try : tag = self . _really_parse_tag ( ) except BadRoute : self . _head = reset self . _emit_text ( "<" ) else : self . _emit_all ( tag ) | Parse an HTML tag at the head of the wikicode string . |
241,715 | def _emit_style_tag ( self , tag , markup , body ) : self . _emit ( tokens . TagOpenOpen ( wiki_markup = markup ) ) self . _emit_text ( tag ) self . _emit ( tokens . TagCloseOpen ( ) ) self . _emit_all ( body ) self . _emit ( tokens . TagOpenClose ( ) ) self . _emit_text ( tag ) self . _emit ( tokens . TagCloseClose ( ... | Write the body of a tag and the tokens that should surround it . |
241,716 | def _parse_italics ( self ) : reset = self . _head try : stack = self . _parse ( contexts . STYLE_ITALICS ) except BadRoute as route : self . _head = reset if route . context & contexts . STYLE_PASS_AGAIN : new_ctx = contexts . STYLE_ITALICS | contexts . STYLE_SECOND_PASS stack = self . _parse ( new_ctx ) else : return... | Parse wiki - style italics . |
241,717 | def _parse_bold ( self ) : reset = self . _head try : stack = self . _parse ( contexts . STYLE_BOLD ) except BadRoute : self . _head = reset if self . _context & contexts . STYLE_SECOND_PASS : self . _emit_text ( "'" ) return True elif self . _context & contexts . STYLE_ITALICS : self . _context |= contexts . STYLE_PAS... | Parse wiki - style bold . |
241,718 | def _emit_table_tag ( self , open_open_markup , tag , style , padding , close_open_markup , contents , open_close_markup ) : self . _emit ( tokens . TagOpenOpen ( wiki_markup = open_open_markup ) ) self . _emit_text ( tag ) if style : self . _emit_all ( style ) if close_open_markup : self . _emit ( tokens . TagCloseOpe... | Emit a table tag . |
241,719 | def _handle_table_style ( self , end_token ) : data = _TagOpenData ( ) data . context = _TagOpenData . CX_ATTR_READY while True : this = self . _read ( ) can_exit = ( not data . context & data . CX_QUOTED or data . context & data . CX_NOTE_SPACE ) if this == end_token and can_exit : if data . context & ( data . CX_ATTR... | Handle style attributes for a table until end_token . |
241,720 | def _parse_table ( self ) : reset = self . _head self . _head += 2 try : self . _push ( contexts . TABLE_OPEN ) padding = self . _handle_table_style ( "\n" ) except BadRoute : self . _head = reset self . _emit_text ( "{" ) return style = self . _pop ( ) self . _head += 1 restore_point = self . _stack_ident try : table ... | Parse a wikicode table by starting with the first line . |
241,721 | def _handle_table_row ( self ) : self . _head += 2 if not self . _can_recurse ( ) : self . _emit_text ( "|-" ) self . _head -= 1 return self . _push ( contexts . TABLE_OPEN | contexts . TABLE_ROW_OPEN ) padding = self . _handle_table_style ( "\n" ) style = self . _pop ( ) self . _head += 1 row = self . _parse ( context... | Parse as style until end of the line then continue . |
241,722 | def _handle_table_cell ( self , markup , tag , line_context ) : old_context = self . _context padding , style = "" , None self . _head += len ( markup ) reset = self . _head if not self . _can_recurse ( ) : self . _emit_text ( markup ) self . _head -= 1 return cell = self . _parse ( contexts . TABLE_OPEN | contexts . T... | Parse as normal syntax unless we hit a style marker then parse style as HTML attributes and the remainder as normal syntax . |
241,723 | def _handle_table_cell_end ( self , reset_for_style = False ) : if reset_for_style : self . _context |= contexts . TABLE_CELL_STYLE else : self . _context &= ~ contexts . TABLE_CELL_STYLE return self . _pop ( keep_context = True ) | Returns the current context with the TABLE_CELL_STYLE flag set if it is necessary to reset and parse style attributes . |
241,724 | def _handle_end ( self ) : if self . _context & contexts . FAIL : if self . _context & contexts . TAG_BODY : if is_single ( self . _stack [ 1 ] . text ) : return self . _handle_single_tag_end ( ) if self . _context & contexts . TABLE_CELL_OPEN : self . _pop ( ) if self . _context & contexts . DOUBLE : self . _pop ( ) s... | Handle the end of the stream of wikitext . |
241,725 | def _verify_safe ( self , this ) : context = self . _context if context & contexts . FAIL_NEXT : return False if context & contexts . WIKILINK_TITLE : if this == "]" or this == "{" : self . _context |= contexts . FAIL_NEXT elif this == "\n" or this == "[" or this == "}" or this == ">" : return False elif this == "<" : ... | Make sure we are not trying to write an invalid character . |
241,726 | def tokenize ( self , text , context = 0 , skip_style_tags = False ) : split = self . regex . split ( text ) self . _text = [ segment for segment in split if segment ] self . _head = self . _global = self . _depth = 0 self . _bad_routes = set ( ) self . _skip_style_tags = skip_style_tags try : tokens = self . _parse ( ... | Build a list of tokens from a string of wikicode and return it . |
241,727 | def _value_needs_quotes ( val ) : if not val : return None val = "" . join ( str ( node ) for node in val . filter_text ( recursive = False ) ) if not any ( char . isspace ( ) for char in val ) : return None if "'" in val and '"' not in val : return '"' if '"' in val and "'" not in val : return "'" return "\"'" | Return valid quotes for the given value or None if unneeded . |
241,728 | def _set_padding ( self , attr , value ) : if not value : setattr ( self , attr , "" ) else : value = str ( value ) if not value . isspace ( ) : raise ValueError ( "padding must be entirely whitespace" ) setattr ( self , attr , value ) | Setter for the value of a padding attribute . |
241,729 | def coerce_quotes ( quotes ) : orig , quotes = quotes , str ( quotes ) if quotes else None if quotes not in [ None , '"' , "'" ] : raise ValueError ( "{!r} is not a valid quote type" . format ( orig ) ) return quotes | Coerce a quote type into an acceptable value or raise an error . |
241,730 | def _indexed_ifilter ( self , recursive = True , matches = None , flags = FLAGS , forcetype = None ) : match = self . _build_matcher ( matches , flags ) if recursive : restrict = forcetype if recursive == self . RECURSE_OTHERS else None def getter ( i , node ) : for ch in self . _get_children ( node , restrict = restri... | Iterate over nodes and their corresponding indices in the node list . |
241,731 | def _get_tree ( self , code , lines , marker , indent ) : def write ( * args ) : if lines and lines [ - 1 ] is marker : lines . pop ( ) last = lines . pop ( ) lines . append ( last + " " . join ( args ) ) else : lines . append ( " " * 6 * indent + " " . join ( args ) ) get = lambda code : self . _get_tree ( code , line... | Build a tree to illustrate the way the Wikicode object was parsed . |
241,732 | def _build_filter_methods ( cls , ** meths ) : doc = make_ifilter = lambda ftype : ( lambda self , * a , ** kw : self . ifilter ( forcetype = ftype , * a , ** kw ) ) make_filter = lambda ftype : ( lambda self , * a , ** kw : self . filter ( forcetype = ftype , * a , ** kw ) ) for name , ftype in ( meths . items ( ) if ... | Given Node types build the corresponding i?filter shortcuts . |
241,733 | def matches ( self , other ) : cmp = lambda a , b : ( a [ 0 ] . upper ( ) + a [ 1 : ] == b [ 0 ] . upper ( ) + b [ 1 : ] if a and b else a == b ) this = self . strip_code ( ) . strip ( ) if isinstance ( other , ( str , bytes , Wikicode , Node ) ) : that = parse_anything ( other ) . strip_code ( ) . strip ( ) return cmp... | Do a loose equivalency test suitable for comparing page names . |
241,734 | def ifilter ( self , recursive = True , matches = None , flags = FLAGS , forcetype = None ) : gen = self . _indexed_ifilter ( recursive , matches , flags , forcetype ) return ( node for i , node in gen ) | Iterate over nodes in our list matching certain conditions . |
241,735 | def get_sections ( self , levels = None , matches = None , flags = FLAGS , flat = False , include_lead = None , include_headings = True ) : title_matcher = self . _build_matcher ( matches , flags ) matcher = lambda heading : ( title_matcher ( heading . title ) and ( not levels or heading . level in levels ) ) iheadings... | Return a list of sections within the page . |
241,736 | def strip_code ( self , normalize = True , collapse = True , keep_template_params = False ) : kwargs = { "normalize" : normalize , "collapse" : collapse , "keep_template_params" : keep_template_params } nodes = [ ] for node in self . nodes : stripped = node . __strip__ ( ** kwargs ) if stripped : nodes . append ( str (... | Return a rendered string without unprintable code such as templates . |
241,737 | def write_pid_file ( fn ) : if not fn : return None if fn == '' or fn == "''" : return None f = open ( fn , "w" ) f . write ( "%s\n" % ( os . getpid ( ) ) ) f . close ( ) | Create a file with our PID . |
241,738 | def input_validate_str ( string , name , max_len = None , exact_len = None ) : if type ( string ) is not str : raise pyhsm . exception . YHSM_WrongInputType ( name , str , type ( string ) ) if max_len != None and len ( string ) > max_len : raise pyhsm . exception . YHSM_InputTooLong ( name , max_len , len ( string ) ) ... | Input validation for strings . |
241,739 | def input_validate_int ( value , name , max_value = None ) : if type ( value ) is not int : raise pyhsm . exception . YHSM_WrongInputType ( name , int , type ( value ) ) if max_value != None and value > max_value : raise pyhsm . exception . YHSM_WrongInputSize ( name , max_value , value ) return value | Input validation for integers . |
241,740 | def input_validate_nonce ( nonce , name = 'nonce' , pad = False ) : if type ( nonce ) is not str : raise pyhsm . exception . YHSM_WrongInputType ( name , str , type ( nonce ) ) if len ( nonce ) > pyhsm . defines . YSM_AEAD_NONCE_SIZE : raise pyhsm . exception . YHSM_InputTooLong ( name , pyhsm . defines . YSM_AEAD_NONC... | Input validation for nonces . |
241,741 | def input_validate_key_handle ( key_handle , name = 'key_handle' ) : if type ( key_handle ) is not int : try : return key_handle_to_int ( key_handle ) except pyhsm . exception . YHSM_Error : raise pyhsm . exception . YHSM_WrongInputType ( name , int , type ( key_handle ) ) return key_handle | Input validation for key_handles . |
241,742 | def input_validate_yubikey_secret ( data , name = 'data' ) : if isinstance ( data , pyhsm . aead_cmd . YHSM_YubiKeySecret ) : data = data . pack ( ) return input_validate_str ( data , name ) | Input validation for YHSM_YubiKeySecret or string . |
241,743 | def input_validate_aead ( aead , name = 'aead' , expected_len = None , max_aead_len = pyhsm . defines . YSM_AEAD_MAX_SIZE ) : if isinstance ( aead , pyhsm . aead_cmd . YHSM_GeneratedAEAD ) : aead = aead . data if expected_len != None : return input_validate_str ( aead , name , exact_len = expected_len ) else : return i... | Input validation for YHSM_GeneratedAEAD or string . |
241,744 | def validate_cmd_response_nonce ( got , used ) : if used == '000000000000' . decode ( 'hex' ) : if got == used : raise ( pyhsm . exception . YHSM_Error ( "Bad nonce in response (got %s, expected HSM generated nonce)" % ( got . encode ( 'hex' ) ) ) ) return got return validate_cmd_response_str ( 'nonce' , got , used ) | Check that the returned nonce matches nonce used in request . |
241,745 | def _raw_pack ( key_handle , flags , data ) : return struct . pack ( '<IBB' , key_handle , flags , len ( data ) ) + data | Common code for packing payload to YHSM_HMAC_SHA1_GENERATE command . |
241,746 | def next ( self , data , final = False , to_buffer = False ) : if final : self . flags = pyhsm . defines . YSM_HMAC_SHA1_FINAL else : self . flags = 0x0 if to_buffer : self . flags |= pyhsm . defines . YSM_HMAC_SHA1_TO_BUFFER self . payload = _raw_pack ( self . key_handle , self . flags , data ) self . final = final re... | Add more input to the HMAC SHA1 . |
241,747 | def get_hash ( self ) : if not self . executed : raise pyhsm . exception . YHSM_Error ( "HMAC-SHA1 hash not available, before execute()." ) return self . result . hash_result | Get the HMAC - SHA1 that has been calculated this far . |
241,748 | def check_signature ( params ) : if 'id' in params : try : id_int = int ( params [ 'id' ] [ 0 ] ) except : my_log_message ( args , syslog . LOG_INFO , "Non-numerical client id (%s) in request." % ( params [ 'id' ] [ 0 ] ) ) return False , None key = client_ids . get ( id_int ) if key : if 'h' in params : sig = params [... | Verify the signature of the parameters in an OTP v2 . 0 verify request . |
241,749 | def validate_oath_hotp ( self , params ) : from_key = params [ "hotp" ] [ 0 ] if not re . match ( hotp_valid_input , from_key ) : self . log_error ( "IN: %s, Invalid OATH-HOTP OTP" % ( params ) ) return "ERR Invalid OATH-HOTP OTP" uid , otp , = get_oath_hotp_bits ( params ) if not uid or not otp : self . log_error ( "I... | Validate OATH - HOTP code using YubiHSM HMAC - SHA1 hashing with token keys secured in AEAD s that we have stored in an SQLite3 database . |
241,750 | def validate_oath_totp ( self , params ) : from_key = params [ "totp" ] [ 0 ] if not re . match ( totp_valid_input , from_key ) : self . log_error ( "IN: %s, Invalid OATH-TOTP OTP" % ( params ) ) return "ERR Invalid OATH-TOTP OTP" uid , otp , = get_oath_totp_bits ( params ) if not uid or not otp : self . log_error ( "I... | Validate OATH - TOTP code using YubiHSM HMAC - SHA1 hashing with token keys secured in AEAD s that we have stored in an SQLite3 database . |
241,751 | def validate_pwhash ( _self , params ) : pwhash , nonce , aead , key_handle = get_pwhash_bits ( params ) d_aead = aead . decode ( 'hex' ) plaintext_len = len ( d_aead ) - pyhsm . defines . YSM_AEAD_MAC_SIZE pw = pwhash . ljust ( plaintext_len , chr ( 0x0 ) ) if hsm . validate_aead ( nonce . decode ( 'hex' ) , key_handl... | Validate password hash using YubiHSM . |
241,752 | def get_pwhash_bits ( params ) : if not "pwhash" in params or not "nonce" in params or not "aead" in params or not "kh" in params : raise Exception ( "Missing required parameter in request (pwhash, nonce, aead or kh)" ) pwhash = params [ "pwhash" ] [ 0 ] nonce = params [ "nonce" ] [ 0 ] aead = params [ "aead" ] [ 0 ] k... | Extract bits for password hash validation from params . |
241,753 | def get_oath_hotp_bits ( params ) : if "uid" in params : return params [ "uid" ] [ 0 ] , int ( params [ "hotp" ] [ 0 ] ) m = re . match ( "^([cbdefghijklnrtuv]*)([0-9]{6,8})" , params [ "hotp" ] [ 0 ] ) uid , otp , = m . groups ( ) return uid , int ( otp ) , | Extract the OATH - HOTP uid and OTP from params . |
241,754 | def load_clients_file ( filename ) : res = { } content = [ ] try : fhandle = file ( filename ) content = fhandle . readlines ( ) fhandle . close ( ) except IOError : return None linenum = 0 for line in content : linenum += 1 while line . endswith ( "\r" ) or line . endswith ( "\n" ) : line = line [ : - 1 ] if re . matc... | Load a list of base64 encoded shared secrets for numerical client ids . |
241,755 | def run ( ) : server_address = ( args . listen_addr , args . listen_port ) httpd = YHSM_VALServer ( server_address , YHSM_VALRequestHandler ) my_log_message ( args , syslog . LOG_INFO , "Serving requests to 'http://%s:%s%s' (YubiHSM: '%s')" % ( args . listen_addr , args . listen_port , args . serve_url , args . device ... | Start the BaseHTTPServer and serve requests forever . |
241,756 | def main ( ) : my_name = os . path . basename ( sys . argv [ 0 ] ) if not my_name : my_name = "yhsm-validation-server" syslog . openlog ( my_name , syslog . LOG_PID , syslog . LOG_LOCAL0 ) global args args = parse_args ( ) args_fixup ( ) global hsm try : hsm = pyhsm . YHSM ( device = args . device , debug = args . debu... | The main function that will be executed when running this as a stand alone script . |
241,757 | def do_GET ( self ) : if self . path . startswith ( args . serve_url ) : res = None log_res = None mode = None params = urlparse . parse_qs ( self . path [ len ( args . serve_url ) : ] ) if "otp" in params : if args . mode_short_otp : mode = 'YubiKey OTP (short)' res = validate_yubikey_otp_short ( self , params ) elif ... | Process validation GET requests . |
241,758 | def get ( self , key ) : c = self . conn . cursor ( ) for row in c . execute ( "SELECT key, nonce, key_handle, aead, oath_C, oath_T FROM oath WHERE key = ?" , ( key , ) ) : return ValOathEntry ( row ) raise Exception ( "OATH token for '%s' not found in database (%s)" % ( key , self . filename ) ) | Fetch entry from database . |
241,759 | def update_oath_hotp_c ( self , entry , new_c ) : key = entry . data [ "key" ] c = self . conn . cursor ( ) c . execute ( "UPDATE oath SET oath_c = ? WHERE key = ? AND ? > oath_c" , ( new_c , key , new_c , ) ) self . conn . commit ( ) return c . rowcount == 1 | Update the OATH - HOTP counter value for entry in the database . |
241,760 | def generate_aead ( hsm , args , password ) : try : pw = password . ljust ( args . min_len , chr ( 0x0 ) ) return hsm . generate_aead_simple ( args . nonce . decode ( 'hex' ) , args . key_handle , pw ) except pyhsm . exception . YHSM_CommandFailed , e : if e . status_str == 'YHSM_FUNCTION_DISABLED' : print "ERROR: The ... | Generate an AEAD using the YubiHSM . |
241,761 | def aead_filename ( aead_dir , key_handle , public_id ) : parts = [ aead_dir , key_handle ] + pyhsm . util . group ( public_id , 2 ) path = os . path . join ( * parts ) if not os . path . isdir ( path ) : os . makedirs ( path ) return os . path . join ( path , public_id ) | Return the filename of the AEAD for this public_id and create any missing directorys . |
241,762 | def safe_process_files ( path , files , args , state ) : for fn in files : full_fn = os . path . join ( path , fn ) try : if not process_file ( path , fn , args , state ) : return False except Exception , e : sys . stderr . write ( "error: %s\n%s\n" % ( os . path . join ( path , fn ) , traceback . format_exc ( ) ) ) st... | Process a number of files in a directory . Catches any exception from the processing and checks if we should fail directly or keep going . |
241,763 | def walk_dir ( path , args , state ) : if args . debug : sys . stderr . write ( "Walking %s\n" % path ) for root , _dirs , files in os . walk ( path ) : if not safe_process_files ( root , files , args , state ) : return False if state . should_quit ( ) : return False return True | Check all files in path to see if there is any requests that we should send out on the bus . |
241,764 | def main ( ) : global args args = parse_args ( ) if not args : return 1 state = MyState ( args ) for path in args . paths : if os . path . isdir ( path ) : walk_dir ( path , args , state ) else : safe_process_files ( os . path . dirname ( path ) , [ os . path . basename ( path ) ] , args , state ) if state . should_qui... | Main function when running as a program . |
241,765 | def search_for_oath_code ( hsm , key_handle , nonce , aead , counter , user_code , look_ahead = 1 ) : key_handle = pyhsm . util . input_validate_key_handle ( key_handle ) nonce = pyhsm . util . input_validate_nonce ( nonce , pad = False ) aead = pyhsm . util . input_validate_aead ( aead ) counter = pyhsm . util . input... | Try to validate an OATH HOTP OTP generated by a token whose secret key is available to the YubiHSM through the AEAD . |
241,766 | def truncate ( hmac_result , length = 6 ) : assert ( len ( hmac_result ) == 20 ) offset = ord ( hmac_result [ 19 ] ) & 0xf bin_code = ( ord ( hmac_result [ offset ] ) & 0x7f ) << 24 | ( ord ( hmac_result [ offset + 1 ] ) & 0xff ) << 16 | ( ord ( hmac_result [ offset + 2 ] ) & 0xff ) << 8 | ( ord ( hmac_result [ offset ... | Perform the truncating . |
241,767 | def flush ( self ) : if self . debug : sys . stderr . write ( "%s: FLUSH INPUT (%i bytes waiting)\n" % ( self . __class__ . __name__ , self . ser . inWaiting ( ) ) ) self . ser . flushInput ( ) | Flush input buffers . |
241,768 | def drain ( self ) : if self . debug : sys . stderr . write ( "%s: DRAIN INPUT (%i bytes waiting)\n" % ( self . __class__ . __name__ , self . ser . inWaiting ( ) ) ) old_timeout = self . ser . timeout self . ser . timeout = 0.1 data = self . ser . read ( 1 ) while len ( data ) : if self . debug : sys . stderr . write (... | Drain input . |
241,769 | def extract_keyhandle ( path , filepath ) : keyhandle = filepath . lstrip ( path ) keyhandle = keyhandle . split ( "/" ) return keyhandle [ 0 ] | extract keyhandle value from the path |
241,770 | def insert_query ( connection , publicId , aead , keyhandle , aeadobj ) : keyhandle = key_handle_to_int ( keyhandle ) if not keyhandle == aead . key_handle : print ( "WARNING: keyhandle does not match aead.key_handle" ) return None try : sql = aeadobj . insert ( ) . values ( public_id = publicId , keyhandle = aead . ke... | this functions read the response fields and creates sql query . then inserts everything inside the database |
241,771 | def import_keys ( hsm , args ) : res = True for line in sys . stdin : if line [ 0 ] == '#' : continue l = line . split ( ',' ) modhex_id = l [ 1 ] uid = l [ 2 ] . decode ( 'hex' ) key = l [ 3 ] . decode ( 'hex' ) if modhex_id and uid and key : public_id = pyhsm . yubikey . modhex_decode ( modhex_id ) padded_id = modhex... | The main stdin iteration loop . |
241,772 | def shorten_aead ( aead ) : head = aead . data [ : 4 ] . encode ( 'hex' ) tail = aead . data [ - 4 : ] . encode ( 'hex' ) return "%s...%s" % ( head , tail ) | Produce pretty - printable version of long AEAD . |
241,773 | def output_filename ( output_dir , key_handle , public_id ) : parts = [ output_dir , key_handle ] + pyhsm . util . group ( public_id , 2 ) path = os . path . join ( * parts ) if not os . path . isdir ( path ) : os . makedirs ( path ) return os . path . join ( path , public_id ) | Return an output filename for a generated AEAD . Creates a hashed directory structure using the last three bytes of the public id to get equal usage . |
241,774 | def parse_result ( self , data ) : public_id , key_handle , self . status = struct . unpack ( "< %is I B" % ( pyhsm . defines . YSM_AEAD_NONCE_SIZE ) , data ) pyhsm . util . validate_cmd_response_str ( 'public_id' , public_id , self . public_id ) pyhsm . util . validate_cmd_response_hex ( 'key_handle' , key_handle , se... | Return True if the AEAD was stored sucessfully . |
241,775 | def gen_keys ( hsm , args ) : if args . verbose : print "Generating %i keys :\n" % ( args . count ) else : print "Generating %i keys" % ( args . count ) for int_id in range ( args . start_id , args . start_id + args . count ) : public_id = ( "%x" % int_id ) . rjust ( args . public_id_chars , '0' ) padded_id = pyhsm . y... | The main key generating loop . |
241,776 | def reset ( stick ) : nulls = ( pyhsm . defines . YSM_MAX_PKT_SIZE - 1 ) * '\x00' res = YHSM_Cmd ( stick , pyhsm . defines . YSM_NULL , payload = nulls ) . execute ( read_response = False ) unlock = stick . acquire ( ) try : stick . drain ( ) stick . flush ( ) finally : unlock ( ) return res == 0 | Send a bunch of zero - bytes to the YubiHSM and flush the input buffer . |
241,777 | def execute ( self , read_response = True ) : if self . command != pyhsm . defines . YSM_NULL : cmd_buf = struct . pack ( 'BB' , len ( self . payload ) + 1 , self . command ) else : cmd_buf = chr ( self . command ) cmd_buf += self . payload debug_info = None unlock = self . stick . acquire ( ) try : if self . stick . d... | Write command to HSM and read response . |
241,778 | def _read_response ( self ) : res = self . stick . read ( 2 , 'response length + response status' ) if len ( res ) != 2 : self . _handle_invalid_read_response ( res , 2 ) response_len , response_status = struct . unpack ( 'BB' , res ) response_len -= 1 debug_info = None if response_status & pyhsm . defines . YSM_RESPON... | After writing a command read response . |
241,779 | def reset ( self , test_sync = True ) : pyhsm . cmd . reset ( self . stick ) if test_sync : data = 'ekoeko' echo = self . echo ( data ) return data == echo else : return True | Perform stream resynchronization . |
241,780 | def set_debug ( self , new ) : if type ( new ) is not bool : raise pyhsm . exception . YHSM_WrongInputType ( 'new' , bool , type ( new ) ) old = self . debug self . debug = new self . stick . set_debug ( new ) return old | Set debug mode . |
241,781 | def echo ( self , data ) : return pyhsm . basic_cmd . YHSM_Cmd_Echo ( self . stick , data ) . execute ( ) | Echo test . |
241,782 | def random ( self , num_bytes ) : return pyhsm . basic_cmd . YHSM_Cmd_Random ( self . stick , num_bytes ) . execute ( ) | Get random bytes from YubiHSM . |
241,783 | def random_reseed ( self , seed ) : return pyhsm . basic_cmd . YHSM_Cmd_Random_Reseed ( self . stick , seed ) . execute ( ) | Provide YubiHSM DRBG_CTR with a new seed . |
241,784 | def get_nonce ( self , increment = 1 ) : return pyhsm . basic_cmd . YHSM_Cmd_Nonce_Get ( self . stick , increment ) . execute ( ) | Get current nonce from YubiHSM . |
241,785 | def load_temp_key ( self , nonce , key_handle , aead ) : return pyhsm . basic_cmd . YHSM_Cmd_Temp_Key_Load ( self . stick , nonce , key_handle , aead ) . execute ( ) | Load the contents of an AEAD into the phantom key handle 0xffffffff . |
241,786 | def load_secret ( self , secret ) : if isinstance ( secret , pyhsm . aead_cmd . YHSM_YubiKeySecret ) : secret = secret . pack ( ) return pyhsm . buffer_cmd . YHSM_Cmd_Buffer_Load ( self . stick , secret ) . execute ( ) | Ask YubiHSM to load a pre - existing YubiKey secret . |
241,787 | def load_data ( self , data , offset ) : return pyhsm . buffer_cmd . YHSM_Cmd_Buffer_Load ( self . stick , data , offset ) . execute ( ) | Ask YubiHSM to load arbitrary data into it s internal buffer at any offset . |
241,788 | def load_random ( self , num_bytes , offset = 0 ) : return pyhsm . buffer_cmd . YHSM_Cmd_Buffer_Random_Load ( self . stick , num_bytes , offset ) . execute ( ) | Ask YubiHSM to generate a number of random bytes to any offset of it s internal buffer . |
241,789 | def generate_aead_random ( self , nonce , key_handle , num_bytes ) : return pyhsm . aead_cmd . YHSM_Cmd_AEAD_Random_Generate ( self . stick , nonce , key_handle , num_bytes ) . execute ( ) | Generate a random AEAD block using the YubiHSM internal DRBG_CTR random generator . |
241,790 | def validate_aead_otp ( self , public_id , otp , key_handle , aead ) : if type ( public_id ) is not str : assert ( ) if type ( otp ) is not str : assert ( ) if type ( key_handle ) is not int : assert ( ) if type ( aead ) is not str : assert ( ) return pyhsm . validate_cmd . YHSM_Cmd_AEAD_Validate_OTP ( self . stick , p... | Ask YubiHSM to validate a YubiKey OTP using an AEAD and a key_handle to decrypt the AEAD . |
241,791 | def aes_ecb_encrypt ( self , key_handle , plaintext ) : return pyhsm . aes_ecb_cmd . YHSM_Cmd_AES_ECB_Encrypt ( self . stick , key_handle , plaintext ) . execute ( ) | AES ECB encrypt using a key handle . |
241,792 | def aes_ecb_decrypt ( self , key_handle , ciphertext ) : return pyhsm . aes_ecb_cmd . YHSM_Cmd_AES_ECB_Decrypt ( self . stick , key_handle , ciphertext ) . execute ( ) | AES ECB decrypt using a key handle . |
241,793 | def aes_ecb_compare ( self , key_handle , ciphertext , plaintext ) : return pyhsm . aes_ecb_cmd . YHSM_Cmd_AES_ECB_Compare ( self . stick , key_handle , ciphertext , plaintext ) . execute ( ) | AES ECB decrypt and then compare using a key handle . |
241,794 | def hmac_sha1 ( self , key_handle , data , flags = None , final = True , to_buffer = False ) : return pyhsm . hmac_cmd . YHSM_Cmd_HMAC_SHA1_Write ( self . stick , key_handle , data , flags = flags , final = final , to_buffer = to_buffer ) . execute ( ) | Have the YubiHSM generate a HMAC SHA1 of data using a key handle . |
241,795 | def db_validate_yubikey_otp ( self , public_id , otp ) : return pyhsm . db_cmd . YHSM_Cmd_DB_Validate_OTP ( self . stick , public_id , otp ) . execute ( ) | Request the YubiHSM to validate an OTP for a YubiKey stored in the internal database . |
241,796 | def aead_filename ( aead_dir , key_handle , public_id ) : parts = [ aead_dir , key_handle ] + pyhsm . util . group ( public_id , 2 ) + [ public_id ] return os . path . join ( * parts ) | Return the filename of the AEAD for this public_id . |
241,797 | def run ( hsm , aead_backend , args ) : write_pid_file ( args . pid_file ) server_address = ( args . listen_addr , args . listen_port ) httpd = YHSM_KSMServer ( server_address , partial ( YHSM_KSMRequestHandler , hsm , aead_backend , args ) ) my_log_message ( args . debug or args . verbose , syslog . LOG_INFO , "Servin... | Start a BaseHTTPServer . HTTPServer and serve requests forever . |
241,798 | def my_log_message ( verbose , prio , msg ) : syslog . syslog ( prio , msg ) if verbose or prio == syslog . LOG_ERR : sys . stderr . write ( "%s\n" % ( msg ) ) | Log to syslog and possibly also to stderr . |
241,799 | def do_GET ( self ) : if self . path . startswith ( self . serve_url ) : from_key = self . path [ len ( self . serve_url ) : ] val_res = self . decrypt_yubikey_otp ( from_key ) self . send_response ( 200 ) self . send_header ( 'Content-type' , 'text/html' ) self . end_headers ( ) self . wfile . write ( val_res ) self .... | Handle a HTTP GET request . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.