idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
52,900
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_validate_int ( counter , 'counter' ) user_code = pyhsm . util . input_validate_int ( user_code , 'user_code' ) hsm . load_temp_key ( nonce , key_handle , aead ) for j in xrange ( look_ahead ) : this_counter = counter + j secret = struct . pack ( "> Q" , this_counter ) hmac_result = hsm . hmac_sha1 ( pyhsm . defines . YSM_TEMP_KEY_HANDLE , secret ) . get_hash ( ) this_code = truncate ( hmac_result ) if this_code == user_code : return this_counter + 1 return None
Try to validate an OATH HOTP OTP generated by a token whose secret key is available to the YubiHSM through the AEAD .
52,901
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 + 3 ] ) & 0xff ) return bin_code % ( 10 ** length )
Perform the truncating .
52,902
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 .
52,903
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 ( "%s: DRAINED 0x%x (%c)\n" % ( self . __class__ . __name__ , ord ( data [ 0 ] ) , data [ 0 ] ) ) data = self . ser . read ( 1 ) self . ser . timeout = old_timeout return True
Drain input .
52,904
def extract_keyhandle ( path , filepath ) : keyhandle = filepath . lstrip ( path ) keyhandle = keyhandle . split ( "/" ) return keyhandle [ 0 ]
extract keyhandle value from the path
52,905
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 . key_handle , nonce = aead . nonce , aead = aead . data ) result = connection . execute ( sql ) return result except sqlalchemy . exc . IntegrityError : pass return None
this functions read the response fields and creates sql query . then inserts everything inside the database
52,906
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_id . rjust ( args . public_id_chars , 'c' ) if int ( public_id , 16 ) == 0 : print "WARNING: Skipping import of key with public ID: %s" % ( padded_id ) print "This public ID is unsupported by the YubiHSM.\n" continue if args . verbose : print " %s" % ( padded_id ) secret = pyhsm . aead_cmd . YHSM_YubiKeySecret ( key , uid ) hsm . load_secret ( secret ) for kh in args . key_handles . keys ( ) : if ( args . random_nonce ) : nonce = "" else : nonce = public_id . decode ( 'hex' ) aead = hsm . generate_aead ( nonce , kh ) if args . internal_db : if not store_in_internal_db ( args , hsm , modhex_id , public_id , kh , aead ) : res = False continue filename = output_filename ( args . output_dir , args . key_handles [ kh ] , padded_id ) if args . verbose : print " %4s, %i bytes (%s) -> %s" % ( args . key_handles [ kh ] , len ( aead . data ) , shorten_aead ( aead ) , filename ) aead . save ( filename ) if args . verbose : print "" if res : print "\nDone\n" else : print "\nDone (one or more entries rejected)" return res
The main stdin iteration loop .
52,907
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 .
52,908
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 .
52,909
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 , self . key_handle ) if self . status == pyhsm . defines . YSM_STATUS_OK : return True else : raise pyhsm . exception . YHSM_CommandFailed ( pyhsm . defines . cmd2str ( self . command ) , self . status )
Return True if the AEAD was stored sucessfully .
52,910
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 . yubikey . modhex_encode ( public_id ) if args . verbose : print " %s" % ( padded_id ) num_bytes = len ( pyhsm . aead_cmd . YHSM_YubiKeySecret ( 'a' * 16 , 'b' * 6 ) . pack ( ) ) hsm . load_random ( num_bytes ) for kh in args . key_handles . keys ( ) : if args . random_nonce : nonce = "" else : nonce = public_id . decode ( 'hex' ) aead = hsm . generate_aead ( nonce , kh ) filename = output_filename ( args . output_dir , args . key_handles [ kh ] , padded_id ) if args . verbose : print " %4s, %i bytes (%s) -> %s" % ( args . key_handles [ kh ] , len ( aead . data ) , shorten_aead ( aead ) , filename ) aead . save ( filename ) if args . verbose : print "" print "\nDone\n"
The main key generating loop .
52,911
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 .
52,912
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 . debug : debug_info = "%s (payload %i/0x%x)" % ( pyhsm . defines . cmd2str ( self . command ) , len ( self . payload ) , len ( self . payload ) ) self . stick . write ( cmd_buf , debug_info ) if not read_response : return None return self . _read_response ( ) finally : unlock ( )
Write command to HSM and read response .
52,913
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_RESPONSE : debug_info = "%s response (%i/0x%x bytes)" % ( pyhsm . defines . cmd2str ( response_status - pyhsm . defines . YSM_RESPONSE ) , response_len , response_len ) res = self . stick . read ( response_len , debug_info ) if res : if response_status == self . command | pyhsm . defines . YSM_RESPONSE : self . executed = True self . response_status = response_status return self . parse_result ( res ) else : reset ( self . stick ) raise pyhsm . exception . YHSM_Error ( 'YubiHSM responded to wrong command' ) else : raise pyhsm . exception . YHSM_Error ( 'YubiHSM did not respond' )
After writing a command read response .
52,914
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 .
52,915
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 .
52,916
def echo ( self , data ) : return pyhsm . basic_cmd . YHSM_Cmd_Echo ( self . stick , data ) . execute ( )
Echo test .
52,917
def random ( self , num_bytes ) : return pyhsm . basic_cmd . YHSM_Cmd_Random ( self . stick , num_bytes ) . execute ( )
Get random bytes from YubiHSM .
52,918
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 .
52,919
def get_nonce ( self , increment = 1 ) : return pyhsm . basic_cmd . YHSM_Cmd_Nonce_Get ( self . stick , increment ) . execute ( )
Get current nonce from YubiHSM .
52,920
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 .
52,921
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 .
52,922
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 .
52,923
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 .
52,924
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 .
52,925
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 .
52,926
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 .
52,927
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 .
52,928
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 .
52,929
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 .
52,930
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 .
52,931
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 .
52,932
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 .
52,933
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 .
52,934
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 . 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 .
52,935
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 ) 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 .
52,936
def my_address_string ( self ) : addr = getattr ( self , 'client_address' , ( '' , None ) ) [ 0 ] if addr in self . proxy_ips : return self . headers . getheader ( 'x-forwarded-for' , addr ) return addr
For logging client host without resolving .
52,937
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 .
52,938
def generate_aead ( hsm , args ) : key = get_oath_k ( args ) 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 .
52,939
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 .
52,940
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 .
52,941
def delete ( self , entry ) : c = self . conn . cursor ( ) c . execute ( "DELETE FROM oath WHERE key = ?" , ( entry . data [ "key" ] , ) )
Delete entry from database .
52,942
def parse_result ( self , data ) : 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 .
52,943
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 .
52,944
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 ) : 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 : self . data = buf [ : pyhsm . defines . YSM_MAX_KEY_SIZE + pyhsm . defines . YSM_BLOCK_SIZE ] aead_f . close ( )
Load AEAD from a file .
52,945
def pack ( self ) : 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 .
52,946
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 ) ) 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 return 0xff
Validate an OTP .
52,947
def search_for_oath_code ( hsm , key_handle , nonce , aead , user_code , interval = 30 , tolerance = 0 ) : 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 .
52,948
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
52,949
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 .
52,950
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 .
52,951
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 .
52,952
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 .
52,953
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 .
52,954
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 .
52,955
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 .
52,956
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 : return otp if otp : sys . stderr . write ( "ERROR: Invalid YubiKey OTP\n" ) return None
Get OTP from YubiKey .
52,957
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 .
52,958
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_ .
52,959
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 .
52,960
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 .
52,961
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 .
52,962
def gaussian_multi_polygons ( points , n = 10 ) : polygons = gaussian_polygons ( points , n * 2 ) 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 .
52,963
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 .
52,964
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 .
52,965
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 .
52,966
def split ( self ) : 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 .
52,967
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 .
52,968
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 .
52,969
def polyplot ( df , projection = None , extent = None , figsize = ( 8 , 6 ) , ax = None , edgecolor = 'black' , facecolor = 'None' , ** kwargs ) : 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 ] ) ) } ) if not ax : ax = plt . subplot ( 111 , projection = projection ) else : if not ax : ax = plt . gca ( ) _lay_out_axes ( ax , projection ) if len ( df . geometry ) == 0 : return ax extrema = _get_envelopes_min_maxes ( df . geometry . envelope . exterior ) _set_extent ( ax , projection , extent , extrema ) 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 : for subgeom in geom : feature = descartes . PolygonPatch ( subgeom , facecolor = facecolor , edgecolor = edgecolor , ** kwargs ) ax . add_patch ( feature ) except ( TypeError , AssertionError ) : feature = descartes . PolygonPatch ( geom , facecolor = facecolor , edgecolor = edgecolor , ** kwargs ) ax . add_patch ( feature ) return ax
Trivial polygonal plot .
52,970
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 ) : 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 ] ) ) } ) if not ax : ax = plt . subplot ( 111 , projection = projection ) else : if not ax : ax = plt . gca ( ) _lay_out_axes ( ax , projection ) if len ( df . geometry ) == 0 : return ax extrema = _get_envelopes_min_maxes ( df . geometry . envelope . exterior ) _set_extent ( ax , projection , extent , extrema ) hue = _validate_hue ( df , hue ) if hue is None : raise ValueError ( "No 'hue' specified." ) if k is not None : 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 ] 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 : hue_values = hue cmap = _continuous_colormap ( hue_values , cmap , vmin , vmax ) colors = [ cmap . to_rgba ( v ) for v in hue_values ] if legend : _paint_colorbar_legend ( ax , hue_values , cmap , legend_kwargs ) 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 : for subgeom in geom : feature = descartes . PolygonPatch ( subgeom , facecolor = color , ** kwargs ) ax . add_patch ( feature ) except ( TypeError , AssertionError ) : feature = descartes . PolygonPatch ( geom , facecolor = color , ** kwargs ) ax . add_patch ( feature ) return ax
Area aggregation plot .
52,971
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 .
52,972
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 .
52,973
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 : ax . set_extent ( ( xmin , xmax , ymin , ymax ) , crs = ccrs . PlateCarree ( ) ) else : 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 : ax . set_extent ( ( xmin , xmax , ymin , ymax ) , crs = ccrs . PlateCarree ( ) ) else : ax . set_xlim ( ( xmin , xmax ) ) ax . set_ylim ( ( ymin , ymax ) )
Sets the plot extent .
52,974
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 : 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 .
52,975
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 .
52,976
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 .
52,977
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
52,978
def get_version ( ) : proc = tmux_cmd ( '-V' ) if proc . stderr : if proc . stderr [ 0 ] == 'tmux: unknown option -- V' : if sys . platform . startswith ( "openbsd" ) : 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 ] if version == 'master' : return LooseVersion ( '%s-master' % TMUX_MAX_VERSION ) version = re . sub ( r'[a-z-]' , '' , version ) return LooseVersion ( version )
Return tmux version .
52,979
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 .
52,980
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 .
52,981
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 .
52,982
def where ( self , attrs , first = False ) : 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 .
52,983
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 .
52,984
def select_window ( self ) : target = ( '%s:%s' % ( self . get ( 'session_id' ) , self . index ) , ) return self . session . select_window ( target )
Select window . Return self .
52,985
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 .
52,986
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 .
52,987
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 .
52,988
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 .
52,989
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 .
52,990
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 .
52,991
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 .
52,992
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 .
52,993
def info ( ctx ) : controller = ctx . obj [ 'controller' ] click . echo ( 'PIV version: %d.%d.%d' % controller . version ) 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 : 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 : 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 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 .
52,994
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 .
52,995
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 .
52,996
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 : 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 .
52,997
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 .
52,998
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 .
52,999
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 .