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 , p...
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 , "Servin...
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_...
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_...
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 ] ) ) resu...
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)" ...
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 . ...
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 [ "...
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...
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 ( ...
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 ...
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 , ...
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 = 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 .
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 : pas...
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...
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 ...
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 , ...
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' , ...
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' :...
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 ( a...
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...
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 ) , ...
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 [ ...
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. ...
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 retu...
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...
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 ) ) [ ...
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 ) ) ...
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 ( '...
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 . res...
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 , po...
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: {} {...
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...
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:\t123...
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 ...
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_certifica...
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 = ...
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...
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...
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...
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...
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 ke...
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 = Tr...
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 ...
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 ( 'Fail...
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' ] = F...
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 ( ) ...
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. Pr...
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...
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 ...
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...
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 Except...
Manage OTP Application .
137
6