idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
241,800
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_...
Try to decrypt a YubiKey OTP .
241,801
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 .
241,802
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 ] ) ) resu...
Loads AEAD from the specified database .
241,803
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...
Protect the oath - k in an AEAD .
241,804
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 . ...
Store the AEAD in the database .
241,805
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 [ "...
Add entry to database .
241,806
def delete ( self , entry ) : c = self . conn . cursor ( ) c . execute ( "DELETE FROM oath WHERE key = ?" , ( entry . data [ "key" ] , ) )
Delete entry from database .
241,807
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...
Returns a YHSM_GeneratedAEAD instance or throws pyhsm . exception . YHSM_CommandFailed .
241,808
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 .
241,809
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 ( ...
Load AEAD from a file .
241,810
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 .
241,811
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 ...
Validate an OTP .
241,812
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 .
241,813
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
241,814
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 .
241,815
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 .
241,816
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 .
241,817
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 .
241,818
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 = spl...
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 .
241,819
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 .
241,820
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 : pas...
Get password of correct length for this YubiHSM version .
241,821
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 o...
Get OTP from YubiKey .
241,822
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 .
241,823
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_ .
241,824
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 .
241,825
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 .
241,826
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 ...
Returns an array of approximately n shapely . geometry . Polygon objects for an array of shapely . geometry . Point objects .
241,827
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 .
241,828
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 .
241,829
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 .
241,830
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 .
241,831
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 , b...
Splits the current QuadTree instance four ways through the midpoint .
241,832
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 .
241,833
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' , ...
Reusable plotting wrapper .
241,834
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 . ...
Trivial polygonal plot .
241,835
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 projectio...
Area aggregation plot .
241,836
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...
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 .
241,837
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 .
241,838
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 : ...
Sets the plot extent .
241,839
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 .
241,840
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 .
241,841
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 [ ...
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 .
241,842
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
241,843
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...
Return tmux version .
241,844
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 retu...
Return if tmux meets version requirement . Version > 1 . 8 or above .
241,845
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...
Raises exception session name invalid modeled after tmux function .
241,846
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 .
241,847
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 . childre...
Return objects matching child objects properties .
241,848
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 .
241,849
def select_window ( self ) : target = ( '%s:%s' % ( self . get ( 'session_id' ) , self . index ) , ) return self . session . select_window ( target )
Select window . Return self .
241,850
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 ) ) i...
Execute tmux command and return output .
241,851
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 .
241,852
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 ( '...
Manage OpenPGP Application .
241,853
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 . res...
Display status of OpenPGP application .
241,854
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 .
241,855
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 , po...
Manage touch policy for OpenPGP keys .
241,856
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: {} {...
Manage pin - retries .
241,857
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 .
241,858
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.'...
Display status of PIV application .
241,859
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:\t123...
Reset all PIV data .
241,860
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 ...
Generate an asymmetric key pair .
241,861
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_certifica...
Import a X . 509 certificate .
241,862
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 = ...
Import a private key .
241,863
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...
Export a X . 509 certificate .
241,864
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 .
241,865
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 .
241,866
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...
Generate a self - signed X . 509 certificate .
241,867
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...
Change the PIN code .
241,868
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...
Change the PUK code .
241,869
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 ke...
Change the management key .
241,870
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 = Tr...
Unblock the PIN .
241,871
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 ...
Read arbitrary PIV object .
241,872
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 ( 'Fail...
Write an arbitrary PIV object .
241,873
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' ] = F...
Manage FIDO applications .
241,874
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 ( ) ...
Display status of FIDO2 application .
241,875
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. Pr...
Reset all FIDO applications .
241,876
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...
Verify U2F PIN for YubiKey FIPS .
241,877
def get_pin_tries ( self ) : _ , 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 .
241,878
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 ...
Configure your YubiKey via the command line .
241,879
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...
List connected YubiKeys .
241,880
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 Except...
Manage OTP Application .
241,881
def info ( ctx ) : dev = ctx . obj [ 'dev' ] controller = ctx . obj [ 'controller' ] slot1 , slot2 = controller . slot_status click . echo ( 'Slot 1: {}' . format ( slot1 and 'programmed' or 'empty' ) ) click . echo ( 'Slot 2: {}' . format ( slot2 and 'programmed' or 'empty' ) ) if dev . is_fips : click . echo ( 'FIPS ...
Display status of YubiKey Slots .
241,882
def swap ( ctx ) : controller = ctx . obj [ 'controller' ] click . echo ( 'Swapping slots...' ) try : controller . swap_slots ( ) except YkpersError as e : _failed_to_write_msg ( ctx , e )
Swaps the two slot configurations .
241,883
def ndef ( ctx , slot , prefix ) : dev = ctx . obj [ 'dev' ] controller = ctx . obj [ 'controller' ] if not dev . config . nfc_supported : ctx . fail ( 'NFC interface not available.' ) if not controller . slot_status [ slot - 1 ] : ctx . fail ( 'Slot {} is empty.' . format ( slot ) ) try : if prefix : controller . conf...
Select slot configuration to use for NDEF .
241,884
def delete ( ctx , slot , force ) : controller = ctx . obj [ 'controller' ] if not force and not controller . slot_status [ slot - 1 ] : ctx . fail ( 'Not possible to delete an empty slot.' ) force or click . confirm ( 'Do you really want to delete' ' the configuration of slot {}?' . format ( slot ) , abort = True , er...
Deletes the configuration of a slot .
241,885
def yubiotp ( ctx , slot , public_id , private_id , key , no_enter , force , serial_public_id , generate_private_id , generate_key ) : dev = ctx . obj [ 'dev' ] controller = ctx . obj [ 'controller' ] if public_id and serial_public_id : ctx . fail ( 'Invalid options: --public-id conflicts with ' '--serial-public-id.' )...
Program a Yubico OTP credential .
241,886
def static ( ctx , slot , password , generate , length , keyboard_layout , no_enter , force ) : controller = ctx . obj [ 'controller' ] keyboard_layout = KEYBOARD_LAYOUT [ keyboard_layout ] if password and len ( password ) > 38 : ctx . fail ( 'Password too long (maximum length is 38 characters).' ) if generate and not ...
Configure a static password .
241,887
def chalresp ( ctx , slot , key , totp , touch , force , generate ) : controller = ctx . obj [ 'controller' ] if key : if generate : ctx . fail ( 'Invalid options: --generate conflicts with KEY argument.' ) elif totp : key = parse_b32_key ( key ) else : key = parse_key ( key ) else : if force and not generate : ctx . f...
Program a challenge - response credential .
241,888
def calculate ( ctx , slot , challenge , totp , digits ) : controller = ctx . obj [ 'controller' ] if not challenge and not totp : ctx . fail ( 'No challenge provided.' ) slot1 , slot2 = controller . slot_status if ( slot == 1 and not slot1 ) or ( slot == 2 and not slot2 ) : ctx . fail ( 'Cannot perform challenge-respo...
Perform a challenge - response operation .
241,889
def hotp ( ctx , slot , key , digits , counter , no_enter , force ) : controller = ctx . obj [ 'controller' ] if not key : while True : key = click . prompt ( 'Enter a secret key (base32)' , err = True ) try : key = parse_b32_key ( key ) break except Exception as e : click . echo ( e ) force or click . confirm ( 'Progr...
Program an HMAC - SHA1 OATH - HOTP credential .
241,890
def settings ( ctx , slot , new_access_code , delete_access_code , enter , pacing , force ) : controller = ctx . obj [ 'controller' ] if ( new_access_code is not None ) and delete_access_code : ctx . fail ( '--new-access-code conflicts with --delete-access-code.' ) if not controller . slot_status [ slot - 1 ] : ctx . f...
Update the settings for a slot .
241,891
def parse_private_key ( data , password ) : if is_pem ( data ) : if b'ENCRYPTED' in data : if password is None : raise TypeError ( 'No password provided for encrypted key.' ) try : return serialization . load_pem_private_key ( data , password , backend = default_backend ( ) ) except ValueError : raise except Exception ...
Identifies decrypts and returns a cryptography private key object .
241,892
def parse_certificates ( data , password ) : if is_pem ( data ) : certs = [ ] for cert in data . split ( PEM_IDENTIFIER ) : try : certs . append ( x509 . load_pem_x509_certificate ( PEM_IDENTIFIER + cert , default_backend ( ) ) ) except Exception : pass if len ( certs ) > 0 : return certs if is_pkcs12 ( data ) : try : ...
Identifies decrypts and returns list of cryptography x509 certificates .
241,893
def get_leaf_certificates ( certs ) : issuers = [ cert . issuer . get_attributes_for_oid ( x509 . NameOID . COMMON_NAME ) for cert in certs ] leafs = [ cert for cert in certs if ( cert . subject . get_attributes_for_oid ( x509 . NameOID . COMMON_NAME ) not in issuers ) ] return leafs
Extracts the leaf certificates from a list of certificates . Leaf certificates are ones whose subject does not appear as issuer among the others .
241,894
def set_lock_code ( ctx , lock_code , new_lock_code , clear , generate , force ) : dev = ctx . obj [ 'dev' ] def prompt_new_lock_code ( ) : return prompt_lock_code ( prompt = 'Enter your new lock code' ) def prompt_current_lock_code ( ) : return prompt_lock_code ( prompt = 'Enter your current lock code' ) def change_lo...
Set or change the configuration lock code .
241,895
def nfc ( ctx , enable , disable , enable_all , disable_all , list , lock_code , force ) : if not ( list or enable_all or enable or disable_all or disable ) : ctx . fail ( 'No configuration options chosen.' ) if enable_all : enable = APPLICATION . __members__ . keys ( ) if disable_all : disable = APPLICATION . __member...
Enable or disable applications over NFC .
241,896
def info ( ctx , check_fips ) : dev = ctx . obj [ 'dev' ] if dev . is_fips and check_fips : fips_status = get_overall_fips_status ( dev . serial , dev . config ) click . echo ( 'Device type: {}' . format ( dev . device_name ) ) click . echo ( 'Serial number: {}' . format ( dev . serial or 'Not set or unreadable' ) ) if...
Show general information .
241,897
def oath ( ctx , password ) : try : controller = OathController ( ctx . obj [ 'dev' ] . driver ) ctx . obj [ 'controller' ] = controller ctx . obj [ 'settings' ] = Settings ( 'oath' ) except APDUError as e : if e . sw == SW . NOT_FOUND : ctx . fail ( "The OATH application can't be found on this YubiKey." ) raise if pas...
Manage OATH Application .
241,898
def info ( ctx ) : controller = ctx . obj [ 'controller' ] version = controller . version click . echo ( 'OATH version: {}.{}.{}' . format ( version [ 0 ] , version [ 1 ] , version [ 2 ] ) ) click . echo ( 'Password protection ' + ( 'enabled' if controller . locked else 'disabled' ) ) keys = ctx . obj [ 'settings' ] . ...
Display status of OATH application .
241,899
def reset ( ctx ) : controller = ctx . obj [ 'controller' ] click . echo ( 'Resetting OATH data...' ) old_id = controller . id controller . reset ( ) settings = ctx . obj [ 'settings' ] keys = settings . setdefault ( 'keys' , { } ) if old_id in keys : del keys [ old_id ] settings . write ( ) click . echo ( 'Success! Al...
Reset all OATH data .