idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
240,800 | def echo ( self , data ) : return pyhsm . basic_cmd . YHSM_Cmd_Echo ( self . stick , data ) . execute ( ) | Echo test . | 36 | 4 |
240,801 | def random ( self , num_bytes ) : return pyhsm . basic_cmd . YHSM_Cmd_Random ( self . stick , num_bytes ) . execute ( ) | Get random bytes from YubiHSM . | 39 | 9 |
240,802 | 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 . | 41 | 16 |
240,803 | def get_nonce ( self , increment = 1 ) : return pyhsm . basic_cmd . YHSM_Cmd_Nonce_Get ( self . stick , increment ) . execute ( ) | Get current nonce from YubiHSM . | 43 | 10 |
240,804 | 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 . | 59 | 17 |
240,805 | 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 . | 71 | 16 |
240,806 | 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 . | 43 | 18 |
240,807 | 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 . | 51 | 21 |
240,808 | 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 . | 65 | 22 |
240,809 | 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 , public_id , otp , key_handle , aead ) . execute ( ) | Ask YubiHSM to validate a YubiKey OTP using an AEAD and a key_handle to decrypt the AEAD . | 126 | 28 |
240,810 | 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 . | 63 | 9 |
240,811 | 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 . | 63 | 9 |
240,812 | 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 . | 68 | 12 |
240,813 | 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 . | 84 | 19 |
240,814 | 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 . | 62 | 22 |
240,815 | 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 . | 63 | 13 |
240,816 | 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 , "Serving requests to 'http://%s:%s%s' with key handle(s) %s (YubiHSM: '%s', AEADs in '%s', DB in '%s')" % ( args . listen_addr , args . listen_port , args . serve_url , args . key_handles , args . device , args . aead_dir , args . db_url ) ) httpd . serve_forever ( ) | Start a BaseHTTPServer . HTTPServer and serve requests forever . | 207 | 14 |
240,817 | 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 . | 60 | 12 |
240,818 | def do_GET ( self ) : # Example session: # in : GET /wsapi/decrypt?otp=ftftftccccdvvbfcfduvvcubikngtchlubtutucrld HTTP/1.0 # out : OK counter=0004 low=f585 high=3e use=03 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 . wfile . write ( "\n" ) elif self . stats_url and self . path == self . stats_url : self . send_response ( 200 ) self . send_header ( 'Content-type' , 'text/html' ) self . end_headers ( ) for key in stats : self . wfile . write ( "%s %d\n" % ( key , stats [ key ] ) ) else : self . log_error ( "Bad URL '%s' - I'm serving '%s' (responding 403)" % ( self . path , self . serve_url ) ) self . send_response ( 403 , 'Forbidden' ) self . end_headers ( ) | Handle a HTTP GET request . | 323 | 6 |
240,819 | def decrypt_yubikey_otp ( self , from_key ) : if not re . match ( valid_input_from_key , from_key ) : self . log_error ( "IN: %s, Invalid OTP" % ( from_key ) ) if self . stats_url : stats [ 'invalid' ] += 1 return "ERR Invalid OTP" public_id , _otp = pyhsm . yubikey . split_id_otp ( from_key ) try : aead = self . aead_backend . load_aead ( public_id ) except Exception as e : self . log_error ( str ( e ) ) if self . stats_url : stats [ 'no_aead' ] += 1 return "ERR Unknown public_id" try : res = pyhsm . yubikey . validate_yubikey_with_aead ( self . hsm , from_key , aead , aead . key_handle ) # XXX double-check public_id in res, in case BaseHTTPServer suddenly becomes multi-threaded # XXX fix use vs session counter confusion val_res = "OK counter=%04x low=%04x high=%02x use=%02x" % ( res . use_ctr , res . ts_low , res . ts_high , res . session_ctr ) if self . stats_url : stats [ 'ok' ] += 1 except pyhsm . exception . YHSM_Error as e : self . log_error ( "IN: %s, Validate FAILED: %s" % ( from_key , str ( e ) ) ) val_res = "ERR" if self . stats_url : stats [ 'err' ] += 1 self . log_message ( "SUCCESS OTP %s PT hsm %s" , from_key , val_res ) return val_res | Try to decrypt a YubiKey OTP . | 424 | 10 |
240,820 | def my_address_string ( self ) : addr = getattr ( self , 'client_address' , ( '' , None ) ) [ 0 ] # If listed in proxy_ips, use the X-Forwarded-For header, if present. if addr in self . proxy_ips : return self . headers . getheader ( 'x-forwarded-for' , addr ) return addr | For logging client host without resolving . | 83 | 7 |
240,821 | def load_aead ( self , public_id ) : connection = self . engine . connect ( ) trans = connection . begin ( ) try : s = sqlalchemy . select ( [ self . aead_table ] ) . where ( ( self . aead_table . c . public_id == public_id ) & self . aead_table . c . keyhandle . in_ ( [ kh [ 1 ] for kh in self . key_handles ] ) ) result = connection . execute ( s ) for row in result : kh_int = row [ 'keyhandle' ] aead = pyhsm . aead_cmd . YHSM_GeneratedAEAD ( None , kh_int , '' ) aead . data = row [ 'aead' ] aead . nonce = row [ 'nonce' ] return aead except Exception as e : trans . rollback ( ) raise Exception ( "No AEAD in DB for public_id %s (%s)" % ( public_id , str ( e ) ) ) finally : connection . close ( ) | Loads AEAD from the specified database . | 231 | 9 |
240,822 | def generate_aead ( hsm , args ) : key = get_oath_k ( args ) # Enabled flags 00010000 = YSM_HMAC_SHA1_GENERATE flags = struct . pack ( "< I" , 0x10000 ) hsm . load_secret ( key + flags ) nonce = hsm . get_nonce ( ) . nonce aead = hsm . generate_aead ( nonce , args . key_handle ) if args . debug : print "AEAD: %s (%s)" % ( aead . data . encode ( 'hex' ) , aead ) return nonce , aead | Protect the oath - k in an AEAD . | 140 | 10 |
240,823 | def store_oath_entry ( args , nonce , aead , oath_c ) : data = { "key" : args . uid , "aead" : aead . data . encode ( 'hex' ) , "nonce" : nonce . encode ( 'hex' ) , "key_handle" : args . key_handle , "oath_C" : oath_c , "oath_T" : None , } entry = ValOathEntry ( data ) db = ValOathDb ( args . db_file ) try : if args . force : db . delete ( entry ) db . add ( entry ) except sqlite3 . IntegrityError , e : sys . stderr . write ( "ERROR: %s\n" % ( e ) ) return False return True | Store the AEAD in the database . | 174 | 8 |
240,824 | def add ( self , entry ) : c = self . conn . cursor ( ) c . execute ( "INSERT INTO oath (key, aead, nonce, key_handle, oath_C, oath_T) VALUES (?, ?, ?, ?, ?, ?)" , ( entry . data [ "key" ] , entry . data [ "aead" ] , entry . data [ "nonce" ] , entry . data [ "key_handle" ] , entry . data [ "oath_C" ] , entry . data [ "oath_T" ] , ) ) self . conn . commit ( ) return c . rowcount == 1 | Add entry to database . | 142 | 5 |
240,825 | def delete ( self , entry ) : c = self . conn . cursor ( ) c . execute ( "DELETE FROM oath WHERE key = ?" , ( entry . data [ "key" ] , ) ) | Delete entry from database . | 45 | 5 |
240,826 | def parse_result ( self , data ) : # typedef struct { # uint8_t nonce[YSM_AEAD_NONCE_SIZE]; // Nonce (publicId for Yubikey AEADs) # uint32_t keyHandle; // Key handle # YSM_STATUS status; // Status # uint8_t numBytes; // Number of bytes in AEAD block # uint8_t aead[YSM_AEAD_MAX_SIZE]; // AEAD block # } YSM_AEAD_GENERATE_RESP; nonce , key_handle , self . status , num_bytes = struct . unpack_from ( "< %is I B B" % ( pyhsm . defines . YSM_AEAD_NONCE_SIZE ) , data , 0 ) pyhsm . util . validate_cmd_response_hex ( 'key_handle' , key_handle , self . key_handle ) if self . status == pyhsm . defines . YSM_STATUS_OK : pyhsm . util . validate_cmd_response_nonce ( nonce , self . nonce ) offset = pyhsm . defines . YSM_AEAD_NONCE_SIZE + 6 aead = data [ offset : offset + num_bytes ] self . response = YHSM_GeneratedAEAD ( nonce , key_handle , aead ) return self . response else : raise pyhsm . exception . YHSM_CommandFailed ( pyhsm . defines . cmd2str ( self . command ) , self . status ) | Returns a YHSM_GeneratedAEAD instance or throws pyhsm . exception . YHSM_CommandFailed . | 347 | 27 |
240,827 | def save ( self , filename ) : aead_f = open ( filename , "wb" ) fmt = "< B I %is %is" % ( pyhsm . defines . YSM_AEAD_NONCE_SIZE , len ( self . data ) ) version = 1 packed = struct . pack ( fmt , version , self . key_handle , self . nonce , self . data ) aead_f . write ( YHSM_AEAD_File_Marker + packed ) aead_f . close ( ) | Store AEAD in a file . | 115 | 7 |
240,828 | def load ( self , filename ) : aead_f = open ( filename , "rb" ) buf = aead_f . read ( 1024 ) if buf . startswith ( YHSM_AEAD_CRLF_File_Marker ) : buf = YHSM_AEAD_File_Marker + buf [ len ( YHSM_AEAD_CRLF_File_Marker ) : ] if buf . startswith ( YHSM_AEAD_File_Marker ) : if buf [ len ( YHSM_AEAD_File_Marker ) ] == chr ( 1 ) : # version 1 format fmt = "< I %is" % ( pyhsm . defines . YSM_AEAD_NONCE_SIZE ) self . key_handle , self . nonce = struct . unpack_from ( fmt , buf , len ( YHSM_AEAD_File_Marker ) + 1 ) self . data = buf [ len ( YHSM_AEAD_File_Marker ) + 1 + struct . calcsize ( fmt ) : ] else : raise pyhsm . exception . YHSM_Error ( 'Unknown AEAD file format' ) else : # version 0 format, just AEAD data self . data = buf [ : pyhsm . defines . YSM_MAX_KEY_SIZE + pyhsm . defines . YSM_BLOCK_SIZE ] aead_f . close ( ) | Load AEAD from a file . | 318 | 7 |
240,829 | def pack ( self ) : # # 22-bytes Yubikey secrets block # typedef struct { # uint8_t key[KEY_SIZE]; // AES key # uint8_t uid[UID_SIZE]; // Unique (secret) ID # } YUBIKEY_SECRETS; return self . key + self . uid . ljust ( pyhsm . defines . UID_SIZE , chr ( 0 ) ) | Return key and uid packed for sending in a command to the YubiHSM . | 94 | 18 |
240,830 | def validate_otp ( hsm , args ) : try : res = pyhsm . yubikey . validate_otp ( hsm , args . otp ) if args . verbose : print "OK counter=%04x low=%04x high=%02x use=%02x" % ( res . use_ctr , res . ts_low , res . ts_high , res . session_ctr ) return 0 except pyhsm . exception . YHSM_CommandFailed , e : if args . verbose : print "%s" % ( pyhsm . defines . status2str ( e . status ) ) # figure out numerical response code for r in [ pyhsm . defines . YSM_OTP_INVALID , pyhsm . defines . YSM_OTP_REPLAY , pyhsm . defines . YSM_ID_NOT_FOUND ] : if e . status == r : return r - pyhsm . defines . YSM_RESPONSE # not found return 0xff | Validate an OTP . | 227 | 6 |
240,831 | def search_for_oath_code ( hsm , key_handle , nonce , aead , user_code , interval = 30 , tolerance = 0 ) : # timecounter is the lowest acceptable value based on tolerance timecounter = timecode ( datetime . datetime . now ( ) , interval ) - tolerance return search_hotp ( hsm , key_handle , nonce , aead , timecounter , user_code , 1 + 2 * tolerance ) | Try to validate an OATH TOTP OTP generated by a token whose secret key is available to the YubiHSM through the AEAD . | 99 | 31 |
240,832 | def timecode ( time_now , interval ) : i = time . mktime ( time_now . timetuple ( ) ) return int ( i / interval ) | make integer and divide by time interval of valid OTP | 34 | 11 |
240,833 | def _xor_block ( a , b ) : return '' . join ( [ chr ( ord ( x ) ^ ord ( y ) ) for ( x , y ) in zip ( a , b ) ] ) | XOR two blocks of equal length . | 46 | 8 |
240,834 | def crc16 ( data ) : m_crc = 0xffff for this in data : m_crc ^= ord ( this ) for _ in range ( 8 ) : j = m_crc & 1 m_crc >>= 1 if j : m_crc ^= 0x8408 return m_crc | Calculate an ISO13239 CRC checksum of the input buffer . | 72 | 15 |
240,835 | def finalize ( self , block ) : t1 = self . mac_aes . encrypt ( block ) t2 = _xor_block ( self . mac , t1 ) self . mac = t2 | The final step of CBC - MAC encrypts before xor . | 45 | 13 |
240,836 | def validate_otp ( hsm , from_key ) : public_id , otp = split_id_otp ( from_key ) return hsm . db_validate_yubikey_otp ( modhex_decode ( public_id ) . decode ( 'hex' ) , modhex_decode ( otp ) . decode ( 'hex' ) ) | Try to validate an OTP from a YubiKey using the internal database on the YubiHSM . | 84 | 22 |
240,837 | def validate_yubikey_with_aead ( hsm , from_key , aead , key_handle ) : from_key = pyhsm . util . input_validate_str ( from_key , 'from_key' , max_len = 48 ) nonce = aead . nonce aead = pyhsm . util . input_validate_aead ( aead ) key_handle = pyhsm . util . input_validate_key_handle ( key_handle ) public_id , otp = split_id_otp ( from_key ) public_id = modhex_decode ( public_id ) otp = modhex_decode ( otp ) if not nonce : nonce = public_id . decode ( 'hex' ) return hsm . validate_aead_otp ( nonce , otp . decode ( 'hex' ) , key_handle , aead ) | Try to validate an OTP from a YubiKey using the AEAD that can decrypt this YubiKey s internal secret using the key_handle for the AEAD . | 206 | 35 |
240,838 | def split_id_otp ( from_key ) : if len ( from_key ) > 32 : public_id , otp = from_key [ : - 32 ] , from_key [ - 32 : ] elif len ( from_key ) == 32 : public_id = '' otp = from_key else : raise pyhsm . exception . YHSM_Error ( "Bad from_key length %i < 32 : %s" % ( len ( from_key ) , from_key ) ) return public_id , otp | Separate public id from OTP given a YubiKey OTP as input . | 119 | 17 |
240,839 | def get_password ( hsm , args ) : expected_len = 32 name = 'HSM password' if hsm . version . have_key_store_decrypt ( ) : expected_len = 64 name = 'master key' if args . stdin : password = sys . stdin . readline ( ) while password and password [ - 1 ] == '\n' : password = password [ : - 1 ] else : if args . debug : password = raw_input ( 'Enter %s (press enter to skip) (will be echoed) : ' % ( name ) ) else : password = getpass . getpass ( 'Enter %s (press enter to skip) : ' % ( name ) ) if len ( password ) <= expected_len : password = password . decode ( 'hex' ) if not password : return None return password else : sys . stderr . write ( "ERROR: Invalid HSM password (expected max %i chars, got %i)\n" % ( expected_len , len ( password ) ) ) return 1 | Get password of correct length for this YubiHSM version . | 224 | 13 |
240,840 | def get_otp ( hsm , args ) : if args . no_otp : return None if hsm . version . have_unlock ( ) : if args . stdin : otp = sys . stdin . readline ( ) while otp and otp [ - 1 ] == '\n' : otp = otp [ : - 1 ] else : otp = raw_input ( 'Enter admin YubiKey OTP (press enter to skip) : ' ) if len ( otp ) == 44 : # YubiHSM admin OTP's always have a public_id length of 6 bytes return otp if otp : sys . stderr . write ( "ERROR: Invalid YubiKey OTP\n" ) return None | Get OTP from YubiKey . | 163 | 8 |
240,841 | def load ( self , df , centerings ) : centering_variables = dict ( ) if not df . empty and df . geometry . notna ( ) . any ( ) : for key , func in centerings . items ( ) : centering_variables [ key ] = func ( df ) return getattr ( ccrs , self . __class__ . __name__ ) ( * * { * * centering_variables , * * self . args } ) | A moderately mind - bendy meta - method which abstracts the internals of individual projections load procedures . | 100 | 21 |
240,842 | def load ( self , df , centerings ) : return super ( ) . load ( df , { key : value for key , value in centerings . items ( ) if key in self . filter_ } ) | Call load method with centerings filtered to keys in self . filter_ . | 44 | 15 |
240,843 | def gaussian_points ( loc = ( 0 , 0 ) , scale = ( 10 , 10 ) , n = 100 ) : arr = np . random . normal ( loc , scale , ( n , 2 ) ) return gpd . GeoSeries ( [ shapely . geometry . Point ( x , y ) for ( x , y ) in arr ] ) | Generates and returns n normally distributed points centered at loc with scale x and y directionality . | 74 | 19 |
240,844 | def classify_clusters ( points , n = 10 ) : arr = [ [ p . x , p . y ] for p in points . values ] clf = KMeans ( n_clusters = n ) clf . fit ( arr ) classes = clf . predict ( arr ) return classes | Return an array of K - Means cluster classes for an array of shapely . geometry . Point objects . | 64 | 21 |
240,845 | def gaussian_polygons ( points , n = 10 ) : gdf = gpd . GeoDataFrame ( data = { 'cluster_number' : classify_clusters ( points , n = n ) } , geometry = points ) polygons = [ ] for i in range ( n ) : sel_points = gdf [ gdf [ 'cluster_number' ] == i ] . geometry polygons . append ( shapely . geometry . MultiPoint ( [ ( p . x , p . y ) for p in sel_points ] ) . convex_hull ) polygons = [ p for p in polygons if ( not isinstance ( p , shapely . geometry . Point ) ) and ( not isinstance ( p , shapely . geometry . LineString ) ) ] return gpd . GeoSeries ( polygons ) | Returns an array of approximately n shapely . geometry . Polygon objects for an array of shapely . geometry . Point objects . | 181 | 26 |
240,846 | def gaussian_multi_polygons ( points , n = 10 ) : polygons = gaussian_polygons ( points , n * 2 ) # Randomly stitch them together. polygon_pairs = [ shapely . geometry . MultiPolygon ( list ( pair ) ) for pair in np . array_split ( polygons . values , n ) ] return gpd . GeoSeries ( polygon_pairs ) | Returns an array of approximately n shapely . geometry . MultiPolygon objects for an array of shapely . geometry . Point objects . | 91 | 27 |
240,847 | def uniform_random_global_points ( n = 100 ) : xs = np . random . uniform ( - 180 , 180 , n ) ys = np . random . uniform ( - 90 , 90 , n ) return [ shapely . geometry . Point ( x , y ) for x , y in zip ( xs , ys ) ] | Returns an array of n uniformally distributed shapely . geometry . Point objects . Points are coordinates distributed equivalently across the Earth s surface . | 73 | 28 |
240,848 | def uniform_random_global_network ( loc = 2000 , scale = 250 , n = 100 ) : arr = ( np . random . normal ( loc , scale , n ) ) . astype ( int ) return pd . DataFrame ( data = { 'mock_variable' : arr , 'from' : uniform_random_global_points ( n ) , 'to' : uniform_random_global_points ( n ) } ) | Returns an array of n uniformally randomly distributed shapely . geometry . Point objects . | 94 | 17 |
240,849 | def subpartition ( quadtree , nmin , nmax ) : subtrees = quadtree . split ( ) if quadtree . n > nmax : return [ q . partition ( nmin , nmax ) for q in subtrees ] elif any ( [ t . n < nmin for t in subtrees ] ) : return [ quadtree ] else : return [ q . partition ( nmin , nmax ) for q in subtrees ] | Recursive core of the QuadTree . partition method . Just five lines of code amazingly . | 95 | 18 |
240,850 | def split ( self ) : # TODO: Investigate why a small number of entries are lost every time this method is run. min_x , max_x , min_y , max_y = self . bounds mid_x , mid_y = ( min_x + max_x ) / 2 , ( min_y + max_y ) / 2 q1 = ( min_x , mid_x , mid_y , max_y ) q2 = ( min_x , mid_x , min_y , mid_y ) q3 = ( mid_x , max_x , mid_y , max_y ) q4 = ( mid_x , max_x , min_y , mid_y ) return [ QuadTree ( self . data , bounds = q1 ) , QuadTree ( self . data , bounds = q2 ) , QuadTree ( self . data , bounds = q3 ) , QuadTree ( self . data , bounds = q4 ) ] | Splits the current QuadTree instance four ways through the midpoint . | 211 | 14 |
240,851 | def partition ( self , nmin , nmax ) : if self . n < nmin : return [ self ] else : ret = subpartition ( self , nmin , nmax ) return flatten ( ret ) | This method call decomposes a QuadTree instances into a list of sub - QuadTree instances which are the smallest possible geospatial buckets given the current splitting rules containing at least thresh points . | 46 | 39 |
240,852 | def plot_state_to_ax ( state , ax ) : gplt . choropleth ( tickets . set_index ( 'id' ) . loc [ : , [ state , 'geometry' ] ] , hue = state , projection = gcrs . AlbersEqualArea ( ) , cmap = 'Blues' , linewidth = 0.0 , ax = ax ) gplt . polyplot ( boroughs , projection = gcrs . AlbersEqualArea ( ) , edgecolor = 'black' , linewidth = 0.5 , ax = ax ) | Reusable plotting wrapper . | 129 | 5 |
240,853 | def polyplot ( df , projection = None , extent = None , figsize = ( 8 , 6 ) , ax = None , edgecolor = 'black' , facecolor = 'None' , * * kwargs ) : # Initialize the figure. fig = _init_figure ( ax , figsize ) if projection : # Properly set up the projection. projection = projection . load ( df , { 'central_longitude' : lambda df : np . mean ( np . array ( [ p . x for p in df . geometry . centroid ] ) ) , 'central_latitude' : lambda df : np . mean ( np . array ( [ p . y for p in df . geometry . centroid ] ) ) } ) # Set up the axis. if not ax : ax = plt . subplot ( 111 , projection = projection ) else : if not ax : ax = plt . gca ( ) # Clean up patches. _lay_out_axes ( ax , projection ) # Immediately return if input geometry is empty. if len ( df . geometry ) == 0 : return ax # Set extent. extrema = _get_envelopes_min_maxes ( df . geometry . envelope . exterior ) _set_extent ( ax , projection , extent , extrema ) # Finally we draw the features. if projection : for geom in df . geometry : features = ShapelyFeature ( [ geom ] , ccrs . PlateCarree ( ) ) ax . add_feature ( features , facecolor = facecolor , edgecolor = edgecolor , * * kwargs ) else : for geom in df . geometry : try : # Duck test for MultiPolygon. for subgeom in geom : feature = descartes . PolygonPatch ( subgeom , facecolor = facecolor , edgecolor = edgecolor , * * kwargs ) ax . add_patch ( feature ) except ( TypeError , AssertionError ) : # Shapely Polygon. feature = descartes . PolygonPatch ( geom , facecolor = facecolor , edgecolor = edgecolor , * * kwargs ) ax . add_patch ( feature ) return ax | Trivial polygonal plot . | 468 | 8 |
240,854 | def choropleth ( df , projection = None , hue = None , scheme = None , k = 5 , cmap = 'Set1' , categorical = False , vmin = None , vmax = None , legend = False , legend_kwargs = None , legend_labels = None , extent = None , figsize = ( 8 , 6 ) , ax = None , * * kwargs ) : # Initialize the figure. fig = _init_figure ( ax , figsize ) if projection : projection = projection . load ( df , { 'central_longitude' : lambda df : np . mean ( np . array ( [ p . x for p in df . geometry . centroid ] ) ) , 'central_latitude' : lambda df : np . mean ( np . array ( [ p . y for p in df . geometry . centroid ] ) ) } ) # Set up the axis. if not ax : ax = plt . subplot ( 111 , projection = projection ) else : if not ax : ax = plt . gca ( ) # Clean up patches. _lay_out_axes ( ax , projection ) # Immediately return if input geometry is empty. if len ( df . geometry ) == 0 : return ax # Set extent. extrema = _get_envelopes_min_maxes ( df . geometry . envelope . exterior ) _set_extent ( ax , projection , extent , extrema ) # Format the data to be displayed for input. hue = _validate_hue ( df , hue ) if hue is None : raise ValueError ( "No 'hue' specified." ) # Generate the coloring information, if needed. Follows one of two schemes, categorical or continuous, # based on whether or not ``k`` is specified (``hue`` must be specified for either to work). if k is not None : # Categorical colormap code path. # Validate buckets. categorical , k , scheme = _validate_buckets ( categorical , k , scheme ) if hue is not None : cmap , categories , hue_values = _discrete_colorize ( categorical , hue , scheme , k , cmap , vmin , vmax ) colors = [ cmap . to_rgba ( v ) for v in hue_values ] # Add a legend, if appropriate. if legend : _paint_hue_legend ( ax , categories , cmap , legend_labels , legend_kwargs ) else : colors = [ 'steelblue' ] * len ( df ) elif k is None and hue is not None : # Continuous colormap code path. hue_values = hue cmap = _continuous_colormap ( hue_values , cmap , vmin , vmax ) colors = [ cmap . to_rgba ( v ) for v in hue_values ] # Add a legend, if appropriate. if legend : _paint_colorbar_legend ( ax , hue_values , cmap , legend_kwargs ) # Draw the features. if projection : for color , geom in zip ( colors , df . geometry ) : features = ShapelyFeature ( [ geom ] , ccrs . PlateCarree ( ) ) ax . add_feature ( features , facecolor = color , * * kwargs ) else : for color , geom in zip ( colors , df . geometry ) : try : # Duck test for MultiPolygon. for subgeom in geom : feature = descartes . PolygonPatch ( subgeom , facecolor = color , * * kwargs ) ax . add_patch ( feature ) except ( TypeError , AssertionError ) : # Shapely Polygon. feature = descartes . PolygonPatch ( geom , facecolor = color , * * kwargs ) ax . add_patch ( feature ) return ax | Area aggregation plot . | 837 | 4 |
240,855 | def _get_envelopes_min_maxes ( envelopes ) : xmin = np . min ( envelopes . map ( lambda linearring : np . min ( [ linearring . coords [ 1 ] [ 0 ] , linearring . coords [ 2 ] [ 0 ] , linearring . coords [ 3 ] [ 0 ] , linearring . coords [ 4 ] [ 0 ] ] ) ) ) xmax = np . max ( envelopes . map ( lambda linearring : np . max ( [ linearring . coords [ 1 ] [ 0 ] , linearring . coords [ 2 ] [ 0 ] , linearring . coords [ 3 ] [ 0 ] , linearring . coords [ 4 ] [ 0 ] ] ) ) ) ymin = np . min ( envelopes . map ( lambda linearring : np . min ( [ linearring . coords [ 1 ] [ 1 ] , linearring . coords [ 2 ] [ 1 ] , linearring . coords [ 3 ] [ 1 ] , linearring . coords [ 4 ] [ 1 ] ] ) ) ) ymax = np . max ( envelopes . map ( lambda linearring : np . max ( [ linearring . coords [ 1 ] [ 1 ] , linearring . coords [ 2 ] [ 1 ] , linearring . coords [ 3 ] [ 1 ] , linearring . coords [ 4 ] [ 1 ] ] ) ) ) return xmin , xmax , ymin , ymax | Returns the extrema of the inputted polygonal envelopes . Used for setting chart extent where appropriate . Note tha the Quadtree . bounds object property serves a similar role . | 317 | 37 |
240,856 | def _get_envelopes_centroid ( envelopes ) : xmin , xmax , ymin , ymax = _get_envelopes_min_maxes ( envelopes ) return np . mean ( xmin , xmax ) , np . mean ( ymin , ymax ) | Returns the centroid of an inputted geometry column . Not currently in use as this is now handled by this library s CRS wrapper directly . Light wrapper over _get_envelopes_min_maxes . | 64 | 44 |
240,857 | def _set_extent ( ax , projection , extent , extrema ) : if extent : xmin , xmax , ymin , ymax = extent xmin , xmax , ymin , ymax = max ( xmin , - 180 ) , min ( xmax , 180 ) , max ( ymin , - 90 ) , min ( ymax , 90 ) if projection : # Input ``extent`` into set_extent(). ax . set_extent ( ( xmin , xmax , ymin , ymax ) , crs = ccrs . PlateCarree ( ) ) else : # Input ``extent`` into set_ylim, set_xlim. ax . set_xlim ( ( xmin , xmax ) ) ax . set_ylim ( ( ymin , ymax ) ) else : xmin , xmax , ymin , ymax = extrema xmin , xmax , ymin , ymax = max ( xmin , - 180 ) , min ( xmax , 180 ) , max ( ymin , - 90 ) , min ( ymax , 90 ) if projection : # Input ``extrema`` into set_extent. ax . set_extent ( ( xmin , xmax , ymin , ymax ) , crs = ccrs . PlateCarree ( ) ) else : # Input ``extrema`` into set_ylim, set_xlim. ax . set_xlim ( ( xmin , xmax ) ) ax . set_ylim ( ( ymin , ymax ) ) | Sets the plot extent . | 337 | 6 |
240,858 | def _lay_out_axes ( ax , projection ) : if projection is not None : try : ax . background_patch . set_visible ( False ) ax . outline_patch . set_visible ( False ) except AttributeError : # Testing... pass else : plt . gca ( ) . axison = False | cartopy enables a a transparent background patch and an outline patch by default . This short method simply hides these extraneous visual features . If the plot is a pure matplotlib one it does the same thing by removing the axis altogether . | 69 | 47 |
240,859 | def _continuous_colormap ( hue , cmap , vmin , vmax ) : mn = min ( hue ) if vmin is None else vmin mx = max ( hue ) if vmax is None else vmax norm = mpl . colors . Normalize ( vmin = mn , vmax = mx ) return mpl . cm . ScalarMappable ( norm = norm , cmap = cmap ) | Creates a continuous colormap . | 95 | 8 |
240,860 | def _discrete_colorize ( categorical , hue , scheme , k , cmap , vmin , vmax ) : if not categorical : binning = _mapclassify_choro ( hue , scheme , k = k ) values = binning . yb binedges = [ binning . yb . min ( ) ] + binning . bins . tolist ( ) categories = [ '{0:.2f} - {1:.2f}' . format ( binedges [ i ] , binedges [ i + 1 ] ) for i in range ( len ( binedges ) - 1 ) ] else : categories = np . unique ( hue ) if len ( categories ) > 10 : warnings . warn ( "Generating a colormap using a categorical column with over 10 individual categories. " "This is not recommended!" ) value_map = { v : i for i , v in enumerate ( categories ) } values = [ value_map [ d ] for d in hue ] cmap = _norm_cmap ( values , cmap , mpl . colors . Normalize , mpl . cm , vmin = vmin , vmax = vmax ) return cmap , categories , values | Creates a discrete colormap either using an already - categorical data variable or by bucketing a non - categorical ordinal one . If a scheme is provided we compute a distribution for the given data . If one is not provided we assume that the input data is categorical . | 264 | 58 |
240,861 | def _norm_cmap ( values , cmap , normalize , cm , vmin = None , vmax = None ) : mn = min ( values ) if vmin is None else vmin mx = max ( values ) if vmax is None else vmax norm = normalize ( vmin = mn , vmax = mx ) n_cmap = cm . ScalarMappable ( norm = norm , cmap = cmap ) return n_cmap | Normalize and set colormap . Taken from geopandas | 103 | 13 |
240,862 | def get_version ( ) : proc = tmux_cmd ( '-V' ) if proc . stderr : if proc . stderr [ 0 ] == 'tmux: unknown option -- V' : if sys . platform . startswith ( "openbsd" ) : # openbsd has no tmux -V return LooseVersion ( '%s-openbsd' % TMUX_MAX_VERSION ) raise exc . LibTmuxException ( 'libtmux supports tmux %s and greater. This system' ' is running tmux 1.3 or earlier.' % TMUX_MIN_VERSION ) raise exc . VersionTooLow ( proc . stderr ) version = proc . stdout [ 0 ] . split ( 'tmux ' ) [ 1 ] # Allow latest tmux HEAD if version == 'master' : return LooseVersion ( '%s-master' % TMUX_MAX_VERSION ) version = re . sub ( r'[a-z-]' , '' , version ) return LooseVersion ( version ) | Return tmux version . | 232 | 6 |
240,863 | def has_minimum_version ( raises = True ) : if get_version ( ) < LooseVersion ( TMUX_MIN_VERSION ) : if raises : raise exc . VersionTooLow ( 'libtmux only supports tmux %s and greater. This system' ' has %s installed. Upgrade your tmux to use libtmux.' % ( TMUX_MIN_VERSION , get_version ( ) ) ) else : return False return True | Return if tmux meets version requirement . Version > 1 . 8 or above . | 97 | 17 |
240,864 | def session_check_name ( session_name ) : if not session_name or len ( session_name ) == 0 : raise exc . BadSessionName ( "tmux session names may not be empty." ) elif '.' in session_name : raise exc . BadSessionName ( "tmux session name \"%s\" may not contain periods." , session_name ) elif ':' in session_name : raise exc . BadSessionName ( "tmux session name \"%s\" may not contain colons." , session_name ) | Raises exception session name invalid modeled after tmux function . | 116 | 13 |
240,865 | def handle_option_error ( error ) : if 'unknown option' in error : raise exc . UnknownOption ( error ) elif 'invalid option' in error : raise exc . InvalidOption ( error ) elif 'ambiguous option' in error : raise exc . AmbiguousOption ( error ) else : raise exc . OptionError ( error ) | Raises exception if error in option command found . | 73 | 10 |
240,866 | def where ( self , attrs , first = False ) : # from https://github.com/serkanyersen/underscore.py def by ( val , * args ) : for key , value in attrs . items ( ) : try : if attrs [ key ] != val [ key ] : return False except KeyError : return False return True if first : return list ( filter ( by , self . children ) ) [ 0 ] else : return list ( filter ( by , self . children ) ) | Return objects matching child objects properties . | 107 | 7 |
240,867 | def get_by_id ( self , id ) : for child in self . children : if child [ self . child_id_attribute ] == id : return child else : continue return None | Return object based on child_id_attribute . | 40 | 10 |
240,868 | def select_window ( self ) : target = ( '%s:%s' % ( self . get ( 'session_id' ) , self . index ) , ) return self . session . select_window ( target ) | Select window . Return self . | 48 | 6 |
240,869 | def cmd ( self , * args , * * kwargs ) : args = list ( args ) if self . socket_name : args . insert ( 0 , '-L{0}' . format ( self . socket_name ) ) if self . socket_path : args . insert ( 0 , '-S{0}' . format ( self . socket_path ) ) if self . config_file : args . insert ( 0 , '-f{0}' . format ( self . config_file ) ) if self . colors : if self . colors == 256 : args . insert ( 0 , '-2' ) elif self . colors == 88 : args . insert ( 0 , '-8' ) else : raise ValueError ( 'Server.colors must equal 88 or 256' ) return tmux_cmd ( * args , * * kwargs ) | Execute tmux command and return output . | 187 | 10 |
240,870 | def switch_client ( self ) : proc = self . cmd ( 'switch-client' , '-t%s' % self . id ) if proc . stderr : raise exc . LibTmuxException ( proc . stderr ) | Switch client to this session . | 53 | 6 |
240,871 | def openpgp ( ctx ) : try : ctx . obj [ 'controller' ] = OpgpController ( ctx . obj [ 'dev' ] . driver ) except APDUError as e : if e . sw == SW . NOT_FOUND : ctx . fail ( "The OpenPGP application can't be found on this " 'YubiKey.' ) logger . debug ( 'Failed to load OpenPGP Application' , exc_info = e ) ctx . fail ( 'Failed to load OpenPGP Application' ) | Manage OpenPGP Application . | 120 | 7 |
240,872 | def info ( ctx ) : controller = ctx . obj [ 'controller' ] click . echo ( 'OpenPGP version: %d.%d.%d' % controller . version ) retries = controller . get_remaining_pin_tries ( ) click . echo ( 'PIN tries remaining: {}' . format ( retries . pin ) ) click . echo ( 'Reset code tries remaining: {}' . format ( retries . reset ) ) click . echo ( 'Admin PIN tries remaining: {}' . format ( retries . admin ) ) click . echo ( ) click . echo ( 'Touch policies' ) click . echo ( 'Signature key {.name}' . format ( controller . get_touch ( KEY_SLOT . SIGNATURE ) ) ) click . echo ( 'Encryption key {.name}' . format ( controller . get_touch ( KEY_SLOT . ENCRYPTION ) ) ) click . echo ( 'Authentication key {.name}' . format ( controller . get_touch ( KEY_SLOT . AUTHENTICATION ) ) ) | Display status of OpenPGP application . | 236 | 8 |
240,873 | def reset ( ctx ) : click . echo ( "Resetting OpenPGP data, don't remove your YubiKey..." ) ctx . obj [ 'controller' ] . reset ( ) click . echo ( 'Success! All data has been cleared and default PINs are set.' ) echo_default_pins ( ) | Reset OpenPGP application . | 68 | 7 |
240,874 | def touch ( ctx , key , policy , admin_pin , force ) : controller = ctx . obj [ 'controller' ] old_policy = controller . get_touch ( key ) if old_policy == TOUCH_MODE . FIXED : ctx . fail ( 'A FIXED policy cannot be changed!' ) force or click . confirm ( 'Set touch policy of {.name} key to {.name}?' . format ( key , policy ) , abort = True , err = True ) if admin_pin is None : admin_pin = click . prompt ( 'Enter admin PIN' , hide_input = True , err = True ) controller . set_touch ( key , policy , admin_pin . encode ( 'utf8' ) ) | Manage touch policy for OpenPGP keys . | 160 | 10 |
240,875 | def set_pin_retries ( ctx , pw_attempts , admin_pin , force ) : controller = ctx . obj [ 'controller' ] resets_pins = controller . version < ( 4 , 0 , 0 ) if resets_pins : click . echo ( 'WARNING: Setting PIN retries will reset the values for all ' '3 PINs!' ) force or click . confirm ( 'Set PIN retry counters to: {} {} {}?' . format ( * pw_attempts ) , abort = True , err = True ) controller . set_pin_retries ( * ( pw_attempts + ( admin_pin . encode ( 'utf8' ) , ) ) ) click . echo ( 'PIN retries successfully set.' ) if resets_pins : click . echo ( 'Default PINs are set.' ) echo_default_pins ( ) | Manage pin - retries . | 191 | 7 |
240,876 | def piv ( ctx ) : try : ctx . obj [ 'controller' ] = PivController ( ctx . obj [ 'dev' ] . driver ) except APDUError as e : if e . sw == SW . NOT_FOUND : ctx . fail ( "The PIV application can't be found on this YubiKey." ) raise | Manage PIV Application . | 78 | 6 |
240,877 | def info ( ctx ) : controller = ctx . obj [ 'controller' ] click . echo ( 'PIV version: %d.%d.%d' % controller . version ) # Largest possible number of PIN tries to get back is 15 tries = controller . get_pin_tries ( ) tries = '15 or more.' if tries == 15 else tries click . echo ( 'PIN tries remaining: %s' % tries ) if controller . puk_blocked : click . echo ( 'PUK blocked.' ) if controller . has_derived_key : click . echo ( 'Management key is derived from PIN.' ) if controller . has_stored_key : click . echo ( 'Management key is stored on the YubiKey, protected by PIN.' ) try : chuid = b2a_hex ( controller . get_data ( OBJ . CHUID ) ) . decode ( ) except APDUError as e : if e . sw == SW . NOT_FOUND : chuid = 'No data available.' click . echo ( 'CHUID:\t' + chuid ) try : ccc = b2a_hex ( controller . get_data ( OBJ . CAPABILITY ) ) . decode ( ) except APDUError as e : if e . sw == SW . NOT_FOUND : ccc = 'No data available.' click . echo ( 'CCC: \t' + ccc ) for ( slot , cert ) in controller . list_certificates ( ) . items ( ) : click . echo ( 'Slot %02x:' % slot ) try : # Try to read out full DN, fallback to only CN. # Support for DN was added in crytography 2.5 subject_dn = cert . subject . rfc4514_string ( ) issuer_dn = cert . issuer . rfc4514_string ( ) print_dn = True except AttributeError : print_dn = False logger . debug ( 'Failed to read DN, falling back to only CNs' ) subject_cn = cert . subject . get_attributes_for_oid ( x509 . NameOID . COMMON_NAME ) subject_cn = subject_cn [ 0 ] . value if subject_cn else 'None' issuer_cn = cert . issuer . get_attributes_for_oid ( x509 . NameOID . COMMON_NAME ) issuer_cn = issuer_cn [ 0 ] . value if issuer_cn else 'None' except ValueError as e : # Malformed certificates may throw ValueError logger . debug ( 'Failed parsing certificate' , exc_info = e ) click . echo ( '\tMalformed certificate: {}' . format ( e ) ) continue fingerprint = b2a_hex ( cert . fingerprint ( hashes . SHA256 ( ) ) ) . decode ( 'ascii' ) algo = ALGO . from_public_key ( cert . public_key ( ) ) serial = cert . serial_number not_before = cert . not_valid_before not_after = cert . not_valid_after # Print out everything click . echo ( '\tAlgorithm:\t%s' % algo . name ) if print_dn : click . echo ( '\tSubject DN:\t%s' % subject_dn ) click . echo ( '\tIssuer DN:\t%s' % issuer_dn ) else : click . echo ( '\tSubject CN:\t%s' % subject_cn ) click . echo ( '\tIssuer CN:\t%s' % issuer_cn ) click . echo ( '\tSerial:\t\t%s' % serial ) click . echo ( '\tFingerprint:\t%s' % fingerprint ) click . echo ( '\tNot before:\t%s' % not_before ) click . echo ( '\tNot after:\t%s' % not_after ) | Display status of PIV application . | 848 | 7 |
240,878 | def reset ( ctx ) : click . echo ( 'Resetting PIV data...' ) ctx . obj [ 'controller' ] . reset ( ) click . echo ( 'Success! All PIV data have been cleared from your YubiKey.' ) click . echo ( 'Your YubiKey now has the default PIN, PUK and Management Key:' ) click . echo ( '\tPIN:\t123456' ) click . echo ( '\tPUK:\t12345678' ) click . echo ( '\tManagement Key:\t010203040506070801020304050607080102030405060708' ) | Reset all PIV data . | 140 | 7 |
240,879 | def generate_key ( ctx , slot , public_key_output , management_key , pin , algorithm , format , pin_policy , touch_policy ) : dev = ctx . obj [ 'dev' ] controller = ctx . obj [ 'controller' ] _ensure_authenticated ( ctx , controller , pin , management_key ) algorithm_id = ALGO . from_string ( algorithm ) if pin_policy : pin_policy = PIN_POLICY . from_string ( pin_policy ) if touch_policy : touch_policy = TOUCH_POLICY . from_string ( touch_policy ) _check_pin_policy ( ctx , dev , controller , pin_policy ) _check_touch_policy ( ctx , controller , touch_policy ) try : public_key = controller . generate_key ( slot , algorithm_id , pin_policy , touch_policy ) except UnsupportedAlgorithm : ctx . fail ( 'Algorithm {} is not supported by this ' 'YubiKey.' . format ( algorithm ) ) key_encoding = format public_key_output . write ( public_key . public_bytes ( encoding = key_encoding , format = serialization . PublicFormat . SubjectPublicKeyInfo ) ) | Generate an asymmetric key pair . | 271 | 8 |
240,880 | def import_certificate ( ctx , slot , management_key , pin , cert , password , verify ) : controller = ctx . obj [ 'controller' ] _ensure_authenticated ( ctx , controller , pin , management_key ) data = cert . read ( ) while True : if password is not None : password = password . encode ( ) try : certs = parse_certificates ( data , password ) except ( ValueError , TypeError ) : if password is None : password = click . prompt ( 'Enter password to decrypt certificate' , default = '' , hide_input = True , show_default = False , err = True ) continue else : password = None click . echo ( 'Wrong password.' ) continue break if len ( certs ) > 1 : # If multiple certs, only import leaf. # Leaf is the cert with a subject that is not an issuer in the chain. leafs = get_leaf_certificates ( certs ) cert_to_import = leafs [ 0 ] else : cert_to_import = certs [ 0 ] def do_import ( retry = True ) : try : controller . import_certificate ( slot , cert_to_import , verify = verify , touch_callback = prompt_for_touch ) except KeypairMismatch : ctx . fail ( 'This certificate is not tied to the private key in the ' '{} slot.' . format ( slot . name ) ) except APDUError as e : if e . sw == SW . SECURITY_CONDITION_NOT_SATISFIED and retry : _verify_pin ( ctx , controller , pin ) do_import ( retry = False ) else : raise do_import ( ) | Import a X . 509 certificate . | 371 | 8 |
240,881 | def import_key ( ctx , slot , management_key , pin , private_key , pin_policy , touch_policy , password ) : dev = ctx . obj [ 'dev' ] controller = ctx . obj [ 'controller' ] _ensure_authenticated ( ctx , controller , pin , management_key ) data = private_key . read ( ) while True : if password is not None : password = password . encode ( ) try : private_key = parse_private_key ( data , password ) except ( ValueError , TypeError ) : if password is None : password = click . prompt ( 'Enter password to decrypt key' , default = '' , hide_input = True , show_default = False , err = True ) continue else : password = None click . echo ( 'Wrong password.' ) continue break if pin_policy : pin_policy = PIN_POLICY . from_string ( pin_policy ) if touch_policy : touch_policy = TOUCH_POLICY . from_string ( touch_policy ) _check_pin_policy ( ctx , dev , controller , pin_policy ) _check_touch_policy ( ctx , controller , touch_policy ) _check_key_size ( ctx , controller , private_key ) controller . import_key ( slot , private_key , pin_policy , touch_policy ) | Import a private key . | 296 | 5 |
240,882 | def export_certificate ( ctx , slot , format , certificate ) : controller = ctx . obj [ 'controller' ] try : cert = controller . read_certificate ( slot ) except APDUError as e : if e . sw == SW . NOT_FOUND : ctx . fail ( 'No certificate found.' ) else : logger . error ( 'Failed to read certificate from slot %s' , slot , exc_info = e ) certificate . write ( cert . public_bytes ( encoding = format ) ) | Export a X . 509 certificate . | 113 | 8 |
240,883 | def set_chuid ( ctx , management_key , pin ) : controller = ctx . obj [ 'controller' ] _ensure_authenticated ( ctx , controller , pin , management_key ) controller . update_chuid ( ) | Generate and set a CHUID on the YubiKey . | 53 | 13 |
240,884 | def set_ccc ( ctx , management_key , pin ) : controller = ctx . obj [ 'controller' ] _ensure_authenticated ( ctx , controller , pin , management_key ) controller . update_ccc ( ) | Generate and set a CCC on the YubiKey . | 53 | 13 |
240,885 | def generate_certificate ( ctx , slot , management_key , pin , public_key , subject , valid_days ) : controller = ctx . obj [ 'controller' ] _ensure_authenticated ( ctx , controller , pin , management_key , require_pin_and_key = True ) data = public_key . read ( ) public_key = serialization . load_pem_public_key ( data , default_backend ( ) ) now = datetime . datetime . now ( ) valid_to = now + datetime . timedelta ( days = valid_days ) try : controller . generate_self_signed_certificate ( slot , public_key , subject , now , valid_to , touch_callback = prompt_for_touch ) except APDUError as e : logger . error ( 'Failed to generate certificate for slot %s' , slot , exc_info = e ) ctx . fail ( 'Certificate generation failed.' ) | Generate a self - signed X . 509 certificate . | 212 | 12 |
240,886 | def change_pin ( ctx , pin , new_pin ) : controller = ctx . obj [ 'controller' ] if not pin : pin = _prompt_pin ( ctx , prompt = 'Enter your current PIN' ) if not new_pin : new_pin = click . prompt ( 'Enter your new PIN' , default = '' , hide_input = True , show_default = False , confirmation_prompt = True , err = True ) if not _valid_pin_length ( pin ) : ctx . fail ( 'Current PIN must be between 6 and 8 characters long.' ) if not _valid_pin_length ( new_pin ) : ctx . fail ( 'New PIN must be between 6 and 8 characters long.' ) try : controller . change_pin ( pin , new_pin ) click . echo ( 'New PIN set.' ) except AuthenticationBlocked as e : logger . debug ( 'PIN is blocked.' , exc_info = e ) ctx . fail ( 'PIN is blocked.' ) except WrongPin as e : logger . debug ( 'Failed to change PIN, %d tries left' , e . tries_left , exc_info = e ) ctx . fail ( 'PIN change failed - %d tries left.' % e . tries_left ) | Change the PIN code . | 275 | 5 |
240,887 | def change_puk ( ctx , puk , new_puk ) : controller = ctx . obj [ 'controller' ] if not puk : puk = _prompt_pin ( ctx , prompt = 'Enter your current PUK' ) if not new_puk : new_puk = click . prompt ( 'Enter your new PUK' , default = '' , hide_input = True , show_default = False , confirmation_prompt = True , err = True ) if not _valid_pin_length ( puk ) : ctx . fail ( 'Current PUK must be between 6 and 8 characters long.' ) if not _valid_pin_length ( new_puk ) : ctx . fail ( 'New PUK must be between 6 and 8 characters long.' ) try : controller . change_puk ( puk , new_puk ) click . echo ( 'New PUK set.' ) except AuthenticationBlocked as e : logger . debug ( 'PUK is blocked.' , exc_info = e ) ctx . fail ( 'PUK is blocked.' ) except WrongPuk as e : logger . debug ( 'Failed to change PUK, %d tries left' , e . tries_left , exc_info = e ) ctx . fail ( 'PUK change failed - %d tries left.' % e . tries_left ) | Change the PUK code . | 297 | 6 |
240,888 | def change_management_key ( ctx , management_key , pin , new_management_key , touch , protect , generate , force ) : controller = ctx . obj [ 'controller' ] pin_verified = _ensure_authenticated ( ctx , controller , pin , management_key , require_pin_and_key = protect , mgm_key_prompt = 'Enter your current management key ' '[blank to use default key]' , no_prompt = force ) if new_management_key and generate : ctx . fail ( 'Invalid options: --new-management-key conflicts with ' '--generate' ) # Touch not supported on NEO. if touch and controller . version < ( 4 , 0 , 0 ) : ctx . fail ( 'Require touch not supported on this YubiKey.' ) # If an old stored key needs to be cleared, the PIN is needed. if not pin_verified and controller . has_stored_key : if pin : _verify_pin ( ctx , controller , pin , no_prompt = force ) elif not force : click . confirm ( 'The current management key is stored on the YubiKey' ' and will not be cleared if no PIN is provided. Continue?' , abort = True , err = True ) if not new_management_key and not protect : if generate : new_management_key = generate_random_management_key ( ) if not protect : click . echo ( 'Generated management key: {}' . format ( b2a_hex ( new_management_key ) . decode ( 'utf-8' ) ) ) elif force : ctx . fail ( 'New management key not given. Please remove the --force ' 'flag, or set the --generate flag or the ' '--new-management-key option.' ) else : new_management_key = click . prompt ( 'Enter your new management key' , hide_input = True , confirmation_prompt = True , err = True ) if new_management_key and type ( new_management_key ) is not bytes : try : new_management_key = a2b_hex ( new_management_key ) except Exception : ctx . fail ( 'New management key has the wrong format.' ) try : controller . set_mgm_key ( new_management_key , touch = touch , store_on_device = protect ) except APDUError as e : logger . error ( 'Failed to change management key' , exc_info = e ) ctx . fail ( 'Changing the management key failed.' ) | Change the management key . | 556 | 5 |
240,889 | def unblock_pin ( ctx , puk , new_pin ) : controller = ctx . obj [ 'controller' ] if not puk : puk = click . prompt ( 'Enter PUK' , default = '' , show_default = False , hide_input = True , err = True ) if not new_pin : new_pin = click . prompt ( 'Enter a new PIN' , default = '' , show_default = False , hide_input = True , err = True ) controller . unblock_pin ( puk , new_pin ) | Unblock the PIN . | 121 | 5 |
240,890 | def read_object ( ctx , pin , object_id ) : controller = ctx . obj [ 'controller' ] def do_read_object ( retry = True ) : try : click . echo ( controller . get_data ( object_id ) ) except APDUError as e : if e . sw == SW . NOT_FOUND : ctx . fail ( 'No data found.' ) elif e . sw == SW . SECURITY_CONDITION_NOT_SATISFIED : _verify_pin ( ctx , controller , pin ) do_read_object ( retry = False ) else : raise do_read_object ( ) | Read arbitrary PIV object . | 146 | 6 |
240,891 | def write_object ( ctx , pin , management_key , object_id , data ) : controller = ctx . obj [ 'controller' ] _ensure_authenticated ( ctx , controller , pin , management_key ) def do_write_object ( retry = True ) : try : controller . put_data ( object_id , data . read ( ) ) except APDUError as e : logger . debug ( 'Failed writing object' , exc_info = e ) if e . sw == SW . INCORRECT_PARAMETERS : ctx . fail ( 'Something went wrong, is the object id valid?' ) raise do_write_object ( ) | Write an arbitrary PIV object . | 148 | 7 |
240,892 | def fido ( ctx ) : dev = ctx . obj [ 'dev' ] if dev . is_fips : try : ctx . obj [ 'controller' ] = FipsU2fController ( dev . driver ) except Exception as e : logger . debug ( 'Failed to load FipsU2fController' , exc_info = e ) ctx . fail ( 'Failed to load FIDO Application.' ) else : try : ctx . obj [ 'controller' ] = Fido2Controller ( dev . driver ) except Exception as e : logger . debug ( 'Failed to load Fido2Controller' , exc_info = e ) ctx . fail ( 'Failed to load FIDO 2 Application.' ) | Manage FIDO applications . | 160 | 7 |
240,893 | def info ( ctx ) : controller = ctx . obj [ 'controller' ] if controller . is_fips : click . echo ( 'FIPS Approved Mode: {}' . format ( 'Yes' if controller . is_in_fips_mode else 'No' ) ) else : if controller . has_pin : try : click . echo ( 'PIN is set, with {} tries left.' . format ( controller . get_pin_retries ( ) ) ) except CtapError as e : if e . code == CtapError . ERR . PIN_BLOCKED : click . echo ( 'PIN is blocked.' ) else : click . echo ( 'PIN is not set.' ) | Display status of FIDO2 application . | 150 | 9 |
240,894 | def reset ( ctx , force ) : n_keys = len ( list ( get_descriptors ( ) ) ) if n_keys > 1 : ctx . fail ( 'Only one YubiKey can be connected to perform a reset.' ) if not force : if not click . confirm ( 'WARNING! This will delete all FIDO credentials, ' 'including FIDO U2F credentials, and restore ' 'factory settings. Proceed?' , err = True ) : ctx . abort ( ) def prompt_re_insert_key ( ) : click . echo ( 'Remove and re-insert your YubiKey to perform the reset...' ) removed = False while True : sleep ( 0.1 ) n_keys = len ( list ( get_descriptors ( ) ) ) if not n_keys : removed = True if removed and n_keys == 1 : return def try_reset ( controller_type ) : if not force : prompt_re_insert_key ( ) dev = list ( get_descriptors ( ) ) [ 0 ] . open_device ( TRANSPORT . FIDO ) controller = controller_type ( dev . driver ) controller . reset ( touch_callback = prompt_for_touch ) else : controller = ctx . obj [ 'controller' ] controller . reset ( touch_callback = prompt_for_touch ) if ctx . obj [ 'dev' ] . is_fips : if not force : destroy_input = click . prompt ( 'WARNING! This is a YubiKey FIPS device. This command will ' 'also overwrite the U2F attestation key; this action cannot be ' 'undone and this YubiKey will no longer be a FIPS compliant ' 'device.\n' 'To proceed, please enter the text "OVERWRITE"' , default = '' , show_default = False , err = True ) if destroy_input != 'OVERWRITE' : ctx . fail ( 'Reset aborted by user.' ) try : try_reset ( FipsU2fController ) except ApduError as e : if e . code == SW . COMMAND_NOT_ALLOWED : ctx . fail ( 'Reset failed. Reset must be triggered within 5 seconds' ' after the YubiKey is inserted.' ) else : logger . error ( 'Reset failed' , exc_info = e ) ctx . fail ( 'Reset failed.' ) except Exception as e : logger . error ( 'Reset failed' , exc_info = e ) ctx . fail ( 'Reset failed.' ) else : try : try_reset ( Fido2Controller ) except CtapError as e : if e . code == CtapError . ERR . ACTION_TIMEOUT : ctx . fail ( 'Reset failed. You need to touch your' ' YubiKey to confirm the reset.' ) elif e . code == CtapError . ERR . NOT_ALLOWED : ctx . fail ( 'Reset failed. Reset must be triggered within 5 seconds' ' after the YubiKey is inserted.' ) else : logger . error ( e ) ctx . fail ( 'Reset failed.' ) except Exception as e : logger . error ( e ) ctx . fail ( 'Reset failed.' ) | Reset all FIDO applications . | 702 | 8 |
240,895 | def unlock ( ctx , pin ) : controller = ctx . obj [ 'controller' ] if not controller . is_fips : ctx . fail ( 'This is not a YubiKey FIPS, and therefore' ' does not support a U2F PIN.' ) if pin is None : pin = _prompt_current_pin ( 'Enter your PIN' ) _fail_if_not_valid_pin ( ctx , pin , True ) try : controller . verify_pin ( pin ) except ApduError as e : if e . code == SW . VERIFY_FAIL_NO_RETRY : ctx . fail ( 'Wrong PIN.' ) if e . code == SW . AUTH_METHOD_BLOCKED : ctx . fail ( 'PIN is blocked.' ) if e . code == SW . COMMAND_NOT_ALLOWED : ctx . fail ( 'PIN is not set.' ) logger . error ( 'PIN verification failed' , exc_info = e ) ctx . fail ( 'PIN verification failed.' ) | Verify U2F PIN for YubiKey FIPS . | 226 | 13 |
240,896 | def get_pin_tries ( self ) : # Verify without PIN gives number of tries left. _ , sw = self . send_cmd ( INS . VERIFY , 0 , PIN , check = None ) return tries_left ( sw , self . version ) | Returns the number of PIN retries left 0 PIN authentication blocked . Note that 15 is the highest value that will be returned even if remaining tries is higher . | 56 | 31 |
240,897 | def cli ( ctx , device , log_level , log_file , reader ) : ctx . obj = YkmanContextObject ( ) if log_level : ykman . logging_setup . setup ( log_level , log_file = log_file ) if reader and device : ctx . fail ( '--reader and --device options can\'t be combined.' ) subcmd = next ( c for c in COMMANDS if c . name == ctx . invoked_subcommand ) if subcmd == list_keys : if reader : ctx . fail ( '--reader and list command can\'t be combined.' ) return transports = getattr ( subcmd , 'transports' , TRANSPORT . usb_transports ( ) ) if transports : def resolve_device ( ) : if device is not None : dev = _run_cmd_for_serial ( ctx , subcmd . name , transports , device ) else : dev = _run_cmd_for_single ( ctx , subcmd . name , transports , reader ) ctx . call_on_close ( dev . close ) return dev ctx . obj . add_resolver ( 'dev' , resolve_device ) | Configure your YubiKey via the command line . | 259 | 11 |
240,898 | def list_keys ( ctx , serials , readers ) : if readers : for reader in list_readers ( ) : click . echo ( reader . name ) ctx . exit ( ) all_descriptors = get_descriptors ( ) descriptors = [ d for d in all_descriptors if d . key_type != YUBIKEY . SKY ] skys = len ( all_descriptors ) - len ( descriptors ) handled_serials = set ( ) for dev in list_devices ( ) : handled = False if skys > 0 and dev . key_type == YUBIKEY . SKY : skys -= 1 serial = None handled = True else : serial = dev . serial if serial not in handled_serials : handled_serials . add ( serial ) matches = [ d for d in descriptors if ( d . key_type , d . mode ) == ( dev . driver . key_type , dev . driver . mode ) ] if len ( matches ) > 0 : d = matches [ 0 ] descriptors . remove ( d ) handled = True if handled : if serials : if serial : click . echo ( serial ) else : click . echo ( '{} [{}]{}' . format ( dev . device_name , dev . mode , ' Serial: {}' . format ( serial ) if serial else '' ) ) dev . close ( ) if not descriptors and not skys : break | List connected YubiKeys . | 312 | 6 |
240,899 | def otp ( ctx , access_code ) : ctx . obj [ 'controller' ] = OtpController ( ctx . obj [ 'dev' ] . driver ) if access_code is not None : if access_code == '' : access_code = click . prompt ( 'Enter access code' , show_default = False , err = True ) try : access_code = parse_access_code_hex ( access_code ) except Exception as e : ctx . fail ( 'Failed to parse access code: ' + str ( e ) ) ctx . obj [ 'controller' ] . access_code = access_code | Manage OTP Application . | 137 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.